gcf-harness-aif-ext 0.28.0 → 0.28.1

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.
@@ -197,22 +197,7 @@ function milestoneStop(report) {
197
197
  export function nextPlan(report, count, skip = []) {
198
198
  const stop = milestoneStop(report);
199
199
  if (stop) return { ids: [], mode: null, units: [], stop };
200
- const scope = inScope(report);
201
- const batch = [];
202
- const ready = (report.items ?? [])
203
- .filter((i) => i.status === 'ready' && !i.running && i.type !== 'feature')
204
- .filter((i) => i.type !== 'release' && (!scope || scope.has(i.id)) && !skip.includes(i.id))
205
- .sort((a, b) => rank(a) - rank(b));
206
- // One run mode a batch: an autopilot starts it as one run, a main one in the checkout.
207
- let mode = null;
208
- for (const i of ready) {
209
- if (batch.length >= count) break;
210
- if (mode && (i.run_mode ?? mode) !== mode) continue;
211
- if (gate(report, [...batch, i.id]).pass) {
212
- batch.push(i.id);
213
- mode ??= i.run_mode ?? null;
214
- }
215
- }
200
+ const { batch, mode } = takeBatch(report, readyOf(report, inScope(report), skip), count);
216
201
 
217
202
  const building = (report.milestones ?? []).find((m) => m.name === report.build_milestone);
218
203
  const units = (building?.units ?? [])
@@ -232,6 +217,30 @@ export function nextPlan(report, count, skip = []) {
232
217
  return { ids: batch, mode, units, stop: empty };
233
218
  }
234
219
 
220
+ /** The ready items an autopilot may take, in scope and not skipped, by priority. */
221
+ const readyOf = (report, scope, skip) =>
222
+ (report.items ?? [])
223
+ .filter((i) => i.status === 'ready' && !i.running && i.type !== 'feature')
224
+ .filter((i) => i.type !== 'release' && (!scope || scope.has(i.id)) && !skip.includes(i.id))
225
+ .sort((a, b) => rank(a) - rank(b));
226
+
227
+ /** Up to `count` of `ready`, each while the batch with it still passes the gate. */
228
+ function takeBatch(report, ready, count) {
229
+ const batch = [];
230
+ // One run mode a batch: an autopilot starts it as one run, a main one in the checkout.
231
+ let mode = null;
232
+ for (const i of ready) {
233
+ if (batch.length >= count) break;
234
+ if (mode && (i.run_mode ?? mode) !== mode) continue;
235
+ if (gate(report, [...batch, i.id]).pass) {
236
+ batch.push(i.id);
237
+ mode ??= i.run_mode ?? null;
238
+ }
239
+ }
240
+
241
+ return { batch, mode };
242
+ }
243
+
235
244
  /** The ids of `nextPlan`: what a board's Run offers. */
236
245
  export const nextBatch = (report, count) => nextPlan(report, count).ids;
237
246
 
@@ -295,7 +304,7 @@ export function withMainQueue(report, runs) {
295
304
  function auditReport() {
296
305
  // Re-enter the same ai-factory CLI that is running this command: no PATH or .cmd lookup.
297
306
  const args = [process.argv[1], 'gcf', 'audit', '--json'];
298
- const res = spawnSync(process.execPath, args, { encoding: 'utf8' });
307
+ const res = spawnSync(process.execPath, args, { windowsHide: true, encoding: 'utf8' });
299
308
  try {
300
309
  return withMainQueue(JSON.parse(res.stdout), path.join(process.cwd(), '.gcf-session', 'runs'));
301
310
  } catch (err) {
@@ -557,7 +566,32 @@ export function register(program) {
557
566
  .action(runGate);
558
567
 
559
568
  registerRun(harness);
569
+ registerNext(harness);
570
+ registerCard(harness);
571
+ harness
572
+ .command('metrics')
573
+ .description('Run metrics from gcf/.metrics: reached moves, cost, plan checks, DoD, guards')
574
+ .option('--since <date>', 'only lines at or after this ISO date or time')
575
+ .option('--json', 'machine output')
576
+ .action(metricsCommand);
577
+ harness
578
+ .command('runs')
579
+ .description('Past runs from gcf/.metrics/run-log.csv, the latest first: items, results, cost')
580
+ .option('--item <id>', 'only the runs that hold this item')
581
+ .option('--limit <n>', 'at most this many runs', '50')
582
+ .option('--json', 'machine output: {runs: [...]}')
583
+ .action(runsCommand);
584
+ harness
585
+ .command('stop <id>')
586
+ .description('Stop the session that works an item; the run goes on, the item stays ready')
587
+ .action((id) => console.log(stopRun(process.cwd(), id)));
588
+ registerHold(harness);
589
+ registerPlanReview(harness);
590
+ registerChat(harness);
591
+ }
560
592
 
593
+ /** `gcf-harness next`: what can run together now, or an autopilot's plan. */
594
+ function registerNext(harness) {
561
595
  harness
562
596
  .command('next [count]')
563
597
  .description('The ready items that can run together now, by priority (the gate decides)')
@@ -588,6 +622,10 @@ export function register(program) {
588
622
  o.json ? JSON.stringify(ids) : ids.join('\n') || plan.stop?.text || 'nothing can run now',
589
623
  );
590
624
  });
625
+ }
626
+
627
+ /** `gcf-harness card`: design units into work, one agent session on main. */
628
+ function registerCard(harness) {
591
629
  harness
592
630
  .command('card <units...>')
593
631
  .description(
@@ -615,26 +653,6 @@ export function register(program) {
615
653
  process.exitCode = 1;
616
654
  }
617
655
  });
618
- harness
619
- .command('metrics')
620
- .description('Run metrics from gcf/.metrics: reached moves, cost, plan checks, DoD, guards')
621
- .option('--since <date>', 'only lines at or after this ISO date or time')
622
- .option('--json', 'machine output')
623
- .action(metricsCommand);
624
- harness
625
- .command('runs')
626
- .description('Past runs from gcf/.metrics/run-log.csv, the latest first: items, results, cost')
627
- .option('--item <id>', 'only the runs that hold this item')
628
- .option('--limit <n>', 'at most this many runs', '50')
629
- .option('--json', 'machine output: {runs: [...]}')
630
- .action(runsCommand);
631
- harness
632
- .command('stop <id>')
633
- .description('Stop the session that works an item; the run goes on, the item stays ready')
634
- .action((id) => console.log(stopRun(process.cwd(), id)));
635
- registerHold(harness);
636
- registerPlanReview(harness);
637
- registerChat(harness);
638
656
  }
639
657
 
640
658
  /** `gcf-harness plan-review`: the outside reviewer's pass of a plan (Hold-Plan d17). */
@@ -899,14 +917,22 @@ export const itemLine = (i) =>
899
917
  i.process,
900
918
  i.shelved && `${i.shelved.id}'s work went to ${i.shelved.branch}`,
901
919
  i.returned && `its work came back with ${i.conflicts?.length ?? 0} conflict(s)`,
902
- i.build &&
903
- !i.build.ok &&
904
- !i.build.moved_on &&
905
- `no build to play: ${i.build.problem.split('\n')[0]}`,
906
- i.build?.dirtied?.length && `its build changed ${i.build.dirtied.join(', ')}`,
920
+ ...buildNotes(i),
907
921
  ]
908
922
  .filter(Boolean)
909
- .join(' — ') + (i.lessons ? `, ${i.lessons} lesson${i.lessons > 1 ? 's' : ''}` : '');
923
+ .join(' — ') + lessonsNote(i);
924
+
925
+ /** What an item's line says of its build: none to play, or the files it changed. */
926
+ const buildNotes = (i) => [
927
+ i.build &&
928
+ !i.build.ok &&
929
+ !i.build.moved_on &&
930
+ `no build to play: ${i.build.problem.split('\n')[0]}`,
931
+ i.build?.dirtied?.length && `its build changed ${i.build.dirtied.join(', ')}`,
932
+ ];
933
+
934
+ /** The lessons an item's sessions left, at its line's end; empty without any. */
935
+ const lessonsNote = (i) => (i.lessons ? `, ${i.lessons} lesson${i.lessons > 1 ? 's' : ''}` : '');
910
936
 
911
937
  /**
912
938
  * The deny rule the last refusal in an item's run chat named (`kind: pattern`), or null: the
@@ -964,16 +990,23 @@ const failed = (r) =>
964
990
  r.items.some((i) => ['conflict', 'error'].includes(i.result)) ||
965
991
  r.orphans.some((o) => o.conflict || o.error);
966
992
 
993
+ /** The minutes of `--timeout` and `--chat-timeout`; a bad option, `--mode` too, throws. */
994
+ function runMinutes(opts) {
995
+ const minutes = opts.timeout === undefined ? undefined : Number(opts.timeout);
996
+ if (minutes !== undefined && !(minutes > 0))
997
+ throw new Error('--timeout is a number of minutes above 0');
998
+ if (opts.mode && !['worktree', 'main'].includes(opts.mode))
999
+ throw new Error('--mode is worktree or main');
1000
+ const answer = opts.chatTimeout === undefined ? null : Number(opts.chatTimeout);
1001
+ if (answer !== null && !(answer >= 0))
1002
+ throw new Error('--chat-timeout is a number of minutes, 0 or more');
1003
+
1004
+ return { minutes, answer };
1005
+ }
1006
+
967
1007
  async function runItems(ids, opts) {
968
1008
  try {
969
- const minutes = opts.timeout === undefined ? undefined : Number(opts.timeout);
970
- if (minutes !== undefined && !(minutes > 0))
971
- throw new Error('--timeout is a number of minutes above 0');
972
- if (opts.mode && !['worktree', 'main'].includes(opts.mode))
973
- throw new Error('--mode is worktree or main');
974
- const answer = opts.chatTimeout === undefined ? null : Number(opts.chatTimeout);
975
- if (answer !== null && !(answer >= 0))
976
- throw new Error('--chat-timeout is a number of minutes, 0 or more');
1009
+ const { minutes, answer } = runMinutes(opts);
977
1010
  // The true-case path: Claude Code trusts a folder by its exact path, and a shell or a board
978
1011
  // may hand over c: for C:, which turns off every allow rule of the project.
979
1012
  const r = await run(realpathSync.native(process.cwd()), [...new Set(ids)], {
@@ -45,6 +45,7 @@ export function planReview(projectDir, o) {
45
45
  ...['--output-schema', FINDINGS_SCHEMA, '-o', out],
46
46
  ];
47
47
  const res = spawnSync(exe, [...pre, ...args], {
48
+ windowsHide: true,
48
49
  cwd: projectDir,
49
50
  input: reviewPrompt(o.id, o.plan),
50
51
  encoding: 'utf8',
@@ -67,7 +68,11 @@ export function planReview(projectDir, o) {
67
68
  function reviewerMissing(cfg, exe, pre, shell) {
68
69
  if (cfg.agent === 'none') return 'plan_review.agent is none';
69
70
  if (cfg.agent !== 'codex') return `no reviewer named ${cfg.agent}: only codex runs`;
70
- const version = spawnSync(exe, [...pre, '--version'], { encoding: 'utf8', shell });
71
+ const version = spawnSync(exe, [...pre, '--version'], {
72
+ windowsHide: true,
73
+ encoding: 'utf8',
74
+ shell,
75
+ });
71
76
 
72
77
  return version.error || version.status !== 0 ? 'no codex in PATH' : null;
73
78
  }
package/commands/run.js CHANGED
@@ -58,7 +58,8 @@ export const DEFAULT_ANSWER =
58
58
  * not even the one the agent recommended.
59
59
  */
60
60
  export const D1_ANSWER =
61
- "No answer came in time: this question is the operator's to answer. Block the item with it and pick nothing.";
61
+ "No answer came in time: this question is the operator's to answer. " +
62
+ 'Block the item with it and pick nothing.';
62
63
 
63
64
  /** The denial of a question card in a run that asks the operator nothing (`chat.ask: none`). */
64
65
  export const ASK_NONE =
@@ -102,6 +103,7 @@ export function cliCore(projectDir) {
102
103
  // `cwd`: another checkout of the project, a worktree whose plan is on its branch.
103
104
  return (args, { cwd = projectDir } = {}) => {
104
105
  const res = spawnSync(process.execPath, [process.argv[1], 'gcf', ...args], {
106
+ windowsHide: true,
105
107
  cwd,
106
108
  encoding: 'utf8',
107
109
  });
@@ -249,6 +251,7 @@ const branchRef = (id) => `refs/heads/work/${id}`;
249
251
  function verified(dir, id) {
250
252
  const format = '--format=%(trailers:key=GCF-Verified,valueonly)';
251
253
  const res = spawnSync('git', ['log', '-1', format, branchRef(id)], {
254
+ windowsHide: true,
252
255
  cwd: dir,
253
256
  encoding: 'utf8',
254
257
  });
@@ -298,7 +301,14 @@ async function claimAll(ids, logs) {
298
301
  }
299
302
 
300
303
  // A dead run's stop mark goes; one from now on stops the item's session as it starts.
301
- await rm(stopOf(logs, id), { force: true });
304
+ try {
305
+ await rm(stopOf(logs, id), { force: true });
306
+ } catch (e) {
307
+ // The caller gets no list to release on a throw: every lock taken so far goes back here.
308
+ for (const r of [{ release }, ...claimed]) await r.release();
309
+ throw e;
310
+ }
311
+
302
312
  claimed.push({ id, release });
303
313
  }
304
314
 
@@ -546,12 +556,20 @@ const taskOf = (r, launch, after) => {
546
556
  // A session that is no item's /gcf-run (a card session) brings its own task.
547
557
  if (r.task) return r.task;
548
558
  const gates = launch?.gatesOf?.(r.id) ?? null;
549
- const assume = gates?.question === 'assume';
550
- const ask = assume ? null : launch?.chat?.ask;
551
559
 
552
560
  return (
553
561
  `/gcf-run ${r.id}${r.main ? '' : ' --worktree'}` +
554
562
  (after ? ' --no-lessons' : '') +
563
+ gateFlags(gates, launch)
564
+ );
565
+ };
566
+
567
+ /** The `--ask`, `--assume` and `--decide` of a session's /gcf-run, by its gates and chat. */
568
+ const gateFlags = (gates, launch) => {
569
+ const assume = gates?.question === 'assume';
570
+ const ask = assume ? null : launch?.chat?.ask;
571
+
572
+ return (
555
573
  (ask && ask !== 'none' ? ` --ask ${ask}` : '') +
556
574
  (assume ? ' --assume' : '') +
557
575
  (gates?.decision === 'agent' ? ' --decide' : '')
@@ -1129,7 +1147,12 @@ const GCF_IDENT = {
1129
1147
  function unverify(r) {
1130
1148
  if (!verified(r.dir, r.id)) return null;
1131
1149
  const git = (args, env = {}) =>
1132
- spawnSync('git', args, { cwd: r.dir, encoding: 'utf8', env: { ...process.env, ...env } });
1150
+ spawnSync('git', args, {
1151
+ windowsHide: true,
1152
+ cwd: r.dir,
1153
+ encoding: 'utf8',
1154
+ env: { ...process.env, ...env },
1155
+ });
1133
1156
  const ref = branchRef(r.id);
1134
1157
  const tip = git(['rev-parse', ref]).stdout.trim();
1135
1158
  const tree = ['commit-tree', `${ref}^{tree}`, '-p', ref, '-m', `gcf(unverified): ${r.id}`];
@@ -1274,6 +1297,7 @@ const MOVE_OF = {
1274
1297
  export function moveOfCommit(projectDir, id) {
1275
1298
  const grep = String.raw`--grep=^gcf\((submit|close|block|decide)\): (go |no )?` + `${id}( |$)`;
1276
1299
  const res = spawnSync('git', ['log', '-1', '-E', grep, '--format=%s'], {
1300
+ windowsHide: true,
1277
1301
  cwd: projectDir,
1278
1302
  encoding: 'utf8',
1279
1303
  });
@@ -1364,22 +1388,7 @@ async function runMain(projectDir, ids, releaseMain, ctx) {
1364
1388
 
1365
1389
  items.push(await mainItem(projectDir, id, { ...ctx, dequeue }));
1366
1390
  // Only now does the folder hold this card and nothing else: the next one waits for its build.
1367
- if (
1368
- !items.at(-1).shelve &&
1369
- items.at(-1).started !== false &&
1370
- (await buildsNow(ctx, id, 'main'))
1371
- ) {
1372
- // Compared here: a build that failed or was stopped leaves its changes without a report.
1373
- const before = loosePaths(projectDir, { files: true }) ?? [];
1374
- const built = await buildStep(ctx, id, { lock: MAIN_RUN });
1375
- const fresh = (loosePaths(projectDir, { files: true }) ?? []).filter(
1376
- (p) => !before.includes(p),
1377
- );
1378
- items.at(-1).build = {
1379
- ...built,
1380
- dirtied: [...new Set([...(built.dirtied ?? []), ...fresh])],
1381
- };
1382
- }
1391
+ await buildOnMain(projectDir, ctx, id, items.at(-1));
1383
1392
 
1384
1393
  if (!items.at(-1).shelve) await postEnd(ctx, items.at(-1));
1385
1394
  const left = items.at(-1).shelve
@@ -1401,6 +1410,19 @@ async function runMain(projectDir, ids, releaseMain, ctx) {
1401
1410
  return items;
1402
1411
  }
1403
1412
 
1413
+ /** A main run's card `item` built in the checkout, when it is built now: its build rides on it. */
1414
+ async function buildOnMain(projectDir, ctx, id, item) {
1415
+ if (item.shelve || item.started === false || !(await buildsNow(ctx, id, 'main'))) return;
1416
+ // Compared here: a build that failed or was stopped leaves its changes without a report.
1417
+ const before = loosePaths(projectDir, { files: true }) ?? [];
1418
+ const built = await buildStep(ctx, id, { lock: MAIN_RUN });
1419
+ const fresh = (loosePaths(projectDir, { files: true }) ?? []).filter((p) => !before.includes(p));
1420
+ item.build = {
1421
+ ...built,
1422
+ dirtied: [...new Set([...(built.dirtied ?? []), ...fresh])],
1423
+ };
1424
+ }
1425
+
1404
1426
  /**
1405
1427
  * The checkout's uncommitted paths outside `gcf/` and `GLOSSARY.md`, untracked ones too (a new
1406
1428
  * folder as one): a main run's code lands among them, so the board warns before its click (Tails
@@ -1414,7 +1436,7 @@ export function loosePaths(dir, { files = false } = {}) {
1414
1436
  ...['--', '.'],
1415
1437
  ...[':(exclude)gcf', ':(exclude)GLOSSARY.md'],
1416
1438
  ];
1417
- const res = spawnSync('git', args, { cwd: dir, encoding: 'utf8' });
1439
+ const res = spawnSync('git', args, { windowsHide: true, cwd: dir, encoding: 'utf8' });
1418
1440
  if (res.status !== 0) return null;
1419
1441
  const parts = res.stdout.split('\0').filter(Boolean);
1420
1442
  const paths = [];
@@ -1472,8 +1494,8 @@ function dirtiedBy(item) {
1472
1494
  * Whether card `id` is built now (docs/Play-Plan.md d3, d4): a project that set up how to play, and
1473
1495
  * a card that waits for its verdict. In a worktree its move is not made yet: its gate and policy
1474
1496
  * say what the move will be.
1475
- * shortcut: a `defer` that A4 turns into a wait gets no build here; a click builds it, as the plan's
1476
- * risk 6 says. Sending the card's `live:` over the board would tell them apart.
1497
+ * shortcut: a `defer` that A4 turns into a wait gets no build here; a click builds it, as the
1498
+ * plan's risk 6 says. Sending the card's `live:` over the board would tell them apart.
1477
1499
  */
1478
1500
  async function buildsNow({ core }, id, mode) {
1479
1501
  try {
@@ -1559,6 +1581,7 @@ function buildResult(out, err, code) {
1559
1581
  /** Whether the folder's baseline names card `id`: its loose work can be shelved. */
1560
1582
  function folderHolds(dir, id) {
1561
1583
  const r = spawnSync('git', ['log', '-1', '--format=%s', 'refs/gcf/main-work', '--'], {
1584
+ windowsHide: true,
1562
1585
  cwd: dir,
1563
1586
  encoding: 'utf8',
1564
1587
  });
@@ -1811,6 +1834,7 @@ const folderReport = (folder) => ({
1811
1834
  function mergedSince(dir, id, head) {
1812
1835
  if (!head) return false;
1813
1836
  const r = spawnSync('git', ['log', '--format=%s', `${head}..HEAD`], {
1837
+ windowsHide: true,
1814
1838
  cwd: dir,
1815
1839
  encoding: 'utf8',
1816
1840
  });
@@ -1824,6 +1848,7 @@ function mergedSince(dir, id, head) {
1824
1848
 
1825
1849
  function headOf(dir) {
1826
1850
  const r = spawnSync('git', ['rev-parse', '--verify', '-q', 'HEAD'], {
1851
+ windowsHide: true,
1827
1852
  cwd: dir,
1828
1853
  encoding: 'utf8',
1829
1854
  });
@@ -1838,6 +1863,7 @@ function headOf(dir) {
1838
1863
  export function movedUnverified(dir, id, head) {
1839
1864
  if (!head) return false;
1840
1865
  const r = spawnSync('git', ['log', '--format=%s', `${head}..HEAD`], {
1866
+ windowsHide: true,
1841
1867
  cwd: dir,
1842
1868
  encoding: 'utf8',
1843
1869
  });
@@ -1945,6 +1971,27 @@ async function runWorktrees(claims, ctx) {
1945
1971
  };
1946
1972
 
1947
1973
  const runs = await Promise.all(ready.map(runOne));
1974
+ const items = await worktreeEnds(runs, failed, ctx, head);
1975
+
1976
+ // A worktree's session records no move: the chat hears of the one main recorded for it.
1977
+ if (ctx.launch?.chat)
1978
+ for (const i of items.filter((x) =>
1979
+ ['submit', 'close', 'block', 'decide', 'deferred'].includes(x.result),
1980
+ ))
1981
+ postTo(chatOut(logs, i.id), { type: 'step', step: 'move', move: i.result, ok: true });
1982
+ for (const r of runs)
1983
+ await remember(
1984
+ logs,
1985
+ r,
1986
+ items.find((i) => i.id === r.id),
1987
+ );
1988
+
1989
+ return endLines(ctx, items, runs);
1990
+ }
1991
+
1992
+ /** Each worktree item's end: refused, blocked, stalled, cut, merged, or what else befell it. */
1993
+ async function worktreeEnds(runs, failed, ctx, head) {
1994
+ const { core } = ctx;
1948
1995
  // Refused before a session: the metrics keep them out of the share (§11).
1949
1996
  const items = failed.map((f) => ({ ...f, started: false }));
1950
1997
  for (const r of runs) {
@@ -1966,40 +2013,35 @@ async function runWorktrees(claims, ctx) {
1966
2013
  // A branch another run merged meanwhile (a main run, at its end or a session's start): its
1967
2014
  // move is on the board.
1968
2015
  const now = open.length ? (json(await core(['board', '--json']), 'board').items ?? []) : [];
2016
+ const seen = { open, now, integrated, waits, head, projectDir: ctx.projectDir };
1969
2017
  for (const r of runs) {
1970
2018
  if (items.some((i) => i.id === r.id)) continue;
1971
- const after = now.find((i) => i.id === r.id);
1972
- // Only the integrator's own commit says the branch went in: a drop by hand is no merge.
1973
- const moved = open.includes(r) && !r.error && mergedSince(ctx.projectDir, r.id, head);
1974
- const gone = open.includes(r) && !moved && !after;
1975
- items.push(
1976
- moved
1977
- ? {
1978
- id: r.id,
1979
- result: after ? (MOVE_OF[after.status] ?? after.status) : 'close',
1980
- reason: 'its branch was merged by another run meanwhile',
1981
- }
1982
- : gone
1983
- ? { id: r.id, result: 'skipped', reason: 'it left the board meanwhile, by another move' }
1984
- : waits && verified(r.dir, r.id)
1985
- ? waiting(r)
1986
- : resultOf(r, integrated),
1987
- );
2019
+ items.push(lateEnd(r, seen));
1988
2020
  }
1989
2021
 
1990
- // A worktree's session records no move: the chat hears of the one main recorded for it.
1991
- if (ctx.launch?.chat)
1992
- for (const i of items.filter((x) =>
1993
- ['submit', 'close', 'block', 'decide', 'deferred'].includes(x.result),
1994
- ))
1995
- postTo(chatOut(logs, i.id), { type: 'step', step: 'move', move: i.result, ok: true });
1996
- for (const r of runs)
1997
- await remember(
1998
- logs,
1999
- r,
2000
- items.find((i) => i.id === r.id),
2001
- );
2022
+ return items;
2023
+ }
2002
2024
 
2025
+ /** The end of a worktree run no block, stall or cut recorded: by its merge, or the board's. */
2026
+ function lateEnd(r, { open, now, integrated, waits, head, projectDir }) {
2027
+ const after = now.find((i) => i.id === r.id);
2028
+ // Only the integrator's own commit says the branch went in: a drop by hand is no merge.
2029
+ const moved = open.includes(r) && !r.error && mergedSince(projectDir, r.id, head);
2030
+ const gone = open.includes(r) && !moved && !after;
2031
+ if (moved)
2032
+ return {
2033
+ id: r.id,
2034
+ result: after ? (MOVE_OF[after.status] ?? after.status) : 'close',
2035
+ reason: 'its branch was merged by another run meanwhile',
2036
+ };
2037
+ if (gone)
2038
+ return { id: r.id, result: 'skipped', reason: 'it left the board meanwhile, by another move' };
2039
+
2040
+ return waits && verified(r.dir, r.id) ? waiting(r) : resultOf(r, integrated);
2041
+ }
2042
+
2043
+ /** The worktree items' report lines, each not left verified posted to its chat as its end. */
2044
+ async function endLines(ctx, items, runs) {
2003
2045
  // What each session spent rides on its item's line, when the agent reported it.
2004
2046
  const lines = items.map((i) => {
2005
2047
  const r = runs.find((x) => x.id === i.id);
@@ -2124,6 +2166,7 @@ export function statusPaths(out) {
2124
2166
  export function leftIn(dir, projectDir) {
2125
2167
  if (!dir || !existsSync(dir)) return null;
2126
2168
  const res = spawnSync('git', ['status', '--porcelain', '-z', '--untracked-files=all'], {
2169
+ windowsHide: true,
2127
2170
  cwd: dir,
2128
2171
  encoding: 'utf8',
2129
2172
  env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' },
@@ -2151,15 +2194,46 @@ const DOD = (ok) => (ok === true ? 'green' : ok === false ? 'red' : 'unknown');
2151
2194
  export function runEndOf(i, projectDir, launch = null) {
2152
2195
  const result = String(i.result ?? 'merged');
2153
2196
  const word = result.split(/[\s:(]/)[0];
2197
+ const outcome = endOutcome(i, result, word);
2198
+ const { unticked, handoff } = planMarks(launch?.planOf?.(i.id) ?? null, projectDir);
2199
+ const { dod, review } = lastChecks(launch?.events ?? []);
2200
+
2201
+ return {
2202
+ type: 'run_end',
2203
+ outcome,
2204
+ move: MOVES.includes(word) ? word : null,
2205
+ reason: endReason(i, outcome, word, result),
2206
+ ...spentOf(i, projectDir),
2207
+ unticked,
2208
+ lessons: i.lessons ?? 0,
2209
+ process: i.process ?? null,
2210
+ dod,
2211
+ review,
2212
+ left: workLeft(outcome, launch, projectDir),
2213
+ handoff,
2214
+ };
2215
+ }
2216
+
2217
+ /** The work a run left uncommitted in its worktree, at its end. */
2218
+ const workLeft = (outcome, launch, projectDir) =>
2219
+ // A branch that went in took its work along.
2220
+ outcome === 'submitted' ? null : leftIn(launch?.worktree, projectDir);
2221
+
2222
+ /** The outcome a run's end names, from its result word (`word`, of `result`). */
2223
+ function endOutcome(i, result, word) {
2154
2224
  // A stop is the operator's, a paused wait cut by it too; then a limit, then the result word.
2155
2225
  const stopped = /\bstopped\b/.test(result) && !OUTCOME[word]?.startsWith('sub');
2156
- const outcome = stopped
2157
- ? 'stopped'
2158
- : i.limit_resets !== undefined
2159
- ? 'paused'
2160
- : (OUTCOME[word] ??
2161
- (word === 'skipped' ? 'skipped' : word === 'merged' ? 'submitted' : 'no-result'));
2162
- const plan = launch?.planOf?.(i.id) ?? null;
2226
+ if (stopped) return 'stopped';
2227
+ if (i.limit_resets !== undefined) return 'paused';
2228
+
2229
+ return (
2230
+ OUTCOME[word] ??
2231
+ (word === 'skipped' ? 'skipped' : word === 'merged' ? 'submitted' : 'no-result')
2232
+ );
2233
+ }
2234
+
2235
+ /** The plan's tasks left unticked (null: no plan), and whether it holds a handoff to play. */
2236
+ function planMarks(plan, projectDir) {
2163
2237
  /** @type {number | null} */
2164
2238
  let unticked = null;
2165
2239
  let handoff = false;
@@ -2172,31 +2246,33 @@ export function runEndOf(i, projectDir, launch = null) {
2172
2246
  // Archived with its item: nothing left.
2173
2247
  }
2174
2248
 
2175
- const steps = (launch?.events ?? []).filter((e) => e.type === 'step');
2249
+ return { unticked, handoff };
2250
+ }
2251
+
2252
+ /** Why a run ended so, word for word. */
2253
+ const endReason = (i, outcome, word, result) =>
2254
+ // A failure says what failed first; a move without one says why it was made.
2255
+ (outcome === 'failed' ? (i.error ?? i.conflict ?? i.reason) : (i.reason ?? i.error)) ??
2256
+ i.skipped ??
2257
+ (OUTCOME[word] && word !== 'paused' ? null : result);
2258
+
2259
+ /** What a run cost and took, and main's commit at its end. */
2260
+ const spentOf = (i, projectDir) => ({
2261
+ cost_usd: i.cost_usd ?? null,
2262
+ duration_ms: i.duration_ms ?? null,
2263
+ commit: headOf(projectDir)?.slice(0, 7) ?? null,
2264
+ });
2265
+
2266
+ /** The run's last DoD and review among its chat's events. */
2267
+ function lastChecks(events) {
2268
+ const steps = events.filter((e) => e.type === 'step');
2176
2269
  const dod = steps.findLast((e) => e.step === 'dod');
2177
2270
  const review = steps.findLast((e) => e.step === 'review');
2178
2271
 
2179
2272
  return {
2180
- type: 'run_end',
2181
- outcome,
2182
- move: MOVES.includes(word) ? word : null,
2183
- // A failure says what failed first; a move without one says why it was made.
2184
- reason:
2185
- (outcome === 'failed' ? (i.error ?? i.conflict ?? i.reason) : (i.reason ?? i.error)) ??
2186
- i.skipped ??
2187
- (OUTCOME[word] && word !== 'paused' ? null : result),
2188
- cost_usd: i.cost_usd ?? null,
2189
- duration_ms: i.duration_ms ?? null,
2190
- commit: headOf(projectDir)?.slice(0, 7) ?? null,
2191
- unticked,
2192
- lessons: i.lessons ?? 0,
2193
- process: i.process ?? null,
2194
2273
  // null: the run reached no DoD, no review.
2195
2274
  dod: dod ? DOD(dod.ok) : null,
2196
2275
  review: review ? (review.ok === false ? 'failed' : 'done') : null,
2197
- // A branch that went in took its work along.
2198
- left: outcome === 'submitted' ? null : leftIn(launch?.worktree, projectDir),
2199
- handoff,
2200
2276
  };
2201
2277
  }
2202
2278
 
@@ -2255,6 +2331,7 @@ async function postEnd(ctx, item, worktree = null) {
2255
2331
  function droppedSince(projectDir, id) {
2256
2332
  const grep = String.raw`--grep=^gcf\(drop\): ` + `${id}( |$)`;
2257
2333
  const res = spawnSync('git', ['log', '-1', '-E', grep, '--format=%h'], {
2334
+ windowsHide: true,
2258
2335
  cwd: projectDir,
2259
2336
  encoding: 'utf8',
2260
2337
  });
@@ -2309,8 +2386,7 @@ async function cardUnits(
2309
2386
  waitLimit,
2310
2387
  } = {},
2311
2388
  ) {
2312
- const bad = units.find((id) => !/^[a-z0-9]+(-[a-z0-9]+)*$/.test(id));
2313
- if (bad) throw new Error(`${bad} is not a unit id (a lowercase hyphen slug)`);
2389
+ assertSlugs(units, 'a unit');
2314
2390
  if (!units.length) throw new Error('name the units to card');
2315
2391
  const logs = path.join(path.resolve(projectDir), '.gcf-session', 'runs');
2316
2392
  await mkdir(logs, { recursive: true });
@@ -2380,9 +2456,18 @@ const heldUnit = (u, ran) => ({
2380
2456
  ...(ran.reserve ? { reserve: ran.reserve } : {}),
2381
2457
  });
2382
2458
 
2383
- async function runBatch(
2459
+ /** An id names a lock file and goes into the agent's shell command: a slug, nothing else. */
2460
+ const assertSlugs = (ids, noun) => {
2461
+ const bad = ids.find((id) => !/^[a-z0-9]+(-[a-z0-9]+)*$/.test(id));
2462
+ if (bad) throw new Error(`${bad} is not ${noun} id (a lowercase hyphen slug)`);
2463
+ };
2464
+
2465
+ /**
2466
+ * What runBatch takes, with each default in place.
2467
+ * @param {string} projectDir
2468
+ */
2469
+ function batchOptions(
2384
2470
  projectDir,
2385
- ids,
2386
2471
  {
2387
2472
  core = cliCore(projectDir),
2388
2473
  agent = DEFAULT_AGENT,
@@ -2408,37 +2493,37 @@ async function runBatch(
2408
2493
  coreCommand = [process.execPath, process.argv[1], 'gcf'],
2409
2494
  },
2410
2495
  ) {
2411
- const startedAt = Date.now();
2412
- const started = new Date(startedAt).toISOString();
2413
- // An id names a lock file and goes into the agent's shell command: a slug, nothing else.
2414
- const bad = ids.find((id) => !/^[a-z0-9]+(-[a-z0-9]+)*$/.test(id));
2415
- if (bad) throw new Error(`${bad} is not an item id (a lowercase hyphen slug)`);
2416
- const override = { model, effort };
2417
- // A bad override is the run's error, before anything starts.
2418
- choiceOf(null, override);
2419
- const orphans = (await integrateNow(core)).results;
2420
- const logs = path.join(path.resolve(projectDir), '.gcf-session', 'runs');
2421
- await mkdir(logs, { recursive: true });
2422
- // The operator's own Run releases its cards' Hold (Hold-Plan d6); automation's does not.
2423
- if (!waitLimit) for (const id of ids) await rm(holdMarkOf(logs, id), { force: true });
2424
- const board = json(await core(['board', '--json']), 'board');
2425
- // Each item where it runs: one part per mode, in the order their items came.
2426
- const parts = [
2427
- ...Map.groupBy(ids, (id) =>
2428
- modeOf(
2429
- mode,
2430
- board,
2431
- board.items?.find((i) => i.id === id),
2432
- ),
2496
+ return {
2497
+ ...{ core, agent, gate, timeoutMs, mode, fresh, waitLimit, limitClock, managed },
2498
+ ...{ chat, model, effort, allow, coreCommand },
2499
+ };
2500
+ }
2501
+
2502
+ /** Each item where it runs: one part per mode, in the order their items came. */
2503
+ const partsOf = (ids, mode, board) => [
2504
+ ...Map.groupBy(ids, (id) =>
2505
+ modeOf(
2506
+ mode,
2507
+ board,
2508
+ board.items?.find((i) => i.id === id),
2433
2509
  ),
2434
- ];
2435
- timeoutMs ??= (board.session_timeout_min ?? DEFAULT_TIMEOUT_MIN) * 60_000;
2436
- // Before any item is claimed: a refusal here leaves no lock behind.
2437
- const launch = await launchOf(logs, managed, board, { chat, allow });
2438
- // One gate over the whole batch, and this run's holds go in with it: the gate counts the items
2439
- // other runs hold. A worktree part's locks; a main part's checkout with its queue, the items it
2440
- // has yet to reach.
2441
- const { passed, claims } = await admitted(logs, async () => {
2510
+ ),
2511
+ ];
2512
+
2513
+ /** Give back the holds of `held` (mode: the main release, or a worktree part's claims). */
2514
+ async function releaseHolds(held) {
2515
+ for (const [m, h] of held)
2516
+ if (m === 'main') await h?.();
2517
+ else for (const c of h.claimed) await c.release();
2518
+ }
2519
+
2520
+ /**
2521
+ * One gate over the whole batch, and this run's holds go in with it: the gate counts the items
2522
+ * other runs hold. A worktree part's locks; a main part's checkout with its queue, the items it
2523
+ * has yet to reach.
2524
+ */
2525
+ const admitBatch = (logs, gate, ids, parts) =>
2526
+ admitted(logs, async () => {
2442
2527
  const verdict = gate(ids);
2443
2528
  if (!verdict.pass) return { passed: verdict, claims: null };
2444
2529
  const held = new Map();
@@ -2447,82 +2532,121 @@ async function runBatch(
2447
2532
  held.set(m, m === 'main' ? await holdMain(logs, part) : await claimAll(part, logs));
2448
2533
  } catch (e) {
2449
2534
  // What was taken goes back: a hold the run never uses must not wait for its exit.
2450
- for (const [m, h] of held)
2451
- if (m === 'main') await h?.();
2452
- else for (const c of h.claimed) await c.release();
2535
+ await releaseHolds(held);
2453
2536
  throw e;
2454
2537
  }
2455
2538
 
2456
2539
  return { passed: verdict, claims: held };
2457
2540
  });
2541
+
2542
+ /** Each failed part's items end as errors, in their chat. */
2543
+ async function postFailed(ctx, parts, driven, error) {
2544
+ for (const [n, d] of driven.entries())
2545
+ if (d.status === 'rejected')
2546
+ for (const id of parts[n][1])
2547
+ await postEnd(
2548
+ ctx,
2549
+ { id, result: 'error', error },
2550
+ parts[n][0] === 'main' ? null : worktreeAt(ctx.projectDir, id),
2551
+ );
2552
+ }
2553
+
2554
+ /** A branch verified while main was held went in just now: its end is that merge's move. */
2555
+ async function postMerged(ctx, driven, after) {
2556
+ for (const d of driven)
2557
+ if (d.status === 'fulfilled')
2558
+ for (const i of d.value.filter((x) => x.result === 'verified')) {
2559
+ const merged = after.find((r) => r.id === i.id);
2560
+ const result = merged?.move ?? (merged?.conflict ? 'conflict' : i.result);
2561
+ await postEnd(
2562
+ ctx,
2563
+ { ...i, result, ...(merged?.conflict && { conflict: merged.conflict }) },
2564
+ worktreeAt(ctx.projectDir, i.id),
2565
+ );
2566
+ }
2567
+ }
2568
+
2569
+ /** Drive each admitted part to its end, then merge what main held back and close features. */
2570
+ async function driveParts(parts, claims, ctx, { orphans, started }) {
2571
+ const { projectDir, core } = ctx;
2572
+ // The run's id: its start alone does not keep two runs started at once apart.
2573
+ const runOf = { id: `${started}-${process.pid}`, started };
2574
+ // Each part to its end, a failing one too: the other's sessions are not left behind.
2575
+ const driven = await Promise.allSettled(
2576
+ parts.map(async ([m, part]) => {
2577
+ const items = await (m === 'main'
2578
+ ? runMain(projectDir, part, claims.get(m), ctx)
2579
+ : runWorktrees(claims.get(m), ctx));
2580
+ logMetrics(projectDir, 'run-log.csv', items.map(runRow(m, runOf)));
2581
+
2582
+ return items;
2583
+ }),
2584
+ );
2585
+ const failed = driven.find((d) => d.status === 'rejected');
2586
+ if (failed) {
2587
+ await postFailed(ctx, parts, driven, String(failed.reason?.message ?? failed.reason));
2588
+ throw failed.reason;
2589
+ }
2590
+
2591
+ // The branches worktree runs verified while a main part held the checkout go in now; a main
2592
+ // its session left dirty keeps them for the next run.
2593
+ const after = claims.has('main')
2594
+ ? (await integrateNow(core).catch(() => ({ results: [] }))).results
2595
+ : [];
2596
+ const features = await closeFinishedFeatures(core).catch(() => []);
2597
+ await postMerged(ctx, driven, after);
2598
+
2599
+ // `limit_wait`: this harness waits for a usage limit's reset itself (AD-19); a board reads it.
2600
+ return {
2601
+ orphans: [...orphans, ...after],
2602
+ mode: parts.map(([m]) => m).join('+'),
2603
+ items: driven.flatMap((d) => (d.status === 'fulfilled' ? d.value : [])),
2604
+ // The features this run finished, closed after it: their close or the core's refusal.
2605
+ features,
2606
+ limit_wait: true,
2607
+ };
2608
+ }
2609
+
2610
+ /**
2611
+ * @param {string} projectDir
2612
+ * @param {string[]} ids
2613
+ * @param {Parameters<typeof batchOptions>[1]} options
2614
+ */
2615
+ async function runBatch(projectDir, ids, options) {
2616
+ const o = batchOptions(projectDir, options);
2617
+ const { core, waitLimit } = o;
2618
+ const startedAt = Date.now();
2619
+ const started = new Date(startedAt).toISOString();
2620
+ assertSlugs(ids, 'an item');
2621
+ const override = { model: o.model, effort: o.effort };
2622
+ // A bad override is the run's error, before anything starts.
2623
+ choiceOf(null, override);
2624
+ const orphans = (await integrateNow(core)).results;
2625
+ const logs = path.join(path.resolve(projectDir), '.gcf-session', 'runs');
2626
+ await mkdir(logs, { recursive: true });
2627
+ // The operator's own Run releases its cards' Hold (Hold-Plan d6); automation's does not.
2628
+ if (!waitLimit) for (const id of ids) await rm(holdMarkOf(logs, id), { force: true });
2629
+ const board = json(await core(['board', '--json']), 'board');
2630
+ const parts = partsOf(ids, o.mode, board);
2631
+ const timeoutMs = o.timeoutMs ?? (board.session_timeout_min ?? DEFAULT_TIMEOUT_MIN) * 60_000;
2632
+ // Before any item is claimed: a refusal here leaves no lock behind.
2633
+ const launch = await launchOf(logs, o.managed, board, { chat: o.chat, allow: o.allow });
2634
+ const { passed, claims } = await admitBatch(logs, o.gate, ids, parts);
2458
2635
  if (!passed.pass) {
2459
2636
  const waits = passed.waits ? { waits: passed.waits } : {};
2460
2637
 
2461
2638
  return { orphans, gate: passed.reason, ...waits, items: [] };
2462
2639
  }
2463
2640
 
2464
- const { agentOf, agentFirst } = commandsOf(core, agent, board, override);
2641
+ const { agentOf, agentFirst } = commandsOf(core, o.agent, board, override);
2642
+ const { fresh, limitClock, coreCommand } = o;
2465
2643
  const ctx = {
2466
2644
  ...{ projectDir, core, logs, agentOf, agentFirst, timeoutMs },
2467
2645
  ...{ fresh, launch, waitLimit, limitClock, coreCommand, startedAt },
2468
2646
  };
2469
2647
  const unhook = stopWithSessions();
2470
2648
  try {
2471
- // The run's id: its start alone does not keep two runs started at once apart.
2472
- const runOf = { id: `${started}-${process.pid}`, started };
2473
- // Each part to its end, a failing one too: the other's sessions are not left behind.
2474
- const driven = await Promise.allSettled(
2475
- parts.map(async ([m, part]) => {
2476
- const items = await (m === 'main'
2477
- ? runMain(projectDir, part, claims.get(m), ctx)
2478
- : runWorktrees(claims.get(m), ctx));
2479
- logMetrics(projectDir, 'run-log.csv', items.map(runRow(m, runOf)));
2480
-
2481
- return items;
2482
- }),
2483
- );
2484
- const failed = driven.find((d) => d.status === 'rejected');
2485
- if (failed) {
2486
- const error = String(failed.reason?.message ?? failed.reason);
2487
- for (const [n, d] of driven.entries())
2488
- if (d.status === 'rejected')
2489
- for (const id of parts[n][1])
2490
- await postEnd(
2491
- ctx,
2492
- { id, result: 'error', error },
2493
- parts[n][0] === 'main' ? null : worktreeAt(projectDir, id),
2494
- );
2495
- throw failed.reason;
2496
- }
2497
-
2498
- // The branches worktree runs verified while a main part held the checkout go in now; a main
2499
- // its session left dirty keeps them for the next run.
2500
- const after = claims.has('main')
2501
- ? (await integrateNow(core).catch(() => ({ results: [] }))).results
2502
- : [];
2503
- const features = await closeFinishedFeatures(core).catch(() => []);
2504
- // A branch verified while main was held went in just now: its end is that merge's move.
2505
- for (const d of driven)
2506
- if (d.status === 'fulfilled')
2507
- for (const i of d.value.filter((x) => x.result === 'verified')) {
2508
- const merged = after.find((r) => r.id === i.id);
2509
- const result = merged?.move ?? (merged?.conflict ? 'conflict' : i.result);
2510
- await postEnd(
2511
- ctx,
2512
- { ...i, result, ...(merged?.conflict && { conflict: merged.conflict }) },
2513
- worktreeAt(projectDir, i.id),
2514
- );
2515
- }
2516
-
2517
- // `limit_wait`: this harness waits for a usage limit's reset itself (AD-19); a board reads it.
2518
- return {
2519
- orphans: [...orphans, ...after],
2520
- mode: parts.map(([m]) => m).join('+'),
2521
- items: driven.flatMap((d) => (d.status === 'fulfilled' ? d.value : [])),
2522
- // The features this run finished, closed after it: their close or the core's refusal.
2523
- features,
2524
- limit_wait: true,
2525
- };
2649
+ return await driveParts(parts, claims, ctx, { orphans, started });
2526
2650
  } finally {
2527
2651
  unhook();
2528
2652
  }
package/extension.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://raw.githubusercontent.com/lee-to/ai-factory/2.x/schemas/extension.schema.json",
3
3
  "name": "gcf-harness-aif-ext",
4
- "version": "0.28.0",
4
+ "version": "0.28.1",
5
5
  "description": "GCF orchestration harness for Claude Code: one-command card pipeline, readset guard",
6
6
  "skills": [
7
7
  "skills/gcf-run",
@@ -139,6 +139,7 @@ function phaseRefusal({ now, converged } = {}) {
139
139
  /** Whether the plan of item `id` converged, by `ai-factory gcf plan check --json`; null unread. */
140
140
  export function convergedOf(projectDir, id) {
141
141
  const res = spawnSync('ai-factory', ['gcf', 'plan', 'check', id, '--json'], {
142
+ windowsHide: true,
142
143
  cwd: projectDir,
143
144
  encoding: 'utf8',
144
145
  shell: process.platform === 'win32',
package/hooks/metrics.js CHANGED
@@ -8,6 +8,7 @@ import path from 'node:path';
8
8
  /** gcf/.metrics of the main checkout of `projectDir`; its own outside a repository. */
9
9
  export function metricsDir(projectDir) {
10
10
  const res = spawnSync('git', ['rev-parse', '--git-common-dir'], {
11
+ windowsHide: true,
11
12
  cwd: projectDir,
12
13
  encoding: 'utf8',
13
14
  });
@@ -901,22 +901,7 @@ const SEEN = {
901
901
  };
902
902
 
903
903
  if (!taskGate(c, e, Date.now(), later)) return;
904
- const prompt = e.phase === 'start' ? e.prompt : null;
905
- post(c, {
906
- type: 'task',
907
- phase: e.phase,
908
- id: e.id,
909
- ...(e.kind ? { kind: e.kind } : {}),
910
- ...(e.agent ? { agent: e.agent } : {}),
911
- ...(e.description ? { description: cut(e.description, WHY_MAX) } : {}),
912
- ...(e.doing ? { doing: cut(e.doing, WHY_MAX) } : {}),
913
- ...(prompt ? { prompt: cut(prompt, TASK_PROMPT_MAX) } : {}),
914
- ...(e.calls !== null ? { calls: e.calls } : {}),
915
- ...(e.ms !== null ? { ms: e.ms } : {}),
916
- ...(e.status ? { status: e.status } : {}),
917
- ...(e.summary ? { summary: cut(e.summary, TASK_SUMMARY_MAX) } : {}),
918
- ...(e.background ? { background: true } : {}),
919
- });
904
+ post(c, taskCard(e));
920
905
  },
921
906
  // While they run, no answer is waited for; claude starts a turn itself as they end. Their end
922
907
  // with no new turn after the grace settles the session, so it is not held for good.
@@ -928,6 +913,27 @@ const SEEN = {
928
913
  },
929
914
  };
930
915
 
916
+ /** The chat's `task` event of a task event `e`: only the fields it has. */
917
+ function taskCard(e) {
918
+ const prompt = e.phase === 'start' ? e.prompt : null;
919
+
920
+ return {
921
+ type: 'task',
922
+ phase: e.phase,
923
+ id: e.id,
924
+ ...(e.kind ? { kind: e.kind } : {}),
925
+ ...(e.agent ? { agent: e.agent } : {}),
926
+ ...(e.description ? { description: cut(e.description, WHY_MAX) } : {}),
927
+ ...(e.doing ? { doing: cut(e.doing, WHY_MAX) } : {}),
928
+ ...(prompt ? { prompt: cut(prompt, TASK_PROMPT_MAX) } : {}),
929
+ ...(e.calls !== null ? { calls: e.calls } : {}),
930
+ ...(e.ms !== null ? { ms: e.ms } : {}),
931
+ ...(e.status ? { status: e.status } : {}),
932
+ ...(e.summary ? { summary: cut(e.summary, TASK_SUMMARY_MAX) } : {}),
933
+ ...(e.background ? { background: true } : {}),
934
+ };
935
+ }
936
+
931
937
  // The events that say a new turn has begun: the messages it echoes count themselves.
932
938
  const TURN = new Set(['said', 'read', 'tool_call', 'tool_result']);
933
939
 
@@ -21,7 +21,11 @@ export function alive(pid) {
21
21
  * group (`detached`), and the group gets the signal.
22
22
  */
23
23
  export function killTree(pid) {
24
- if (WIN) spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore' });
24
+ if (WIN)
25
+ spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], {
26
+ windowsHide: true,
27
+ stdio: 'ignore',
28
+ });
25
29
  else {
26
30
  try {
27
31
  process.kill(-pid, 'SIGKILL');
@@ -70,29 +70,25 @@ function handoffWatch(handoff, windowOf, write, { stop, onFlag, fresh = false })
70
70
  onFlag(info);
71
71
  };
72
72
 
73
+ const pastFlag = (share) => {
74
+ if (w.flagged && (w.after > HARD_TURNS || share >= handoff.pct + HARD_OVER)) {
75
+ write([`[${clock()}] handoff: the session went on past its flag, stopped`]);
76
+ stop();
77
+ }
78
+ };
79
+
73
80
  const check = (model, compacted) => {
74
81
  const win = windowOf(model);
75
82
  const pct = win ? Math.round((100 * w.context) / win) : null;
76
83
  // No share is under every threshold: a session of an unknown window hands over at a compaction.
77
84
  const share = pct ?? 0;
78
85
  if (pct === null && !compacted) unknownOnce(model);
79
- // A run's fresh session starts from the same prompt; a project chat's, from a summary.
80
- const under = fresh && !handoff.soft && w.readings === 1 && share >= handoff.pct;
81
- if (under && !compacted && !w.under) {
82
- w.under = true;
83
- write([
84
- `[${clock()}] handoff: off, the session starts at ${pct}% of the window, over ` +
85
- `context_handoff_pct ${handoff.pct}: a fresh session would start there too; raise it`,
86
- ]);
87
- }
86
+ underOnce(w, handoff, write, { fresh, pct, share, compacted });
88
87
 
89
88
  if (!w.flagged && (compacted || (share >= handoff.pct && !w.under))) flag(win, pct, compacted);
90
89
  // A project chat hands over by its summary turn, which goes on past the flag (AD-42).
91
90
  if (handoff.soft) return;
92
- if (w.flagged && (w.after > HARD_TURNS || share >= handoff.pct + HARD_OVER)) {
93
- write([`[${clock()}] handoff: the session went on past its flag, stopped`]);
94
- stop();
95
- }
91
+ pastFlag(share);
96
92
  };
97
93
 
98
94
  return {
@@ -113,6 +109,34 @@ function handoffWatch(handoff, windowOf, write, { stop, onFlag, fresh = false })
113
109
  };
114
110
  }
115
111
 
112
+ /** The chat of a session with `chat` options (`runSession`), and its context line `shown`. */
113
+ function openSessionChat(s, child, { watch, limit, windowOf, seen }) {
114
+ const parts = { ...sessionOf(child, watch, limit, windowOf), limited: () => !!seen.limit };
115
+ const talk = openChat({
116
+ ...s.chat,
117
+ ...parts,
118
+ id: s.id,
119
+ prompt: s.prompt,
120
+ encode: s.adapter.encode,
121
+ });
122
+ const shown = contextWatch((e) => talk?.event(e), windowOf);
123
+
124
+ return { talk, shown };
125
+ }
126
+
127
+ /** The note, once, of a fresh session at its first reading over the share (`w` its watch). */
128
+ function underOnce(w, handoff, write, { fresh, pct, share, compacted }) {
129
+ // A run's fresh session starts from the same prompt; a project chat's, from a summary.
130
+ const under = fresh && !handoff.soft && w.readings === 1 && share >= handoff.pct;
131
+ if (under && !compacted && !w.under) {
132
+ w.under = true;
133
+ write([
134
+ `[${clock()}] handoff: off, the session starts at ${pct}% of the window, over ` +
135
+ `context_handoff_pct ${handoff.pct}: a fresh session would start there too; raise it`,
136
+ ]);
137
+ }
138
+ }
139
+
116
140
  /** A held session's own hard stop (`w` its watch): `check` runs only with a share to watch. */
117
141
  function heldTooLong(w, write, stop) {
118
142
  if (!w.held || w.hardStop || w.after <= HARD_TURNS) return;
@@ -330,7 +354,7 @@ function sessionTimeout(ms, onTimeout, onHalt) {
330
354
  * held?: string}>}
331
355
  */
332
356
  export function runSession(s) {
333
- const { adapter, fd, timeoutMs, id, onSpawn, handoff, quota, chat, observe, halt, ownReply } = s;
357
+ const { adapter, fd, timeoutMs, onSpawn, handoff, quota, chat, observe, halt, ownReply } = s;
334
358
 
335
359
  return new Promise((resolve) => {
336
360
  const child = launchSession(s);
@@ -362,11 +386,7 @@ export function runSession(s) {
362
386
  const limit = sessionTimeout(timeoutMs, stop('timeout'), halts);
363
387
  /** @type {((tokens: number, model?: string) => void) | null} */
364
388
  let shown = null;
365
- if (chat) {
366
- const parts = { ...sessionOf(child, watch, limit, windowOf), limited: () => !!seen.limit };
367
- talk = openChat({ ...chat, ...parts, id, prompt: s.prompt, encode: adapter.encode });
368
- shown = contextWatch((e) => talk?.event(e), windowOf);
369
- }
389
+ if (chat) ({ talk, shown } = openSessionChat(s, child, { watch, limit, windowOf, seen }));
370
390
 
371
391
  const flushOut = byLine(child.stdout, (line) => {
372
392
  const a = adapter.parse(line);
@@ -24,17 +24,22 @@ export function writeAtomic(file, text) {
24
24
  const tmp = `${file}.${process.pid}.tmp`;
25
25
  try {
26
26
  writeFileSync(tmp, text);
27
- for (let i = 0; ; i++)
28
- try {
29
- renameSync(tmp, file);
30
-
31
- return;
32
- } catch (e) {
33
- if (!HELD.has(e.code) || i >= 10) throw e;
34
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
35
- }
27
+ renameHeld(tmp, file);
36
28
  } catch (e) {
37
29
  rmSync(tmp, { force: true });
38
30
  throw e;
39
31
  }
40
32
  }
33
+
34
+ /** Rename `tmp` over `file`, again for a file held for a moment. */
35
+ function renameHeld(tmp, file) {
36
+ for (let i = 0; ; i++)
37
+ try {
38
+ renameSync(tmp, file);
39
+
40
+ return;
41
+ } catch (e) {
42
+ if (!HELD.has(e.code) || i >= 10) throw e;
43
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
44
+ }
45
+ }
@@ -220,9 +220,7 @@ function markOnce(dir, [kind, key], t, last = false) {
220
220
  * of the thread, a handoff's too, runs by it. A started thread is bound to nothing.
221
221
  */
222
222
  export function createThread(dir, { item = null, entry = null, start = null } = {}) {
223
- if (item && entry) throw new RangeError('a thread is bound to an item or an entry, not both');
224
- if (start && (item || entry)) throw new RangeError('a started thread is bound to nothing');
225
- const [kind, key] = item ? ['items', item] : ['entries', entry];
223
+ const [kind, key] = markKey(item, entry, start);
226
224
  const had = key ? boundTo(dir, kind, key) : null;
227
225
  if (had) return had;
228
226
  mkdirSync(path.join(chatsDir(dir), kind), { recursive: true });
@@ -236,6 +234,14 @@ export function createThread(dir, { item = null, entry = null, start = null } =
236
234
  return t;
237
235
  }
238
236
 
237
+ /** The mark of a new thread, `[kind, key]` (`createThread`); a RangeError for a bound one twice. */
238
+ function markKey(item, entry, start) {
239
+ if (item && entry) throw new RangeError('a thread is bound to an item or an entry, not both');
240
+ if (start && (item || entry)) throw new RangeError('a started thread is bound to nothing');
241
+
242
+ return item ? ['items', item] : ['entries', entry];
243
+ }
244
+
239
245
  /** A thread's folder made exclusively under a fresh id: the id. */
240
246
  function newDir(dir) {
241
247
  for (;;) {
@@ -95,7 +95,10 @@ export function reasonOf(e, err, timeoutMs = ASK_TIMEOUT_MS) {
95
95
  function killAll(child) {
96
96
  if (!child.pid) return;
97
97
  if (process.platform === 'win32')
98
- spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
98
+ spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], {
99
+ windowsHide: true,
100
+ stdio: 'ignore',
101
+ });
99
102
  else
100
103
  try {
101
104
  process.kill(-child.pid, 'SIGKILL');
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gcf-session",
3
- "version": "0.19.2",
3
+ "version": "0.19.3",
4
4
  "private": true,
5
5
  "description": "The session engine of GCF: one agent session and a run as a chain of them, the chat protocol, the provider adapters. Bundled by gcf-harness-aif-ext and gcf-board, never published.",
6
6
  "type": "module",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gcf-harness-aif-ext",
3
- "version": "0.28.0",
3
+ "version": "0.28.1",
4
4
  "description": "GCF orchestration harness for Claude Code: one-command card pipeline, readset guard",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -84,6 +84,7 @@ forbidden_behaviors:
84
84
  - a refusal none of those replaces is a stop: run `ai-factory gcf block <id> --reason "needs permission: <command>"` and stop the item; under `--worktree` step 22 records it instead
85
85
  - the operator reruns a `needs permission` stop with that one rule off (the board's **Allow <rule> for one run**, or `gcf-harness run <id> --allow`)
86
86
  - so name the refused call and what the tree already holds, and do not ask the operator to turn its group off
87
+ - do not name or guess the rule that refused it: you do not know it, and the board names it on that Allow button
87
88
  - a call the handoff guard denies with "context at", "the operator holds this item" or "reserve" is no refusal: block nothing, write the `## Handoff` it asks for and end the reply
88
89
  - an aif-implement the implement guard denies for the planning phase or an unconverged plan is no refusal either: record the pass, if any, and end the reply; the harness starts the next session
89
90
  - a read the readset guard denies is no refusal either: drop that read; never add a `system:` or `depends:` only to read a file - when one of them is wrong in substance, fix it on main, and under `--worktree` stop with a block that names the fix