c8ctl-plugin-nano 1.70.5 → 1.70.7

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
@@ -835,6 +835,14 @@ the job with a decremented retry count. Profiles are stored in the plugin's
835
835
  > the resume needs (issue #295). The sweep fails closed (any missing key / unreachable
836
836
  > lookup spares the ref; the 7-day TTL is the backstop) and degrades to the element-only
837
837
  > check on hosts whose SDK lacks process-instance lookup.
838
+ > The same sweep reclaims stale `nano/agent-work/*` fallback branches (tip older than
839
+ > the same TTL) **without losing work**: a branch that heads an open PR is kept (as is
840
+ > any branch whose PR status can't be determined, e.g. non-GitHub remotes or `gh`
841
+ > failing); a branch whose tip is contained in another branch is deleted; otherwise the
842
+ > tip is first pushed to `refs/nano/archive/agent-work/<archivedAtMs>/<name>` and only then
843
+ > is the branch deleted. Archive refs are purged after `NANO_AGENT_WORK_ARCHIVE_TTL_MS`
844
+ > (90 days; `0` keeps them forever). Recover one with
845
+ > `git fetch origin refs/nano/archive/agent-work/<ts>/<name>:refs/heads/<name>`.
838
846
  > - **Safety:** pushes use `--force-with-lease`, so a superseded worker can't clobber a
839
847
  > newer run's checkpoint. A remote *policy* refusal (repository rules, secret push
840
848
  > protection) or a permission error stops checkpointing for that job with a warning;
@@ -121,6 +121,8 @@ const DEFAULTS = Object.freeze({
121
121
  // wall clock to observe the cancel-on-timeout behaviour (Copilot review on #296).
122
122
  sdkTimeoutMs: 10_000,
123
123
  ttlMs: 7 * 24 * 60 * 60 * 1000,
124
+ // Retention for archived (unmerged) fallback-branch tips — see sweepStaleAgentWorkBranches.
125
+ agentWorkArchiveTtlMs: 90 * 24 * 60 * 60 * 1000,
124
126
  gcGraceMs: 60 * 60 * 1000,
125
127
  gcEveryMs: 60 * 60 * 1000,
126
128
  });
