gcf-aif-ext 0.18.8 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/work-ops.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // docs, the parent feature, a removal item, the archived plan. Atomic: a refused commit rolls
5
5
  // every file back.
6
6
  import { copyFile, mkdir, readFile, unlink } from 'node:fs/promises';
7
- import { existsSync, lstatSync, readdirSync } from 'node:fs';
7
+ import { existsSync, lstatSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
8
8
  import { spawnSync } from 'node:child_process';
9
9
  import { createHash } from 'node:crypto';
10
10
  import path from 'node:path';
@@ -43,6 +43,9 @@ import { locked, runHolder } from './main-lock.js';
43
43
  import { dropAgentSession, ownsMark, releaseSession, sessionActive } from './session-mark.js';
44
44
  import { dropStamp, unverifiedProblem } from './verify-stamp.js';
45
45
  import { planTicks } from './plan-check.js';
46
+ import { commitPaths, operationInProgress, restoreIndex, snapshotIndex } from './git.js';
47
+ import { verdictDeferred } from './gates.js';
48
+ import { appendQuestions, questionsFile } from './questions.js';
46
49
 
47
50
  /**
48
51
  * Options of a committed move; each move reads the ones it needs.
@@ -53,6 +56,9 @@ import { planTicks } from './plan-check.js';
53
56
  * @property {boolean} [remove] create a removal item; absent = the move's default
54
57
  * @property {string[]} [constraints]
55
58
  * @property {boolean} [commit]
59
+ * @property {string[]} [assume] the agent's assumptions: D2 records in the move's commit
60
+ * @property {boolean} [dropOutcome] the integrator's: the plan's `## Outcome` leaves in the commit
61
+ * @property {string} [said] the agent's word for the human, into the commit's subject
56
62
  */
57
63
 
58
64
  const SOFT = ['mechanic', 'resource'];
@@ -293,7 +299,9 @@ function needTicked(m, opts) {
293
299
  /** The commit's tail of a move made without a green verify, or with tasks left unticked. */
294
300
  const unverifiedTail = (opts) =>
295
301
  (opts.unverified ? ` (unverified: ${opts.unverified})` : '') +
296
- (opts.unticked ? ` (unticked: ${opts.unticked})` : '');
302
+ (opts.unticked ? ` (unticked: ${opts.unticked})` : '') +
303
+ // What the agent said for the human in its plan's Outcome, when the gates did not let it act.
304
+ (opts.said ? ` (${opts.said})` : '');
297
305
 
298
306
  const writeItem = (item, data, body = item.body) => atomicWrite(item.file, serialize(data, body));
299
307
  /**
@@ -390,6 +398,36 @@ function archivePlan(m, item) {
390
398
  return destRel;
391
399
  }
392
400
 
401
+ /** A plan's text without its `## Outcome` block (to the next heading of level 1 or 2). */
402
+ export function withoutOutcome(text) {
403
+ const lines = String(text).split(/(?<=\n)/);
404
+ const at = lines.findIndex((l) => /^## Outcome[ \t]*\r?\n?$/.test(l));
405
+ if (at < 0) return text;
406
+ const rest = lines.slice(at + 1).findIndex((l) => /^#{1,2} /.test(l));
407
+ const end = rest < 0 ? lines.length : at + 1 + rest;
408
+
409
+ return lines.slice(0, at).join('') + lines.slice(end).join('');
410
+ }
411
+
412
+ /**
413
+ * The integrator's move takes the plan's `## Outcome` out in its own commit (`dropOutcome`): a
414
+ * later run of the item, after a tune, must not record its assumptions again. A plan the move
415
+ * archives keeps it there, read by nobody.
416
+ */
417
+ function dropOutcomeOf(m) {
418
+ const rel = m.item.data.plan ?? `.ai-factory/plans/${m.item.data.id}.md`;
419
+ const file = resolveInside(m.projectDir, rel);
420
+ if (!existsSync(file)) return;
421
+ m.touch(file);
422
+ m.step(async () => {
423
+ // Archived meanwhile by this move: nothing left here.
424
+ if (!existsSync(file)) return;
425
+ const text = await readFile(file, 'utf8');
426
+ const out = withoutOutcome(text);
427
+ if (out !== text) await atomicWrite(file, out);
428
+ });
429
+ }
430
+
393
431
  /** A delta whose changes name no refs points at where the item's detail now lives. */
394
432
  function withRefs(delta, refs) {
395
433
  if (!delta || 'none' in delta || !refs) return delta;
@@ -550,7 +588,58 @@ function refuseOpenDepends(m, move, opts = {}) {
550
588
  );
551
589
  }
552
590
 
553
- /** ready → awaiting-verdict / awaiting-decision; `since` marks where the wait began.
591
+ /**
592
+ * The agent's assumptions a move carries (`assume`, docs/Autonomy-Plan.md B): D2 records of
593
+ * gcf/open-questions.md in the move's own commit. A line `<question> = <value>` splits there.
594
+ * @param {string[]} [lines]
595
+ */
596
+ function assumeInto(m, lines = []) {
597
+ if (!lines.length) return;
598
+ const id = String(m.item.data.id);
599
+ const records = lines.map((line) => {
600
+ const at = line.indexOf(' = ');
601
+
602
+ return {
603
+ class: 'D2',
604
+ question: at > 0 ? line.slice(0, at) : line,
605
+ assumed: at > 0 ? line.slice(at + 3) : line,
606
+ sys: (m.item.data.system ?? []).join(', '),
607
+ until: SOFT.includes(m.item.data.type) ? `verdict(${id})` : null,
608
+ lens: id,
609
+ };
610
+ });
611
+ m.touch(questionsFile(m.root));
612
+ m.step(() => appendQuestions(m.root, records));
613
+ }
614
+
615
+ /**
616
+ * A4: the capabilities a soft unit's delta modifies or removes. Such a unit cannot close
617
+ * unplayed — a tune or a kill could not take its change back out — so it waits for a verdict.
618
+ */
619
+ const playChanges = (item) =>
620
+ SOFT.includes(item.data.type)
621
+ ? (item.data.live?.changes ?? []).filter((c) => c.change !== 'added').map((c) => c.id)
622
+ : [];
623
+
624
+ /**
625
+ * A4 in one write: gate verdict, awaiting-verdict, and why (`gate_why`) — status alone would
626
+ * break "awaiting-verdict needs gate: verdict".
627
+ */
628
+ function awaitVerdict(m, why = null) {
629
+ const data = {
630
+ ...without(m.item.data, 'blocked'),
631
+ gate: 'verdict',
632
+ status: 'awaiting-verdict',
633
+ ...(why ? { gate_why: why } : {}),
634
+ since: headHash(m.projectDir),
635
+ };
636
+ m.step(() => writeItem(m.item, data));
637
+ }
638
+
639
+ /**
640
+ * ready → awaiting-verdict / awaiting-decision; `since` marks where the wait began. A soft unit
641
+ * under `gates.verdict: defer` closes unplayed instead (played with its milestone), unless its
642
+ * delta changes a capability (A4): then it waits, with the reason.
554
643
  * @param {MoveOpts} [opts]
555
644
  */
556
645
  async function submitItemUnlocked(projectDir, id, opts = {}) {
@@ -558,25 +647,43 @@ async function submitItemUnlocked(projectDir, id, opts = {}) {
558
647
  const m = await begin(projectDir, id, 'submit');
559
648
  if (m.item.data.gate === 'auto')
560
649
  throw new Error(`${id} has gate auto: nobody waits for it — close it with gcf close ${id}`);
561
- refuseOpenDepends(m, 'submit', { waiting: true });
650
+ // Whether the gates defer it, its delta aside: a changed capability (A4) then says why it waits.
651
+ const deferred = verdictDeferred(await readConfig(m.root), { ...m.item.data, live: null });
652
+ const changes = playChanges(m.item);
653
+ // Unplayed needs its dependencies played, as a close does: not one still waiting (§4.1).
654
+ refuseOpenDepends(m, 'submit', { waiting: !deferred || changes.length > 0 });
562
655
  needTicked(m, opts);
563
656
  needVerified(m, opts);
564
- const status = m.item.data.gate === 'verdict' ? 'awaiting-verdict' : 'awaiting-decision';
565
- const data = { ...without(m.item.data, 'blocked'), status, since: headHash(projectDir) };
566
- m.step(() => writeItem(m.item, data));
657
+ assumeInto(m, opts.assume);
658
+ if (opts.dropOutcome) dropOutcomeOf(m);
659
+ if (deferred && !changes.length) {
660
+ closeUnplayed(m);
661
+ const tail = `${id} → unplayed (deferred)${unverifiedTail(opts)}`;
662
+
663
+ return {
664
+ id,
665
+ status: 'unplayed',
666
+ deferred: true,
667
+ hash: await finish(m, 'submit', tail, commit),
668
+ };
669
+ }
567
670
 
568
- return { id, status, hash: await finish(m, 'submit', `${id}${unverifiedTail(opts)}`, commit) };
569
- }
671
+ const verdict = m.item.data.gate === 'verdict';
672
+ const why = deferred ? `modifies ${changes.join(', ')}` : null;
673
+ if (verdict) awaitVerdict(m, why);
674
+ else {
675
+ const data = {
676
+ ...without(m.item.data, 'blocked'),
677
+ status: 'awaiting-decision',
678
+ since: headHash(projectDir),
679
+ };
680
+ m.step(() => writeItem(m.item, data));
681
+ }
570
682
 
571
- /** Why a soft gate-auto item cannot close unplayed, or null: only an `added` comes back out. */
572
- export function unplayedCloseProblem(item) {
573
- if (!SOFT.includes(item.data.type) || item.data.gate !== 'auto') return null;
574
- if (!(item.data.live?.changes ?? []).some((c) => c.change !== 'added')) return null;
683
+ const status = verdict ? 'awaiting-verdict' : 'awaiting-decision';
684
+ const tail = `${id}${why ? ` → ${status} (${why})` : ''}${unverifiedTail(opts)}`;
575
685
 
576
- return (
577
- `${item.data.id}: an unplayed close can only add capabilities (a modified or removed one ` +
578
- 'cannot be taken back) — set gate: verdict and submit it'
579
- );
686
+ return { id, status, hash: await finish(m, 'submit', tail, commit) };
580
687
  }
581
688
 
582
689
  /**
@@ -587,8 +694,6 @@ export function unplayedCloseProblem(item) {
587
694
  function closeUnplayed(m) {
588
695
  const { item } = m;
589
696
  const id = String(item.data.id);
590
- const refused = unplayedCloseProblem(item);
591
- if (refused) throw new Error(refused);
592
697
  const systems = item.data.system ?? [];
593
698
  m.touch(...systemFiles(m.root, systems));
594
699
  m.step(async () => {
@@ -631,17 +736,30 @@ async function closeItemUnlocked(projectDir, id, opts = {}) {
631
736
  const { constraints = [], commit = true } = opts;
632
737
  const m = await begin(projectDir, id, 'close');
633
738
  const unplayed = SOFT.includes(m.item.data.type);
739
+ const changes = m.item.data.gate === 'auto' ? playChanges(m.item) : [];
634
740
  if (m.item.data.type === 'feature') closeFeature(m);
635
741
  else {
636
742
  if (m.item.data.gate !== 'auto')
637
743
  throw new Error(`${id} has gate ${m.item.data.gate}: submit it, the operator closes it`);
638
- refuseOpenDepends(m, 'close');
744
+ // A4: it will wait for a verdict, so a dependency waiting for its own is no bar.
745
+ refuseOpenDepends(m, 'close', { waiting: changes.length > 0 });
639
746
  needTicked(m, opts);
640
747
  needVerified(m, opts);
641
- if (unplayed) closeUnplayed(m);
748
+ if (changes.length) awaitVerdict(m, `modifies ${changes.join(', ')}`);
749
+ else if (unplayed) closeUnplayed(m);
642
750
  else await closeEnding(m, constraints);
643
751
  }
644
752
 
753
+ assumeInto(m, opts.assume);
754
+ if (opts.dropOutcome) dropOutcomeOf(m);
755
+ if (changes.length) {
756
+ // The item waits now: the move is a submit's, as the integrator and the history read it.
757
+ const why = `modifies ${changes.join(', ')}`;
758
+ const tail = `${id} → awaiting-verdict (${why})${unverifiedTail(opts)}`;
759
+
760
+ return { id, hash: await finish(m, 'submit', tail, commit), unplayed: false, awaits: why };
761
+ }
762
+
645
763
  const tail = `${id}${unplayed ? ' → unplayed' : ''}${unverifiedTail(opts)}`;
646
764
  const hash = await finish(m, 'close', tail, commit);
647
765
 
@@ -712,12 +830,150 @@ async function verdictItemUnlocked(projectDir, id, verdict, opts = {}) {
712
830
  if (verdict === 'keep') await keep(m, constraints);
713
831
  else if (verdict === 'tune') await tune(m, note);
714
832
  else removal = endToGraveyard(m, m.item, { reason: note, tags, removal: remove ?? true });
715
- const tail = `${verdict} ${id} → ${systems.join(',')}`;
833
+ // Where the operator played it: a note for the history, never a condition (Plan, C).
834
+ const played = opts.playedOn?.length ? ` (played on: ${opts.playedOn.join('; ')})` : '';
835
+ const tail = `${verdict} ${id} → ${systems.join(',')}${played}`;
716
836
  const hash = await finish(m, `verdict:${verdict}`, tail, commit);
717
837
 
718
838
  return { verdict, id, systems, hash, removal };
719
839
  }
720
840
 
841
+ // What a milestone's keep may write: gcf/ and the plans its items archive.
842
+ const KEEP_SCOPE = ['gcf', '.ai-factory/plans', '.ai-factory/archive'];
843
+
844
+ /** The paths under KEEP_SCOPE git sees changed or new, relative to the project. */
845
+ function changedIn(projectDir) {
846
+ const res = spawnSync(
847
+ 'git',
848
+ ['-c', 'core.quotePath=false', 'status', '--porcelain', '-uall', '--', ...KEEP_SCOPE],
849
+ { cwd: projectDir, encoding: 'utf8' },
850
+ );
851
+ if (res.status !== 0) throw new Error(`git status failed: ${res.stderr.trim()}`);
852
+ // Porcelain paths are the repository's: a project inside a bigger repository is a prefix in.
853
+ const prefix = spawnSync('git', ['rev-parse', '--show-prefix'], {
854
+ cwd: projectDir,
855
+ encoding: 'utf8',
856
+ }).stdout.trim();
857
+
858
+ return res.stdout
859
+ .split('\n')
860
+ .filter(Boolean)
861
+ .map((l) => {
862
+ const file = l.slice(3).replace(/^.* -> /, '');
863
+
864
+ return {
865
+ untracked: l.startsWith('??'),
866
+ file: prefix && file.startsWith(prefix) ? file.slice(prefix.length) : file,
867
+ };
868
+ });
869
+ }
870
+
871
+ /** The pack's ids in dependency order: each after every pack item it depends on. */
872
+ function keepOrder(pack) {
873
+ const ids = new Set(pack.map((i) => String(i.data.id)));
874
+ const deps = new Map(
875
+ pack.map((i) => [String(i.data.id), (i.data.depends ?? []).filter((d) => ids.has(d))]),
876
+ );
877
+ const order = [];
878
+ const state = new Map();
879
+ const visit = (id, trail) => {
880
+ if (state.get(id) === 'done') return;
881
+ if (state.get(id) === 'open')
882
+ throw new Error(`a dependency cycle inside the milestone: ${[...trail, id].join(' → ')}`);
883
+ state.set(id, 'open');
884
+ for (const d of deps.get(id)) visit(d, [...trail, id]);
885
+ state.set(id, 'done');
886
+ order.push(id);
887
+ };
888
+
889
+ for (const id of ids) visit(id, []);
890
+
891
+ return order;
892
+ }
893
+
894
+ /**
895
+ * keep of a whole milestone (docs/Autonomy-Plan.md, C): every unplayed and awaiting-verdict item
896
+ * of it, one commit, all or nothing. Every check comes before the first write: a frozen body
897
+ * edited, a dependency outside the milestone not played yet, a cycle inside it. The items
898
+ * inside keep in dependency order, each seeing the ones before it ended. gcf/ and the plans
899
+ * must be clean but for the pack's own item files (their compress edits ride along); a failure
900
+ * on the way restores them all.
901
+ * @param {MoveOpts & {playedOn?: string[]}} [opts]
902
+ */
903
+ async function keepMilestoneUnlocked(projectDir, name, opts = {}) {
904
+ const { note = '', playedOn = [], commit = true } = opts;
905
+ const root = gcfOf(projectDir);
906
+ const milestones = (await gameMilestones(root)) ?? [];
907
+ if (!milestones.some((m) => m.name === name))
908
+ throw new Error(`${name} is not a milestone of game.md`);
909
+ const ledger = await buildLedger(projectDir);
910
+ const pack = ledger.items.filter(
911
+ (i) => i.data.milestone === name && ['unplayed', 'awaiting-verdict'].includes(i.data.status),
912
+ );
913
+ if (!pack.length) throw new Error(`milestone ${name}: nothing waits for its play`);
914
+ const ids = new Set(pack.map((i) => String(i.data.id)));
915
+ for (const i of pack) {
916
+ const id = String(i.data.id);
917
+ refuseRunning(projectDir, id);
918
+ if (i.data.status === 'unplayed')
919
+ refuseEdited(i, `carry the edit in a new item with reopens: ${id}`);
920
+ const outside = openDepends(ledger, i.data.depends ?? []).filter((d) => !ids.has(d));
921
+ if (outside.length)
922
+ throw new Error(
923
+ `keep --milestone ${name}: ${id} depends on ${outside.join(', ')}, outside the ` +
924
+ 'milestone and not played yet — keep that first, or keep the items one by one',
925
+ );
926
+ }
927
+
928
+ const order = keepOrder(pack);
929
+ const own = new Set(pack.map((i) => path.relative(projectDir, i.file).replaceAll('\\', '/')));
930
+ const loose = changedIn(projectDir).filter((c) => !own.has(c.file));
931
+ if (loose.length)
932
+ throw new Error(
933
+ `commit or stash these first, keep --milestone ${name} would carry them: ` +
934
+ loose.map((c) => c.file).join(', '),
935
+ );
936
+
937
+ if (commit && onWorkBranch(projectDir))
938
+ throw new Error('keep --milestone records on main: a work/ branch records no move');
939
+ const busy = commit ? operationInProgress(projectDir) : null;
940
+ if (busy) throw new Error(`cannot keep milestone ${name} while ${busy} is in progress`);
941
+
942
+ const saved = pack.map((i) => [i.file, readFileSync(i.file)]);
943
+ // Their index as the operator left it: a staged compress edit stays staged after a rollback.
944
+ const index = snapshotIndex(
945
+ projectDir,
946
+ pack.map((i) => i.file),
947
+ );
948
+ const played = playedOn.length ? ` (played on: ${playedOn.join('; ')})` : '';
949
+ try {
950
+ for (const id of order)
951
+ await verdictItemUnlocked(projectDir, id, 'keep', { note, playedOn, commit: false });
952
+ if (!commit) return { milestone: name, ids: order, hash: null };
953
+ const files = changedIn(projectDir).map((c) => path.join(projectDir, c.file));
954
+ const message = `gcf(verdict): keep ${name} → ${order.join(', ')}${played}`;
955
+ const hash = commitPaths(projectDir, message, files, { key: 'verdict:keep', items: order });
956
+
957
+ return { milestone: name, ids: order, hash };
958
+ } catch (e) {
959
+ // Nothing kept: what the keep wrote back to HEAD (staged or not); the pack's own files keep
960
+ // the operator's edits on disk and in the index as they were.
961
+ const mine = changedIn(projectDir)
962
+ .map((c) => c.file)
963
+ .filter((f) => !own.has(f));
964
+ if (mine.length) spawnSync('git', ['reset', '-q', '--', ...mine], { cwd: projectDir });
965
+ for (const c of changedIn(projectDir)) {
966
+ if (own.has(c.file)) continue;
967
+ if (c.untracked) rmSync(path.join(projectDir, c.file), { force: true });
968
+ else spawnSync('git', ['checkout', 'HEAD', '--', c.file], { cwd: projectDir });
969
+ }
970
+
971
+ for (const [file, text] of saved) writeFileSync(file, text);
972
+ if (index) restoreIndex(index);
973
+ throw new Error(`keep --milestone ${name}: nothing kept — ${e.message}`, { cause: e });
974
+ }
975
+ }
976
+
721
977
  /** decide kill: the live children go down with the feature, without removal items of their own. */
722
978
  function killFeature(m, { reason, remove }) {
723
979
  const { item, ledger } = m;
@@ -788,7 +1044,15 @@ async function decideItemUnlocked(projectDir, id, choice, opts = {}) {
788
1044
  const m = await begin(projectDir, id, `decide:${choice}`);
789
1045
  fitDecision(choice, m.item);
790
1046
  const removal = DECIDE[choice](m, { reason, remove }) ?? null;
791
- const hash = await finish(m, `decide:${choice}`, `${choice} ${id}`, commit);
1047
+ assumeInto(m, opts.assume);
1048
+ // The reason in the commit's body: a go keeps it nowhere else.
1049
+ const why = String(reason).trim();
1050
+ const hash = await finish(
1051
+ m,
1052
+ `decide:${choice}`,
1053
+ `${choice} ${id}${why ? `\n\n${why}` : ''}`,
1054
+ commit,
1055
+ );
792
1056
 
793
1057
  return { id, choice, hash, removal };
794
1058
  }
@@ -803,6 +1067,7 @@ async function blockItemUnlocked(projectDir, id, opts = {}) {
803
1067
  const m = await begin(projectDir, id, 'block');
804
1068
  const data = { ...m.item.data, status: 'blocked', blocked: why, since: headHash(projectDir) };
805
1069
  m.step(() => writeItem(m.item, data));
1070
+ if (opts.dropOutcome) dropOutcomeOf(m);
806
1071
 
807
1072
  return { id, hash: await finish(m, 'block', id, commit) };
808
1073
  }
@@ -1161,6 +1426,35 @@ async function setRunModeUnlocked(projectDir, id, { run, commit = true } = {}) {
1161
1426
  return { ...result, hash };
1162
1427
  }
1163
1428
 
1429
+ const SKIP_GATES = { skip: true, wait: false, project: undefined };
1430
+
1431
+ /**
1432
+ * The operator's choice of an item's gates (docs/Autonomy-Plan.md, B): `skip` puts its verdict,
1433
+ * decision and question gates on their second value, `wait` holds them, `project` takes the
1434
+ * field off and the project's `gates:` hold. Commit `gcf(item)`, key `gates`.
1435
+ */
1436
+ async function setGatesUnlocked(projectDir, id, { gates, commit = true } = {}) {
1437
+ if (!(gates in SKIP_GATES)) throw new Error(`gates is ${Object.keys(SKIP_GATES).join(' | ')}`);
1438
+ const ledger = await buildLedger(projectDir);
1439
+ const item = ledger.item(id);
1440
+ if (!item) throw new Error(`${id} is not a work item`);
1441
+ refuseRunning(projectDir, id);
1442
+ const data = without(item.data, 'skip_gates');
1443
+ if (SKIP_GATES[gates] !== undefined) data.skip_gates = SKIP_GATES[gates];
1444
+ const result = { id, skip_gates: data.skip_gates ?? null };
1445
+ if (data.skip_gates === item.data.skip_gates) return { ...result, hash: null };
1446
+ const hash = await commitMove(projectDir, `gcf(item): ${id} gates ${gates}`, {
1447
+ files: [item.file],
1448
+ inputs: [item.file],
1449
+ mutate: () => atomicWrite(item.file, serialize(data, item.body)),
1450
+ commit,
1451
+ key: 'gates',
1452
+ items: [id],
1453
+ });
1454
+
1455
+ return { ...result, hash };
1456
+ }
1457
+
1164
1458
  // An attachment is a picture or a file the operator gave the item (a chat image, a reference).
1165
1459
  const ATTACH_MAX = 10 * 1024 * 1024;
1166
1460
 
@@ -1203,6 +1497,9 @@ function lstatOr(file) {
1203
1497
  }
1204
1498
  }
1205
1499
 
1500
+ /** @type {typeof setGatesUnlocked} */
1501
+ export const setGates = (projectDir, id, opts = {}) =>
1502
+ locked(projectDir, opts.commit ?? true, () => setGatesUnlocked(projectDir, id, opts));
1206
1503
  /** @type {typeof attachItemUnlocked} */
1207
1504
  export const attachItem = (projectDir, id, file, opts = {}) =>
1208
1505
  locked(projectDir, opts.commit ?? true, () => attachItemUnlocked(projectDir, id, file, opts));
@@ -1244,12 +1541,19 @@ async function newItemUnlocked(projectDir, given) {
1244
1541
  ? given
1245
1542
  : { ...given, id: deriveId(await titleForId(root, given), ledger.known, given.type) };
1246
1543
  const gate = checkNew(ledger, spec);
1247
- const milestones = spec.milestone ? await gameMilestones(root) : null;
1248
- if (milestones && !milestones.some((m) => m.name === spec.milestone))
1544
+ const feature = spec.type === 'feature';
1545
+ const milestones = spec.milestone || feature ? await gameMilestones(root) : null;
1546
+ if (spec.milestone && milestones && !milestones.some((m) => m.name === spec.milestone))
1249
1547
  throw new Error(
1250
1548
  `--milestone ${spec.milestone} is not a milestone of game.md: ` +
1251
1549
  (milestones.map((m) => m.name).join(', ') || 'it lists none'),
1252
1550
  );
1551
+ // A feature is played with its milestone (docs/Autonomy-Plan.md, C), its children with it.
1552
+ if (feature && !spec.milestone && milestones?.length)
1553
+ throw new Error(
1554
+ `a feature is played with its milestone: --milestone ` +
1555
+ `<${milestones.map((m) => m.name).join(' | ')}>`,
1556
+ );
1253
1557
  if (spec.proposal !== undefined && !/^[\w-]+\/[\w-]+$/.test(spec.proposal))
1254
1558
  throw new Error(`--proposal is <thread>/<proposal id>, not ${spec.proposal}`);
1255
1559
  if (spec.dryRun) return { id: spec.id, item: `gcf/work/${spec.id}.md`, hash: null };
@@ -1340,6 +1644,9 @@ export const closeItem = (projectDir, id, opts = {}) =>
1340
1644
  /** @type {typeof verdictItemUnlocked} */
1341
1645
  export const verdictItem = (projectDir, id, verdict, opts = {}) =>
1342
1646
  locked(projectDir, opts.commit ?? true, () => verdictItemUnlocked(projectDir, id, verdict, opts));
1647
+ /** @type {typeof keepMilestoneUnlocked} */
1648
+ export const keepMilestone = (projectDir, name, opts = {}) =>
1649
+ locked(projectDir, opts.commit ?? true, () => keepMilestoneUnlocked(projectDir, name, opts));
1343
1650
  /** @type {typeof decideItemUnlocked} */
1344
1651
  export const decideItem = (projectDir, id, choice, opts = {}) =>
1345
1652
  locked(projectDir, opts.commit ?? true, () => decideItemUnlocked(projectDir, id, choice, opts));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gcf-aif-ext",
3
- "version": "0.18.8",
3
+ "version": "0.19.1",
4
4
  "description": "Game Context Framework for AI Factory",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/profiles/game.md CHANGED
@@ -51,8 +51,8 @@ sections:
51
51
  form: record-list
52
52
  required: yes
53
53
  record_keys: name, goal
54
- optional_record_keys: content
55
- note: the closed vocabulary of a unit's and a work item's milestone field; content is a volume written as a comparison
54
+ optional_record_keys: content, play
55
+ note: the closed vocabulary of a unit's and a work item's milestone field, in build order; each is the smallest slice of the game that can be played; play is the question its play answers; content is a volume written as a comparison
56
56
 
57
57
  - key: provenance
58
58
  form: record-list
@@ -59,6 +59,9 @@
59
59
  "anyOf": [{ "type": "null" }, { "enum": ["critical", "high", "medium", "low"] }]
60
60
  },
61
61
  "blocked": { "$ref": "#/definitions/textOrNull" },
62
+ "skip_gates": { "type": "boolean" },
63
+ "gate_why": { "$ref": "#/definitions/textOrNull" },
64
+ "play_on": { "type": "array", "items": { "type": "string", "pattern": "\\S" } },
62
65
  "since": {
63
66
  "anyOf": [{ "type": "null" }, { "type": "string", "pattern": "^[0-9a-f]{7,64}$" }]
64
67
  },
@@ -11,6 +11,7 @@ purpose:
11
11
 
12
12
  inputs:
13
13
  - an id from `gcf/backlog.md`, several ids to group under a feature, a free-text idea, or a request for non-design work
14
+ - `--assume` when `ai-factory gcf-harness card` started this session for an autopilot: nobody answers a question here
14
15
 
15
16
  preconditions:
16
17
  - `gcf/` exists; `gcf/INDEX.md` lists the current subsystems and items
@@ -18,6 +19,9 @@ preconditions:
18
19
  forbidden_behaviors:
19
20
  - do not invent a new subsystem name when INDEX carries a synonym: reuse or ask
20
21
  - do not answer a `TBD` yourself: ask the human, and offer your draft as the proposed answer
22
+ - under `--assume` ask nothing: a choice you can take back (the route, the gate, `contract:`, the cut, the order) is yours, and you write why
23
+ - under `--assume`, what only the human can answer becomes a D1: `ai-factory gcf question add --class D1 --question "<q>" --proposed "<a>" --blocks <unit>`
24
+ - under `--assume`, a unit a D1 holds stays in design, and you go on with the next unit
21
25
  - do not take a unit an open D1 blocks: `ai-factory gcf design check` names the blocking question, and the human answers it first (`ai-factory gcf question answer <q-id> --text="<answer>"`, or on the board)
22
26
  - do not write a digit in prose: a number is an envelope `a..b <unit>` in `feel` or a closing comparison
23
27
  - do not put `until:` in the frontmatter: it is a line annotation inside slots
@@ -31,10 +35,12 @@ outputs:
31
35
  - each answered slot gets a provenance record `- slot: <block>` with `answer: manual`, or `answer: q-NNN` when it closes a question
32
36
  - a design-unit item body carries every block of its type; a mechanic or resource item adds `contract:` (paths and entry points) and `interactions:` (`<other id>: how the two cross`, or `- none: <why>`)
33
37
  - every item carries a `live:` delta before it ends: what it adds, modifies or removes in `gcf/LIVE.md`, or `none: <why>`
38
+ - a mechanic or resource with a milestone carries `gate: auto`: it closes unplayed, and the human plays it with its milestone
39
+ - `gate: verdict` on such an item carries `gate_why:`: the rest is built on its feel - input, controls, camera, the core verb
34
40
 
35
41
  workflow:
36
42
  1. for a free-text design idea: ask "into work now, or park it?"; `ai-factory gcf design save --kind unit --system <s> --type <t> --title "<title>" --fields-file -`, `{}` on stdin, writes it with `TBD` slots and prints its id; on "park" stop here
37
- 2. for non-design work: pick the type - tech, bug, spike, asset, content, perf, release - among those `ai-factory gcf phase` says the phase takes, and propose the gate its type gives; the human may flip it (`--gate auto` is "no playtest")
43
+ 2. for non-design work: pick the type - tech, bug, spike, asset, content, perf, release - among those `ai-factory gcf phase` says the phase takes, and propose the gate its type gives; the human may flip it
38
44
  3. a bug needs `--severity <level>` and a `repro:` the human confirms; a release needs `--release <version> --channel <name>` from the human; those flags go on the `item new` of step 4
39
45
  4. run `ai-factory gcf item new --title "<line>" --type <type> [--gate <gate>] [--parent <feature>]`, `--from <in-id>` from the inbox, `--blocked "file needed"` for an asset; it prints the id first; write `intent:`, a bug's `repro:` and `live:`; stop
40
46
  5. for a design unit: run `ai-factory gcf where <id>`; the id must be a single unit of `gcf/design/`; read its section from the file the command names
@@ -47,8 +53,8 @@ workflow:
47
53
  12. write each answer into the unit in place, with its `answer:` provenance record
48
54
  13. a record of `gcf/open-questions.md` with the human's `answer:` that names this unit in `blocks:` goes into the slot of every unit it blocks, each with `answer: q-NNN`; it leaves the file after the last of them has it
49
55
  14. run `ai-factory gcf design check --json` until the unit's entry in `units` reads `ready: true`, then commit the answered unit
50
- 15. run `ai-factory gcf take <id>` for one unit, or `ai-factory gcf take <id> <id> --feature <feature-id>` to group several under a feature; it writes `gcf/work/<id>.md` and removes the sections and backlog lines in one step
51
- 16. in each mechanic or resource item write `contract:` from the code tree and `interactions:` from the units and items that write the same state; a soft unit whose human wants no playtest gets `gate: auto` - it will close as unplayed
56
+ 15. run `ai-factory gcf take <id>`, or `take <id> <id> --feature <feature-id>` to group units; a unit without its milestone takes `--milestone <name>` from `gcf/game.md`; it writes `gcf/work/<id>.md`
57
+ 16. in each mechanic or resource item write `contract:` from the code tree and `interactions:` from the units and items that write the same state
52
58
  17. write the item's `live:` delta (a feature's children keep `none: parent`; the feature writes the capability), run `ai-factory gcf design check`, and commit
53
59
  18. when the work is several items (a feature's children, or a batch), cut them along subsystem boundaries: each a thin slice that builds and tests alone
54
60
  19. two items of one subsystem that change different files get `parallel: ok`, and their `contract:` or `intent:` names those files
@@ -10,6 +10,7 @@ purpose:
10
10
 
11
11
  inputs:
12
12
  - an item id and a verdict word (keep, tune, kill) or a decision word (go, no, wontfix, known, close, continue, kill); or nothing, which means "print the playtest list"
13
+ - a milestone name and keep: every item of it that waits for play, in one commit
13
14
 
14
15
  preconditions:
15
16
  - a verdict: the item is `awaiting-verdict` or `unplayed`, and the human has played the build
@@ -18,20 +19,22 @@ preconditions:
18
19
  forbidden_behaviors:
19
20
  - do not decide the verdict or the decision: the human decides, this skill records
20
21
  - do not run `keep` when the human has not answered the item's miss_criterion question
22
+ - do not hold a keep for a play condition: the human decides where to play; remind once of a line of `platforms` not played, then take the answer
21
23
  - do not edit systems docs, `LIVE.md`, history or graveyard by hand: the commands own them
22
24
  - a tune note triage left in the inbox for the item goes into `--note`; after the verdict run `ai-factory gcf inbox drop <in-id>`, not before
23
25
 
24
26
  workflow:
25
- 1. with no arguments: run `ai-factory gcf playtest session` and stop - its build line and checklist of awaiting-verdict and unplayed items are the session's playtest sheet
27
+ 1. with no arguments: run `ai-factory gcf playtest session` and stop - its sheet goes milestone by milestone, the `play:` question first
26
28
  2. read the item; for a verdict ask the human the miss_criterion question and record the answer in one line
27
29
  3. for `tune` at the tune limit (`tune_limit` in `gcf/config.yml`, 3 by default): the command refuses; the way out is a kill, and a redesigned envelope becomes a new item with `reopens: <id>`
28
30
  4. for `keep` of a design-unit item still awaiting its verdict: compress it first - the collapse copies lines verbatim, 1 line per behavior record, refusal and boundary
29
31
  5. for that keep: strip `contract:` down to paths and entry points and cut `intent:` to the line the subsystem's purpose still lacks; leave an unplayed item as it is - its close froze the body
30
- 6. run `ai-factory gcf verdict <id> <verdict> --note "<answer or reason>"`; a kill creates the removal item for code already in main unless the human says `--no-remove`
32
+ 6. run `ai-factory gcf verdict <id> <verdict> --note "<answer>"`, with `--played-on "<line>"` per line of `platforms` the human played on; a kill makes a removal item for code in main unless `--no-remove`
31
33
  7. for a decision run `ai-factory gcf decide <id> <choice> --reason "<why>"`; `known` parks a bug and lists it in `gcf/LIVE.md` known issues
32
34
  8. for a feature whose child died, the human picks: `close` without the child, `continue` with a replacement, or `kill` with its live children
33
35
  9. for `keep` on an item touching 2 or more subsystems: read each updated systems doc and report a contradiction between constraints as a D1 question instead of finishing silently
34
36
  10. report the commit hash, `git revert <hash>` undoes that one move - not the code, nor a later move or edit on the same files - and the id of any removal item the command made
37
+ 11. a whole milestone: compress its awaiting-verdict units as in steps 4-5, then run `ai-factory gcf verdict <milestone> keep --milestone`
35
38
 
36
39
  invocation:
37
40
  - run after a playtest session, on a human decision, or with no arguments to print the playtest sheet
@@ -23,6 +23,10 @@ forbidden_behaviors:
23
23
 
24
24
  outputs:
25
25
  - `gcf/game.md` in the form of `templates/game.md`: logline, platforms, audience, references, scope in and out, milestones
26
+ - a milestone is the smallest slice of the game the human can play, in build order; its `play:` is the question that play answers
27
+ - a release is no milestone: it is a `release` item of the milestone it ships
28
+ - `platforms` holds one line per way to play: a platform and its input, "PC, mouse"; the human picks where to play, the lines are hints
29
+ - each unit carries the milestone the human plays it with; `TBD` only while `gcf/game.md` has no milestones
26
30
  - one `gcf/design/<system>.md` per subsystem, opening with `# <system>` and `purpose:`, with one `## <id>` unit per mechanic, resource or rule the human named, `source: manual`, every unknown slot `TBD`
27
31
  - `gcf/backlog.md` with one `- <id>` line per unit, in the order the human ranks them
28
32
 
@@ -27,6 +27,10 @@ gcf_work:
27
27
  - a release item carries `version:` and `channel:` (`item new --title "<title>" --type release --release <v> --channel <c>`): its end writes the `release:` block of `gcf/LIVE.md`
28
28
  - `item new` and `take` refuse a type the current phase does not take: run `ai-factory gcf phase` and bring the refusal to the human
29
29
  - an item's milestone (`item new --milestone <name>`) is a `name` of the `milestones` in `gcf/game.md`, as a unit's: `item new` refuses another; a new milestone is a change of the vision, for the human (the gcf-vision skill)
30
+ - a milestone is a slice of the game the human plays as one, in `gcf/game.md`'s order; a mechanic or resource with one gets `gate: auto`, closes unplayed and is played with it; a feature and a taken soft unit need one while `gcf/game.md` lists them (`take --milestone <name>`)
31
+ - the lines of `platforms` in `gcf/game.md` are where the game can be played; an item may narrow them in `play_on:`; they are a hint for the human, never a condition of a move
32
+ - the stops that wait for the human are the `gates:` of `gcf/config.yml` (`milestone`, `verdict`, `decision`, `question`) and each card's `skip_gates:`, both the human's (`config set`, `item gates`); the core applies them itself
33
+ - the board's autopilot starts the runs and the card sessions (`ai-factory gcf-harness card`) by itself and stops when a milestone is built for the human to play; an agent starts neither
30
34
  - an item the human wants run on a given model or effort gets `item new --title "<title>" --model <m> --effort <e>`: the harness run passes both to the agent; an existing item changes with `ai-factory gcf item agent <id> --model <m> --effort <e>` (`default` takes one off), never a hand edit; its next run takes them; an item without its own runs on the project's `agent.model` and `agent.effort` of `gcf/config.yml`, a setting of the human, and without those on opus, effort high
31
35
  - where an item's runs go, the project folder or a worktree, is the human's choice: `ai-factory gcf item mode <id> --run main|worktree|default` over the project's `run_mode`, never a hand edit; set it only when the human asks
32
36
  - before starting a run, `ai-factory gcf-harness gate --each <ids...> --json` says what the run gate refuses each item alone for now (it exits 0; a batch is still gated as a whole by `gate <ids...>`, exit 1); a session stops after `session_timeout_min` of `gcf/config.yml`, its item stays ready
@@ -47,7 +51,8 @@ gcf_work:
47
51
 
48
52
  gcf_forbidden:
49
53
  - do not edit `status:`, `frozen:`, `gcf/LIVE.md`, `gcf/history.md`, `gcf/graveyard.md`, `gcf/inbox/` or `gcf/INDEX.md` by hand: the commands own them
50
- - do not give a verdict or a decision: `verdict` and `decide` belong to the human, through the gcf-verdict skill
54
+ - do not give a verdict: `verdict` belongs to the human, through the gcf-verdict skill; nor a decision, but `go` or `no` of the spike you drive when the gates say `decision: agent`
55
+ - the core refuses the human's moves to a harness run and a board chat (`verdict`, `decide`, `drop` of a work item, `unblock`, `question answer`, `config set`, `permissions`, `phase next`, `pillar`, `hooks-install`): bring the move to the human, or block the item with the question
51
56
  - do not answer a `TBD` of a design unit yourself: ask the human and offer your draft as the proposed answer
52
57
  - do not run `ai-factory gcf phase next`: the phase moves on the human's word only
53
58
  - do not change what agent runs may do: `ai-factory gcf permissions` and its deny groups belong to the human