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/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
@@ -2671,6 +2723,16 @@ const RESERVED_RESULT_KEYS = new Set([
2671
2723
  // signal for consumers (the nested envelope is host-built and correct, but the
2672
2724
  // flat completion vars must not be spoofable).
2673
2725
  'pushFailed', 'pushError', 'strandedCommits', 'branchMismatch', 'scanError',
2726
+ // `worldMarker` is the host-authored world-restore marker (buildWorldMarker,
2727
+ // nano-workforce #324): shape `{commitSha, effects}`, emitted ONLY on a real push
2728
+ // with a 40-hex head. It is spread into the completion vars AFTER the agent's
2729
+ // sanitized result, but ONLY when the host actually built one — so without
2730
+ // reserving it here an agent-supplied `worldMarker` survives sanitizeResultVars
2731
+ // and, whenever this round produced no host marker (no push, or an abbreviated
2732
+ // head SHA), leaks through UNSHADOWED into the completion. That forges a world
2733
+ // push-checkpoint / points world-restore at an arbitrary SHA, so reserve it
2734
+ // alongside the other host-owned git-result keys (thread 4117276817).
2735
+ 'worldMarker',
2674
2736
  ]);
2675
2737
 
2676
2738
  // Parse `text` as a JSON object, returning it only when it is a plain object.
@@ -2754,6 +2816,41 @@ function hasEffectiveResultVars(obj) {
2754
2816
  return false;
2755
2817
  }
2756
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
+
2757
2854
  // Choose the agent's structured result from its candidate sources (result file,
2758
2855
  // stdout sentinel, ACP outcome) in priority order. Prefer the first candidate
2759
2856
  // that carries at least one EFFECTIVE var (i.e. survives sanitizeResultVars —
@@ -2779,6 +2876,103 @@ function pickAgentResult(...thunks) {
2779
2876
  return firstPresent ?? null;
2780
2877
  }
2781
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
+
2782
2976
  const SANDBOXES = ['none', 'docker', 'podman'];
2783
2977
  // Only container-based sandboxes need an image / disk hygiene / a runtime bin.
2784
2978
  const CONTAINER_SANDBOXES = new Set(['docker', 'podman']);
@@ -2886,7 +3080,7 @@ async function resolveAgentResultWithNudge({ result, resultFile, rerun, logger,
2886
3080
  // `truncated` flag consistent with it — echo the incoming `result.truncated`
2887
3081
  // rather than hardcoding false, so callers that trust the return value don't
2888
3082
  // see an already-truncated stdout reported as untruncated.
2889
- 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 };
2890
3084
  }
2891
3085
  let nudge = null;
2892
3086
  let nudgeError = null;
@@ -2921,7 +3115,13 @@ async function resolveAgentResultWithNudge({ result, resultFile, rerun, logger,
2921
3115
  // `workAgent` — otherwise the escalation and the recorded envelope outcome would
2922
3116
  // silently reflect only the first turn's outcome. Fall back to the first result's
2923
3117
  // outcome when the nudge reported none.
2924
- 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 };
2925
3125
  }
2926
3126
 
