gcf-harness-aif-ext 0.15.0 → 0.16.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.
package/README.md CHANGED
@@ -47,6 +47,8 @@ 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.16.1 needs gcf-aif-ext 0.16.1: an older core would merge a worktree branch under a main run's agent (Board-PRD decision 28). Without `--mode` each item runs where its own `run_mode` says, else the project's; a batch of both is two parts at once under one gate, one report (`mode: main+worktree`, in the order the items came). A main run's own sessions still run `gcf integrate` at their start, as before. A main run names the items it has yet to reach in `.gcf-session/runs/.main-run.queue`, and the gate counts them as running, so a worktree run beside it cannot take them. While a main run holds the checkout, core 0.16 merges nothing: a worktree item whose branch is green reads `verified` ("its branch merges when that run ends"), and the main run merges it as it ends (its `orphans`).
51
+
50
52
  0.15.0 works with gcf-aif-ext 0.14.0 or 0.15.0. A run on main refreshes and, at the end, clears its item's session mark only while the mark is its own (`GCF_RUN_OWNER`) or names nobody: a mark another session claimed after a `gcf release` by hand stays that session's.
51
53
 
52
54
  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`.
@@ -9,7 +9,15 @@ import { spawnSync } from 'node:child_process';
9
9
  import path from 'node:path';
10
10
  import { fileURLToPath } from 'node:url';
11
11
  import { metricsCommand, runsCommand } from './metrics.js';
12
- import { run, cliCore, DEFAULT_AGENT, DEFAULT_TIMEOUT_MIN, MAIN_RUN, stopOf } from './run.js';
12
+ import {
13
+ run,
14
+ cliCore,
15
+ DEFAULT_AGENT,
16
+ DEFAULT_TIMEOUT_MIN,
17
+ MAIN_RUN,
18
+ queueOf,
19
+ stopOf,
20
+ } from './run.js';
13
21
  import { CHAT_TIMEOUT_MIN, ChatRefusal, alive, chatInput, killTree, readText } from 'gcf-session';
14
22
 
15
23
  const EXT_ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
@@ -139,13 +147,35 @@ export function gate(report, ids) {
139
147
  );
140
148
  }
141
149
 
142
- /** `gcf audit` exits 1 on any finding, so the report is read from stdout whatever the code. */
150
+ /**
151
+ * The report with the items a live main run has yet to reach (`.main-run.queue`) as running:
152
+ * they hold no lock or mark before their turn, and another run must not take them meanwhile.
153
+ */
154
+ export function withMainQueue(report, runs) {
155
+ if (!Array.isArray(report?.items) || !lockOf(path.join(runs, `${MAIN_RUN}.lock`))) return report;
156
+ let queued;
157
+ try {
158
+ queued = new Set(readFileSync(queueOf(runs), 'utf8').split('\n').filter(Boolean));
159
+ } catch {
160
+ return report;
161
+ }
162
+
163
+ return {
164
+ ...report,
165
+ items: report.items.map((i) => (queued.has(i.id) ? { ...i, running: true } : i)),
166
+ };
167
+ }
168
+
169
+ /**
170
+ * `gcf audit` exits 1 on any finding, so the report is read from stdout whatever the code. The
171
+ * items a main run has queued count as running.
172
+ */
143
173
  function auditReport() {
144
174
  // Re-enter the same ai-factory CLI that is running this command: no PATH or .cmd lookup.
145
175
  const args = [process.argv[1], 'gcf', 'audit', '--json'];
146
176
  const res = spawnSync(process.execPath, args, { encoding: 'utf8' });
147
177
  try {
148
- return JSON.parse(res.stdout);
178
+ return withMainQueue(JSON.parse(res.stdout), path.join(process.cwd(), '.gcf-session', 'runs'));
149
179
  } catch (err) {
150
180
  const output = (res.stderr || res.stdout || '').trim();
151
181
  throw new Error(`\`ai-factory gcf audit --json\` produced no report: ${output}`, {
package/commands/run.js CHANGED
@@ -93,6 +93,18 @@ export function cliCore(projectDir) {
93
93
  };
94
94
  }
95
95
 
