Claude Cursor Skill

delivery

Deliver a change through an approved design contract, sequential implementation, independent review and exact-HEAD release. Use for any Bounded or Architectural change — including a small, one-line behavioral fix, which is the canonical Bounded case — so it gets design approval a

LLM Mart · 0 points · 0 views 9 listing impressions 0 install-command copies
Virus-scanned Reviewed automatically before listing.

Full trust report

Download hieuphung97-dely-skills_delivery-e874990.zip · 18 KB

Install

skills CLI npx skills add https://github.com/hieuphung97/dely/tree/main/skills/delivery
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install hieuphung97-dely@llmmart
Git git clone https://github.com/hieuphung97/dely.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole hieuphung97/dely collection as a plugin from our marketplace. Git is the plain clone.

Skill manifest

Delivery

Dely accepts a request that may still be vague, brings it to an approved design contract, then automates sequential implementation, independent review, and pull-request preparation. It is a thin control protocol, not an orchestrator, SDLC framework, or second source of Git state.

Read AGENTS.md in the repository for this project's gate commands, artifact paths, default branch, and per-phase harness/model/effort pins. This skill never names them.

Two human gates

  1. Approve the design contract before candidate mutation.
  2. Merge or publish after Dely has prepared the reviewed pull request.

Dely pauses outside those gates only for a scope or architecture change, a destructive action, new authority, replan, or an unavailable required runtime.

The control session

The current interactive session is Control. It owns the approval invariant, task boundaries, exception handling, dispatch supervision, and release. It does not implement or review the candidate, and does not prescribe question count, order, format, or skill-selection precedence. Native Plan Mode and active design skills govern their own surfaces under the harness's precedence; neither bypasses approval. Before mutation, Control obtains explicit human approval of a design contract. One approval covers that scope; a material change needs a new one. Control surfaces uncertainty that could materially change intent, acceptance, authority, public contract, architecture, or consequential risk. Material assumptions must be explicit.

Shape

Use the smallest contract that safely holds the change. Risk may promote an otherwise small change; diff size never demotes data-loss, security, permission, or public-compatibility risk.

Shape Use Artifact Review
Spike Investigation only; no candidate is delivered Approved probe and recommendation; no delivery run none
Bounded Small change, clear behaviour and ownership Approved in-chat design and short execution envelope one whole-change review
Architectural Multiple behaviours, public-contract change, architecture decision, or promoted risk Approved decision record, task plan, execution envelope task review per task, then one integration review

An approved design contract states intent and success criteria; scope and authority; affected public contract or architecture; consequential risks and material assumptions; and a plausible counterexample that distinguishes correct behaviour from a present-but-wrong implementation. If no executable instrument can discriminate, the contract names the manual inspection and its limit.

Architectural work uses templates/decision-record.md (durable) and templates/plan.md (transient, deleted in the release commit, before the release-binding review). Commit both before implementation begins — that commit is the review baseline.

Acceptance

One table: each requirement, the instrument that proves it, the plausible wrong implementation that instrument rejects, and where that rejection was observed.

An acceptance row is invalid until its instrument discriminates. A row that passes both before and after the change proves nothing and will be found at review. Baseline-red is not enough: red only because the feature is absent says nothing about catching an implementation that is present, runs, returns a pass, and is wrong. Each row names such a wrong implementation. "The feature is absent" does not satisfy Counterexample. Where none exists, the row says so and a human reads the diff.

Record what the instruments cannot observe. Prefer the simplest instrument that proves the contract. Any claim about extent — a scope, a count, a set of call sites — names the command that produced it, reports its output, and enumerates rather than samples. Naming the command is not the measurement; the command must have been run.

Execution envelope

Before mutation, Control resolves deployment preferences against the live harness surface, starts Orca and verifies its required capabilities, records the dirty baseline and exact-path ownership, and creates a feature branch when starting on the default branch. The envelope freezes owned scope and paths; protected pre-existing dirty paths; acceptance criteria, counterexample, and focused instruments; branch, base, remote, and pull-request target; resolved harness, model, and effort for dispatched roles; and authority to branch, commit owned paths, run gates, push, and open or update a pull request. It never authorises merge, force-push, stash, reset, cleanup, or an edit outside owned scope. Dely stages and commits only contract-owned paths. It never stashes, resets, cleans, or silently absorbs the user's existing changes. If a path carries protected baseline changes and Dely must also modify it, Control pauses rather than combining ownership.

Orca and the helper

Orca is the required execution plane. It launches and supervises fresh native harness TUIs with the resolved harness, model, and effort. Orchestration is a required Orca capability. dely:delivery starts Orca, then Control loads orca skills get orchestration and follows its supervised loop. It stops only when the CLI is missing, the runtime cannot start, or a required capability is absent — there is no direct dispatch and no headless fallback of any kind. The launcher is scripts/dely relative to this skill. Control's wake mode is that harness's controlWake in ../../harnesses.json. The preflight step runs in setup and again after a NO_ACK; a delivery does not preflight before its first dispatch.

Write the prompt to an untracked file inside the worktree. Never inline it in a shell argument: prompts carry backticks, quotes and newlines, and a shell argument mangles them. A path outside the workspace can trigger a second permission surface some harnesses still prompt for even when tool approval is skipped. Do not stage that file. After the worker returns, delete it: Control owns that dispatch artifact, not git clean. The handoff is a file in the worktree; its path travels as payload.reportPath and the message body stays short. --spec and --body are shell arguments, which this skill already forbids for prompts.

The dispatch prompt carries the task, its scope, and the evidence required. It does not define role dispositions or the conditions for reaching one — those belong to this skill, and a prompt that restates them narrows or contradicts them. Where the design contract states an acceptance row, the prompt carries that row as written. Every dispatch goes through dely dispatch. Control does not compose a worker launch or call worker-start by hand. The helper reads the pins from AGENTS.md and appends the acknowledgement instruction and a sentence that the Orca preamble and the spec file are everything the worker needs and that it should read no other skill. The worker-start receipt records launch.requested and launch.effective; it does not establish that the worker can serve the request or that it cannot. Orca applies the execution plane's configured permission default and does not add a sandbox the project did not pin.

Name the model and effort on every dispatch. The helper passes --model/--effort when ../../harnesses.json says that harness takes them, and omits a flag whose value is default. On a harness that takes neither, a Model written there is silently not applied: write default and set the model in Orca's agent default arguments. A worker left on a harness default is an unpinned environment: it lives in the harness's own config, it changes without announcing itself, and the dispatch that relies on it looks identical to one that pinned the same value deliberately.

Never act on an Orca nudge. After DISPATCHED, wait by the wake mode of this Control's own harness — not the harness of the worker being waited on. --control is this session's harness id, the same id whatever worker is in flight. background runs dely wait --run <run> --control <self> as a background command and ends the turn; waker runs dely wait-bg --run <run> --control <self> as its last command, then ends the turn (a waker Control never runs dely wait); unsupported cannot be Control. The helper reads the harness of the Orca terminal it runs in and refuses a waker even when --control names another one, so REFUSED … (called with --control …) means use wait-bg.

Result handling. SETTLED: process the batch, do the guide's completion accounting, and acknowledge. ATTENTION has two routes, and the difference is whether the plane can still see the worker. With nextAction.kind other than none, run the argv Orca printed and skip that id next time. With nextAction: none and attention.requiresAction, the plane has lost sight of the worker rather than asked for something: read it with worker-read and worker-show, and if the process is gone, worker-stop, then worker-abandon when the stop reports stop_unknown, then worker-release, then one fresh dely dispatch with the same prompt file. A second time on the same input goes to the human. An absent nextAction is absent, not none with attention — that row is not ATTENTION and the wait continues. STALLED: read the output, then wait again or recover. NO_ACK: run setup's dely preflight in the same Run. If every pin passes, one fresh dely dispatch with the same prompt file; never retry into the same terminal, and never reuse a settled terminal; a second failure on the same input goes to the human. Any PREFLIGHT … FAIL: do not dispatch to any pin — a failed pin's cause is already known and another dispatch only repeats it. Stop and relay the printed reason: the harness, the path, and that the human opens that harness there once to answer its own dialog; Dely never answers it. The failed worker is already stopped and released. When the human says it is done, rerun dely preflight in the same Run and continue from there. FAILED: one fresh dely dispatch with the same prompt file and the same retry limits. DEADLINE: a checkpoint — check worker-list and the last output; if the worker is progressing, wait again; a second DEADLINE with no progress goes to the human. ERROR: go to the human. The worker reports once with worker_done and an --outcome; completion comes from that worker_done — do not infer it from reading the worker's terminal. Each delivery opens its own Run with an objective (orca orchestration run-create --objective) rather than reusing another's, so a stale report cannot settle a new wait.

