gcf-aif-ext 0.18.9 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/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,17 @@ 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 {
47
+ commitPaths,
48
+ dirtyGcf,
49
+ dirtyRefusal,
50
+ GATE_SCOPE,
51
+ operationInProgress,
52
+ restoreIndex,
53
+ snapshotIndex,
54
+ } from './git.js';
55
+ import { verdictDeferred } from './gates.js';
56
+ import { appendQuestions, questionsFile } from './questions.js';
46
57
 
47
58
  /**
48
59
  * Options of a committed move; each move reads the ones it needs.
@@ -53,6 +64,9 @@ import { planTicks } from './plan-check.js';
53
64
  * @property {boolean} [remove] create a removal item; absent = the move's default
54
65
  * @property {string[]} [constraints]
55
66
  * @property {boolean} [commit]
67
+ * @property {string[]} [assume] the agent's assumptions: D2 records in the move's commit
68
+ * @property {boolean} [dropOutcome] the integrator's: the plan's `## Outcome` leaves in the commit
69
+ * @property {string} [said] the agent's word for the human, into the commit's subject
56
70
  */
57
71
 
58
72
  const SOFT = ['mechanic', 'resource'];
@@ -293,7 +307,9 @@ function needTicked(m, opts) {
293
307
  /** The commit's tail of a move made without a green verify, or with tasks left unticked. */
294
308
  const unverifiedTail = (opts) =>
295
309
  (opts.unverified ? ` (unverified: ${opts.unverified})` : '') +
296
- (opts.unticked ? ` (unticked: ${opts.unticked})` : '');
310
+ (opts.unticked ? ` (unticked: ${opts.unticked})` : '') +
311
+ // What the agent said for the human in its plan's Outcome, when the gates did not let it act.
312
+ (opts.said ? ` (${opts.said})` : '');
297
313
 
298
314
  const writeItem = (item, data, body = item.body) => atomicWrite(item.file, serialize(data, body));
299
315
  /**
@@ -390,6 +406,36 @@ function archivePlan(m, item) {
390
406
  return destRel;
391
407
  }
392
408
 
409
+ /** A plan's text without its `## Outcome` block (to the next heading of level 1 or 2). */
410
+ export function withoutOutcome(text) {
411
+ const lines = String(text).split(/(?<=\n)/);
412
+ const at = lines.findIndex((l) => /^## Outcome[ \t]*\r?\n?$/.test(l));
413
+ if (at < 0) return text;
414
+ const rest = lines.slice(at + 1).findIndex((l) => /^#{1,2} /.test(l));
415
+ const end = rest < 0 ? lines.length : at + 1 + rest;
416
+
417
+ return lines.slice(0, at).join('') + lines.slice(end).join('');
418
+ }
419
+
420
+ /**
421
+ * The integrator's move takes the plan's `## Outcome` out in its own commit (`dropOutcome`): a
422
+ * later run of the item, after a tune, must not record its assumptions again. A plan the move
423
+ * archives keeps it there, read by nobody.
424
+ */
425
+ function dropOutcomeOf(m) {
426
+ const rel = m.item.data.plan ?? `.ai-factory/plans/${m.item.data.id}.md`;
427
+ const file = resolveInside(m.projectDir, rel);
428
+ if (!existsSync(file)) return;
429
+ m.touch(file);
430
+ m.step(async () => {
431
+ // Archived meanwhile by this move: nothing left here.
432
+ if (!existsSync(file)) return;
433
+ const text = await readFile(file, 'utf8');
434
+ const out = withoutOutcome(text);
435
+ if (out !== text) await atomicWrite(file, out);
436
+ });
437
+ }
438
+
393
439
  /** A delta whose changes name no refs points at where the item's detail now lives. */
394
440
  function withRefs(delta, refs) {
395
441
  if (!delta || 'none' in delta || !refs) return delta;
@@ -550,7 +596,58 @@ function refuseOpenDepends(m, move, opts = {}) {
550
596
  );
551
597
  }
552
598
 
553
- /** ready → awaiting-verdict / awaiting-decision; `since` marks where the wait began.
599
+ /**
600
+ * The agent's assumptions a move carries (`assume`, docs/Autonomy-Plan.md B): D2 records of
601
+ * gcf/open-questions.md in the move's own commit. A line `<question> = <value>` splits there.
602
+ * @param {string[]} [lines]
603
+ */
604
+ function assumeInto(m, lines = []) {
605
+ if (!lines.length) return;
606
+ const id = String(m.item.data.id);
607
+ const records = lines.map((line) => {
608
+ const at = line.indexOf(' = ');
609
+
610
+ return {
611
+ class: 'D2',
612
+ question: at > 0 ? line.slice(0, at) : line,
613
+ assumed: at > 0 ? line.slice(at + 3) : line,
614
+ sys: (m.item.data.system ?? []).join(', '),
615
+ until: SOFT.includes(m.item.data.type) ? `verdict(${id})` : null,
616
+ lens: id,
617
+ };
618
+ });
619
+ m.touch(questionsFile(m.root));
620
+ m.step(() => appendQuestions(m.root, records));
621
+ }
622
+
623
+ /**
624
+ * A4: the capabilities a soft unit's delta modifies or removes. Such a unit cannot close
625
+ * unplayed — a tune or a kill could not take its change back out — so it waits for a verdict.
626
+ */
627
+ const playChanges = (item) =>
628
+ SOFT.includes(item.data.type)
629
+ ? (item.data.live?.changes ?? []).filter((c) => c.change !== 'added').map((c) => c.id)
630
+ : [];
631
+
632
+ /**
633
+ * A4 in one write: gate verdict, awaiting-verdict, and why (`gate_why`) — status alone would
634
+ * break "awaiting-verdict needs gate: verdict".
635
+ */
636
+ function awaitVerdict(m, why = null) {
637
+ const data = {
638
+ ...without(m.item.data, 'blocked'),
639
+ gate: 'verdict',
640
+ status: 'awaiting-verdict',
641
+ ...(why ? { gate_why: why } : {}),
642
+ since: headHash(m.projectDir),
643
+ };
644
+ m.step(() => writeItem(m.item, data));
645
+ }
646
+
647
+ /**
648
+ * ready → awaiting-verdict / awaiting-decision; `since` marks where the wait began. A soft unit
649
+ * under `gates.verdict: defer` closes unplayed instead (played with its milestone), unless its
650
+ * delta changes a capability (A4): then it waits, with the reason.
554
651
  * @param {MoveOpts} [opts]
555
652
  */
556
653
  async function submitItemUnlocked(projectDir, id, opts = {}) {
@@ -558,25 +655,43 @@ async function submitItemUnlocked(projectDir, id, opts = {}) {
558
655
  const m = await begin(projectDir, id, 'submit');
559
656
  if (m.item.data.gate === 'auto')
560
657
  throw new Error(`${id} has gate auto: nobody waits for it — close it with gcf close ${id}`);
561
- refuseOpenDepends(m, 'submit', { waiting: true });
658
+ // Whether the gates defer it, its delta aside: a changed capability (A4) then says why it waits.
659
+ const deferred = verdictDeferred(await readConfig(m.root), { ...m.item.data, live: null });
660
+ const changes = playChanges(m.item);
661
+ // Unplayed needs its dependencies played, as a close does: not one still waiting (§4.1).
662
+ refuseOpenDepends(m, 'submit', { waiting: !deferred || changes.length > 0 });
562
663
  needTicked(m, opts);
563
664
  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));
665
+ assumeInto(m, opts.assume);
666
+ if (opts.dropOutcome) dropOutcomeOf(m);
667
+ if (deferred && !changes.length) {
668
+ closeUnplayed(m);
669
+ const tail = `${id} → unplayed (deferred)${unverifiedTail(opts)}`;
670
+
671
+ return {
672
+ id,
673
+ status: 'unplayed',
674
+ deferred: true,
675
+ hash: await finish(m, 'submit', tail, commit),
676
+ };
677
+ }
567
678
 
568
- return { id, status, hash: await finish(m, 'submit', `${id}${unverifiedTail(opts)}`, commit) };
569
- }
679
+ const verdict = m.item.data.gate === 'verdict';
680
+ const why = deferred ? `modifies ${changes.join(', ')}` : null;
681
+ if (verdict) awaitVerdict(m, why);
682
+ else {
683
+ const data = {
684
+ ...without(m.item.data, 'blocked'),
685
+ status: 'awaiting-decision',
686
+ since: headHash(projectDir),
687
+ };
688
+ m.step(() => writeItem(m.item, data));
689
+ }
570
690
 
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;
691
+ const status = verdict ? 'awaiting-verdict' : 'awaiting-decision';
692
+ const tail = `${id}${why ? ` → ${status} (${why})` : ''}${unverifiedTail(opts)}`;
575
693
 
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
- );
694
+ return { id, status, hash: await finish(m, 'submit', tail, commit) };
580
695
  }