96
+ /**
97
+ * Merge the verified branches now (`gcf integrate`): their results; none, `waits`, while a main
98
+ * run works in the checkout: the core merges nothing under it, and they go in when it ends.
99
+ */
100
+ async function integrateNow(core) {
101
+ const r = await core(['integrate', '--json']);
102
+ if (!r.ok && /a main run works in the main checkout/.test(r.err + r.out))
103
+ return { results: [], waits: true };
104
+
105
+ return { results: json(r, 'integrate') };
106
+ }
107
+
96
108
  /** The JSON report of a core command, or its refusal as the error. */
97
109
  export function json(res, what) {
98
110
  try {
@@ -789,6 +801,13 @@ function unverify(r) {
789
801
  }
790
802
 
791
803
  /** The result line of an item the integrator handled, or why it has none. */
804
+ /** A verified branch a main run keeps out of the checkout: it merges as that run ends. */
805
+ const waiting = (run) => ({
806
+ id: run.id,
807
+ result: 'verified',
808
+ reason: 'a main run works in the main checkout: its branch merges when that run ends',
809
+ });
810
+
792
811
  function resultOf(run, integrated) {
793
812
  const done = integrated.find((x) => x.id === run.id);
794
813
  if (!done && run.error) return { id: run.id, result: 'error', error: run.error };
@@ -875,14 +894,12 @@ export const MAIN_RUN = '.main-run';
875
894
  * `run_mode: main` (Methodology §7): one item after another in the main checkout, where the
876
895
  * editor the agent works through lives. The agent records each item's move itself, so the item
877
896
  * carries a session mark (`gcf claim`), not a run lock: a lock would refuse the agent's own
878
- * moves. A session that stopped without a move leaves no mark behind.
897
+ * moves. The items it has yet to reach are named in `.main-run.queue`, so another run's gate
898
+ * counts them, and stay free to change: each takes its model as it starts. A session that
899
+ * stopped without a move leaves no mark behind.
879
900
  */
880
- async function runMain(projectDir, ids, ctx) {
901
+ async function runMain(projectDir, ids, releaseMain, ctx) {
881
902
  const { logs } = ctx;
882
- // The owner of the items' marks: this run's core calls and every agent session it starts
883
- // (a fresh one after a handoff included) inherit it, so their `gcf claim` and moves pass.
884
- process.env.GCF_RUN_OWNER = `run:${process.pid}`;
885
- const releaseMain = await claim(lockFile(logs, MAIN_RUN));
886
903
  if (!releaseMain)
887
904
  return ids.map((id) => ({
888
905
  id,
@@ -890,20 +907,51 @@ async function runMain(projectDir, ids, ctx) {
890
907
  error: 'another run works in the main checkout: wait for it, or stop it',
891
908
  started: false,
892
909
  }));
910
+ // The owner of the items' marks: this run's core calls and every agent session it starts
911
+ // (a fresh one after a handoff included) inherit it, so their `gcf claim` and moves pass.
912
+ process.env.GCF_RUN_OWNER = `run:${process.pid}`;
893
913
 
894
914
  const items = [];
895
915
  try {
896
- for (const id of ids) items.push(await mainItem(projectDir, id, ctx));
916
+ for (const [n, id] of ids.entries()) {
917
+ // Its mark holds it from its claim on: the queue lets it go then.
918
+ // Advisory only: a write refused (a file held by a scanner) leaves the item run as it is.
919
+ const dequeue = () => {
920
+ try {
921
+ writeAtomic(queueOf(logs), `${ids.slice(n + 1).join('\n')}\n`);
922
+ } catch {}
923
+ };
924
+ items.push(await mainItem(projectDir, id, { ...ctx, dequeue }));
925
+ }
897
926
  } finally {
927
+ await rm(queueOf(logs), { force: true });
898
928
  await releaseMain();
899
929
  }
900
930
 
901
931
  return items;
902
932
  }
903
933
 
934
+ /** The items a main run has yet to reach, one id a line. */
935
+ export const queueOf = (logs) => path.join(logs, `${MAIN_RUN}.queue`);
936
+
937
+ /** The main checkout for a main run, with its items queued; null while another run holds it. */
938
+ async function holdMain(logs, ids) {
939
+ const release = await claim(lockFile(logs, MAIN_RUN));
940
+ // Whole or not at all: a gate reads it meanwhile. With no queue the checkout is not held:
941
+ // another run's gate would see the items free.
942
+ try {
943
+ if (release) writeAtomic(queueOf(logs), `${ids.join('\n')}\n`);
944
+ } catch (e) {
945
+ await release?.();
946
+ throw e;
947
+ }
948
+
949
+ return release;
950
+ }
951
+
904
952
  /** One item of a main run: marked, its session, its mark cleared, its result read. */
905
953
  async function mainItem(projectDir, id, ctx) {
906
- const { core, logs, agentOf } = ctx;
954
+ const { core, logs, agentOf, dequeue } = ctx;
907
955
  let r;
908
956
  let started = false;
909
957
  let marked = false;
@@ -913,8 +961,12 @@ async function mainItem(projectDir, id, ctx) {
913
961
  writeFileSync(path.join(logs, `${MAIN_RUN}.lock`), `${process.pid}\n${id}\n`);
914
962
  try {
915
963
  const claimed = await core(['claim', id]);
916
- if (!claimed.ok) throw new Error((claimed.err || claimed.out).trim());
964
+ if (!claimed.ok) {
965
+ dequeue();
966
+ throw new Error((claimed.err || claimed.out).trim());
967
+ }
917
968
  marked = true;
969
+ dequeue();
918
970
  const none = async () => {};
919
971
 
920
972
  // The agent recorded the item's move: no fresh session takes it over.
@@ -962,6 +1014,21 @@ async function mainItem(projectDir, id, ctx) {
962
1014
  }
963
1015
 
964
1016
  /** The checkout's HEAD, or null before its first commit. */
1017
+ /** Whether main merged item `id`'s branch since `head`: the integrator's `gcf(integrate): <id>`. */
1018
+ function mergedSince(dir, id, head) {
1019
+ if (!head) return false;
1020
+ const r = spawnSync('git', ['log', '--format=%s', `${head}..HEAD`], {
1021
+ cwd: dir,
1022
+ encoding: 'utf8',
1023
+ });
1024
+ const subject = `gcf(integrate): ${id}`;
1025
+
1026
+ // `tray` must not match `tray-2`: the id ends at the end or at a space (a spike's ` plan`).
1027
+ return (
1028
+ r.status === 0 && r.stdout.split('\n').some((s) => s === subject || s.startsWith(`${subject} `))
1029
+ );
1030
+ }
1031
+
965
1032
  function headOf(dir) {
966
1033
  const r = spawnSync('git', ['rev-parse', '--verify', '-q', 'HEAD'], {
967
1034
  cwd: dir,
@@ -1051,6 +1118,8 @@ const extras = (r, note = null) => {
1051
1118
  /** Every claimed item in its worktree at once; blocks recorded on main, verified ones merged. */
1052
1119
  async function runWorktrees(claims, ctx) {
1053
1120
  const { core, logs } = ctx;
1121
+ // Main as the run starts: a merge since is in its log.
1122
+ const head = headOf(ctx.projectDir);
1054
1123
  // Its items are locked already: no move changes them after the run's first read.
1055
1124
  const { ready, failed } = await prepare(claims, core, ctx.agentFirst);
1056
1125
  // A session that verified its branch, or left an outcome, is done: no fresh one follows.
@@ -1070,8 +1139,33 @@ async function runWorktrees(claims, ctx) {
1070
1139
  }
1071
1140
  }
1072
1141
 
1073
- const integrated = json(await core(['integrate', '--json']), 'integrate');
1074
- for (const r of runs) if (!items.some((i) => i.id === r.id)) items.push(resultOf(r, integrated));
1142
+ const { results: integrated, waits } = await integrateNow(core);
1143
+ const open = runs.filter(
1144
+ (r) => !items.some((i) => i.id === r.id) && !integrated.some((x) => x.id === r.id),
1145
+ );
1146
+ // A branch another run merged meanwhile (a main run, at its end or a session's start): its
1147
+ // move is on the board.
1148
+ const now = open.length ? (json(await core(['board', '--json']), 'board').items ?? []) : [];
1149
+ for (const r of runs) {
1150
+ if (items.some((i) => i.id === r.id)) continue;
1151
+ const after = now.find((i) => i.id === r.id);
1152
+ // Only the integrator's own commit says the branch went in: a drop by hand is no merge.
1153
+ const moved = open.includes(r) && !r.error && mergedSince(ctx.projectDir, r.id, head);
1154
+ const gone = open.includes(r) && !moved && !after;
1155
+ items.push(
1156
+ moved
1157
+ ? {
1158
+ id: r.id,
1159
+ result: after ? (MOVE_OF[after.status] ?? after.status) : 'close',
1160
+ reason: 'its branch was merged by another run meanwhile',
1161
+ }
1162
+ : gone
1163
+ ? { id: r.id, result: 'skipped', reason: 'it left the board meanwhile, by another move' }
1164
+ : waits && verified(r.dir, r.id)
1165
+ ? waiting(r)
1166
+ : resultOf(r, integrated),
1167
+ );
1168
+ }
1075
1169
  // A worktree's session records no move: the chat hears of the one main recorded for it.
1076
1170
  if (ctx.launch?.chat)
1077
1171
  for (const i of items.filter((x) => ['submit', 'close', 'block'].includes(x.result)))
@@ -1122,13 +1216,15 @@ function commandsOf(core, agent, board, override) {
1122
1216
  return { agentOf, agentFirst: (id) => commandOf(board, id) };
1123
1217
  }
1124
1218
 
1125
- /** The mode a run takes: the one asked for, else the project's. */
1126
- const modeOf = (mode, board) => mode ?? board.run_mode ?? 'worktree';
1219
+ /** Where an item's run goes: the run's mode, else the item's `run_mode`, else the project's. */
1220
+ const modeOf = (mode, board, item) => mode ?? item?.run_mode ?? board.run_mode ?? 'worktree';
1127
1221
 
1128
1222
  /**
1129
- * Pick up orphans, gate the batch, run the items in the project's run mode (`mode` overrides
1130
- * it). `gate(ids)` answers `{pass, reason}`; a session past `timeoutMs` is stopped with all it
1131
- * started, and its item stays ready. `fresh` starts new sessions where kept ones would resume;
1223
+ * Pick up orphans, gate the batch, run each item where it runs: the run's `mode`, else its own
1224
+ * `run_mode`, else the project's. Items of two modes are two parts at once under one gate, one
1225
+ * report: the main part in the checkout, one item after another, the worktree part beside it;
1226
+ * a branch it verifies merges when the main part ends. `gate(ids)` answers `{pass, reason}`; a
1227
+ * session past `timeoutMs` is stopped with all it started, and its item stays ready. `fresh` starts new sessions where kept ones would resume;
1132
1228
  * `waitLimit` holds each session while the account's usage limit is known to reset ahead.
1133
1229
  * `chat` ({answerMs}) keeps each session open to the operator (docs/Chat-Plan.md).
1134
1230
  * The core's moves it and its agents make name the run as their maker (`GCF-By`); the variable
@@ -1177,39 +1273,80 @@ async function runBatch(
1177
1273
  const override = { model, effort };
1178
1274
  // A bad override is the run's error, before anything starts.
1179
1275
  choiceOf(null, override);
1180
- const orphans = json(await core(['integrate', '--json']), 'integrate');
1276
+ const orphans = (await integrateNow(core)).results;
1181
1277
  const logs = path.join(path.resolve(projectDir), '.gcf-session', 'runs');
1182
1278
  await mkdir(logs, { recursive: true });
1183
1279
  const board = json(await core(['board', '--json']), 'board');
1184
- const runMode = modeOf(mode, board);
1280
+ // Each item where it runs: one part per mode, in the order their items came.
1281
+ const parts = [
1282
+ ...Map.groupBy(ids, (id) =>
1283
+ modeOf(
1284
+ mode,
1285
+ board,
1286
+ board.items?.find((i) => i.id === id),
1287
+ ),
1288
+ ),
1289
+ ];
1185
1290
  timeoutMs ??= (board.session_timeout_min ?? DEFAULT_TIMEOUT_MIN) * 60_000;
1186
1291
  // Before any item is claimed: a refusal here leaves no lock behind.
1187
1292
  const launch = await launchOf(logs, managed, board, chat);
1188
- // The gate counts the items other runs hold locks on, so this run's locks go in with its gate.
1189
- // shortcut: a main run marks each item only as its session starts, so the items it has yet
1190
- // to reach do not count for another run's gate; claim them all here if main and worktree
1191
- // runs come to share a project.
1293
+ // One gate over the whole batch, and this run's holds go in with it: the gate counts the items
1294
+ // other runs hold. A worktree part's locks; a main part's checkout with its queue, the items it
1295
+ // has yet to reach.
1192
1296
  const { passed, claims } = await admitted(logs, async () => {
1193
1297
  const verdict = gate(ids);
1194
- const go = verdict.pass && runMode !== 'main';
1298
+ if (!verdict.pass) return { passed: verdict, claims: null };
1299
+ const held = new Map();
1300
+ try {
1301
+ for (const [m, part] of parts)
1302
+ held.set(m, m === 'main' ? await holdMain(logs, part) : await claimAll(part, logs));
1303
+ } catch (e) {
1304
+ // What was taken goes back: a hold the run never uses must not wait for its exit.
1305
+ for (const [m, h] of held)
1306
+ if (m === 'main') await h?.();
1307
+ else for (const c of h.claimed) await c.release();
1308
+ throw e;
1309
+ }
1195
1310
 
1196
- return { passed: verdict, claims: go ? await claimAll(ids, logs) : null };
1311
+ return { passed: verdict, claims: held };
1197
1312
  });
1198
1313
  if (!passed.pass) return { orphans, gate: passed.reason, items: [] };
1199
1314
 
1200
1315
  const { agentOf, agentFirst } = commandsOf(core, agent, board, override);
1201
- const ctx = { core, logs, agentOf, agentFirst, timeoutMs, fresh, launch, waitLimit, limitClock };
1316
+ const ctx = {
1317
+ ...{ projectDir, core, logs, agentOf, agentFirst, timeoutMs },
1318
+ ...{ fresh, launch, waitLimit, limitClock },
1319
+ };
1202
1320
  const unhook = stopWithSessions();
1203
1321
  try {
1204
- const items = await (runMode === 'main'
1205
- ? runMain(projectDir, ids, ctx)
1206
- : runWorktrees(claims, ctx));
1207
1322
  // The run's id: its start alone does not keep two runs started at once apart.
1208
1323
  const runOf = { id: `${started}-${process.pid}`, started };
1209
- logMetrics(projectDir, 'run-log.csv', items.map(runRow(runMode, runOf)));
1324
+ // Each part to its end, a failing one too: the other's sessions are not left behind.
1325
+ const driven = await Promise.allSettled(
1326
+ parts.map(async ([m, part]) => {
1327
+ const items = await (m === 'main'
1328
+ ? runMain(projectDir, part, claims.get(m), ctx)
1329
+ : runWorktrees(claims.get(m), ctx));
1330
+ logMetrics(projectDir, 'run-log.csv', items.map(runRow(m, runOf)));
1331
+
1332
+ return items;
1333
+ }),
1334
+ );
1335
+ const failed = driven.find((d) => d.status === 'rejected');
1336
+ if (failed) throw failed.reason;
1337
+ // The branches worktree runs verified while a main part held the checkout go in now; a main
1338
+ // its session left dirty keeps them for the next run.
1339
+ const after = claims.has('main')
1340
+ ? (await integrateNow(core).catch(() => ({ results: [] }))).results
1341
+ : [];
1210
1342
 
1211
1343
  // `limit_wait`: this harness waits for a usage limit's reset itself (AD-19); a board reads it.
1212
- return { orphans, mode: runMode, items, limit_wait: true };
1344
+ return {
1345
+ orphans: [...orphans, ...after],
1346
+ mode: parts.map(([m]) => m).join('+'),
1347
+ items: driven.flatMap((d) => (d.status === 'fulfilled' ? d.value : [])),
1348
+ limit_wait: true,
1349
+ };
1213
1350
  } finally {
1214
1351
  unhook();
1215
1352
  }
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.15.0",
4
+ "version": "0.16.1",
5
5
  "description": "GCF orchestration harness for Claude Code: one-command card pipeline, readset guard",
6
6
  "skills": [
7
7
  "skills/gcf-run",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gcf-harness-aif-ext",
3
- "version": "0.15.0",
3
+ "version": "0.16.1",
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.14.0 || ^0.15.0"
31
+ "gcf-aif-ext": "^0.16.1"
32
32
  },
33
33
  "dependencies": {
34
34
  "gcf-session": "file:../gcf-session"