gcf-harness-aif-ext 0.28.1 → 0.30.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
@@ -176,7 +176,8 @@ Removal does not touch `.claude/settings.json`: delete the entries whose command
176
176
 
177
177
  - `gcf-harness hold <id>` holds an item: its session hands over at its next call, its work waits `ready`, and your Run goes on from the plan. `hold --project` holds the queue and the autopilot (your own Run still goes); `hold --release [<id>]` lets go.
178
178
  - Automation (`--wait-limit`, the autopilot's card sessions) keeps `quota_reserve_pct` of each usage window (`~/.gcf/settings.json`, 10): it waits for the 5-hour reset, and stops at the week's.
179
- - Planning and implementation are two sessions: `GCF_RUN_PHASE` comes from `gcf plan check`; `aif-implement` goes only on a converged plan. `gcf-harness plan-review <id>` is an outside reviewer's read-only pass (Codex CLI, `plan_review:`).
179
+ - `gcf-harness wake <id>` (or `--thread <t>`, or `--all`): the usage limit was reset early, so a live limit or reserve wait goes on now; it marks only a wait that lives. A fresh `/usage` reading under the limit wakes a wait too (automation reads it every 5 minutes; your own Run and a chat thread ask it themselves). A wake before the reset spends no try; the operator's wake lets the reserve go till that reset. The wait's chat says `limit {until, reserve?, pct?}` and, at its end, `limit_end {by}`. `gcf-harness chat say --json` prints `{id}` of the line it wrote.
180
+ - Planning and implementation are two sessions: `GCF_RUN_PHASE` comes from `gcf plan check`; `aif-implement` goes only on a converged plan. `gcf-harness codex-review <id> --kind plan|code --pass <k> --json` is a review pass by the Codex CLI, read-only, when row k of `review.plan|code` is Codex's: a family (`sol`, `astra`) is the newest listed slug of `codex debug models` (kept 6 h in `.gcf-session/codex-models.json`, `--bundled` when the live read fails); Claude rows are the session's subagents with the row's model and effort. A code review's rows over with a blocking finding: the code is committed and the card blocks (`stall.code`); under `--worktree` the trailer comes off first, so nothing merges until the human answers. Each session gets `GCF_RUN_BASE`, the commit its card's work started from.
180
181
 
181
182
  ## Docs
182
183
 
@@ -0,0 +1,125 @@
1
+ // `gcf-harness codex-review <id> --kind plan|code --pass <k>` (Operator-Tasks-Plan t2 d2): a review
2
+ // pass by the Codex CLI, read-only, when row k of `review.plan|code` is Codex's. Codex runs in its
3
+ // read-only sandbox: the audit holds by the sandbox, not by trust. The row's model is a family
4
+ // (`sol`), made the newest listed slug of the catalog, or a full slug as it is. Its answer is
5
+ // findings as JSON; with no Codex, or when it fails, the session's own subagent makes the pass
6
+ // (SKILL.md, steps 8-11 and 14-16).
7
+ import { spawnSync } from 'node:child_process';
8
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { codexInstalled, codexModels, slugOf } from 'gcf-session';
13
+
14
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
15
+ export const FINDINGS_SCHEMA = path.join(HERE, 'codex-review.schema.json');
16
+ export const REVIEW_TIMEOUT_MS = 25 * 60_000;
17
+
18
+ const ANSWER = [
19
+ 'A finding is blocking when the work, as it stands, would be wrong, miss what the item asks,',
20
+ 'break what the code already does or a pillar; polish when it only reads better.',
21
+ 'Answer with the findings only, as the schema says.',
22
+ ];
23
+
24
+ /**
25
+ * The review's prompt: what to read and how to answer; the reviewer reads the files itself. The
26
+ * plan's carries aif-improve's criteria and the pillars' invariants; the code's the diff file and
27
+ * the pillars' review questions (SKILL.md steps 9, 15).
28
+ * @param {{id: string, kind: string, plan: string, diff?: string | null}} o
29
+ */
30
+ export function reviewPrompt({ id, kind, plan, diff }) {
31
+ if (kind === 'code')
32
+ return [
33
+ `Review the code change of work item ${id} before its commit. The diff is in ${diff};`,
34
+ `read it, the item gcf/work/${id}.md, its plan ${plan} and the code around the change.`,
35
+ 'Change nothing. Check that the change does what the item and the plan ask, breaks nothing,',
36
+ 'and is tested. Answer the review_question of each pillar in gcf/PILLARS.md over the diff:',
37
+ 'an answer that breaks a pillar is a blocking finding.',
38
+ ...ANSWER,
39
+ ].join('\n');
40
+
41
+ return [
42
+ `Audit the implementation plan of work item ${id}: ${plan}.`,
43
+ `Read the item gcf/work/${id}.md, the plan, and the code the plan names. Change nothing.`,
44
+ 'Apply the criteria of an improve pass: every task provable by a check, nothing the item asks',
45
+ 'missing, no wrong behavior, no conflict with a project rule. Check every task against the',
46
+ 'invariant of each pillar in gcf/PILLARS.md, and against the graveyard_hits lines of',
47
+ `\`ai-factory gcf context ${id} --json\`. Check each claim of the plan against the code.`,
48
+ ...ANSWER,
49
+ ].join('\n');
50
+ }
51
+
52
+ /**
53
+ * Run the pass: `{findings, by}`, `{skipped: why}` (the row is not Codex's, no Codex) or
54
+ * `{failed: why}`. `row` is `gcf review row`'s answer; `codex` the command (a test's fake).
55
+ * @param {string} projectDir
56
+ * @param {{row: any, codex?: string[], timeoutMs?: number}} o
57
+ */
58
+ export function codexReview(projectDir, o) {
59
+ const { row } = o;
60
+ if (row.row?.agent !== 'codex')
61
+ return { skipped: `pass ${row.pass} is ${row.by ?? 'no row'}'s: a subagent makes it` };
62
+ const cmd = o.codex
63
+ ? { exe: o.codex[0], pre: o.codex.slice(1), shell: false }
64
+ : { exe: 'codex', pre: [], shell: process.platform === 'win32' };
65
+ if (!codexInstalled(cmd)) return { skipped: 'no codex in PATH' };
66
+ // The catalog is read once a while for the project's runs (t2 d4).
67
+ const cache = path.join(projectDir, '.gcf-session', 'codex-models.json');
68
+ const slug = slugOf(codexModels({ cache, cmd }), row.row.model);
69
+ if (!slug) return { failed: `Codex lists no model of ${row.row.model}` };
70
+ const { effort } = row.row;
71
+
72
+ return { ...run(projectDir, cmd, { ...o, slug, effort }), by: `codex:${slug}:${effort}` };
73
+ }
74
+
75
+ /**
76
+ * `codex exec` in its read-only sandbox, the findings to a file.
77
+ * @param {string} projectDir
78
+ * @param {any} cmd
79
+ * @param {any} o
80
+ */
81
+ function run(projectDir, cmd, { row, slug, effort, timeoutMs }) {
82
+ const dir = mkdtempSync(path.join(os.tmpdir(), 'gcf-review-'));
83
+ const out = path.join(dir, 'findings.json');
84
+ try {
85
+ const args = [
86
+ ...['exec', '-', '-s', 'read-only', '-m', slug],
87
+ ...['-c', `model_reasoning_effort=${effort}`, '--ephemeral'],
88
+ ...['--output-schema', FINDINGS_SCHEMA, '-o', out],
89
+ ];
90
+ const res = spawnSync(cmd.exe, [...cmd.pre, ...args], {
91
+ windowsHide: true,
92
+ cwd: projectDir,
93
+ input: reviewPrompt({ ...row, diff: row.diff?.file ?? null }),
94
+ encoding: 'utf8',
95
+ timeout: timeoutMs ?? REVIEW_TIMEOUT_MS,
96
+ shell: cmd.shell,
97
+ });
98
+ if (/** @type {NodeJS.ErrnoException | undefined} */ (res.error)?.code === 'ETIMEDOUT')
99
+ return { failed: 'the review timed out' };
100
+ // A flag or a model the CLI does not take is named as it said it (Hold-Plan risk 11).
101
+ if (res.status !== 0)
102
+ return { failed: `codex exit ${res.status}: ${firstLine(res.stderr || res.stdout)}` };
103
+
104
+ return findingsOf(out);
105
+ } finally {
106
+ rmSync(dir, { recursive: true, force: true });
107
+ }
108
+ }
109
+
110
+ const firstLine = (text) =>
111
+ String(text ?? '')
112
+ .trim()
113
+ .split(/\r?\n/)[0] || 'no output';
114
+
115
+ /** The findings the reviewer wrote, or why they cannot be read. */
116
+ function findingsOf(file) {
117
+ try {
118
+ const x = JSON.parse(readFileSync(file, 'utf8'));
119
+ if (!Array.isArray(x?.findings)) return { failed: 'the answer has no findings list' };
120
+
121
+ return { findings: x.findings };
122
+ } catch (e) {
123
+ return { failed: `the answer is not JSON: ${e.message}` };
124
+ }
125
+ }
@@ -17,7 +17,7 @@ import { spawnSync } from 'node:child_process';
17
17
  import path from 'node:path';
18
18
  import { fileURLToPath } from 'node:url';
19
19
  import { metricsCommand, runsCommand } from './metrics.js';
20
- import { planReview } from './plan-review.js';
20
+ import { codexReview } from './codex-review.js';
21
21
  import {
22
22
  run,
23
23
  card,
@@ -32,6 +32,7 @@ import {
32
32
  loosePaths,
33
33
  queueOf,
34
34
  stopOf,
35
+ wakeOf,
35
36
  } from './run.js';
36
37
  import {
37
38
  CHAT_TIMEOUT_MIN,
@@ -41,6 +42,9 @@ import {
41
42
  chatOut,
42
43
  killTree,
43
44
  readText,
45
+ THREAD_ID,
46
+ threadWaits,
47
+ wakeThread,
44
48
  } from 'gcf-session';
45
49
 
46
50
  const EXT_ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
@@ -585,8 +589,24 @@ export function register(program) {
585
589
  .command('stop <id>')
586
590
  .description('Stop the session that works an item; the run goes on, the item stays ready')
587
591
  .action((id) => console.log(stopRun(process.cwd(), id)));
592
+ harness
593
+ .command('wake [id]')
594
+ .description(
595
+ "The usage limit was reset early: an item's limit wait goes on now (--thread: a chat " +
596
+ "thread's; --all: every wait of the project)",
597
+ )
598
+ .option('--thread <t>', "a project chat thread's wait")
599
+ .option('--all', 'every live wait of the project: the limit is one for the account')
600
+ .action((id, o) => {
601
+ try {
602
+ console.log(wakeCommand(process.cwd(), id, o));
603
+ } catch (e) {
604
+ console.error(`gcf-harness wake: ${e.message}`);
605
+ process.exitCode = 1;
606
+ }
607
+ });
588
608
  registerHold(harness);
589
- registerPlanReview(harness);
609
+ registerCodexReview(harness);
590
610
  registerChat(harness);
591
611
  }
592
612
 
@@ -655,17 +675,19 @@ function registerCard(harness) {
655
675
  });
656
676
  }
657
677
 
658
- /** `gcf-harness plan-review`: the outside reviewer's pass of a plan (Hold-Plan d17). */
659
- function registerPlanReview(harness) {
678
+ /** `gcf-harness codex-review`: a review pass by the Codex CLI (Operator-Tasks-Plan t2 d2). */
679
+ function registerCodexReview(harness) {
660
680
  harness
661
- .command('plan-review <id>')
681
+ .command('codex-review <id>')
662
682
  .description(
663
- "An improve pass of the item's plan by an outside reviewer, read-only (plan_review: of " +
664
- 'gcf/config.yml; Codex CLI): its findings, or skipped or failed with why',
683
+ "Pass k of the item's plan or code review by the Codex CLI, read-only, when row k of " +
684
+ 'review.plan|code is Codex: its findings, or skipped or failed with why',
665
685
  )
666
- .option('--json', 'machine output: {findings} | {skipped} | {failed}')
686
+ .requiredOption('--kind <kind>', 'plan or code')
687
+ .requiredOption('--pass <k>', 'the pass number, 1 or more')
688
+ .option('--json', 'machine output: {findings, by} | {skipped} | {failed, by?}')
667
689
  .action((id, o) => {
668
- const r = reviewOf(process.cwd(), id);
690
+ const r = /** @type {any} */ (codexReviewOf(process.cwd(), id, o));
669
691
  if (o.json) return console.log(JSON.stringify(r));
670
692
  if (r.findings)
671
693
  for (const f of r.findings) console.log(`${f.severity}: ${f.where}: ${f.text}`);
@@ -749,6 +771,7 @@ function registerChat(harness) {
749
771
  .option('--text-file <path>', 'say: the message from a file, - for stdin')
750
772
  .option('--image <path>', 'say: a picture with it (png, jpg, gif, webp; repeat)', collect, [])
751
773
  .option('--answers-file <path>', 'answer: {"<question>": "<answer>"} from a file, - for stdin')
774
+ .option('--json', 'machine output: {id} of the line written (a message is known by it)')
752
775
  .action(chatAction);
753
776
  }
754
777
 
@@ -760,7 +783,7 @@ function collect(v, list) {
760
783
  function chatAction(id, action, words, opts) {
761
784
  try {
762
785
  const runs = path.join(process.cwd(), '.gcf-session', 'runs');
763
- chatInput(
786
+ const line = chatInput(
764
787
  process.cwd(),
765
788
  id,
766
789
  { action, words, ...opts },
@@ -769,7 +792,9 @@ function chatAction(id, action, words, opts) {
769
792
  read: readText,
770
793
  },
771
794
  );
772
- console.log('sent');
795
+ // A message's line has its id (AD-35); an answer or an interrupt has none.
796
+ const sent = line && 'id' in line ? line.id : null;
797
+ console.log(opts.json ? JSON.stringify({ id: sent }) : 'sent');
773
798
  } catch (e) {
774
799
  console.error(`gcf-harness chat: ${e.message}`);
775
800
  // 4: the input was good, writing it failed (a disk, a permission): the board answers 500.
@@ -829,17 +854,27 @@ export function itemLock(runs, id) {
829
854
  }
830
855
 
831
856
  /**
832
- * The review of item `id`'s plan with the project's `plan_review:`; GCF_CODEX (a JSON list: the
833
- * command and its first arguments) names another Codex, a test's fake.
857
+ * Pass k of item `id`'s review of `kind` by Codex: the row from the core (`gcf review row`, the
858
+ * code's diff written with it), then the pass. GCF_CODEX (a JSON list: the command and its first
859
+ * arguments) names another Codex, a test's fake.
834
860
  */
835
- function reviewOf(projectDir, id) {
836
- const board = json(cliCore(projectDir)(['board', '--json']), 'board');
837
- const item = board.items?.find((i) => i.id === id);
838
- if (!item) return { failed: `${id} is not a work item of the board` };
861
+ function codexReviewOf(projectDir, id, { kind, pass }) {
862
+ const diff = kind === 'code' ? ['--diff'] : [];
863
+ const r = cliCore(projectDir)([
864
+ 'review',
865
+ 'row',
866
+ id,
867
+ '--kind',
868
+ kind,
869
+ '--pass',
870
+ pass,
871
+ ...diff,
872
+ '--json',
873
+ ]);
874
+ if (!r.ok) return { failed: (r.err || r.out).trim() };
839
875
  const codex = process.env.GCF_CODEX ? JSON.parse(process.env.GCF_CODEX) : undefined;
840
- const plan = item.plan_file ?? `.ai-factory/plans/${id}.md`;
841
876
 
842
- return planReview(projectDir, { id, plan, config: board.plan_review ?? {}, codex });
877
+ return codexReview(projectDir, { row: json(r, 'review row'), codex });
843
878
  }
844
879
 
845
880
  /** The autopilot's stop while the project is held (Hold-Plan d9). */
@@ -890,6 +925,62 @@ export function holdCommand(projectDir, id, { project = false, release = false }
890
925
  : 'held the project: its sessions hand over, nothing queued or autopiloted starts';
891
926
  }
892
927
 
928
+ /**
929
+ * Whether item `id`'s run waits for the limit's reset now (t1 d1): its record names a reset and
930
+ * a live run holds its lock. A stopped or killed wait keeps its reset: the record alone is not.
931
+ */
932
+ function itemWaits(runs, id) {
933
+ try {
934
+ const rec = JSON.parse(readFileSync(path.join(runs, `${id}.agent.json`), 'utf8'));
935
+
936
+ return Boolean(rec.resets) && Boolean(itemLock(runs, id));
937
+ } catch {
938
+ return false;
939
+ }
940
+ }
941
+
942
+ /**
943
+ * `gcf-harness wake`: the mark that ends a limit wait early (Operator-Tasks-Plan t1 d4), only
944
+ * while one lives: an item's, a thread's (`thread`), or every one of the project (`all`).
945
+ * @param {string} projectDir
946
+ * @param {string | undefined} id
947
+ * @param {{thread?: string, all?: boolean}} [o]
948
+ */
949
+ export function wakeCommand(projectDir, id, { thread, all = false } = {}) {
950
+ if ([id, thread, all || undefined].filter(Boolean).length !== 1)
951
+ throw new Error('name one item, --thread <t> or --all');
952
+ const dir = path.resolve(projectDir);
953
+ if (thread) return wakeThread(dir, thread);
954
+ const runs = runsDir(dir);
955
+ if (id) {
956
+ if (!itemWaits(runs, id)) return `nothing waits for ${id}`;
957
+ writeFileSync(wakeOf(runs, id), `${new Date().toISOString()}\n`);
958
+
959
+ return `woke ${id}: its session goes on now`;
960
+ }
961
+
962
+ const items = safeList(runs)
963
+ .filter((n) => n.endsWith('.agent.json'))
964
+ .map((n) => n.slice(0, -'.agent.json'.length))
965
+ .filter((x) => itemWaits(runs, x));
966
+ for (const x of items) writeFileSync(wakeOf(runs, x), `${new Date().toISOString()}\n`);
967
+ const threads = safeList(path.join(dir, '.gcf-session', 'chats')).filter(
968
+ (t) => THREAD_ID.test(t) && threadWaits(dir, t),
969
+ );
970
+ for (const t of threads) wakeThread(dir, t);
971
+ const woke = [...items, ...threads.map((t) => `thread ${t}`)];
972
+
973
+ return woke.length ? `woke ${woke.join(', ')}` : 'nothing waits';
974
+ }
975
+
976
+ const safeList = (d) => {
977
+ try {
978
+ return readdirSync(d);
979
+ } catch {
980
+ return [];
981
+ }
982
+ };
983
+
893
984
  export function stopRun(projectDir, id, core = cliCore(projectDir)) {
894
985
  const runs = path.join(path.resolve(projectDir), '.gcf-session', 'runs');
895
986
  const lockFor = () => itemLock(runs, id);
@@ -13,6 +13,8 @@ export const REVIEW = 'gcf review';
13
13
  /** @type {[RegExp, string][]} */
14
14
  const BASH = [
15
15
  [/\bai-factory\s+gcf\s+plan\s+check\b/, 'plan-check'],
16
+ // The code's review by Codex (Operator-Tasks-Plan t2 d2); the plan's is no step of the chat.
17
+ [/\bai-factory\s+gcf-harness\s+codex-review\b[^|&;]*--kind[\s=]+code\b/, 'review'],
16
18
  [/\bai-factory\s+gcf\s+verify\b/, 'dod'],
17
19
  [/\bgit\s+commit\b/, 'commit'],
18
20
  [/\bai-factory\s+gcf\s+(submit|close|block|decide)\b/, 'move'],
@@ -96,7 +98,13 @@ export function milestones({ verifyLog, item, head = () => null, worktree = fals
96
98
  const step = stepOf(e);
97
99
  if (step?.step === 'move' && worktree) return [];
98
100
  if (step && step.step !== 'plan')
99
- calls.set(e.id, { ...step, at: Date.now(), head: step.step === 'commit' ? head() : null });
101
+ calls.set(e.id, {
102
+ ...step,
103
+ at: Date.now(),
104
+ head: step.step === 'commit' ? head() : null,
105
+ // A shell in the background answers at once: its step ends with its task (t2 d2).
106
+ background: e.kind === 'shell' && e.input?.run_in_background === true,
107
+ });
100
108
 
101
109
  return [];
102
110
  };
@@ -114,6 +122,7 @@ export function milestones({ verifyLog, item, head = () => null, worktree = fals
114
122
 
115
123
  const ended = (e) => {
116
124
  const call = calls.get(e.id);
125
+ if (call?.background) return [];
117
126
  calls.delete(e.id);
118
127
  if (!call || call.step === 'plan-check') {
119
128
  if (call) w.checks++;
@@ -121,12 +130,23 @@ export function milestones({ verifyLog, item, head = () => null, worktree = fals
121
130
  return [];
122
131
  }
123
132
 
124
- const { at: _, head: __, ...step } = call;
133
+ const { at: _, head: __, background: ___, ...step } = call;
125
134
  const ok = okOf(call, e);
126
135
 
127
136
  return [{ type: 'step', ...step, ok, ...(ok === false ? { text: firstLine(e.text) } : {}) }];
128
137
  };
129
138
 
139
+ /** A background shell's step at its task's end: `completed` is ok, else its summary says why. */
140
+ const backgroundEnded = (e) => {
141
+ const call = e.call ? calls.get(e.call) : null;
142
+ if (!call?.background) return [];
143
+ calls.delete(/** @type {string} */ (e.call));
144
+ const { at: _, head: __, background: ___, ...step } = call;
145
+ const ok = e.status === 'completed';
146
+
147
+ return [{ type: 'step', ...step, ok, ...(ok ? {} : { text: firstLine(e.summary ?? '') }) }];
148
+ };
149
+
130
150
  return {
131
151
  // Kept for its callers: the plan's step comes from the phase's end now, not from a call.
132
152
  skipPlan: () => {},
@@ -144,6 +164,7 @@ export function milestones({ verifyLog, item, head = () => null, worktree = fals
144
164
  // A subagent's calls (a reviewer running the tests) are its own, not the item's steps.
145
165
  if (!e || e.sub) return [];
146
166
  if (e.type === 'tool_call') return called(e);
167
+ if (e.type === 'task' && e.phase === 'end') return backgroundEnded(e);
147
168
 
148
169
  return e.type === 'tool_result' ? ended(e) : [];
149
170
  },