581
696
 
582
697
  /**
@@ -587,8 +702,6 @@ export function unplayedCloseProblem(item) {
587
702
  function closeUnplayed(m) {
588
703
  const { item } = m;
589
704
  const id = String(item.data.id);
590
- const refused = unplayedCloseProblem(item);
591
- if (refused) throw new Error(refused);
592
705
  const systems = item.data.system ?? [];
593
706
  m.touch(...systemFiles(m.root, systems));
594
707
  m.step(async () => {
@@ -631,17 +744,30 @@ async function closeItemUnlocked(projectDir, id, opts = {}) {
631
744
  const { constraints = [], commit = true } = opts;
632
745
  const m = await begin(projectDir, id, 'close');
633
746
  const unplayed = SOFT.includes(m.item.data.type);
747
+ const changes = m.item.data.gate === 'auto' ? playChanges(m.item) : [];
634
748
  if (m.item.data.type === 'feature') closeFeature(m);
635
749
  else {
636
750
  if (m.item.data.gate !== 'auto')
637
751
  throw new Error(`${id} has gate ${m.item.data.gate}: submit it, the operator closes it`);
638
- refuseOpenDepends(m, 'close');
752
+ // A4: it will wait for a verdict, so a dependency waiting for its own is no bar.
753
+ refuseOpenDepends(m, 'close', { waiting: changes.length > 0 });
639
754
  needTicked(m, opts);
640
755
  needVerified(m, opts);
641
- if (unplayed) closeUnplayed(m);
756
+ if (changes.length) awaitVerdict(m, `modifies ${changes.join(', ')}`);
757
+ else if (unplayed) closeUnplayed(m);
642
758
  else await closeEnding(m, constraints);
643
759
  }
644
760
 
761
+ assumeInto(m, opts.assume);
762
+ if (opts.dropOutcome) dropOutcomeOf(m);
763
+ if (changes.length) {
764
+ // The item waits now: the move is a submit's, as the integrator and the history read it.
765
+ const why = `modifies ${changes.join(', ')}`;
766
+ const tail = `${id} → awaiting-verdict (${why})${unverifiedTail(opts)}`;
767
+
768
+ return { id, hash: await finish(m, 'submit', tail, commit), unplayed: false, awaits: why };
769
+ }
770
+
645
771
  const tail = `${id}${unplayed ? ' → unplayed' : ''}${unverifiedTail(opts)}`;
646
772
  const hash = await finish(m, 'close', tail, commit);
647
773
 
@@ -712,12 +838,155 @@ async function verdictItemUnlocked(projectDir, id, verdict, opts = {}) {
712
838
  if (verdict === 'keep') await keep(m, constraints);
713
839
  else if (verdict === 'tune') await tune(m, note);
714
840
  else removal = endToGraveyard(m, m.item, { reason: note, tags, removal: remove ?? true });
715
- const tail = `${verdict} ${id} → ${systems.join(',')}`;
841
+ // Where the operator played it: a note for the history, never a condition (Plan, C).
842
+ const played = opts.playedOn?.length ? ` (played on: ${opts.playedOn.join('; ')})` : '';
843
+ const tail = `${verdict} ${id} → ${systems.join(',')}${played}`;
716
844
  const hash = await finish(m, `verdict:${verdict}`, tail, commit);
717
845
 
718
846
  return { verdict, id, systems, hash, removal };
719
847
  }
720
848
 
849
+ // What a milestone's keep may write: gcf/ as the gate reads it (no .metrics, which audit and
850
+ // context append to on every run) and the plans its items archive.
851
+ const KEEP_SCOPE = [...GATE_SCOPE, '.ai-factory/plans', '.ai-factory/archive'];
852
+
853
+ /** The paths under KEEP_SCOPE git sees changed or new, relative to the project. */
854
+ function changedIn(projectDir) {
855
+ const res = spawnSync(
856
+ 'git',
857
+ ['-c', 'core.quotePath=false', 'status', '--porcelain', '-uall', '--', ...KEEP_SCOPE],
858
+ { cwd: projectDir, encoding: 'utf8' },
859
+ );
860
+ if (res.status !== 0) throw new Error(`git status failed: ${res.stderr.trim()}`);
861
+ // Porcelain paths are the repository's: a project inside a bigger repository is a prefix in.
862
+ const prefix = spawnSync('git', ['rev-parse', '--show-prefix'], {
863
+ cwd: projectDir,
864
+ encoding: 'utf8',
865
+ }).stdout.trim();
866
+
867
+ return res.stdout
868
+ .split('\n')
869
+ .filter(Boolean)
870
+ .map((l) => {
871
+ const file = l.slice(3).replace(/^.* -> /, '');
872
+
873
+ return {
874
+ untracked: l.startsWith('??'),
875
+ file: prefix && file.startsWith(prefix) ? file.slice(prefix.length) : file,
876
+ };
877
+ });
878
+ }
879
+
880
+ /** The pack's ids in dependency order: each after every pack item it depends on. */
881
+ function keepOrder(pack) {
882
+ const ids = new Set(pack.map((i) => String(i.data.id)));
883
+ const deps = new Map(
884
+ pack.map((i) => [String(i.data.id), (i.data.depends ?? []).filter((d) => ids.has(d))]),
885
+ );
886
+ const order = [];
887
+ const state = new Map();
888
+ const visit = (id, trail) => {
889
+ if (state.get(id) === 'done') return;
890
+ if (state.get(id) === 'open')
891
+ throw new Error(`a dependency cycle inside the milestone: ${[...trail, id].join(' → ')}`);
892
+ state.set(id, 'open');
893
+ for (const d of deps.get(id)) visit(d, [...trail, id]);
894
+ state.set(id, 'done');
895
+ order.push(id);
896
+ };
897
+
898
+ for (const id of ids) visit(id, []);
899
+
900
+ return order;
901
+ }
902
+
903
+ /**
904
+ * keep of a whole milestone (docs/Autonomy-Plan.md, C): every unplayed and awaiting-verdict item
905
+ * of it, one commit, all or nothing. Every check comes before the first write: a frozen body
906
+ * edited, a dependency outside the milestone not played yet, a cycle inside it. The items
907
+ * inside keep in dependency order, each seeing the ones before it ended. gcf/ and the plans
908
+ * must be clean but for the pack's own item files (their compress edits ride along); a failure
909
+ * on the way restores them all.
910
+ * @param {MoveOpts & {playedOn?: string[]}} [opts]
911
+ */
912
+ async function keepMilestoneUnlocked(projectDir, name, opts = {}) {
913
+ const { note = '', playedOn = [], commit = true } = opts;
914
+ const root = gcfOf(projectDir);
915
+ const milestones = (await gameMilestones(root)) ?? [];
916
+ if (!milestones.some((m) => m.name === name))
917
+ throw new Error(`${name} is not a milestone of game.md`);
918
+ const ledger = await buildLedger(projectDir);
919
+ const pack = ledger.items.filter(
920
+ (i) => i.data.milestone === name && ['unplayed', 'awaiting-verdict'].includes(i.data.status),
921
+ );
922
+ if (!pack.length) throw new Error(`milestone ${name}: nothing waits for its play`);
923
+ const ids = new Set(pack.map((i) => String(i.data.id)));
924
+ for (const i of pack) {
925
+ const id = String(i.data.id);
926
+ refuseRunning(projectDir, id);
927
+ if (i.data.status === 'unplayed')
928
+ refuseEdited(i, `carry the edit in a new item with reopens: ${id}`);
929
+ const outside = openDepends(ledger, i.data.depends ?? []).filter((d) => !ids.has(d));
930
+ if (outside.length)
931
+ throw new Error(
932
+ `keep --milestone ${name}: ${id} depends on ${outside.join(', ')}, outside the ` +
933
+ 'milestone and not played yet — keep that first, or keep the items one by one',
934
+ );
935
+ }
936
+
937
+ const order = keepOrder(pack);
938
+ const own = new Set(pack.map((i) => path.relative(projectDir, i.file).replaceAll('\\', '/')));
939
+ const loose = changedIn(projectDir).filter((c) => !own.has(c.file));
940
+ if (loose.length) {
941
+ // The board's Commit clears only gcf/'s edits: a loose plan gets the words alone.
942
+ const all = dirtyGcf(projectDir, own);
943
+ throw dirtyRefusal(
944
+ loose.every((c) => all.includes(c.file)) ? all : [],
945
+ `commit or stash these first, keep --milestone ${name} would carry them: ` +
946
+ loose.map((c) => c.file).join(', '),
947
+ );
948
+ }
949
+
950
+ if (commit && onWorkBranch(projectDir))
951
+ throw new Error('keep --milestone records on main: a work/ branch records no move');
952
+ const busy = commit ? operationInProgress(projectDir) : null;
953
+ if (busy) throw new Error(`cannot keep milestone ${name} while ${busy} is in progress`);
954
+
955
+ const saved = pack.map((i) => [i.file, readFileSync(i.file)]);
956
+ // Their index as the operator left it: a staged compress edit stays staged after a rollback.
957
+ const index = snapshotIndex(
958
+ projectDir,
959
+ pack.map((i) => i.file),
960
+ );
961
+ const played = playedOn.length ? ` (played on: ${playedOn.join('; ')})` : '';
962
+ try {
963
+ for (const id of order)
964
+ await verdictItemUnlocked(projectDir, id, 'keep', { note, playedOn, commit: false });
965
+ if (!commit) return { milestone: name, ids: order, hash: null };
966
+ const files = changedIn(projectDir).map((c) => path.join(projectDir, c.file));
967
+ const message = `gcf(verdict): keep ${name} → ${order.join(', ')}${played}`;
968
+ const hash = commitPaths(projectDir, message, files, { key: 'verdict:keep', items: order });
969
+
970
+ return { milestone: name, ids: order, hash };
971
+ } catch (e) {
972
+ // Nothing kept: what the keep wrote back to HEAD (staged or not); the pack's own files keep
973
+ // the operator's edits on disk and in the index as they were.
974
+ const mine = changedIn(projectDir)
975
+ .map((c) => c.file)
976
+ .filter((f) => !own.has(f));
977
+ if (mine.length) spawnSync('git', ['reset', '-q', '--', ...mine], { cwd: projectDir });
978
+ for (const c of changedIn(projectDir)) {
979
+ if (own.has(c.file)) continue;
980
+ if (c.untracked) rmSync(path.join(projectDir, c.file), { force: true });
981
+ else spawnSync('git', ['checkout', 'HEAD', '--', c.file], { cwd: projectDir });
982
+ }
983
+
984
+ for (const [file, text] of saved) writeFileSync(file, text);
985
+ if (index) restoreIndex(index);
986
+ throw new Error(`keep --milestone ${name}: nothing kept — ${e.message}`, { cause: e });
987
+ }
988
+ }
989
+
721
990
  /** decide kill: the live children go down with the feature, without removal items of their own. */
