gcf-aif-ext 0.22.1 → 0.24.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/lib/integrate.js CHANGED
@@ -3,11 +3,12 @@
3
3
  // not in memory. `integrate` merges such a branch into main and records the item's move there,
4
4
  // under the main lock; without an id it picks up every verified branch a dead run left behind.
5
5
  import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';
6
- import { existsSync } from 'node:fs';
6
+ import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
7
7
  import { spawnSync } from 'node:child_process';
8
8
  import path from 'node:path';
9
9
  import { buildLedger } from './ledger.js';
10
10
  import { parse } from './frontmatter.js';
11
+ import { blockLines } from './systems-doc.js';
11
12
  import { withMainLock, runHolder, lockedItem, MAIN_RUN } from './main-lock.js';
12
13
  import { verifyItem, deltaProblems } from './verify.js';
13
14
  import { submitItem, closeItem, blockItem, decideItem } from './work-ops.js';
@@ -15,7 +16,7 @@ import { readConfig } from './gcf-paths.js';
15
16
  import { agentDecideProblem } from './gates.js';
16
17
  import { isValidId } from './id.js';
17
18
  import { writeIndex } from './index-gen.js';
18
- import { moveTrailers } from './git.js';
19
+ import { moveTrailers, restoreIndex, snapshotIndex } from './git.js';
19
20
 
20
21
  const TRAILER = 'GCF-Verified';
21
22
  export const branchOf = (id) => `work/${id}`;
