gcf-aif-ext 0.29.1 → 0.29.2

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/unit-ops.js CHANGED
@@ -2,8 +2,7 @@
2
2
  // straight into tests and code, `drop` into the graveyard. Each one removes the section and its
3
3
  // backlog line in the same step, so an id never lives in two places (M12).
4
4
  import { readFile } from 'node:fs/promises';
5
- import { existsSync, readFileSync } from 'node:fs';
6
- import { spawnSync } from 'node:child_process';
5
+ import { existsSync } from 'node:fs';
7
6
  import path from 'node:path';
8
7
  import { serialize } from './frontmatter.js';
9
8
  import { CARD_TYPES, SLUG_RE, blockOrder, listOf } from './design.js';
@@ -11,12 +10,12 @@ import { buildLedger } from './ledger.js';
11
10
  import { cycleMessage, designCheck, dependsGraph, gameMilestones, pathTo } from './design-check.js';
12
11
  import { atomicWrite, withFileRollback } from './safe-path.js';
13
12
  import { writeIndex } from './index-gen.js';
14
- import { operationInProgress, commitPaths, dirtyGcf, dirtyRefusal } from './git.js';
15
13
  import { upsertBlock, openSystemDoc } from './systems-doc.js';
16
14
  import { buryLine, recordLine } from './verdict-fs.js';
17
15
  import { defaultGate } from './validate-item.js';
18
16
  import { refuseByPhase } from './phase.js';
19
- import { locked, withMainLock } from './main-lock.js';
17
+ import { locked } from './main-lock.js';
18
+ import { commitMove } from './commit-move.js';
20
19
 
21
20
  /** A design file's text without the `## <id>` section. */
22
21
  export function removeUnit(text, id) {
@@ -183,6 +182,27 @@ function refuseUnready(units, summaries) {
183
182
  }
184
183
  }
185
184
 