@@ -234,6 +236,8 @@ export function checkpointConfig(env = process.env) {
234
236
  intervalMs: intOr(env.NANO_AGENT_CHECKPOINT_INTERVAL_MS, DEFAULTS.intervalMs),
235
237
  maxFileBytes: intOr(env.NANO_AGENT_CHECKPOINT_MAX_FILE_BYTES, DEFAULTS.maxFileBytes),
236
238
  ttlMs: intOr(env.NANO_AGENT_CHECKPOINT_TTL_MS, DEFAULTS.ttlMs),
239
+ // 0 disables purging archived agent-work tips (they are then kept forever).
240
+ agentWorkArchiveTtlMs: intOr(env.NANO_AGENT_WORK_ARCHIVE_TTL_MS, DEFAULTS.agentWorkArchiveTtlMs),
237
241
  gcGraceMs: DEFAULTS.gcGraceMs,
238
242
  gcEveryMs: DEFAULTS.gcEveryMs,
239
243
  gitTimeoutMs: DEFAULTS.gitTimeoutMs,
@@ -1157,6 +1161,143 @@ export async function sweepStaleCheckpoints({ git, ownRef = null, ttlMs = DEFAUL
1157
1161
  }
1158
1162
  }
1159
1163
 
1164
+ // The fallback work-branch namespace `provisionRepo` cuts when a push-enabled round is
1165
+ // provisioned WITHOUT a `branch.create` naming a real (non-base) work branch (issue #231):
1166
+ // rather than commit directly on the base, the harness cuts `nano/agent-work/<base>-<runId>`
1167
+ // and pushes it so the round's commits are never lost. When the round's work also landed on a
1168
+ // real PR branch (the app now emits `branch.create`, jwulf/c8ctl-plugin-nano#231 / nano-workforce
1169
+ // service fix), or the run is long dead, these pushed fallbacks are pure orphans that otherwise
1170
+ // accumulate forever — the WIP-checkpoint sweep only reclaims `refs/nano/wip/*`.
1171
+ export const AGENT_WORK_REF_PREFIX = 'refs/heads/nano/agent-work/';
1172
+
1173
+ // Archive namespace for unmerged fallback tips the GC removes from the branch list. NOT under
1174
+ // `refs/heads/`, so it never clutters branches / PR pickers, but the commits stay reachable
1175
+ // (and fetchable by exact ref) on the remote. Layout: `<prefix><archivedAtMs>/<branch-suffix>` —
1176
+ // the archive TIME is encoded in the ref because git refs carry no timestamp and the tip's
1177
+ // commit date (old by construction) can't measure how long it has been archived.
1178
+ export const AGENT_WORK_ARCHIVE_PREFIX = 'refs/nano/archive/agent-work/';
1179
+
1180
+ // Orphan GC for the pushed fallback work branches. A fallback branch can be the ONLY copy of a
1181
+ // run's work (the agent died without opening a PR), so age alone never authorises deleting it.
1182
+ // A branch past `ttlMs` (tip commit age — the branch segment is a UUID runId, not an element
1183
+ // instance key, so the WIP sweep's element-terminal lookup can't map here) is then:
1184
+ // 1. KEPT if it heads an open PR (`hasOpenPr(branch) === true`) — deleting a PR's head branch
1185
+ // closes the PR. FAIL-CLOSED: no lookup, a throw, or any non-boolean answer also keeps it.
1186
+ // 2. DELETED ('merged') if its tip is contained in another remote branch — the work is safe.
1187
+ // 3. Otherwise ARCHIVED ('archived'): the tip is pushed to `AGENT_WORK_ARCHIVE_PREFIX` FIRST and
1188
+ // the branch is deleted only after that push succeeds, so the commits are never unreachable.
1189
+ // Archive refs are purged once `archiveTtlMs` past their archive time (<= 0 disables purging).
1190
+ // Every remote delete is leased against the SHA observed at ls-remote time, so a ref a
1191
+ // concurrent activation just advanced is left intact. Runs in the same isolated scratch repo as
1192
+ // `sweepStaleCheckpoints`, so it shares the GC deadline/abort signal.
1193
+ //
1194
+ // Only GENERATED per-run fallbacks are GC candidates. The `nano/agent-work/` namespace is not
1195
+ // fallback-only — a stable/unrelated branch (`nano/agent-work/my-feature`) can live under it
1196
+ // (see `fallbackBranchParts`), and age must never authorise deleting one. So the ls-remote list
1197
+ // is filtered through the same generated-name parser provisioning's names satisfy
1198
+ // (`<base>-<runToken>`, runToken a UUID or `run-<token>`): a name that does not parse is NOT a
1199
+ // fallback — it is kept (reported 'not-a-fallback'), never fetched as a candidate, and counts
1200
+ // as a safe "other" head for the containment test (its commits are real, retained work).
1201
+ export async function sweepStaleAgentWorkBranches({ git, ttlMs = DEFAULTS.ttlMs, archiveTtlMs = DEFAULTS.agentWorkArchiveTtlMs, hasOpenPr = null, now = () => Date.now(), maxDeletes = 50, remote = 'origin', signal = null }) {
1202
+ const ls = await git(['ls-remote', '--refs', remote, 'refs/heads/*', `${AGENT_WORK_ARCHIVE_PREFIX}*`]);
1203
+ if (!ok(ls)) return { error: errText(ls), deleted: [], kept: [], purged: [] };
1204
+ const entries = out(ls).split('\n').filter(Boolean).map((l) => { const [sha, ref] = l.split(/\s+/); return { sha, ref }; }).filter((e) => e.ref);
1205
+ const inNs = entries.filter((e) => e.ref.startsWith(AGENT_WORK_REF_PREFIX));
1206
+ // Split the namespace into generated fallbacks (GC candidates) and everything else (stable —
1207
+ // kept, and a safe containment home). `fallbackBranchParts` is the single source of truth for
1208
+ // what provisioning's generated name looks like, so the GC can never mistake a stable branch
1209
+ // for a fallback no matter how old its tip is.
1210
+ const work = [];
1211
+ const stable = [];
1212
+ for (const e of inNs) (fallbackBranchParts(e.ref.slice('refs/heads/'.length)) ? work : stable).push(e);
1213
+ const others = entries.filter((e) => e.ref.startsWith('refs/heads/') && !e.ref.startsWith(AGENT_WORK_REF_PREFIX));
1214
+ const archives = entries.filter((e) => e.ref.startsWith(AGENT_WORK_ARCHIVE_PREFIX));
1215
+ const result = { scanned: work.length, deleted: [], kept: stable.map((e) => ({ ref: e.ref, why: 'not-a-fallback' })), purged: [] };
1216
+ let lastError = null;
1217
+
1218
+ // Purge archives past their retention. Needs no fetch: the archive time is in the ref name.
1219
+ if (archiveTtlMs > 0) {
1220
+ for (const { ref, sha } of archives) {
1221
+ if (result.purged.length >= maxDeletes || signal?.aborted) break;
1222
+ const at = Number(ref.slice(AGENT_WORK_ARCHIVE_PREFIX.length).split('/')[0]);
1223
+ if (!Number.isFinite(at) || at <= 0 || now() - at <= archiveTtlMs) continue;
1224
+ const r = await deleteCheckpointRef({ git, ref, remote, expectSha: sha });
1225
+ if (r.ok) result.purged.push({ ref, why: 'archive-ttl' });
1226
+ else if (r.error) lastError = r.error;
1227
+ }
1228
+ }
1229
+ if (!work.length) { if (lastError && !result.purged.length) result.error = lastError; return result; }
1230
+
1231
+ // Fetch the fallback tips AND every other branch head (for the containment test) into
1232
+ // throwaway local refs, always removed in `finally`. The two sets land in DISJOINT namespaces
1233
+ // so the containment scan can never count a fallback branch (itself or a sibling fallback,
1234
+ // both GC candidates) as a safe home for the work. Stable namespace branches are NOT
1235
+ // candidates, so they join `others` as legitimate containment homes.
1236
+ const workLocal = (r) => `refs/nano-gc/agent-work/${r.slice(AGENT_WORK_REF_PREFIX.length)}`;
1237
+ const otherLocal = (r) => `refs/nano-gc/other-heads/${r.slice('refs/heads/'.length)}`;
1238
+ const specs = [...work.map((e) => [e.ref, workLocal(e.ref)]), ...others.map((e) => [e.ref, otherLocal(e.ref)]), ...stable.map((e) => [e.ref, otherLocal(e.ref)])];
1239
+ const fetch = await git(['fetch', '--quiet', '--no-tags', '--no-write-fetch-head', remote, ...specs.map(([r, l]) => `+${r}:${l}`)]);
1240
+ if (!ok(fetch)) return { ...result, error: errText(fetch) };
1241
+ try {
1242
+ const stale = [];
1243
+ for (const e of work) {
1244
+ if (signal?.aborted) break;
1245
+ const at = Number(out(await git(['log', '-1', '--format=%ct', workLocal(e.ref)]))) * 1000;
1246
+ if (!Number.isFinite(at) || at <= 0) continue;
1247
+ if (ttlMs > 0 && now() - at > ttlMs) stale.push(e);
1248
+ }
1249
+ let actions = 0;
1250
+ for (const { ref, sha } of stale) {
1251
+ if (actions >= maxDeletes || signal?.aborted) break;
1252
+ const branch = ref.slice('refs/heads/'.length);
1253
+ let open = null;
1254
+ try { open = typeof hasOpenPr === 'function' ? await hasOpenPr(branch) : null; } catch { open = null; }
1255
+ if (open !== false) { result.kept.push({ ref, why: open === true ? 'open-pr' : 'pr-unknown' }); continue; }
1256
+ actions++;
1257
+ // Any containment home — a non-namespace branch OR a stable namespace branch — runs the query.
1258
+ const contains = (others.length || stable.length)
1259
+ ? await git(['for-each-ref', '--count=1', '--format=%(refname)', '--contains', sha, 'refs/nano-gc/other-heads/'])
1260
+ : null;
1261
+ if (contains && !ok(contains)) { lastError = errText(contains); result.kept.push({ ref, why: 'containment-unknown' }); continue; }
1262
+ let contained = !!(contains && out(contains));
1263
+ if (contained) {
1264
+ // The containment answer comes from the ls-remote/fetch SNAPSHOT, but only the
1265
+ // candidate's own delete is leased: a home that contained the tip at scan time can be
1266
+ // force-pushed or deleted before this delete lands, orphaning the tip despite the
1267
+ // must-never-lose-work contract (Copilot discussion_r4475075083). Revalidate the home
1268
+ // against the LIVE remote immediately before deleting: a home that no longer contains
1269
+ // the tip demotes the delete to the archive path. An UNREACHABLE remote fails closed
1270
+ // (kept, 'containment-unknown') — never delete on an unverifiable home.
1271
+ // The for-each-ref output is the LOCAL throwaway ref — map it back to the remote
1272
+ // branch name it was fetched from (the fetch spec inverted `otherLocal`).
1273
+ const homeLocal = out(contains).trim();
1274
+ const homeRef = `refs/heads/${homeLocal.slice('refs/nano-gc/other-heads/'.length)}`;
1275
+ const live = await git(['ls-remote', remote, homeRef]);
1276
+ if (!ok(live)) { lastError = errText(live); result.kept.push({ ref, why: 'containment-unknown' }); continue; }
1277
+ const liveSha = (out(live).split(/\s+/)[0] || '').trim();
1278
+ if (!liveSha) contained = false; // the home itself is gone
1279
+ else {
1280
+ const re = await git(['merge-base', '--is-ancestor', sha, liveSha]);
1281
+ if (re.status !== 0 && re.status !== 1) { lastError = errText(re); result.kept.push({ ref, why: 'containment-unknown' }); continue; }
1282
+ contained = re.status === 0;
1283
+ }
1284
+ }
1285
+ if (!contained) {
1286
+ const archiveRef = `${AGENT_WORK_ARCHIVE_PREFIX}${now()}/${ref.slice(AGENT_WORK_REF_PREFIX.length)}`;
1287
+ const a = await git(['push', '--quiet', '--no-verify', remote, `${sha}:${archiveRef}`]);
1288
+ if (!ok(a)) { lastError = errText(a); result.kept.push({ ref, why: 'archive-failed' }); continue; }
1289
+ }
1290
+ const r = await deleteCheckpointRef({ git, ref, remote, expectSha: sha });
1291
+ if (r.ok) result.deleted.push({ ref, why: contained ? 'merged' : 'archived' });
1292
+ else if (r.error) lastError = r.error;
1293
+ }
1294
+ if (!result.deleted.length && !result.purged.length && lastError) result.error = lastError;
1295
+ return result;
1296
+ } finally {
1297
+ for (const [, l] of specs) await git(['update-ref', '-d', l]);
1298
+ }
1299
+ }
1300
+
1160
1301
  // Prompt note appended when a checkpoint was restored into the workspace.
1161
1302
  export function checkpointRestoredNote(info) {
1162
1303
  if (!info?.restored) return '';
package/c8ctl-plugin.js CHANGED
@@ -90,7 +90,7 @@ import { createAgentInstanceProducer, isExternalAgentJob } from './agent-instanc
90
90
  // so the new agent CONTINUES rather than cold-reruns — at-least-once delivery becomes
91
91
  // a continuation, not a duplicate. Best-effort; degrades to the legacy cold rerun.
92
92
  import { resolveEffectiveEnvelope } from './agent-resume.mjs';
93
- import { checkpointConfig, checkpointEligibility, checkpointRef, recoveredCheckpointRef, predecessorCheckpointRef, resumeRefIsExplicit, pushNamedRef, observeRemoteRefSha, makeOrphanProbe, normalizeSecretValues, credentialsFromUrl, isAuthenticatedRemote, shouldSweep, sweepStaleCheckpoints, createGitRunner, fetchCheckpoint, restoreCheckpoint, createWorkspaceCheckpoint, createCheckpointer, deleteCheckpointRef, withCheckpointNote, sanitizeBranchSegment } from './agent-checkpoint.mjs';
93
+ import { checkpointConfig, checkpointEligibility, checkpointRef, recoveredCheckpointRef, predecessorCheckpointRef, resumeRefIsExplicit, pushNamedRef, observeRemoteRefSha, makeOrphanProbe, normalizeSecretValues, credentialsFromUrl, isAuthenticatedRemote, shouldSweep, sweepStaleCheckpoints, sweepStaleAgentWorkBranches, createGitRunner, fetchCheckpoint, restoreCheckpoint, createWorkspaceCheckpoint, createCheckpointer, deleteCheckpointRef, withCheckpointNote, sanitizeBranchSegment } from './agent-checkpoint.mjs';
94
94
 
95
95
  const requireFromHere = createRequire(import.meta.url);
96
96
  const pluginDir = dirname(fileURLToPath(import.meta.url));
@@ -3169,18 +3169,49 @@ const NUDGE_CONTEXT_CAP_CHARS = 24_000;
3169
3169
 
3170
3170
  // The bespoke prompt for the re-emit turn: derive the status from the work the
3171
3171
  // agent already did, write ONLY the result, change nothing else.
3172
- function buildResultNudgePrompt(priorStdout, { hasResultFile = true } = {}) {
3172
+ // ACP `StopReason` values (#301). Only `end_turn` means the agent finished its
3173
+ // turn on its own; anything else (`max_turn_requests`, `max_tokens`, `refusal`,
3174
+ // `cancelled`, …) means the turn was CUT OFF, so the work may be incomplete.
3175
+ export function acpStopReasonFrom(promptResult) {
3176
+ const r = promptResult?.stopReason;
3177
+ return typeof r === 'string' && r.trim() ? r.trim().slice(0, 64) : null;
3178
+ }
3179
+ export function isTruncatedStopReason(stopReason) {
3180
+ return typeof stopReason === 'string' && stopReason !== '' && stopReason !== 'end_turn';
3181
+ }
3182
+
3183
+ function buildResultNudgePrompt(priorStdout, { hasResultFile = true, stopReason = null } = {}) {
3173
3184
  const ctx = typeof priorStdout === 'string' ? priorStdout.slice(-NUDGE_CONTEXT_CAP_CHARS) : '';
3174
- const intro = [
3175
- 'You already completed the task in your previous turn, but you did NOT emit a',
3176
- 'machine-readable result, so the orchestrator cannot read your status and the',
3177
- 'run cannot advance.',
3178
- '',
3179
- 'Do NOT redo the work, re-run tools, edit files, push, or open/modify a PR. Just',
3180
- 'emit the result for the work you already did: a single flat JSON object of your',
3181
- 'result variables (at minimum {"status":"..."}).',
3182
- '',
3183
- ];
3185
+ // #301: never ASSERT completion. A budget-cut turn gets a bounded continuation
3186
+ // that asks the agent to preserve its work and report honestly; a clean
3187
+ // end_turn gets a softened re-emit that still allows `blocked`.
3188
+ const intro = isTruncatedStopReason(stopReason)
3189
+ ? [
3190
+ `Your previous turn was CUT OFF before you finished (stop reason: ${stopReason}).`,
3191
+ 'You did NOT emit a machine-readable result, and the task may be INCOMPLETE.',
3192
+ '',
3193
+ 'Do not start new work. If you have uncommitted changes that belong to the task,',
3194
+ 'commit them LOCALLY (`git commit -s`) so they are not lost — do NOT push:',
3195
+ 'this turn runs without the task\'s branch/push policy, and the harness pushes',
3196
+ 'for you afterwards when the task allows it (a push here could bypass that',
3197
+ 'policy and publish to the wrong branch).',
3198
+ 'Then report your TRUE status as a single flat JSON object of result variables.',
3199
+ 'Use "blocked" (with a "summary" and a "question" explaining what remains) unless',
3200
+ 'you actually delivered the full task (e.g. the PR is open). Never claim',
3201
+ '"completed" for work that was not committed and delivered.',
3202
+ '',
3203
+ ]
3204
+ : [
3205
+ 'Your previous turn ended, but you did NOT emit a machine-readable result, so',
3206
+ 'the orchestrator cannot read your status and the run cannot advance.',
3207
+ '',
3208
+ 'Do NOT redo the work, re-run tools, edit files, push, or open/modify a PR. Just',
3209
+ 'report your TRUE status for the work so far: a single flat JSON object of your',
3210
+ 'result variables (at minimum {"status":"..."}). If the task is not actually',
3211
+ 'finished, report "blocked" with a "summary" and a "question" — do not claim',
3212
+ 'completion for work you did not deliver.',
3213
+ '',
3214
+ ];
3184
3215
  // When the harness could not create the result file, AGENT_RESULT_FILE is NOT
3185
3216
  // exported (runAgentJob only sets it for a truthy resultFile), so the usual
3186
3217
  // "write to $AGENT_RESULT_FILE" instruction is impossible. Lead with the stdout
@@ -3229,6 +3260,49 @@ function capStdoutTail(s) {
3229
3260
  return { text: buf.subarray(start).toString('utf8'), truncated: true };
3230
3261
  }
3231
3262
 
3263
+ // #301: statuses that already report an honest non-success; left untouched.
3264
+ // `needs_input` belongs here too: it is a supported non-success result that
3265
+ // carries the actual `question` a human must answer. Rewriting it to `blocked`
3266
+ // would replace that question with the generic budget-retry prompt and lose the
3267
+ // information needed to unblock the task (Copilot review on #302, "previously
3268
+ // missed" — see agent-workers.test.mjs for needs_input as a supported status).
3269
+ const HONEST_NON_SUCCESS_STATUSES = new Set(['blocked', 'escalated', 'failed', 'incomplete', 'needs_input']);
3270
+ export function isWorkDelivered(git) {
3271
+ if (!git) return false;
3272
+ // A PR only proves delivery while it is OPEN or MERGED. `reconcileAgentPr`
3273
+ // searches `--state all`, so `found: true` also matches a CLOSED, unmerged PR
3274
+ // — e.g. an old, abandoned PR on the same branch. Treating that as delivered
3275
+ // would leave a claimed `completed` result unchanged for work that never
3276
+ // shipped, so a closed-unmerged PR is NOT delivery proof (Copilot review on
3277
+ // #302, discussion_r4464312576). `state` is the gh `pr list` field
3278
+ // (OPEN/CLOSED/MERGED); an absent/unknown state fails closed (not delivered).
3279
+ if (git.pr?.found) {
3280
+ const state = typeof git.pr.state === 'string' ? git.pr.state.trim().toUpperCase() : '';
3281
+ if (state === 'OPEN' || state === 'MERGED') return true;
3282
+ // CLOSED (unmerged) or unknown: fall through to the commit proof below.
3283
+ }
3284
+ return git.pushed === true && Array.isArray(git.commits) && git.commits.length > 0;
3285
+ }
3286
+ // Given the picked raw result of a run whose ACP turn ended with `stopReason`,
3287
+ // return an honest `blocked` result when the turn was cut off (non-`end_turn`)
3288
+ // and the work was NOT verifiably delivered. Otherwise return `raw` unchanged.
3289
+ export function downgradeBudgetStopResult(raw, { stopReason, git } = {}) {
3290
+ if (!isTruncatedStopReason(stopReason)) return raw;
3291
+ if (isWorkDelivered(git)) return raw;
3292
+ const status = isPlainObject(raw) && typeof raw.status === 'string' ? raw.status.trim().toLowerCase() : null;
3293
+ if (status && HONEST_NON_SUCCESS_STATUSES.has(status)) return raw;
3294
+ const prior = isPlainObject(raw) && typeof raw.summary === 'string' && raw.summary.trim() ? ` Agent's own summary: ${raw.summary.trim().slice(0, 2000)}` : '';
3295
+ const msg = `The agent's turn was cut off (stopReason=${stopReason}) before it delivered the task (no PR found, no commits pushed).${prior}`;
3296
+ return {
3297
+ ...(isPlainObject(raw) ? raw : {}),
3298
+ status: 'blocked',
3299
+ summary: msg,
3300
+ question: `Agent run stopped early (${stopReason}) without delivering. Retry with a larger budget, or recover the WIP checkpoint and continue?`,
3301
+ stopReason,
3302
+ claimedStatus: status,
3303
+ };
3304
+ }
3305
+
3232
3306
  async function resolveAgentResultWithNudge({ result, resultFile, rerun, logger, logPrefix = '' }) {
3233
3307
  const stdout0 = result && typeof result.stdout === 'string' ? result.stdout : '';
3234
3308
  // A parsed result only counts as usable if it still carries at least one
@@ -3259,7 +3333,8 @@ async function resolveAgentResultWithNudge({ result, resultFile, rerun, logger,
3259
3333
  }
3260
3334
  let nudge = null;
3261
3335
  let nudgeError = null;
3262
- try { nudge = await rerun(buildResultNudgePrompt(stdout0, { hasResultFile: resultFile != null })); } catch (err) { nudge = null; nudgeError = err; }
3336
+ const stopReason = result?.stopReason ?? null;
3337
+ try { nudge = await rerun(buildResultNudgePrompt(stdout0, { hasResultFile: resultFile != null, stopReason })); } catch (err) { nudge = null; nudgeError = err; }
3263
3338
  const nudgeOut = nudge && typeof nudge.stdout === 'string' ? nudge.stdout : '';
3264
3339
  // Re-apply the per-stream capture cap after concatenation: `result.stdout` is
3265
3340
  // forwarded verbatim into the job vars (`output`) and the audit envelope, so
@@ -3276,13 +3351,22 @@ async function resolveAgentResultWithNudge({ result, resultFile, rerun, logger,
3276
3351
  // no-nudge early return above).
3277
3352
  const truncated = result?.truncated === true || capped.truncated;
3278
3353
  const recovered = hasUsableResult(readAgentResultFile(resultFile) ?? parseResultFromStdout(stdout));
3354
+ // The nudge turn has its OWN ACP `stopReason` (#301, Copilot review on #302,
3355
+ // discussion_r4464312610). It must NOT be discarded: when the first turn ended
3356
+ // cleanly (`end_turn`) but the NUDGE was itself cut off (`max_turn_requests`,
3357
+ // `max_tokens`, …) after writing `status:"completed"`, the delivery check must
3358
+ // still see a truncated reason or it would permit completion without delivery
3359
+ // and the logs/audit would show only the first turn's reason. Prefer the
3360
+ // nudge's reason when it is truncated; otherwise keep the first turn's.
3361
+ const nudgeStopReason = nudge && typeof nudge.stopReason === 'string' && nudge.stopReason.trim() ? nudge.stopReason.trim() : null;
3362
+ const effectiveStopReason = (isTruncatedStopReason(nudgeStopReason) ? nudgeStopReason : null) ?? stopReason;
3279
3363
  if (nudgeError && logger?.warn) {
3280
3364
  logger.warn(`${logPrefix} re-emit nudge rerun threw — ${nudgeError?.message ?? nudgeError}`);
3281
3365
  }
3282
3366
  if (logger?.info) {
3283
3367
  logger.info(recovered
3284
- ? `${logPrefix} no result on the first turn — recovered it via one re-emit nudge`
3285
- : `${logPrefix} no result on the first turn — re-emit nudge did not recover one`);
3368
+ ? `${logPrefix} no result on the first turn${stopReason ? ` (stopReason=${stopReason})` : ''} — recovered it via one ${isTruncatedStopReason(stopReason) ? 'budget-continuation' : 're-emit'} nudge${nudgeStopReason ? ` (nudge stopReason=${nudgeStopReason})` : ''}`
3369
+ : `${logPrefix} no result on the first turn${stopReason ? ` (stopReason=${stopReason})` : ''} — ${isTruncatedStopReason(stopReason) ? 'budget-continuation' : 're-emit'} nudge did not recover one${nudgeStopReason ? ` (nudge stopReason=${nudgeStopReason})` : ''}`);
3286
3370
  }
3287
3371
  // Propagate the rerun turn's OWN validated ACP outcome back to the caller (#263):
3288
3372
  // the nudge is a continuation, so a fresh `_meta.outcome` it reports (e.g. a
@@ -3296,7 +3380,7 @@ async function resolveAgentResultWithNudge({ result, resultFile, rerun, logger,
3296
3380
  // agent work (thread 4118913047).
3297
3381
  const transcriptFloorOnly = result?.acpTranscriptFloorOnly === true
3298
3382
  && (!nudgeOut.trim() || nudge?.acpTranscriptFloorOnly === true);
3299
- return { stdout, nudged: true, truncated, acpOutcome: nudge?.acpOutcome ?? result?.acpOutcome ?? null, transcriptFloorOnly };
3383
+ return { stdout, nudged: true, truncated, acpOutcome: nudge?.acpOutcome ?? result?.acpOutcome ?? null, transcriptFloorOnly, stopReason: effectiveStopReason, nudgeStopReason };
3300
3384
  }
3301
3385
 
3302
3386
  function coerceBool(v, dflt = false) {
@@ -6642,6 +6726,38 @@ function reconcileAgentPr({ workspaceDir, token, branch, provider }) {
6642
6726
  }
6643
6727
  }
6644
6728
 
6729
+ // Does `branch` head an OPEN PR? Used by the agent-work branch GC, which must never delete a
6730
+ // PR's head branch (GitHub closes the PR). Tri-state: true / false, or null when unknown (non-
6731
+ // GitHub provider, gh missing/failing, unparsable output) — the GC treats null as "keep".
6732
+ // Async (not spawnSync) so a slow gh never blocks the event loop; aborts with the GC signal.
6733
+ function ghHasOpenPr({ cwd, token, branch, provider = 'github', signal = null, timeoutMs = 30_000, spawnImpl = spawn }) {
6734
+ if (provider !== 'github') return Promise.resolve(null);
6735
+ return new Promise((resolve) => {
6736
+ let stdout = '';
6737
+ let done = false;
6738
+ // Declared BEFORE the spawn so a synchronous spawn throw (invalid cwd/options) reaching
6739
+ // finish() never reads `timer` in its TDZ (a ReferenceError instead of the tri-state null).
6740
+ let timer = null;
6741
+ const finish = (v) => { if (!done) { done = true; if (timer) clearTimeout(timer); resolve(v); } };
6742
+ let child;
6743
+ try {
6744
+ child = spawnImpl('gh', ['pr', 'list', '--head', branch, '--state', 'open', '--json', 'number', '--limit', '1'],
6745
+ { cwd, env: ghAuthEnv(token, cwd), stdio: ['ignore', 'pipe', 'ignore'], signal: signal || undefined });
6746
+ } catch { finish(null); return; }
6747
+ timer = setTimeout(() => { try { child.kill('SIGKILL'); } catch { /* gone */ } finish(null); }, timeoutMs);
6748
+ timer.unref?.();
6749
+ child.stdout?.on('data', (d) => { stdout += d; });
6750
+ child.on('error', () => finish(null));
6751
+ child.on('close', (code) => {
6752
+ if (code !== 0) return finish(null);
6753
+ try {
6754
+ const arr = JSON.parse(stdout.trim() || 'null');
6755
+ finish(Array.isArray(arr) ? arr.length > 0 : null);
6756
+ } catch { finish(null); }
6757
+ });
6758
+ });
6759
+ }
6760
+
6645
6761
  // Build the gh environment for PR-side calls: inject the resolved job token, or
6646
6762
  // (anonymous path) scrub every ambient gh credential so we can only use what we
6647
6763
  // were explicitly handed. Scrubbing the token env vars alone is not enough — gh
@@ -6768,6 +6884,8 @@ async function setupWorkspaceCheckpoints({ provisioned, envelope = null, token =
6768
6884
  restoreCheckpoint: restoreCp = restoreCheckpoint,
6769
6885
  deleteCheckpointRef: deleteCp = deleteCheckpointRef,
6770
6886
  sweep = sweepStaleCheckpoints,
6887
+ sweepAgentWork = sweepStaleAgentWorkBranches,
6888
+ hasOpenPr: openPr = ghHasOpenPr,
6771
6889
  now = () => Date.now(),
6772
6890
  } = deps;
6773
6891
  const log = {
@@ -7037,6 +7155,23 @@ async function setupWorkspaceCheckpoints({ provisioned, envelope = null, token =
7037
7155
  else if (sweepAbort.signal.aborted) log.debug(`checkpoint GC bounded at ${GC_OVERALL_TIMEOUT_MS}ms — aborted its in-flight git and drained; leftover refs reclaimed on a later sweep.`);
7038
7156
  else if (r?.error) log.debug(`checkpoint GC skipped — ${redactToken(oneLineLog(r.error), token)}.`);
7039
7157
  }, (err) => log.debug(`checkpoint GC threw — ${redactToken(oneLineLog(err?.message || err), token)}.`))
7158
+ // Reclaim orphaned `nano/agent-work/*` fallback branches in the SAME scratch repo, sharing
7159
+ // the deadline/abort (issue #231). Chained (not raced) so `close()`/`discard()` await
7160
+ // both sweeps before the scratch dir is reaped. Never loses work: open-PR heads are kept,
7161
+ // contained tips are deleted, unmerged tips are archived first. Failures stay debug-level.
7162
+ .then(() => sweepAgentWork({
7163
+ git: sweepGit, ttlMs: cfg.ttlMs, archiveTtlMs: cfg.agentWorkArchiveTtlMs, now, signal: sweepAbort.signal,
7164
+ // gh resolves the repo from the scratch repo's `origin`. Unknown (null) => branch kept.
7165
+ hasOpenPr: (branch) => openPr({ cwd: sweepDir, token, branch, provider: envelope?.repository?.provider || 'github', signal: sweepAbort.signal }),
7166
+ }))
7167
+ .then((r) => {
7168
+ if (r?.deleted?.length) logger.info?.(`${prefix} (${corr}): reclaimed ${r.deleted.length} orphaned agent-work branch(es): ${r.deleted.map((d) => `${d.ref} [${d.why}]`).join(', ')}.`);
7169
+ if (r?.purged?.length) logger.info?.(`${prefix} (${corr}): purged ${r.purged.length} expired agent-work archive ref(s): ${r.purged.map((d) => d.ref).join(', ')}.`);
7170
+ if (r?.kept?.length) log.debug(`agent-work branch GC kept ${r.kept.length} stale branch(es): ${r.kept.map((k) => `${k.ref} [${k.why}]`).join(', ')}.`);
7171
+ if (r?.deleted?.length || r?.purged?.length) return;
7172
+ if (sweepAbort.signal.aborted) log.debug(`agent-work branch GC bounded at ${GC_OVERALL_TIMEOUT_MS}ms — aborted its in-flight git and drained; leftover branches reclaimed on a later sweep.`);
7173
+ else if (r?.error) log.debug(`agent-work branch GC skipped — ${redactToken(oneLineLog(r.error), token)}.`);
7174
+ }, (err) => log.debug(`agent-work branch GC threw — ${redactToken(oneLineLog(err?.message || err), token)}.`))
7040
7175
  .finally(() => { clearTimeout(deadlineTimer); if (sweepDir) { try { rmSync(sweepDir, { recursive: true, force: true }); } catch { /* best effort */ } } });
7041
7176
  } catch (err) {
7042
7177
  if (sweepDir) { try { rmSync(sweepDir, { recursive: true, force: true }); } catch { /* best effort */ } }
@@ -9139,6 +9274,7 @@ function spawnCaptureAcp({ command, args = [], cwd, env, stdinData, timeoutMs, i
9139
9274
  let childClosed = null; // { code, signal } once the child exits
9140
9275
  let promptResolved = false; // the main session/prompt turn sent + resolved
9141
9276
  let acpOutcome = null; // the turn's `_meta.outcome`, if the agent reported one
9277
+ let acpStopReason = null; // the turn's ACP `stopReason` (#301)
9142
9278
  let settleTimer = null; // post-turn grace before force-reaping a lingering agent
9143
9279
  // One-time warning latch for the reserved escalate/filter policies so the
9144
9280
  // deferral is observable (not silent) but never spams a warning per request.
@@ -9245,6 +9381,7 @@ function spawnCaptureAcp({ command, args = [], cwd, env, stdinData, timeoutMs, i
9245
9381
  // floor (thread 4118913047).
9246
9382
  const floorOnly = floorEmitted && !sawRealTranscript;
9247
9383
  let resolved = acpOutcome ? { ...result, acpOutcome } : result;
9384
+ if (acpStopReason) resolved = { ...resolved, stopReason: acpStopReason };
9248
9385
  if (floorOnly) resolved = { ...resolved, acpTranscriptFloorOnly: true };
9249
9386
  resolve(resolved);
9250
9387
  };
@@ -9709,6 +9846,7 @@ function spawnCaptureAcp({ command, args = [], cwd, env, stdinData, timeoutMs, i
9709
9846
  prompt: [{ type: 'text', text: String(stdinData ?? '') }],
9710
9847
  });
9711
9848
  acpOutcome = acpOutcomeFrom(prompted);
9849
+ acpStopReason = acpStopReasonFrom(prompted);
9712
9850
  // End-of-turn: the main session/prompt request resolved. Mark it so the
9713
9851
  // `close` handler can tell a completed turn from an early/handshake exit.
9714
9852
  promptResolved = true;
@@ -10140,6 +10278,12 @@ function buildResultEnvelope(result, { sandbox, image, git, result: agentResult,
10140
10278
  // The agent's explicit ACP end-of-task report (`_meta.outcome`), host-recorded
10141
10279
  // alongside whatever result vars it returned.
10142
10280
  if (result.acpOutcome) env.outcome = result.acpOutcome;
10281
+ // #301: why the (first) ACP turn ended — `end_turn` or a budget cut-off. After a
10282
+ // nudge this is the EFFECTIVE reason (the nudge's when it was truncated), and the
10283
+ // nudge turn's own reason is recorded separately so the audit shows both turns.
10284
+ if (result.stopReason) env.stopReason = result.stopReason;
10285
+ if (result.nudgeStopReason) env.nudgeStopReason = result.nudgeStopReason;
10286
+ if (result.budgetDowngraded) env.budgetDowngraded = true;
10143
10287
  // Audit (issue #63): record which linked-resource key supplied the base prompt.
10144
10288
  // The engine only keeps `latest` per resourceId (no pinning), so recording the
10145
10289
  // resolved key is the only reproducibility handle for which prompt version ran.
@@ -13375,7 +13519,7 @@ async function workAgent(req, flags, ctx) {
13375
13519
  // the result is recoverable only via the stdout `::nano:result::`
13376
13520
  // sentinel, which `resolveAgentResultWithNudge` handles directly.
13377
13521
  if (result.ok) {
13378
- const { stdout, nudged, truncated, acpOutcome, transcriptFloorOnly } = await resolveAgentResultWithNudge({
13522
+ const { stdout, nudged, truncated, acpOutcome, transcriptFloorOnly, stopReason: effectiveStopReason, nudgeStopReason } = await resolveAgentResultWithNudge({
13379
13523
  result,
13380
13524
  resultFile,
13381
13525
  logger,
@@ -13407,6 +13551,15 @@ async function workAgent(req, flags, ctx) {
13407
13551
  // Adopt the nudge turn's outcome so the escalation / envelope reflect
13408
13552
  // the latest continuation, not only the first turn (#263).
13409
13553
  result.acpOutcome = acpOutcome;
13554
+ // Adopt the EFFECTIVE stopReason (#301, Copilot review on #302,
13555
+ // discussion_r4464312610): when the nudge turn was itself cut off
13556
+ // (e.g. first turn `end_turn`, nudge `max_turn_requests`), the
13557
+ // delivery check + logs/audit must reflect the truncated nudge turn,
13558
+ // not only the first turn. `effectiveStopReason` is the nudge's reason
13559
+ // when truncated, else the first turn's. Record the nudge's own reason
13560
+ // separately for audit.
13561
+ if (effectiveStopReason) result.stopReason = effectiveStopReason;
13562
+ if (nudgeStopReason) result.nudgeStopReason = nudgeStopReason;
13410
13563
  }
13411
13564
  }
13412
13565
 
@@ -13643,11 +13796,21 @@ async function workAgent(req, flags, ctx) {
13643
13796
  // outputs. Read before deleting the temp dir.
13644
13797
  // Last resort: vars implied by the agent's ACP `_meta.outcome` (a `blocked`
13645
13798
  // report → an escalation) when it wrote no result of its own.
13646
- const rawResult = pickAgentResult(
13799
+ let rawResult = pickAgentResult(
13647
13800
  () => readAgentResultFile(resultFile),
13648
13801
  () => parseResultFromStdout(result.stdout),
13649
13802
  () => resultVarsFromAcpOutcome(result.acpOutcome),
13650
13803
  );
13804
+ // #301: a turn cut off by its budget is never recorded as a success
13805
+ // unless the work was verifiably delivered (PR found / commits pushed).
13806
+ {
13807
+ const honest = downgradeBudgetStopResult(rawResult, { stopReason: result.stopReason, git: gitResult });
13808
+ if (honest !== rawResult) {
13809
+ logger.warn(`[${jobType}] job ${job.jobKey}: turn ended with stopReason=${result.stopReason} and the work was not delivered — recording status "blocked" instead of ${JSON.stringify(rawResult?.status ?? null)}`);
13810
+ rawResult = honest;
13811
+ result.budgetDowngraded = true;
13812
+ }
13813
+ }
13651
13814
  if (resultDir) { try { rmSync(resultDir, { recursive: true, force: true }); } catch { /* best effort */ } liveRunDirs.delete(resultDir); }
13652
13815
  const resultVars = sanitizeResultVars(rawResult);
13653
13816
 
@@ -13656,7 +13819,7 @@ async function workAgent(req, flags, ctx) {
13656
13819
  const gitNote = gitResult
13657
13820
  ? ` [${gitResult.branch ? `branch ${gitResult.branch}` : 'detached HEAD'}: ${gitResult.commits.length} commit(s), ${gitResult.branch ? (gitResult.pushed ? 'pushed' : (gitResult.pushFailed ? 'push FAILED' : 'not pushed')) : 'no branch to push'}${gitResult.pr?.found ? `, PR #${gitResult.pr.number}` : ''}]`
13658
13821
  : '';
13659
- logger.info(`[${jobType}] job ${job.jobKey} complete (exit 0)${result.truncated ? ' [output truncated]' : ''}${gitNote}`);
13822
+ logger.info(`[${jobType}] job ${job.jobKey} complete (exit 0)${result.stopReason ? ` [stopReason=${result.stopReason}]` : ''}${result.truncated ? ' [output truncated]' : ''}${gitNote}`);
13660
13823
  if (gitResult?.pushFailed) {
13661
13824
  // Elevate a push failure from a terse info tail to a loud, actionable
13662
13825
  // error naming the stranded commit SHAs (issue #231): these commits are
@@ -20064,6 +20227,7 @@ export {
20064
20227
  sanitizeBranchSegment,
20065
20228
  shouldPreserveRunDir,
20066
20229
  setupWorkspaceCheckpoints,
20230
+ ghHasOpenPr,
20067
20231
  computeRelayCloseReason,
20068
20232
  describeGitFailure,
20069
20233
  boundGitOutput,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "c8ctl-plugin-nano",
3
- "version": "1.70.5",
3
+ "version": "1.70.7",
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.70.5",
80
- "@nanobpm/c8ctl-plugin-nano-darwin-x64": "1.70.5",
81
- "@nanobpm/c8ctl-plugin-nano-linux-x64": "1.70.5",
82
- "@nanobpm/c8ctl-plugin-nano-linux-arm64": "1.70.5",
83
- "@nanobpm/c8ctl-plugin-nano-linux-armv7": "1.70.5",
84
- "@nanobpm/c8ctl-plugin-nano-linux-armv6": "1.70.5",
85
- "@nanobpm/c8ctl-plugin-nano-win32-x64": "1.70.5"
79
+ "@nanobpm/c8ctl-plugin-nano-darwin-arm64": "1.70.7",
80
+ "@nanobpm/c8ctl-plugin-nano-darwin-x64": "1.70.7",
81
+ "@nanobpm/c8ctl-plugin-nano-linux-x64": "1.70.7",
82
+ "@nanobpm/c8ctl-plugin-nano-linux-arm64": "1.70.7",
83
+ "@nanobpm/c8ctl-plugin-nano-linux-armv7": "1.70.7",
84
+ "@nanobpm/c8ctl-plugin-nano-linux-armv6": "1.70.7",
85
+ "@nanobpm/c8ctl-plugin-nano-win32-x64": "1.70.7"
86
86
  }
87
87
  }