Investigation is one read-only diagnostic dispatch inheriting the implement pin; it may reproduce, inspect, and report, but does not edit, commit, launch workers, or expand scope.

Stop and ask the human when: a result maps to no route or more than one; the worker failed rather than returned a stop status — a non-zero exit with no result, an exhausted quota, an authentication error — which is not BLOCKED and must not be treated as one; Orca is unavailable or a required capability is absent; an action needs authority policy reserves to the human; or the same worker fails twice on the same input. Say what you know, what you tried, and what the options are. Do not pick one.

Implementation

Control creates a separate task only when that unit has its own test cycle and a reviewer could accept it while rejecting its neighbor. Same-shaped mechanical changes are batched. Tightly coupled work stays one task and one implementer. Each independent task gets a fresh implementer TUI.

An implementer reads the decision record, the plan, and the baseline — not the design session's transcript. It owns only its task, runs a focused acceptance instrument, and creates one task-scoped commit. For behaviour with a deterministic executable test it uses TDD; the portable invariant is smaller: observe a discriminating failure for the intended reason before changing behaviour. A shell probe, parser fixture, or diff inspection may be the correct instrument for configuration, documentation, generated files, or environment-bound integration.

The counterexample named in each acceptance row is observed red and cited. That observation is not the behaviour's own absence: one is the feature absent, the other is an implementation that is present, runs, returns a pass, and is wrong.

Implement the whole task before handing back. Stop and return BLOCKED or NEEDS_REPLAN instead of a partial solution when the record contradicts the code, the contract is ambiguous, work outside the task becomes necessary, an existing test disproves an assumption, or the task no longer fits one session. A task needing continuation is a decomposition failure.

Handoff

Status: DONE | BLOCKED | NEEDS_REPLAN
Harness:            name, model, effort, sandbox
Session:            the dispatch id
Baseline:
Changed paths:
Contract coverage:
Verification:
Deviations from plan:
Residue:
Git state:
END OF HANDOFF

END OF HANDOFF is the last line and load-bearing: the only thing that distinguishes a handoff from one cut off mid-write. Under Residue, a claim of nothing left needs evidence: name the check that returned empty. Under Verification, cite the dispatch-bound command, output, and outcome that Orca recovers for that task — the transcript or terminal it selects, and any cursor mechanics, are Orca's concern, not this skill's. Do not transcribe output by hand. Where Orca cannot recover a dispatch item, treat the worker's own account as the thing under check rather than as the check, and say so.

Review

Review independence is role independence: a fresh session that did not implement and does not edit the candidate. It gets the decision record (or Bounded design), the baseline, and the diff. The phase adds no sandbox by default; AGENTS.md may pin one for a concrete risk. Review depth is adaptive: Bounded work gets one independent whole-change review. Each Architectural task gets an independent task review. After all tasks are accepted, a different fresh reviewer performs one integration review of task interactions, complete-contract coverage, deferred findings, candidate identity, and release readiness. Only that final review is release-binding for Architectural work; Bounded work has no earlier task review and no duplicate integration review. No worker runs while a review of the same working tree runs. The working tree and its gate surface are shared mutable state, and a review reproduces gates in that tree, so a concurrent edit makes another task's work look like this one's result.

Reproduce, do not accept. Run the gates yourself. A claim you did not reproduce is not evidence. The reviewer observes the counterexample discriminate for itself — an implementation that is present, runs, returns a pass, and is wrong. An instrument red only because the behaviour was absent is not that observation.

Classify findings: Blocking — contract failure, regression, data or security risk. Important — missing required behaviour, test, or reconciliation. Minor — useful, does not block. Out of scope — recorded, not absorbed. Return exactly one role disposition: ACCEPT, CHANGES_REQUESTED, or BLOCKED. State what the review did not verify — what it did not reproduce or read. A contradiction you cannot resolve is CHANGES_REQUESTED. Do not open remediation over wording when deterministic checks already prove the contract.

Remediation

One pass is one remediation pass per finding, not per review. For an in-contract CHANGES_REQUESTED finding, the original implementer verifies it, fixes the root cause, reruns the affected instruments and closure gates, and writes a separate remediation commit — this is the single original-party remediation. Control owns the plan and the decision record for the whole run, including remediating findings inside them. Amending them is not implementing the candidate. The reviewer that raised the finding checks its reproduction and the fix-only diff, and scope-checks a Control amendment the same way. If that scoped re-review does not accept, Control routes to REPLAN_OR_SPLIT — it does not start another repair loop. BLOCKED preserves the candidate and escalates the unresolved dependency or authority question to Control separately from a failed worker process; it is not remediated by the original implementer. A fresh replacement reviewer is used only when the original reviewer is unavailable or contested, and for the Architectural integration review.

Release

Control performs release with native Git and forge tools; release dispatches no LLM worker and makes no post-review candidate edit.

  1. Complete implementation and, for Architectural work, its task reviews.
  2. Reconcile owning documentation, delete the plan, and commit the complete candidate.
  3. Run the focused instruments and project closure gates on exact HEAD.
  4. Push the feature branch and create or update a draft pull request.
  5. Run the applicable final review while remote CI runs on that same HEAD.
  6. Require both that review's ACCEPT and required checks green.
  7. Mark the pull request ready and report it for human merge.

Any candidate mutation after the applicable final review invalidates that verdict; Control reruns the affected gates and review on the new exact HEAD. Affected gates are those that can observe the change class; a project may name that subset. Dely never merges, force-pushes, or publishes outside the approved target and authority. If project policy cannot publish work in progress, Dely delays the push and pull request until the applicable review accepts.

Maintenance logging is machine-local and opt-in at ~/.dely/log.jsonl. It stays opt-in on the presence of ~/.dely/ and is never created by Dely. Control closes a delivery with dely log --run <run> --json '<object>', after release or when it stops early, rather than assembling a line by hand. dely with no arguments prints which copy is running, and its usage.

Failure and recovery

Recovery uses Orca records, Git, CI, and pull-request state — never inferred from an ambiguous, missing, or merely transport-level outcome.