185
+ // A child of a live feature is played with the feature's milestone unless told otherwise.
186
+ const givenMilestone = (ledger, feature, milestone) =>
187
+ milestone ?? (feature ? ledger.item(feature)?.data.milestone : null) ?? null;
188
+
189
+ /** The feature item `units` go under, new or live, refused when one of them waits for it. */
190
+ function featureWrite(ledger, root, units, { feature, ids, names, milestone, today }) {
191
+ const systems = units.flatMap((u) => listOf(u.header.system)).filter((s) => s !== 'TBD');
192
+ // A new feature gets the milestone its units are played with: the given one, else theirs.
193
+ const own = milestone ?? [...new Set(names.values())].find(Boolean) ?? null;
194
+ const write = featureFor(ledger, root, {
195
+ id: feature,
196
+ unitIds: ids,
197
+ systems,
198
+ today,
199
+ milestone: own,
200
+ });
201
+ refuseFeatureCycle(ledger, feature, units);
202
+
203
+ return write;
204
+ }
205
+
186
206
  /**
187
207
  * Take ready design units into work: each section becomes gcf/work/<id>.md with the same body.
188
208
  * One unit stands alone; `feature` groups them under a feature item, new or live. No commit —
@@ -198,9 +218,11 @@ export async function takeUnits(
198
218
  const ledger = await buildLedger(projectDir);
199
219
  const units = ids.map((id) => designUnitOf(ledger, id));
200
220
  refuseUnready(units, (await designCheck(projectDir)).units);
201
- // A child of a live feature is played with the feature's milestone unless told otherwise.
202
- const given = milestone ?? (feature ? ledger.item(feature)?.data.milestone : null) ?? null;
203
- const names = milestonesOf(units, given, await gameMilestones(root));
221
+ const names = milestonesOf(
222
+ units,
223
+ givenMilestone(ledger, feature, milestone),
224
+ await gameMilestones(root),
225
+ );
204
226
  for (const u of units) await refuseByPhase(projectDir, u.header.type, u.header.reopens ?? null);
205
227
  if (feature && !ledger.item(feature)) await refuseByPhase(projectDir, 'feature');
206
228
  const writes = units.map((unit) => ({
@@ -212,15 +234,8 @@ export async function takeUnits(
212
234
  }));
213
235
  for (const w of writes)
214
236
  if (existsSync(w.file)) throw new Error(`gcf/work/${path.basename(w.file)} already exists`);
215
- if (feature) {
216
- const systems = units.flatMap((u) => listOf(u.header.system)).filter((s) => s !== 'TBD');
217
- // A new feature gets the milestone its units are played with: the given one, else theirs.
218
- const own = milestone ?? [...new Set(names.values())].find(Boolean) ?? null;
219
- writes.push(
220
- featureFor(ledger, root, { id: feature, unitIds: ids, systems, today, milestone: own }),
221
- );
222
- refuseFeatureCycle(ledger, feature, units);
223
- }
237
+ if (feature)
238
+ writes.push(featureWrite(ledger, root, units, { feature, ids, names, milestone, today }));
224
239
 
225
240
  const paths = units.map((u) => basePaths(root, u));
226
241
  const touched = [
@@ -237,99 +252,6 @@ export async function takeUnits(
237
252
  return { items: writes.map((w) => `gcf/work/${path.basename(w.file)}`) };
238
253
  }
239
254
 
240
- /** A file's text at a git revision spec (`HEAD:./x`, `:./x` for the index), '' when absent. */
241
- export function gitText(projectDir, spec) {
242
- const res = spawnSync('git', ['show', spec], { cwd: projectDir, encoding: 'utf8' });
243
-
244
- return res.status === 0 ? res.stdout : '';
245
- }
246
-
247
- /**
248
- * True when `file` differs from HEAD in the index or on disk. Line endings do not count: a file
249
- * stored with CRLF and checked out with LF is not an edit.
250
- */
251
- function uncommitted(projectDir, file) {
252
- const rel = `./${path.relative(projectDir, file).replaceAll('\\', '/')}`;
253
- const norm = (t) => String(t).replace(/\r\n/g, '\n').trimEnd();
254
- const head = norm(gitText(projectDir, `HEAD:${rel}`));
255
- const disk = norm(existsSync(file) ? readFileSync(file, 'utf8') : '');
256
-
257
- return head !== norm(gitText(projectDir, `:${rel}`)) || head !== disk;
258
- }
259
-
260
- /**
261
- * Run a move that ends with its fixed-format commit, all of it or none of it. The commit takes
262
- * whole files and deletes the unit's section, so any uncommitted edit in them refuses the move
263
- * up front — an answer in the unit itself included: it would leave in a commit that never held
264
- * it, and no history would keep it. `inputs` are the item files the move reads and rewrites:
265
- * their own uncommitted edits (an answer, a live: delta) ride along on purpose.
266
- * @param {string} projectDir
267
- * @param {string} message
268
- * `key` is the domain's move key and `items` the ids it touched: the commit's trailers.
269
- * @param {{files: string[], mutate: () => Promise<void>, commit: boolean, inputs?: string[],
270
- * key?: string, items?: string[]}} move
271
- */
272
- /** A worktree of the integrator (Methodology §7): its gcf/ state is main's to move. */
273
- export const onWorkBranch = (projectDir) =>
274
- /^work\//.test(
275
- spawnSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], {
276
- cwd: projectDir,
277
- encoding: 'utf8',
278
- }).stdout?.trim() ?? '',
279
- );
280
-
281
- export async function commitMove(projectDir, message, move) {
282
- // A move that commits holds the main lock while it writes and commits (Methodology §7).
283
- return move.commit
284
- ? withMainLock(projectDir, () => record(projectDir, message, move))
285
- : record(projectDir, message, move);
286
- }
287
-
288
- async function record(
289
- projectDir,
290
- message,
291
- { files, mutate, commit, inputs = [], key, items, proposal },
292
- ) {
293
- if (commit && onWorkBranch(projectDir))
294
- throw new Error(
295
- `cannot record ${message} on a work/ branch: a worktree records no move — the run ` +
296
- 'leaves .gcf-session/outcome.json, and the main checkout records it',
297
- );
298
- const busy = commit ? operationInProgress(projectDir) : null;
299
- if (busy) throw new Error(`cannot record ${message} while ${busy} is in progress`);
300
- const dirty = commit
301
- ? files.filter((f) => !inputs.includes(f) && uncommitted(projectDir, f))
302
- : [];
303
- if (dirty.length) {
304
- const rels = dirty.map((f) => path.relative(projectDir, f).replaceAll('\\', '/'));
305
- // The whole of gcf/'s edits, not only these: the gate would refuse the next one at once.
306
- // Only when that set holds them all: a move's own file outside it (an archived plan) is no
307
- // edit `gcf edits` takes, and a Commit of the rest would be refused again.
308
- const all = dirtyGcf(projectDir, inputs);
309
- throw dirtyRefusal(
310
- rels.every((r) => all.includes(r)) ? all : [],
311
- `commit or stash these first (an answered unit is committed before its move), ` +
312
- `${message} would carry them: ${rels.join(', ')}`,
313
- );
314
- }
315
-
316
- const root = path.join(path.resolve(projectDir), 'gcf');
317
- const touched = [...files, path.join(root, 'INDEX.md')];
318
- /** @type {string | null} */
319
- let hash = null;
320
- await withFileRollback(
321
- touched,
322
- async () => {
323
- await mutate();
324
- await writeIndex(root);
325
- if (commit) hash = commitPaths(projectDir, message, touched, { key, items, proposal });
326
- },
327
- { gitCwd: commit ? path.resolve(projectDir) : null },
328
- );
329
-
330
- return hash;
331
- }
332
-
333
255
  /**
334
256
  * A hard unit is built and its tests are green: it leaves design/ without a work item. A line
335
257
  * every future reader of the subsystem must remember goes to the systems doc's `constraints:`.
package/lib/verdict-fs.js CHANGED
@@ -103,7 +103,7 @@ export function unplayedCloseCommit(projectDir, id) {
103
103
  const log = spawnSync(
104
104
  'git',
105
105
  ['log', '-1', '--format=%H', '--fixed-strings', `--grep=gcf(close): ${id} → unplayed`],
106
- { cwd: projectDir, encoding: 'utf8' },
106
+ { windowsHide: true, cwd: projectDir, encoding: 'utf8' },
107
107
  );
108
108
 
109
109
  return (log.status === 0 && log.stdout.trim()) || null;
@@ -113,6 +113,7 @@ export function unplayedCloseCommit(projectDir, id) {
113
113
  export function fileAt(projectDir, rev, file) {
114
114
  const rel = path.relative(projectDir, file).replace(/\\/g, '/');
115
115
  const show = spawnSync('git', ['show', `${rev}:${rel}`], {
116
+ windowsHide: true,
116
117
  cwd: projectDir,
117
118
  encoding: 'utf8',
118
119
  maxBuffer: 64 * 1024 * 1024,
@@ -16,7 +16,12 @@ const stampFile = (projectDir, id) =>
16
16
  path.join(path.resolve(projectDir), '.gcf-session', 'runs', `${id}.verified`);
17
17
 
18
18
  const git = (projectDir, args, env = {}) =>
19
- spawnSync('git', args, { cwd: projectDir, encoding: 'utf8', env: { ...process.env, ...env } });
19
+ spawnSync('git', args, {
20
+ windowsHide: true,
21
+ cwd: projectDir,
22
+ encoding: 'utf8',
23
+ env: { ...process.env, ...env },
24
+ });
20
25
 
21
26
  /**
22
27
  * The git tree of the project's code as it is on disk, committed or not, new files included
package/lib/verify.js CHANGED
@@ -27,7 +27,7 @@ function parents() {
27
27
  return [];
28
28
  }
29
29
  });
30
- const res = spawnSync('ps', ['-A', '-o', 'pid=,ppid='], { encoding: 'utf8' });
30
+ const res = spawnSync('ps', ['-A', '-o', 'pid=,ppid='], { windowsHide: true, encoding: 'utf8' });
31
31
 
32
32
  return (res.stdout ?? '')
33
33
  .split('\n')
@@ -54,7 +54,10 @@ const signal = (p, sig) => {
54
54
  */
