gcf-aif-ext 0.23.0 → 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/README.md CHANGED
@@ -50,6 +50,14 @@ Updating preserves `gcf/`, `cnlp.config.json` and the pre-commit hook. Run `ai-f
50
50
 
51
51
  On Windows, run `extension add` and `extension update` from PowerShell or cmd, not Git Bash: the installer unpacks with `tar`, and Git Bash's GNU tar reads `C:\…` as a remote host (`Cannot connect to C: resolve failed`). The Windows `tar.exe` handles it.
52
52
 
53
+ ### 0.24.0
54
+
55
+ - A card's unfinished work in main mode goes to its branch when another card claims the folder (Methodology §7, [Shelve-Plan](https://github.com/VirtualMaestro/GCF/blob/main/docs/Shelve-Plan.md)). `gcf claim` pins a baseline at `refs/gcf/main-work`; the next card's claim moves what the card changed since to `work/<id>` as a commit with `GCF-Shelved: <id>`, untouched files keep their mtime, and no hook runs. Its own claim brings the work back by a three-way merge: conflicts stay as markers in the file, for the agent. A journal, `refs/gcf/main-switch`, makes every step recoverable.
56
+ - `gcf claim --json` gives `{shelved, returned, moved, conflicts}`; a claim that cannot move the folder refuses with `gcf-refusal: {"code":"shelve","reason":…}`.
57
+ - `close` and `submit` refuse a shelved card. `drop`, `decide no` and a feature's kill delete its branch; no `remove-<id>` when `GCF-Whole: yes` says none of its code reached main and `tune_count` is 0.
58
+ - `gcf audit --json` carries `main_work: {id, paths}` while a baseline stands; `gcf board --json` carries `items[].shelved: {files, commits}`.
59
+ - Needs git 2.40; an older git, a project inside a bigger repository or a linked worktree record nothing and stop a batch as before.
60
+
53
61
  ### 0.23.0
54
62
 
55
63
  - `gcf item amend <id>` fixes a live card's text from every stored status but `unplayed`, the status unchanged: `--text` (`--text-file`) replaces the blocks it names, a key alone takes one out; `--add` adds to `notes:`; `--title`; `--from <in-id>` takes an inbox entry in the same commit, its pictures one by one. `provenance:` and `tuning:` cannot be named; a unit's block must be in its profile. `--dry-run --json` writes nothing and gives `{base, title, text, changes}`; `--base <hash>` refuses a card changed since (`gcf-refusal: {"code":"stale"}`). The operator's: a run and a thread are refused, the deny group `human-moves` holds it, and a chat agent proposes it (`propose_amend`). Refused during this card's run or session (`{"code":"running"}`). Findings on the new text come from the pre-commit gate, with its rollback. The domain's `preview` and `hint` tell a board.
package/commands/gcf.js CHANGED
@@ -8,6 +8,10 @@ import path from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
9
 
10
10
  const EXT_ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
11
+ /** The commit a switch kept of what a card had staged apart from the disk. */
12
+ const stagedLine = (r) =>
13
+ r.staged ? [`what ${r.id} had staged apart from the disk: commit ${r.staged}`] : [];
14
+
11
15
  const lib = (name) => import(new URL(`../lib/${name}.js`, import.meta.url).href);
12
16
 
13
17
  // Must stay byte-identical to the comment line inside the shim below: hooks-install
@@ -87,11 +91,37 @@ function registerSession(gcf) {
87
91
  'An agent session starts working the item on main: the board shows it running until a ' +
88
92
  'move ends it, release, or 2 hours without a gcf command on it',
89
93
  )
90
- .action(async (id) => {
94
+ .option('--json', 'machine output: what moved in the folder')
95
+ .action(async (id, o) => {
91
96
  const { buildLedger } = await lib('ledger');
92
97
  if (!(await buildLedger(process.cwd())).item(id)) throw new Error(`${id} is not a work item`);
93
- await (await lib('session-mark')).claimSession(process.cwd(), id);
94
- console.log(`claimed ${id}`);
98
+ const moved = await (await lib('session-mark')).claimSession(process.cwd(), id);
99
+ out(o.json, moved, (m) =>
100
+ [
101
+ `claimed ${id}`,
102
+ ...(m.shelved
103
+ ? [
104
+ `shelved ${m.shelved.id}: ${m.shelved.files} file(s) went to ${m.shelved.branch}`,
105
+ ...stagedLine(m.shelved),
106
+ ]
107
+ : []),
108
+ ...(m.returned
109
+ ? [
110
+ `returned ${m.returned.id}: ${m.returned.files} file(s), ` +
111
+ `main moved ${m.moved} commit(s)`,
112
+ ...stagedLine(m.returned),
113
+ ...(m.returned.branch_moved
114
+ ? [`work/${m.returned.id} moved on and stays: its new commits are not here`]
115
+ : []),
116
+ ]
117
+ : []),
118
+ ...m.conflicts.map((c) =>
119
+ c.kept_main
120
+ ? `conflict ${c.path}: kept main's, the card's copy is in commit ${m.returned.copy}`
121
+ : `conflict ${c.path}: resolve its markers first, or block`,
122
+ ),
123
+ ].join('\n'),
124
+ );
95
125
  });
96
126
  gcf
97
127
  .command('release <id>')
@@ -803,7 +833,7 @@ function registerChanges(gcf) {
803
833
  const allOf = (o, cmd) => cmd?.optsWithGlobals?.() ?? o;
804
834
  const group = gcf
805
835
  .command('changes')
806
- .description("What is not committed in the main checkout or a run's worktree: read only")
836
+ .description("What is not committed in the main checkout or a run's worktree")
807
837
  .allowExcessArguments(false)
808
838
  .option('--worktree <id>', TREE)
809
839
  .option('--json', '{tree, base, count, files, trees, more, watch}')
@@ -860,6 +890,27 @@ function registerChanges(gcf) {
860
890
  ).changeFile(process.cwd(), o.path, o.side, { worktree: o.worktree });
861
891
  out(true, r);
862
892
  });
893
+ registerChangesCommit(group, allOf);
894
+ }
895
+
896
+ function registerChangesCommit(group, allOf) {
897
+ group
898
+ .command('commit')
899
+ .description(
900
+ "Commit these files of the main checkout with this message: the board's Commit, the " +
901
+ "operator's move",
902
+ )
903
+ .requiredOption('--fields-file <path>', '{message, paths} as JSON, - for stdin')
904
+ .option('--json', '{hash, subject, files}')
905
+ .action(async (own, cmd) => {
906
+ const o = allOf(own, cmd);
907
+ if (o.worktree) throw new Error('changes commit: a run commits its own work in a worktree');
908
+ await operatorOnly('changes commit');
909
+ const r = await (
910
+ await lib('commit-files')
911
+ ).commitFiles(process.cwd(), fieldsOf(o.fieldsFile));
912
+ out(o.json, r, (x) => `committed ${x.files} file${x.files === 1 ? '' : 's'} ${x.hash}`);
913
+ });
863
914
  }
864
915
 
865
916
  function registerMigrate(design) {
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-aif-ext",
4
- "version": "0.23.0",
4
+ "version": "0.24.0",
5
5
  "description": "Game Context Framework for AI Factory",
6
6
  "skills": [
7
7
  "skills/gcf-init",
@@ -197,6 +197,8 @@ export const DENY_GROUPS = [
197
197
  // A human's hand edits under gcf/: their unfinished work, not the agent's to keep or erase.
198
198
  'ai-factory gcf edits commit*',
199
199
  'ai-factory gcf edits discard*',
200
+ // What goes into the operator's commit is theirs to say; an agent commits with git.
201
+ 'ai-factory gcf changes commit*',
200
202
  'ai-factory gcf-harness init*',
201
203
  // The space keeps `gcf-harness runs`, the history of past runs, a read the agent may make.
202
204
  'ai-factory gcf-harness run *',
package/lib/audit-core.js CHANGED
@@ -17,6 +17,7 @@ import { inboxProblems } from './inbox.js';
17
17
  import { inboxVocabulary } from './domain.js';
18
18
  import { gatePolicy, verdictDeferred } from './gates.js';
19
19
  import { milestoneState } from './milestone-state.js';
20
+ import { mainWork } from './shelf.js';
20
21
 
21
22
  function git(args, cwd) {
22
23
  // A blame of a long file overflows the 1 MiB default, and an overflow reads as a git failure.
@@ -57,6 +58,7 @@ function runningOf(projectDir, id) {
57
58
  * @property {Array<{id: string, tune_count: number, limit: number}>} tune_limit
58
59
  * @property {Array<{id: string, depends: string[]}>} open_depends
59
60
  * @property {{count: number, limit: number, over: boolean}} wip
61
+ * @property {{id: string, paths: string[]}} [main_work] the card in the folder (lib/shelf.js)
60
62
  * @property {{count: number, warn_after: number, over: boolean}} unplayed
61
63
  * @property {string[]} legacy_cards
62
64
  * @property {{tokens: number, budget: number, over: boolean, count: number, too_many: boolean}
@@ -143,6 +145,9 @@ export async function audit(projectDir) {
143
145
  deferred: verdictDeferred(config, c.data),
144
146
  ...runningOf(projectDir, String(c.data.id)),
145
147
  }));
148
+ // The card whose unfinished work lies in the folder (lib/shelf.js): the next claim shelves it.
149
+ const work = mainWork(projectDir);
150
+ if (work) report.main_work = work;
146
151
  const design = await designCheck(projectDir);
147
152
  checkItems(report, items, config, { projectDir, ledger });
148
153
  report.design = {
package/lib/board.js CHANGED
@@ -20,6 +20,7 @@ import { lessonRepeats } from './inbox-categories.js';
20
20
  import { openDepends } from './work-ops.js';
21
21
  import { listQuestions } from './questions.js';
22
22
  import { sessionActive } from './session-mark.js';
23
+ import { shelvedCards } from './shelf.js';
23
24
  import { agentOf } from './agent-permissions.js';
24
25
  import { projectSettings } from './config-set.js';
25
26
  import { designCheck, designUnits } from './design-check.js';
@@ -315,7 +316,7 @@ async function attachmentsOf(projectDir, id) {
315
316
  }
316
317
 
317
318
  /** One item of the board. */
318
- async function itemOf(projectDir, c, { verified, ledger, harness, config }) {
319
+ async function itemOf(projectDir, c, { verified, shelved, ledger, harness, config }) {
319
320
  const id = String(c.data.id);
320
321
  // A trailer counts only while the item waits on main for its integrate.
321
322
  const ready = c.data.status === 'ready' && verified.has(id);
@@ -349,6 +350,8 @@ async function itemOf(projectDir, c, { verified, ledger, harness, config }) {
349
350
  resumable,
350
351
  resume,
351
352
  verified: ready,
353
+ // Its unfinished work waits on its branch (lib/shelf.js); a run brings it back.
354
+ ...(shelved.has(id) ? { shelved: shelved.get(id) } : {}),
352
355
  waits_for: waitsOf(c, running, ledger),
353
356
  needs: needsOf(ledger, c.data.depends ?? []),
354
357
  moves: offered(c, { running, verified: ready, harness }),
@@ -365,12 +368,13 @@ export async function board(projectDir) {
365
368
  const root = path.join(path.resolve(projectDir), 'gcf');
366
369
  const ledger = await buildLedger(projectDir);
367
370
  const verified = verifiedOf(projectDir);
371
+ const shelved = shelvedCards(projectDir);
368
372
  const { extensions, error: extensionsError } = await extensionsOf(projectDir);
369
373
  const harness = hasHarness(extensions);
370
374
  const config = await readConfig(root);
371
375
  const items = [];
372
376
  for (const c of ledger.items)
373
- items.push(await itemOf(projectDir, c, { verified, ledger, harness, config }));
377
+ items.push(await itemOf(projectDir, c, { verified, shelved, ledger, harness, config }));
374
378
  inRunOrder(items);
375
379
  // When the wait began: the time of the commit `since` names (Board-PRD §13).
376
380
  const times = commitTimes(
package/lib/changes.js CHANGED
@@ -514,6 +514,13 @@ export async function changesOf(projectDir, { worktree } = {}) {
514
514
  };
515
515
  }
516
516
 
517
+ /** The main checkout's rows as a commit reads them, past the list's limit: `xy` and `why` kept. */
518
+ export async function rowsToCommit(projectDir) {
519
+ const { tree, rows } = await readTree(projectDir);
520
+
521
+ return { base: tree.base, rows: (rows ?? []).map((r) => byDisk(tree.dir, r)) };
522
+ }
523
+
517
524
  /** The row of `p` with its view, or the refusal of a path the list does not hold. */
518
525
  async function rowOf(projectDir, p, worktree) {
519
526
  const { tree, rows, noDiff } = await readTree(projectDir, worktree);
@@ -0,0 +1,292 @@
1
+ // The operator's commit from the Changes screen (Board-PRD decision 50, docs/Round11-Plan.md): the
2
+ // files they ticked with their own message, in the main checkout. Not `commitMove`: its rollback
3
+ // rewrites the files it read, so a save during a slow hook would go, and it always takes INDEX.md,
4
+ // so a commit of code alone would enter the gate. The working tree is never written, but INDEX.md
5
+ // when gcf/ is committed; on a refusal the index and INDEX.md are as they were.
6
+ import { spawnSync } from 'node:child_process';
7
+ import { existsSync, lstatSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import { rowsToCommit } from './changes.js';
11
+ import {
12
+ commitOnly,
13
+ dirtyGcf,
14
+ dirtyRefusal,
15
+ inParts,
16
+ literal,
17
+ moveTrailers,
18
+ operationInProgress,
19
+ } from './git.js';
20
+ import { writeIndex } from './index-gen.js';
21
+ import { MAIN_RUN, runHolder, withMainLock } from './main-lock.js';
22
+ import { refusal } from './refusal.js';
23
+ import { onWorkBranch } from './unit-ops.js';
24
+
25
+ const INDEX = 'gcf/INDEX.md';
26
+ // The ids a commit touches, as `gcf edits commit` finds them: item history reads them.
27
+ const ITEM_PATH = /^gcf\/work\/([^/]+?)(?:\.md$|\/)/;
28
+ const UNFIT = ['nested repository', 'not a regular file'];
29
+
30
+ /** Whether the commit gate reads `p` (GATE_SCOPE in git.js). */
31
+ const inGate = (p) =>
32
+ p === 'GLOSSARY.md' ||
33
+ (p.startsWith('gcf/') &&
34
+ !p.startsWith('gcf/.metrics/') &&
35
+ !/^gcf\/source\/[^/]+\.import\.json$/.test(p));
36
+
37
+ const git = (dir, args, opts = {}) =>
38
+ spawnSync('git', ['-c', 'core.quotePath=false', ...args], {
39
+ cwd: dir,
40
+ encoding: 'utf8',
41
+ ...opts,
42
+ });
43
+
44
+ const nul = (dir, paths) => paths.map((p) => `${literal(dir, p)}\0`).join('');
45
+
46
+ /** A commit needs a branch to land on: an unborn one is one, a detached HEAD is not. */
47
+ function refuseWhereNoCommitBelongs(dir, subject) {
48
+ if (onWorkBranch(dir))
49
+ throw new Error(`cannot record ${subject} on a work/ branch: a run commits its own work`);
50
+ const busy = operationInProgress(dir);
51
+ if (busy) throw new Error(`cannot record ${subject} while ${busy} is in progress`);
52
+ if (git(dir, ['symbolic-ref', '-q', 'HEAD']).status !== 0)
53
+ throw new Error(`cannot record ${subject} on a detached HEAD: check out a branch first`);
54
+ if (runHolder(dir, MAIN_RUN))
55
+ throw refusal('running', {}, `cannot record ${subject}: a run writes in the main checkout`);
56
+ }
57
+
58
+ /** A staged rename only: the index holds the old file's text under the new name. */
59
+ const onlyMoved = (dir, r) =>
60
+ r.xy[0] === 'R' &&
61
+ git(dir, ['rev-parse', `:./${r.path}`]).stdout ===
62
+ git(dir, ['rev-parse', `HEAD:./${r.from}`]).stdout;
63
+
64
+ /**
65
+ * What the disk would overwrite: `--only` takes the disk, so a text staged and changed again
66
+ * would go without a trace, and a file out of the index by `rm --cached` would come back.
67
+ */
68
+ function stagedAway(dir, base, rows) {
69
+ const out = git(dir, [
70
+ 'diff',
71
+ '--cached',
72
+ '--no-renames',
73
+ '--diff-filter=D',
74
+ '--name-only',
75
+ '-z',
76
+ '--relative',
77
+ base,
78
+ ]);
79
+ const removed = new Set(out.stdout.split('\0'));
80
+
81
+ return rows.filter((r) =>
82
+ r.status === 'untracked'
83
+ ? removed.has(r.path)
84
+ : r.xy && !r.xy.includes('.') && !onlyMoved(dir, r),
85
+ );
86
+ }
87
+
88
+ // A whole block, not one line: `=======` alone underlines a Markdown heading.
89
+ const MARKERS = /^<{7}[ \r\n][\s\S]*?^={7}\r?$[\s\S]*?^>{7}[ \r\n]/m;
90
+ const MARKERS_READ = 16 * 1024 * 1024;
91
+
92
+ /** The text of a file on the disk with a conflict's markers in it that the last commit lacks. */
93
+ function newMarkers(dir, r) {
94
+ const file = path.join(dir, r.path);
95
+ if (r.status === 'deleted' || !existsSync(file)) return false;
96
+ const st = lstatSync(file);
97
+ if (!st.isFile() || st.size > MARKERS_READ) return false;
98
+ const bytes = readFileSync(file);
99
+ if (bytes.includes(0) || !MARKERS.test(bytes.toString('latin1'))) return false;
100
+ const old = git(dir, ['show', `HEAD:./${r.from ?? r.path}`]);
101
+
102
+ return !(old.status === 0 && MARKERS.test(old.stdout));
103
+ }
104
+
105
+ /**
106
+ * A return's conflict leaves its markers in a plain modified file: git sees no conflict, and
107
+ * whatever `-diff` says of it, a commit would take them.
108
+ */
109
+ function refuseMarkers(dir, rows, subject) {
110
+ const marked = rows.filter((r) => newMarkers(dir, r)).map((r) => r.path);
111
+ if (marked.length)
112
+ throw refusal(
113
+ 'unfit',
114
+ { paths: marked },
115
+ `cannot record ${subject}: ${marked.join(', ')} still hold conflict markers: resolve them ` +
116
+ 'first; a file meant to hold them goes by Commit with agent',
117
+ );
118
+ }
119
+
120
+ /** Stops before anything is written. */
121
+ function refuseRows(dir, base, rows, subject) {
122
+ const unfit = rows
123
+ .filter((r) => r.status === 'conflict' || UNFIT.includes(r.why))
124
+ .map((r) => r.path);
125
+ if (unfit.length)
126
+ throw refusal(
127
+ 'unfit',
128
+ { paths: unfit },
129
+ `cannot record ${subject}: ${unfit.join(', ')} cannot be committed: resolve a conflict ` +
130
+ 'first; a nested repository or anything but a file stays out',
131
+ );
132
+ refuseMarkers(dir, rows, subject);
133
+ // `--only` takes the disk for the old name too: a new file there would ride along, unticked.
134
+ // Only its letters changed: on a disk that ignores case the old name is the new file.
135
+ const reused = rows.filter(
136
+ (r) =>
137
+ r.status === 'renamed' &&
138
+ r.from &&
139
+ r.from.toLowerCase() !== r.path.toLowerCase() &&
140
+ existsSync(path.join(dir, r.from)),
141
+ );
142
+ if (reused.length)
143
+ throw refusal(
144
+ 'staged',
145
+ { paths: reused.map((r) => r.path) },
146
+ `cannot record ${subject}: something new stands at the old name of ` +
147
+ `${reused.map((r) => `${r.from} → ${r.path}`).join(', ')}: commit that first, ` +
148
+ 'or use Commit with agent',
149
+ );
150
+ const staged = stagedAway(dir, base, rows).map((r) => r.path);
151
+ if (staged.length)
152
+ throw refusal(
153
+ 'staged',
154
+ { paths: staged },
155
+ `cannot record ${subject}: ${staged.join(', ')} ha${staged.length === 1 ? 's' : 've'} ` +
156
+ 'staged text the disk does not hold, and this commit takes the disk: `git add` to take ' +
157
+ 'the disk, `git restore --staged` to drop what is staged, or use Commit with agent',
158
+ );
159
+ }
160
+
161
+ /** The gate reads the whole of its scope: its dirty files go together, or not at all. */
162
+ function refuseGateRest(dir, names, subject) {
163
+ const rest = dirtyGcf(dir, [...names.filter(inGate), INDEX]);
164
+ if (rest.length)
165
+ throw dirtyRefusal(
166
+ rest,
167
+ `cannot record ${subject} while gcf/ holds uncommitted changes: ${rest.join(', ')} — ` +
168
+ 'commit or discard them, then try again',
169
+ );
170
+ }
171
+
172
+ /** `git commit -F`, as a message of many lines and a list on stdin share no command line. */
173
+ function commitWith(dir, subject, specs, text) {
174
+ const tmp = mkdtempSync(path.join(os.tmpdir(), 'gcf-commit-'));
175
+ const file = path.join(tmp, 'message');
176
+ try {
177
+ writeFileSync(file, text);
178
+
179
+ return commitOnly(dir, subject, specs, ['-F', file, '--cleanup=whitespace']);
180
+ } finally {
181
+ rmSync(tmp, { recursive: true, force: true });
182
+ }
183
+ }
184
+
185
+ /** Stage `add`, commit `all`; `clean` when nothing of it differs from the last commit. */
186
+ function stageAndCommit(dir, { add, all, subject, text }) {
187
+ // No paths: `git add -A` on an empty list takes the whole tree, a staged text's copy too.
188
+ if (add.length) {
189
+ const staged = git(dir, ['add', '-A', '--pathspec-from-file=-', '--pathspec-file-nul'], {
190
+ input: nul(dir, add),
191
+ });
192
+ if (staged.status !== 0) throw new Error(`commit failed: ${staged.stderr.trim()}`);
193
+ }
194
+
195
+ const specs = all.map((p) => literal(dir, p));
196
+ const same = inParts(specs).every(
197
+ (part) => git(dir, ['diff', '--cached', '--quiet', 'HEAD', '--', ...part]).status === 0,
198
+ );
199
+ if (same)
200
+ throw refusal(
201
+ 'clean',
202
+ { paths: all, left: [] },
203
+ `cannot record ${subject}: nothing left to commit in these files`,
204
+ );
205
+
206
+ return commitWith(dir, subject, all, text);
207
+ }
208
+
209
+ /** The index file's bytes, and how to put them back: `git add` of a folder takes more. */
210
+ function indexKeeper(dir) {
211
+ const file = path.resolve(dir, git(dir, ['rev-parse', '--git-path', 'index']).stdout.trim());
212
+ const bytes = existsSync(file) ? readFileSync(file) : null;
213
+ const head = git(dir, ['rev-parse', '-q', '--verify', 'HEAD']).stdout;
214
+
215
+ return () => {
216
+ // Someone committed meanwhile: this index is theirs now.
217
+ if (git(dir, ['rev-parse', '-q', '--verify', 'HEAD']).stdout !== head) return;
218
+ if (bytes) writeFileSync(file, bytes);
219
+ else rmSync(file, { force: true });
220
+ };
221
+ }
222
+
223
+ /** `run` with INDEX.md and the index put back if it throws. */
224
+ async function undoingOnRefusal(dir, gated, run) {
225
+ const index = path.join(dir, INDEX);
226
+ const before = gated && existsSync(index) ? readFileSync(index) : null;
227
+ const putBack = indexKeeper(dir);
228
+ try {
229
+ if (gated) await writeIndex(path.join(dir, 'gcf'));
230
+
231
+ return run();
232
+ } catch (e) {
233
+ putBack();
234
+ if (before) writeFileSync(index, before);
235
+ else if (gated) rmSync(index, { force: true });
236
+ throw e;
237
+ }
238
+ }
239
+
240
+ /** The message as the operator wrote it, and a move's trailers when the commit moves gcf/. */
241
+ function messageOf(message, rows, gated) {
242
+ if (!gated) return message;
243
+ const items = rows.flatMap((r) => ITEM_PATH.exec(r.path)?.[1] ?? []);
244
+ const lines = moveTrailers({ key: 'edits-commit', items })[1];
245
+
246
+ return `${message.trimEnd()}\n\n${lines}\n`;
247
+ }
248
+
249
+ /**
250
+ * Commit these rows of the main checkout with `message`: a rename takes both names, a ticked file
251
+ * gone clean meanwhile drops out. Other staged files stay staged, out of the commit.
252
+ * @param {string} projectDir
253
+ * @param {{message: unknown, paths: unknown}} fields
254
+ */
255
+ export async function commitFiles(projectDir, { message, paths }) {
256
+ const dir = path.resolve(projectDir);
257
+ const subject = typeof message === 'string' ? message.trim().split('\n')[0].trim() : '';
258
+ if (!subject) throw new Error('changes commit: write the message first');
259
+ if (!Array.isArray(paths) || !paths.length || paths.some((p) => typeof p !== 'string'))
260
+ throw new Error('changes commit: name the paths, as `gcf changes` lists them');
261
+
262
+ return withMainLock(dir, async () => {
263
+ refuseWhereNoCommitBelongs(dir, subject);
264
+ const { base, rows } = await rowsToCommit(dir);
265
+ const wanted = new Set(paths);
266
+ const picked = rows.filter((r) => wanted.has(r.path));
267
+ if (!picked.length)
268
+ throw refusal(
269
+ 'clean',
270
+ { paths, left: [] },
271
+ `cannot record ${subject}: nothing left to commit in these files`,
272
+ );
273
+ refuseRows(dir, base, picked, subject);
274
+ const moved = picked.flatMap((r) => (r.status === 'renamed' && r.from ? [r.from] : []));
275
+ const names = [...picked.map((r) => r.path), ...moved];
276
+ const gated = names.some(inGate) && existsSync(path.join(dir, 'gcf'));
277
+ if (gated) refuseGateRest(dir, names, subject);
278
+ const all = [...new Set(gated ? [...names, INDEX] : names)];
279
+ // Neither on disk nor in the index, git add finds nothing by them; `--only` finds them in HEAD.
280
+ const gone = new Set([...moved, ...picked.filter((r) => r.xy?.[0] === 'D').map((r) => r.path)]);
281
+ const text = messageOf(message, picked, gated);
282
+ const hash = await undoingOnRefusal(dir, gated, () =>
283
+ stageAndCommit(dir, { add: all.filter((p) => !gone.has(p)), all, subject, text }),
284
+ );
285
+
286
+ return {
287
+ hash: git(dir, ['rev-parse', '--short', hash]).stdout.trim(),
288
+ subject,
289
+ files: picked.length,
290
+ };
291
+ });
292
+ }
package/lib/domain.js CHANGED
@@ -839,7 +839,8 @@ const SECTIONS = {
839
839
  // A move's `dirty` refusal: the board reads `gcf edits diff` and offers these.
840
840
  edits: { commit: 'edits-commit', discard: 'edits-discard' },
841
841
  // `gcf changes` reads what is uncommitted: the board's Changes screen and its header's marker.
842
- changes: {},
842
+ // `commit`: its `gcf changes commit` takes the operator's ticked files and message.
843
+ changes: { commit: true },
843
844
  lessons: {},
844
845
  playtest: {
845
846
  // The inbox category a note from the playtest screen goes with.
@@ -885,6 +886,7 @@ const CHANGES = [
885
886
  'design discard',
886
887
  'edits commit',
887
888
  'edits discard',
889
+ 'changes commit',
888
890
  'take',
889
891
  'done',
890
892
  'drop',
package/lib/git.js CHANGED
@@ -277,8 +277,20 @@ export function commitPaths(projectDir, message, paths, move = {}) {
277
277
  // path commits the deletion. A file staged but never committed and now deleted matches
278
278
  // nothing: no pathspec.
279
279
  const real = paths.filter((p) => existsSync(p) || inHead(projectDir, p));
280
- const msg = ['-m', message, ...moveTrailers(move)];
281
- const only = real.map((p) => literal(projectDir, p));
280
+
281
+ return commitOnly(projectDir, message, real, ['-m', message, ...moveTrailers(move)]);
282
+ }
283
+
284
+ /**
285
+ * `git commit --only` of `paths`, whatever they are, with `msg` its message arguments: the gate's
286
+ * refusals in the words of `message`. Returns the new HEAD.
287
+ * @param {string} projectDir
288
+ * @param {string} message
289
+ * @param {string[]} paths
290
+ * @param {string[]} msg
291
+ */
292
+ export function commitOnly(projectDir, message, paths, msg) {
293
+ const only = paths.map((p) => literal(projectDir, p));
282
294
  // A list past one command line goes on stdin (git 2.25+); a move's few paths as arguments.
283
295
  const long = inParts(only).length > 1;
284
296
  const res = spawnSync(
@@ -299,7 +311,7 @@ export function commitPaths(projectDir, message, paths, move = {}) {
299
311
  // The gate reads the whole gcf/ tree: another file's edit stops the move, in the Operator's
300
312
  // words. Its paths from git: the move's own staged files ride along and stop nothing.
301
313
  if (res.status !== 0 && /gcf\/ has changes outside the index/.test(out)) {
302
- const loose = dirtyGcf(projectDir, real);
314
+ const loose = dirtyGcf(projectDir, paths);
303
315
  throw dirtyRefusal(
304
316
  loose,
305
317
  `cannot record ${message} while gcf/ holds uncommitted changes: ${loose.join(', ')} — ` +
@@ -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