gcf-harness-aif-ext 0.12.2 → 0.14.0

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
@@ -47,6 +47,10 @@ Updating keeps the hook entry valid — it points into the extension's install d
47
47
 
48
48
  0.5.1 is a fix release. During a run, `gcf/config.yml` is always readable, and a Grep inside `gcf/` reads only readset files. An import breaks a `depends:` cycle the pair checks closed and asks a D1 about it. It cuts a section longer than a segment at paragraphs, and lens and pair prompts carry a window around the quote. `/gcf-run` checks the plan against each pillar's invariant and asks each pillar's review question over the diff. Use it with core 0.4.1, which brings the parent feature into the readset.
49
49
 
50
+ 0.14.0 needs gcf-aif-ext 0.14.0 (docs/Base-A-Plan.md). Without `--timeout` a session's limit is `session_timeout_min` of `gcf/config.yml` (120 without it); an item without its own `model:` / `effort:` runs on the project's `agent.model` / `agent.effort` (the run's override still goes over both); `ai-factory gcf-harness gate --each [<id>…] --json` gives the gate of each named item (none: every ready one) run alone now, from one audit, `{items: {<id>: {pass, reason}}}`, exit 0: the board shows a refusal before the click. The bundled session engine offers Always for one MCP tool, marked `always_wide`.
51
+
52
+ 0.13.0 keeps its past runs for the board (docs/Board-V2-Data-Plan.md) and needs gcf-aif-ext 0.13.0 for the moves' `GCF-By`. `run-log.csv` lines get six columns at their end (`run_id, started, model, effort, log_from, log_to`; older lines still read); `ai-factory gcf-harness runs [--item <id>] [--limit <n>] --json` lists the runs; `run --model <m> --effort <e>` runs every item on another model for that run only, the item unchanged; a run sets `GCF_MOVE_BY=run` for its core calls and its agents.
53
+
50
54
  0.12.2 reads an item as it starts it: in a main-mode batch, an item the run has yet to reach takes a model or effort set meanwhile (`ai-factory gcf item agent`, core 0.12.3; a worktree run locks its items first). A stored `default` gives no `--model` or `--effort` flag.
51
55
 
52
56
  0.12.0 moves the session mechanics into the bundled session engine `gcf-session` (docs/Session-Engine.md) and needs gcf-aif-ext 0.12.0: a core without neutral rules (`agent.rules`) is refused before any item is claimed. The hooks keep their files and matchers: no new `init` is needed.
@@ -124,11 +128,13 @@ Removal does not touch `.claude/settings.json`: delete the entries whose command
124
128
 
125
129
  **`/gcf-run <item-id…>`** — drives work items through plan, implementation and DoD, with every gate checked *before* the tokens are spent: the audit ritual, the gate below, the context budget. The plan is written by `aif-plan`, then improved in passes, each by a fresh subagent that reads only the plan and the readset and records every default it picks; `ai-factory gcf plan check <id>` runs after each pass, and a pass with no blocking finding (a wrong or missing behavior or task, a broken pillar invariant, a rule conflict, an unprovable task) ends the loop. A blocking finding left after `plan_passes` passes (3 by default), or a question only the human can answer (a save format, a public API, a new dependency, a pillar conflict), blocks the item before any code is written. The DoD is `ai-factory gcf verify <id>` — the gate's checks, the item's `live:` delta, and the project's `dod.build` and `dod.test` commands from `gcf/config.yml` — plus a review by a fresh subagent, up to `dod_attempts` attempts. Every item ends in a state the core records: `gcf submit` (gate `verdict` or `decision` — waits for the human), `gcf close` (gate `auto` — done, or a soft unit closed as `unplayed`) or `gcf block` with the reason. The verdict and the decision belong to the human: the pipeline stops at `submit` and prints the playtest list.
126
130
 
127
- **`ai-factory gcf-harness gate <item-id…>`** — the `/gcf-run` gate as code. It reads one `gcf audit --json` report and exits 1 with a one-line reason when the items may not go: a core older than 0.4.0, a `schema:` other than 1 in `gcf/config.yml`, an id with no work item, a feature (run its children; the feature closes when they are finished), an item that is not `ready`, an unplayed dependency, no WIP room for the batch (items awaiting a verdict + the batch's `gate: verdict` items over `wip_built_limit`), or two items of the batch touching the same system unless both say `parallel: ok`. The tune limit is not a gate rule: `verdict tune` itself refuses at the limit, and an item tuned up to it still gets its last build. The skill runs it and stops on a non-zero exit — no model compares the numbers.
131
+ **`ai-factory gcf-harness gate <item-id…>`** — the `/gcf-run` gate as code (`--each`: each item alone, see 0.14.0 above). It reads one `gcf audit --json` report and exits 1 with a one-line reason when the items may not go: a core older than 0.4.0, a `schema:` other than 1 in `gcf/config.yml`, an id with no work item, a feature (run its children; the feature closes when they are finished), an item that is not `ready`, an unplayed dependency, no WIP room for the batch (items awaiting a verdict + the batch's `gate: verdict` items over `wip_built_limit`), or two items of the batch touching the same system unless both say `parallel: ok`. The tune limit is not a gate rule: `verdict tune` itself refuses at the limit, and an item tuned up to it still gets its last build. The skill runs it and stops on a non-zero exit — no model compares the numbers.
132
+
133
+ **`ai-factory gcf-harness run <item-id…> [--agent "<cmd>"]`** — runs a batch at once, each item in its own worktree (`gcf worktree <id>`) with its own agent session: `claude -p --output-format stream-json --verbose "/gcf-run <id> --worktree"` by default, or the command in `--agent` / `GCF_RUN_AGENT`. The sessions run unattended, so set the agent's permissions for print mode first. A session ends with a commit and `gcf verify <id> --mark` (the `GCF-Verified` trailer); a question for the human goes into `.gcf-session/outcome.json` in its worktree, and `run` records the block on main. Then `gcf integrate` merges the verified branches and records each move, and `run` prints the playtest session. Its first step, like `/gcf-run`'s, integrates the verified branches a dead run left. A session that ended with no result leaves its item `ready`; the next `run` resumes its worktree and the agent's own session (`--resume <session_id>`, kept in `.gcf-session/runs/<id>.agent.json`), in either run mode; `--fresh` starts a new session instead. A session cut off by Claude's usage limit reports `paused (usage limit, resets 3am (…))` and `limit_resets`. Logs: `.gcf-session/runs/<id>.log`, written as the session works: a `start:` line, then one stamped line per agent message, tool call (`tool: Edit <file>`, `tool: Bash <command>`) and failed tool result, and at the end the agent's final text and `done in 34m, 212 turns, $3.41 (…tokens)`; stderr goes in as it is, and a non-Claude `--agent` keeps its own lines. With `--json`, each item carries the session's `cost_usd`, `tokens`, `turns` and `duration_ms` when the agent reported them, what it ran on (`model`, `effort`; null: the agent's own) and `log: {from, to}`, the bytes of its log this run wrote. `--model <m>` and `--effort <e>` set the model and effort of every item for this run only, over the item's own `model:` and `effort:` (`default` or none: the item's); the item file is not changed. A run sets `GCF_MOVE_BY=run` for its core calls and every agent it starts, in either mode, so the core's moves name the run as their maker. One run drives an item at a time (`.gcf-session/runs/<id>.lock`), and a resumed worktree first gets main merged in, so the answer from an `unblock` reaches the session. A worktree sees only what is committed: keep `.ai-factory.json`, the installed extensions with their `node_modules` (a `node_modules/` line in `.gitignore` drops the core's `yaml` and `cnlp-kit`, and `ai-factory gcf` fails in the worktree) and `.claude/` (skills, the readset-guard hook) in git, or the session has no `/gcf-run` and no `ai-factory gcf`. On Windows a project in a deep folder needs `git config core.longpaths true`, or `git worktree add` fails on `Filename too long`.
128
134
 
129
- **`ai-factory gcf-harness run <item-id…> [--agent "<cmd>"]`** — runs a batch at once, each item in its own worktree (`gcf worktree <id>`) with its own agent session: `claude -p --output-format stream-json --verbose "/gcf-run <id> --worktree"` by default, or the command in `--agent` / `GCF_RUN_AGENT`. The sessions run unattended, so set the agent's permissions for print mode first. A session ends with a commit and `gcf verify <id> --mark` (the `GCF-Verified` trailer); a question for the human goes into `.gcf-session/outcome.json` in its worktree, and `run` records the block on main. Then `gcf integrate` merges the verified branches and records each move, and `run` prints the playtest session. Its first step, like `/gcf-run`'s, integrates the verified branches a dead run left. A session that ended with no result leaves its item `ready`; the next `run` resumes its worktree and the agent's own session (`--resume <session_id>`, kept in `.gcf-session/runs/<id>.agent.json`), in either run mode; `--fresh` starts a new session instead. A session cut off by Claude's usage limit reports `paused (usage limit, resets 3am (…))` and `limit_resets`. Logs: `.gcf-session/runs/<id>.log`, written as the session works: a `start:` line, then one stamped line per agent message, tool call (`tool: Edit <file>`, `tool: Bash <command>`) and failed tool result, and at the end the agent's final text and `done in 34m, 212 turns, $3.41 (…tokens)`; stderr goes in as it is, and a non-Claude `--agent` keeps its own lines. With `--json`, each item carries the session's `cost_usd`, `tokens`, `turns` and `duration_ms` when the agent reported them. One run drives an item at a time (`.gcf-session/runs/<id>.lock`), and a resumed worktree first gets main merged in, so the answer from an `unblock` reaches the session. A worktree sees only what is committed: keep `.ai-factory.json`, the installed extensions with their `node_modules` (a `node_modules/` line in `.gitignore` drops the core's `yaml` and `cnlp-kit`, and `ai-factory gcf` fails in the worktree) and `.claude/` (skills, the readset-guard hook) in git, or the session has no `/gcf-run` and no `ai-factory gcf`. On Windows a project in a deep folder needs `git config core.longpaths true`, or `git worktree add` fails on `Filename too long`.
135
+ **`ai-factory gcf-harness metrics [--since <date>] [--json]`** — the run metrics of Harness-PRD §11 from `gcf/.metrics`: how many item runs reached `submit` or `close` (a run the usage limit paused or a session cut short does not count as finished), the block reasons, what the runs cost (dollars, minutes, turns, handoffs, code written outside aif-implement), the plan checks per item (the improve passes), the DoD attempts per item and the checks that failed them, and the guard firings by hook and by item. The logs: `run-log.csv` (one line per item of each `run`: `at, item, mode, result, reason, cost_usd, input, output, cache_read, turns, duration_ms, handoffs, process, run_id, started, model, effort, log_from, log_to`; `result` is `submit`, `close`, `block`, `error`, `conflict`, `skipped`, `paused` for the usage limit, `no-result` for a session cut short, `not-started`; `run_id` is `<started>-<pid>` of the run; `model` and `effort` what the item ran on, empty for the agent's own; `log_from`, `log_to` the bytes of `.gcf-session/runs/<id>.log` this run wrote; older lines end at `process`), `guard-log.csv` (each denial of readset-guard and implement-guard, by hook: `readset`, `implement`, or `verify` for a move past the verify gate), and the core's `plan-log.csv` and `verify-log.csv`. A worktree session's lines go to the main checkout's logs; the next `gcf integrate` commits them.
130
136
 
131
- **`ai-factory gcf-harness metrics [--since <date>] [--json]`** — the run metrics of Harness-PRD §11 from `gcf/.metrics`: how many item runs reached `submit` or `close` (a run the usage limit paused or a session cut short does not count as finished), the block reasons, what the runs cost (dollars, minutes, turns, handoffs, code written outside aif-implement), the plan checks per item (the improve passes), the DoD attempts per item and the checks that failed them, and the guard firings by hook and by item. The logs: `run-log.csv` (one line per item of each `run`), `guard-log.csv` (each denial of readset-guard and implement-guard, by hook: `readset`, `implement`, or `verify` for a move past the verify gate), and the core's `plan-log.csv` and `verify-log.csv`. A worktree session's lines go to the main checkout's logs; the next `gcf integrate` commits them.
137
+ **`ai-factory gcf-harness runs [--item <id>] [--limit <n>] [--json]`** — the past runs in `run-log.csv`, the latest first, at most `--limit` (50 by default); `--item` keeps the runs that hold that item. `--json` gives `{runs: [{id, started, ended, mode, cost_usd, items: [{id, result, reason, cost_usd, tokens: {input, output, cache_read}, turns, duration_ms, handoffs, process, model, effort, log: {from, to} | null}]}]}`. A run's lines share its `run_id`; a line older than it is grouped by its `at` (all lines of one run share it), with `id` and `started` null and `log` null (the whole log). Known limits: two such older runs that ended in the same millisecond read as one; a reason's commas read as `;` (the csv turns them so). A run that fails as a whole (its gate refused it, an error of `run` itself) or whose process was killed leaves no lines, so it is not listed. A stop (`gcf-harness stop`, the board's Stop) ends only the item's session: the run writes its line, `no-result` with reason `stopped`; a stop while the session waits for the usage limit's reset writes `paused` with `usage limit; resets <when>; stopped during the wait`.
132
138
 
133
139
  **`/gcf-run-ingest <gdd.md>`** — imports a design document as a fan-out workflow: parallel aspect extraction, provenance verified by code rather than by an agent (a quote either is a verbatim substring of its section or it is not), completeness lenses per candidate, and an interaction matrix computed from the candidates that write the same state.
134
140
 
@@ -8,7 +8,7 @@ import { existsSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
8
8
  import { spawnSync } from 'node:child_process';
9
9
  import path from 'node:path';
10
10
  import { fileURLToPath } from 'node:url';
11
- import { metricsCommand } from './metrics.js';
11
+ import { metricsCommand, runsCommand } from './metrics.js';
12
12
  import { run, cliCore, DEFAULT_AGENT, DEFAULT_TIMEOUT_MIN, MAIN_RUN, stopOf } from './run.js';
13
13
  import { CHAT_TIMEOUT_MIN, ChatRefusal, alive, chatInput, killTree, readText } from 'gcf-session';
14
14
 
@@ -323,7 +323,41 @@ async function init(program) {
323
323
  await ignoreSession(projectDir);
324
324
  }
325
325
 
326
+ /**
327
+ * The gate of each item run alone now, from one report: the named ones, or every ready item
328
+ * (Board-PRD §5.3: a board shows a refusal before the click). A batch of several is still gated
329
+ * when it starts: two items of one subsystem pass alone.
330
+ */
331
+ export function gateEach(report, ids) {
332
+ const named = ids.length
333
+ ? ids
334
+ : (report.items ?? [])
335
+ .filter((i) => i.status === 'ready' && !i.running && i.type !== 'feature')
336
+ .map((i) => i.id);
337
+
338
+ return { items: Object.fromEntries(named.map((id) => [id, gate(report, [id])])) };
339
+ }
340
+
326
341
  function runGate(ids, opts) {
342
+ if (opts.each) {
343
+ const result = gateEach(auditReport(), [...new Set(ids)]);
344
+ if (opts.json) console.log(JSON.stringify(result));
345
+ else
346
+ for (const [id, v] of Object.entries(result.items))
347
+ console.log(v.pass ? `${id}: pass` : `${id}: ${v.reason}`);
348
+
349
+ return;
350
+ }
351
+
352
+ if (!ids.length) {
353
+ const reason = 'name the items to gate, or --each for every ready one';
354
+ if (opts.json) console.log(JSON.stringify({ pass: false, reason }));
355
+ console.error(`gcf gate: ${reason}`);
356
+ process.exitCode = 1;
357
+
358
+ return;
359
+ }
360
+
327
361
  const result = gate(auditReport(), [...new Set(ids)]);
328
362
  if (opts.json) console.log(JSON.stringify(result));
329
363
  else if (result.pass) console.log('gate: pass');
@@ -345,9 +379,14 @@ export function register(program) {
345
379
  .action(() => init(program));
346
380
 
347
381
  harness
348
- .command('gate <ids...>')
382
+ .command('gate [ids...]')
349
383
  .description('Gate work items before the paid stages of /gcf-run: exit 1 with the reason')
350
384
  .option('--json', 'machine output: {pass, reason}')
385
+ .option(
386
+ '--each',
387
+ 'gate each item alone (the named ones, else every ready one); exit 0, ' +
388
+ 'machine output {items: {<id>: {pass, reason}}}',
389
+ )
351
390
  .action(runGate);
352
391
 
353
392
  registerRun(harness);
@@ -366,6 +405,13 @@ export function register(program) {
366
405
  .option('--since <date>', 'only lines at or after this ISO date or time')
367
406
  .option('--json', 'machine output')
368
407
  .action(metricsCommand);
408
+ harness
409
+ .command('runs')
410
+ .description('Past runs from gcf/.metrics/run-log.csv, the latest first: items, results, cost')
411
+ .option('--item <id>', 'only the runs that hold this item')
412
+ .option('--limit <n>', 'at most this many runs', '50')
413
+ .option('--json', 'machine output: {runs: [...]}')
414
+ .action(runsCommand);
369
415
  harness
370
416
  .command('stop <id>')
371
417
  .description('Stop the session that works an item; the run goes on, the item stays ready')
@@ -385,8 +431,8 @@ function registerRun(harness) {
385
431
  )
386
432
  .option(
387
433
  '--timeout <minutes>',
388
- 'stop a session that runs longer; its item stays ready',
389
- String(DEFAULT_TIMEOUT_MIN),
434
+ 'stop a session that runs longer; its item stays ready (default: session_timeout_min of ' +
435
+ `gcf/config.yml, else ${DEFAULT_TIMEOUT_MIN})`,
390
436
  )
391
437
  .option('--mode <mode>', 'worktree | main (default: run_mode of gcf/config.yml)')
392
438
  .option('--fresh', 'start new agent sessions: an interrupted one is not resumed')
@@ -403,6 +449,12 @@ function registerRun(harness) {
403
449
  'how long a chat question waits for the operator (default: chat.answer_timeout_min of ' +
404
450
  `gcf/config.yml, else ${CHAT_TIMEOUT_MIN}; 0: nobody watches)`,
405
451
  )
452
+ .option(
453
+ '--model <model>',
454
+ "this run's model for every item, over the item's own (default: the item's); the item " +
455
+ 'file is not changed',
456
+ )
457
+ .option('--effort <effort>', "this run's effort for every item, as --model")
406
458
  .option('--json', 'machine output')
407
459
  .action(runItems);
408
460
  }
@@ -517,8 +569,9 @@ const failed = (r) =>
517
569
 
518
570
  async function runItems(ids, opts) {
519
571
  try {
520
- const minutes = Number(opts.timeout);
521
- if (!(minutes > 0)) throw new Error('--timeout is a number of minutes above 0');
572
+ const minutes = opts.timeout === undefined ? undefined : Number(opts.timeout);
573
+ if (minutes !== undefined && !(minutes > 0))
574
+ throw new Error('--timeout is a number of minutes above 0');
522
575
  if (opts.mode && !['worktree', 'main'].includes(opts.mode))
523
576
  throw new Error('--mode is worktree or main');
524
577
  const answer = opts.chatTimeout === undefined ? null : Number(opts.chatTimeout);
@@ -529,11 +582,13 @@ async function runItems(ids, opts) {
529
582
  const r = await run(realpathSync.native(process.cwd()), [...new Set(ids)], {
530
583
  agent: opts.agent,
531
584
  gate: (batch) => gate(auditReport(), batch),
532
- timeoutMs: minutes * 60_000,
585
+ timeoutMs: minutes === undefined ? undefined : minutes * 60_000,
533
586
  mode: opts.mode,
534
587
  fresh: Boolean(opts.fresh),
535
588
  waitLimit: Boolean(opts.waitLimit),
536
589
  chat: opts.chat ? { answerMin: answer } : null,
590
+ model: opts.model,
591
+ effort: opts.effort,
537
592
  });
538
593
  if (opts.json) console.log(JSON.stringify(r, null, 2));
539
594
  else printRun(r);
@@ -83,7 +83,7 @@ const UNFINISHED = ['paused', 'no-result', 'not-started'];
83
83
  /** The summary of the logs in `dir`, from `since` on. */
84
84
  export function summarize(dir, since = '') {
85
85
  // run-log: at, item, mode, result, reason, cost_usd, input, output, cache_read, turns,
86
- // duration_ms, handoffs, process
86
+ // duration_ms, handoffs, process (then run_id, started, model, effort, log_from, log_to)
87
87
  const runs = rows(dir, 'run-log.csv', since);
88
88
  const finished = runs.filter((r) => !UNFINISHED.includes(r[3]));
89
89
  const reached = finished.filter((r) => ['submit', 'close'].includes(r[3]));
@@ -183,6 +183,68 @@ export function formatMetrics(s) {
183
183
  ].join('\n');
184
184
  }
185
185
 
186
+ /** An item's line of run-log.csv as a past run shows it (gcf-board `PastRunItem`). */
187
+ const pastItem = (r) => ({
188
+ id: r[1],
189
+ result: r[3],
190
+ reason: r[4] || null,
191
+ cost_usd: num(r[5]),
192
+ tokens: { input: num(r[6]), output: num(r[7]), cache_read: num(r[8]) },
193
+ turns: num(r[9]),
194
+ duration_ms: num(r[10]),
195
+ handoffs: num(r[11]) ?? 0,
196
+ process: r[12] || null,
197
+ model: r[15] || null,
198
+ effort: r[16] || null,
199
+ // A line older than the offsets names none: the whole log is the item's.
200
+ log: r[17] && r[18] ? { from: Number(r[17]), to: Number(r[18]) } : null,
201
+ });
202
+
203
+ /**
204
+ * The past runs in `dir`'s run-log.csv (gcf-board `PastRun`), the latest first, at most `limit`;
205
+ * with `item`, only the runs that hold it. A run's lines share its `run_id`; a line older than
206
+ * it goes by its `at`, the one stamp all lines of a run share.
207
+ * shortcut: two such older runs that ended in the same millisecond read as one.
208
+ * @param {string} dir
209
+ * @param {{item?: string | null, limit?: number}} [o]
210
+ */
211
+ export function pastRuns(dir, { item = null, limit = 50 } = {}) {
212
+ const runs = new Map();
213
+ for (const r of rows(dir, 'run-log.csv', '')) {
214
+ const key = r[13] ? `id ${r[13]}` : `at ${r[0]}`;
215
+ const run = runs.get(key) ?? {
216
+ ...{ id: r[13] || null, started: r[14] || null, ended: r[0], mode: r[2] },
217
+ ...{ cost_usd: null, items: [] },
218
+ };
219
+ const i = pastItem(r);
220
+ run.items.push(i);
221
+ // Cents of many lines add up to float noise.
222
+ if (i.cost_usd !== null)
223
+ run.cost_usd = Math.round(((run.cost_usd ?? 0) + i.cost_usd) * 1e6) / 1e6;
224
+ runs.set(key, run);
225
+ }
226
+
227
+ return [...runs.values()]
228
+ .filter((x) => !item || x.items.some((i) => i.id === item))
229
+ .sort((a, b) => (a.ended < b.ended ? 1 : a.ended > b.ended ? -1 : 0))
230
+ .slice(0, limit);
231
+ }
232
+
233
+ /** The `runs` command: the project's past runs, the latest first. */
234
+ export function runsCommand(o) {
235
+ const limit = Number(o.limit ?? 50);
236
+ if (!Number.isInteger(limit) || limit < 1) throw new Error('--limit is a whole number above 0');
237
+ const runs = pastRuns(metricsDir(process.cwd()), { item: o.item ?? null, limit });
238
+ if (o.json) return console.log(JSON.stringify({ runs }, null, 2));
239
+ const cost = (v) => (v === null ? '' : ` $${v.toFixed(2)}`);
240
+ for (const r of runs)
241
+ console.log(
242
+ `${r.ended} ${r.mode}${cost(r.cost_usd)}: ` +
243
+ r.items.map((i) => `${i.id} ${i.result}`).join(', '),
244
+ );
245
+ if (!runs.length) console.log('no runs');
246
+ }
247
+
186
248
  /** The `metrics` command: the project's logs, from `--since` on. */
187
249
  export function metricsCommand(o) {
188
250
  // The logs stamp UTC: a local date or time is turned into one before the comparison. A bare
package/commands/run.js CHANGED
@@ -106,19 +106,42 @@ export function json(res, what) {
106
106
  const RUN_WORD = /^[A-Za-z0-9][\w.-]*$/;
107
107
 
108
108
  /**
109
- * The agent command of one item: its `model:` and `effort:` become `--model` and `--effort`,
110
- * the flags of `claude`. The command goes through a shell, and an item file can be edited by
111
- * hand: a value that is not one plain word is refused; `default` leaves it to the agent.
109
+ * What one item runs on: the run's override (`run --model|--effort`, this run only) over the
110
+ * item's own `model:` and `effort:`, over the project's (`agent.model|effort` of
111
+ * gcf/config.yml); null or `default` at one level falls to the next, none at all leaves it to
112
+ * the agent. The values go into a
113
+ * shell command, and an item file can be edited by hand: a value that is not one plain word is
114
+ * refused.
115
+ * @param {any} item
116
+ * @param {{model?: string | null, effort?: string | null}} [override]
117
+ * @param {{model?: string | null, effort?: string | null}} [project]
112
118
  */
113
- export function agentFor(agent, item) {
114
- const flags = [];
115
- for (const k of ['model', 'effort']) {
116
- const v = item?.[k];
117
- if (v === null || v === undefined || v === 'default') continue;
118
- if (!RUN_WORD.test(String(v))) throw new Error(`${k}: ${v} is not one plain word`);
119
- flags.push(`--${k} ${v}`);
119
+ export function choiceOf(item, override = {}, project = {}) {
120
+ const set = (v) => (v === null || v === undefined || v === 'default' ? null : String(v));
121
+ /** @type {{model: string | null, effort: string | null}} */
122
+ const out = { model: null, effort: null };
123
+ for (const k of /** @type {const} */ (['model', 'effort'])) {
124
+ const v = set(override?.[k]) ?? set(item?.[k]) ?? set(project?.[k]);
125
+ if (v !== null && !RUN_WORD.test(v)) throw new Error(`${k}: ${v} is not one plain word`);
126
+ out[k] = v;
120
127
  }
121
128
 
129
+ return out;
130
+ }
131
+
132
+ /**
133
+ * The agent command of one item: what it runs on (`choiceOf`) becomes `--model` and `--effort`,
134
+ * the flags of `claude`.
135
+ * @param {string} agent
136
+ * @param {any} item
137
+ * @param {{model?: string | null, effort?: string | null}} [override]
138
+ * @param {{model?: string | null, effort?: string | null}} [project]
139
+ */
140
+ export function agentFor(agent, item, override = {}, project = {}) {
141
+ const flags = Object.entries(choiceOf(item, override, project))
142
+ .filter(([, v]) => v !== null)
143
+ .map(([k, v]) => `--${k} ${v}`);
144
+
122
145
  return [agent, ...flags].join(' ');
123
146
  }
124
147
 
@@ -211,16 +234,17 @@ async function claimAll(ids, logs) {
211
234
 
212
235
  /**
213
236
  * The worktree and the agent command of each claimed item; an item that cannot start is an
214
- * error. `agentOf(id)` gives the command.
237
+ * error. `agentOf(id)` gives the command and what it runs on (`{agent, choice}`).
215
238
  */
216
239
  async function prepare({ claimed, failed }, core, agentOf) {
217
240
  const ready = [];
218
241
  for (const { id, release } of claimed) {
219
242
  try {
220
- const agent = agentOf(id);
243
+ const { agent, choice } = agentOf(id);
221
244
  const wt = json(await core(['worktree', id, '--json']), `worktree ${id}`);
222
245
  if (wt.sync) throw new Error(wt.sync);
223
- ready.push({ id, dir: wt.path, agent, release, lessonsPrompt: await lessonsFor(core, id) });
246
+ const lessonsPrompt = await lessonsFor(core, id);
247
+ ready.push({ id, dir: wt.path, agent, choice, release, lessonsPrompt });
224
248
  } catch (e) {
225
249
  await release();
226
250
  failed.push({ id, result: 'error', error: e.message });
@@ -646,10 +670,14 @@ async function session(r, { core, logs, timeoutMs, fresh, launch, waitLimit, lim
646
670
  // On main the item carries a session mark; a stage with no gcf command must not expire it.
647
671
  const mark = path.join(logs, `${r.id}.session`);
648
672
  const keep = r.main ? setInterval(() => touch(mark), 5 * 60_000) : null;
673
+ // The bytes of the item's log this run writes: every run appends to the one file (run-log).
674
+ let from = 0;
675
+ const span = async () => (log ? { from, to: (await log.stat()).size } : null);
649
676
  try {
650
677
  if (fresh) await rm(recordOf(logs, r.id), { force: true });
651
678
  const rec = fresh ? null : await kept(logs, r.id);
652
679
  log = await open(path.join(logs, `${r.id}.log`), 'a');
680
+ from = (await log.stat()).size;
653
681
  const s = {
654
682
  r,
655
683
  core,
@@ -664,9 +692,9 @@ async function session(r, { core, logs, timeoutMs, fresh, launch, waitLimit, lim
664
692
  };
665
693
  const { sessions: _, after: __, ...ran } = await itemJob(s, rec);
666
694
 
667
- return { ...r, ...ran };
695
+ return { ...r, ...ran, log: await span() };
668
696
  } catch (e) {
669
- return { ...r, code: null, error: e.message };
697
+ return { ...r, code: null, error: e.message, log: await span().catch(() => null) };
670
698
  } finally {
671
699
  if (keep) clearInterval(keep);
672
700
  await rm(stopOf(logs, r.id), { force: true });
@@ -882,7 +910,7 @@ async function mainItem(projectDir, id, ctx) {
882
910
  const s = {
883
911
  id,
884
912
  dir: projectDir,
885
- agent: await agentOf(id),
913
+ ...(await agentOf(id)),
886
914
  release: none,
887
915
  main: true,
888
916
  done,
@@ -949,26 +977,37 @@ function outcome(i) {
949
977
 
950
978
  /**
951
979
  * An item's line of run-log.csv (Harness-PRD §11): its result word (`paused` for the usage
952
- * limit, `no-result` for a session cut short), why, and what its sessions spent. A missing
953
- * value is an empty field.
980
+ * limit, `no-result` for a session cut short), why, and what its sessions spent; then its run
981
+ * (`run.id`, `run.started`), what it ran on and the bytes of its log this run wrote. New fields
982
+ * go at the end: `metrics` reads by index. A missing value is an empty field.
983
+ * @param {string} mode
984
+ * @param {{id?: string, started?: string}} [run]
954
985
  */
955
- export const runRow = (mode) => (i) => [
956
- i.id,
957
- mode,
958
- ...outcome(i),
959
- i.cost_usd,
960
- i.tokens?.input,
961
- i.tokens?.output,
962
- i.tokens?.cache_read,
963
- i.turns,
964
- i.duration_ms,
965
- i.handoffs ?? 0,
966
- i.process,
967
- ];
986
+ export const runRow =
987
+ (mode, run = {}) =>
988
+ (i) => [
989
+ i.id,
990
+ mode,
991
+ ...outcome(i),
992
+ i.cost_usd,
993
+ i.tokens?.input,
994
+ i.tokens?.output,
995
+ i.tokens?.cache_read,
996
+ i.turns,
997
+ i.duration_ms,
998
+ i.handoffs ?? 0,
999
+ i.process,
1000
+ run.id,
1001
+ run.started,
1002
+ i.model,
1003
+ i.effort,
1004
+ i.log?.from,
1005
+ i.log?.to,
1006
+ ];
968
1007
 
969
1008
  /**
970
- * What rides on an item's line beside its result: its handoffs, and its broken steps (a
971
- * skipped step 13, a move with no green verify).
1009
+ * What rides on an item's line beside its result: what it ran on, the bytes of its log, its
1010
+ * handoffs, and its broken steps (a skipped step 13, a move with no green verify).
972
1011
  * @param {any} r
973
1012
  * @param {string | null} [note]
974
1013
  */
@@ -976,6 +1015,8 @@ const extras = (r, note = null) => {
976
1015
  const notes = [r?.skipped && OUTSIDE_IMPLEMENT, note].filter(Boolean).join('; ');
977
1016
 
978
1017
  return {
1018
+ ...r?.choice,
1019
+ ...(r?.log ? { log: r.log } : {}),
979
1020
  ...(r?.handoffs ? { handoffs: r.handoffs } : {}),
980
1021
  ...(notes ? { process: notes } : {}),
981
1022
  ...(r?.lessons ? { lessons: r.lessons } : {}),
@@ -1025,6 +1066,37 @@ async function runWorktrees(claims, ctx) {
1025
1066
  });
1026
1067
  }
1027
1068
 
1069
+ /**
1070
+ * The agent command of each item and what it runs on (`{agent, choice}`), the run's override
1071
+ * over the item's own over the project's: `agentOf` (main) reads the board as each item starts,
1072
+ * so a main run's later items take a model or effort set meanwhile (`gcf item agent`,
1073
+ * `gcf config set agent.model`), and a board that cannot be read leaves the run's first read;
1074
+ * `agentFirst` (worktree) takes the run's first read.
1075
+ */
1076
+ function commandsOf(core, agent, board, override) {
1077
+ const itemOf = (items, id) => (items ?? []).find((i) => i.id === id);
1078
+ const commandOf = (b, id) => {
1079
+ const item = itemOf(b.items, id);
1080
+
1081
+ return {
1082
+ agent: agentFor(agent, item, override, b.agent),
1083
+ choice: choiceOf(item, override, b.agent),
1084
+ };
1085
+ };
1086
+ const agentOf = async (id) => {
1087
+ let now = null;
1088
+ try {
1089
+ now = json(await core(['board', '--json']), 'board');
1090
+ } catch {
1091
+ // The first read below.
1092
+ }
1093
+
1094
+ return commandOf(now && itemOf(now.items, id) ? now : board, id);
1095
+ };
1096
+
1097
+ return { agentOf, agentFirst: (id) => commandOf(board, id) };
1098
+ }
1099
+
1028
1100
  /** The mode a run takes: the one asked for, else the project's. */
1029
1101
  const modeOf = (mode, board) => mode ?? board.run_mode ?? 'worktree';
1030
1102
 
@@ -1034,15 +1106,30 @@ const modeOf = (mode, board) => mode ?? board.run_mode ?? 'worktree';
1034
1106
  * started, and its item stays ready. `fresh` starts new sessions where kept ones would resume;
1035
1107
  * `waitLimit` holds each session while the account's usage limit is known to reset ahead.
1036
1108
  * `chat` ({answerMs}) keeps each session open to the operator (docs/Chat-Plan.md).
1109
+ * The core's moves it and its agents make name the run as their maker (`GCF-By`); the variable
1110
+ * goes back as it was when the run ends, for a caller in the same process.
1111
+ * @type {typeof runBatch}
1037
1112
  */
1038
- export async function run(
1113
+ export const run = async (projectDir, ids, opts) => {
1114
+ const was = process.env.GCF_MOVE_BY;
1115
+ process.env.GCF_MOVE_BY = 'run';
1116
+ try {
1117
+ return await runBatch(projectDir, ids, opts);
1118
+ } finally {
1119
+ if (was === undefined) delete process.env.GCF_MOVE_BY;
1120
+ else process.env.GCF_MOVE_BY = was;
1121
+ }
1122
+ };
1123
+
1124
+ async function runBatch(
1039
1125
  projectDir,
1040
1126
  ids,
1041
1127
  {
1042
1128
  core = cliCore(projectDir),
1043
1129
  agent = DEFAULT_AGENT,
1044
1130
  gate,
1045
- timeoutMs = DEFAULT_TIMEOUT_MIN * 60_000,
1131
+ // None: `session_timeout_min` of gcf/config.yml, else DEFAULT_TIMEOUT_MIN.
1132
+ timeoutMs = undefined,
1046
1133
  mode = undefined,
1047
1134
  fresh = false,
1048
1135
  // A queued start: each session first waits while the usage limit's reset is ahead (AD-19).
@@ -1053,16 +1140,24 @@ export async function run(
1053
1140
  managed = agent === DEFAULT_AGENT,
1054
1141
  // Open each session to the operator (chat.js): how long a question waits for an answer.
1055
1142
  chat,
1143
+ // This run's model and effort over each item's own (`default` or none: the item's).
1144
+ model,
1145
+ effort,
1056
1146
  },
1057
1147
  ) {
1148
+ const started = new Date().toISOString();
1058
1149
  // An id names a lock file and goes into the agent's shell command: a slug, nothing else.
1059
1150
  const bad = ids.find((id) => !/^[a-z0-9]+(-[a-z0-9]+)*$/.test(id));
1060
1151
  if (bad) throw new Error(`${bad} is not an item id (a lowercase hyphen slug)`);
1152
+ const override = { model, effort };
1153
+ // A bad override is the run's error, before anything starts.
1154
+ choiceOf(null, override);
1061
1155
  const orphans = json(await core(['integrate', '--json']), 'integrate');
1062
1156
  const logs = path.join(path.resolve(projectDir), '.gcf-session', 'runs');
1063
1157
  await mkdir(logs, { recursive: true });
1064
1158
  const board = json(await core(['board', '--json']), 'board');
1065
1159
  const runMode = modeOf(mode, board);
1160
+ timeoutMs ??= (board.session_timeout_min ?? DEFAULT_TIMEOUT_MIN) * 60_000;
1066
1161
  // Before any item is claimed: a refusal here leaves no lock behind.
1067
1162
  const launch = await launchOf(logs, managed, board, chat);
1068
1163
  // The gate counts the items other runs hold locks on, so this run's locks go in with its gate.
@@ -1077,28 +1172,16 @@ export async function run(
1077
1172
  });
1078
1173
  if (!passed.pass) return { orphans, gate: passed.reason, items: [] };
1079
1174
 
1080
- const itemOf = (items, id) => (items ?? []).find((i) => i.id === id);
1081
- // Read as the item starts: a main run's later items take a model or effort set meanwhile
1082
- // (`gcf item agent`); a board that cannot be read leaves the run's first read.
1083
- const agentOf = async (id) => {
1084
- let now = null;
1085
- try {
1086
- now = itemOf(json(await core(['board', '--json']), 'board').items, id);
1087
- } catch {
1088
- // The first read below.
1089
- }
1090
-
1091
- return agentFor(agent, now ?? itemOf(board.items, id));
1092
- };
1093
-
1094
- const agentFirst = (id) => agentFor(agent, itemOf(board.items, id));
1175
+ const { agentOf, agentFirst } = commandsOf(core, agent, board, override);
1095
1176
  const ctx = { core, logs, agentOf, agentFirst, timeoutMs, fresh, launch, waitLimit, limitClock };
1096
1177
  const unhook = stopWithSessions();
1097
1178
  try {
1098
1179
  const items = await (runMode === 'main'
1099
1180
  ? runMain(projectDir, ids, ctx)
1100
1181
  : runWorktrees(claims, ctx));
1101
- logMetrics(projectDir, 'run-log.csv', items.map(runRow(runMode)));
1182
+ // The run's id: its start alone does not keep two runs started at once apart.
1183
+ const runOf = { id: `${started}-${process.pid}`, started };
1184
+ logMetrics(projectDir, 'run-log.csv', items.map(runRow(runMode, runOf)));
1102
1185
 
1103
1186
  // `limit_wait`: this harness waits for a usage limit's reset itself (AD-19); a board reads it.
1104
1187
  return { orphans, mode: runMode, items, limit_wait: true };
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.12.2",
4
+ "version": "0.14.0",
5
5
  "description": "GCF orchestration harness for Claude Code: one-command card pipeline, readset guard",
6
6
  "skills": [
7
7
  "skills/gcf-run",
@@ -260,24 +260,32 @@ function requested(e) {
260
260
  input,
261
261
  title: String(title),
262
262
  reason: typeof e.request.description === 'string' ? e.request.description : null,
263
- always: alwaysOf(e.request.permission_suggestions),
263
+ ...alwaysOf(e.request.permission_suggestions),
264
264
  },
265
265
  ];
266
266
  }
267
267
 
268
+ // One tool of one MCP server, as claude names it (letters, digits, - and _): it suggests it
269
+ // bare, with no content to narrow it.
270
+ const MCP_TOOL = /^mcp__[A-Za-z0-9-][\w-]*__[A-Za-z0-9-][\w-]*$/;
271
+
268
272
  /**
269
273
  * The rule "always" would save (AD-2): claude's suggestion of an allow rule for the local
270
- * settings, as `Tool(content)`; null for none, for a bare tool or a bare `*`: too wide.
274
+ * settings, as `Tool(content)`; `always: null` for none, a bare `*`, or a bare tool, which is too
275
+ * wide, except one tool of an MCP server: the operator sees its name and decides, and the card
276
+ * says it holds for any arguments (`always_wide`).
271
277
  */
272
278
  function alwaysOf(suggestions) {
273
279
  const add = (Array.isArray(suggestions) ? suggestions : []).find(
274
280
  (s) => s?.type === 'addRules' && s.behavior === 'allow' && s.destination === 'localSettings',
275
281
  );
276
282
  const r = add?.rules?.[0];
283
+ const tool = typeof r?.toolName === 'string' ? r.toolName : '';
277
284
  const content = typeof r?.ruleContent === 'string' ? r.ruleContent.trim() : '';
278
- if (typeof r?.toolName !== 'string' || !content || /^\**$/.test(content)) return null;
285
+ if (!tool || /^\*+$/.test(content)) return { always: null };
286
+ if (!content) return MCP_TOOL.test(tool) ? { always: tool, always_wide: true } : { always: null };
279
287
 
280
- return `${r.toolName}(${content})`;
288
+ return { always: `${tool}(${content})` };
281
289
  }
282
290
 
283
291
  /** @returns {Neutral[]} */
@@ -311,12 +311,17 @@ function imagesOf(c, paths) {
311
311
  * engine. An input line's message has its `paths` (pictures), its `id` (which its `say` event
312
312
  * carries, AD-35), its `entry` in the input, and `retry` when an earlier session took it.
313
313
  * Returns whether it went: a closing session or a missing picture refuses it.
314
- * @param {{paths?: string[], id?: string, entry?: any, retry?: boolean}} [m]
314
+ * `own`: the operator's own words, when a prefix goes before them.
315
+ * @param {{paths?: string[], id?: string, entry?: any, retry?: boolean, own?: string}} [m]
315
316
  */
316
317
  function say(c, text, by, m = {}) {
317
- const { paths = [], id, entry = null, retry } = m;
318
+ const { paths = [], id, entry = null, retry, own = text } = m;
318
319
  const refused = (why) => {
319
- post(c, { type: 'error', text: `${why}, not sent: ${text.slice(0, 80)}` });
320
+ post(c, {
321
+ type: 'error',
322
+ text: `${why}, not sent: ${own.slice(0, 80)}`,
323
+ ...(id ? { id } : {}),
324
+ });
320
325
 
321
326
  return false;
322
327
  };
@@ -380,7 +385,7 @@ function heard(c, e, m) {
380
385
  const text = c.prefix ? `${c.prefix}\n\n${e.text}` : e.text;
381
386
  const paths = Array.isArray(e.images) ? e.images : [];
382
387
  // The context goes with the message that goes: a refused one leaves it for the next.
383
- if (say(c, text, 'operator', { paths, id, ...m }) && c.prefix) {
388
+ if (say(c, text, 'operator', { paths, id, own: e.text, ...m }) && c.prefix) {
384
389
  c.prefix = null;
385
390
  c.onPrefix?.();
386
391
  }
@@ -619,6 +624,8 @@ function permit(c, e) {
619
624
  title: e.title,
620
625
  ...(e.reason ? { reason: e.reason } : {}),
621
626
  ...(always ? { always } : {}),
627
+ // The rule holds for any arguments of the tool: the card says so before Always.
628
+ ...(always && e.always_wide ? { always_wide: true } : {}),
622
629
  });
623
630
  waitCards(c);
624
631
  }
@@ -27,6 +27,8 @@ export async function open(dir, t) {
27
27
  }
28
28
 
29
29
  const stop = path.join(td, 'stop');
30
+ // shortcut: a stop the board writes between the claim and this removal is lost (a window of
31
+ // milliseconds); the page's "closing…" gives up after 15 s, and the operator closes again.
30
32
  rmSync(stop, { force: true });
31
33
  const unhook = stopWithSessions();
32
34
  try {
@@ -57,5 +57,6 @@ export {
57
57
  threadAgent,
58
58
  threadDir,
59
59
  threadOf,
60
+ threadOfEntry,
60
61
  } from './thread.js';
61
62
  export { writeAtomic } from './store.js';
@@ -37,6 +37,7 @@ const AFTER_MS = 10 * 60_000;
37
37
  * watch of its neutral events; its result rides on the session
38
38
  * @property {() => boolean | Promise<boolean>} [done] the work made its move
39
39
  * @property {() => boolean} [stopped] the operator stopped the work
40
+ * @property {boolean} [halt] the stop ends a live session too, not only a wait between sessions
40
41
  * @property {any} [handoff] `{pct, windowOf(model, live), flag(info), clear()}`
41
42
  * @property {number} [maxHandoffs] fresh sessions in a row; the next handoff is the cap
42
43
  * @property {() => Promise<void>} [onCap] the cap is reached
@@ -192,6 +193,7 @@ async function session(j, kind, rec) {
192
193
  handoff: p.handoff,
193
194
  quota: p.quota,
194
195
  observe: watch?.see ?? null,
196
+ halt: p.halt ? p.stopped : undefined,
195
197
  // A project chat's options may be the kind's: the summary a fresh session starts from.
196
198
  chat: typeof p.chat === 'function' ? p.chat(kind, rec) : p.chat && { ...p.chat, kind },
197
199
  });
@@ -11,6 +11,9 @@ import { writeAtomic } from './store.js';
11
11
  const HARD_TURNS = 8;
12
12
  const HARD_OVER = 15;
13
13
 
14
+ /** How often a session that may be stopped (`halt`) looks for the stop. */
15
+ const HALT_POLL_MS = 1000;
16
+
14
17
  /**
15
18
  * Keep what a session's activity told: the last of each, and the model's window from the result.
16
19
  */
@@ -153,14 +156,34 @@ function launchSession(s) {
153
156
  return spawnAgent(command, dir, { ...env, ...adapter.env(dir) }, Boolean(chat));
154
157
  }
155
158
 
159
+ /**
160
+ * The operator's stop of a session that may be stopped (`halt`): `stop` once it comes, without
161
+ * waiting for the session's `close`, which a tool that outlived the kill may hold off by keeping
162
+ * the pipes open. The watch, to clear at the session's end.
163
+ */
164
+ function haltWatch(halt, stop) {
165
+ if (!halt) return undefined;
166
+ const t = setInterval(() => {
167
+ if (halt()) stop();
168
+ }, HALT_POLL_MS);
169
+ t.unref();
170
+
171
+ return t;
172
+ }
173
+
156
174
  /**
157
175
  * A session's timeout that stands still while the session waits for the operator (`pause`);
158
- * `waited()` is how long it stood. After `stop()` nothing starts it again.
176
+ * `waited()` is how long it stood. After `stop()` nothing starts it again. The operator's stop
177
+ * (`halt`) is watched with it.
178
+ * @param {number} ms
179
+ * @param {() => void} onTimeout
180
+ * @param {{halt?: () => boolean, stop: () => void}} onHalt
159
181
  */
160
- function sessionTimeout(ms, onTimeout) {
182
+ function sessionTimeout(ms, onTimeout, onHalt) {
161
183
  /** @type {{left: number, since: number, timer?: NodeJS.Timeout, waited: number,
162
184
  * pausedAt: number | null, stopped: boolean}} */
163
185
  const t = { left: ms, since: Date.now(), waited: 0, pausedAt: null, stopped: false };
186
+ const halting = haltWatch(onHalt.halt, onHalt.stop);
164
187
  const arm = () => {
165
188
  t.since = Date.now();
166
189
  t.timer = setTimeout(onTimeout, t.left);
@@ -186,6 +209,7 @@ function sessionTimeout(ms, onTimeout) {
186
209
  stop: () => {
187
210
  t.stopped = true;
188
211
  clearTimeout(t.timer);
212
+ clearInterval(halting);
189
213
  resume();
190
214
  },
191
215
  waited: () => t.waited,
@@ -208,6 +232,7 @@ function sessionTimeout(ms, onTimeout) {
208
232
  * @property {any} [handoff] `{pct, windowOf(model, live), flag(info)}`
209
233
  * @property {string | null} [quota] the file the last usage-limit state goes to
210
234
  * @property {any} [chat] the chat's options (chat.js `openChat`)
235
+ * @property {() => boolean} [halt] the operator stopped the work: the session ends at once
211
236
  * @property {((events: import('./activity.js').Neutral[]) => void) | null} [observe]
212
237
  */
213
238
 
@@ -233,7 +258,7 @@ function sessionTimeout(ms, onTimeout) {
233
258
  * handedOver: boolean, model?: string, window?: number, result?: string, waited: number}>}
234
259
  */
235
260
  export function runSession(s) {
236
- const { adapter, fd, timeoutMs, id, onSpawn, handoff, quota, chat, observe } = s;
261
+ const { adapter, fd, timeoutMs, id, onSpawn, handoff, quota, chat, observe, halt } = s;
237
262
 
238
263
  return new Promise((resolve) => {
239
264
  const child = launchSession(s);
@@ -259,7 +284,7 @@ export function runSession(s) {
259
284
  stop: stop('handoff'),
260
285
  onFlag: flagged,
261
286
  });
262
- const limit = sessionTimeout(timeoutMs, stop('timeout'));
287
+ const limit = sessionTimeout(timeoutMs, stop('timeout'), { halt, stop: stop('stopped') });
263
288
  /** @type {((tokens: number, model?: string) => void) | null} */
264
289
  let shown = null;
265
290
  if (chat) {
@@ -272,7 +297,8 @@ export function runSession(s) {
272
297
  const a = adapter.parse(line);
273
298
  // The result's window first: the chat's context share of this line is taken of it.
274
299
  absorb(seen, a);
275
- if (talk) talk.see(a.events);
300
+ // A stopped session ended before its pipes: what it still wrote reaches no chat.
301
+ if (talk && open) talk.see(a.events);
276
302
  if (a.quota && quota) keepQuota(quota, a.quota);
277
303
  observe?.(a.events);
278
304
  write(a.lines);
@@ -284,9 +310,10 @@ export function runSession(s) {
284
310
  write([line]);
285
311
  });
286
312
  function end(exit) {
287
- if (!open) return;
288
313
  flushOut();
289
314
  flushErr();
315
+ // Ended already, by an earlier call or by a last line that stopped it.
316
+ if (!open) return;
290
317
  open = false;
291
318
  limit.stop();
292
319
  // A project chat that closed its session says why: `idle`, `handoff`.
@@ -12,6 +12,7 @@ import {
12
12
  openSync,
13
13
  readFileSync,
14
14
  readdirSync,
15
+ renameSync,
15
16
  rmSync,
16
17
  writeFileSync,
17
18
  } from 'node:fs';
@@ -20,7 +21,9 @@ import { createHash } from 'node:crypto';
20
21
  import { PICKS } from './adapter/claude.js';
21
22
  import { adapterFor } from './adapter/index.js';
22
23
  import { runJob } from './job.js';
23
- import { alive, killTree } from './proc.js';
24
+ import { postTo, readFrom } from './chat.js';
25
+ import { realClock } from './limit.js';
26
+ import { alive } from './proc.js';
24
27
  import { chatsDir, runsDir, writeAtomic } from './store.js';
25
28
  import { readWindows, windowFor } from './windows.js';
26
29
 
@@ -30,9 +33,15 @@ export const THREAD_ID = /^t[0-9a-f]{8}$/;
30
33
  /** The share of the window a thread hands over at when the domain names none (AD-43). */
31
34
  export const HANDOFF_PCT = 60;
32
35
 
33
- /** How often a live session's thread looks for its stop mark. */
36
+ /** How often a thread waiting for the usage limit looks for its stop mark. */
34
37
  const STOP_POLL_MS = 1000;
35
38
 
39
+ // The limit wait's clock: the operator's stop ends it within a second, not at the next poll.
40
+ const stopClock = {
41
+ now: realClock.now,
42
+ sleep: (ms) => realClock.sleep(Math.min(ms, STOP_POLL_MS)),
43
+ };
44
+
36
45
  /** How long a summary turn may take before it counts as failed (AD-42). */
37
46
  export const SUMMARY_MS = 2 * 60_000;
38
47
 
@@ -62,11 +71,15 @@ const GIT_OPTS = String.raw`(?:(?:${GIT_OPT})\s+)*`;
62
71
  const GIT_CHANGES = new RegExp(String.raw`\bgit\s+${GIT_OPTS}(?:${GIT_VERBS})\b`);
63
72
 
64
73
  export const threadDir = (dir, t) => path.join(chatsDir(dir), t);
65
- const itemMark = (dir, item) => path.join(chatsDir(dir), 'items', item);
74
+ // A bound thread's mark: `chats/items/<item>` or `chats/entries/<entry>`, the thread's id.
75
+ const markOf = (dir, kind, key) => path.join(chatsDir(dir), kind, key);
66
76
 
67
- /** The thread `t`'s record, `{id, item, sessions, created_at, in_at}`. */
77
+ /** The thread `t`'s record, `{id, item, entry, sessions, created_at, in_at}`; no `entry`: null. */
68
78
  export function readThread(dir, t) {
69
- return JSON.parse(readFileSync(path.join(threadDir(dir, t), 'thread.json'), 'utf8'));
79
+ return {
80
+ entry: null,
81
+ ...JSON.parse(readFileSync(path.join(threadDir(dir, t), 'thread.json'), 'utf8')),
82
+ };
70
83
  }
71
84
 
72
85
  const writeThread = (dir, t, rec) =>
@@ -96,12 +109,14 @@ const pickFile = (td) => path.join(td, 'agent.json');
96
109
  const wordOf = (v) =>
97
110
  typeof v === 'string' && v !== AGENT_DEFAULT && PICK_WORD.test(v) ? v : null;
98
111
 
112
+ /** The plain words of a pick, `{model?, effort?}`; a bad word left out. */
113
+ const wordsOf = (v) =>
114
+ Object.fromEntries(PICKS.flatMap((k) => (wordOf(v?.[k]) ? [[k, v[k]]] : [])));
115
+
99
116
  /** What `agent.json` of folder `td` picks, `{model?, effort?}`; a hand edit's bad word left out. */
100
117
  function pickIn(td) {
101
118
  try {
102
- const v = JSON.parse(readFileSync(pickFile(td), 'utf8'));
103
-
104
- return Object.fromEntries(PICKS.flatMap((k) => (wordOf(v?.[k]) ? [[k, v[k]]] : [])));
119
+ return wordsOf(JSON.parse(readFileSync(pickFile(td), 'utf8')));
105
120
  } catch {
106
121
  return {};
107
122
  }
@@ -134,10 +149,10 @@ export function setThreadAgent(dir, t, pick) {
134
149
  return kept;
135
150
  }
136
151
 
137
- /** The thread bound to `item`, or null (AD-46). */
138
- export function threadOf(dir, item) {
152
+ /** The thread of mark `kind/key`, or null. */
153
+ function boundTo(dir, kind, key) {
139
154
  try {
140
- const t = readFileSync(itemMark(dir, item), 'utf8').trim();
155
+ const t = readFileSync(markOf(dir, kind, key), 'utf8').trim();
141
156
 
142
157
  return THREAD_ID.test(t) && existsSync(threadDir(dir, t)) ? t : null;
143
158
  } catch {
@@ -145,26 +160,71 @@ export function threadOf(dir, item) {
145
160
  }
146
161
  }
147
162
 
163
+ /** The thread bound to `item`, or null (AD-46). */
164
+ export const threadOf = (dir, item) => boundTo(dir, 'items', item);
165
+
166
+ /** The thread bound to inbox entry `entry` (Draft with agent), or null. */
167
+ export const threadOfEntry = (dir, entry) => boundTo(dir, 'entries', entry);
168
+
148
169
  /**
149
- * A new thread, its id; bound to `item`, the one it already has (AD-46). Ids and the item's
150
- * mark are made exclusively: two at once never take one id, nor give an item two threads.
170
+ * Bind new thread `t` to `key`, exclusively: the thread that holds the mark, `t` when it took
171
+ * it. Taken by a thread made just now: that one, and `t` goes. A mark whose thread is gone (its
172
+ * folder erased by hand) is stale: `t` takes it over.
151
173
  */
152
- export function createThread(dir, { item = null } = {}) {
153
- if (item && threadOf(dir, item)) return /** @type {string} */ (threadOf(dir, item));
154
- mkdirSync(path.join(chatsDir(dir), 'items'), { recursive: true });
155
- const t = newDir(dir);
156
- if (item) {
157
- try {
158
- writeFileSync(itemMark(dir, item), t, { flag: 'wx' });
159
- } catch (e) {
160
- rmSync(threadDir(dir, t), { recursive: true, force: true });
161
- if (/** @type {any} */ (e).code === 'EEXIST') return createThread(dir, { item });
162
- throw e;
163
- }
174
+ function takeMark(dir, kind, key, t) {
175
+ const had = markOnce(dir, [kind, key], t);
176
+ if (had) return had;
177
+ // A stale mark is moved aside under this thread's own name, then taken exclusively again: of
178
+ // two at once, the one whose move fails finds the other's mark on its last try.
179
+ // shortcut: a mark read between another's create and its write looks stale (empty); two boards
180
+ // on one project in that instant could still split a thread.
181
+ const aside = `${markOf(dir, kind, key)}.${t}`;
182
+ try {
183
+ renameSync(markOf(dir, kind, key), aside);
184
+ rmSync(aside, { force: true });
185
+ } catch {
186
+ // Moved by the other one: its mark wins below.
164
187
  }
165
188
 
189
+ return markOnce(dir, [kind, key], t, true);
190
+ }
191
+
192
+ /**
193
+ * One exclusive try at the mark: `t` when taken, the thread that holds it, or null for a stale
194
+ * one (`last`: throw then). `t`'s folder goes when it does not get the mark.
195
+ */
196
+ function markOnce(dir, [kind, key], t, last = false) {
197
+ try {
198
+ writeFileSync(markOf(dir, kind, key), t, { flag: 'wx' });
199
+
200
+ return t;
201
+ } catch (e) {
202
+ const taken = /** @type {any} */ (e).code === 'EEXIST';
203
+ const won = taken ? boundTo(dir, kind, key) : null;
204
+ if (!won && taken && !last) return null;
205
+ rmSync(threadDir(dir, t), { recursive: true, force: true });
206
+ if (won) return won;
207
+ throw e;
208
+ }
209
+ }
210
+
211
+ /**
212
+ * A new thread, its id; bound to `item` or to inbox `entry`, the one it already has (AD-46).
213
+ * Ids and the marks are made exclusively: two at once never take one id, nor give an item or an
214
+ * entry two threads. Both `item` and `entry` is a RangeError.
215
+ */
216
+ export function createThread(dir, { item = null, entry = null } = {}) {
217
+ if (item && entry) throw new RangeError('a thread is bound to an item or an entry, not both');
218
+ const [kind, key] = item ? ['items', item] : ['entries', entry];
219
+ const had = key ? boundTo(dir, kind, key) : null;
220
+ if (had) return had;
221
+ mkdirSync(path.join(chatsDir(dir), kind), { recursive: true });
222
+ const t = newDir(dir);
223
+ const won = key ? takeMark(dir, kind, key, t) : t;
224
+ if (won !== t) return won;
225
+
166
226
  const now = new Date().toISOString();
167
- writeThread(dir, t, { id: t, item, sessions: [], created_at: now, in_at: 0 });
227
+ writeThread(dir, t, { id: t, item, entry, sessions: [], created_at: now, in_at: 0 });
168
228
 
169
229
  return t;
170
230
  }
@@ -283,8 +343,8 @@ function flagsOf({ dir, td, spec, adapter }, settings) {
283
343
  * Run thread `t` of project `dir` until its session idles out, is stopped, or ends: a job of
284
344
  * sessions (AD-41), each resumed from the one before, a fresh one after a handoff (AD-42).
285
345
  * `spec` (its `spec.json`): `agent`, `rules` `{deny, ask, allow}`, `mcp` (config files),
286
- * `answerMin`, `handoffPct`, `window`, `skill`, `mainLock`, `timeoutMin`. `stopped()` says the
287
- * operator stopped it.
346
+ * `answerMin`, `handoffPct`, `window`, `skill`, `mainLock`, `timeoutMin`, `pick` (the project's
347
+ * model and effort, under the thread's own). `stopped()` says the operator stopped it.
288
348
  * @param {{stopped?: () => boolean}} [opts]
289
349
  */
290
350
  export async function runThread(dir, t, spec, opts = {}) {
@@ -304,28 +364,72 @@ export async function runThread(dir, t, spec, opts = {}) {
304
364
  summary: rec.sessions.findLast((x) => x.summary)?.summary ?? null,
305
365
  saved: /** @type {string | null} */ (null),
306
366
  started: contextHash(td),
307
- pid: 0,
308
367
  fd: openSync(path.join(td, 'thread.log'), 'a'),
309
368
  };
310
- // A stop ends the live session too, not only a wait between sessions.
311
- const watchStop = setInterval(() => {
312
- if (s.pid && stopped()) killTree(s.pid);
313
- }, STOP_POLL_MS);
314
- watchStop.unref();
369
+ /** @type {any} */
370
+ let ran = null;
315
371
  try {
316
372
  // The last session: resumed, or a fresh one from its summary after a handoff.
317
- const ran = await runJob(jobOf(s, goesOn(last)));
318
-
373
+ ran = await runJob(jobOf(s, goesOn(last)));
319
374
  // The session it resumed is gone: a fresh one takes the operator's message.
320
- return ran.lost && !stopped() ? await runJob(jobOf(s, null)) : ran;
375
+ if (ran.lost && !stopped()) ran = await runJob(jobOf(s, null));
376
+
377
+ return ran;
321
378
  } finally {
322
- clearInterval(watchStop);
379
+ // A stop that came after the session ended by itself closed nothing; one that came after a
380
+ // lost resume kept the fresh session from starting.
381
+ if (ran ? ran.stopped || (ran.lost && stopped()) : stopped()) closed(s);
323
382
  closeSync(s.fd);
324
383
  }
325
384
  }
326
385
 
386
+ /**
387
+ * The operator closed the thread's agent: what they wrote that no session took in is dropped,
388
+ * each message with its error line, and the chat says the agent is closed (AD-52). A message
389
+ * the agent had not yet acknowledged counts as not taken: it may have been lost with it.
390
+ */
391
+ function closed(s) {
392
+ const { rec, td } = s;
393
+ const out = path.join(td, 'chat.jsonl');
394
+ const { lines, next } = readFrom(path.join(td, 'chat-in.jsonl'), Number(rec.in_at) || 0);
395
+ const says = lines.flatMap((l) => {
396
+ try {
397
+ const e = JSON.parse(l);
398
+
399
+ return e?.type === 'say' ? [{ text: String(e.text ?? '').slice(0, 80), id: e.id }] : [];
400
+ } catch {
401
+ return [];
402
+ }
403
+ });
404
+ rec.in_at = next;
405
+ rec.in_read = Math.max(Number(rec.in_read) || 0, next);
406
+ // The record before the word: unwritten, the board would start the thread again with what the
407
+ // operator is told was dropped. A scanner's hold on the file passes in a moment.
408
+ for (let tries = 1; ; tries++)
409
+ try {
410
+ writeThread(s.dir, s.t, rec);
411
+ break;
412
+ } catch (e) {
413
+ if (tries === 3) throw e;
414
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 200);
415
+ }
416
+
417
+ for (const { text, id } of says)
418
+ postTo(out, {
419
+ type: 'error',
420
+ text: `the agent was closed, not sent: ${text}`,
421
+ ...(typeof id === 'string' ? { id } : {}),
422
+ });
423
+ postTo(out, { type: 'closed', dropped: says.length });
424
+ }
425
+
327
426
  const CHANGED = "The thread's context changed since this session began:";
328
427
 
428
+ // The first message of a session the operator closed, resumed (AD-52).
429
+ const CLOSED =
430
+ 'The operator closed your last session: the processes it started (servers, watchers, ' +
431
+ 'background tasks) are stopped.';
432
+
329
433
  // The first message of a session the usage limit cut, after its reset: the operator's last
330
434
  // message got no answer.
331
435
  const AFTER_LIMIT =
@@ -371,7 +475,10 @@ function keep(s, ran, kind) {
371
475
  const { rec, input } = s;
372
476
  rec.sessions.push({
373
477
  ...(ran.session_id ? { session_id: ran.session_id } : {}),
374
- ended: String(ran.code),
478
+ // Stopped as it idled out: what it started is killed all the same, and its resume is told.
479
+ ended: ran.stopped && ran.code === 'idle' ? 'stopped' : String(ran.code),
480
+ // Closed by the operator as it handed over: the fresh session is told too.
481
+ ...(ran.stopped ? { stopped: true } : {}),
375
482
  kind,
376
483
  context: s.started,
377
484
  ...(ran.code === 'handoff' && s.saved ? { summary: s.saved } : {}),
@@ -406,6 +513,19 @@ const handoverOf = (s) => ({
406
513
  },
407
514
  });
408
515
 
516
+ /**
517
+ * What the session's first message starts with: the operator's close of the session before
518
+ * (AD-52), the context that changed since it began; null for nothing.
519
+ */
520
+ function prefixOf(td, prev, changed) {
521
+ const parts = [
522
+ prev?.stopped || prev?.ended === 'stopped' ? CLOSED : null,
523
+ changed ? `${CHANGED}\n\n${readOr(path.join(td, 'context.md'))}` : null,
524
+ ].filter(Boolean);
525
+
526
+ return parts.length ? parts.join('\n\n') : null;
527
+ }
528
+
409
529
  /** The chat of a thread's session of `kind`, after the session `prev`. */
410
530
  function chatOf(s, kind, prev) {
411
531
  const { dir, td, rec, spec } = s;
@@ -436,7 +556,7 @@ function chatOf(s, kind, prev) {
436
556
  rec.unheard = false;
437
557
  keepTrying(dir, s.t, rec);
438
558
  },
439
- prefix: changed ? `${CHANGED}\n\n${readOr(path.join(td, 'context.md'))}` : null,
559
+ prefix: prefixOf(td, prev, changed),
440
560
  onPrefix: () => {
441
561
  s.started = now;
442
562
  },
@@ -460,17 +580,14 @@ function jobOf(s, record) {
460
580
  prompt: (kind, _caps, rec) => (rec?.ended === 'limit' ? AFTER_LIMIT : null),
461
581
  // The flags come before the chat of each session (job.js): the chat says what they picked.
462
582
  flags: (kind) => {
463
- s.pick = pickIn(s.td);
583
+ // The thread's own pick over the project's (`spec.pick`, as the thread's agent started).
584
+ s.pick = { ...wordsOf(spec.pick), ...pickIn(s.td) };
464
585
 
465
586
  return s.flags(kind, s.summary, s.pick);
466
587
  },
467
- onSpawn: (p) => {
468
- s.pid = p;
469
- },
470
- onIdle: () => {
471
- s.pid = 0;
472
- },
473
588
  stopped: s.stopped,
589
+ halt: true,
590
+ clock: stopClock,
474
591
  chatFile: path.join(s.td, 'chat.jsonl'),
475
592
  handoff: {
476
593
  pct: Number(spec.handoffPct) > 0 ? Number(spec.handoffPct) : HANDOFF_PCT,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gcf-session",
3
- "version": "0.12.2",
3
+ "version": "0.14.0",
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",
@@ -21,11 +21,13 @@ export type ChatEvent = At &
21
21
  }
22
22
  | {
23
23
  type: 'session_end';
24
- code: number | 'timeout' | 'handoff' | 'idle' | string;
24
+ code: number | 'timeout' | 'handoff' | 'idle' | 'stopped' | string;
25
25
  cost_usd: number | null;
26
26
  limit_resets?: string | null;
27
27
  }
28
28
  | { type: 'limit'; until: string }
29
+ /** A project chat's: the operator closed its agent; `dropped` messages it never took in. */
30
+ | { type: 'closed'; dropped: number }
29
31
  | {
30
32
  type: 'say';
31
33
  by: 'run' | 'operator' | 'timeout' | 'engine';
@@ -41,7 +43,8 @@ export type ChatEvent = At &
41
43
  | { type: 'waiting'; kind: 'card' | 'text' | 'stop' }
42
44
  | { type: 'timeout'; kind: 'card' | 'text' }
43
45
  | { type: 'interrupt' }
44
- | { type: 'error'; text: string }
46
+ /** `id`: the input line of the operator's message it did not send, when it has one. */
47
+ | { type: 'error'; text: string; id?: string }
45
48
  | { type: 'background'; tasks: { id: string; description: string }[] }
46
49
  | {
47
50
  type: 'question';
@@ -68,6 +71,8 @@ export type ChatEvent = At &
68
71
  title: string;
69
72
  reason?: string;
70
73
  always?: string;
74
+ /** `always` holds for any arguments of the tool (one MCP tool, bare). */
75
+ always_wide?: boolean;
71
76
  }
72
77
  | { type: 'allowed'; request_id: string; by: 'operator'; always: boolean; rule?: string }
73
78
  | {
@@ -129,6 +134,8 @@ export interface Rule {
129
134
  export interface Thread {
130
135
  id: string;
131
136
  item: string | null;
137
+ /** The inbox entry the thread drafts an item from (Draft with agent); null for none. */
138
+ entry: string | null;
132
139
  sessions: { session_id?: string; ended: string; kind: string; summary?: string }[];
133
140
  created_at: string;
134
141
  in_at: number;
@@ -145,6 +152,8 @@ export interface ThreadSpec {
145
152
  skill?: string;
146
153
  mainLock?: string | null;
147
154
  timeoutMin?: number;
155
+ /** The project's model and effort: a session takes them where the thread picked none. */
156
+ pick?: AgentPick;
148
157
  }
149
158
 
150
159
  /** The model and effort an operator picked, `chats/<t>/agent.json`: none, the agent's own. */
@@ -166,8 +175,12 @@ export declare function setThreadAgent(
166
175
  pick: { model?: string | null; effort?: string | null },
167
176
  ): AgentPick;
168
177
  export declare function presetsOf(agent: string): AgentPresets;
169
- export declare function createThread(dir: string, opts?: { item?: string | null }): string;
178
+ export declare function createThread(
179
+ dir: string,
180
+ opts?: { item?: string | null; entry?: string | null },
181
+ ): string;
170
182
  export declare function threadOf(dir: string, item: string): string | null;
183
+ export declare function threadOfEntry(dir: string, entry: string): string | null;
171
184
  export declare function threadDir(dir: string, t: string): string;
172
185
  export declare function readThread(dir: string, t: string): Thread;
173
186
  export declare function listThreads(dir: string): Thread[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gcf-harness-aif-ext",
3
- "version": "0.12.2",
3
+ "version": "0.14.0",
4
4
  "description": "GCF orchestration harness for Claude Code: one-command card pipeline, readset guard",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -28,7 +28,7 @@
28
28
  "prepack": "node -e \"const p=require('./package.json'),e=require('./extension.json');if(p.version!==e.version)throw new Error('version mismatch: package.json '+p.version+' vs extension.json '+e.version);require('node:fs').statSync('node_modules/gcf-session/lib/index.js')\""
29
29
  },
30
30
  "peerDependencies": {
31
- "gcf-aif-ext": "^0.12.0"
31
+ "gcf-aif-ext": "^0.14.0"
32
32
  },
33
33
  "dependencies": {
34
34
  "gcf-session": "file:../gcf-session"