c8ctl-plugin-nano 1.69.2 → 1.69.4

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
@@ -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/c8ctl-plugin.js CHANGED
@@ -2275,6 +2275,23 @@ async function hireWorker(req, flags) {
2275
2275
  process.exit(1);
2276
2276
  }
2277
2277
 
2278
+ // Issue #275 (2): refuse the exact hire that caused the incident — a command
2279
+ // that runs the harness in ACP mode (`--acp` / `acp` subcommand / `*-acp`
2280
+ // adapter binary) persisted with `protocol: pipe`. The worker would pipe plain
2281
+ // JSON to an ACP-speaking binary that rejects it and exits 0 empty, silently
2282
+ // completing every job it takes. Fail loudly at hire time instead. Checked
2283
+ // against the EFFECTIVE protocol (`effectiveHarnessProtocol`): a container
2284
+ // sandbox runs pipe-only regardless of `--protocol`, so `--sandbox docker
2285
+ // --command 'nano-coder --acp' --protocol acp` is the same empty-husk mismatch
2286
+ // and must be rejected at hire time too — otherwise it persists cleanly here
2287
+ // and only `work` refuses it later (thread 4118414685).
2288
+ const hireEffectiveProtocol = effectiveHarnessProtocol(protocol, CONTAINER_SANDBOXES.has(sandbox));
2289
+ const hireMismatch = detectProtocolMismatch({ command, args: commandArgs, protocol: hireEffectiveProtocol });
2290
+ if (hireMismatch) {
2291
+ logger.error(`Refusing to hire "${name || '(unnamed)'}": ${hireMismatch.reason}`);
2292
+ process.exit(1);
2293
+ }
2294
+
2278
2295
  if (!isValidProfileName(name)) {
2279
2296
  logger.error(`Invalid profile name "${name}". Use letters, digits, dot, dash or underscore.`);
2280
2297
  process.exit(1);
@@ -2639,6 +2656,41 @@ const MAX_TASK_HARD_CAP_MS = 24 * 60 * 60_000;
2639
2656
  // version so the two contracts can evolve separately without silently coupling.
2640
2657
  const RESULT_ENVELOPE_SCHEMA_VERSION = 1;
2641
2658
 
2659
+ // The harness-protocol version this worker advertises at registration (issue
2660
+ // #272). nano-workforce (issue nanobpm/nano-workforce#802) grades a worker's
2661
+ // harness by this integer: a worker that advertises none is flagged "stale
2662
+ // harness" (and, under NANO_AGENTIC_STALE_HARNESS_POLICY=refuse, drained). It is
2663
+ // carried in the agentic presence REGISTER capability frame (the path this fleet
2664
+ // uses) so a freshly-registered worker reports `harnessStale: false` against a
2665
+ // default-configured nano-workforce (min protocol 1).
2666
+ //
2667
+ // SINGLE SOURCE OF TRUTH — bump this whenever the machine-readable-artifact
2668
+ // contract a downstream cockpit/app consumes changes: AgentInstance minting
2669
+ // (agent-instance.mjs), transcript flush, the result envelope
2670
+ // (RESULT_ENVELOPE_SCHEMA_VERSION / buildResultEnvelope), or the reserved
2671
+ // `worldMarker` completion variable.
2672
+ const HARNESS_PROTOCOL_VERSION = 1;
2673
+
2674
+ // The presence attributes a worker announces on the agentic `register`
2675
+ // (ENROLMENT attributes, not routing tokens — jobKeys are carried by the
2676
+ // explicit claim/release ownership frames the dispatch lifecycle emits, never
2677
+ // smuggled in here). Extracted as a pure builder so the *actual* advertised
2678
+ // capability — the value `workAgent` hands to `supervisor.ownership.register` —
2679
+ // is directly testable (issue #272): the tests pin `harnessProtocol` to the
2680
+ // single-source-of-truth constant here, so a dropped/misspelled production
2681
+ // assignment fails a test rather than silently regressing.
2682
+ function buildAgenticCapability(profile, host = hostname()) {
2683
+ return {
2684
+ cognition: profile.rank,
2685
+ family: profile.model || undefined,
2686
+ host,
2687
+ // Advertise the harness-protocol version (issue #272) so nano-workforce
2688
+ // (#802) does not flag this worker "stale harness". Absent => stale; min
2689
+ // configurable via NANO_AGENTIC_MIN_HARNESS_PROTOCOL (default 1).
2690
+ harnessProtocol: HARNESS_PROTOCOL_VERSION,
2691
+ };
2692
+ }
2693
+
2642
2694
  // Structured result channel (agent → harness). A coding CLI streams a lot of
2643
2695
  // noisy prose/tool output on stdout, so scraping it for the job's structured
2644
2696
  // result is fragile. Instead the harness hands the agent a private file path in
@@ -2764,6 +2816,41 @@ function hasEffectiveResultVars(obj) {
2764
2816
  return false;
2765
2817
  }
2766
2818
 
2819
+ // Remove from `stdout` only the result markers that carry NO effective vars — a
2820
+ // `::nano:result:: {…}` sentinel, or a fenced JSON block, whose parsed object is
2821
+ // empty / reserved-keys-only / null-valued (so `hasEffectiveResultVars` is false).
2822
+ // A marker that DID carry effective vars, and every other line of ordinary prose,
2823
+ // is left intact. Used by the empty-job detector so that a run whose sole stdout
2824
+ // is a value-less result sentinel/fence is treated as producing no work (issue
2825
+ // #275, thread 4118471796) while substantive stdout still counts as evidence.
2826
+ //
2827
+ // Only the marker itself is stripped, NOT the whole line: a sentinel can share a
2828
+ // line with substantive prose (`work done ::nano:result:: {}`), and dropping the
2829
+ // entire line would mis-classify that run as a husk even though the harness
2830
+ // produced real output (thread 4118560562). The sentinel runs to end-of-line, so
2831
+ // we cut from the sentinel start to EOL and keep the prefix (trimmed); a line
2832
+ // that is ONLY the sentinel reduces to '' and is dropped.
2833
+ function stdoutStrippedOfEmptyResult(stdout) {
2834
+ if (typeof stdout !== 'string' || stdout === '') return '';
2835
+ const keptLines = stdout.split(/\r?\n/).map((line) => {
2836
+ const idx = line.indexOf(RESULT_SENTINEL);
2837
+ if (idx === -1) return line;
2838
+ const obj = parseAgentResultObject(line.slice(idx + RESULT_SENTINEL.length).trim());
2839
+ // Strip the sentinel only when it parsed to a value-less result object; keep
2840
+ // an unparseable sentinel (it isn't a recognised result) or one that carried
2841
+ // real vars. Preserve any substantive text BEFORE the sentinel on the same
2842
+ // line (thread 4118560562) rather than dropping the whole line.
2843
+ if (obj && !hasEffectiveResultVars(obj)) return line.slice(0, idx).replace(/\s+$/, '');
2844
+ return line;
2845
+ });
2846
+ return keptLines
2847
+ .join('\n')
2848
+ .replace(/```[^\n]*\r?\n([\s\S]*?)```/g, (whole, inner) => {
2849
+ const obj = parseAgentResultObject(inner.trim());
2850
+ return obj && !hasEffectiveResultVars(obj) ? '' : whole;
2851
+ });
2852
+ }
2853
+
2767
2854
  // Choose the agent's structured result from its candidate sources (result file,
2768
2855
  // stdout sentinel, ACP outcome) in priority order. Prefer the first candidate
2769
2856
  // that carries at least one EFFECTIVE var (i.e. survives sanitizeResultVars —
@@ -2789,6 +2876,103 @@ function pickAgentResult(...thunks) {
2789
2876
  return firstPresent ?? null;
2790
2877
  }
2791
2878
 
2879
+ // Issue #275 (1): the empty-job detector. A harness run that exits 0 yet produced
2880
+ // NOTHING — no result vars, no output, no commits, no push — did no work (the
2881
+ // canonical case: a protocol-mismatched harness, e.g. an ACP-mode binary fed a
2882
+ // pipe payload, rejects stdin and exits 0 empty). COMPLETING such a job silently
2883
+ // drops whatever the job carried (an escalation answer, a review verdict) because
2884
+ // downstream gateways see no status and fall through to their default — so the
2885
+ // worker FAILS the job instead, preserving retries so it reactivates (ideally on
2886
+ // a healthy worker) and surfaces as an incident.
2887
+ //
2888
+ // `hasTurns`/`hasPlan` attest the harness genuinely engaged (a real ACP session
2889
+ // emitted updates / a plan); `hasOutcome` attests the agent reported an explicit
2890
+ // ACP `_meta.outcome`. Any one of these means the run was real work, not a husk.
2891
+ // A non-empty `stderr` is deliberately NOT a work signal: the canonical husk (a
2892
+ // protocol-mismatched harness fed a pipe payload) prints an ACP parse error to
2893
+ // stderr while producing nothing on stdout/result vars/transcript/git, so treating
2894
+ // stderr diagnostics as evidence of work would let exactly the run this detector
2895
+ // exists to catch slip through. Only a POSITIVE stdout/result/ACP/git signal counts.
2896
+ //
2897
+ // stdout counts as a work signal only when it carries SUBSTANTIVE content. A run
2898
+ // whose ONLY stdout is an empty/reserved/null-valued result sentinel or fence
2899
+ // (`::nano:result:: {}`, a `{}`/reserved-keys-only/null-valued JSON fence) did no
2900
+ // work: `parseResultFromStdout` accepts it but it yields no EFFECTIVE vars, so the
2901
+ // job would otherwise be COMPLETED with no usable result — the husk this detector
2902
+ // exists to catch (thread 4118471796). `stdoutStrippedOfEmptyResult` removes only
2903
+ // those value-less result markers; any other prose survives and still attests work.
2904
+ // Pure + exported for tests; the caller folds the result into the settle path.
2905
+ function detectEmptyAgentJob({ resultVars, stdout, gitResult, hasTurns, hasPlan, hasOutcome, transcriptFloorOnly } = {}) {
2906
+ if (hasEffectiveResultVars(resultVars)) return null;
2907
+ // A synthetic ACP transcript FLOOR (see `maybeEmitTranscriptFloor`) is captured
2908
+ // into stdout even when the harness produced no real work, so when the returned
2909
+ // stdout is ONLY that floor it is NOT evidence of agent work — skip the stdout
2910
+ // check so a no-op ACP husk is still detected as empty (thread 4118913047).
2911
+ if (transcriptFloorOnly !== true && typeof stdout === 'string' && stdoutStrippedOfEmptyResult(stdout).trim() !== '') return null;
2912
+ if (hasTurns === true || hasPlan === true || hasOutcome === true) return null;
2913
+ if ((gitResult?.commits?.length ?? 0) > 0) return null;
2914
+ if (gitResult?.pushed === true) return null;
2915
+ return {
2916
+ reason:
2917
+ 'agent exited 0 but produced nothing — no result vars, no output, no transcript turns, ' +
2918
+ 'no commits and no push. This is the signature of a protocol-mismatched or no-op harness ' +
2919
+ '(e.g. an ACP-mode binary driven over protocol "pipe"): completing the job would silently ' +
2920
+ 'drop what it carried, so it is failed (retries preserved) instead of completed.',
2921
+ };
2922
+ }
2923
+
2924
+ // Issue #275 (2): command ↔ protocol consistency. The incident behind #275 was a
2925
+ // hire whose command ran the harness in ACP mode (`nano-coder --acp`) while the
2926
+ // profile protocol stayed `pipe`, so the worker piped plain JSON to an
2927
+ // ACP-speaking binary that rejected it and exited 0 empty. Detect the mismatch
2928
+ // from the command line itself:
2929
+ // - `protocol: pipe` (or anything else) while the command line carries an ACP
2930
+ // selector (`--acp` / `acp` subcommand / `*-acp` adapter binary) → the
2931
+ // harness will speak JSON-RPC while the worker pipes plain JSON. Refused.
2932
+ // - `protocol: acp` with no ACP selector on the line is NOT an error:
2933
+ // `ensureAcpFlag` appends `--acp` at spawn time, so that shape is supported.
2934
+ // The selector scan reuses ensureAcpFlag's contract: a line where ensureAcpFlag
2935
+ // returns the line UNCHANGED already carries a selector. A shell wrapper hides
2936
+ // the selector inside its `-c` script (which the pipe executor runs through a
2937
+ // shell), so descend into that script too (bounded recursion). Pure + exported.
2938
+ function commandLineHasAcpSelector(commandLine, depth = 0) {
2939
+ if (typeof commandLine !== 'string' || commandLine.trim() === '') return false;
2940
+ if (ensureAcpFlag(commandLine) === commandLine) return true;
2941
+ if (depth >= 4) return false; // bound recursion against pathological nesting
2942
+ const script = shellWrappedScript(commandLine);
2943
+ return script != null && commandLineHasAcpSelector(script, depth + 1);
2944
+ }
2945
+
2946
+ function detectProtocolMismatch({ command, args = [], protocol } = {}) {
2947
+ const line = buildAgentCommandLine(String(command || ''), Array.isArray(args) ? args : []);
2948
+ if (!line.trim()) return null;
2949
+ const proto = String(protocol || 'pipe').trim().toLowerCase();
2950
+ if (proto !== 'acp' && commandLineHasAcpSelector(line)) {
2951
+ return {
2952
+ reason:
2953
+ `command "${line}" selects ACP mode (an --acp/acp token or a *-acp adapter binary) but ` +
2954
+ `protocol is "${proto}" — the worker would pipe plain JSON to an ACP-speaking harness that ` +
2955
+ 'rejects it and exits 0 empty, silently completing jobs with no work done (issue #275). ' +
2956
+ 'Re-hire with --protocol acp (or drop the ACP selector from the command).',
2957
+ };
2958
+ }
2959
+ return null;
2960
+ }
2961
+
2962
+ // The transport protocol a worker will ACTUALLY use, which is what the startup
2963
+ // command↔protocol mismatch check must be evaluated against (issue #275
2964
+ // follow-up). A container sandbox runs the harness over the pipe path today
2965
+ // REGARDLESS of the declared `protocol` (runAgentJob's `void protocol`), so its
2966
+ // effective protocol is always `pipe` — an ACP selector baked into a container
2967
+ // profile's command (`command: nano-coder --acp`, `protocol: acp`) would still
2968
+ // feed plain JSON to an ACP-speaking harness (the same empty-husk mismatch),
2969
+ // which the host-only `!isContainer` guard used to miss. Reducing the effective
2970
+ // protocol to `pipe` for containers makes detectProtocolMismatch flag exactly
2971
+ // that case while still passing a plain (non-ACP) container command.
2972
+ function effectiveHarnessProtocol(protocol, isContainer) {
2973
+ return isContainer ? 'pipe' : String(protocol || 'pipe').trim().toLowerCase();
2974
+ }
2975
+
2792
2976
  const SANDBOXES = ['none', 'docker', 'podman'];
2793
2977
  // Only container-based sandboxes need an image / disk hygiene / a runtime bin.
2794
2978
  const CONTAINER_SANDBOXES = new Set(['docker', 'podman']);
@@ -2896,7 +3080,7 @@ async function resolveAgentResultWithNudge({ result, resultFile, rerun, logger,
2896
3080
  // `truncated` flag consistent with it — echo the incoming `result.truncated`
2897
3081
  // rather than hardcoding false, so callers that trust the return value don't
2898
3082
  // see an already-truncated stdout reported as untruncated.
2899
- return { stdout: stdout0, nudged: false, truncated: result?.truncated === true, acpOutcome: result?.acpOutcome ?? null };
3083
+ return { stdout: stdout0, nudged: false, truncated: result?.truncated === true, acpOutcome: result?.acpOutcome ?? null, transcriptFloorOnly: result?.acpTranscriptFloorOnly === true };
2900
3084
  }
2901
3085
  let nudge = null;
2902
3086
  let nudgeError = null;
@@ -2931,7 +3115,13 @@ async function resolveAgentResultWithNudge({ result, resultFile, rerun, logger,
2931
3115
  // `workAgent` — otherwise the escalation and the recorded envelope outcome would
2932
3116
  // silently reflect only the first turn's outcome. Fall back to the first result's
2933
3117
  // outcome when the nudge reported none.
2934
- return { stdout, nudged: true, truncated, acpOutcome: nudge?.acpOutcome ?? result?.acpOutcome ?? null };
3118
+ // The combined stdout is FLOOR-ONLY only when both turns produced no real work:
3119
+ // the first turn was floor-only AND the nudge added nothing real (no output, or
3120
+ // its own turn was floor-only). Any real nudge output makes the stdout genuine
3121
+ // agent work (thread 4118913047).
3122
+ const transcriptFloorOnly = result?.acpTranscriptFloorOnly === true
3123
+ && (!nudgeOut.trim() || nudge?.acpTranscriptFloorOnly === true);
3124
+ return { stdout, nudged: true, truncated, acpOutcome: nudge?.acpOutcome ?? result?.acpOutcome ?? null, transcriptFloorOnly };
2935
3125
  }
2936
3126
 
2937
3127
  function coerceBool(v, dflt = false) {
@@ -7049,6 +7239,105 @@ function spawnCapturePty({ command, args = [], cwd, env, stdinData, timeoutMs, i
7049
7239
  });
7050
7240
  }
7051
7241
 
7242
+ // Split a shell command line into WORDS. A shell WORD is a contiguous run of
7243
+ // quoted and/or unquoted segments with no whitespace between them (so `FOO='a b'`
7244
+ // is ONE word), which is why a naive `\S+` split is wrong. Returns each word with
7245
+ // its shell quoting stripped (POSIX single-quotes AND double-quotes). Shared by
7246
+ // ensureAcpFlag (via unquoteShellWord) and the shell-wrapper descent below.
7247
+ function unquoteShellWord(tok) {
7248
+ let out = '';
7249
+ const seg = /'((?:[^']|'\\'')*)'|"((?:[^"\\]|\\.)*)"|([^\s'"]+)/g;
7250
+ let m;
7251
+ while ((m = seg.exec(tok)) !== null) {
7252
+ if (m[1] !== undefined) out += m[1].replace(/'\\''/g, "'");
7253
+ else if (m[2] !== undefined) out += m[2].replace(/\\(["\\$`])/g, '$1');
7254
+ else out += m[3];
7255
+ }
7256
+ return out;
7257
+ }
7258
+ function tokenizeShellWords(commandLine) {
7259
+ const words = commandLine.match(/(?:'(?:[^']|'\\'')*'|"(?:[^"\\]|\\.)*"|[^\s'"]+)+/g) || [];
7260
+ return words.map(unquoteShellWord);
7261
+ }
7262
+
7263
+ // A shell wrapper runs its `-c <script>` argument through a shell, so an ACP
7264
+ // selector INSIDE that script is live even though the top-level tokenizer sees
7265
+ // only the wrapper (`sh -c 'nano-coder --acp'`). Return the inner <script> so the
7266
+ // selector scan can descend into what the wrapper actually launches; null when the
7267
+ // line is not a recognised `<shell> [-opts] -c <script>` wrapper (thread 4118471822).
7268
+ //
7269
+ // The shell need not be word 0: a profile may prefix it with a run of environment
7270
+ // assignments (`FOO=1 sh -c …`) or an `env` wrapper (`env FOO=1 sh -c …`,
7271
+ // `env -i sh -c …`). Skip that leading prefix — assignments, the `env` command and
7272
+ // its options/assignments — so the shell lookup lands on the real shell token
7273
+ // (thread 4118560608). Mirrors the leading-assignment skip in ensureAcpFlag.
7274
+ const WRAPPER_SHELL_BASENAMES = new Set(['sh', 'bash', 'dash', 'zsh', 'ash', 'ksh']);
7275
+ // A leading `NAME=value` environment assignment (POSIX name, `=` present).
7276
+ const ENV_ASSIGNMENT_RE = /^[A-Za-z_][A-Za-z0-9_]*=/;
7277
+ // The shell-word tokenizer regex (a run of quoted/unquoted segments with no
7278
+ // whitespace between them). Shared so both the read (`shellWrappedScript`) and
7279
+ // the rewrite (`ensureAcpFlag`'s wrapper injection) tokenize identically.
7280
+ const SHELL_WORD_RE = /(?:'(?:[^']|'\\'')*'|"(?:[^"\\]|\\.)*"|[^\s'"]+)+/g;
7281
+ // Locate the `-c <script>` payload of a shell wrapper. Returns the RAW tokens
7282
+ // (quoting preserved) and the index of the `<script>` token — or null when the
7283
+ // line is not a recognised `<prefix> <shell> [-opts] -c <script>` wrapper. The
7284
+ // prefix-skip (leading `NAME=value` assignments / an `env` wrapper) and the
7285
+ // shell/`-c` detection live here ONCE, shared by `shellWrappedScript` (which
7286
+ // just reads the inner script) and `ensureAcpFlag` (which rewrites it to inject
7287
+ // the ACP flag INSIDE the script) so the two can never drift.
7288
+ // Skip a leading `NAME=value` env-assignment run and an optional `env` wrapper
7289
+ // (`env` itself, its options `-i`/`--null`/`-u NAME`/bare `-`, and any
7290
+ // assignments it carries) to reach the index of the REAL command token. Shared
7291
+ // by `locateShellWrapperScript` (to find the wrapping shell past the prefix) and
7292
+ // `ensureAcpFlag` (to find the command token for the `*-acp` adapter check) so an
7293
+ // `env`-wrapped adapter (`env claude-agent-acp`, `env FOO=1 claude-agent-acp`) is
7294
+ // unwrapped identically on both paths — otherwise the adapter check treats `env`
7295
+ // as the executable and misses the selector (thread 4118839851).
7296
+ function commandStartIndex(tokens) {
7297
+ let i = 0;
7298
+ // Skip a leading run of `NAME=value` assignments (`FOO=1 sh -c …`).
7299
+ while (i < tokens.length && ENV_ASSIGNMENT_RE.test(unquoteShellWord(tokens[i]))) i++;
7300
+ // Skip an `env` wrapper: `env` itself, its options (`-i`, `-u NAME`, `--null`),
7301
+ // and any `NAME=value` assignments it carries, up to the command it runs.
7302
+ if (i < tokens.length && unquoteShellWord(tokens[i]).replace(/^.*[\\/]/, '') === 'env') {
7303
+ i++;
7304
+ while (i < tokens.length) {
7305
+ const w = unquoteShellWord(tokens[i]);
7306
+ if (ENV_ASSIGNMENT_RE.test(w)) { i++; continue; }
7307
+ // `env` options: a switch that is not yet the command. `-u`/`--unset` take a
7308
+ // NAME argument — skip it too. A bare `-` (env's "ignore rest") ends options.
7309
+ if (w === '-') { i++; break; }
7310
+ if (w.startsWith('-')) {
7311
+ if (w === '-u' || w === '--unset') { i += 2; continue; }
7312
+ i++;
7313
+ continue;
7314
+ }
7315
+ break; // first non-option, non-assignment word is the command env runs
7316
+ }
7317
+ }
7318
+ return i;
7319
+ }
7320
+ function locateShellWrapperScript(commandLine) {
7321
+ const tokens = String(commandLine).match(SHELL_WORD_RE) || [];
7322
+ if (tokens.length < 3) return null;
7323
+ const i = commandStartIndex(tokens);
7324
+ if (tokens.length - i < 3) return null;
7325
+ const base = unquoteShellWord(tokens[i]).replace(/^.*[\\/]/, '');
7326
+ if (!WRAPPER_SHELL_BASENAMES.has(base)) return null;
7327
+ for (let j = i + 1; j < tokens.length; j++) {
7328
+ const w = unquoteShellWord(tokens[j]);
7329
+ if (!w.startsWith('-')) return null; // reached the command/script without a -c
7330
+ // `-c` (possibly combined with other short opts, e.g. `-lc`, `-euxc`) takes
7331
+ // the NEXT word as the script to run.
7332
+ if (/^-[a-z]*c$/i.test(w)) return j + 1 < tokens.length ? { tokens, scriptIndex: j + 1 } : null;
7333
+ }
7334
+ return null;
7335
+ }
7336
+ function shellWrappedScript(commandLine) {
7337
+ const loc = locateShellWrapperScript(commandLine);
7338
+ return loc ? unquoteShellWord(loc.tokens[loc.scriptIndex]) : null;
7339
+ }
7340
+
7052
7341
  // ---- ACP capture (C3 #110 — the third harness path, "minimal mode") ---------
