c8ctl-plugin-nano 1.69.1 → 1.69.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -521,6 +521,33 @@ NANO_AGENTIC_PERMISSION=escalate c8ctl nano work coder
521
521
  - `--permission yolo|escalate|filter` (default `yolo`) selects the ACP permission
522
522
  policy. `NANO_AGENTIC_PERMISSION` overrides it at work time.
523
523
 
524
+ **Protocol must match the command.** The command and the protocol have to agree:
525
+ a command that runs the harness in ACP mode (an `--acp` / `acp` token or a
526
+ `*-acp` adapter binary) hired with `protocol: pipe` would have plain JSON piped
527
+ to an ACP-speaking binary that rejects it and exits 0 empty — and the worker
528
+ would silently **complete** every job it took with no work done (issue #275). To
529
+ prevent that, `hire` **refuses** an ACP-mode command on `protocol: pipe`, and
530
+ `work` **refuses to start** a worker with the same mismatch (a pre-existing
531
+ or hand-edited profile). Re-hire with `--protocol acp` (or drop the ACP selector
532
+ from the command). `protocol: acp` with no selector on the command is fine — the
533
+ worker appends `--acp` at spawn time.
534
+
535
+ **Container workers are pipe-only.** A `--sandbox docker|podman` worker runs the
536
+ harness over the pipe transport regardless of `--protocol`, so an ACP-mode
537
+ command is a mismatch there *even with* `--protocol acp` (the container would
538
+ still pipe plain JSON to an ACP-speaking harness). Both `hire` and `work`
539
+ evaluate the **effective** protocol, so such a container profile is rejected at
540
+ hire time and refused at work time — drop the ACP selector from the command for a
541
+ container role.
542
+
543
+ **An empty job is failed, not completed.** If a harness exits 0 but produced
544
+ *nothing* — no result vars, no output, no transcript turns, no commits and no
545
+ push — the worker **fails** the job (preserving its retries, so it reactivates
546
+ and surfaces as an incident) instead of completing it. Completing an empty job
547
+ would silently drop whatever it carried (an escalation answer, a review verdict)
548
+ because downstream gateways see no status and fall through to their default. A
549
+ run with *any* evidence of real work completes exactly as before.
550
+
524
551
  **What ACP unlocks.** Because the harness speaks a structured protocol rather than
525
552
  a scraped terminal, the ACP path gives you a **structured turn/tool event stream**
526
553
  (today serialized to text chunks on the relay lane — a *minimal* mode, not yet
@@ -714,21 +741,30 @@ the job with a decremented retry count. Profiles are stored in the plugin's
714
741
  >
715
742
  > **Recovery scope (what survives a re-activation):**
716
743
  > - **Committed work is durable *only when this activation re-checks-out the exact
717
- > branch the prior run pushed onto*** — a single invariant: `repository.ref` names a
718
- > stable non-base branch **and** `branch.create` names that **same** branch
719
- > (`create === ref`). The clone lands the workspace on `ref` (prior commits present),
720
- > and `provisionRepo`'s honored `git checkout -B <create>` is then a no-op that keeps
721
- > the workspace on it and pushes it back, so the resumed agent can inspect it for the
722
- > **last pushed commit** (`git log` / the open PR for what landed). Every other shape
723
- > is **not** durable and is classified **transcript-only**: a `ref`-only job with no
724
- > `branch.create` (the PR-based review/fix-ci/rebase shape) is committed onto a
725
- > **per-run `nano/agent-work/<base>-<runId>` fallback branch** the next clone of `ref`
726
- > never sees; a `branch.create` that differs from `ref` does `checkout -B <create>`
727
- > off the freshly re-cloned base and never fetches the existing remote `<create>`; and
728
- > a base-like ref/create, a bare-URL / base-only clone, `branch.push=false`, or a
729
- > `repository.sha`-detached checkout likewise recover nothing. For every transcript-only
730
- > run the resume preamble points at the transcript (VERIFY-first) rather than promising
731
- > a branch to check out.
744
+ > branch the prior run pushed onto* — and only when the envelope alone can *prove*
745
+ > that.** One envelope shape qualifies: `repository.ref` names a stable non-base
746
+ > branch **and** `branch.create` names that **same** branch (`create === ref`). The
747
+ > clone lands the workspace on `ref` (prior commits present) and `provisionRepo`'s
748
+ > honored `git checkout -B <create>` is a no-op that keeps it there and pushes it back,
749
+ > so the resumed agent can inspect it for the **last pushed commit** (`git log` / the
750
+ > open PR for what landed). The **ref-only** shape (no `branch.create`, the PR-based
751
+ > review/fix-ci/rebase shape) is deliberately **transcript-only** even though
752
+ > `provisionRepo` often *does* push the checked-out PR head: that decision hinges on
753
+ > `provisionRepo` **resolving the remote default** (a checked-out branch that *is* the
754
+ > default is base-like and gets fallback-branched, and an unresolvable default fails
755
+ > closed), and resume gating runs **before the clone with no network**, so it can never
756
+ > prove a bare `ref` is not the repo's (possibly custom, e.g. `trunk`) default — it
757
+ > fails closed to transcript-only rather than over-claim recovery for a
758
+ > fallback-branched run. Every other shape is likewise **not** durable and classified
759
+ > **transcript-only**: a `branch.create` that differs from `ref` does `checkout -B
760
+ > <create>` off the freshly re-cloned base and never fetches the existing remote
761
+ > `<create>`; and a base-like ref/create (including a conventional `main`/`master`
762
+ > head, or a ref-only job with no configured base), a bare-URL / base-only clone,
763
+ > `branch.push=false`, or a `repository.sha`-detached checkout likewise recover
764
+ > nothing. For every transcript-only run the resume preamble points at the transcript
765
+ > (VERIFY-first) rather than promising a branch to check out. (The **#270 provisioning
766
+ > fix** — a ref-only PR head is pushed to, not diverted onto a per-run fallback — is
767
+ > unaffected; only the resume *prompt wording* is conservative here.)
732
768
  > - **Uncommitted working-tree changes are *not* recovered** by default —
733
769
  > the throwaway workspace does not persist across activations, so any delta the
734
770
  > previous run had not committed is lost and the resumed agent re-derives it. The
@@ -235,6 +235,32 @@ export function describeSdkError(err) {
235
235
  return { status: status ?? null, body: normalizedBody, message };
236
236
  }
237
237
 
238
+ /**
239
+ * True when an HTTP status marks a PERMANENT rejection of the terminal
240
+ * status→COMPLETED update (issue #275): a 4xx (a stale lease fence, an invalid
241
+ * transition, a 0-turns husk the engine refuses to terminalize) will not succeed
242
+ * on a blind retry, so the producer stops retrying it immediately instead of
243
+ * burning the remaining attempts against a dying lease. 5xx / network / timeout
244
+ * failures are potentially transient and still retry. `null`/unknown statuses are
245
+ * treated as transient (retry) — fail-safe toward recovery, not toward giving up.
246
+ *
247
+ * Two 4xx statuses are the exception — NOT permanent, because a retry can still
248
+ * succeed:
249
+ * - HTTP 429 (Too Many Requests): rate limiting, so a retry (after backoff) can
250
+ * succeed. This repository already treats 429 as non-lease-loss/transient
251
+ * elsewhere (supervisor.test.mjs), so classifying it as permanent here would
252
+ * give up after one attempt and strand the instance non-terminal.
253
+ * - HTTP 408 (Request Timeout): a transient server-side timeout of the request,
254
+ * not a durable rejection of the transition, so the terminal update can succeed
255
+ * when retried. Classifying it as permanent would strand the AgentInstance
256
+ * non-terminal after a single attempt over a temporary timeout.
257
+ */
258
+ export function isPermanentTerminalStatus(status) {
259
+ const n = Number(status);
260
+ if (n === 429 || n === 408) return false;
261
+ return Number.isFinite(n) && n >= 400 && n < 500;
262
+ }
263
+
238
264
  // Redact a lease token down to a presence + short tail so it can be logged for
239
265
  // correlation without leaking the opaque fence value. For a short token a last-4
240
266
  // tail would reveal most (or all) of the value, so emit a fixed redacted marker
@@ -684,6 +710,10 @@ export function createAgentInstanceProducer(opts = {}) {
684
710
  // "created but nothing ingested over a long run", and a deduplicated no-op from a
685
711
  // real append (issue #230 / #229 / #232).
686
712
  let appendedTurns = 0;
713
+ // Issue #275: latches true once the harness emits a plan update, so the empty-job
714
+ // detector can tell a genuinely-engaged ACP run (a plan, even with 0 persisted
715
+ // turns) from a protocol-mismatched husk.
716
+ let sawPlan = false;
687
717
  // Elevate the FIRST per-turn append failure to `warn` (repeats stay `debug`) so a
688
718
  // 400/404 append storm is visible without flooding the log (issue #230 / #229).
689
719
  let appendFailureLogged = false;
@@ -919,6 +949,9 @@ export function createAgentInstanceProducer(opts = {}) {
919
949
  const onPlan = (rawUpdate, opts) => {
920
950
  const content = buildPlanContent(rawUpdate);
921
951
  if (!content) return;
952
+ // Issue #275: note that the harness emitted a plan (real ACP engagement), so a
953
+ // 0-turn run that still planned is not mistaken for an empty husk.
954
+ sawPlan = true;
922
955
  const id = shortHash(JSON.stringify(content[1].object));
923
956
  // Already recorded, or an identical plan is still settling — skip either way so we
924
957
  // neither double-record nor enqueue a duplicate in-flight append.
@@ -1532,6 +1565,21 @@ export function createAgentInstanceProducer(opts = {}) {
1532
1565
  get agentInstanceKey() {
1533
1566
  return agentInstanceKey;
1534
1567
  },
1568
+ /**
1569
+ * Count of AgentHistory turns the engine actually created for this instance
1570
+ * (issue #275): read by the worker's empty-job detector to tell a genuinely
1571
+ * engaged ACP run from a protocol-mismatched husk that appended nothing.
1572
+ */
1573
+ get appendedTurns() {
1574
+ return appendedTurns;
1575
+ },
1576
+ /**
1577
+ * True once the harness emitted an ACP `plan` update (issue #275): plan
1578
+ * engagement attests a real session even when no history turn persisted.
1579
+ */
1580
+ get sawPlan() {
1581
+ return sawPlan;
1582
+ },
1535
1583
 
1536
1584
  /**
1537
1585
  * Mint the AgentInstance (lease-gated) with an opening CONFIGURATION turn that
@@ -1594,6 +1642,25 @@ export function createAgentInstanceProducer(opts = {}) {
1594
1642
  await queue;
1595
1643
  },
1596
1644
 
1645
+ /**
1646
+ * Drain queued appends WITHOUT transitioning status, BOUNDED at `timeoutMs`
1647
+ * (defaults to finalizeTimeoutMs). Returns `true` when the queue fully drained
1648
+ * within the window, `false` when the bound won (appends are still in flight in
1649
+ * the background). Unlike `drain()` — which awaits the ENTIRE serialized append
1650
+ * queue and can therefore block for up to N×finalizeTimeoutMs on a large ACP
1651
+ * transcript or during an AgentHistory outage — this never holds its caller past
1652
+ * the bound, so an inspection step (e.g. the pre-settlement empty-job guard) can
1653
+ * sample the `appendedTurns`/`sawPlan` signals without risking the broker lease
1654
+ * (thread 4118913008). A `false` return is itself transcript evidence: turns were
1655
+ * enqueued (real agent activity) but not yet confirmed. The overrun appends keep
1656
+ * draining in the background (each is individually bounded), exactly like the
1657
+ * aggregate-drain overrun in `complete()`. Best-effort; never throws.
1658
+ */
1659
+ async drainBounded(timeoutMs = finalizeTimeoutMs) {
1660
+ flushMessage();
1661
+ return settleWithin(queue, timeoutMs, setTimer);
1662
+ },
1663
+
1597
1664
  /**
1598
1665
  * Abort/discard teardown for a run ABANDONED during setup (issue #222). Unlike
1599
1666
  * `complete()` this does NOT drive a terminal COMPLETED update and — critically —
@@ -1812,6 +1879,10 @@ export function createAgentInstanceProducer(opts = {}) {
1812
1879
  let completedOk = false;
1813
1880
  let terminalErr = null;
1814
1881
  let terminalTimedOut = false;
1882
+ // Issue #275: latches when the terminal update was rejected with a PERMANENT
1883
+ // (4xx) status — surfaced in the diagnostics so a fence/validation rejection
1884
+ // (the stuck-instance case) is distinguishable from a transient 5xx/outage.
1885
+ let terminalPermanent = false;
1815
1886
  const terminalAttempts = Math.max(1, terminalRetryMax);
1816
1887
  if (ok) {
1817
1888
  for (let attempt = 1; attempt <= terminalAttempts; attempt += 1) {
@@ -1840,11 +1911,19 @@ export function createAgentInstanceProducer(opts = {}) {
1840
1911
  // A hung endpoint won't recover within the next attempt and each retry
1841
1912
  // burns another finalizeTimeoutMs against the lease, so STOP retrying on a
1842
1913
  // timeout (the underlying call is left to settle in the background). A
1843
- // plain rejection is potentially transient, so those still retry.
1914
+ // plain rejection is potentially transient, so those still retry — EXCEPT
1915
+ // a permanent 4xx (issue #275): a 422/409/400 terminal rejection (a stale
1916
+ // lease fence, an invalid transition, a 0-turns husk the engine refuses to
1917
+ // terminalize) will not succeed on a blind retry, so break immediately
1918
+ // rather than burn the remaining attempts against a dying lease.
1844
1919
  if (err && err.__nanoTimeout) {
1845
1920
  terminalTimedOut = true;
1846
1921
  break;
1847
1922
  }
1923
+ if (isPermanentTerminalStatus(terminalErr?.status)) {
1924
+ terminalPermanent = true;
1925
+ break;
1926
+ }
1848
1927
  }
1849
1928
  }
1850
1929
  }
@@ -1856,7 +1935,11 @@ export function createAgentInstanceProducer(opts = {}) {
1856
1935
  // that manual reconciliation is required (issue #230).
1857
1936
  logger?.warn?.(
1858
1937
  `AgentInstance ${agentInstanceKey}: terminal status update to COMPLETED ` +
1859
- `${terminalTimedOut ? `timed out (bounded at ${finalizeTimeoutMs}ms)` : `failed after ${terminalAttempts} attempt(s)`} — ` +
1938
+ `${terminalTimedOut
1939
+ ? `timed out (bounded at ${finalizeTimeoutMs}ms)`
1940
+ : terminalPermanent
1941
+ ? `rejected permanently (HTTP ${terminalErr?.status ?? '4xx'}) — not retried`
1942
+ : `failed after ${terminalAttempts} attempt(s)`} — ` +
1860
1943
  `status=${terminalErr?.status ?? 'n/a'} ` +
1861
1944
  `body=${terminalErr?.body ?? 'n/a'} message=${terminalErr?.message ?? 'n/a'}; ` +
1862
1945
  `MANUAL RECONCILIATION REQUIRED — the job settles now with no reactivation to retry ` +
package/agent-resume.mjs CHANGED
@@ -901,28 +901,41 @@ export function seedResumeEnvelope(envelope, transcriptText, opts = {}) {
901
901
  // Does this envelope declare a STABLE branch the prior run pushed its commits ONTO that
902
902
  // THIS activation will RE-CHECK-OUT with those commits present, so committed work is
903
903
  // durably recoverable? This is the ONLY case that justifies the recovery preamble's
904
- // "your committed work is on the pushed branch" promise, and it is a SINGLE, exact
905
- // invariant (issue #241): `repository.ref` names a stable non-base branch AND
906
- // `branch.create` names that SAME branch (`create === ref`). Why both, and why equal:
904
+ // "your committed work is on the pushed branch" promise. ONE envelope shape qualifies
905
+ // (issue #241): `repository.ref` names a stable non-base branch AND `branch.create` names
906
+ // that SAME branch (`create === ref`). Why:
907
907
  // - the clone checks out `repository.ref`, so only a stable `ref` lands the workspace
908
908
  // on the branch the prior run pushed (with its commits present);
909
- // - provisionRepo's honored `git checkout -B <create>` then keeps the workspace on
910
- // that branch and pushes it back — but ONLY when `create === ref` is the checkout a
911
- // NO-OP that preserves the prior commits. A `create !== ref` does `checkout -B
912
- // <create>` off the FRESHLY re-cloned `ref`/base HEAD and never fetches an existing
913
- // remote `<create>`, so prior commits on it are ABSENT;
914
- // - a `ref` with NO `branch.create` does NOT recover either: provisionRepo's
915
- // `checkedOut && wantPush` arm cuts a per-run `nano/agent-work/<base>-<runId>`
916
- // FALLBACK branch even for a checked-out PR head (the review/fix-ci/rebase shape,
917
- // which `repoEnvelope` emits with no `branch.create`), so the prior commits land on
918
- // a run-scoped ref that is NOT `ref`, and the next clone of `ref` lacks them.
909
+ // - with `create === ref`, provisionRepo's honored `git checkout -B <create>` is a
910
+ // NO-OP that keeps the workspace on the re-cloned `ref` and pushes it back preserving
911
+ // the prior commits;
912
+ // - a `create !== ref` does `checkout -B <create>` off the FRESHLY re-cloned `ref`/base
913
+ // HEAD and never fetches an existing remote `<create>`, so prior commits on it are
914
+ // ABSENT → non-recoverable;
919
915
  // - a repo-less job, `branch.push === false`, or a `repository.sha` (which DETACHES
920
916
  // HEAD, leaving no symbolic branch to push) is likewise non-recoverable.
921
- // A `ref`/`create` equal to the base commits on the base, which provisionRepo ALSO
917
+ // The REF-ONLY shape (no `branch.create`) is deliberately NON-recoverable here, even
918
+ // though provisionRepo's #270 `checkedOut && wantPush` arm often DOES stay on and push
919
+ // the checked-out non-base PR head. The catch: provisionRepo makes that decision AFTER
920
+ // RESOLVING THE REMOTE DEFAULT — a checked-out branch that IS the remote default is
921
+ // base-like and gets fallback-branched — and it FAILS CLOSED (cuts a fallback) whenever
922
+ // that default cannot be resolved. This module runs BEFORE the clone with NO network, so
923
+ // it can never resolve the remote default and thus can never prove a bare `ref` is not
924
+ // the repo's (possibly CUSTOM, e.g. `trunk`) default. A ref-only envelope
925
+ // `{ref:'trunk', baseRef:'main', branch:{push:true}}` is base-like to provisionRepo (it
926
+ // fallback-branches `trunk`) yet neither `main`/`master` nor `=== baseRef` here, so
927
+ // accepting it would OVER-CLAIM recovery for a run whose commits are actually on a per-run
928
+ // fallback (thread 4117276834). So we MIRROR provisionRepo's fail-closed-on-unresolvable-
929
+ // default stance: reject ref-only, requiring the explicit `create === ref` author-declared
930
+ // push target. (A ref-only #270 job still recovers safely — it falls through to the
931
+ // transcript-only preamble, which is VERIFY-first anyway.)
932
+ // A `ref` equal to the base commits on the base, which provisionRepo ALSO
922
933
  // fallback-branches → non-recoverable. The base is resolved with provisionRepo's
923
934
  // PRECEDENCE (`branch.base` before `repository.baseRef`), and a KNOWN non-blank base is
924
935
  // REQUIRED: with no configured base provisionRepo treats the checked-out `ref` as the
925
- // base and fallback-branches it, so a blank base cannot prove `ref` is non-base.
936
+ // base and fallback-branches it, so a blank base cannot prove `ref` is non-base. A
937
+ // conventional default name (main/master) is likewise treated as base-like (provisionRepo
938
+ // fallback-branches the resolved remote default, which the envelope can't reveal here).
926
939
  // (A push *rejected* at runtime is not knowable here; declared intent is the best signal
927
940
  // available at seed time; the recovery preamble is VERIFY-first so a not-yet-reconciled
928
941
  // branch still degrades safely.)
@@ -934,10 +947,19 @@ function envelopeHasPushedBranch(envelope) {
934
947
  if (isNonBlank(repo.sha)) return false;
935
948
  const ref = isNonBlank(repo.ref) ? String(repo.ref).trim() : '';
936
949
  const create = isNonBlank(branch?.create) ? String(branch.create).trim() : '';
937
- // The clone must re-check-out the exact branch the prior run pushed onto: a stable
938
- // `ref` AND a `branch.create` naming that SAME branch. Anything else (ref-only →
939
- // per-run fallback; create-only / create !== ref → `checkout -B` off base) leaves the
940
- // prior commits on a branch this activation does not check out.
950
+ // The clone must re-check-out the exact branch the prior run pushed onto, and we must be
951
+ // able to prove — from the ENVELOPE ALONE (no network at seed time) — that provisionRepo
952
+ // stayed on it rather than cutting a fallback. Only the explicit `create === ref` shape
953
+ // gives that proof: provisionRepo's honored `checkout -B <create>` is a no-op keeping the
954
+ // workspace on the re-cloned `ref` with its prior commits. Reject:
955
+ // - a blank `ref` (nothing stable to check out), and
956
+ // - the ref-only shape (`create === ''`): provisionRepo's push-onto-checked-out-head
957
+ // decision hinges on a remote-default resolution we cannot reproduce here, so a bare
958
+ // `ref` that is secretly the repo's custom default would over-claim recovery for a
959
+ // fallback-branched run (thread 4117276834) — fail closed, and
960
+ // - a create naming a DIFFERENT branch (`create !== '' && create !== ref`): its
961
+ // `checkout -B <create>` off the freshly re-cloned base HEAD never fetches an existing
962
+ // remote `<create>`, so the prior commits on it are ABSENT → non-recoverable.
941
963
  if (ref === '' || create === '' || create !== ref) return false;
942
964
  // provisionRepo ALSO fallback-branches when `ref`/`create` names the RESOLVED REMOTE
943
965
  // DEFAULT branch (base-like), which is not knowable from the envelope here. Conservatively