@quolu/lattice 0.105.0 → 0.107.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/src/todo-cli.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createTodoReadiness, listTodoConnections, retireStateConflict, validateProspectiveEvent } from './todo-readiness.mjs';
2
2
  import { cliCommandKind } from './cli-command-kind.mjs';
3
3
  import { cliFailureClass } from './cli-failure-class.mjs';
4
- import { ENFORCED_DONE_MESSAGE, FLAG_PLACEHOLDER, publicRefusalCode, withRefusalGuidance } from './cli-refusal-guidance.mjs';
4
+ import { FLAG_PLACEHOLDER, publicRefusalCode, withRefusalGuidance } from './cli-refusal-guidance.mjs';
5
5
  import { readTaskBackchainContext } from './plan-backchain.mjs';
6
6
  import { auditPendingNextCommands, phaseAuditRequired } from './todo-audit-pending.mjs';
7
7
  import { gitSync } from './git-process.mjs';
@@ -16,7 +16,6 @@ import {
16
16
  isAuthoringPathToken,
17
17
  matchFlagCommand,
18
18
  parseFlagMap,
19
- parseAuthoringJson,
20
19
  readAuthoringJsonFile,
21
20
  repairAuthoringArtifact,
22
21
  resolveAuthoringInputPath,
@@ -30,7 +29,6 @@ import {
30
29
  TODO_TEST_RESULT_CONTRACT_ID,
31
30
  canonicalizeTodoArtifact,
32
31
  digestTodoArtifact,
33
- exactRecord,
34
32
  explainTodoDesignMemo,
35
33
  isTodoDigest,
36
34
  isTodoDesignMemo,
@@ -38,7 +36,6 @@ import {
38
36
  isTodoRef,
39
37
  isTodoTestResult,
40
38
  todoSelfDigest,
41
- validateEvidenceDescriptor,
42
39
  } from './todo-contracts.mjs';
43
40
  import {
44
41
  adoptTodoDashboardActivity,
@@ -71,7 +68,6 @@ import {
71
68
  createTodoStoreWriter,
72
69
  TodoStoreError,
73
70
  isPhaselessTodoPlanSchema,
74
- isTodoEvidenceUncommitted,
75
71
  isUninitializedTodoStore,
76
72
  projectTodoCrossPlanDependencies,
77
73
  TERMINAL_AUDIT_PHASE_ID,
@@ -91,6 +87,7 @@ import {
91
87
  writeTodoWitnessSet,
92
88
  readTodoStoreDisplaySource,
93
89
  readTodoStoreForDisplay,
90
+ readTodoChartMeta,
94
91
  readTodoStoreStable,
95
92
  rebuildTodoSnapshot,
96
93
  writeTodoIndependenceArtifact,
@@ -211,8 +208,8 @@ import { repairTodoStoreWorktreeEol } from './todo-store-worktree-eol.mjs';
211
208
  const CLI_ERROR_SCHEMA = 'lattice.cli_error.v2';
212
209
  const DEFAULT_GANTT_SCOPE = 'live';
213
210
  const MAX_NOTE_INPUT_BYTES = 16_384;
214
- /** u03 A58: `todo done` without --evidence/--message records this text as its evidence. */
215
- const DONE_WITHOUT_EVIDENCE_MESSAGE = '証拠の指定なしで完了した。\n';
211
+ /** `todo done` without --message records this text. */
212
+ const DONE_WITHOUT_MESSAGE = '証拠の指定なしで完了した。\n';
216
213
 
217
214
  /**
218
215
  * `revise` / `revise-set` / `revise-phase` / `migrate`が配布する名前付き入力契約のJSON
@@ -278,16 +275,6 @@ function guidanceContext(argv, env = {}) {
278
275
  };
279
276
  }
280
277
 
281
- /** Enforced plans, so a refusal's done hint names the change their done gate needs; none when the store is unreadable. */
282
- async function enforcedPlanKeys(cwd) {
283
- try {
284
- const { members } = await readTodoStore({ repoRoot: resolveRepoRoot(cwd) });
285
- return members.filter((member) => member.coordination?.mode === 'enforced').map(({ descriptor }) => descriptor.plan_key);
286
- } catch {
287
- return [];
288
- }
289
- }
290
-
291
278
  /**
292
279
  * An error that reached here is, by definition, one none of the typed
293
280
  * TodoStoreError/TypeError branches recognized — the one case where the
@@ -314,7 +301,7 @@ function internalFailure(stderr, error) {
314
301
  const TODO_COMMAND_NAMES = Object.freeze([
315
302
  'status', 'show', 'note', 'bindings', 'display', 'independence', 'structure', 'seam-profile', 'seam-proposal',
316
303
  'verify', 'repair-eol', 'snapshot', 'gantt', 'dashboard', 'phase', 'migrate', 'start', 'block',
317
- 'unblock', 'retire', 'done', 'reopen', 'evidence', 'split', 'revise', 'revise-phase', 'revise-set',
304
+ 'unblock', 'retire', 'done', 'reopen', 'split', 'revise', 'revise-phase', 'revise-set',
318
305
  'retract', 'dependency', 'predecessor', 'connect', 'add', 'notice', 'wait', 'blockers', 'compact',
319
306
  ]);
320
307
 
@@ -371,11 +358,9 @@ const TODO_FLAG_SPECS = Object.freeze({
371
358
  split: Object.freeze({ known: ['plan', 'input'], required: ['plan', 'input'] }),
372
359
  note: NOTE_FLAG_SPEC,
373
360
  // a28: the rest of the writes, and the reads whose --json is optional (their output is JSON either way).
374
- 'phase accept': Object.freeze({ known: ['plan', 'phase', 'evidence', 'message', 'input'], required: ['plan', 'phase'] }),
375
- 'phase reject': Object.freeze({ known: ['plan', 'phase', 'evidence', 'message', 'reason', 'input'], required: ['plan', 'phase'] }),
361
+ 'phase accept': Object.freeze({ known: ['plan', 'phase', 'evidence', 'message'], required: ['plan', 'phase'] }),
362
+ 'phase reject': Object.freeze({ known: ['plan', 'phase', 'evidence', 'message', 'reason'], required: ['plan', 'phase'] }),
376
363
  'phase reopen': Object.freeze({ known: ['plan', 'phase', 'reason', 'override-reason'], required: ['plan', 'phase', 'reason'] }),
377
- 'evidence promote': Object.freeze({ known: ['plan', 'task', 'evidence'], required: ['plan', 'task', 'evidence'] }),
378
- 'evidence anchor': Object.freeze({ known: ['json'], required: [], booleans: ['json'] }),
379
364
  'independence compile': Object.freeze({ known: ['plan', 'input'], required: ['plan', 'input'] }),
380
365
  'independence mode': Object.freeze({ known: ['plan', 'set', 'reason'], required: ['plan', 'set', 'reason'] }),
381
366
  'independence witness scaffold': Object.freeze({ known: ['plan', 'input'], required: ['plan', 'input'] }),
@@ -401,9 +386,8 @@ const TODO_SUBCOMMANDS = Object.freeze({
401
386
  predecessor: { names: ['add', 'remove'], example: 'add' },
402
387
  connect: { names: ['condition', 'priority'], example: 'priority' },
403
388
  phase: { names: ['status', 'review', 'accept', 'reject', 'reopen', 'close-unaudited', 'baseline'], example: 'review' },
404
- evidence: { names: ['promote'], example: 'promote' },
405
389
  });
406
- const GROUP_COMMANDS = ['dependency', 'predecessor', 'connect', 'phase', 'evidence', 'independence', 'note', 'structure'];
390
+ const GROUP_COMMANDS = ['dependency', 'predecessor', 'connect', 'phase', 'independence', 'note', 'structure'];
407
391
  const IDENTIFIER_FLAGS = ['plan', 'task', 'phase', 'from-plan', 'from-task', 'to-plan', 'to-task'];
408
392
  // The shared table is FLAG_PLACEHOLDER (cli-refusal-guidance, a27).
409
393
  const placeholder = (name) => FLAG_PLACEHOLDER[name] ?? `<${name}>`;
@@ -522,23 +506,13 @@ function explainArgumentRefusal(argv) {
522
506
  }
523
507
  }
524
508
  if (argv[0] === 'phase' && ['accept', 'reject'].includes(argv[1])) {
525
- const given = ['evidence', 'message', 'input'].filter((name) => typeof flags[name] === 'string' && flags[name].length > 0);
526
- if (given.length === 0) {
527
- return { pointer: '--evidence', rule: 'flag_missing',
528
- next_action: `Add --evidence <file> (or --message <text>, or --input <decision file>): \`${repairedCommand(head, { ...spec, required: [...spec.required, 'evidence', ...(argv[1] === 'reject' ? ['reason'] : [])] }, flags)}\`.` };
529
- }
530
- if (given.length > 1) {
531
- const [keep, drop] = given;
532
- return { pointer: `--${drop}`, rule: 'flags_exclusive',
533
- next_action: `Pass one of --evidence, --message or --input: \`${repairedCommand(head, spec, { ...flags, ...Object.fromEntries(given.filter((name) => name !== keep).map((name) => [name, undefined])) })}\`.` };
509
+ if (flags.evidence !== undefined && flags.message !== undefined) {
510
+ return { pointer: '--evidence', rule: 'flags_exclusive',
511
+ next_action: `Pass --message <text> alone: \`${repairedCommand(head, spec, { ...flags, evidence: undefined })}\`.` };
534
512
  }
535
- if (argv[1] === 'reject' && given[0] !== 'input' && !(typeof flags.reason === 'string' && flags.reason.length > 0)) {
513
+ if (argv[1] === 'reject' && !(typeof flags.reason === 'string' && flags.reason.length > 0)) {
536
514
  return { pointer: '--reason', rule: 'flag_missing',
537
- next_action: `A reject with --${given[0]} needs --reason <text>: \`${repairedCommand(head, { ...spec, required: [...spec.required, 'reason'] }, flags)}\`.` };
538
- }
539
- if (given[0] === 'input' && flags.reason !== undefined) {
540
- return { pointer: '--reason', rule: 'flag_unknown',
541
- next_action: `With --input the reason is inside the decision file; drop --reason: \`${repairedCommand(head, spec, { ...flags, reason: undefined })}\`.` };
515
+ next_action: `A reject needs --reason <text>: \`${repairedCommand(head, { ...spec, required: [...spec.required, 'reason'] }, flags)}\`.` };
542
516
  }
543
517
  }
544
518
  for (const name of ['input', 'evidence']) {
@@ -587,7 +561,6 @@ function supportsAtomicStoreCommit(argv) {
587
561
  if (command === 'migrate') return !argv.includes('--dry-run') && !argv.includes('--schema');
588
562
  if (['revise', 'split', 'revise-set', 'revise-phase', 'start', 'retract', 'block',
589
563
  'unblock', 'retire', 'done', 'reopen', 'add'].includes(command)) return true;
590
- if (command === 'evidence') return argv[1] === 'promote';
591
564
  if (command === 'phase') return argv[1] !== 'status';
592
565
  return false;
593
566
  }
@@ -747,130 +720,22 @@ async function readRevisionInput(repoRoot, inputRef, {
747
720
  return revision;
748
721
  }
749
722
 
750
- // --evidenceが受け取るのは生の証拠ファイルではなくJSON記述子。ここを間違えた呼び出しAIが
751
- // json_parse_failed/schema_invalidだけを見て手詰まりになるので、期待形をエラーに同梱する(ADR 0130)。
752
- const EVIDENCE_DESCRIPTOR_EXPECTED = Object.freeze({
753
- shape: '{ "evidence_id": "<identifier>", "repo_id": "<identifier>", "path": "<repo相対path>",'
754
- + ' "git_blob_oid": "<40/64桁hex>", "content_digest": "<sha256 64桁hex>",'
755
- + ' "media_type": "text/markdown", "anchor_digest": null }',
756
- note: '証拠ファイル本体ではなく、コミット済みblobを指すJSON記述子を渡す。'
757
- + '対象ファイルをcommitした後、git_blob_oidは `git rev-parse HEAD:<path>`、'
758
- + 'content_digestはblob bytesのsha256(hex)で得る。refsから到達可能なblobだけが検証を通る',
759
- });
760
-
761
- function evidenceIdFor(planKey, taskId) {
762
- const compact = `ev-${planKey}-${taskId}`.replace(/[^0-9A-Za-z._-]/gu, '-').slice(0, 128);
763
- return isTodoIdentifier(compact) ? compact : 'evidence';
764
- }
765
-
766
- function mediaTypeFor(ref) {
767
- if (ref.endsWith('.md')) return 'text/markdown';
768
- if (ref.endsWith('.json')) return 'application/json';
769
- return 'text/plain';
770
- }
771
-
772
- function looksLikeEvidenceDescriptor(value) {
773
- return value !== null && typeof value === 'object' && !Array.isArray(value);
774
- }
775
-
776
- // evidence-ref: every evidence blob Lattice writes is anchored here so gc keeps it. The Store's reachability walk
777
- // excludes refs/lattice/evidence/* (seam refs still count), so an anchored blob still reads `uncommitted` until a commit reaches it.
778
- const EVIDENCE_REF_PREFIX = 'refs/lattice/evidence/';
779
-
780
- function anchorEvidenceBlob(repoRoot, oid) {
781
- gitSync(['update-ref', `${EVIDENCE_REF_PREFIX}${oid}`, oid], { cwd: repoRoot, stdio: ['ignore', 'ignore', 'pipe'] });
782
- }
783
-
784
- function evidenceAnchored(repoRoot, oid) {
785
- try {
786
- gitSync(['show-ref', '--verify', '--quiet', `${EVIDENCE_REF_PREFIX}${oid}`], { cwd: repoRoot, stdio: 'ignore' });
787
- return true;
788
- } catch {
789
- return false;
790
- }
791
- }
792
-
793
- function writeEvidenceBlob(repoRoot, bytes, blobPath, write = true) {
794
- // worktree pathから作る証拠は`git add`と同じclean filterを通す。生のCRLF bytesを
795
- // そのままhashすると、commit先はLFへ正規化される一方、descriptorはdangling blobを
796
- // 指すため、commit後もhard検証を通せない。
797
- const oid = gitSync(['hash-object', ...(write ? ['-w'] : []), `--path=${blobPath}`, '--stdin'], {
798
- cwd: repoRoot, input: bytes, encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'],
799
- }).trim();
800
- let storedBytes;
801
- try {
802
- storedBytes = gitSync(['cat-file', 'blob', oid], { cwd: repoRoot, stdio: ['ignore', 'pipe', 'ignore'] });
803
- } catch (error) {
804
- // a23: a comparison-only hash writes nothing; content never stored has no digest to compare.
805
- if (!write) return { git_blob_oid: oid, content_digest: null };
806
- throw error;
807
- }
808
- // Anchored before the event is appended: no recorded evidence without an anchor. A failed append leaves one ref
809
- // keeping one blob alive (bounded, harmless).
810
- if (write) anchorEvidenceBlob(repoRoot, oid);
811
- return {
812
- git_blob_oid: oid,
813
- content_digest: createHash('sha256').update(storedBytes).digest('hex'),
814
- };
815
- }
816
-
817
- async function resolveDoneEvidence({
818
- repoRoot, evidenceRef, evidenceMessage, planKey, taskId, write = true, inlineFlag = null,
819
- }) {
820
- if (typeof evidenceMessage === 'string') {
821
- const bytes = Buffer.from(evidenceMessage, 'utf8');
822
- const sourceDigest = createHash('sha256').update(bytes).digest('hex');
823
- const evidencePath = `.lattice/todo/evidence/${planKey}/${taskId}/${sourceDigest}.md`;
824
- const descriptor = {
825
- evidence_id: evidenceIdFor(planKey, taskId),
826
- repo_id: 'self',
827
- path: evidencePath,
828
- ...writeEvidenceBlob(repoRoot, bytes, evidencePath, write),
829
- media_type: 'text/markdown',
830
- anchor_digest: null,
831
- };
832
- if (write && (!validateEvidenceDescriptor(descriptor) || !isTodoRef(descriptor.path))) {
833
- throw new TodoStoreError('INVALID_EVIDENCE', 'authored_evidence_descriptor_invalid');
834
- }
835
- return descriptor;
836
- }
723
+ /**
724
+ * One-version alias: `--evidence <file>` stands for `--message <text>` with the file's text. No blob is written
725
+ * and no descriptor is built; the text is the record.
726
+ */
727
+ async function readEvidenceText(repoRoot, evidenceRef, { inlineFlag = '--message' } = {}) {
837
728
  const located = await resolveAuthoringInputPath(repoRoot, evidenceRef, { inlineFlag });
838
729
  const bytes = await readFile(located.absolute);
839
- let text;
840
- try { text = new TextDecoder('utf-8', { fatal: true }).decode(bytes); }
730
+ try { return new TextDecoder('utf-8', { fatal: true }).decode(bytes); }
841
731
  catch { throw new TodoStoreError('INVALID_EVIDENCE', 'evidence_input_invalid_utf8'); }
842
- let parsed = null;
843
- try {
844
- parsed = parseAuthoringJson(text, { invalidCode: 'INVALID_JSON' });
845
- } catch (error) {
846
- if (error instanceof TodoStoreError && error.code !== 'INVALID_JSON') throw error;
847
- }
848
- if (looksLikeEvidenceDescriptor(parsed)) {
849
- if (!validateEvidenceDescriptor(parsed)) {
850
- throw new TodoStoreError('INVALID_EVIDENCE', 'schema_invalid', undefined, {
851
- expected: EVIDENCE_DESCRIPTOR_EXPECTED,
852
- });
853
- }
854
- return parsed;
855
- }
856
- const descriptor = {
857
- evidence_id: evidenceIdFor(planKey, taskId),
858
- repo_id: 'self',
859
- path: located.inputRef,
860
- ...writeEvidenceBlob(repoRoot, bytes, located.inputRef, write),
861
- media_type: mediaTypeFor(located.inputRef),
862
- anchor_digest: null,
863
- };
864
- if (write && !validateEvidenceDescriptor(descriptor)) {
865
- throw new TodoStoreError('INVALID_EVIDENCE', 'authored_evidence_descriptor_invalid');
866
- }
867
- return descriptor;
868
732
  }
869
733
 
870
- async function readEvidenceInput(repoRoot, inputRef) {
871
- return resolveDoneEvidence({
872
- repoRoot, evidenceRef: inputRef, evidenceMessage: null, planKey: 'evidence', taskId: 'body',
873
- });
734
+ /** The alias says which flag replaces it, after the command succeeded. */
735
+ function retiredEvidenceFlag(stderr, command, result) {
736
+ stderr.write(`${JSON.stringify({ schema: 'lattice.todo_command_retired.v1', command: `${command} --evidence`,
737
+ still_works_until: 'the next minor version', use: `lattice ${command} --message <text>` })}\n`);
738
+ return result;
874
739
  }
875
740
 
876
741
  async function readJsonInput(repoRoot, inputRef, { validate, invalidCode, expected = null }) {
@@ -937,19 +802,16 @@ async function readStructureSetDraft(repoRoot, inputRef) {
937
802
  */
938
803
  function auditGateGuidance(planKey, phaseId, auditRequired = false) {
939
804
  const target = `--plan ${planKey} --phase ${phaseId}`;
940
- const audit = `lattice todo phase review ${target} --reason <text> → accept ${target} --evidence <file>`;
941
- // ADR 0200 gate 5: an enforced plan's heavy phase refuses close-unaudited, so only the audit is offered,
942
- // with the --message route for a seat that cannot write a file into the Store root.
943
- if (auditRequired) return `全ToDoがdone。このplanはenforcedでheavyの段階なので監査する: ${audit}(fileを置けないなら --message <text>)`;
805
+ const audit = `lattice todo phase review ${target} --reason <text> → accept ${target} [--message <text>]`;
806
+ // ADR 0200 gate 5: an enforced plan's heavy phase refuses close-unaudited, so only the audit is offered.
807
+ if (auditRequired) return `全ToDoがdone。このplanはenforcedでheavyの段階なので監査する: ${audit}`;
944
808
  return `全ToDoがdone。監査せず閉じるなら: lattice todo phase close-unaudited ${target} --reason <text>`
945
809
  + `(監査するなら ${audit})`;
946
810
  }
947
811
 
948
812
  /** a36: reviewing and rejected phases say their next command too (the same lines as audit_pending). */
949
813
  function auditDecisionGuidance(plan, phase) {
950
- const slots = todoPhaseDefinitions(plan).find(({ phase_id: id }) => id === phase.phase_id)
951
- ?.required_evidence_slots.length ?? 1;
952
- const [first, second] = auditPendingNextCommands(plan.plan_key, phase.phase_id, phase.status, slots);
814
+ const [first, second] = auditPendingNextCommands(plan.plan_key, phase.phase_id, phase.status);
953
815
  return phase.status === 'reviewing'
954
816
  ? `監査中(review済み)。受け入れるなら: ${first}(通らないなら: ${second})`
955
817
  : `監査が通らなかった。やり直すなら: ${first}`;
@@ -1013,7 +875,7 @@ function externalValidator(external) {
1013
875
  }
1014
876
 
1015
877
  async function mutate({
1016
- repoRoot, env, planKey, taskId, kind, payload, evidenceRef, evidenceMessage = null,
878
+ repoRoot, env, planKey, taskId, kind, payload, message = null,
1017
879
  advisory = null, noteContext = null, structureContext = null, featureContext = null,
1018
880
  testResultRef = null, actor: carriedActor = null, externalTasks = null,
1019
881
  }) {
@@ -1022,31 +884,11 @@ async function mutate({
1022
884
  const external = externalTasks ?? (kind === 'start' || (kind === 'done' && payload === 'authored')
1023
885
  ? (await readTodoExternalTasks(await readTodoStore({ repoRoot }), env)).external_tasks : []);
1024
886
  const validator = externalValidator(external);
1025
- const evidence = evidenceRef === null && evidenceMessage === null
1026
- ? null
1027
- : await resolveDoneEvidence({
1028
- repoRoot, evidenceRef, evidenceMessage, planKey, taskId,
1029
- // Only an authored done takes --message as the inline alternative to --evidence.
1030
- inlineFlag: kind === 'done' && payload === 'authored' ? '--message' : null,
1031
- });
1032
887
  const testResult = testResultRef === null ? null : await readTestResultInput(repoRoot, testResultRef);
1033
- const materializedEvidence = typeof evidenceMessage === 'string'
1034
- ? {
1035
- ref: evidence.path,
1036
- bytes: gitSync(['cat-file', 'blob', evidence.git_blob_oid], {
1037
- cwd: repoRoot, stdio: ['ignore', 'pipe', 'ignore'],
1038
- }),
1039
- }
1040
- : null;
1041
888
  let eventPayload = payload;
1042
889
  if (kind === 'done' && payload === 'authored') {
1043
- eventPayload = { evidence, ...(testResult === null ? {} : { test_result: testResult }) };
1044
- }
1045
- if (kind === 'done' && payload === 'evidence_promotion') {
1046
- // imported/authored の由来はlock内のcanonical stateから解決する。
1047
- // CLI側で固定するとauthored doneの証拠を再束縛できず、path更新後の
1048
- // evidence_unverifiedを修復する公開経路が無くなる。
1049
- eventPayload = { done_mode: 'evidence_promotion', evidence };
890
+ // The store canonicalizes only the legacy {evidence} input, so the CLI sends the recorded shape itself.
891
+ eventPayload = { done_mode: 'authored', imported: false, message, ...(testResult === null ? {} : { test_result: testResult }) };
1050
892
  }
1051
893
  const { event, snapshot, plan, phases } = await appendTodoEvent({
1052
894
  validateProspectiveEvent: validator,
@@ -1054,7 +896,6 @@ async function mutate({
1054
896
  writer: createTodoStoreWriter({ caller: 'g5-authoring' }),
1055
897
  planKey,
1056
898
  event: { kind, task_id: taskId, actor, payload: eventPayload },
1057
- materializedEvidence,
1058
899
  });
1059
900
  const task = snapshot.tasks.find(({ task_id: current }) => current === event.task_id);
1060
901
  const authoredTask = plan.tasks.find(({ task_id: current }) => current === event.task_id);
@@ -1108,7 +949,7 @@ function withBlockGuidance(result) {
1108
949
 
1109
950
  /** retract-anyone: a reopened task is unstarted again; the redo records a start (from any seat). */
1110
951
  async function reopenTask({ repoRoot, env, planKey, taskId, payload }) {
1111
- const result = await mutate({ repoRoot, env, planKey, taskId, kind: 'reopen', payload, evidenceRef: null });
952
+ const result = await mutate({ repoRoot, env, planKey, taskId, kind: 'reopen', payload });
1112
953
  const hinted = {
1113
954
  ...result,
1114
955
  next_action: `${result.plan_key}/${result.task_id} is unstarted again; redo it with`
@@ -1187,38 +1028,21 @@ async function mutateUnlessUnchanged(options) {
1187
1028
  /** a23: block/retire drop a --reason that differs from the recorded one. */
1188
1029
  const reasonDropped = (reason) => async (recorded) => (recorded?.payload?.reason === reason ? [] : ['--reason']);
1189
1030
 
1190
- /** The evidence a `todo done` records: the message (naming the file when both are given), the file, or the default text. */
1191
- async function doneEvidenceInput({ repoRoot, flags, write = true }) {
1192
- const hasEvidence = isAuthoringPathToken(flags.evidence);
1193
- const hasMessage = typeof flags.message === 'string' && flags.message.length > 0;
1194
- if (hasEvidence && hasMessage) {
1195
- // The message is the record; it names the resolved file so nothing given is lost.
1196
- const file = await resolveDoneEvidence({
1197
- repoRoot, evidenceRef: flags.evidence, evidenceMessage: null, planKey: flags.plan, taskId: flags.task,
1198
- write, inlineFlag: '--message',
1199
- });
1200
- return { evidenceRef: null, evidenceMessage: `${flags.message}\n\nevidence: ${file.repo_id}:${file.path}`
1201
- + ` (git blob ${file.git_blob_oid}, sha256 ${file.content_digest})\n` };
1202
- }
1203
- if (hasEvidence) return { evidenceRef: flags.evidence, evidenceMessage: null };
1204
- return { evidenceRef: null, evidenceMessage: hasMessage ? flags.message : DONE_WITHOUT_EVIDENCE_MESSAGE };
1031
+ /** The text a `todo done` records: --message, else the text of the one-version `--evidence <file>` alias, else the default. */
1032
+ async function doneMessage({ repoRoot, flags }) {
1033
+ if (typeof flags.message === 'string' && flags.message.length > 0) return flags.message;
1034
+ if (isAuthoringPathToken(flags.evidence)) return readEvidenceText(repoRoot, flags.evidence);
1035
+ return DONE_WITHOUT_MESSAGE;
1205
1036
  }
1206
1037
 
1207
- /**
1208
- * a23: the content flags of a repeated done that the recorded done does not hold. Compared by git blob,
1209
- * hashed without writing; a file that cannot be read counts as differing.
1210
- */
1038
+ /** a23: the content flags of a repeated done that the recorded done does not hold. */
1211
1039
  async function doneDropped({ repoRoot, flags, recorded }) {
1212
- const given = (names) => names.filter((name) => flags[name] !== undefined).map((name) => `--${name}`);
1213
- const sameEvidence = async () => {
1214
- const evidence = await resolveDoneEvidence({ repoRoot, ...await doneEvidenceInput({ repoRoot, flags, write: false }),
1215
- planKey: flags.plan, taskId: flags.task, write: false });
1216
- return evidence.git_blob_oid === recorded?.payload?.evidence?.git_blob_oid;
1217
- };
1040
+ const sameMessage = async () => (await doneMessage({ repoRoot, flags })) === recorded?.payload?.message;
1218
1041
  const sameTestResult = async () => (await readTestResultInput(repoRoot, flags['test-result'])) === recorded?.payload?.test_result;
1219
1042
  const differs = async (same) => { try { return !(await same()); } catch { return true; } };
1043
+ const given = ['message', 'evidence'].filter((name) => flags[name] !== undefined).map((name) => `--${name}`);
1220
1044
  return [
1221
- ...(given(['message', 'evidence']).length > 0 && await differs(sameEvidence) ? given(['message', 'evidence']) : []),
1045
+ ...(given.length > 0 && await differs(sameMessage) ? given : []),
1222
1046
  ...(flags['test-result'] !== undefined && await differs(sameTestResult) ? ['--test-result'] : []),
1223
1047
  ];
1224
1048
  }
@@ -1249,7 +1073,7 @@ async function retireTask({ repoRoot, env, planKey, taskId, reason }) {
1249
1073
  const state = member?.tasks.find(({ task_id: current }) => current === taskId);
1250
1074
  if (state === undefined) {
1251
1075
  // 未知のplan/taskはStoreの既存の拒否をそのまま通す。
1252
- return mutate({ repoRoot, env, planKey, taskId, kind: 'retire', payload: { reason }, evidenceRef: null });
1076
+ return mutate({ repoRoot, env, planKey, taskId, kind: 'retire', payload: { reason } });
1253
1077
  }
1254
1078
  if (state.status === 'retired') {
1255
1079
  return unchangedTransition(store, { env, planKey, taskId, kind: 'retire', dropped: reasonDropped(reason) });
@@ -1259,7 +1083,7 @@ async function retireTask({ repoRoot, env, planKey, taskId, reason }) {
1259
1083
  let result;
1260
1084
  try {
1261
1085
  result = await mutate({ repoRoot, env, planKey, taskId, kind: 'retire',
1262
- payload: { reason, prior_status: state.status }, evidenceRef: null });
1086
+ payload: { reason, prior_status: state.status } });
1263
1087
  } catch (error) {
1264
1088
  throw retireStateConflict(error, { planKey, taskId, priorStatus: state.status });
1265
1089
  }
@@ -1524,7 +1348,7 @@ async function startTask({
1524
1348
  const advisory = await startAdvisory({
1525
1349
  repoRoot, store, projection, planKey, taskId: resolvedTaskId,
1526
1350
  });
1527
- if (member.coordination?.mode === 'enforced') {
1351
+ if (member.coordination?.mode === 'enforced' && !(await noCodeTask({ repoRoot, member, taskId: resolvedTaskId }))) {
1528
1352
  enforcedStartGate({ advisory, planKey, taskId: resolvedTaskId, overrideReason });
1529
1353
  }
1530
1354
  const structureContext = await startStructureContext({
@@ -1542,7 +1366,7 @@ async function startTask({
1542
1366
  { code: 'LATTICE_START_BACKCHAIN_UNUSABLE' });
1543
1367
  }
1544
1368
  return mutate({ repoRoot, env, planKey, taskId: resolvedTaskId, kind: 'start',
1545
- payload: { override_reason: overrideReason }, evidenceRef: null, advisory, noteContext,
1369
+ payload: { override_reason: overrideReason }, advisory, noteContext,
1546
1370
  structureContext, featureContext, externalTasks: store.external_tasks ?? [] });
1547
1371
  }
1548
1372
 
@@ -1566,6 +1390,16 @@ function headResolves(repoRoot) {
1566
1390
  const declareCommand = (planKey, taskId) => `lattice todo independence witness declare --plan ${planKey} --task ${taskId}`
1567
1391
  + ' --owns <path>[,<path>...] [--reads <path>,...] [--writes <path>,...]';
1568
1392
 
1393
+ /**
1394
+ * g3: a task in a lane the host marked `no_code_lanes` (`chart set --no-code-lane`) touches no code, so gates 1–3 do not apply:
1395
+ * it counts as declared with an empty boundary and can neither conflict nor go stale. Lattice names no lane itself.
1396
+ * An unreadable chart meta means no lane is marked (the gates apply).
1397
+ */
1398
+ async function noCodeTask({ repoRoot, member, taskId }) {
1399
+ const lane = member.plan.tasks.find(({ task_id: id }) => id === taskId)?.lane;
1400
+ return (await readTodoChartMeta({ repoRoot }).catch(() => null))?.no_code_lanes?.includes(lane) ?? false;
1401
+ }
1402
+
1569
1403
  /** ADR 0200 gates 1–3: an enforced plan does not start undeclared, stale or conflicting work. Reads the advisory only. */
1570
1404
  function enforcedStartGate({ advisory, planKey, taskId, overrideReason }) {
1571
1405
  const unknown = (kind) => advisory.self_unknowns.some((entry) => entry.kind === kind);
@@ -1586,24 +1420,6 @@ function enforcedStartGate({ advisory, planKey, taskId, overrideReason }) {
1586
1420
  }
1587
1421
  }
1588
1422
 
1589
- /** ADR 0200 gate 4: done on an enforced plan names the change: evidence, an http(s) URL, or a commit in HEAD. */
1590
- async function enforcedDoneGate({ repoRoot, planKey, flags }) {
1591
- const member = (await readTodoStore({ repoRoot })).members.find(({ descriptor }) => descriptor.plan_key === planKey);
1592
- if (member?.coordination?.mode !== 'enforced' || flags.evidence !== undefined) return;
1593
- const message = typeof flags.message === 'string' ? flags.message : '';
1594
- if (/https?:\/\/\S+/u.test(message)) return;
1595
- for (const token of message.match(/\b[0-9a-f]{7,40}\b/gu) ?? []) {
1596
- try {
1597
- gitSync(['merge-base', '--is-ancestor', token, 'HEAD'], { cwd: repoRoot, stdio: 'ignore' });
1598
- return;
1599
- } catch { /* not a commit in HEAD; try the next token */ }
1600
- }
1601
- throw new TodoStoreError('TODO_TRANSITION_REFUSED', 'enforced_done_reference_missing', undefined, {
1602
- plan_key: planKey, task_id: flags.task,
1603
- next_action: `Name the adopted change: \`lattice todo done --plan ${planKey} --task ${flags.task} --message ${ENFORCED_DONE_MESSAGE}\` (a sha must be in HEAD).`,
1604
- });
1605
- }
1606
-
1607
1423
  // plan改訂でcarryされたin-progress ToDoの再束縛入口(ADR 0191)。task状態・開始時刻は
1608
1424
  // 変えず、現plan_version・現actorのstart束縛だけをjournalへ積む。runtime intakeは
1609
1425
  // literal startだけを束縛に使いcarryを推定しないため、改訂を跨いだ進行中工程の
@@ -1642,7 +1458,7 @@ export async function rebindStart({ repoRoot, env, planKey, taskId, reason, acto
1642
1458
  }
1643
1459
  return mutate({
1644
1460
  repoRoot, env, planKey, taskId, kind: 'start',
1645
- payload: { start_mode: 'rebind', reason }, evidenceRef: null, noteContext, actor,
1461
+ payload: { start_mode: 'rebind', reason }, noteContext, actor,
1646
1462
  });
1647
1463
  }
1648
1464
 
@@ -1678,85 +1494,22 @@ async function retractStart({ repoRoot, env, planKey, taskId, reason }) {
1678
1494
  action: () => mutate({
1679
1495
  repoRoot, env, planKey, taskId: binding.task_id, kind: 'start_retracted',
1680
1496
  payload: { reason, target_start_digest: binding.activation_event_digest },
1681
- evidenceRef: null,
1682
1497
  }),
1683
1498
  });
1684
1499
  }
1685
1500
 
1686
- function validatePhaseDecisionInput(value, outcome) {
1687
- const keys = outcome === 'accept'
1688
- ? ['schema', 'review_event_digest', 'decision_evidence', 'evidence_slots', 'input_digest']
1689
- : ['schema', 'review_event_digest', 'reason', 'decision_evidence', 'input_digest'];
1690
- return exactRecord(value, keys) && value.schema === `lattice.phase_${outcome}_input.v1`
1691
- && isTodoDigest(value.review_event_digest) && validateEvidenceDescriptor(value.decision_evidence)
1692
- && (outcome === 'accept'
1693
- ? Array.isArray(value.evidence_slots) && value.evidence_slots.length > 0
1694
- && value.evidence_slots.every((entry) => exactRecord(entry, ['slot_id', 'evidence'])
1695
- && isTodoIdentifier(entry.slot_id) && validateEvidenceDescriptor(entry.evidence))
1696
- && value.evidence_slots.every((entry, index) => index === 0
1697
- || value.evidence_slots[index - 1].slot_id < entry.slot_id)
1698
- : typeof value.reason === 'string' && value.reason.length > 0)
1699
- && isTodoDigest(value.input_digest) && value.input_digest === todoSelfDigest(value, 'input_digest');
1700
- }
1701
-
1702
- // `--input`の形が合わないとき、期待形をerrorへ同梱する(ADR 0130)。自己digestは入口が補うので
1703
- // 空でよい(ADR 0181)。証拠記述子を手で作らせないために、ふつうは`--evidence`を案内する。
1704
- const PHASE_DECISION_EXPECTED = Object.freeze({
1705
- accept: '{ "schema": "lattice.phase_accept_input.v1", "review_event_digest": "<phase reviewのevent_digest>",'
1706
- + ' "decision_evidence": <evidence記述子>, "evidence_slots": [{ "slot_id": "<必須slot>", "evidence": <evidence記述子> }],'
1707
- + ' "input_digest": "" }',
1708
- reject: '{ "schema": "lattice.phase_reject_input.v1", "review_event_digest": "<phase reviewのevent_digest>",'
1709
- + ' "reason": "<text>", "decision_evidence": <evidence記述子>, "input_digest": "" }',
1710
- note: 'input_digestは入口が計算する。証拠fileがcommit済みなら、`--evidence <file>`で'
1711
- + 'review_event_digest・記述子・必須slotを機械が埋める。fileを置けないなら`--message <text>`でも同じく埋まる'
1712
- + '(commitまではuncommitted)。evidence記述子の形はEVIDENCE_DESCRIPTOR_EXPECTEDを見る。',
1713
- });
1714
-
1715
- async function phaseDecision({ repoRoot, env, planKey, phaseId, outcome, inputRef }) {
1716
- let input;
1717
- try {
1718
- input = await readRevisionInput(repoRoot, inputRef, {
1719
- validate: (value) => validatePhaseDecisionInput(value, outcome),
1720
- invalidCode: 'PHASE_DECISION_INVALID', invalidReason: 'phase_decision_schema_or_digest_invalid',
1721
- // phase decision入力はrevision契約と別形状。既定のrevision explainを誤って当てない。
1722
- explain: null,
1723
- });
1724
- } catch (error) {
1725
- if (error instanceof TodoStoreError && error.code === 'PHASE_DECISION_INVALID') {
1726
- throw new TodoStoreError('PHASE_DECISION_INVALID', 'phase_decision_schema_or_digest_invalid', undefined, {
1727
- expected: PHASE_DECISION_EXPECTED[outcome], note: PHASE_DECISION_EXPECTED.note,
1728
- evidence_descriptor: EVIDENCE_DESCRIPTOR_EXPECTED,
1729
- next_action: `lattice todo phase ${outcome} --plan ${planKey} --phase ${phaseId}`
1730
- + (outcome === 'reject' ? ' --reason <text>' : '') + ' --evidence <repo内の監査file>',
1731
- });
1732
- }
1733
- throw error;
1734
- }
1735
- const payload = outcome === 'accept'
1736
- ? { review_event_digest: input.review_event_digest, decision_evidence: input.decision_evidence,
1737
- evidence_slots: input.evidence_slots }
1738
- : { review_event_digest: input.review_event_digest, reason: input.reason,
1739
- decision_evidence: input.decision_evidence };
1740
- return phaseMutation({ repoRoot, env, planKey, phaseId, kind: `phase_${outcome}`, payload });
1741
- }
1742
-
1743
1501
  /**
1744
- * `--evidence <file>`から判断入力を組み立てる(ADR 0181の下書き受理をphase判断へ広げる)。
1745
- * review_event_digestはstoreの現在のreviewから、記述子は`todo done`と同じ処理でcommit済み
1746
- * fileから作る。必須slotが1つならその証拠で埋める。複数slotへ1つの証拠を流用すると
1747
- * 「各slotを別々に確かめた」ことを偽るので、その場合は`--input`で明示させる。
1502
+ * `phase accept|reject`: the decision binds to the current review and records an optional --message.
1503
+ * No evidence is asked for; the phase closes on the decision alone.
1748
1504
  */
1749
- async function phaseDecisionFromEvidence({
1750
- repoRoot, env, planKey, phaseId, outcome, evidenceRef = null, evidenceMessage = null, reason,
1751
- }) {
1505
+ async function phaseDecision({ repoRoot, env, planKey, phaseId, outcome, message = null, reason = null }) {
1752
1506
  const store = await readTodoStore({ repoRoot });
1753
1507
  const member = store.members.find(({ plan }) => plan.plan_key === planKey);
1754
1508
  if (member === undefined) {
1755
1509
  throw new TodoStoreError('PHASE_DECISION_INVALID', 'plan_not_active', undefined, { plan_key: planKey });
1756
1510
  }
1757
1511
  const state = member.phases.find(({ phase_id: current }) => current === phaseId);
1758
- const definition = todoPhaseDefinitions(member.plan).find(({ phase_id: current }) => current === phaseId);
1759
- if (state === undefined || definition === undefined) {
1512
+ if (state === undefined) {
1760
1513
  throw new TodoStoreError('PHASE_DECISION_INVALID', 'phase_not_found', undefined, {
1761
1514
  plan_key: planKey, phase_id: phaseId,
1762
1515
  phases: todoPhaseDefinitions(member.plan).map(({ phase_id: id }) => id),
@@ -1768,30 +1521,14 @@ async function phaseDecisionFromEvidence({
1768
1521
  next_action: `lattice todo phase review --plan ${planKey} --phase ${phaseId} --reason <text>`,
1769
1522
  });
1770
1523
  }
1771
- if (outcome === 'accept' && definition.required_evidence_slots.length !== 1) {
1772
- throw new TodoStoreError('PHASE_DECISION_INVALID', 'multiple_evidence_slots_need_input', undefined, {
1773
- required_evidence_slots: definition.required_evidence_slots,
1774
- expected: PHASE_DECISION_EXPECTED.accept, evidence_descriptor: EVIDENCE_DESCRIPTOR_EXPECTED,
1775
- next_action: `lattice todo phase accept --plan ${planKey} --phase ${phaseId} --input <file>`,
1776
- });
1777
- }
1778
- // A --message becomes message evidence exactly as in `todo done`: no file inside the Store root is needed.
1779
- const evidence = await resolveDoneEvidence({
1780
- repoRoot, evidenceRef, evidenceMessage, planKey, taskId: `${phaseId}-${outcome}`,
1781
- });
1782
- const payload = outcome === 'accept'
1783
- ? { review_event_digest: state.review_event_digest, decision_evidence: evidence,
1784
- evidence_slots: definition.required_evidence_slots.map((slotId) => ({ slot_id: slotId, evidence })) }
1785
- : { review_event_digest: state.review_event_digest, reason, decision_evidence: evidence };
1524
+ const payload = {
1525
+ review_event_digest: state.review_event_digest,
1526
+ ...(outcome === 'reject' ? { reason } : {}),
1527
+ ...(message === null ? {} : { message }),
1528
+ };
1786
1529
  return phaseMutation({ repoRoot, env, planKey, phaseId, kind: `phase_${outcome}`, payload });
1787
1530
  }
1788
1531
 
1789
- /** A phase decision's evidence: committed, uncommitted (no ref reaches it yet, e.g. `--message` on a root with no commit) or null. */
1790
- function decisionEvidenceState(repoRoot, store, evidence) {
1791
- if (evidence === null || evidence === undefined) return null;
1792
- return isTodoEvidenceUncommitted({ repoRoot, store, evidence }) ? 'uncommitted' : 'committed';
1793
- }
1794
-
1795
1532
  async function phaseMutation({ repoRoot, env, planKey, phaseId, kind, payload }) {
1796
1533
  if (kind === 'phase_close_unaudited') {
1797
1534
  // ADR 0200 gate 5: an enforced plan keeps the audit its author required for a heavy phase.
@@ -1801,9 +1538,8 @@ async function phaseMutation({ repoRoot, env, planKey, phaseId, kind, payload })
1801
1538
  if (phaseAuditRequired(member, phase?.gate_policy)) {
1802
1539
  throw new TodoStoreError('TODO_TRANSITION_REFUSED', 'enforced_heavy_phase_unaudited', undefined, {
1803
1540
  plan_key: planKey, phase_id: phaseId,
1804
- next_action: `Audit it: \`lattice todo phase review --plan ${planKey} --phase ${phaseId} --reason <text>\` then \`lattice todo phase accept --plan ${planKey} --phase ${phaseId} --evidence <file>\``
1805
- + ` (or \`--message <text>\` when no file can be written into the Store root);`
1806
- + ' or revise the phase to a non-heavy gate_policy with `lattice plan revise` (recorded).',
1541
+ next_action: `Audit it: \`lattice todo phase review --plan ${planKey} --phase ${phaseId} --reason <text>\` then \`lattice todo phase accept --plan ${planKey} --phase ${phaseId}\``
1542
+ + ' (a --message <text> is optional); or revise the phase to a non-heavy gate_policy with `lattice plan revise` (recorded).',
1807
1543
  });
1808
1544
  }
1809
1545
  }
@@ -1822,8 +1558,6 @@ async function phaseMutation({ repoRoot, env, planKey, phaseId, kind, payload })
1822
1558
  kind: event.kind, sequence: event.sequence, event_digest: event.event_digest,
1823
1559
  journal_head_digest: event.event_digest, snapshot_digest: snapshot.snapshot_digest,
1824
1560
  status: phase.status,
1825
- decision_evidence_state: phase.decision_evidence === null || phase.decision_evidence === undefined ? null
1826
- : decisionEvidenceState(repoRoot, await readTodoStore({ repoRoot }), phase.decision_evidence),
1827
1561
  result_digest: '',
1828
1562
  };
1829
1563
  result.result_digest = todoSelfDigest(result, 'result_digest');
@@ -2342,12 +2076,11 @@ async function phaseStatus({ repoRoot, planKey }) {
2342
2076
  // 無いのでsnapshot.phasesは直接読まない)。ここでPHASE_UNAVAILABLEへ拒否せず、その暗黙Phase
2343
2077
  // をそのまま返す——`implicit`で機械可読に「宣言されたPhaseではない」ことを示す。
2344
2078
  const implicit = isPhaselessTodoPlanSchema(member.plan.schema);
2345
- // ADR 0148裁定8: gate_readyのPhaseには、なぜ監査待ちになったかと次の一歩をここでも言う
2079
+ // ADR 0148裁定8: gate_readyのPhaseには、なぜ監査前になったかと次の一歩をここでも言う
2346
2080
  // (todo doneのadvisoryと同じ文言)。implicit(暗黙のterminal-audit Phase)に限らず、
2347
2081
  // v4/v5の実Phaseがgate_readyになった場合も同じ理由で同じ案内が要る。
2348
2082
  const phases = member.phases.map((phase) => ({
2349
2083
  ...phase,
2350
- decision_evidence_state: decisionEvidenceState(repoRoot, store, phase.decision_evidence),
2351
2084
  acceptance_stale: phaseAcceptanceStale(member.plan, member.journal.events, phase, member.tasks),
2352
2085
  guidance: phaseAcceptanceStale(member.plan, member.journal.events, phase, member.tasks)
2353
2086
  ? staleAcceptanceGuidance(member.plan.plan_key, phase.phase_id)
@@ -2539,7 +2272,7 @@ async function migrate({ repoRoot, inputRef }) {
2539
2272
  next_action: `lattice todo revise-phase --plan ${imported.plan.plan_key} --input <phase-revision.json>`,
2540
2273
  } : null,
2541
2274
  // ob03: 起票直後のplanは必ず調整方式が未宣言である。ここで案内しないと、選ぶ機会が
2542
- // 「誰も呼ぶ動機の無いdrilldown」にしか無くなる——前campaignの監査待ちと同じ形になる。
2275
+ // 「誰も呼ぶ動機の無いdrilldown」にしか無くなる——前campaignの監査前と同じ形になる。
2543
2276
  coordination_guidance: imported.connectionOnly === true ? null : {
2544
2277
  mode: null,
2545
2278
  modes: [...TODO_COORDINATION_MODES],
@@ -2558,8 +2291,8 @@ function extractionFreshnessViolations(repoRoot, extraction) {
2558
2291
  // rev-listの出力はobject数に比例して伸びる(本repo実測で既定maxBuffer 1MiB超過済み)。
2559
2292
  // 隣のgit showと同様にmaxBufferを明示しないと、ENOBUFSが握られて
2560
2293
  // source_reachability_unreadableへ誤変換される。
2561
- // evidence-ref: an anchored evidence blob is not a reachable source.
2562
- reachable = new Set(gitSync(['rev-list', '--objects', `--exclude=${EVIDENCE_REF_PREFIX}*`, '--all'], {
2294
+ // Blobs anchored by 0.105 and earlier live under refs/lattice/evidence/*; they are not a reachable source.
2295
+ reachable = new Set(gitSync(['rev-list', '--objects', '--exclude=refs/lattice/evidence/*', '--all'], {
2563
2296
  cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 134_217_728,
2564
2297
  }).split('\n').filter(Boolean).map((line) => line.split(' ')[0]));
2565
2298
  } catch {
@@ -3491,7 +3224,7 @@ async function recordStructureRealization({ repoRoot, planKey, taskId, realizati
3491
3224
  previous_realization_digest: appended.previous_realization_digest,
3492
3225
  history_length: appended.history_length,
3493
3226
  effective: taskProjection,
3494
- next_action: `lattice todo done --plan ${planKey} --task ${taskId} --evidence <file>`,
3227
+ next_action: `lattice todo done --plan ${planKey} --task ${taskId} --message <text>`,
3495
3228
  result_digest: '',
3496
3229
  };
3497
3230
  result.result_digest = todoSelfDigest(result, 'result_digest');
@@ -4949,7 +4682,6 @@ function writesTodoStore(argv) {
4949
4682
  case 'structure': return ['compile', 'realize', 'finalize'].includes(second)
4950
4683
  || (second === 'input' && !argv.includes('--dry-run'));
4951
4684
  case 'seam-proposal': return ['compile', 'apply', 'land'].includes(second);
4952
- case 'evidence': return second === 'promote';
4953
4685
  case 'dependency': return ['connect', 'disconnect'].includes(second);
4954
4686
  case 'predecessor': return ['add', 'remove'].includes(second);
4955
4687
  case 'connect': return second === 'condition' && ['add', 'remove', 'resolve'].includes(argv[2]);
@@ -5211,106 +4943,17 @@ async function ensureActiveProjectDashboard({ repoRoot, env, stderr, strict = fa
5211
4943
  }
5212
4944
  }
5213
4945
 
5214
- /** evidence-ref: an uncommitted item says whether gc is kept off it, and how to protect it if not. */
5215
- function uncommittedEvidenceItem(repoRoot, store, evidence) {
5216
- const anchored = evidenceAnchored(evidenceRepoRoot(repoRoot, store, evidence), evidence.git_blob_oid);
5217
- return { repo_id: evidence.repo_id, path: evidence.path, anchored,
5218
- next_action: anchored
5219
- ? `Commit ${evidence.path} (repository ${evidence.repo_id}), then rerun \`lattice todo verify --json\`.`
5220
- : 'Anchor it so gc keeps it: `lattice todo evidence anchor --json`; commit it to make it committed.' };
5221
- }
5222
-
5223
- function evidenceRepoRoot(repoRoot, store, evidence) {
5224
- const ref = store.manifest.repositories.find(({ repo_id: id }) => id === evidence.repo_id)?.path ?? '.';
5225
- return path.resolve(repoRoot, ref);
5226
- }
5227
-
5228
- /** The evidence descriptors a Store records: task evidence, phase decision evidence and accepted slot evidence. */
5229
- function recordedEvidence(store) {
5230
- const entries = [];
5231
- for (const member of store.members) {
5232
- const planKey = member.plan.plan_key;
5233
- for (const task of member.tasks) {
5234
- if (validateEvidenceDescriptor(task.evidence)) entries.push({ plan_key: planKey, task_id: task.task_id, evidence: task.evidence });
5235
- }
5236
- for (const event of member.journal.events) {
5237
- if (!['phase_accept', 'phase_reject'].includes(event.kind)) continue;
5238
- for (const evidence of [event.payload.decision_evidence, ...(event.payload.evidence_slots ?? []).map((slot) => slot.evidence)]) {
5239
- if (validateEvidenceDescriptor(evidence)) entries.push({ plan_key: planKey, phase_id: event.phase_id, evidence });
5240
- }
5241
- }
5242
- }
5243
- return entries;
5244
- }
5245
-
5246
- /**
5247
- * `todo evidence anchor` (evidence-ref): anchor evidence recorded before writes anchored it. Idempotent; run once per
5248
- * existing chart. Evidence gc already pruned cannot come back and is listed as `missing`.
5249
- */
5250
- async function evidenceAnchor({ repoRoot }) {
5251
- // No Store yet: nothing recorded, so nothing to anchor. Answer like `todo status` does, not as a broken store.
5252
- if (await isUninitializedTodoStore({ repoRoot })) {
5253
- const result = { schema: 'lattice.todo_evidence_anchor_uninitialized.v1', anchored: [], already: 0, missing: [],
5254
- next_actions: ['lattice plan create --template --json', 'lattice plan create --input <file>'], result_digest: '' };
5255
- result.result_digest = todoSelfDigest(result, 'result_digest');
5256
- return result;
5257
- }
5258
- const store = await readTodoStore({ repoRoot });
5259
- const anchored = [];
5260
- const missing = [];
5261
- const seen = new Set();
5262
- let already = 0;
5263
- for (const { evidence, ...owner } of recordedEvidence(store)) {
5264
- const repo = evidenceRepoRoot(repoRoot, store, evidence);
5265
- const key = `${repo}\0${evidence.git_blob_oid}`;
5266
- if (seen.has(key)) continue;
5267
- seen.add(key);
5268
- const item = { ...owner, git_blob_oid: evidence.git_blob_oid };
5269
- if (isTodoEvidenceUncommitted({ repoRoot, store, evidence })) {
5270
- if (evidenceAnchored(repo, evidence.git_blob_oid)) already += 1;
5271
- else { anchorEvidenceBlob(repo, evidence.git_blob_oid); anchored.push(item); }
5272
- continue;
5273
- }
5274
- try {
5275
- gitSync(['cat-file', '-e', evidence.git_blob_oid], { cwd: repo, stdio: 'ignore' });
5276
- } catch {
5277
- missing.push(item);
5278
- }
5279
- }
5280
- const result = { schema: 'lattice.todo_evidence_anchor_result.v1', project_id: store.project_id,
5281
- anchored, already, missing, result_digest: '' };
5282
- result.result_digest = todoSelfDigest(result, 'result_digest');
5283
- return result;
5284
- }
5285
-
5286
4946
  async function verify({ repoRoot, requestedPlanKey }) {
5287
- const store = await readTodoStore({ repoRoot });
4947
+ // k4: the full history checks (hash chain, canonical bytes, whole-snapshot comparison) run only here, on request.
4948
+ const store = await readTodoStore({ repoRoot, verifyHistory: true });
5288
4949
  const members = selectMembers(store, requestedPlanKey);
5289
4950
  // note chainはlifecycle storeと独立だが、verifyは両方を検査する。破損を空扱いしない。
5290
4951
  for (const member of members) {
5291
4952
  await readTodoNoteEvents({ repoRoot, planKey: member.plan.plan_key });
5292
4953
  }
5293
4954
  const verifiedSourceInventories = new Map();
5294
- const uncommittedEvidence = [];
5295
4955
  for (const member of members) {
5296
4956
  const planKey = member.descriptor.plan_key;
5297
- // a12: evidence waiting for a commit is an item; missing or changed evidence still refuses.
5298
- const pending = member.tasks.filter((task) => task.evidence_unverified
5299
- && isTodoEvidenceUncommitted({ repoRoot, store, evidence: task.evidence }));
5300
- for (const { task_id: taskId, evidence } of pending) {
5301
- uncommittedEvidence.push({ plan_key: planKey, task_id: taskId, ...uncommittedEvidenceItem(repoRoot, store, evidence) });
5302
- }
5303
- for (const { phase_id: phaseId, decision_evidence: evidence } of member.phases) {
5304
- if (decisionEvidenceState(repoRoot, store, evidence) !== 'uncommitted') continue;
5305
- uncommittedEvidence.push({ plan_key: planKey, phase_id: phaseId, ...uncommittedEvidenceItem(repoRoot, store, evidence) });
5306
- }
5307
- const unverified = member.tasks.find((task) => task.evidence_unverified && !pending.includes(task));
5308
- if (unverified !== undefined) {
5309
- throw new TodoStoreError('STORE_INCONSISTENT', 'evidence_unverified', 'evidence_unverified', {
5310
- plan_key: member.descriptor.plan_key,
5311
- task_id: unverified.task_id,
5312
- });
5313
- }
5314
4957
  if (member.revision !== null) {
5315
4958
  switch (member.revision.schema) {
5316
4959
  case 'lattice.todo_revision.v1':
@@ -5389,7 +5032,8 @@ async function verify({ repoRoot, requestedPlanKey }) {
5389
5032
  requested_plan_key: requestedPlanKey,
5390
5033
  verified_members: verifiedMembers,
5391
5034
  snapshot_stale: verifiedMembers.some((member) => member.snapshot_stale),
5392
- uncommitted_evidence: uncommittedEvidence,
5035
+ // shortcut: constant [] so v4 readers keep working; drop the key with the next verify schema bump.
5036
+ uncommitted_evidence: [],
5393
5037
  result_digest: '',
5394
5038
  };
5395
5039
  result.result_digest = todoSelfDigest(result, 'result_digest');
@@ -5397,15 +5041,12 @@ async function verify({ repoRoot, requestedPlanKey }) {
5397
5041
  }
5398
5042
 
5399
5043
  // `todo verify`の人間向け1行。--jsonと同じresultから導く(verifyは不整合を例外で拒否するので、
5400
- // ここへ届くのは検証が通った結果だけ。注意が要るのはsnapshot古さとcommit前の証拠)。
5044
+ // ここへ届くのは検証が通った結果だけ。注意が要るのはsnapshot古さだけ)。
5401
5045
  function verifyVerdictLine(result) {
5402
5046
  const members = result.verified_members.map((member) => `${member.plan_key} ${member.reconciliation_state}${
5403
5047
  member.reconciliation_state === 'reconciled' ? '' : ', nothing to do'}`);
5404
5048
  const notes = [];
5405
5049
  if (result.snapshot_stale) notes.push('snapshot stale');
5406
- if (result.uncommitted_evidence.length > 0) {
5407
- notes.push(`${result.uncommitted_evidence.length} uncommitted evidence (commit it, then rerun)`);
5408
- }
5409
5050
  const count = result.verified_members.length;
5410
5051
  return `todo verify: ${notes.length === 0 ? 'ok' : 'attention'}, ${count} plan${count === 1 ? '' : 's'} verified`
5411
5052
  + `${notes.map((note) => `, ${note}`).join('')} (${members.join('; ')})`;
@@ -5820,30 +5461,19 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
5820
5461
  kind: 'phase_review', payload: { reason: flags.reason } });
5821
5462
  } else if (argv[0] === 'phase' && ['accept', 'reject'].includes(argv[1])) {
5822
5463
  const outcome = argv[1];
5823
- const flags = matchFlagCommand(argv, ['phase', outcome], {
5824
- known: ['plan', 'phase', 'input', 'evidence', 'message', 'reason'], required: ['plan', 'phase'],
5825
- });
5464
+ const flags = matchFlagCommand(argv, ['phase', outcome], TODO_FLAG_SPECS[`phase ${outcome}`]);
5826
5465
  const reasonFits = outcome === 'accept' ? flags?.reason === undefined
5827
5466
  : typeof flags?.reason === 'string' && flags.reason.length > 0;
5828
- const base = flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.phase);
5829
- if (base && isAuthoringPathToken(flags.input) && flags.evidence === undefined && flags.message === undefined
5830
- && flags.reason === undefined) {
5831
- action = (repoRoot) => phaseDecision({
5832
- repoRoot, env, planKey: flags.plan, phaseId: flags.phase,
5833
- outcome, inputRef: flags.input,
5834
- });
5835
- } else if (base && flags.input === undefined && flags.message === undefined
5836
- && isAuthoringPathToken(flags.evidence) && reasonFits) {
5837
- action = (repoRoot) => phaseDecisionFromEvidence({
5838
- repoRoot, env, planKey: flags.plan, phaseId: flags.phase,
5839
- outcome, evidenceRef: flags.evidence, reason: flags.reason ?? null,
5840
- });
5841
- } else if (base && flags.input === undefined && flags.evidence === undefined
5842
- && typeof flags.message === 'string' && flags.message.length > 0 && reasonFits) {
5843
- action = (repoRoot) => phaseDecisionFromEvidence({
5844
- repoRoot, env, planKey: flags.plan, phaseId: flags.phase,
5845
- outcome, evidenceMessage: flags.message, reason: flags.reason ?? null,
5846
- });
5467
+ const textFits = flags !== null && (flags.message === undefined || flags.evidence === undefined)
5468
+ && (flags.message === undefined || (typeof flags.message === 'string' && flags.message.length > 0))
5469
+ && (flags.evidence === undefined || isAuthoringPathToken(flags.evidence));
5470
+ if (flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.phase) && reasonFits && textFits) {
5471
+ action = async (repoRoot) => {
5472
+ const message = flags.evidence === undefined ? flags.message ?? null : await readEvidenceText(repoRoot, flags.evidence);
5473
+ const result = await phaseDecision({ repoRoot, env, planKey: flags.plan, phaseId: flags.phase,
5474
+ outcome, message, reason: flags.reason ?? null });
5475
+ return flags.evidence === undefined ? result : retiredEvidenceFlag(stderr, `todo phase ${outcome}`, result);
5476
+ };
5847
5477
  }
5848
5478
  } else if (argv[0] === 'phase' && argv[1] === 'reopen' && phaseReopenFlags(argv) !== null) {
5849
5479
  const flags = phaseReopenFlags(argv);
@@ -5878,19 +5508,19 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
5878
5508
  }
5879
5509
  } else if (argv[0] === 'done') {
5880
5510
  const flags = matchFlagCommand(argv, ['done'], DONE_FLAG_SPEC);
5881
- // u03 A58: both, one or neither of --evidence/--message is accepted.
5882
5511
  if (flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task)
5512
+ && (flags.message === undefined || flags.evidence === undefined)
5883
5513
  && (flags.evidence === undefined || isAuthoringPathToken(flags.evidence))
5884
5514
  && (flags['test-result'] === undefined || isAuthoringPathToken(flags['test-result']))) {
5885
5515
  action = (repoRoot) => mutateUnlessUnchanged({ repoRoot, env, planKey: flags.plan, taskId: flags.task,
5886
5516
  kind: 'done', dropped: (recorded) => doneDropped({ repoRoot, flags, recorded }),
5887
5517
  action: async () => {
5888
- await enforcedDoneGate({ repoRoot, planKey: flags.plan, flags });
5889
- return mutate({
5518
+ const result = await mutate({
5890
5519
  repoRoot, env, planKey: flags.plan, taskId: flags.task, kind: 'done', payload: 'authored',
5891
- ...await doneEvidenceInput({ repoRoot, flags }),
5520
+ message: await doneMessage({ repoRoot, flags }),
5892
5521
  testResultRef: flags['test-result'] ?? null,
5893
5522
  });
5523
+ return flags.evidence === undefined ? result : retiredEvidenceFlag(stderr, 'todo done', result);
5894
5524
  } });
5895
5525
  }
5896
5526
  }
@@ -5907,7 +5537,7 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
5907
5537
  action = (repoRoot) => mutateUnlessUnchanged({ repoRoot, env, planKey: flags.plan, taskId: flags.task,
5908
5538
  kind: 'block', dropped: reasonDropped(flags.reason), action: async () => withBlockGuidance(await mutate({
5909
5539
  repoRoot, env, planKey: flags.plan, taskId: flags.task,
5910
- kind: 'block', payload: { reason: flags.reason }, evidenceRef: null,
5540
+ kind: 'block', payload: { reason: flags.reason },
5911
5541
  })) });
5912
5542
  }
5913
5543
  } else if (argv[0] === 'add') {
@@ -5929,21 +5559,9 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
5929
5559
  action = (repoRoot) => mutateUnlessUnchanged({ repoRoot, env, planKey: flags.plan, taskId: flags.task,
5930
5560
  kind: 'unblock', action: () => mutate({
5931
5561
  repoRoot, env, planKey: flags.plan, taskId: flags.task,
5932
- kind: 'unblock', payload: {}, evidenceRef: null,
5562
+ kind: 'unblock', payload: {},
5933
5563
  }) });
5934
5564
  }
5935
- } else if (argv[0] === 'evidence' && argv[1] === 'anchor'
5936
- && matchFlagCommand(argv, ['evidence', 'anchor'], TODO_FLAG_SPECS['evidence anchor']) !== null) {
5937
- action = (repoRoot) => evidenceAnchor({ repoRoot });
5938
- } else if (argv[0] === 'evidence' && argv[1] === 'promote') {
5939
- const flags = matchFlagCommand(argv, ['evidence', 'promote'], TODO_FLAG_SPECS['evidence promote']);
5940
- if (flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task)
5941
- && isAuthoringPathToken(flags.evidence)) {
5942
- action = (repoRoot) => mutate({
5943
- repoRoot, env, planKey: flags.plan, taskId: flags.task,
5944
- kind: 'done', payload: 'evidence_promotion', evidenceRef: flags.evidence,
5945
- });
5946
- }
5947
5565
  } else if (argv[0] === 'reopen') {
5948
5566
  const flags = matchFlagCommand(argv, ['reopen'], TODO_FLAG_SPECS.reopen);
5949
5567
  if (flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task)
@@ -6005,7 +5623,7 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
6005
5623
  } catch (error) {
6006
5624
  if (error instanceof TodoStoreError || (typeof error?.code === 'string'
6007
5625
  && error.detail !== null && typeof error.detail === 'object')) {
6008
- return typedFailure(stderr, error, { ...guidanceContext(argv, env), enforcedPlans: await enforcedPlanKeys(cwd) });
5626
+ return typedFailure(stderr, error, guidanceContext(argv, env));
6009
5627
  }
6010
5628
  // 漏れた`fetch failed`もTypeErrorで届く。呼び出し側の契約違反と答えず、内部故障として観測口へ渡す。
6011
5629
  if (error instanceof TypeError && cliFailureClass(error) !== 'transport') {