722
991
  function killFeature(m, { reason, remove }) {
723
992
  const { item, ledger } = m;
@@ -788,7 +1057,15 @@ async function decideItemUnlocked(projectDir, id, choice, opts = {}) {
788
1057
  const m = await begin(projectDir, id, `decide:${choice}`);
789
1058
  fitDecision(choice, m.item);
790
1059
  const removal = DECIDE[choice](m, { reason, remove }) ?? null;
791
- const hash = await finish(m, `decide:${choice}`, `${choice} ${id}`, commit);
1060
+ assumeInto(m, opts.assume);
1061
+ // The reason in the commit's body: a go keeps it nowhere else.
1062
+ const why = String(reason).trim();
1063
+ const hash = await finish(
1064
+ m,
1065
+ `decide:${choice}`,
1066
+ `${choice} ${id}${why ? `\n\n${why}` : ''}`,
1067
+ commit,
1068
+ );
792
1069
 
793
1070
  return { id, choice, hash, removal };
794
1071
  }
@@ -803,6 +1080,7 @@ async function blockItemUnlocked(projectDir, id, opts = {}) {
803
1080
  const m = await begin(projectDir, id, 'block');
804
1081
  const data = { ...m.item.data, status: 'blocked', blocked: why, since: headHash(projectDir) };
805
1082
  m.step(() => writeItem(m.item, data));
1083
+ if (opts.dropOutcome) dropOutcomeOf(m);
806
1084
 
807
1085
  return { id, hash: await finish(m, 'block', id, commit) };
808
1086
  }
@@ -1161,6 +1439,35 @@ async function setRunModeUnlocked(projectDir, id, { run, commit = true } = {}) {
1161
1439
  return { ...result, hash };
1162
1440
  }
1163
1441
 
1442
+ const SKIP_GATES = { skip: true, wait: false, project: undefined };
1443
+
1444
+ /**
1445
+ * The operator's choice of an item's gates (docs/Autonomy-Plan.md, B): `skip` puts its verdict,
1446
+ * decision and question gates on their second value, `wait` holds them, `project` takes the
1447
+ * field off and the project's `gates:` hold. Commit `gcf(item)`, key `gates`.
1448
+ */
1449
+ async function setGatesUnlocked(projectDir, id, { gates, commit = true } = {}) {
1450
+ if (!(gates in SKIP_GATES)) throw new Error(`gates is ${Object.keys(SKIP_GATES).join(' | ')}`);
1451
+ const ledger = await buildLedger(projectDir);
1452
+ const item = ledger.item(id);
1453
+ if (!item) throw new Error(`${id} is not a work item`);
1454
+ refuseRunning(projectDir, id);
1455
+ const data = without(item.data, 'skip_gates');
1456
+ if (SKIP_GATES[gates] !== undefined) data.skip_gates = SKIP_GATES[gates];
1457
+ const result = { id, skip_gates: data.skip_gates ?? null };
1458
+ if (data.skip_gates === item.data.skip_gates) return { ...result, hash: null };
1459
+ const hash = await commitMove(projectDir, `gcf(item): ${id} gates ${gates}`, {
1460
+ files: [item.file],
1461
+ inputs: [item.file],
1462
+ mutate: () => atomicWrite(item.file, serialize(data, item.body)),
1463
+ commit,
1464
+ key: 'gates',
1465
+ items: [id],
1466
+ });
1467
+
1468
+ return { ...result, hash };
1469
+ }
1470
+
1164
1471
  // An attachment is a picture or a file the operator gave the item (a chat image, a reference).
1165
1472
  const ATTACH_MAX = 10 * 1024 * 1024;
1166
1473
 
@@ -1203,6 +1510,9 @@ function lstatOr(file) {
1203
1510
  }
1204
1511
  }