@@ -53,12 +54,21 @@ function dropLogs(dir) {
53
54
  /**
54
55
  * A merge stopped on gcf/INDEX.md alone: both sides counted something (an inbox entry a branch
55
56
  * added, a move on main). The index is generated, so it is written again and the merge goes on,
56
- * past the commit gate like a merge that needs no hand (git runs no pre-commit for it). True
57
- * when the merge is done; false leaves the caller to abort it.
57
+ * past the commit gate like a merge that needs no hand (git runs no pre-commit for it). `card`,
58
+ * when given, may stop it too: main's text wins, the human's (a fix made while the branch waited).
59
+ * True when the merge is done; false leaves the caller to abort it.
58
60
  */
59
- async function mergedPastIndex(dir) {
60
- const unmerged = git(dir, ['diff', '--name-only', '--diff-filter=U'], { check: false }).out;
61
- if (unmerged.split('\n').filter(Boolean).join() !== 'gcf/INDEX.md') return false;
61
+ async function mergedPastIndex(dir, card = null) {
62
+ const unmerged = git(dir, ['diff', '--name-only', '--diff-filter=U'], { check: false })
63
+ .out.split('\n')
64
+ .filter(Boolean);
65
+ const ours = ['gcf/INDEX.md', ...(card ? [card] : [])];
66
+ if (!unmerged.length || unmerged.some((f) => !ours.includes(f))) return false;
67
+ if (card && unmerged.includes(card)) {
68
+ git(dir, ['checkout', '--theirs', '--', card], { check: false });
69
+ git(dir, ['add', '--', card], { check: false });
70
+ }
71
+
62
72
  try {
63
73
  await writeIndex(path.join(dir, 'gcf'));
64
74
  } catch {
@@ -73,19 +83,63 @@ async function mergedPastIndex(dir) {
73
83
  return git(dir, commit, { check: false }).ok;
74
84
  }
75
85
 
86
+ /**
87
+ * Whether a refused merge stands on the worktree's unsaved card alone: of what is uncommitted
88
+ * there, main changes nothing else. Anything more stays refused, and the card as it is.
89
+ */
90
+ function cardAloneHolds(dir, main, card) {
91
+ if (git(dir, ['rev-parse', '-q', '--verify', 'MERGE_HEAD'], { check: false }).ok) return false;
92
+ const list = (args) => git(dir, args, { check: false }).out.split('\n').filter(Boolean);
93
+ const moved = new Set(list(['diff', '--name-only', `HEAD...${main}`]));
94
+ const loose = [
95
+ ...list(['diff', '--name-only', 'HEAD']),
96
+ ...list(['ls-files', '--others', '--exclude-standard']),
97
+ ];
98
+ const held = loose.filter((f) => moved.has(f));
99
+
100
+ return held.length === 1 && held[0] === card;
101
+ }
102
+
103
+ /** The card as a worktree holds it, on disk and in the index; the call puts it back. */
104
+ function holdCard(dir, card) {
105
+ const file = path.join(dir, card);
106
+ const bytes = existsSync(file) ? readFileSync(file) : null;
107
+ const index = snapshotIndex(dir, [file]);
108
+
109
+ return () => {
110
+ restoreIndex(index);
111
+ if (bytes) writeFileSync(file, bytes);
112
+ else rmSync(file, { force: true });
113
+ };
114
+ }
115
+
76
116
  /**
77
117
  * Bring the main checkout's branch into a resumed worktree: the operator's answer from
78
- * `unblock`, a newer LIVE.md and the other items' states live on main only.
118
+ * `unblock`, a fix from `amend`, a newer LIVE.md and the other items' states live on main only.
119
+ * The item's card on main wins over what a stopped run wrote into its copy, saved or not: the
120
+ * run's edit came from the card's notes, and the next session reads them again; code stays. A
121
+ * merge that does not go leaves the unsaved card as it was.
79
122
  */
80
- async function syncWithMain(projectDir, dir) {
123
+ async function syncWithMain(projectDir, dir, id) {
81
124
  const main = git(projectDir, ['rev-parse', '--abbrev-ref', 'HEAD']).out;
82
125
  if (main === 'HEAD' || main.startsWith('work/')) return {};
83
126
  // An earlier run's lines in the worktree's logs would stop main's newer logs merging in.
84
127
  dropLogs(dir);
85
- const res = git(dir, ['merge', '--no-edit', '-m', `gcf(sync): ${main}`, main], { check: false });
86
- if (res.ok || (await mergedPastIndex(dir))) return {};
128
+ const merge = () =>
129
+ git(dir, ['merge', '--no-edit', '-m', `gcf(sync): ${main}`, main], { check: false });
130
+ const card = `gcf/work/${id}.md`;
131
+ let res = merge();
132
+ let putBack = null;
133
+ if (!res.ok && cardAloneHolds(dir, main, card)) {
134
+ putBack = holdCard(dir, card);
135
+ git(dir, ['checkout', 'HEAD', '--', card], { check: false });
136
+ res = merge();
137
+ }
138
+
139
+ if (res.ok || (await mergedPastIndex(dir, card))) return {};
87
140
  if (git(dir, ['rev-parse', '-q', '--verify', 'MERGE_HEAD'], { check: false }).ok)
88
141
  git(dir, ['merge', '--abort'], { check: false });
142
+ putBack?.();
89
143
 
90
144
  return { sync: `${main} does not merge into the worktree: ${res.err}` };
91
145
  }
@@ -105,7 +159,7 @@ export async function addWorktree(projectDir, id) {
105
159
  path: dir,
106
160
  branch: branchOf(id),
107
161
  created: false,
108
- ...(await syncWithMain(projectDir, dir)),
162
+ ...(await syncWithMain(projectDir, dir, id)),
109
163
  };
110
164
  if (item.data.status !== 'ready')
111
165
  throw new Error(`${id} is ${item.data.status}: a run starts on a ready item`);
@@ -116,8 +170,10 @@ export async function addWorktree(projectDir, id) {
116
170
  const exists = git(projectDir, ['rev-parse', '--verify', '--quiet', ref], { check: false }).ok;
117
171
  const from = exists ? [dir, branchOf(id)] : ['-b', branchOf(id), dir, 'HEAD'];
118
172
  git(projectDir, ['worktree', 'add', ...from]);
173
+ // A branch that outlived its folder lags behind main as a resumed worktree does.
174
+ const sync = exists ? await syncWithMain(projectDir, dir, id) : {};
119
175
 
120
- return { id, path: dir, branch: branchOf(id), created: true };
176
+ return { id, path: dir, branch: branchOf(id), created: true, ...sync };
121
177
  }
122
178
 
123
179
  /**
@@ -178,18 +234,22 @@ function cleanUp(projectDir, id, { force = false } = {}) {
178
234
  return notes.length ? { cleanup: notes } : {};
179
235
  }
180
236
 
181
- /** The item file at `rev` without its `live:`: what a branch must leave as main has it. */
237
+ /**
238
+ * The item file at `rev` as a branch must leave it: its frontmatter but `live:`, and the blocks
239
+ * that hold the operator's words and the record of where it came from.
240
+ */
182
241
  function itemBeyondLive(projectDir, rev, id) {
183
242
  const res = git(projectDir, ['show', `${rev}:./gcf/work/${id}.md`], { check: false });
184
243
  if (!res.ok) return null;
185
244
  const { data, body } = parse(res.out);
186
245
  const { live, ...rest } = data;
187
246
 
188
- return JSON.stringify([rest, String(body).trim()]);
247
+ return JSON.stringify([rest, ['tuning', 'notes', 'provenance'].map((k) => blockLines(body, k))]);
189
248
  }
190
249
 
191
250
  /**
192
- * The branch may change in gcf/ only its own item's `live:` (Methodology §5.2): status, other
251
+ * The branch may change in gcf/ only its own item's `live:` and the slots of its card, which a
252
+ * run rewrites by the operator's word (Methodology §5.2): status, the operator's blocks, other
193
253
  * items and the config move on main through their commands.
194
254
  */
195
255
  const INBOX_ENTRY = /^gcf\/inbox\/in-[0-9a-f]{8}\.md$/;
package/lib/lessons.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // Lessons (Methodology §5.2.2): at the end of a session on a work item, its agent says what got in
2
2
  // its way — a tool, a rule, the framework, the project's template. Each answer is an inbox entry
3
- // of the category `lesson`, its kind the detail, with its `item`, so the operator triages it like any raw input and the
3
+ // of the category `lesson`, its kind the detail, with its `item`, so the operator triages it like
4
+ // any raw input and the
4
5
  // board shows where agents struggle. The questions stay out of the agent's working context until
5
6
  // the session ends: the harness asks them in one more turn, `/gcf-run` asks them at its close.
6
7
  import { readFile } from 'node:fs/promises';
package/lib/main-lock.js CHANGED
@@ -31,7 +31,7 @@ export const alive = (pid) => {
31
31
  */
32
32
  export const MAIN_RUN = '.main-run';
33
33
 
34
- /** The item a run lock names on its second line (the main run's: the item it works now), or null. */
34
+ /** The item a run lock names on its second line (a main run's: what it works now), or null. */
35
35
  export function lockedItem(projectDir, id) {
36
36
  try {
37
37
  const file = path.join(path.resolve(projectDir), '.gcf-session', 'runs', `${id}.lock`);
package/lib/migrate.js CHANGED
@@ -200,6 +200,7 @@ export function unitText(c, id, depends) {
200
200
  ...prov,
201
201
  ].join('\n');
202
202
  }
203
+
203
204
  /** The slug of a name, Cyrillic transliterated, or null when nothing in it slugs. */
204
205
  /** The slug of a name, or null when the name has no latin letter or digit to slug. */
205
206
  function safeSlug(name) {
@@ -55,7 +55,8 @@ function holdsBuild(ledger, item) {
55
55
  * the D1 questions that hold it), its items by status (a release is the operator's and counts
56
56
  * for nothing), and `empty`, `built`, `played`; then `build_milestone` (the first not built)
57
57
  * and `play_milestone` (the first built and not played) by name, and `milestone_order`: each
58
- * item of an earlier milestone that depends on an item of a later one. `units` is the design check's unit summaries.
58
+ * item of an earlier milestone that depends on an item of a later one. `units` is the design
59
+ * check's unit summaries.
59
60
  * @param {string} projectDir
60
61
  * @param {any} ledger buildLedger's
61
62
  * @param {{id: string, milestone: string, blocked_by: string[]}[]} units
@@ -5,11 +5,12 @@
5
5
  // and the move that ends the run clears it. A mark nobody refreshed for SESSION_TTL_MS is a
6
6
  // session that stopped: the item reads as not running again. The mark names its owner, so a
7
7
  // second session cannot take an item the first one works.
8
- import { existsSync, readFileSync, rmSync, statSync, utimesSync } from 'node:fs';
8
+ import { existsSync, readdirSync, readFileSync, rmSync, statSync, utimesSync } from 'node:fs';
9
9
  import { mkdir, writeFile } from 'node:fs/promises';
10
10
  import path from 'node:path';
11
11
  import { excludeSession } from './integrate.js';
12
12
  import { alive, withMainLock } from './main-lock.js';
13
+ import { enterFolder } from './shelf.js';
13
14
 
14
15
  // A run's default timeout: an agent can implement for long without a gcf command. The harness
15
16
  // and its readset-guard hook refresh a live session's mark meanwhile.
@@ -45,19 +46,43 @@ export function ownsMark(projectDir, id, owner = ownerOf()) {
45
46
  return !held || held === owner;
46
47
  }
47
48
 
48
- /** Mark item `id` as worked by `owner`; refused while another owner's mark is fresh. */
49
- export async function claimSession(projectDir, id, owner = ownerOf()) {
49
+ /** Whether a session of another owner works another item in this folder now. */
50
+ function otherSessionLives(projectDir, id, owner) {
51
+ const runs = path.dirname(markOf(projectDir, id));
52
+ const held = (other) =>
53
+ sessionActive(projectDir, other) && ownerLine(projectDir, other) !== owner;
54
+
55
+ return readdirSync(runs).some(
56
+ (f) => f.endsWith('.session') && f !== `${id}.session` && held(f.slice(0, -'.session'.length)),
57
+ );
58
+ }
59
+
60
+ /**
61
+ * Mark item `id` as worked by `owner`; refused while another owner's mark is fresh. The folder
62
+ * changes hands here, the one door a harness run and a console session both pass: the work of
63
+ * the card that held it goes to its branch, and this card's own comes back (lib/shelf.js).
64
+ * @param {{step?: (name: string) => void, gitVersion?: string}} [opts] for a test
65
+ * @returns {Promise<ReturnType<typeof enterFolder>>} what moved
66
+ */
67
+ export async function claimSession(projectDir, id, owner = ownerOf(), opts = {}) {
50
68
  const file = markOf(projectDir, id);
51
69
  await excludeSession(projectDir);
52
70
  await mkdir(path.dirname(file), { recursive: true });
71
+
53
72
  // Under the main lock: two sessions claiming at once must not both pass the check.
54
- await withMainLock(projectDir, async () => {
73
+ return withMainLock(projectDir, async () => {
55
74
  if (!ownsMark(projectDir, id, owner))
56
75
  throw new Error(
57
76
  `${id} is worked by another agent session (${markOwner(projectDir, id)}): leave it to ` +
58
77
  `that session, or run ai-factory gcf release ${id} when no session works it`,
59
78
  );
79
+ const shared = otherSessionLives(projectDir, id, owner ?? null);
80
+ const moved = enterFolder(projectDir, id, { shared, ...opts });
81
+ // A shelved card is no running card, whoever held it.
82
+ if (moved.shelved) releaseSession(projectDir, moved.shelved.id);
60
83
  await writeFile(file, `${new Date().toISOString()}\n${owner ?? ''}\n`);
84
+
85
+ return moved;
61
86
  });
62
87
  }
63
88