55
55
  export function killTree(pid) {
56
56
  if (process.platform === 'win32') {
57
- spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore' });
57
+ spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], {
58
+ windowsHide: true,
59
+ stdio: 'ignore',
60
+ });
58
61
 
59
62
  return;
60
63
  }
@@ -87,6 +90,7 @@ function stopChildren(doomed) {
87
90
  export function runCommand(cmd, cwd, stdio, ms) {
88
91
  let child;
89
92
  const done = new Promise((resolve) => {
93
+ // No windowsHide: the DoD's output goes to the operator's stderr; a hidden console loses it.
90
94
  child = spawn(cmd, { cwd, shell: true, stdio, env: commandEnv() });
91
95
  let timedOut = false;
92
96
  const timer =
package/lib/work-ops.js CHANGED
@@ -15,7 +15,8 @@ import { atomicWrite, resolveInside } from './safe-path.js';
15
15
  import { allowedFrom, decisionFits, FEATURE_ONLY, fromOf } from './transitions.js';
16
16
  import { ITEM_TYPES, DEFAULT_GATE, GATES, SEVERITIES, UNIT_ITEM_TYPES } from './validate-item.js';
17
17
  import { deriveId, isValidId } from './id.js';
18
- import { commitMove, addConstraints, onWorkBranch } from './unit-ops.js';
18
+ import { addConstraints } from './unit-ops.js';
19
+ import { commitMove, onWorkBranch } from './commit-move.js';
19
20
  import { blocksNamed, blocksOf, openSystemDoc, replaceBlock, upsertBlock } from './systems-doc.js';
20
21
  import { blockOrder } from './design.js';
21
22
  import {
@@ -58,6 +59,7 @@ import { appendQuestions, questionsFile } from './questions.js';
58
59
  import { refusal } from './refusal.js';
59
60
  import { releaseBuild } from './play.js';
60
61
  import { playNotesCheck, playNotesOf, withoutPlayNotes } from './play-notes.js';
62
+ import { frozenHash, legacyFrozen, matchesFrozen } from './frozen.js';
61
63
 
62
64
  /**
63
65
  * Options of a committed move; each move reads the ones it needs.
@@ -81,7 +83,11 @@ const gcfOf = (projectDir) => path.join(path.resolve(projectDir), 'gcf');
81
83
 
82
84
  /** HEAD's hash, null outside a repository or before the first commit. */
83
85
  function headHash(projectDir) {
84
- const res = spawnSync('git', ['rev-parse', 'HEAD'], { cwd: projectDir, encoding: 'utf8' });
86
+ const res = spawnSync('git', ['rev-parse', 'HEAD'], {
87
+ windowsHide: true,
88
+ cwd: projectDir,
89
+ encoding: 'utf8',
90
+ });
85
91
 
86
92
  return res.status === 0 ? res.stdout.trim() : null;
87
93
  }
@@ -124,27 +130,6 @@ export function openDepends(ledger, depends = [], { waiting = false } = {}) {
124
130
  });
125
131
  }
126
132
 
127
- /**
128
- * The hash an unplayed item is frozen at (Methodology §5.4): its body and its `live:` delta —
129
- * the two things a tune or a kill takes back out of systems/ and LIVE.md.
130
- */
131
- export const frozenHash = (item) =>
132
- createHash('sha1')
133
- .update(String(item.body).replace(/\r\n/g, '\n').trim())
134
- .update(`\nlive: ${JSON.stringify(item.data.live ?? null)}`)
135
- .digest('hex');
136
-
137
- /** The 0.4.0 `frozen:`: the sha1 of the body alone, without the `live:` delta. */
138
- const legacyFrozen = (item) =>
139
- createHash('sha1').update(String(item.body).replace(/\r\n/g, '\n').trim()).digest('hex');
140
-
141
- /**
142
- * Whether an unplayed item still matches its `frozen:`. An item closed by 0.4.0 holds the
143
- * legacy form, which guards the body only, until `gcf init` restamps it (restampFrozen).
144
- */
145
- export const matchesFrozen = (item) =>
146
- item.data.frozen === frozenHash(item) || item.data.frozen === legacyFrozen(item);
147
-
148
133
  /** Whether the item's `live:` is the one its unplayed close committed. */
149
134
  function liveAsClosed(projectDir, item) {
150
135
  const close = unplayedCloseCommit(projectDir, item.data.id);
@@ -419,6 +404,7 @@ const dropKnownIssue = (m, id) =>
419
404
  /** True when git tracks `file`: an ignored or new plan stays out of the move's commit. */
420
405
  function tracked(projectDir, file) {
421
406
  const res = spawnSync('git', ['ls-files', '--error-unmatch', '--', file], {
407
+ windowsHide: true,
422
408
  cwd: projectDir,
423
409
  stdio: 'ignore',
424
410
  });
@@ -928,6 +914,9 @@ const newCycle = (data) => ({
928
914
  plan_cycle: Number(data.plan_cycle ?? 0) + 1,
929
915
  });
930
916
 
917
+ // Where the operator played it: a note for the history, never a condition (Plan, C).
918
+ const playedNote = (playedOn) => (playedOn?.length ? ` (played on: ${playedOn.join('; ')})` : '');
919
+
931
920
  /** keep | tune | kill on an item waiting for its verdict or unplayed (Methodology §5.4).
932
921
  * @param {MoveOpts} [opts]
933
922
  */
@@ -940,9 +929,7 @@ async function verdictItemUnlocked(projectDir, id, verdict, opts = {}) {
940
929
  if (verdict === 'keep') await keep(m, constraints);
941
930
  else if (verdict === 'tune') await tune(m, note);
942
931
  else removal = endToGraveyard(m, m.item, { reason: note, tags, removal: remove ?? true });
943
- // Where the operator played it: a note for the history, never a condition (Plan, C).
944
- const played = opts.playedOn?.length ? ` (played on: ${opts.playedOn.join('; ')})` : '';
945
- const tail = `${verdict} ${id} → ${systems.join(',')}${played}`;
932
+ const tail = `${verdict} ${id} → ${systems.join(',')}${playedNote(opts.playedOn)}`;
946
933
  const hash = await finish(m, `verdict:${verdict}`, tail, commit);
947
934
 
948
935
  return { verdict, id, systems, hash, removal, ...buildLeft(m) };
@@ -957,11 +944,12 @@ function changedIn(projectDir) {
957
944
  const res = spawnSync(
958
945
  'git',
959
946
  ['-c', 'core.quotePath=false', 'status', '--porcelain', '-uall', '--', ...KEEP_SCOPE],
960
- { cwd: projectDir, encoding: 'utf8' },
947
+ { windowsHide: true, cwd: projectDir, encoding: 'utf8' },
961
948
  );
962
949
  if (res.status !== 0) throw new Error(`git status failed: ${res.stderr.trim()}`);
963
950
  // Porcelain paths are the repository's: a project inside a bigger repository is a prefix in.
964
951
  const prefix = spawnSync('git', ['rev-parse', '--show-prefix'], {
952
+ windowsHide: true,
965
953
  cwd: projectDir,
966
954
  encoding: 'utf8',
967
955
  }).stdout.trim();
@@ -1002,17 +990,8 @@ function keepOrder(pack) {
1002
990
  return order;
1003
991
  }
1004
992
 
1005
- /**
1006
- * keep of a whole milestone (docs/Autonomy-Plan.md, C): every unplayed and awaiting-verdict item
1007
- * of it, one commit, all or nothing. Every check comes before the first write: a frozen body
1008
- * edited, a dependency outside the milestone not played yet, a cycle inside it. The items
1009
- * inside keep in dependency order, each seeing the ones before it ended. gcf/ and the plans
1010
- * must be clean but for the pack's own item files (their compress edits ride along); a failure
1011
- * on the way restores them all.
1012
- * @param {MoveOpts & {playedOn?: string[]}} [opts]
1013
- */
1014
- async function keepMilestoneUnlocked(projectDir, name, opts = {}) {
1015
- const { note = '', playedOn = [], commit = true } = opts;
993
+ /** The milestone's items that wait for its play, each checked before the first write. */
994
+ async function keepPack(projectDir, name) {
1016
995
  const root = gcfOf(projectDir);
1017
996
  const milestones = (await gameMilestones(root)) ?? [];
1018
997
  if (!milestones.some((m) => m.name === name))
@@ -1036,8 +1015,11 @@ async function keepMilestoneUnlocked(projectDir, name, opts = {}) {
1036
1015
  );
1037
1016
  }
1038
1017
 
1039
- const order = keepOrder(pack);
1040
- const own = new Set(pack.map((i) => path.relative(projectDir, i.file).replaceAll('\\', '/')));
1018
+ return pack;
1019
+ }
1020
+
1021
+ /** Refuse a milestone keep that would carry changes of gcf/ or the plans but the pack's own. */
1022
+ function refuseLoose(projectDir, name, own) {
1041
1023
  const loose = changedIn(projectDir).filter((c) => !own.has(c.file));
1042
1024
  if (loose.length) {
1043
1025
  // The board's Commit clears only gcf/'s edits: a loose plan gets the words alone.
@@ -1048,11 +1030,64 @@ async function keepMilestoneUnlocked(projectDir, name, opts = {}) {
1048
1030
  loose.map((c) => c.file).join(', '),
1049
1031
  );
1050
1032
  }
1033
+ }
1051
1034
 
1035
+ function refuseKeepBusy(projectDir, name, commit) {
1052
1036
  if (commit && onWorkBranch(projectDir))
1053
1037
  throw new Error('keep --milestone records on main: a work/ branch records no move');
1054
1038
  const busy = commit ? operationInProgress(projectDir) : null;
1055
1039
  if (busy) throw new Error(`cannot keep milestone ${name} while ${busy} is in progress`);
1040
+ }
1041
+
1042
+ /** The pack's keeps in `order`, and the one commit of them. */
1043
+ async function keepAll(projectDir, name, order, { note, playedOn, commit }) {
1044
+ for (const id of order)
1045
+ await verdictItemUnlocked(projectDir, id, 'keep', { note, playedOn, commit: false });
1046
+ if (!commit) return { milestone: name, ids: order, hash: null };
1047
+ const files = changedIn(projectDir).map((c) => path.join(projectDir, c.file));
1048
+ const message = `gcf(verdict): keep ${name} → ${order.join(', ')}${playedNote(playedOn)}`;
1049
+ const hash = commitPaths(projectDir, message, files, { key: 'verdict:keep', items: order });
1050
+ for (const id of order) clearCard(projectDir, id);
1051
+ const left = order.map((id) => releaseBuild(projectDir, id)).filter(Boolean);
1052
+
1053
+ return { milestone: name, ids: order, hash, ...(left.length ? { build_left: left } : {}) };
1054
+ }
1055
+
1056
+ function undoKeep(projectDir, own, saved, index) {
1057
+ // Nothing kept: what the keep wrote back to HEAD (staged or not); the pack's own files keep
1058
+ // the operator's edits on disk and in the index as they were.
1059
+ const mine = changedIn(projectDir)
1060
+ .map((c) => c.file)
1061
+ .filter((f) => !own.has(f));
1062
+ if (mine.length)
1063
+ spawnSync('git', ['reset', '-q', '--', ...mine], { windowsHide: true, cwd: projectDir });
1064
+ for (const c of changedIn(projectDir)) {
1065
+ if (own.has(c.file)) continue;
1066
+ if (c.untracked) rmSync(path.join(projectDir, c.file), { force: true });
1067
+ else
1068
+ spawnSync('git', ['checkout', 'HEAD', '--', c.file], { windowsHide: true, cwd: projectDir });
1069
+ }
1070
+
1071
+ for (const [file, text] of saved) writeFileSync(file, text);
1072
+ if (index) restoreIndex(index);
1073
+ }
1074
+
1075
+ /**
1076
+ * keep of a whole milestone (docs/Autonomy-Plan.md, C): every unplayed and awaiting-verdict item
1077
+ * of it, one commit, all or nothing. Every check comes before the first write: a frozen body
1078
+ * edited, a dependency outside the milestone not played yet, a cycle inside it. The items
1079
+ * inside keep in dependency order, each seeing the ones before it ended. gcf/ and the plans
1080
+ * must be clean but for the pack's own item files (their compress edits ride along); a failure
1081
+ * on the way restores them all.
1082
+ * @param {MoveOpts & {playedOn?: string[]}} [opts]
1083
+ */
1084
+ async function keepMilestoneUnlocked(projectDir, name, opts = {}) {
1085
+ const { note = '', playedOn = [], commit = true } = opts;
1086
+ const pack = await keepPack(projectDir, name);
1087
+ const order = keepOrder(pack);
1088
+ const own = new Set(pack.map((i) => path.relative(projectDir, i.file).replaceAll('\\', '/')));
1089
+ refuseLoose(projectDir, name, own);
1090
+ refuseKeepBusy(projectDir, name, commit);
1056
1091
 
1057
1092
  const saved = pack.map((i) => [i.file, readFileSync(i.file)]);
1058
1093
  // Their index as the operator left it: a staged compress edit stays staged after a rollback.
@@ -1060,33 +1095,10 @@ async function keepMilestoneUnlocked(projectDir, name, opts = {}) {
1060
1095
  projectDir,
1061
1096
  pack.map((i) => i.file),
1062
1097
  );
1063
- const played = playedOn.length ? ` (played on: ${playedOn.join('; ')})` : '';
1064
1098
  try {
1065
- for (const id of order)
1066
- await verdictItemUnlocked(projectDir, id, 'keep', { note, playedOn, commit: false });
1067
- if (!commit) return { milestone: name, ids: order, hash: null };
1068
- const files = changedIn(projectDir).map((c) => path.join(projectDir, c.file));
1069
- const message = `gcf(verdict): keep ${name} → ${order.join(', ')}${played}`;
1070
- const hash = commitPaths(projectDir, message, files, { key: 'verdict:keep', items: order });
1071
- for (const id of order) clearCard(projectDir, id);
1072
- const left = order.map((id) => releaseBuild(projectDir, id)).filter(Boolean);
1073
-
1074
- return { milestone: name, ids: order, hash, ...(left.length ? { build_left: left } : {}) };
1099
+ return await keepAll(projectDir, name, order, { note, playedOn, commit });
1075
1100
  } catch (e) {
1076
- // Nothing kept: what the keep wrote back to HEAD (staged or not); the pack's own files keep
1077
- // the operator's edits on disk and in the index as they were.
1078
- const mine = changedIn(projectDir)
1079
- .map((c) => c.file)
1080
- .filter((f) => !own.has(f));
1081
- if (mine.length) spawnSync('git', ['reset', '-q', '--', ...mine], { cwd: projectDir });
1082
- for (const c of changedIn(projectDir)) {
1083
- if (own.has(c.file)) continue;
1084
- if (c.untracked) rmSync(path.join(projectDir, c.file), { force: true });
1085
- else spawnSync('git', ['checkout', 'HEAD', '--', c.file], { cwd: projectDir });
1086
- }
1087
-
1088
- for (const [file, text] of saved) writeFileSync(file, text);
1089
- if (index) restoreIndex(index);
1101
+ undoKeep(projectDir, own, saved, index);
1090
1102
  throw new Error(`keep --milestone ${name}: nothing kept — ${e.message}`, { cause: e });
1091
1103
  }
1092
1104
  }
@@ -1537,9 +1549,20 @@ function checkDepends(ledger, id, depends, { added = depends, parent = null } =
1537
1549
  }
1538
1550
  }
1539
1551
 
1552
+ /** The gate a new item of `type` gets, refused when it is none or its type forbids it. */
1553
+ function gateOfNew({ type, gate, severity }) {
1554
+ const g = gate ?? DEFAULT_GATE[type];
1555
+ if (!GATES.includes(g)) throw new Error(`gate must be ${GATES.join(' | ')}`);
1556
+ if (type === 'feature' && g !== 'auto') throw new Error('a feature always has gate auto');
1557
+ if (type === 'bug' && !SEVERITIES.includes(severity))
1558
+ throw new Error(`a bug needs --severity ${SEVERITIES.join('|')}`);
1559
+
1560
+ return g;
1561
+ }
1562
+
1540
1563
  /** Refuse a spec `item new` cannot honour; returns the gate the item gets. */
1541
1564
  function checkNew(ledger, spec) {
1542
- const { id, type, gate, severity } = spec;
1565
+ const { id, type } = spec;
1543
1566
  if (!isValidId(id)) throw new Error(`${id} is not a lowercase hyphen slug`);
1544
1567
  if (spec.parent && !isValidId(spec.parent))
1545
1568
  throw new Error(`--parent is one feature item, not ${spec.parent}`);
@@ -1547,11 +1570,7 @@ function checkNew(ledger, spec) {
1547
1570
  if (!ITEM_TYPES.includes(type)) throw new Error(`type must be ${ITEM_TYPES.join(' | ')}`);
1548
1571
  if (UNIT_ITEM_TYPES.includes(type))
1549
1572
  throw new Error(`a ${type} is a design unit: write it in gcf/design/, then gcf take ${id}`);
1550
- const g = gate ?? DEFAULT_GATE[type];
1551
- if (!GATES.includes(g)) throw new Error(`gate must be ${GATES.join(' | ')}`);
1552
- if (type === 'feature' && g !== 'auto') throw new Error('a feature always has gate auto');
1553
- if (type === 'bug' && !SEVERITIES.includes(severity))
1554
- throw new Error(`a bug needs --severity ${SEVERITIES.join('|')}`);
1573
+ const g = gateOfNew(spec);
1555
1574
  checkRelease(spec);
1556
1575
  checkDepends(ledger, id, spec.depends ?? [], { parent: spec.parent });
1557
1576
 
@@ -1860,7 +1879,10 @@ function lstatOr(file) {
1860
1879
  }
1861
1880
  }
1862
1881
 
1863
- /** @type {typeof setGatesUnlocked} */
1882
+ /**
1883
+ * @type {typeof setGatesUnlocked}
1884
+ * @public gcf.js imports lib modules by name at run time, out of knip's sight.
1885
+ */
1864
1886
  export const setGates = (projectDir, id, opts = {}) =>
1865
1887
  locked(projectDir, opts.commit ?? true, () => setGatesUnlocked(projectDir, id, opts));
1866
1888
  /** @type {typeof attachItemUnlocked} */
@@ -1896,14 +1918,8 @@ async function titleForId(root, spec) {
1896
1918
  return title;
1897
1919
  }
1898
1920
 
1899
- async function newItemUnlocked(projectDir, given) {
1900
- const root = gcfOf(projectDir);
1901
- const ledger = await buildLedger(projectDir);
1902
- // The system's id, made under the lock that writes it: two moves never take one id.
1903
- const spec = given.id
1904
- ? given
1905
- : { ...given, id: deriveId(await titleForId(root, given), ledger.known, given.type) };
1906
- const gate = checkNew(ledger, spec);
1921
+ /** Refuse a new item's milestone that game.md does not list, or a feature without one. */
1922
+ async function checkNewMilestone(root, spec) {
1907
1923
  const feature = spec.type === 'feature';
1908
1924
  const milestones = spec.milestone || feature ? await gameMilestones(root) : null;
1909
1925
  if (spec.milestone && milestones && !milestones.some((m) => m.name === spec.milestone))
@@ -1917,9 +1933,10 @@ async function newItemUnlocked(projectDir, given) {
1917
1933
  `a feature is played with its milestone: --milestone ` +
1918
1934
  `<${milestones.map((m) => m.name).join(' | ')}>`,
1919
1935
  );
1920
- if (spec.proposal !== undefined && !/^[\w-]+\/[\w-]+$/.test(spec.proposal))
1921
- throw new Error(`--proposal is <thread>/<proposal id>, not ${spec.proposal}`);
1922
- if (spec.dryRun) return { id: spec.id, item: `gcf/work/${spec.id}.md`, hash: null };
1936
+ }
1937
+
1938
+ /** The new item's file, refused where the phase, its reopens, the file or its note forbid it. */
1939
+ async function checkNewWrite(projectDir, root, ledger, spec) {
1923
1940
  await refuseByPhase(projectDir, spec.type, spec.reopens);
1924
1941
  if (spec.reopens && !ledger.where(spec.reopens).terminal.length)
1925
1942
  throw new Error(`reopens names ${spec.reopens}, which has not ended`);
@@ -1927,6 +1944,23 @@ async function newItemUnlocked(projectDir, given) {
1927
1944
  if (existsSync(file)) throw new Error(`gcf/work/${spec.id}.md already exists`);
1928
1945
  if (spec.note !== undefined && spec.note.length > NOTE_MAX)
1929
1946
  throw new Error(`the note is ${spec.note.length} characters: up to ${NOTE_MAX}`);
1947
+
1948
+ return file;
1949
+ }
1950
+
1951
+ async function newItemUnlocked(projectDir, given) {
1952
+ const root = gcfOf(projectDir);
1953
+ const ledger = await buildLedger(projectDir);
1954
+ // The system's id, made under the lock that writes it: two moves never take one id.
1955
+ const spec = given.id
1956
+ ? given
1957
+ : { ...given, id: deriveId(await titleForId(root, given), ledger.known, given.type) };
1958
+ const gate = checkNew(ledger, spec);
1959
+ await checkNewMilestone(root, spec);
1960
+ if (spec.proposal !== undefined && !/^[\w-]+\/[\w-]+$/.test(spec.proposal))
1961
+ throw new Error(`--proposal is <thread>/<proposal id>, not ${spec.proposal}`);
1962
+ if (spec.dryRun) return { id: spec.id, item: `gcf/work/${spec.id}.md`, hash: null };
1963
+ const file = await checkNewWrite(projectDir, root, ledger, spec);
1930
1964
  const take = await takeEntry(projectDir, root, spec);
1931
1965
  // A note given goes over what the entry says: a board's form shows that text and sends it back,
1932
1966
  // and a human's edit of it is the note.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gcf-aif-ext",
3
- "version": "0.29.1",
3
+ "version": "0.29.2",
4
4
  "description": "Game Context Framework for AI Factory",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -135,6 +135,7 @@ gcf_forbidden:
135
135
  - do not change what agent runs may do: `ai-factory gcf permissions`, its deny groups and the board's YOLO belong to the human
136
136
  - a run blocked with `needs permission` goes on once the human allows that one rule for its next run: the board's **Allow <rule> for one run**
137
137
  - its console form is `ai-factory gcf unblock <id>`, then `ai-factory gcf-harness run <id> --allow "<rule>"`, the rule as the refusal card names it
138
+ - do not name or guess the rule that refused a call (`Edit(.claude/settings.json)` is a guess): you do not know it; name the refused call and point the human to that Allow button on the item's card
138
139
  - do not change a setting of `gcf/config.yml` or the `language` of `.ai-factory/config.yaml`: `ai-factory gcf config set` belongs to the human
139
140
  - do not reuse an ended id: rework gets a new id with `reopens: <old id>`
140
141
  - do not commit past the gate with `--no-verify`: a refused commit names what to fix