7053
7342
  // Some ACP agents are native (`copilot --acp`, `qwen --experimental-acp`,
7054
7343
  // `opencode acp`), some ride an adapter (`claude-code-acp`, `pi-acp`). In every
@@ -7057,20 +7346,44 @@ function spawnCapturePty({ command, args = [], cwd, env, stdinData, timeoutMs, i
7057
7346
  // select ACP, so a native/adapter invocation is never doubled. This mirrors how
7058
7347
  // the pipe path spawns the line under a shell.
7059
7348
  function ensureAcpFlag(commandLine) {
7060
- // Detection must survive buildAgentCommandLine()'s POSIX single-quoting: a
7061
- // structured `--arg acp` (or `--arg --acp`) lands here as the quoted token
7062
- // 'acp' / '--acp', so a naive `\bacp\b` on the raw line would miss it and
7063
- // wrongly append a second --acp. Tokenise the line, strip the shell quoting
7064
- // (both POSIX single-quotes from buildAgentCommandLine() AND double-quotes a
7065
- // legacy `profile.command` may bake in, e.g. `copilot "--acp"`), and match:
7349
+ // A shell wrapper runs the harness INSIDE its `-c <script>`. Tokens AFTER the
7350
+ // script are the shell's positional params ($0, $1, …), NOT arguments to the
7351
+ // wrapped command, and the shell's own options come BEFORE the script — so an
7352
+ // ACP selector is only meaningful INSIDE the script. Handle the wrapper FIRST,
7353
+ // before the outer-token scan, so a trailing `--acp` that is really the `-c`
7354
+ // script's `$0` (`sh -c 'copilot' --acp`) is NOT mistaken for a live selector
7355
+ // (which would leave the harness in pipe mode while an ACP worker sends it ACP
7356
+ // frames, and falsely pass `protocol: pipe` validation — thread 4118839872).
7357
+ // Recurse into the script: a selector already present leaves it unchanged;
7358
+ // otherwise inject `--acp` INTO the script (so it reaches the harness, not the
7359
+ // outer `$0`), rebuilding the `-c` argument. The inner script shrinks each
7360
+ // level, so the mutual recursion with `locateShellWrapperScript` terminates.
7361
+ const wrapperLoc = locateShellWrapperScript(commandLine);
7362
+ if (wrapperLoc) {
7363
+ const inner = unquoteShellWord(wrapperLoc.tokens[wrapperLoc.scriptIndex]);
7364
+ const ensuredInner = ensureAcpFlag(inner);
7365
+ if (ensuredInner === inner) return commandLine; // ACP already selected inside
7366
+ const rebuilt = wrapperLoc.tokens.slice();
7367
+ // Re-quote the rewritten script as one POSIX literal so it survives the
7368
+ // shell as a single `-c` argument; other tokens keep their original quoting.
7369
+ rebuilt[wrapperLoc.scriptIndex] = shQuote(ensuredInner);
7370
+ return rebuilt.join(' ');
7371
+ }
7372
+ // Not a shell wrapper. Detection must survive buildAgentCommandLine()'s POSIX
7373
+ // single-quoting: a structured `--arg acp` (or `--arg --acp`) lands here as the
7374
+ // quoted token 'acp' / '--acp', so a naive `\bacp\b` on the raw line would miss
7375
+ // it and wrongly append a second --acp. Tokenise the line, strip the shell
7376
+ // quoting (both POSIX single-quotes from buildAgentCommandLine() AND
7377
+ // double-quotes a legacy `profile.command` may bake in, e.g. `copilot "--acp"`),
7378
+ // and match:
7066
7379
  // - a native ACP selector `acp`/`-acp`/`--acp` (subcommand or switch) as a
7067
7380
  // WHOLE token, in ANY position (it may be the command or an argument), or
7068
7381
  // - an adapter command whose basename ends in `-acp` (claude-agent-acp,
7069
7382
  // pi-acp) — but ONLY the command token (the first token past any leading
7070
- // env-assignment prefix, see commandIndex below), since an *argument*
7071
- // that merely ends in `-acp` (e.g. `--model foo-acp`) is not an ACP
7072
- // selector. Matching whole tokens/basenames (not a substring) also avoids
7073
- // the false positive of a path that merely contains `/acp/`.
7383
+ // env-assignment / `env`-wrapper prefix, see commandIndex below), since an
7384
+ // *argument* that merely ends in `-acp` (e.g. `--model foo-acp`) is not an
7385
+ // ACP selector. Matching whole tokens/basenames (not a substring) also
7386
+ // avoids the false positive of a path that merely contains `/acp/`.
7074
7387
  // A shell WORD is a contiguous run of quoted and/or unquoted segments with no
7075
7388
  // whitespace between them, so a `\S+` token boundary is wrong: an env prefix
7076
7389
  // whose value is quoted and contains spaces (e.g. `FOO='a b' claude-code-acp`)
@@ -7080,28 +7393,15 @@ function ensureAcpFlag(commandLine) {
7080
7393
  const tokens = commandLine.match(/(?:'(?:[^']|'\\'')*'|"(?:[^"\\]|\\.)*"|[^\s'"]+)+/g) || [];