2927
3127
  function coerceBool(v, dflt = false) {
@@ -4706,6 +4906,15 @@ function githubCloneToken({ provider, authRef, secretResolver, ghAuthToken = ghA
4706
4906
  // Clone repo into <runDir>/workspace and check out / create the working branch.
4707
4907
  // Returns { workspaceDir, gitEnv, startSha, workingBranch, remote }. Throws a
4708
4908
  // ProvisionError (token-redacted) on any git failure so the caller can shed.
4909
+ //
4910
+ // Conventional default-branch names. provisionRepo resolves the remote's ACTUAL default
4911
+ // (origin/HEAD / ls-remote --symref) where it can, but when that resolution fails it
4912
+ // conservatively treats these names as base-like so a checked-out branch that is very
4913
+ // likely the shared base is fallback-branched rather than pushed onto directly. Kept in
4914
+ // lockstep with agent-resume.mjs's CONVENTIONAL_BASE_BRANCHES so the provisioning and
4915
+ // resume sides agree on which no-create push targets are recoverable (#270).
4916
+ const CONVENTIONAL_BASE_BRANCHES = new Set(['main', 'master']);
4917
+
4709
4918
  function provisionRepo({ envelope, token, runDir, runId, timeoutMs = 120_000, logger = null, corr = '', abortSignal = null, _runGit = null }) {
4710
4919
  // Test-only seam mirroring finalizeGit: route every git call through `runGitFn` so a
4711
4920
  // deterministic test can observe the per-call timeouts drawn from the shared
@@ -5148,7 +5357,17 @@ function provisionRepo({ envelope, token, runDir, runId, timeoutMs = 120_000, lo
5148
5357
  // timeout): an indeterminate probe cannot prove the create is not the default, so
5149
5358
  // honoring it would re-open the fail-OPEN this guard exists to close (thread 4477).
5150
5359
  let defaultUnverified = false;
5151
- if (explicitCreate && wantPush && explicitCreate !== effectiveBase) {
5360
+ // Resolve the remote default whenever it can change a push-target decision:
5361
+ // - an explicit branch.create we would otherwise HONOR (push enabled, not the base), OR
5362
+ // - #270: the no-create decision below that would otherwise STAY ON and push the
5363
+ // checked-out branch. A checked-out branch that IS the remote default (the
5364
+ // mismatched shape the reviewer flagged: ref=main + baseRef=develop with no
5365
+ // branch.create, where effectiveBase='develop' so an effectiveBase compare alone
5366
+ // misses that 'main' is the shared default) must be recognised as base-like and
5367
+ // fallback-branched, not pushed onto directly.
5368
+ const resolveDefaultForCreate = explicitCreate && wantPush && explicitCreate !== effectiveBase;
5369
+ const resolveDefaultForCheckedOut = !explicitCreate && wantPush && !!checkedOut && checkedOut !== effectiveBase;
5370
+ if (resolveDefaultForCreate || resolveDefaultForCheckedOut) {
5152
5371
  const dh = runGitFn(['rev-parse', '--abbrev-ref', 'origin/HEAD'], { cwd: workspaceDir, env: gitEnv, timeoutMs: provTimeoutMs() });
5153
5372
  if (dh.status === 0) {
5154
5373
  const def = (dh.stdout || '').trim().replace(/^origin\//, '');
@@ -5161,7 +5380,7 @@ function provisionRepo({ envelope, token, runDir, runId, timeoutMs = 120_000, lo
5161
5380
  if (m && m[1] && !m[1].startsWith('-')) remoteDefaultBranch = m[1];
5162
5381
  }
5163
5382
  }
5164
- if (!remoteDefaultBranch && !configuredBaseRef && !envelope.branch?.base) {
5383
+ if (resolveDefaultForCreate && !remoteDefaultBranch && !configuredBaseRef && !envelope.branch?.base) {
5165
5384
  // The create could still be the unverified default — but only if it already
5166
5385
  // exists remotely. Probe for it; a genuinely-new branch stays honored.
5167
5386
  // `ls-remote` does NOT reliably accept `--end-of-options` on older git (<2.24),
@@ -5217,9 +5436,40 @@ function provisionRepo({ envelope, token, runDir, runId, timeoutMs = 120_000, lo
5217
5436
  if (workingBranch === effectiveBase) log.warn?.(`provisionRepo${cs}: branch.create='${workingBranch}' IS the effective base and push is disabled → any commits land directly on the base branch (not pushed, but this throwaway workspace is reaped)`);
5218
5437
  else log.debug?.(`provisionRepo${cs}: branch.create=${workingBranch} → cut work branch off base '${baseBranchName || '(unknown)'}'`);
5219
5438
  } else if (checkedOut && wantPush) {
5220
- // Either no branch.create, OR an explicit create that NAMES the effective base
5221
- // while pushing — both would otherwise commit on the base, so cut a fallback.
5222
- cutFallbackBranch(checkedOut);
5439
+ // No branch.create (or a create that named the base, routed here): the clone
5440
+ // landed on a symbolic branch. If that branch IS the shared base/default — or the
5441
+ // base/default could NOT be resolved (fail closed, #231/4444) — committing +
5442
+ // pushing there races the base and a non-ff reject strands the work, so cut a
5443
+ // fallback off it. But when the clone landed on a KNOWN NON-base branch it is the
5444
+ // PR head (the review-round / fix-ci / rebase shape: nano-workforce's repoEnvelope
5445
+ // emits repository.ref=<PR head> with NO branch.create). That branch IS the
5446
+ // intended push target — stay on it so `finalizeGit` advances the PR head. Cutting
5447
+ // a fallback here would strand the agent's commit on a throwaway nano/agent-work/*
5448
+ // ref while the PR head never moves, which nano-workforce's convergence loop then
5449
+ // (correctly) flags as a no-advance escalation despite a genuine "pushed" round
5450
+ // (the divergence that stranded nano-coder#26/#28 — c8ctl-plugin-nano#270).
5451
+ const baseKnown = !!(effectiveBase || remoteDefaultBranch);
5452
+ const createNamedBase = !!explicitCreate && createNamesBase(explicitCreate);
5453
+ // The checked-out branch is base-like — cut a fallback rather than push onto it —
5454
+ // when it equals the effective base or the RESOLVED remote default
5455
+ // (`createNamesBase`), OR when it is a conventional default name (main/master):
5456
+ // provisionRepo also fallback-branches the resolved remote default, and the resume
5457
+ // contract (agent-resume.mjs `envelopeHasPushedBranch`) conservatively treats
5458
+ // main/master as base-like, so mirror it here so a mismatched ref=main + baseRef=develop
5459
+ // shape is fallback-branched on BOTH sides.
5460
+ const checkedOutBaseLike = createNamesBase(checkedOut) || CONVENTIONAL_BASE_BRANCHES.has(String(checkedOut).toLowerCase());
5461
+ // Fail closed (#231/4444): we needed the remote default to clear a checked-out branch
5462
+ // that is NOT the effective base, but could not resolve it (a transient network/auth
5463
+ // failure emptied both origin/HEAD and the ls-remote --symref fallback). We cannot
5464
+ // prove the branch is not the shared default, so cut a fallback rather than risk a
5465
+ // silent fast-forward push directly onto it.
5466
+ const defaultUnresolvedForCheckedOut = !remoteDefaultBranch && checkedOut !== effectiveBase;
5467
+ if (baseKnown && !checkedOutBaseLike && !createNamedBase && !defaultUnresolvedForCheckedOut) {
5468
+ workingBranch = checkedOut;
5469
+ log.debug?.(`provisionRepo${cs}: no base-naming branch.create; clone landed on non-base PR head '${checkedOut}' (base '${effectiveBase || remoteDefaultBranch}') → commit + push there so the PR head advances`);
5470
+ } else {
5471
+ cutFallbackBranch(checkedOut);
5472
+ }
5223
5473
  } else if (unbornBranch && wantPush) {
5224
5474
  // Unborn branch (empty remote clone) with push enabled: the agent's FIRST
5225
5475
  // commit belongs on a pushable work branch, not stranded on the unborn default.
@@ -6989,6 +7239,105 @@ function spawnCapturePty({ command, args = [], cwd, env, stdinData, timeoutMs, i
6989
7239
  });
6990
7240
  }
6991
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
+
6992
7341
  // ---- ACP capture (C3 #110 — the third harness path, "minimal mode") ---------
6993
7342
  // Some ACP agents are native (`copilot --acp`, `qwen --experimental-acp`,
6994
7343
  // `opencode acp`), some ride an adapter (`claude-code-acp`, `pi-acp`). In every
@@ -6997,20 +7346,44 @@ function spawnCapturePty({ command, args = [], cwd, env, stdinData, timeoutMs, i
6997
7346
  // select ACP, so a native/adapter invocation is never doubled. This mirrors how
6998
7347
  // the pipe path spawns the line under a shell.
6999
7348
  function ensureAcpFlag(commandLine) {
7000
- // Detection must survive buildAgentCommandLine()'s POSIX single-quoting: a
7001
- // structured `--arg acp` (or `--arg --acp`) lands here as the quoted token
7002
- // 'acp' / '--acp', so a naive `\bacp\b` on the raw line would miss it and
7003
- // wrongly append a second --acp. Tokenise the line, strip the shell quoting
7004
- // (both POSIX single-quotes from buildAgentCommandLine() AND double-quotes a
7005
- // 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:
7006
7379
  // - a native ACP selector `acp`/`-acp`/`--acp` (subcommand or switch) as a
7007
7380
  // WHOLE token, in ANY position (it may be the command or an argument), or
7008
7381
  // - an adapter command whose basename ends in `-acp` (claude-agent-acp,
7009
7382
  // pi-acp) — but ONLY the command token (the first token past any leading
7010
- // env-assignment prefix, see commandIndex below), since an *argument*
7011
- // that merely ends in `-acp` (e.g. `--model foo-acp`) is not an ACP
7012
- // selector. Matching whole tokens/basenames (not a substring) also avoids
7013
- // 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/`.
7014
7387
  // A shell WORD is a contiguous run of quoted and/or unquoted segments with no
7015
7388
  // whitespace between them, so a `\S+` token boundary is wrong: an env prefix
7016
7389
  // whose value is quoted and contains spaces (e.g. `FOO='a b' claude-code-acp`)
@@ -7020,28 +7393,15 @@ function ensureAcpFlag(commandLine) {
7020
7393
  const tokens = commandLine.match(/(?:'(?:[^']|'\\'')*'|"(?:[^"\\]|\\.)*"|[^\s'"]+)+/g) || [];
7021
7394
  // Strip shell quoting across ALL of a word's segments (a word may mix quoted
7022
7395
  // and unquoted runs, e.g. `FOO='a b'`), yielding the logical value.
7023
- const unquote = (tok) => {
7024
- let out = '';
7025
- const seg = /'((?:[^']|'\\'')*)'|"((?:[^"\\]|\\.)*)"|([^\s'"]+)/g;
7026
- let m;
7027
- while ((m = seg.exec(tok)) !== null) {
7028
- if (m[1] !== undefined) out += m[1].replace(/'\\''/g, "'");
7029
- else if (m[2] !== undefined) out += m[2].replace(/\\(["\\$`])/g, '$1');
7030
- else out += m[3];
7031
- }
7032
- return out;
7033
- };
7396
+ const unquote = unquoteShellWord;
7034
7397
  // The `*-acp` adapter suffix identifies the COMMAND token, but the command is
7035
7398
  // not always token 0: a shell command line may be prefixed with a contiguous
7036
7399
  // run of env assignments (`NAME=value`, e.g. the `ACP=true` in
7037
- // `ACP=true claude-code-acp`). Skip that leading assignment prefix so the
7038
- // adapter check lands on the real command token. Only a *leading* run counts —
7039
- // once a real command token appears, later `FOO=bar` tokens are arguments.
7040
- let commandIndex = 0;
7041
- while (commandIndex < tokens.length &&
7042
- /^[A-Za-z_][A-Za-z0-9_]*=/.test(unquote(tokens[commandIndex]))) {
7043
- commandIndex++;
7044
- }
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);
7045
7405
  for (let i = 0; i < tokens.length; i++) {
7046
7406
  let tok = unquote(tokens[i]);
7047
7407
  // Normalise a GNU-style `--opt=value` selector to its option-NAME part, so
@@ -7065,6 +7425,8 @@ function ensureAcpFlag(commandLine) {
7065
7425
  if (/^--?[a-z0-9][a-z0-9-]*-acp$/i.test(name)) return commandLine;
7066
7426
  if (i === commandIndex && /-acp$/i.test(base)) return commandLine;
7067
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`.
7068
7430
  return `${commandLine} --acp`;
7069
7431
  }
7070
7432
 
@@ -7203,6 +7565,12 @@ function spawnCaptureAcp({ command, args = [], cwd, env, stdinData, timeoutMs, i
7203
7565
  // drill-in shows the outcome instead of nothing (see `maybeEmitTranscriptFloor`).
7204
7566
  let transcriptChunksPublished = 0;
7205
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;
7206
7574
 
7207
7575
  // Live "spy" tee (--stream), line-buffered, mirroring the other paths.
7208
7576
  // Separate line buffers per lane (stdout-human vs stderr) so a partial line
@@ -7284,7 +7652,14 @@ function spawnCaptureAcp({ command, args = [], cwd, env, stdinData, timeoutMs, i
7284
7652
  if (teeSink) { tee('', true); teeErr('', true); }
7285
7653
  // Reap the child if it is still alive (turn resolved but agent lingering).
7286
7654
  try { if (child && childClosed === null) killTree(child); } catch { /* best effort */ }
7287
- 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);
7288
7663
  };
7289
7664
 
7290
7665
  // --- JSON-RPC 2.0 plumbing (newline-delimited framing) -------------------
@@ -7413,6 +7788,9 @@ function spawnCaptureAcp({ command, args = [], cwd, env, stdinData, timeoutMs, i
7413
7788
  // the update has no canonical mapping OR the relay exposes no transcript seam,
7414
7789
  // so nothing is ever dropped (no regression vs minimal mode).
7415
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;
7416
7794
  const chunk = encodeTranscriptChunk(update);
7417
7795
  if (chunk && relayTap && typeof relayTap.relayTranscriptChunk === 'function') {
7418
7796
  // Only skip the text fallback when the chunk publish ACTUALLY succeeded.
@@ -8086,6 +8464,38 @@ function runAgentJob(profile, job, opts = {}) {
8086
8464
 
8087
8465
  // Shape the io.nanobpm.agentResult output envelope. When a repository was
8088
8466
  // provisioned (increment 2a), the `git` block adds branch/commits/push/PR facts.
8467
+ /**
8468
+ * Build the world-restore marker (nano-workforce issue #324 / ADR 0062 Slice 4/5, the WORLD half)
8469
+ * from a finalizeGit result, or `null` when the round pushed nothing durable.
8470
+ *
8471
+ * When a round's work actually LANDED on the remote (`gitResult.pushed`), nano-workforce's
8472
+ * `persist-round` worker records a durable push-checkpoint keyed off the pushed commit SHA so a
8473
+ * REPLACEMENT activation (a fresh worktree after a lease loss) reconstructs the working tree to the
8474
+ * EXACT pushed SHA — inverting this round's `git push` into `git fetch && git checkout <sha>` — and
8475
+ * so its no-advance self-heal has a reachable SHA to reconcile the PR head against. It reads the
8476
+ * reserved top-level `worldMarker` completion variable, shape `{commitSha, effects?}` (see
8477
+ * `workers/persist-round/worker.ts` `worldMarkerOf`). Without this the world store stays empty and
8478
+ * world-restore is dark.
8479
+ *
8480
+ * The marker is emitted ONLY when the push succeeded AND the final head SHA is a well-formed 40-hex
8481
+ * object name — the SAME `isCommitSha` guard the consumer applies, so the emit/consume boundaries
8482
+ * can't drift (an abbreviated SHA or a symbolic ref would fail the exact-tree restore contract).
8483
+ * A single `push` effect carries the pushed SHA as its fence idempotency key (per the contract:
8484
+ * push → commit SHA), so a fence-replay on resume skips an already-landed push.
8485
+ */
8486
+ function buildWorldMarker(gitResult) {
8487
+ if (!gitResult || !gitResult.pushed) return null;
8488
+ const commitSha = typeof gitResult.headSha === 'string' ? gitResult.headSha.trim() : '';
8489
+ if (!/^[0-9a-f]{40}$/i.test(commitSha)) return null;
8490
+ const branch = gitResult.branch ? String(gitResult.branch) : null;
8491
+ return {
8492
+ commitSha,
8493
+ effects: [
8494
+ { kind: 'push', idempotencyKey: commitSha, ...(branch ? { description: `push ${branch}@${commitSha.slice(0, 12)}` } : {}) },
8495
+ ],
8496
+ };
8497
+ }
8498
+
8089
8499
  function buildResultEnvelope(result, { sandbox, image, git, result: agentResult, promptResourceKey } = {}) {
8090
8500
  const status = result.ok ? 'completed' : (result.timedOut ? 'timedOut' : 'failed');
8091
8501
  const env = {
@@ -9375,13 +9785,11 @@ async function workAgent(req, flags, ctx) {
9375
9785
 
9376
9786
  const stored = readHires()[name];
9377
9787
  if (!stored) {
9378
- logger.error(`No hire named "${name}". List profiles with: c8ctl nano hire --list`);
9379
- process.exit(1);
9788
+ exitConfigError(logger, `No hire named "${name}". List profiles with: c8ctl nano hire --list`);
9380
9789
  }
9381
9790
  const normalized = normalizeStoredProfile(name, stored);
9382
9791
  if (normalized.error) {
9383
- logger.error(`Cannot work "${name}": ${normalized.error}. Re-create it with: c8ctl nano hire`);
9384
- process.exit(1);
9792
+ exitConfigError(logger, `Cannot work "${name}": ${normalized.error}. Re-create it with: c8ctl nano hire`);
9385
9793
  }
9386
9794
  const profile = normalized.profile;
9387
9795
 
@@ -9393,8 +9801,7 @@ async function workAgent(req, flags, ctx) {
9393
9801
  // supervisor path); a non-blank one must be a safe worker-name token.
9394
9802
  const explicitName = flags?.name ? String(flags.name).trim() : '';
9395
9803
  if (explicitName !== '' && !isValidWorkerName(explicitName)) {
9396
- logger.error(`Invalid --name "${flags.name}": use only letters, digits, and . _ -`);
9397
- process.exit(1);
9804
+ exitConfigError(logger, `Invalid --name "${flags.name}": use only letters, digits, and . _ -`);
9398
9805
  }
9399
9806
  const workerName = explicitName !== '' ? explicitName : autoWorkerName(name);
9400
9807
 
@@ -9408,8 +9815,7 @@ async function workAgent(req, flags, ctx) {
9408
9815
  // config such as permission toggles (e.g. a coder CLI started with tools enabled).
9409
9816
  const { env: workEnv, errors: workEnvErrors } = parseEnvPairs(flags?.env);
9410
9817
  if (workEnvErrors.length > 0) {
9411
- logger.error(workEnvErrors.join('; '));
9412
- process.exit(1);
9818
+ exitConfigError(logger, workEnvErrors.join('; '));
9413
9819
  }
9414
9820
  const profileEnv = { ...profile.env, ...workEnv };
9415
9821
 
@@ -9977,12 +10383,9 @@ async function workAgent(req, flags, ctx) {
9977
10383
  // The presence attributes this worker announces on `register` (ENROLMENT
9978
10384
  // attributes, not routing tokens — jobKeys are carried by the explicit
9979
10385
  // claim/release ownership frames the dispatch lifecycle emits, never smuggled in
9980
- // here). Reused for the initial seed and any resync.
9981
- const agenticCapability = {
9982
- cognition: profile.rank,
9983
- family: profile.model || undefined,
9984
- host: hostname(),
9985
- };
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);
9986
10389
  // Maintain `activeJobs` unconditionally: it feeds the supervisor activity file
9987
10390
  // (gated inside writeActivity) so a standalone worker still reports its current
9988
10391
  // jobs. Live presence/ownership jobKeys are now owned by the runtime — the
@@ -10251,6 +10654,27 @@ async function workAgent(req, flags, ctx) {
10251
10654
  const envPermission = (process.env.NANO_AGENTIC_PERMISSION || '').trim().toLowerCase();
10252
10655
  const rolePermission = resolveAgenticSetting(envPermission, profile.permission, PERMISSION_MODES, 'yolo');
10253
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
+
10254
10678
  // The agent job runner (issue #172 hot-path flip). The single-owner supervisor
10255
10679
  // runtime dispatches each activated job to this `run(job)`; it executes the
10256
10680
  // harness exactly as the retired per-type SDK jobHandler did, but SETTLES via the
@@ -10872,7 +11296,7 @@ async function workAgent(req, flags, ctx) {
10872
11296
  // the result is recoverable only via the stdout `::nano:result::`
10873
11297
  // sentinel, which `resolveAgentResultWithNudge` handles directly.
10874
11298
  if (result.ok) {
10875
- const { stdout, nudged, truncated, acpOutcome } = await resolveAgentResultWithNudge({
11299
+ const { stdout, nudged, truncated, acpOutcome, transcriptFloorOnly } = await resolveAgentResultWithNudge({
10876
11300
  result,
10877
11301
  resultFile,
10878
11302
  logger,
@@ -10894,6 +11318,10 @@ async function workAgent(req, flags, ctx) {
10894
11318
  }),
10895
11319
  });
10896
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;
10897
11325
  if (nudged) {
10898
11326
  result.nudgedForResult = true;
10899
11327
  if (truncated) result.truncated = true;
@@ -10903,12 +11331,26 @@ async function workAgent(req, flags, ctx) {
10903
11331
  }
10904
11332
  }
10905
11333
 
10906
- // #194: end the AgentInstance lifecycle. Flush any pending turn and drain
10907
- // the append queue, then drive the instance to COMPLETED on a successful
10908
- // job end (a failed run leaves it non-terminal so a retry/reactivation
10909
- // 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;
10910
11352
  if (agentInstanceProducer) {
10911
- 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.`); }
10912
11354
  }
10913
11355
 
10914
11356
  // #264: the run is done — take a FINAL snapshot (so edits still pending in
@@ -11162,6 +11604,52 @@ async function workAgent(req, flags, ctx) {
11162
11604
  const resultKeys = Object.keys(resultVars);
11163
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.`);
11164
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
+
11165
11653
  const settled = await settleJob.complete({
11166
11654
  ...resultVars,
11167
11655
  [AGENT_RESULT_KEY]: resultEnvelope,
@@ -11172,11 +11660,19 @@ async function workAgent(req, flags, ctx) {
11172
11660
  ...(gitResult
11173
11661
  ? { branch: gitResult.branch, commits: gitResult.commits, pushed: gitResult.pushed, pullRequest: gitResult.pr || null }
11174
11662
  : {}),
11663
+ ...(buildWorldMarker(gitResult) ? { worldMarker: buildWorldMarker(gitResult) } : {}),
11175
11664
  });
11176
11665
  // The engine acknowledged completion: the WIP checkpoint is no longer needed.
11177
11666
  if (discardCheckpointOnAck) await checkpointing.discardAfterAck();
11178
11667
  return settled;
11179
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
+ }
11180
11676
  const retries = Math.max(0, (Number(job.retries) || 1) - 1);
11181
11677
  const detail = result.error
11182
11678
  || (result.stderr || '').trim() + (result.stderrTruncated && (result.stderr || '').trim() ? ' [stderr truncated]' : '')
@@ -11520,6 +12016,21 @@ const SUPERVISOR_BACKOFF_MAX_MS = 30_000;
11520
12016
  // A child that stayed up at least this long before exiting is not crash-looping,
11521
12017
  // so its restart backoff is reset to zero.
11522
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
+ }
11523
12034
  const SUPERVISOR_CONNECT_TIMEOUT_MS = 6_000;
11524
12035
  // End-to-end deadline for a single request: once connected, a wedged/incompatible
11525
12036
  // daemon that accepts but never sends a `final` frame must not hang the client.
@@ -11921,6 +12432,10 @@ function summarizeSupervisorWorker(w, now = Date.now()) {
11921
12432
  pid: alive ? w.pid : null,
11922
12433
  state: w.stopping ? 'stopping' : alive ? 'running' : 'down',
11923
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,
11924
12439
  uptimeMs,
11925
12440
  startedAtMs,
11926
12441
  lastExit: w.lastExit ?? null,
@@ -12222,7 +12737,12 @@ function formatSupervisorStatus(status) {
12222
12737
  const rows = workers.map((w) => ({
12223
12738
  id: String(w.id),
12224
12739
  profile: String(w.profile),
12225
- 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),
12226
12746
  engine: supervisorEngineCell(w),
12227
12747
  agentic: supervisorAgenticCell(w),
12228
12748
  job: supervisorJobCell(w),
@@ -12525,7 +13045,7 @@ async function runSupervisorDaemon() {
12525
13045
  workers: [...workers.values()].map((w) => ({
12526
13046
  id: w.id, profile: w.profile, args: w.args, pid: isPidAlive(w.pid) ? w.pid : null,
12527
13047
  startedAt: w.startedAt || null, restarts: w.restarts, lastExit: w.lastExit ?? null,
12528
- stopping: !!w.stopping, logFile: w.logFile,
13048
+ stopping: !!w.stopping, logFile: w.logFile, configFailed: w.configFailed === true,
12529
13049
  })),
12530
13050
  });
12531
13051
  } catch { /* best effort */ }
@@ -12547,6 +13067,10 @@ async function runSupervisorDaemon() {
12547
13067
  const workerLogMaxBytes = resolveLogMaxBytes(process.env.NANO_SUPERVISOR_LOG_MAX_BYTES);
12548
13068
 
12549
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;
12550
13074
  // With a cap we pipe stdout/stderr through the daemon so the ring can bound
12551
13075
  // them; unbounded (opt-out) keeps the legacy direct-fd append. `fd` is only
12552
13076
  // used on the direct-fd path.
@@ -12642,6 +13166,19 @@ async function runSupervisorDaemon() {
12642
13166
  return;
12643
13167
  }
12644
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
+ }
12645
13182
  w.restarts += 1;
12646
13183
  dlog(`worker '${w.id}' down (${reason}); restarting in ${delay}ms (restart #${w.restarts})`);
12647
13184
  broadcast({ type: 'event', event: 'worker-exit', worker: workerPublic(w), restartInMs: delay });
@@ -17156,6 +17693,7 @@ export {
17156
17693
  };
17157
17694
  export { compareSemver, githubRepoSlug, filterReleasesSince, renderReleaseBody };
17158
17695
  export { probeAgentCliVersion };
17696
+ export { HARNESS_PROTOCOL_VERSION, buildAgenticCapability };
17159
17697
  export {
17160
17698
  webConsoleUrl,
17161
17699
  consoleLinkLabel,
@@ -17188,12 +17726,19 @@ export {
17188
17726
  buildAgentPayload,
17189
17727
  buildAgentStdin,
17190
17728
  buildResultEnvelope,
17729
+ buildWorldMarker,
17191
17730
  parseAgentResultObject,
17192
17731
  readAgentResultFile,
17193
17732
  parseResultFromStdout,
17194
17733
  sanitizeResultVars,
17195
17734
  hasEffectiveResultVars,
17196
17735
  pickAgentResult,
17736
+ stdoutStrippedOfEmptyResult,
17737
+ detectEmptyAgentJob,
17738
+ detectProtocolMismatch,
17739
+ effectiveHarnessProtocol,
17740
+ commandLineHasAcpSelector,
17741
+ shellWrappedScript,
17197
17742
  buildResultNudgePrompt,
17198
17743
  resolveAgentResultWithNudge,
17199
17744
  parseEnvPairs,