1205
1512
 
1513
+ /** @type {typeof setGatesUnlocked} */
1514
+ export const setGates = (projectDir, id, opts = {}) =>
1515
+ locked(projectDir, opts.commit ?? true, () => setGatesUnlocked(projectDir, id, opts));
1206
1516
  /** @type {typeof attachItemUnlocked} */
1207
1517
  export const attachItem = (projectDir, id, file, opts = {}) =>
1208
1518
  locked(projectDir, opts.commit ?? true, () => attachItemUnlocked(projectDir, id, file, opts));
@@ -1244,12 +1554,19 @@ async function newItemUnlocked(projectDir, given) {
1244
1554
  ? given
1245
1555
  : { ...given, id: deriveId(await titleForId(root, given), ledger.known, given.type) };
1246
1556
  const gate = checkNew(ledger, spec);
1247
- const milestones = spec.milestone ? await gameMilestones(root) : null;
1248
- if (milestones && !milestones.some((m) => m.name === spec.milestone))
1557
+ const feature = spec.type === 'feature';
1558
+ const milestones = spec.milestone || feature ? await gameMilestones(root) : null;
1559
+ if (spec.milestone && milestones && !milestones.some((m) => m.name === spec.milestone))
1249
1560
  throw new Error(
1250
1561
  `--milestone ${spec.milestone} is not a milestone of game.md: ` +
1251
1562
  (milestones.map((m) => m.name).join(', ') || 'it lists none'),
1252
1563
  );
1564
+ // A feature is played with its milestone (docs/Autonomy-Plan.md, C), its children with it.
1565
+ if (feature && !spec.milestone && milestones?.length)
1566
+ throw new Error(
1567
+ `a feature is played with its milestone: --milestone ` +
1568
+ `<${milestones.map((m) => m.name).join(' | ')}>`,
1569
+ );
1253
1570
  if (spec.proposal !== undefined && !/^[\w-]+\/[\w-]+$/.test(spec.proposal))
1254
1571
  throw new Error(`--proposal is <thread>/<proposal id>, not ${spec.proposal}`);
1255
1572
  if (spec.dryRun) return { id: spec.id, item: `gcf/work/${spec.id}.md`, hash: null };
@@ -1340,6 +1657,9 @@ export const closeItem = (projectDir, id, opts = {}) =>
1340
1657
  /** @type {typeof verdictItemUnlocked} */
1341
1658
  export const verdictItem = (projectDir, id, verdict, opts = {}) =>
1342
1659
  locked(projectDir, opts.commit ?? true, () => verdictItemUnlocked(projectDir, id, verdict, opts));
1660
+ /** @type {typeof keepMilestoneUnlocked} */
1661
+ export const keepMilestone = (projectDir, name, opts = {}) =>
1662
+ locked(projectDir, opts.commit ?? true, () => keepMilestoneUnlocked(projectDir, name, opts));
1343
1663
  /** @type {typeof decideItemUnlocked} */
1344
1664
  export const decideItem = (projectDir, id, choice, opts = {}) =>
1345
1665
  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.9",
3
+ "version": "0.20.0",
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
@@ -8,7 +8,7 @@ mode: human gate
8
8
  purpose:
9
9
  - answer the human's questions about the game, its design, its work items and its runs from what `gcf/` and the run files say
10
10
  - turn a bug, an idea or a task the talk finds into a proposed work item the human accepts with one click
11
- - propose a move on an item or an inbox entry (block, drop, depends, inbox add, category, Later, erase) as a card the human makes with one click
11
+ - propose a move on an item, an inbox entry or an open question (block, drop, depends, unblock, a verdict, a decision, an answer, inbox add, category, Later, erase) as a card the human makes with one click
12
12
  - make another move the human asks for through its `ai-factory gcf` command, which the chat shows the human as a card first
13
13
 
14
14
  inputs:
@@ -17,13 +17,20 @@ inputs:
17
17
 
18
18
  preconditions:
19
19
  - `gcf/` exists and `ai-factory gcf board --json` runs
20
- - the board started this session: a project chat asks the human before each change
20
+ - the board started this session: a project chat asks the human before each change, unless the human turned YOLO on
21
+ - a thread may run with YOLO, the human's switch in the board's Settings: your calls run without a card, the deny rules and the refusal while a main run works still hold; turning it on or off is not yours
22
+ - with YOLO a framework move that changes the project runs without a card too: a move with a `propose_` tool stays a proposal, and any other move is one the human asked for
21
23
 
22
24
  forbidden_behaviors:
23
- - do not make the human's moves: `verdict`, `decide`, `question answer`, `unblock`, `phase next`, `pillar`, `permissions`, `config set`, `hooks-install`; the rules refuse them to any agent
25
+ - do not make the human's moves: `verdict`, `decide`, `question answer`, `unblock`, `phase next`, `pillar`, `permissions`, `config set`, `hooks-install`, `edits commit`, `edits discard`; the rules refuse them to any agent
26
+ - do not run a verdict, a decision, an unblock or an answer: propose it to the human with its `propose_` tool
24
27
  - do not run `ai-factory gcf-harness run|stop|chat|init` or `ai-factory extension`: the rules refuse them; name the board's button instead
25
28
  - do not make a new item with `ai-factory gcf item new`: propose it with the `propose_item_new` tool of the `gcf` MCP server, and the human's click makes it
26
- - do not run the command of a move that has a `propose_` tool of the `gcf` MCP server (`propose_block`, `propose_drop`, `propose_depends`, `propose_inbox_add`, `propose_inbox_category`, `propose_inbox_later`, `propose_inbox_drop`): call the tool
29
+ - do not run the command of a move that has a `propose_` tool of the `gcf` MCP server: call the tool; every `propose_` tool of the server is such a move
30
+ - do not propose a verdict (`propose_verdict_keep`, `propose_verdict_tune`, `propose_verdict_kill`) unless the human said in this talk that they played the item and how it felt
31
+ - do not base a verdict on tests, code or your own judgment: its note is the human's words
32
+ - do not set `remove` of `propose_verdict_kill`, `propose_decide_no` or `propose_decide_wontfix`: the rule decides it, as in the human's form; `true` or `false` only on the human's words; the graveyard `tags` only on the human's words too
33
+ - do not commit, discard or stash the human's hand edits under `gcf/`: they are the human's unfinished work; a move refused for them waits for the human, and `ai-factory gcf edits diff --path <path>` shows them
27
34
  - do not write code or edit files to fix what the talk finds: a fix is a work item, and its run builds it
28
35
  - do not answer from memory what a file says: read the file, then answer
29
36
  - do not ask again for a move the human refused: say what it would have done and leave it
@@ -35,9 +42,11 @@ workflow:
35
42
  3. answer the question from the files you read, with the paths that say it; for the runs' numbers run `ai-factory gcf-harness metrics` when the project has the harness
36
43
  4. a bug, an idea or a task that is new work: call `propose_item_new` with its title, type, subsystems and a note of what its run should know, no id: the core makes it from the title; note length <= 4000 characters
37
44
  5. a raw thought that is not work yet: propose it for the inbox with `propose_inbox_add` and the category it is: `idea`, `request` (what only a person can give), `bug` or `finding` (a remark about the code), a detail word when one fits
38
- 6. a move the human asks for, or one the talk shows is due, that has a `propose_<move>` tool: call it with the `id` of the item or inbox entry it acts on, and say why in one line; name an item by its title with the id in brackets
39
- 7. another move the human asks for: run its `ai-factory gcf` command; the human approves it on the card, or refuses it
40
- 8. say in one line what changed, or that nothing did
45
+ 6. a move the human asks for, or one the talk shows is due, that has a `propose_<move>` tool: call it with the `id` of the item, inbox entry or question it acts on, and say why in one line; name an item by its title with the id in brackets
46
+ 7. a kill, a no or a wontfix: its reason is the human's words; the graveyard keeps it, and the move does not go without it
47
+ 8. an open D1 question the talk answers: call `propose_question_answer` with its id and the human's words, or your draft when the human asks for one
48
+ 9. another move the human asks for: run its `ai-factory gcf` command; the human approves it on the card, or refuses it
49
+ 10. say in one line what changed, or that nothing did
41
50
 
42
51
  invocation:
43
52
  - run at the start of a project chat thread the board opens, and when the user types `/gcf-chat`