7081
7394
  // Strip shell quoting across ALL of a word's segments (a word may mix quoted
7082
7395
  // and unquoted runs, e.g. `FOO='a b'`), yielding the logical value.
7083
- const unquote = (tok) => {
7084
- let out = '';
7085
- const seg = /'((?:[^']|'\\'')*)'|"((?:[^"\\]|\\.)*)"|([^\s'"]+)/g;
7086
- let m;
7087
- while ((m = seg.exec(tok)) !== null) {
7088
- if (m[1] !== undefined) out += m[1].replace(/'\\''/g, "'");
7089
- else if (m[2] !== undefined) out += m[2].replace(/\\(["\\$`])/g, '$1');
7090
- else out += m[3];
7091
- }
7092
- return out;
7093
- };
7396
+ const unquote = unquoteShellWord;
7094
7397
  // The `*-acp` adapter suffix identifies the COMMAND token, but the command is
7095
7398
  // not always token 0: a shell command line may be prefixed with a contiguous
7096
7399
  // run of env assignments (`NAME=value`, e.g. the `ACP=true` in
7097
- // `ACP=true claude-code-acp`). Skip that leading assignment prefix so the
7098
- // adapter check lands on the real command token. Only a *leading* run counts —
7099
- // once a real command token appears, later `FOO=bar` tokens are arguments.
7100
- let commandIndex = 0;
7101
- while (commandIndex < tokens.length &&
7102
- /^[A-Za-z_][A-Za-z0-9_]*=/.test(unquote(tokens[commandIndex]))) {
7103
- commandIndex++;
7104
- }
7400
+ // `ACP=true claude-code-acp`) and/or an `env` wrapper (`env claude-agent-acp`).
7401
+ // Skip that leading prefix so the adapter check lands on the real command token
7402
+ // (thread 4118839851). Only a *leading* prefix counts — once a real command
7403
+ // token appears, later `FOO=bar` tokens are arguments.
7404
+ const commandIndex = commandStartIndex(tokens);
7105
7405
  for (let i = 0; i < tokens.length; i++) {
7106
7406
  let tok = unquote(tokens[i]);
7107
7407
  // Normalise a GNU-style `--opt=value` selector to its option-NAME part, so
@@ -7125,6 +7425,8 @@ function ensureAcpFlag(commandLine) {
7125
7425
  if (/^--?[a-z0-9][a-z0-9-]*-acp$/i.test(name)) return commandLine;
7126
7426
  if (i === commandIndex && /-acp$/i.test(base)) return commandLine;
7127
7427
  }
7428
+ // No ACP selector on the line. This is not a shell wrapper (those are handled
7429
+ // at the top), so the harness runs directly — append the default `--acp`.
7128
7430
  return `${commandLine} --acp`;
7129
7431
  }
7130
7432
 
@@ -7263,6 +7565,12 @@ function spawnCaptureAcp({ command, args = [], cwd, env, stdinData, timeoutMs, i
7263
7565
  // drill-in shows the outcome instead of nothing (see `maybeEmitTranscriptFloor`).
7264
7566
  let transcriptChunksPublished = 0;
7265
7567
  let floorEmitted = false;
7568
+ // #275: did the harness ever send a real `session/update`? The synthetic floor
7569
+ // is captured into stdout even when it did not, so the empty-job guard needs to
7570
+ // tell "stdout carries agent work" from "stdout is ONLY the synthetic floor"
7571
+ // (thread 4118913047). Any session/update — mapped chunk OR fallback text —
7572
+ // flips this; the floor never does.
7573
+ let sawRealTranscript = false;
7266
7574
 
7267
7575
  // Live "spy" tee (--stream), line-buffered, mirroring the other paths.
7268
7576
  // Separate line buffers per lane (stdout-human vs stderr) so a partial line
@@ -7344,7 +7652,14 @@ function spawnCaptureAcp({ command, args = [], cwd, env, stdinData, timeoutMs, i
7344
7652
  if (teeSink) { tee('', true); teeErr('', true); }
7345
7653
  // Reap the child if it is still alive (turn resolved but agent lingering).
7346
7654
  try { if (child && childClosed === null) killTree(child); } catch { /* best effort */ }
7347
- resolve(acpOutcome ? { ...result, acpOutcome } : result);
7655
+ // #275: flag when the ONLY captured stdout is the synthetic transcript floor
7656
+ // (the turn resolved but no real session/update ever arrived). The empty-job
7657
+ // guard reads this so a no-op ACP husk is not made to look non-empty by its own
7658
+ // floor (thread 4118913047).
7659
+ const floorOnly = floorEmitted && !sawRealTranscript;
7660
+ let resolved = acpOutcome ? { ...result, acpOutcome } : result;
7661
+ if (floorOnly) resolved = { ...resolved, acpTranscriptFloorOnly: true };
7662
+ resolve(resolved);
7348
7663
  };
7349
7664
 
7350
7665
  // --- JSON-RPC 2.0 plumbing (newline-delimited framing) -------------------
@@ -7473,6 +7788,9 @@ function spawnCaptureAcp({ command, args = [], cwd, env, stdinData, timeoutMs, i
7473
7788
  // the update has no canonical mapping OR the relay exposes no transcript seam,
7474
7789
  // so nothing is ever dropped (no regression vs minimal mode).
7475
7790
  const emitTranscript = (update) => {
7791
+ // A real `session/update` reached us — agent work, distinct from the synthetic
7792
+ // floor below (thread 4118913047).
7793
+ sawRealTranscript = true;
7476
7794
  const chunk = encodeTranscriptChunk(update);
7477
7795
  if (chunk && relayTap && typeof relayTap.relayTranscriptChunk === 'function') {
7478
7796
  // Only skip the text fallback when the chunk publish ACTUALLY succeeded.
@@ -9467,13 +9785,11 @@ async function workAgent(req, flags, ctx) {
9467
9785
 
9468
9786
  const stored = readHires()[name];
9469
9787
  if (!stored) {
9470
- logger.error(`No hire named "${name}". List profiles with: c8ctl nano hire --list`);
9471
- process.exit(1);
9788
+ exitConfigError(logger, `No hire named "${name}". List profiles with: c8ctl nano hire --list`);
9472
9789
  }
9473
9790
  const normalized = normalizeStoredProfile(name, stored);
9474
9791
  if (normalized.error) {
9475
- logger.error(`Cannot work "${name}": ${normalized.error}. Re-create it with: c8ctl nano hire`);
9476
- process.exit(1);
9792
+ exitConfigError(logger, `Cannot work "${name}": ${normalized.error}. Re-create it with: c8ctl nano hire`);
9477
9793
  }
9478
9794
  const profile = normalized.profile;
9479
9795
 
@@ -9485,8 +9801,7 @@ async function workAgent(req, flags, ctx) {
9485
9801
  // supervisor path); a non-blank one must be a safe worker-name token.
9486
9802
  const explicitName = flags?.name ? String(flags.name).trim() : '';
9487
9803
  if (explicitName !== '' && !isValidWorkerName(explicitName)) {
9488
- logger.error(`Invalid --name "${flags.name}": use only letters, digits, and . _ -`);
9489
- process.exit(1);
9804
+ exitConfigError(logger, `Invalid --name "${flags.name}": use only letters, digits, and . _ -`);
9490
9805
  }
9491
9806
  const workerName = explicitName !== '' ? explicitName : autoWorkerName(name);
9492
9807
 
@@ -9500,8 +9815,7 @@ async function workAgent(req, flags, ctx) {
9500
9815
  // config such as permission toggles (e.g. a coder CLI started with tools enabled).
9501
9816
  const { env: workEnv, errors: workEnvErrors } = parseEnvPairs(flags?.env);
9502
9817
  if (workEnvErrors.length > 0) {
9503
- logger.error(workEnvErrors.join('; '));
9504
- process.exit(1);
9818
+ exitConfigError(logger, workEnvErrors.join('; '));
9505
9819
  }
9506
9820
  const profileEnv = { ...profile.env, ...workEnv };
9507
9821
 
@@ -10069,12 +10383,9 @@ async function workAgent(req, flags, ctx) {
10069
10383
  // The presence attributes this worker announces on `register` (ENROLMENT
10070
10384
  // attributes, not routing tokens — jobKeys are carried by the explicit
10071
10385
  // claim/release ownership frames the dispatch lifecycle emits, never smuggled in
10072
- // here). Reused for the initial seed and any resync.
10073
- const agenticCapability = {
10074
- cognition: profile.rank,
10075
- family: profile.model || undefined,
10076
- host: hostname(),
10077
- };
10386
+ // here). Reused for the initial seed and any resync. Built by the exported
10387
+ // `buildAgenticCapability` so the advertised value is directly under test.
10388
+ const agenticCapability = buildAgenticCapability(profile);
10078
10389
  // Maintain `activeJobs` unconditionally: it feeds the supervisor activity file
10079
10390
  // (gated inside writeActivity) so a standalone worker still reports its current
10080
10391
  // jobs. Live presence/ownership jobKeys are now owned by the runtime — the
@@ -10343,6 +10654,27 @@ async function workAgent(req, flags, ctx) {
10343
10654
  const envPermission = (process.env.NANO_AGENTIC_PERMISSION || '').trim().toLowerCase();
10344
10655
  const rolePermission = resolveAgenticSetting(envPermission, profile.permission, PERMISSION_MODES, 'yolo');
10345
10656
 
10657
+ // Issue #275 (2): refuse to poll with a command/protocol mismatch. A hire
10658
+ // predating the hire-time refusal (or one hand-edited into config.json) can
10659
+ // still pair an ACP-mode command (`--acp`) with a transport that pipes plain
10660
+ // JSON; starting the worker would let it silently complete every job it takes
10661
+ // with no work done. Checked against the EFFECTIVE protocol (env override
10662
+ // included) and the full effective args (profile --arg + work-time --arg),
10663
+ // before any polling begins. Container sandboxes run pipe-only today regardless
10664
+ // of `protocol` (runAgentJob's `void protocol`), so an ACP selector baked into a
10665
+ // container profile's command STILL pipes plain JSON to an ACP harness — the
10666
+ // same husk. `effectiveHarnessProtocol` reduces a container's protocol to `pipe`
10667
+ // so the refusal covers that pipe-only executor too, not just the host (thread
10668
+ // 4118327651).
10669
+ const effectiveProtocol = effectiveHarnessProtocol(roleProtocol, isContainer);
10670
+ const startupMismatch = detectProtocolMismatch({ command: profile.command, args: effectiveArgs, protocol: effectiveProtocol });
10671
+ if (startupMismatch) {
10672
+ // Non-restartable config failure: under the supervisor this must exit with
10673
+ // NANO_EXIT_CONFIG so the daemon stops retrying instead of restart-looping the
10674
+ // same refusal (thread 4118560521).
10675
+ exitConfigError(logger, `Cannot work "${name}": ${startupMismatch.reason}`);
10676
+ }
10677
+
10346
10678
  // The agent job runner (issue #172 hot-path flip). The single-owner supervisor
10347
10679
  // runtime dispatches each activated job to this `run(job)`; it executes the
10348
10680
  // harness exactly as the retired per-type SDK jobHandler did, but SETTLES via the
@@ -10964,7 +11296,7 @@ async function workAgent(req, flags, ctx) {
10964
11296
  // the result is recoverable only via the stdout `::nano:result::`
10965
11297
  // sentinel, which `resolveAgentResultWithNudge` handles directly.
10966
11298
  if (result.ok) {
10967
- const { stdout, nudged, truncated, acpOutcome } = await resolveAgentResultWithNudge({
11299
+ const { stdout, nudged, truncated, acpOutcome, transcriptFloorOnly } = await resolveAgentResultWithNudge({
10968
11300
  result,
10969
11301
  resultFile,
10970
11302
  logger,
@@ -10986,6 +11318,10 @@ async function workAgent(req, flags, ctx) {
10986
11318
  }),
10987
11319
  });
10988
11320
  result.stdout = stdout;
11321
+ // Recompute the floor-only signal over the COMBINED (first + nudge) stdout
11322
+ // so a nudge that added real output is no longer classed floor-only, and a
11323
+ // still-empty husk stays floor-only for the guard (thread 4118913047).
11324
+ result.acpTranscriptFloorOnly = transcriptFloorOnly;
10989
11325
  if (nudged) {
10990
11326
  result.nudgedForResult = true;
10991
11327
  if (truncated) result.truncated = true;
@@ -10995,12 +11331,26 @@ async function workAgent(req, flags, ctx) {
10995
11331
  }
10996
11332
  }
10997
11333
 
10998
- // #194: end the AgentInstance lifecycle. Flush any pending turn and drain
10999
- // the append queue, then drive the instance to COMPLETED on a successful
11000
- // job end (a failed run leaves it non-terminal so a retry/reactivation
11001
- // continues the same instance). Best-effort — never disturbs job settlement.
11334
+ // #194 + #275: flush any pending turn and DRAIN the append queue now, so
11335
+ // the `appendedTurns`/`sawPlan` signals the empty-job guard reads below
11336
+ // reflect a trailing coalesced message — but DEFER the terminal COMPLETED
11337
+ // transition until AFTER that guard has run. Driving the instance to
11338
+ // COMPLETED here on `result.ok === true` would terminalize an empty husk
11339
+ // (which the guard is about to FAIL, retries preserved) before the guard
11340
+ // ever sees it: the instance would be stranded COMPLETED, a retry could no
11341
+ // longer continue the same non-terminal instance, and the terminal update
11342
+ // could hit the same 422 (thread 4118327671). `drain()` transitions no
11343
+ // status. Best-effort — never disturbs job settlement. BOUNDED (drainBounded):
11344
+ // the public `drain()` awaits the ENTIRE serialized append queue, so a large ACP
11345
+ // transcript or an AgentHistory outage could otherwise hold the job here — past
11346
+ // the broker lease — before settleJob.fail/complete ever runs, preventing the
11347
+ // empty-job guard from settling at all. A bounded-out drain leaves appends still
11348
+ // in flight (they keep draining in the background); that is itself transcript
11349
+ // evidence — turns were produced but not yet confirmed — which the guard below
11350
+ // treats as non-empty via `preGuardDrainTimedOut` (thread 4118913008).
11351
+ let preGuardDrainTimedOut = false;
11002
11352
  if (agentInstanceProducer) {
11003
- try { await agentInstanceProducer.complete(result.ok); } catch (err) { logger.warn(`[${jobType}] AgentInstance producer complete() threw (${aiCorr}) — ${oneLineLog(err?.message || err)}; job settlement unaffected.`); }
11353
+ try { preGuardDrainTimedOut = (await agentInstanceProducer.drainBounded()) === false; } catch (err) { logger.warn(`[${jobType}] AgentInstance producer drainBounded() threw (${aiCorr}) — ${oneLineLog(err?.message || err)}; job settlement unaffected.`); }
11004
11354
  }
11005
11355
 
11006
11356
  // #264: the run is done — take a FINAL snapshot (so edits still pending in
@@ -11254,6 +11604,52 @@ async function workAgent(req, flags, ctx) {
11254
11604
  const resultKeys = Object.keys(resultVars);
11255
11605
  if (resultKeys.length === 0) logger.warn(`[${jobType}] job ${job.jobKey}: agent returned no usable result vars — write a JSON object of result variables to $AGENT_RESULT_FILE (or print a "${RESULT_SENTINEL} {…}" line) so downstream gateways see status/summary/etc.`);
11256
11606
  else logger.info(`[${jobType}] job ${job.jobKey}: merged agent result vars [${resultKeys.join(', ')}]`);
11607
+
11608
+ // Issue #275 (1): FAIL an empty job instead of completing it. A run
11609
+ // that exited 0 with no result vars, no output, no transcript turns,
11610
+ // no commits and no push did no work (the canonical case is a
11611
+ // protocol-mismatched harness — an ACP-mode binary fed a pipe payload
11612
+ // rejects stdin and exits 0 empty). Completing it silently drops
11613
+ // whatever the job carried (an escalation answer, a review verdict),
11614
+ // so fail it here: retries are preserved, the job reactivates (on a
11615
+ // healthy worker), and it surfaces as an incident. A run with ANY
11616
+ // evidence of real work (output, ACP turns, a plan, an outcome,
11617
+ // commits, a push) is NOT empty and completes as before.
11618
+ const emptyJob = detectEmptyAgentJob({
11619
+ resultVars,
11620
+ stdout: result.stdout,
11621
+ gitResult,
11622
+ // A bounded pre-guard drain that timed out left appends in flight — turns
11623
+ // WERE produced (real activity), just not yet confirmed — so treat it as
11624
+ // transcript evidence (thread 4118913008).
11625
+ hasTurns: agentInstanceProducer?.appendedTurns > 0 || preGuardDrainTimedOut,
11626
+ hasPlan: agentInstanceProducer?.sawPlan === true,
11627
+ hasOutcome: result.acpOutcome != null,
11628
+ // The ACP path synthesises a transcript FLOOR into stdout when the turn
11629
+ // resolved but no session/update arrived (`maybeEmitTranscriptFloor`). That
11630
+ // floor is NOT agent work, so a no-op ACP husk must not look non-empty on
11631
+ // the strength of its own synthetic floor (thread 4118913047).
11632
+ transcriptFloorOnly: result.acpTranscriptFloorOnly === true,
11633
+ });
11634
+ // #194 + #275: NOW terminalize the AgentInstance, keyed off REAL work — not
11635
+ // the bare exit code. A non-empty success drives COMPLETED; an empty husk
11636
+ // (about to be FAILED below with retries preserved) passes `false` so the
11637
+ // instance stays non-terminal and a retry/reactivation continues the SAME
11638
+ // instance rather than being stranded COMPLETED (thread 4118327671).
11639
+ // Best-effort — never disturbs job settlement.
11640
+ if (agentInstanceProducer) {
11641
+ try { await agentInstanceProducer.complete(!emptyJob); } catch (err) { logger.warn(`[${jobType}] AgentInstance producer complete() threw (${aiCorr}) — ${oneLineLog(err?.message || err)}; job settlement unaffected.`); }
11642
+ }
11643
+ if (emptyJob) {
11644
+ const retries = Math.max(0, (Number(job.retries) || 1) - 1);
11645
+ logger.error(`[${jobType}] job ${job.jobKey}: FAILING empty agent job — ${emptyJob.reason} (retries left ${retries})`);
11646
+ return await settleJob.fail({
11647
+ errorMessage: `agent "${profile.name}" produced an empty result: ${emptyJob.reason}`.slice(0, 2000),
11648
+ retries,
11649
+ variables: { [AGENT_RESULT_KEY]: resultEnvelope },
11650
+ });
11651
+ }
11652
+
11257
11653
  const settled = await settleJob.complete({
11258
11654
  ...resultVars,
11259
11655
  [AGENT_RESULT_KEY]: resultEnvelope,
@@ -11270,6 +11666,13 @@ async function workAgent(req, flags, ctx) {
11270
11666
  if (discardCheckpointOnAck) await checkpointing.discardAfterAck();
11271
11667
  return settled;
11272
11668
  }
11669
+ // #194: the run failed (non-zero exit / signal / harness error). Leave the
11670
+ // AgentInstance NON-terminal so a retry/reactivation continues the same
11671
+ // instance; complete(false) drains pending appends without a terminal
11672
+ // transition. Best-effort — never disturbs job settlement.
11673
+ if (agentInstanceProducer) {
11674
+ try { await agentInstanceProducer.complete(false); } catch (err) { logger.warn(`[${jobType}] AgentInstance producer complete() threw (${aiCorr}) — ${oneLineLog(err?.message || err)}; job settlement unaffected.`); }
11675
+ }
11273
11676
  const retries = Math.max(0, (Number(job.retries) || 1) - 1);
11274
11677
  const detail = result.error
11275
11678
  || (result.stderr || '').trim() + (result.stderrTruncated && (result.stderr || '').trim() ? ' [stderr truncated]' : '')
@@ -11613,6 +12016,21 @@ const SUPERVISOR_BACKOFF_MAX_MS = 30_000;
11613
12016
  // A child that stayed up at least this long before exiting is not crash-looping,
11614
12017
  // so its restart backoff is reset to zero.
11615
12018
  const SUPERVISOR_HEALTHY_UPTIME_MS = 60_000;
12019
+ // sysexits.h EX_CONFIG: a worker that exits with this code refused to start on a
12020
+ // NON-RESTARTABLE configuration failure (a missing/invalid/hand-edited profile, a
12021
+ // command↔protocol mismatch, bad --env). Restarting it would re-hit the identical
12022
+ // refusal forever, re-allocating startup state and re-emitting the same error
12023
+ // (thread 4118560521) — so the supervisor's death handler treats this code as
12024
+ // terminal and does NOT schedule a restart, surfacing one actionable failure.
12025
+ const NANO_EXIT_CONFIG = 78;
12026
+ // Log `msg` and exit with NANO_EXIT_CONFIG (EX_CONFIG). Used for the non-restartable
12027
+ // configuration failures a worker can hit BEFORE it starts polling — under `nano
12028
+ // supervisor` a plain exit(1) is indistinguishable from a crash and the daemon would
12029
+ // restart-loop the same refusal forever (thread 4118560521). Pure-ish (exits).
12030
+ function exitConfigError(logger, msg) {
12031
+ logger.error(msg);
12032
+ process.exit(NANO_EXIT_CONFIG);
12033
+ }
11616
12034
  const SUPERVISOR_CONNECT_TIMEOUT_MS = 6_000;
11617
12035
  // End-to-end deadline for a single request: once connected, a wedged/incompatible
11618
12036
  // daemon that accepts but never sends a `final` frame must not hang the client.
@@ -12014,6 +12432,10 @@ function summarizeSupervisorWorker(w, now = Date.now()) {
12014
12432
  pid: alive ? w.pid : null,
12015
12433
  state: w.stopping ? 'stopping' : alive ? 'running' : 'down',
12016
12434
  restarts: Number(w.restarts) || 0,
12435
+ // True when the worker last exited with NANO_EXIT_CONFIG (a NON-RESTARTABLE
12436
+ // configuration failure) — the daemon left it down rather than restart-looping
12437
+ // (thread 4118560521). Surfaced so `supervisor status` shows WHY it is down.
12438
+ configFailed: w.configFailed === true,
12017
12439
  uptimeMs,
12018
12440
  startedAtMs,
12019
12441
  lastExit: w.lastExit ?? null,
@@ -12315,7 +12737,12 @@ function formatSupervisorStatus(status) {
12315
12737
  const rows = workers.map((w) => ({
12316
12738
  id: String(w.id),
12317
12739
  profile: String(w.profile),
12318
- state: String(w.state),
12740
+ // A worker the daemon left DOWN because it exited with NANO_EXIT_CONFIG (a
12741
+ // non-restartable configuration failure) is rendered `down (config)` so it is
12742
+ // visibly distinguishable from an ordinary down/crashed worker the daemon is
12743
+ // still restart-backing-off — thread 4118745101. The latch is cleared on any
12744
+ // fresh (re)start, so this only shows while the worker is genuinely down.
12745
+ state: String(w.state) === 'down' && w.configFailed === true ? 'down (config)' : String(w.state),
12319
12746
  engine: supervisorEngineCell(w),
12320
12747
  agentic: supervisorAgenticCell(w),
12321
12748
  job: supervisorJobCell(w),
@@ -12618,7 +13045,7 @@ async function runSupervisorDaemon() {
12618
13045
  workers: [...workers.values()].map((w) => ({
12619
13046
  id: w.id, profile: w.profile, args: w.args, pid: isPidAlive(w.pid) ? w.pid : null,
12620
13047
  startedAt: w.startedAt || null, restarts: w.restarts, lastExit: w.lastExit ?? null,
12621
- stopping: !!w.stopping, logFile: w.logFile,
13048
+ stopping: !!w.stopping, logFile: w.logFile, configFailed: w.configFailed === true,
12622
13049
  })),
12623
13050
  });
12624
13051
  } catch { /* best effort */ }
@@ -12640,6 +13067,10 @@ async function runSupervisorDaemon() {
12640
13067
  const workerLogMaxBytes = resolveLogMaxBytes(process.env.NANO_SUPERVISOR_LOG_MAX_BYTES);
12641
13068
 
12642
13069
  const startWorker = (w) => {
13070
+ // A fresh (re)start attempts the profile again, so clear any prior
13071
+ // non-restartable config-failure latch — the operator may have fixed the
13072
+ // profile since (thread 4118560521).
13073
+ w.configFailed = false;
12643
13074
  // With a cap we pipe stdout/stderr through the daemon so the ring can bound
12644
13075
  // them; unbounded (opt-out) keeps the legacy direct-fd append. `fd` is only
12645
13076
  // used on the direct-fd path.
@@ -12735,6 +13166,19 @@ async function runSupervisorDaemon() {
12735
13166
  return;
12736
13167
  }
12737
13168
  const delay = supervisorBackoffMs(w.restarts);
13169
+ // A worker that exited with NANO_EXIT_CONFIG refused to start on a
13170
+ // NON-RESTARTABLE configuration failure (bad/mismatched profile, bad --env).
13171
+ // Restarting re-hits the identical refusal forever, so surface ONE actionable
13172
+ // failure and leave the worker down instead of scheduling a restart
13173
+ // (thread 4118560521). The operator fixes the profile and re-adds/restarts.
13174
+ const exitCode = /^code (\d+)$/.exec(reason)?.[1];
13175
+ if (exitCode === String(NANO_EXIT_CONFIG)) {
13176
+ w.configFailed = true;
13177
+ dlog(`worker '${w.id}' refused to start (configuration failure, exit ${NANO_EXIT_CONFIG}); NOT restarting — fix the profile and restart it`);
13178
+ broadcast({ type: 'event', event: 'worker-config-error', worker: workerPublic(w) });
13179
+ persist();
13180
+ return;
13181
+ }
12738
13182
  w.restarts += 1;
12739
13183
  dlog(`worker '${w.id}' down (${reason}); restarting in ${delay}ms (restart #${w.restarts})`);
12740
13184
  broadcast({ type: 'event', event: 'worker-exit', worker: workerPublic(w), restartInMs: delay });
@@ -17249,6 +17693,7 @@ export {
17249
17693
  };
17250
17694
  export { compareSemver, githubRepoSlug, filterReleasesSince, renderReleaseBody };
17251
17695
  export { probeAgentCliVersion };
17696
+ export { HARNESS_PROTOCOL_VERSION, buildAgenticCapability };
17252
17697
  export {
17253
17698
  webConsoleUrl,
17254
17699
  consoleLinkLabel,
@@ -17288,6 +17733,12 @@ export {
17288
17733
  sanitizeResultVars,
17289
17734
  hasEffectiveResultVars,
17290
17735
  pickAgentResult,
17736
+ stdoutStrippedOfEmptyResult,
17737
+ detectEmptyAgentJob,
17738
+ detectProtocolMismatch,
17739
+ effectiveHarnessProtocol,
17740
+ commandLineHasAcpSelector,
17741
+ shellWrappedScript,
17291
17742
  buildResultNudgePrompt,
17292
17743
  resolveAgentResultWithNudge,
17293
17744
  parseEnvPairs,
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.0.23",
3
- "commit": "28273b3",
4
- "updated": "2026-09-26T21:03:43Z"
2
+ "version": "0.0.24",
3
+ "commit": "daa4cfd",
4
+ "updated": "2026-09-29T05:36:49Z"
5
5
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "c8ctl-plugin-nano",
3
- "version": "1.69.2",
3
+ "version": "1.69.4",
4
4
  "type": "module",
5
5
  "description": "c8ctl plugin to start, inspect, and stop a local Nano BPM (nanobpmn) cluster",
6
6
  "main": "c8ctl-plugin.js",
@@ -76,12 +76,12 @@
76
76
  },
77
77
  "optionalDependencies": {
78
78
  "node-pty": "^1.0.0",
79
- "@nanobpm/c8ctl-plugin-nano-darwin-arm64": "1.69.2",
80
- "@nanobpm/c8ctl-plugin-nano-darwin-x64": "1.69.2",
81
- "@nanobpm/c8ctl-plugin-nano-linux-x64": "1.69.2",
82
- "@nanobpm/c8ctl-plugin-nano-linux-arm64": "1.69.2",
83
- "@nanobpm/c8ctl-plugin-nano-linux-armv7": "1.69.2",
84
- "@nanobpm/c8ctl-plugin-nano-linux-armv6": "1.69.2",
85
- "@nanobpm/c8ctl-plugin-nano-win32-x64": "1.69.2"
79
+ "@nanobpm/c8ctl-plugin-nano-darwin-arm64": "1.69.4",
80
+ "@nanobpm/c8ctl-plugin-nano-darwin-x64": "1.69.4",
81
+ "@nanobpm/c8ctl-plugin-nano-linux-x64": "1.69.4",
82
+ "@nanobpm/c8ctl-plugin-nano-linux-arm64": "1.69.4",
83
+ "@nanobpm/c8ctl-plugin-nano-linux-armv7": "1.69.4",
84
+ "@nanobpm/c8ctl-plugin-nano-linux-armv6": "1.69.4",
85
+ "@nanobpm/c8ctl-plugin-nano-win32-x64": "1.69.4"
86
86
  }
87
87
  }
package/work-channel.mjs CHANGED
@@ -93,7 +93,7 @@ export function redactAgenticUrl(url) {
93
93
  * breaking older peers"), so the visibility page can surface `capability.jobs`
94
94
  * without any wire-contract change.
95
95
  *
96
- * @param {{ cognition?: string, weight?: number, family?: string, host?: string }} capability
96
+ * @param {{ cognition?: string, weight?: number, family?: string, host?: string, harnessProtocol?: number }} capability
97
97
  * @param {readonly string[]} jobs
98
98
  * @returns {object}
99
99
  */
@@ -104,6 +104,12 @@ function presenceCapability(capability, jobs) {
104
104
  if (typeof capability.weight === 'number' && Number.isFinite(capability.weight)) out.weight = capability.weight;
105
105
  if (typeof capability.family === 'string' && capability.family !== '') out.family = capability.family;
106
106
  if (typeof capability.host === 'string' && capability.host !== '') out.host = capability.host;
107
+ // Harness-protocol version (issue #272): nano-workforce (#802) flags a worker
108
+ // that advertises no protocol as "stale harness". Forward it on the REGISTER
109
+ // capability frame so the visibility page grades this worker current.
110
+ if (typeof capability.harnessProtocol === 'number' && Number.isInteger(capability.harnessProtocol)) {
111
+ out.harnessProtocol = capability.harnessProtocol;
112
+ }
107
113
  }
108
114
  out.jobs = Array.isArray(jobs) ? jobs.map(String) : [];
109
115
  return out;
@@ -135,7 +141,7 @@ function presenceCapability(capability, jobs) {
135
141
  * @param {object} opts
136
142
  * @param {string} opts.instance stable worker instance id (the worker name) carried on every presence frame
137
143
  * @param {string} opts.host the worker's host label
138
- * @param {{ cognition?: string, weight?: number, family?: string, host?: string }} [opts.capability] declared enrolment capability
144
+ * @param {{ cognition?: string, weight?: number, family?: string, host?: string, harnessProtocol?: number }} [opts.capability] declared enrolment capability
139
145
  * @param {() => readonly string[]} [opts.listJobKeys] reads the live jobKey set from the worker's activeJobs map
140
146
  * @param {string} opts.url the app's HTTP(S) base URL (the channel is served same-port at `/agentic`)
141
147
  * @param {string} opts.token ADR 0028 identity token