Failure Disposition
In-contract implementation defect Original implementer remediates
Scoped remediation re-review does not accept REPLAN_OR_SPLIT
Scope or architecture must change Return to the design gate
New authority or destructive action is required Ask the human
Orca or a required capability is unavailable Stop; no headless fallback
any PREFLIGHT … FAIL Dispatch to no pin; relay harness, path and dialog to the human; rerun preflight in the same Run when told
Harness fails or evidence is insufficient Preserve the candidate, report the native outcome and role disposition
Idempotent release step is interrupted Verify Git and pull-request state, then resume
Files (dely)
  • scripts
    • dely 571 B · in bundle
    • dely.js 22.6 KB
      #!/usr/bin/env node
      "use strict";
      
      const { execFileSync } = require("child_process");
      const crypto = require("crypto");
      const fs = require("fs");
      const os = require("os");
      const path = require("path");
      
      const ACK_S = Number(process.env.DELY_ACK_S || 60);
      const POLL_S = Number(process.env.DELY_POLL_S || 15);
      const PROGRESS_S = Number(process.env.DELY_PROGRESS_S || 60);
      const seconds = (v, d) => (Number.isFinite(+v) && +v > 0 ? +v : d);
      const PREFLIGHT_S = seconds(process.env.DELY_PREFLIGHT_S, 150);
      const NOTIFY_RETRY_S = seconds(process.env.DELY_NOTIFY_RETRY_S, 30);
      const NOTIFY_GIVEUP_S = seconds(process.env.DELY_NOTIFY_GIVEUP_S, 1800);
      
      function orca(args) {
        const bin = process.env.ORCA_CLI_COMMAND || "orca";
        const argv = /\.m?js$/i.test(bin) ? [bin, ...args, "--json"] : [...args, "--json"];
        const cmd = /\.m?js$/i.test(bin) ? process.execPath : bin;
        try {
          const out = execFileSync(cmd, argv, {
            encoding: "utf8",
            stdio: ["ignore", "pipe", "pipe"],
            maxBuffer: 64 << 20,
            env: process.env,
          });
          return JSON.parse(out || "{}");
        } catch (e) {
          try {
            return JSON.parse(String(e.stdout || "{}"));
          } catch (_) {
            return { ok: false, error: { message: String((e.stderr || e.message || "").trim() || e) } };
          }
        }
      }
      
      function flags(argv) {
        const f = {};
        for (let i = 0; i < argv.length; i++) {
          if (argv[i].startsWith("--")) {
            const n = argv[i + 1];
            if (n != null && !String(n).startsWith("--")) {
              f[argv[i].slice(2)] = n;
              i++;
            } else {
              f[argv[i].slice(2)] = true;
            }
          }
        }
        return f;
      }
      
      const PACKAGE_ROOT = path.resolve(__dirname, "../../..");
      const HARNESSES_PATH = path.join(PACKAGE_ROOT, "harnesses.json");
      
      let _harnesses;
      function loadHarnesses() {
        if (_harnesses) return _harnesses;
        let raw;
        try {
          raw = fs.readFileSync(HARNESSES_PATH, "utf8");
        } catch (e) {
          fail("cannot read " + HARNESSES_PATH + ": " + (e.message || e));
        }
        let data;
        try {
          data = JSON.parse(raw);
        } catch (e) {
          fail("cannot parse " + HARNESSES_PATH + ": " + (e.message || e));
        }
        if (!data || !Array.isArray(data.harnesses)) {
          fail(HARNESSES_PATH + " has no harnesses array");
        }
        _harnesses = data.harnesses;
        return _harnesses;
      }
      
      function effortRequiresModel() {
        let raw;
        try {
          raw = JSON.parse(fs.readFileSync(HARNESSES_PATH, "utf8"));
        } catch (_) {
          return true;
        }
        return raw && raw.effortRequiresModel !== false;
      }
      
      function harnessById(id) {
        return loadHarnesses().find((h) => h.id === id);
      }
      
      function pin(repo, phase) {
        const md = fs.readFileSync(path.join(repo, "AGENTS.md"), "utf8");
        const row = md.split("\n").find((l) => new RegExp("^\\|\\s*`?" + phase + "`?\\s*\\|").test(l));
        if (!row) throw new Error("no " + phase + " pin in AGENTS.md");
        const [, harness, model, effort] = row.split("|").slice(1).map((c) => c.trim().replace(/`/g, ""));
        const h = loadHarnesses().find((x) => x.name === harness);
        if (!h) throw new Error("unknown harness " + harness);
        return { phase, agent: h.id, model, effort, modelFlag: h.modelFlag, effortFlag: h.effortFlag };
      }
      
      const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
      const USAGE =
        "usage: dely preflight|dispatch|wait|wait-bg|notify | log --run ID --json OBJ";
      const out = (line, code) => {
        console.log(typeof line === "string" ? line : JSON.stringify(line));
        if (code != null) process.exit(code);
      };
      
      let _sha;
      function delySha() {
        if (_sha !== undefined) return _sha;
        try {
          _sha = String(
            execFileSync("git", ["-C", PACKAGE_ROOT, "rev-parse", "HEAD"], {
              encoding: "utf8",
              stdio: ["ignore", "pipe", "pipe"],
            })
          ).trim();
          if (!_sha) _sha = null;
        } catch (_) {
          _sha = null;
        }
        return _sha;
      }
      
      let _orcaVer;
      function orcaVersion() {
        if (_orcaVer !== undefined) return _orcaVer;
        try {
          _orcaVer = ((orca(["status"]).result || {}).runtime || {}).appVersion || null;
        } catch (_) {
          _orcaVer = null;
        }
        return _orcaVer;
      }
      
      // Append one JSON object to ~/.dely/log.jsonl when that directory already
      // exists. Never mkdir. A write failure must not change exit, print, or flow.
      function logEvent(event, extra) {
        extra = extra || {};
        try {
          if (!fs.statSync(path.join(os.homedir(), ".dely")).isDirectory()) return;
          const rec = {
            ts: new Date().toISOString(),
            run: extra.run == null ? null : extra.run,
            repo: extra.repo == null ? null : extra.repo,
            sha: delySha(),
            orca: orcaVersion(),
            event,
          };
          for (const k of Object.keys(extra)) {
            if (k in rec) continue;
            rec[k] = extra[k];
          }
          fs.appendFileSync(path.join(os.homedir(), ".dely", "log.jsonl"), JSON.stringify(rec) + "\n");
        } catch (_) {
          /* observer */
        }
      }
      
      function fail(reason, extra) {
        logEvent("error", Object.assign({ reason }, extra || {}));
        out("ERROR " + reason, 9);
      }
      
      function printIdentity() {
        let version = "unknown";
        try {
          version = JSON.parse(
            fs.readFileSync(path.join(PACKAGE_ROOT, ".claude-plugin/plugin.json"), "utf8")
          ).version;
        } catch (_) {
          /* missing or unreadable */
        }
        let skill = "unreadable";
        try {
          skill = crypto
            .createHash("sha256")
            .update(fs.readFileSync(path.join(PACKAGE_ROOT, "skills/delivery/SKILL.md")))
            .digest("hex");
        } catch (_) {
          /* missing */
        }
        console.log("dely " + version + " sha " + (delySha() || "null") + " sha256 " + skill);
      }
      
      function start(repo, run, p, spec, title) {
        const args = [
          "orchestration",
          "worker-start",
          "--spec",
          spec,
          "--worktree",
          "path:" + repo,
          "--run",
          run,
          "--task-title",
          title,
          "--agent",
          p.agent,
        ];
        const wantsModel = p.modelFlag && p.model !== "default";
        const wantsEffort = p.effortFlag && p.effort !== "default";
        if (effortRequiresModel() && wantsEffort && !wantsModel) {
          return {
            error:
              "effort " + p.effort + " pinned with model default for " + p.agent +
              "; --effort requires --model, so set a model or set effort to default",
          };
        }
        if (wantsModel) args.push("--model", p.model);
        if (wantsEffort) args.push("--effort", p.effort);
        const r = orca(args);
        const id = r.result && r.result.dispatchId;
        if (!id) {
          return { error: (r.error && r.error.message) || String((r.result && r.result.failedStage) || "worker-start") };
        }
        return { id };
      }
      
      function namesDispatch(m, id) {
        return JSON.stringify(m).includes(id);
      }
      
      function clip(s) {
        return String(s || "")
          .replace(/\s+/g, " ")
          .trim()
          .slice(-400);
      }
      
      function messageText(m) {
        if (m == null) return "";
        if (typeof m === "string") return m;
        const blocks = Array.isArray(m.blocks) ? m.blocks : [];
        let last = "";
        let toolOut = "";
        for (const b of blocks) {
          if (!b || typeof b !== "object") continue;
          if (b.type === "text" && typeof b.text === "string" && b.text.trim()) last = b.text;
          else if (!toolOut && b.type === "tool-result" && typeof b.output === "string" && b.output.trim()) {
            toolOut = b.output;
          }
        }
        return last || toolOut;
      }
      
      function screenLines(id) {
        const r = orca(["orchestration", "worker-read", "--dispatch", id, "--source", "auto", "--limit", "200"]);
        const res = r.result || {};
        if (res.terminal && Array.isArray(res.terminal.tail)) {
          return res.terminal.tail.filter((l) => String(l || "").trim());
        }
        const msgs = (res.transcript && res.transcript.messages) || [];
        for (let i = msgs.length - 1; i >= 0; i--) {
          const t = messageText(msgs[i]);
          if (String(t).trim()) return [t];
        }
        return [];
      }
      
      function screenText(id) {
        return screenLines(id).join("\n");
      }
      
      function lastText(id) {
        return clip(screenText(id));
      }
      
      function preflight(f) {
        const pins = ["implement", "review"].map((ph) => pin(f.repo, ph));
        const uniq = pins.filter(
          (p, i) => pins.findIndex((q) => q.agent === p.agent && q.model === p.model && q.effort === p.effort) === i
        );
        const spec =
          "Preflight only. Do not read, edit or run anything in the repository. Send a heartbeat with subject `ack`, then send worker_done --outcome succeeded with subject `preflight ok`, then stop.";
        const open = {};
        let failed = 0;
        for (const p of uniq) {
          const s = start(f.repo, f.run, p, spec, "preflight-" + p.phase);
          if (s.error) {
            logEvent("preflight", {
              run: f.run,
              repo: f.repo,
              phase: p.phase,
              agent: p.agent,
              result: "FAIL",
              seconds: 0,
              reason: "start: " + s.error,
            });
            out("PREFLIGHT " + p.phase + " " + p.agent + " FAIL start: " + s.error);
            failed++;
          } else open[s.id] = Object.assign({ messaged: false }, p);
        }
        const drop = (id, rec, line) => {
          logEvent("preflight", {
            run: f.run,
            repo: f.repo,
            phase: rec.phase,
            agent: rec.agent,
            result: "FAIL",
            seconds: Math.round((Date.now() - t0) / 1000),
            reason: line.replace(/^PREFLIGHT \S+ \S+ FAIL /, ""),
          });
          out(line);
          orca(["orchestration", "worker-stop", "--dispatch", id]);
          orca(["orchestration", "worker-release", "--dispatch", id]);
          delete open[id];
          failed++;
        };
        const pollDead = () => {
          const rows = ((orca(["orchestration", "worker-list", "--run", f.run]).result || {}).workers || []);
          for (const [id, rec] of Object.entries(open)) {
            if (rec.messaged) continue;
            const w = rows.find((x) => x.dispatchId === id);
            if (!w) continue;
            const stage = (w.projection || {}).stage || {};
            let why = "";
            if (w.dispatchStatus === "failed") why = "worker failed: " + (stage.detail || "failed");
            else if (stage.worker === "start_unknown") why = "worker never started a turn: " + (stage.detail || "start_unknown");
            if (!why) continue;
            drop(id, rec, "PREFLIGHT " + rec.phase + " " + rec.agent + " FAIL " + why + "; last output: " + lastText(id));
          }
        };
        const t0 = Date.now();
        while (Object.keys(open).length && Date.now() - t0 < PREFLIGHT_S * 1000) {
          const r = orca([
            "orchestration",
            "check",
            "--wait",
            "--run",
            f.run,
            "--timeout-ms",
            String(Math.max(1, Math.floor(POLL_S * 1000))),
          ]);
          if (r.ok === false) {
            const why = (r.error && r.error.message) || "check failed";
            for (const [id, rec] of Object.entries(open)) drop(id, rec, "PREFLIGHT " + rec.phase + " " + rec.agent + " FAIL " + why);
            process.exit(failed ? 1 : 0);
          }
          const res = r.result || {};
          if (res.deliveryId) {
            for (const m of res.messages || []) {
              const hit = Object.keys(open).find((id) => namesDispatch(m, id));
              if (hit) open[hit].messaged = true;
              if (hit && m.type === "worker_done") {
                const secs = Math.round((Date.now() - t0) / 1000);
                logEvent("preflight", {
                  run: f.run,
                  repo: f.repo,
                  phase: open[hit].phase,
                  agent: open[hit].agent,
                  result: "PASS",
                  seconds: secs,
                });
                out("PREFLIGHT " + open[hit].phase + " " + open[hit].agent + " PASS " + secs + "s");
                orca(["orchestration", "worker-release", "--dispatch", hit]);
                delete open[hit];
              }
            }
            orca(["orchestration", "check", "--run", f.run, "--ack", res.deliveryId]);
          }
          pollDead();
        }
        for (const [id, rec] of Object.entries(open)) {
          drop(id, rec, "PREFLIGHT " + rec.phase + " " + rec.agent + " FAIL no worker_done in " + PREFLIGHT_S + "s; last output: " + lastText(id));
        }
        process.exit(failed ? 1 : 0);
      }
      
      function dispatch(f) {
        const p = pin(f.repo, f.phase);
        const spec =
          fs.readFileSync(path.resolve(f.repo, f["spec-file"]), "utf8") +
          "\n\nFirst action, before anything else: send a heartbeat with subject `ack`. The Orca preamble and this spec file are everything the worker needs; read no other skill.";
        const s = start(f.repo, f.run, p, spec, f.phase);
        if (s.error) {
          logEvent("error", { run: f.run, repo: f.repo, reason: s.error });
          out("FAILED " + s.error, 5);
        }
        const interval = Math.max(20, Math.min(5000, Math.floor(POLL_S * 1000)));
        const t0 = Date.now();
        for (; Date.now() - t0 < ACK_S * 1000; sleep(interval)) {
          const peek = orca(["orchestration", "check", "--peek", "--run", f.run]);
          if (((peek.result || {}).messages || []).some((m) => namesDispatch(m, s.id))) {
            logEvent("dispatch", {
              run: f.run,
              repo: f.repo,
              phase: p.phase,
              agent: p.agent,
              dispatchId: s.id,
              seconds: Math.round((Date.now() - t0) / 1000),
            });
            out("DISPATCHED " + s.id, 0);
          }
          const row = ((orca(["orchestration", "worker-list", "--run", f.run]).result || {}).workers || []).find((w) => w.dispatchId === s.id);
          if (row && row.dispatchStatus === "failed") break;
        }
        const raw = screenText(s.id);
        const secs = Math.round((Date.now() - t0) / 1000);
        orca(["orchestration", "worker-stop", "--dispatch", s.id]);
        orca(["orchestration", "worker-release", "--dispatch", s.id]);
        logEvent("no_ack", { run: f.run, repo: f.repo, dispatchId: s.id, seconds: secs, text: raw });
        out("NO_ACK " + s.id + " stopped after " + secs + "s; last output: " + clip(raw), 4);
      }
      
      function advance(track, id) {
        const t = track[id] || (track[id] = { cursor: null, at: Date.now() });
        for (let page = 0; page < 20; page++) {
          const args = ["orchestration", "worker-read", "--dispatch", id, "--source", "auto", "--limit", "200"];
          if (t.cursor) args.push("--cursor", t.cursor);
          const r = orca(args);
          if (r.ok === false) {
            t.error = (r.error && r.error.message) || "worker-read failed";
            break;
          }
          const res = r.result || {};
          if (res.source) t.source = res.source;
          const body = res.transcript || res.terminal || {};
          const cursor = body.nextCursor || null;
          const n = Number(body.returnedMessageCount || body.returnedLineCount || 0);
          if (cursor && cursor !== t.cursor) t.at = Date.now();
          if (cursor) t.cursor = cursor;
          if (!body.limited || n === 0) break;
        }
        return (Date.now() - t.at) / 60000;
      }
      
      // The harness this process is actually running in, read from the Orca terminal
      // that launched it. --control is what the caller says it is; this is what it is.
      // Measured on Orca 1.4.203: a Codex Control passed --control cursor and
      // --control claude, naming the workers it waited on, and a guard that trusted
      // the flag let a waker Control run a blocking wait. Null outside Orca.
      function selfHarness() {
        const me = process.env.ORCA_TERMINAL_HANDLE;
        if (!me) return null;
        const terms = ((orca(["terminal", "list"]).result || {}).terminals || []);
        const t = terms.find((x) => x && x.handle === me);
        return (t && t.agentIdentity) || null;
      }
      
      function wait(f) {
        if (process.env.DELY_WAITER !== "1") {
          const self = selfHarness();
          const who = self || f.control;
          const wake = (harnessById(who) || {}).controlWake || "unknown";
          if (wake !== "background") {
            const said = self && self !== f.control ? " (called with --control " + f.control + ")" : "";
            out("REFUSED " + who + " wakes by " + wake + said + "; use dely wait-bg", 3);
          }
        }
        const deadline = Date.now() + Number(f["timeout-min"] || 60) * 60000;
        const stallMin = Number(f["stall-min"] || 10);
        const skip = String(f.skip || "").split(",").filter(Boolean);
        const as = f.as ? ["--terminal", f.as] : [];
        const track = {};
        let lastProgressCheck = 0;
        while (Date.now() < deadline) {
          const r = orca([
            "orchestration",
            "check",
            ...as,
            "--wait",
            "--run",
            f.run,
            "--timeout-ms",
            String(Math.max(1, Math.floor(POLL_S * 1000))),
          ]);
          if (r.ok === false) fail((r.error && r.error.message) || "check failed", { run: f.run });
          const res = r.result || {};
          if (res.deliveryId) {
            const msgs = res.messages || [];
            if (msgs.some((m) => ["worker_done", "escalation", "question"].includes(m.type))) {
              logEvent("settled", {
                run: f.run,
                deliveryId: res.deliveryId,
                messages: msgs.map((m) => ({ type: m.type, subject: m.subject })),
              });
              out(
                {
                  SETTLED: res.deliveryId,
                  messages: msgs.map((m) => ({
                    id: m.id,
                    type: m.type,
                    from: m.from_handle,
                    subject: m.subject,
                    payload: m.payload,
                  })),
                },
                0
              );
            }
            orca(["orchestration", "check", ...as, "--run", f.run, "--ack", res.deliveryId]);
            continue;
          }
          const rows = ((orca(["orchestration", "worker-list", "--run", f.run]).result || {}).workers || []).filter(
            (w) => !skip.includes(w.dispatchId)
          );
          // dispatched is load-bearing: pending+requiresAction is the start
          // transient; completed+release is a settled worker awaiting release.
          const act = rows.filter((w) => {
            const proj = w.projection || {};
            // An absent optional field is an absent field, not a value: a row with
            // no projection, or a projection with no nextAction, is not attention.
            const kind = (proj.nextAction || {}).kind || "none";
            const needs = (proj.attention || {}).requiresAction === true;
            return w.dispatchStatus === "dispatched" && (kind !== "none" || needs);
          });
          if (act.length) {
            const payload = act.map((w) => ({
              dispatchId: w.dispatchId,
              liveness: (w.projection || {}).liveness,
              nextAction: (w.projection || {}).nextAction,
              attention: (w.projection || {}).attention,
            }));
            logEvent("attention", { run: f.run, workers: payload });
            out({ ATTENTION: payload }, 8);
          }
          if (Date.now() - lastProgressCheck < PROGRESS_S * 1000) continue;
          lastProgressCheck = Date.now();
          for (const w of rows.filter((w) => w.dispatchStatus === "dispatched")) {
            const idle = advance(track, w.dispatchId);
            const rec = track[w.dispatchId] || {};
            if (!rec.error && rec.source !== "transcript") continue;
            if (idle >= stallMin) {
              const raw = screenText(w.dispatchId);
              const why = rec.error ? rec.error : "no new output for " + Math.floor(idle) + " min";
              logEvent("stalled", {
                run: f.run,
                dispatchId: w.dispatchId,
                idleMinutes: Math.floor(idle),
                liveness: (w.projection || {}).liveness,
                text: raw,
              });
              out(
                "STALLED " +
                  w.dispatchId +
                  " " +
                  why +
                  "; liveness " +
                  JSON.stringify((w.projection || {}).liveness) +
                  "; last output: " +
                  clip(raw),
                6
              );
            }
          }
        }
        logEvent("deadline", { run: f.run });
        out("DEADLINE", 7);
      }
      
      function waitBg(f) {
        const me = process.env.ORCA_TERMINAL_HANDLE;
        if (!me) fail("not inside an Orca terminal", { run: f.run });
        const file = path.resolve(f.out || path.join(os.tmpdir(), "dely-wait-" + f.run + ".out"));
        const lock = file + ".lock";
        const recorded = () => {
          try {
            const j = JSON.parse(fs.readFileSync(lock, "utf8"));
            return (j && j.terminal) || "";
          } catch (_) {
            return "";
          }
        };
        const live = (handle) => {
          if (!handle) return false;
          const terms = ((orca(["terminal", "list"]).result || {}).terminals || []);
          return terms.some((t) => t && t.handle === handle);
        };
        const writeLock = (handle) => {
          try {
            fs.writeFileSync(lock, JSON.stringify({ terminal: handle || "" }));
          } catch (_) {
            /* vanished or unwritable */
          }
        };
        try {
          fs.writeFileSync(lock, JSON.stringify({ terminal: "" }), { flag: "wx" });
        } catch (_) {
          if (live(recorded())) {
            logEvent("wait_bg", { run: f.run, which: "ALREADY_WAITING", path: file });
            out("ALREADY_WAITING: a dely wait is running for this Run; end your turn, it will wake you.", 0);
          }
          writeLock("");
        }
        try {
          fs.unlinkSync(file);
        } catch (_) {
          /* no prior output */
        }
        const q = JSON.stringify;
        const self = q(__filename);
        const bin = q(process.execPath);
        const extra = ["control", "skip", "stall-min", "timeout-min"]
          .filter((k) => f[k] && f[k] !== true)
          .map((k) => " --" + k + " " + q(f[k]))
          .join("");
        const cmd =
          "DELY_WAITER=1 " +
          bin +
          " " +
          self +
          " wait --run " +
          q(f.run) +
          " --as " +
          q(me) +
          extra +
          " > " +
          q(file) +
          " 2>&1; rm -f " +
          q(lock) +
          "; " +
          bin +
          " " +
          self +
          " notify --run " +
          q(f.run) +
          " --as " +
          q(me) +
          " --out " +
          q(file) +
          "; exit";
        const r = orca(["terminal", "create", "--worktree", "path:" + process.cwd(), "--title", "dely-wait", "--command", cmd]);
        if (r.ok === false) {
          try {
            fs.unlinkSync(lock);
          } catch (_) {
            /* lock */
          }
          fail((r.error && r.error.message) || "terminal create failed", { run: f.run });
        }
        writeLock((r.result && r.result.terminal && r.result.terminal.handle) || "");
        logEvent("wait_bg", { run: f.run, which: "WAITING", path: file });
        out("WAITING", 0);
      }
      
      function notify(f) {
        const run = (orca(["orchestration", "run-show", "--id", f.run]).result || {}).run || {};
        const to = run.coordinator_handle || f.as;
        const text = "dely wait finished for " + f.run + ". Finish your current step, then read " + f.out + " and continue.";
        const retryMs = Math.max(1, Math.floor(NOTIFY_RETRY_S * 1000));
        const giveUpMs = NOTIFY_GIVEUP_S * 1000;
        for (const t0 = Date.now(); ; ) {
          const r = orca(["terminal", "send", "--terminal", to, "--text", text, "--enter"]);
          if (r.ok !== false) {
            logEvent("notify", { run: f.run, target: to, result: "sent" });
            return;
          }
          const msg = (r.error && r.error.message) || "";
          if (!/agent_prompt_blocked/.test(msg)) {
            logEvent("notify", { run: f.run, target: to, result: "failed" });
            return;
          }
          const left = giveUpMs - (Date.now() - t0);
          if (left <= 0) {
            logEvent("notify", { run: f.run, target: to, result: "gave_up" });
            process.exit(1);
          }
          sleep(Math.min(retryMs, left));
        }
      }
      
      function logCmd(f) {
        let payload;
        try {
          payload = JSON.parse(f.json);
        } catch (e) {
          fail("cannot parse --json: " + (e.message || e), { run: f.run });
        }
        if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
          fail("--json must be an object", { run: f.run });
        }
        logEvent("delivery", Object.assign({}, payload, { run: f.run, repo: f.repo || payload.repo || null }));
        process.exit(0);
      }
      
      const [cmd, ...rest] = process.argv.slice(2);
      const table = { preflight, dispatch, wait, "wait-bg": waitBg, notify, log: logCmd };
      const need = {
        preflight: ["repo", "run"],
        dispatch: ["repo", "run", "phase", "spec-file"],
        wait: ["run", "control"],
        "wait-bg": ["run", "control"],
        notify: ["run", "out"],
        log: ["run", "json"],
      };
      if (!cmd) {
        printIdentity();
        out(USAGE, 0);
      }
      if (!table[cmd]) out(USAGE, 2);
      const f = flags(rest);
      if (need[cmd].some((k) => !f[k])) out(USAGE, 2);
      table[cmd](f);
      
  • templates
    • decision-record.md 1.5 KB
      # Decision record template
      
      Durable. It records what was decided and why, and changes only when the decision
      changes. It is not a task tracker and not a test log.
      
      If the project has a frontmatter convention for decision documents, follow it —
      `AGENTS.md` names it. Where a field asks for a commit SHA, resolve it with `git`;
      never write the SHA of the commit that will carry the field, because a commit
      cannot record its own SHA before it exists.
      
      ---
      
      # <Decision, stated as an outcome rather than a task>
      
      ## Context
      
      The problem, and the current behaviour it applies to, with evidence. Numbers and
      observations rather than impressions. If a rule or a limit is being changed, name
      what it was and why it is no longer right.
      
      ## Decision
      
      What is now true. Written so a reader can tell whether an implementation complies.
      
      Where the decision replaces an earlier one, say which and how — amend the earlier
      record in place rather than deleting its reasoning.
      
      ## Alternatives considered
      
      Each one that was genuinely considered, and the reason it lost. An alternative
      listed without a reason is decoration.
      
      ## Consequences
      
      What follows, including what gets worse or stays unsolved. State what this decision
      is **not** expected to improve, so a later reader does not judge it against a
      promise it never made.
      
      ## Non-goals
      
      Things a reader might reasonably assume are included and are not.
      
      ## Deferred
      
      Work this decision deliberately leaves out, with what would trigger it. Anything
      deferred without a trigger is abandoned; say so instead.
      
    • plan.md 3.8 KB
      # Plan template
      
      Transient. Deleted in the release commit, before the release-binding review,
      after anything durable has moved into the decision record or the documents
      that own the changed paths.
      
      Three to five tightly related tasks. One coherent contract. One acceptance table.
      No status duplicated anywhere else.
      
      ---
      
      # Plan — <the contract this delivers>
      
      Decision record: `<path>`
      
      **Baseline:** the SHA of the commit carrying the decision record and this plan.
      Leave empty until that commit exists rather than guessing it.
      
      ## Goal
      
      One paragraph. What is true when this is done, and what is out of reach.
      
      ## Allowed scope
      
      ```
      <paths that may change>
      ```
      
      Carried without being listed: the colocated test of any allowed source file, any
      registry test enumerating what this plan adds, and any document owning an allowed
      path. State here which of those apply and which yielded nothing — checked, not
      assumed. State the command that produced the listed paths and any count or
      scope; the claim reports that command's output, and a count or a scope
      enumerates rather than samples.
      
      ## Forbidden scope
      
      Paths a reader might expect to be included, with why they are not. Name anything
      whose filename suggests relevance but whose contents do not.
      
      ## Execution envelope
      
      Protected dirty paths: pre-existing uncommitted changes this plan must not stage,
      overwrite, stash, or reset — name them, or say the tree was clean at baseline.
      
      Branch, base, remote, and pull-request target: the feature branch this plan
      commits to, the branch and remote it targets, and where its pull request goes.
      
      Resolved phase pins: the harness, model, and effort each dispatched role runs
      under, taken from `AGENTS.md` — not a default left implicit.
      
      Authority: this plan may branch, commit only its own owned paths, run gates,
      push the named branch, and open or update the named pull request. It may not
      merge, force-push, stash, reset, clean, or edit anything outside owned scope.
      
      ## Tasks
      
      ### 1. <behaviour, not activity>
      
      **Behaviour.** What becomes true. Observable, not internal.
      
      **Direction.** Enough for an implementer to start without re-deciding the contract.
      Not a pasted implementation.
      
      **Files.** Expected owners. If a task needs a file outside allowed scope, the plan
      is wrong — fix it now, not at review.
      
      **Focused verification.** The command or check that proves this task, and how it
      fails if the task is not done.
      
      **Document impact.** Which owning documents this task obliges you to reconcile, and
      why each one — ownership, not habit.
      
      ## Acceptance
      
      | Requirement | Instrument | Counterexample | Observed red |
      | --- | --- | --- | --- |
      | | | | |
      
      Design fills Counterexample; implement fills Observed red. An empty cell is an
      unfinished row. "The feature is absent" does not satisfy Counterexample. A row
      with no counterexample must say so and say a human reads the diff — that escape
      stays legal and is worth keeping only when someone actually reads it.
      
      Every row's instrument must tell a pass from a failure. A row that cannot
      discriminate is not acceptance; either replace the instrument or record that no
      instrument exists and that a human reads the diff.
      
      **Cannot be observed:** what the available instruments do not cover. A green suite
      that never exercises a surface is not evidence about that surface.
      
      ## Stop conditions
      
      What makes this `BLOCKED` or `NEEDS_REPLAN` rather than something to work around.
      Include any assumption that holds for one tool, harness or environment and has not
      been verified for the others this plan touches.
      
      ## Closure gates
      
      ```
      <exact commands, with the directory each runs from>
      ```
      
      If a gate is skipped, record the boundary and why the change cannot be observed by
      it. Report every gate with the exact command, the summary line verbatim, and the
      exit code. `$?` after a pipe reports the last command in the pipe, not the gate.
      
  • SKILL.md 19.1 KB
    ---
    name: delivery
    description: Deliver a change through an approved design contract, sequential implementation, independent review and exact-HEAD release. Use for any Bounded or Architectural change — including a small, one-line behavioral fix, which is the canonical Bounded case — so it gets design approval and independent review. Not for a Spike, which investigates and recommends without starting a delivery run.
    ---
    
    # Delivery
    
    Dely accepts a request that may still be vague, brings it to an approved
    design contract, then automates sequential implementation, independent
    review, and pull-request preparation. It is a thin control protocol, not an
    orchestrator, SDLC framework, or second source of Git state.
    
    Read `AGENTS.md` in the repository for this project's gate commands, artifact
    paths, default branch, and per-phase harness/model/effort pins. This skill
    never names them.
    
    ## Two human gates
    
    1. Approve the design contract before candidate mutation.
    2. Merge or publish after Dely has prepared the reviewed pull request.
    
    Dely pauses outside those gates only for a scope or architecture change, a
    destructive action, new authority, replan, or an unavailable required runtime.
    
    ## The control session
    
    The current interactive session is Control. It owns the approval invariant,
    task boundaries, exception handling, dispatch supervision, and release. It
    does not implement or review the candidate, and does not prescribe question
    count, order, format, or skill-selection precedence. Native Plan Mode and
    active design skills govern their own surfaces under the harness's
    precedence; neither bypasses approval. Before mutation, Control obtains
    explicit human approval of a design contract. One approval covers that
    scope; a material change needs a new one. Control surfaces uncertainty that
    could materially change intent, acceptance, authority, public contract,
    architecture, or consequential risk. Material assumptions must be explicit.
    
    ## Shape
    
    Use the smallest contract that safely holds the change. Risk may promote an
    otherwise small change; diff size never demotes data-loss, security,
    permission, or public-compatibility risk.
    
    | Shape | Use | Artifact | Review |
    | --- | --- | --- | --- |
    | Spike | Investigation only; no candidate is delivered | Approved probe and recommendation; no delivery run | none |
    | Bounded | Small change, clear behaviour and ownership | Approved in-chat design and short execution envelope | one whole-change review |
    | Architectural | Multiple behaviours, public-contract change, architecture decision, or promoted risk | Approved decision record, task plan, execution envelope | task review per task, then one integration review |
    
    An approved design contract states intent and success criteria; scope and
    authority; affected public contract or architecture; consequential risks and
    material assumptions; and a plausible counterexample that distinguishes
    correct behaviour from a present-but-wrong implementation. If no executable
    instrument can discriminate, the contract names the manual inspection and
    its limit.
    
    Architectural work uses `templates/decision-record.md` (durable) and
    `templates/plan.md` (transient, deleted in the release commit, before the
    release-binding review). Commit both before implementation begins — that
    commit is the review baseline.
    
    ### Acceptance
    
    One table: each requirement, the instrument that proves it, the plausible
    wrong implementation that instrument rejects, and where that rejection was
    observed.
    
    **An acceptance row is invalid until its instrument discriminates.** A row
    that passes both before and after the change proves nothing and will be
    found at review. Baseline-red is not enough: red only because the feature
    is absent says nothing about catching an implementation that is present,
    runs, returns a pass, and is wrong. Each row names such a wrong
    implementation. "The feature is absent" does not satisfy Counterexample.
    Where none exists, the row says so and a human reads the diff.
    
    Record what the instruments cannot observe. Prefer the simplest instrument
    that proves the contract. Any claim about extent — a scope, a count, a set
    of call sites — names the command that produced it, reports its output, and
    enumerates rather than samples. Naming the command is not the measurement;
    the command must have been run.
    
    ## Execution envelope
    
    Before mutation, Control resolves deployment preferences against the live
    harness surface, starts Orca and verifies its required capabilities,
    records the dirty baseline and exact-path ownership, and creates a feature
    branch when starting on the default branch. The envelope freezes owned
    scope and paths; protected pre-existing dirty paths; acceptance criteria,
    counterexample, and focused instruments; branch, base, remote, and
    pull-request target; resolved harness, model, and effort for dispatched
    roles; and authority to branch, commit owned paths, run gates, push, and
    open or update a pull request. It never authorises merge, force-push,
    stash, reset, cleanup, or an edit outside owned scope. Dely stages and
    commits only contract-owned paths. It never stashes, resets, cleans, or
    silently absorbs the user's existing changes. If a path carries protected
    baseline changes and Dely must also modify it, Control pauses rather than
    combining ownership.
    
    ## Orca and the helper
    
    Orca is the required execution plane. It launches and supervises fresh
    native harness TUIs with the resolved harness, model, and effort.
    Orchestration is a required Orca capability. `dely:delivery` starts Orca,
    then Control loads `orca skills get orchestration` and follows its
    supervised loop. It stops only when the CLI is missing, the runtime cannot
    start, or a required capability is absent — there is no direct dispatch and
    no headless fallback of any kind. The launcher is `scripts/dely` relative
    to this skill. Control's wake mode is that harness's `controlWake` in
    `../../harnesses.json`. The preflight step runs in setup and again after a
    `NO_ACK`; a delivery does not preflight before its first dispatch.
    
    Write the prompt to an untracked file **inside the worktree**. Never inline
    it in a shell argument: prompts carry backticks, quotes and newlines, and a
    shell argument mangles them. A path outside the workspace can trigger a
    second permission surface some harnesses still prompt for even when tool
    approval is skipped. Do not stage that file. After the worker returns,
    delete it: Control owns that dispatch artifact, not `git clean`. The handoff
    is a file in the worktree; its path travels as `payload.reportPath` and the
    message body stays short. `--spec` and `--body` are shell arguments, which
    this skill already forbids for prompts.
    
    The dispatch prompt carries the task, its scope, and the evidence required.
    It does not define role dispositions or the conditions for reaching one —
    those belong to this skill, and a prompt that restates them narrows or
    contradicts them. Where the design contract states an acceptance row, the
    prompt carries that row as written. Every dispatch goes through
    `dely dispatch`. Control does not compose a worker launch or call
    `worker-start` by hand. The helper reads the pins from `AGENTS.md` and
    appends the acknowledgement instruction and a sentence that the Orca
    preamble and the spec file are everything the worker needs and that it
    should read no other skill. The `worker-start` receipt records
    `launch.requested` and `launch.effective`; it does not establish that the
    worker can serve the request or that it cannot. Orca applies the execution
    plane's configured permission default and does not add a sandbox the project
    did not pin.
    
    **Name the model and effort on every dispatch.** The helper passes
    `--model`/`--effort` when `../../harnesses.json` says that harness takes
    them, and omits a flag whose value is `default`. On a harness that takes
    neither, a Model written there is silently not applied: write `default` and
    set the model in Orca's agent default arguments. A worker left on a harness
    default is an unpinned environment: it lives in the harness's own config,
    it changes without announcing itself, and the dispatch that relies on it
    looks identical to one that pinned the same value deliberately.
    
    **Never act on an Orca nudge.** After `DISPATCHED`, wait by the wake mode
    of **this Control's own harness** — not the harness of the worker being
    waited on. `--control` is this session's harness id, the same id whatever
    worker is in flight. **background** runs
    `dely wait --run <run> --control <self>` as a background command and ends
    the turn; **waker** runs `dely wait-bg --run <run> --control <self>` as its
    last command, then ends the turn (a waker Control never runs `dely wait`);
    **unsupported** cannot be Control. The helper reads the harness of the Orca
    terminal it runs in and refuses a waker even when `--control` names another
    one, so `REFUSED … (called with --control …)` means use `wait-bg`.
    
    **Result handling.** `SETTLED`: process the batch, do the guide's completion
    accounting, and acknowledge. `ATTENTION` has two routes, and the difference
    is whether the plane can still see the worker. With `nextAction.kind` other
    than `none`, run the argv Orca printed and skip that id next time. With
    `nextAction: none` and `attention.requiresAction`, the plane has lost sight
    of the worker rather than asked for something: read it with `worker-read`
    and `worker-show`, and if the process is gone, `worker-stop`, then
    `worker-abandon` when the stop reports `stop_unknown`, then
    `worker-release`, then one fresh `dely dispatch` with the same prompt file.
    A second time on the same input goes to the human. An absent `nextAction` is
    absent, not `none` with attention — that row is not `ATTENTION` and the wait
    continues. `STALLED`: read the output, then wait again or recover.
    `NO_ACK`: run setup's `dely preflight` in the same Run. If every pin passes,
    one fresh `dely dispatch` with the same prompt file; never retry into the same
    terminal, and never reuse a settled terminal; a second failure on the same
    input goes to the human. Any `PREFLIGHT … FAIL`: do not dispatch to any
    pin — a failed pin's cause is already known and another dispatch only
    repeats it.
    Stop and relay the printed reason: the harness, the path, and that the human
    opens that harness there once to answer its own dialog; Dely never answers
    it. The failed worker is already stopped and released. When the human says
    it is done, rerun `dely preflight` in the same Run and continue from there.
    `FAILED`: one fresh `dely dispatch` with the same prompt file and the same
    retry limits. `DEADLINE`: a checkpoint — check `worker-list` and the last
    output; if the worker is progressing, wait again; a second `DEADLINE` with
    no progress goes to the human. `ERROR`: go to the human. The worker reports
    once with `worker_done` and an `--outcome`; completion comes from that
    `worker_done` — do not infer it from reading the worker's terminal. Each
    delivery opens its own Run with an objective
    (`orca orchestration run-create --objective`) rather than reusing another's,
    so a stale report cannot settle a new wait.
    
    Investigation is one read-only diagnostic dispatch inheriting the
    `implement` pin; it may reproduce, inspect, and report, but does not edit,
    commit, launch workers, or expand scope.
    
    Stop and ask the human when: a result maps to no route or more than one; the
    worker **failed** rather than returned a stop status — a non-zero exit with
    no result, an exhausted quota, an authentication error — which is not
    `BLOCKED` and must not be treated as one; Orca is unavailable or a required
    capability is absent; an action needs authority policy reserves to the
    human; or the same worker fails twice on the same input. Say what you know,
    what you tried, and what the options are. Do not pick one.
    
    ## Implementation
    
    Control creates a separate task only when that unit has its own test cycle
    and a reviewer could accept it while rejecting its neighbor. Same-shaped
    mechanical changes are batched. Tightly coupled work stays one task and one
    implementer. Each independent task gets a fresh implementer TUI.
    
    An implementer reads the decision record, the plan, and the baseline — not
    the design session's transcript. It owns only its task, runs a focused
    acceptance instrument, and creates one task-scoped commit. For behaviour
    with a deterministic executable test it uses TDD; the portable invariant is
    smaller: observe a discriminating failure for the intended reason before
    changing behaviour. A shell probe, parser fixture, or diff inspection may
    be the correct instrument for configuration, documentation, generated
    files, or environment-bound integration.
    
    The counterexample named in each acceptance row is observed red and cited.
    That observation is not the behaviour's own absence: one is the feature
    absent, the other is an implementation that is present, runs, returns a
    pass, and is wrong.
    
    Implement the whole task before handing back. Stop and return `BLOCKED` or
    `NEEDS_REPLAN` instead of a partial solution when the record contradicts
    the code, the contract is ambiguous, work outside the task becomes
    necessary, an existing test disproves an assumption, or the task no longer
    fits one session. A task needing continuation is a decomposition failure.
    
    ### Handoff
    
    ```text
    Status: DONE | BLOCKED | NEEDS_REPLAN
    Harness:            name, model, effort, sandbox
    Session:            the dispatch id
    Baseline:
    Changed paths:
    Contract coverage:
    Verification:
    Deviations from plan:
    Residue:
    Git state:
    END OF HANDOFF
    ```
    
    `END OF HANDOFF` is the last line and load-bearing: the only thing that
    distinguishes a handoff from one cut off mid-write. Under `Residue`, a claim
    of nothing left needs evidence: name the check that returned empty. Under
    `Verification`, cite the dispatch-bound command, output, and outcome that
    Orca recovers for that task — the transcript or terminal it selects, and
    any cursor mechanics, are Orca's concern, not this skill's. Do not
    transcribe output by hand. Where Orca cannot recover a dispatch item, treat
    the worker's own account as the thing under check rather than as the check,
    and say so.
    
    ## Review
    
    Review independence is role independence: a fresh session that did not
    implement and does not edit the candidate. It gets the decision record (or
    Bounded design), the baseline, and the diff. The phase adds no sandbox by
    default; `AGENTS.md` may pin one for a concrete risk. Review depth is
    adaptive: Bounded work gets one independent whole-change review. Each
    Architectural task gets an independent task review. After all tasks are
    accepted, a different fresh reviewer performs one integration review of
    task interactions, complete-contract coverage, deferred findings, candidate
    identity, and release readiness. Only that final review is release-binding
    for Architectural work; Bounded work has no earlier task review and no
    duplicate integration review. No worker runs while a review of the same
    working tree runs. The working tree and its gate surface are shared mutable
    state, and a review reproduces gates in that tree, so a concurrent edit
    makes another task's work look like this one's result.
    
    **Reproduce, do not accept.** Run the gates yourself. A claim you did not
    reproduce is not evidence. The reviewer observes the counterexample
    discriminate for itself — an implementation that is present, runs, returns
    a pass, and is wrong. An instrument red only because the behaviour was
    absent is not that observation.
    
    Classify findings: **Blocking** — contract failure, regression, data or
    security risk. **Important** — missing required behaviour, test, or
    reconciliation. **Minor** — useful, does not block. **Out of scope** —
    recorded, not absorbed. Return exactly one role disposition: `ACCEPT`,
    `CHANGES_REQUESTED`, or `BLOCKED`. State what the review did not verify —
    what it did not reproduce or read. A contradiction you cannot resolve is
    `CHANGES_REQUESTED`. Do not open remediation over wording when
    deterministic checks already prove the contract.
    
    ### Remediation
    
    One pass is one remediation pass per finding, not per review. For an
    in-contract `CHANGES_REQUESTED` finding, the **original implementer**
    verifies it, fixes the root cause, reruns the affected instruments and
    closure gates, and writes a separate remediation commit — this is the
    single original-party remediation. Control owns the plan and the decision
    record for the whole run, including remediating findings inside them.
    Amending them is not implementing the candidate. The **reviewer that raised
    the finding** checks its reproduction and the fix-only diff, and
    scope-checks a Control amendment the same way. If that scoped re-review
    does not accept, Control routes to `REPLAN_OR_SPLIT` — it does not start
    another repair loop. `BLOCKED` preserves the candidate and escalates the
    unresolved dependency or authority question to Control separately from a
    failed worker process; it is not remediated by the original implementer. A
    fresh replacement reviewer is used only when the original reviewer is
    unavailable or contested, and for the Architectural integration review.
    
    ## Release
    
    Control performs release with native Git and forge tools; release dispatches
    no LLM worker and makes no post-review candidate edit.
    
    1. Complete implementation and, for Architectural work, its task reviews.
    2. Reconcile owning documentation, delete the plan, and commit the
       complete candidate.
    3. Run the focused instruments and project closure gates on exact HEAD.
    4. Push the feature branch and create or update a draft pull request.
    5. Run the applicable final review while remote CI runs on that same HEAD.
    6. Require both that review's `ACCEPT` and required checks green.
    7. Mark the pull request ready and report it for human merge.
    
    Any candidate mutation after the applicable final review invalidates that
    verdict; Control reruns the affected gates and review on the new exact HEAD.
    Affected gates are those that can observe the change class; a project may
    name that subset. Dely never merges, force-pushes, or publishes outside the
    approved target and authority. If project policy cannot publish work in
    progress, Dely delays the push and pull request until the applicable review
    accepts.
    
    Maintenance logging is machine-local and opt-in at `~/.dely/log.jsonl`. It
    stays opt-in on the presence of `~/.dely/` and is never created by Dely.
    Control closes a delivery with `dely log --run <run> --json '<object>'`,
    after release or when it stops early, rather than assembling a line by hand.
    `dely` with no arguments prints which copy is running, and its usage.
    
    ## Failure and recovery
    
    Recovery uses Orca records, Git, CI, and pull-request state — never inferred
    from an ambiguous, missing, or merely transport-level outcome.
    
    | Failure | Disposition |
    | --- | --- |
    | In-contract implementation defect | Original implementer remediates |
    | Scoped remediation re-review does not accept | `REPLAN_OR_SPLIT` |
    | Scope or architecture must change | Return to the design gate |
    | New authority or destructive action is required | Ask the human |
    | Orca or a required capability is unavailable | Stop; no headless fallback |
    | any `PREFLIGHT … FAIL` | Dispatch to no pin; relay harness, path and dialog to the human; rerun preflight in the same Run when told |
    | Harness fails or evidence is insufficient | Preserve the candidate, report the native outcome and role disposition |
    | Idempotent release step is interrupted | Verify Git and pull-request state, then resume |
    

Comments (0)

Sign in to join the conversation.

No comments yet.

Reviews (0)

No reviews yet.

Related