@quolu/lattice 0.80.0 → 0.82.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.
@@ -0,0 +1,175 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+
4
+ import { canonicalizeTodoArtifact, exactRecord, isTodoIdentifier, todoSelfDigest } from './todo-contracts.mjs';
5
+ import { gitSync } from './git-process.mjs';
6
+ import { readAuthoringJsonFile, repairAuthoringArtifact } from './todo-authoring-input.mjs';
7
+ import { validatePlanCreateInput } from './project-cli.mjs';
8
+ import {
9
+ compilePhaseMigration, planSeed, readPlanBackchainBinding, rebindCarriedWork,
10
+ } from './plan-backchain.mjs';
11
+ import {
12
+ applyPhaseTodoRevision, buildTodoPlan, createTodoStoreWriter, readTodoStore, TodoStoreError,
13
+ } from './todo-store.mjs';
14
+ import { phaseTodoRevisionPlanVersion, validatePhaseTodoRevision } from './todo-revision.mjs';
15
+
16
+ export { validateBindingCarry } from './plan-binding-carry.mjs';
17
+
18
+ const INPUT_SCHEMA = 'lattice.plan_revise_input.v1';
19
+
20
+ function fail(reason, pointer, detail = {}) {
21
+ throw new TodoStoreError('INPUT_INVALID', reason, undefined, { pointer, ...detail });
22
+ }
23
+
24
+ export function compilePlanRevision({ member, input }) {
25
+ if (!exactRecord(input, ['schema', 'desired', 'continuity']) || input.schema !== INPUT_SCHEMA) {
26
+ fail('plan_revise_schema_invalid', '/', { expected: INPUT_SCHEMA });
27
+ }
28
+ const desired = repairAuthoringArtifact(input.desired);
29
+ try { validatePlanCreateInput(desired); }
30
+ catch (error) {
31
+ if (typeof error?.detail?.pointer === 'string') {
32
+ error.detail.pointer = `/desired${error.detail.pointer === '/' ? '' : error.detail.pointer}`;
33
+ }
34
+ throw error;
35
+ }
36
+ if (member === undefined) fail('plan_not_active', '/desired/plan_key');
37
+ if (member.plan.schema === 'lattice.todo_plan.v6'
38
+ || member.journal.events[0].schema === 'lattice.todo_event.v2'
39
+ || [...member.plan.tasks, ...desired.tasks].some((task) => task.narrative_anchor !== null)) {
40
+ fail('plan_revise_requires_source_revision', '/desired/tasks', {
41
+ next_action: `lattice todo revise-phase --plan ${desired.plan_key} --input <phase-revision.json>`,
42
+ });
43
+ }
44
+ if (member.plan.schema !== 'lattice.todo_plan.v7') {
45
+ fail('predecessor_plan_schema_unsupported', '/desired/plan_key');
46
+ }
47
+ if (desired.project_id !== member.plan.project_id || desired.plan_key !== member.plan.plan_key) {
48
+ fail('plan_revise_identity_mismatch', '/desired/plan_key');
49
+ }
50
+ if (!Array.isArray(input.continuity) || input.continuity.length !== member.plan.tasks.length) {
51
+ fail('plan_revise_continuity_incomplete', '/continuity', {
52
+ expected: { task_ids: member.plan.tasks.map(({ task_id }) => task_id) },
53
+ });
54
+ }
55
+ const oldIds = new Set(member.plan.tasks.map(({ task_id }) => task_id));
56
+ const decisions = new Map();
57
+ for (const [index, entry] of input.continuity.entries()) {
58
+ if (!exactRecord(entry, ['task_id', 'policy', 'reason']) || !isTodoIdentifier(entry.task_id)
59
+ || !['carry', 'reset', 'retire'].includes(entry.policy)
60
+ || typeof entry.reason !== 'string' || entry.reason.trim().length === 0
61
+ || !oldIds.has(entry.task_id) || decisions.has(entry.task_id)) {
62
+ fail('plan_revise_continuity_invalid', `/continuity/${index}`);
63
+ }
64
+ decisions.set(entry.task_id, entry.policy);
65
+ }
66
+ const desiredIds = new Set(desired.tasks.map(({ task_id }) => task_id));
67
+ const taskMigration = member.plan.tasks.map(({ task_id: id }) => {
68
+ const policy = decisions.get(id);
69
+ if ((policy === 'retire') === desiredIds.has(id)) {
70
+ fail('plan_revise_removed_task_mismatch', '/continuity', { task_id: id });
71
+ }
72
+ return { from_task_id: id, to_task_id: policy === 'retire' ? 'removed' : id,
73
+ state_policy: policy === 'retire' ? 'removed'
74
+ : policy === 'carry' ? 'carry_reconciled_metadata' : 'reset_pending' };
75
+ });
76
+ const predecessor = {
77
+ plan_digest: member.plan.plan_digest,
78
+ journal_head_digest: member.journal.events.at(-1).event_digest,
79
+ plan_version: member.plan.plan_version,
80
+ };
81
+ const seed = planSeed(desired, predecessor.plan_digest);
82
+ const phaseMigration = compilePhaseMigration(member.plan, seed, taskMigration);
83
+ const version = phaseTodoRevisionPlanVersion({
84
+ projectId: desired.project_id, planKey: desired.plan_key, predecessor,
85
+ desiredPlan: seed, taskMigration, phaseMigration,
86
+ });
87
+ const revision = {
88
+ schema: 'lattice.phase_todo_revision.v5', project_id: desired.project_id,
89
+ plan_key: desired.plan_key, predecessor,
90
+ desired_plan: buildTodoPlan({ ...seed, plan_version: version }),
91
+ task_migration: taskMigration, phase_migration: phaseMigration, revision_digest: '',
92
+ };
93
+ revision.revision_digest = todoSelfDigest(revision, 'revision_digest');
94
+ return revision;
95
+ }
96
+
97
+ export async function planReviseSchema() {
98
+ return JSON.parse(await readFile(new URL('../docs/schemas/lattice.plan_revise_input.v1.schema.json', import.meta.url)));
99
+ }
100
+
101
+ export async function runPlanRevise({ cwd, inputRef, stdout, dryRun = false, env = process.env }) {
102
+ let repoRoot;
103
+ try {
104
+ repoRoot = path.resolve(gitSync(['rev-parse', '--show-toplevel'], {
105
+ cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'],
106
+ }).replace(/\r?\n$/u, ''));
107
+ } catch { throw new TodoStoreError('REPO_UNRESOLVED', 'git_toplevel_unresolved'); }
108
+ const input = await readAuthoringJsonFile(repoRoot, inputRef, { invalidCode: 'INPUT_INVALID' });
109
+ const store = await readTodoStore({ repoRoot });
110
+ const member = store.members.find(({ plan }) => plan.plan_key === input?.desired?.plan_key);
111
+ const revision = compilePlanRevision({ member, input });
112
+ if (await readPlanBackchainBinding({ repoRoot, plan: member.plan }) !== null) {
113
+ fail('plan_revise_requires_backchain', '/desired/plan_key', {
114
+ next_action: 'lattice plan backchain --input <file> --json',
115
+ });
116
+ }
117
+ const unchanged = input.continuity.every(({ policy }) => policy === 'carry')
118
+ && canonicalizeTodoArtifact(planSeed(input.desired, null))
119
+ === canonicalizeTodoArtifact(planSeed(member.plan, null));
120
+ if (!unchanged && !validatePhaseTodoRevision(revision)) fail('plan_revise_artifact_invalid', '/');
121
+ if (!unchanged) {
122
+ const { todoTaskCarrySemantics } = await import('./todo-store-view.mjs');
123
+ const idMap = new Map(revision.task_migration.map(({ from_task_id, to_task_id }) => [from_task_id, to_task_id]));
124
+ const removedTaskIds = new Set(revision.task_migration.filter(({ state_policy }) => state_policy === 'removed')
125
+ .map(({ from_task_id }) => from_task_id));
126
+ for (const [index, entry] of input.continuity.entries()) {
127
+ if (entry.policy !== 'carry') continue;
128
+ const before = todoTaskCarrySemantics(member.plan, entry.task_id, idMap,
129
+ { reconciliationMetadata: true, includeDesignMemo: false, removedTaskIds });
130
+ const after = todoTaskCarrySemantics(revision.desired_plan, entry.task_id, new Map(),
131
+ { reconciliationMetadata: true, includeDesignMemo: false });
132
+ if (canonicalizeTodoArtifact(before) !== canonicalizeTodoArtifact(after)) {
133
+ throw new TodoStoreError('REVISION_INVALID', 'carry_semantics_changed', undefined, {
134
+ pointer: `/continuity/${index}`, task_id: entry.task_id,
135
+ expected: { policy: 'reset' }, actual: { policy: 'carry' },
136
+ next_action: 'set_the_reported_continuity_policy_to_reset_then_rerun_plan_revise_dry_run',
137
+ });
138
+ }
139
+ }
140
+ }
141
+ let applied = null;
142
+ let reboundTaskIds = [];
143
+ if (!dryRun) {
144
+ if (!unchanged) {
145
+ applied = await applyPhaseTodoRevision({ repoRoot,
146
+ writer: createTodoStoreWriter({ caller: 'g5-authoring' }), revision,
147
+ actor: input.desired.actor, recordedAt: input.desired.recorded_at,
148
+ });
149
+ }
150
+ try {
151
+ reboundTaskIds = await rebindCarriedWork({ repoRoot, planKey: revision.plan_key, env,
152
+ reason: '工程改訂後のplan versionへ作業中ToDoを結び直す',
153
+ failureCode: 'PLAN_REBIND_PENDING' });
154
+ } catch (error) {
155
+ // 公開後に起きたStoreの失敗は、改訂が確定済みであることを必ず報告する(2026-11-07
156
+ // 初回使用: rebind読込の素のbinding_staleが公開済み事実を隠した)
157
+ if (error instanceof TodoStoreError) {
158
+ error.detail = { ...error.detail, revision_applied: !unchanged,
159
+ revision_digest: unchanged ? null : revision.revision_digest,
160
+ plan_version: unchanged ? member.plan.plan_version : revision.desired_plan.plan_version };
161
+ }
162
+ throw error;
163
+ }
164
+ }
165
+ const result = {
166
+ schema: unchanged ? 'lattice.plan_revise_unchanged.v1' : 'lattice.plan_revise_result.v1',
167
+ project_id: revision.project_id, plan_key: revision.plan_key,
168
+ plan_version: unchanged ? member.plan.plan_version : revision.desired_plan.plan_version,
169
+ dry_run: dryRun, revision: unchanged ? null : revision, applied,
170
+ continuity: input.continuity, rebound_task_ids: reboundTaskIds, result_digest: '',
171
+ };
172
+ result.result_digest = todoSelfDigest(result, 'result_digest');
173
+ stdout.write(`${JSON.stringify(result)}\n`);
174
+ return 0;
175
+ }
@@ -27,9 +27,11 @@ import { ensureTodoDashboardActivity } from './todo-dashboard-registry.mjs';
27
27
  import { reportProjectDashboardDelivery } from './dashboard-delivery.mjs';
28
28
  import { resolveProjectIdentity } from './project-identity.mjs';
29
29
  import {
30
+ appendAuthoredTodoPlan,
30
31
  buildTodoPlan,
31
32
  createTodoStoreWriter,
32
33
  initializeAuthoredTodoStore,
34
+ isUninitializedTodoStore,
33
35
  isPhaselessTodoPlanSchema,
34
36
  readTodoIndependenceArtifact,
35
37
  readTodoStore,
@@ -121,7 +123,7 @@ export function validateProjectStatus(value) {
121
123
  && typeof value.next_action.reason === 'string' && value.next_action.reason.length > 0;
122
124
  }
123
125
  return value.project !== null && isTodoIdentifier(value.project.project_id)
124
- && value.can_create_plan === false && exactRecord(value.next_action, ['command', 'reason'])
126
+ && value.can_create_plan === true && exactRecord(value.next_action, ['command', 'reason'])
125
127
  && typeof value.next_action.reason === 'string' && value.next_action.reason.length > 0
126
128
  && (value.state !== 'active_run' || value.active_runs.length > 0)
127
129
  && (value.state !== 'ready' || value.active_runs.length === 0);
@@ -252,7 +254,10 @@ async function resolveProjectState({ cwd, cliVersion, diagnoseStructureArtifacts
252
254
  try { manifestState = await lstat(manifestAbsolute); } catch (error) {
253
255
  if (error?.code !== 'ENOENT') return invalid('manifest_unreadable');
254
256
  }
255
- if (storeState === undefined && manifestState === undefined) {
257
+ let uninitialized;
258
+ try { uninitialized = await isUninitializedTodoStore({ repoRoot }); }
259
+ catch { return invalid('store_unreadable'); }
260
+ if (uninitialized) {
256
261
  return { exitCode: 0, repoRoot, store: null, todo: null, result: statusResult({
257
262
  cli: { available: true, version: cliVersion },
258
263
  project: { root: repoRoot, git_head: gitHead(repoRoot), project_id: null },
@@ -318,7 +323,7 @@ async function resolveProjectState({ cwd, cliVersion, diagnoseStructureArtifacts
318
323
  plan_key: entry.plan_key, plan_version: entry.plan_version,
319
324
  })),
320
325
  active_runs: activeRuns,
321
- can_create_plan: false,
326
+ can_create_plan: true,
322
327
  next_action: next,
323
328
  });
324
329
  return { exitCode: 0, repoRoot, store, todo, result };
@@ -596,10 +601,7 @@ function describeCreateInputViolation(value) {
596
601
  return null;
597
602
  }
598
603
 
599
- export async function runPlanCreate({ cwd, inputRef, stdout, inputValue = null, featureChain = null }) {
600
- const repoRoot = resolveRepoRoot(cwd);
601
- if (repoRoot === null) throw new TodoStoreError('REPO_UNRESOLVED', 'git_toplevel_unresolved');
602
- const input = inputValue ?? await readCanonicalInput(repoRoot, inputRef);
604
+ export function validatePlanCreateInput(input) {
603
605
  if (input?.schema !== MEMO_PHASE_CREATE_INPUT_SCHEMA) {
604
606
  throw new TodoStoreError('INPUT_INVALID', 'plan_create_schema_retired', undefined, {
605
607
  violation_kind: 'const_mismatch', pointer: '/schema',
@@ -631,6 +633,13 @@ export async function runPlanCreate({ cwd, inputRef, stdout, inputValue = null,
631
633
  next_action: 'correct_the_reported_pointer_then_rerun_plan_create',
632
634
  });
633
635
  }
636
+ }
637
+
638
+ export async function runPlanCreate({ cwd, inputRef, stdout, inputValue = null, featureChain = null }) {
639
+ const repoRoot = resolveRepoRoot(cwd);
640
+ if (repoRoot === null) throw new TodoStoreError('REPO_UNRESOLVED', 'git_toplevel_unresolved');
641
+ const input = inputValue ?? await readCanonicalInput(repoRoot, inputRef);
642
+ validatePlanCreateInput(input);
634
643
  // dispatch_shapeは結果へ載せる観測であり、直列度では初期化を拒まない(ADR 0180)。
635
644
  const dispatchShape = computeTodoDispatchShapeForPlan({
636
645
  projectId: input.project_id,
@@ -639,10 +648,9 @@ export async function runPlanCreate({ cwd, inputRef, stdout, inputValue = null,
639
648
  hardDependencies: input.hard_dependencies,
640
649
  joins: input.joins,
641
650
  });
642
- const store = await initializeAuthoredTodoStore({
651
+ const options = {
643
652
  repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }),
644
- projectId: input.project_id, repositories: [{ repo_id: 'self', path: '.' }],
645
- plan: {
653
+ plan: buildTodoPlan({
646
654
  schema: input.schema === MEMO_PHASE_CREATE_INPUT_SCHEMA ? 'lattice.todo_plan.v7'
647
655
  : input.schema === DECOUPLED_PHASE_CREATE_INPUT_SCHEMA ? 'lattice.todo_plan.v5'
648
656
  : input.schema === PHASE_CREATE_INPUT_SCHEMA
@@ -654,11 +662,19 @@ export async function runPlanCreate({ cwd, inputRef, stdout, inputValue = null,
654
662
  MEMO_PHASE_CREATE_INPUT_SCHEMA].includes(input.schema) ? { phases: input.phases } : {}),
655
663
  ...([DECOUPLED_PHASE_CREATE_INPUT_SCHEMA, MEMO_PHASE_CREATE_INPUT_SCHEMA].includes(input.schema)
656
664
  ? { phase_accept_dependencies: input.phase_accept_dependencies } : {}),
657
- },
665
+ }),
658
666
  genesis: { actor: input.actor, recorded_at: input.recorded_at, provenance: null },
659
667
  ...(featureChain === null ? {} : { featureChain }),
668
+ };
669
+ const manifest = await lstat(path.join(repoRoot, MANIFEST_REF)).catch((error) => {
670
+ if (!['ENOENT', 'ENOTDIR'].includes(error?.code)) throw error;
671
+ return null;
660
672
  });
661
- const member = store.members[0];
673
+ const store = manifest === null
674
+ ? await initializeAuthoredTodoStore({ ...options,
675
+ projectId: input.project_id, repositories: [{ repo_id: 'self', path: '.' }] })
676
+ : await appendAuthoredTodoPlan(options);
677
+ const member = store.members.find(({ plan }) => plan.plan_key === input.plan_key);
662
678
  const result = {
663
679
  schema: CREATE_RESULT_SCHEMA, project_id: store.project_id,
664
680
  plan_key: member.plan.plan_key, plan_version: member.plan.plan_version,
@@ -12,6 +12,8 @@ import path from 'node:path';
12
12
 
13
13
  import { canonicalizeArtifact, digestArtifact } from './artifact-contracts.mjs';
14
14
  import { buildExecutorPackets } from './runtime-engine.mjs';
15
+ import { verifyRunEventChain } from './runtime-event-store.mjs';
16
+ import { validateRuntimeControlJournal } from './runtime-control-store.mjs';
15
17
  import {
16
18
  RUNTIME_CONFLICT_KINDS,
17
19
  validateExecutorPacket,
@@ -93,6 +95,42 @@ function selfDigestValid(value, field) {
93
95
  return digestArtifact(body) === value[field];
94
96
  }
95
97
 
98
+ function activationPrefixEvidence(events, expectedDigest, { stream, runId, plan }) {
99
+ plan ??= {};
100
+ const isArray = Array.isArray(events);
101
+ const index = isArray ? events.findIndex((event) => event?.event_digest === expectedDigest) : -1;
102
+ const actual = isArray ? events.at(-1)?.event_digest : null;
103
+ const chainValid = isArray && (stream === 'run'
104
+ ? verifyRunEventChain({ events }).valid && events[0]?.run_id === runId
105
+ : validateRuntimeControlJournal(events, runId));
106
+ const conflicting = chainValid && index >= 0 ? events.slice(index + 1).find((event) => {
107
+ if (stream === 'run') {
108
+ return event.plan_epoch > plan.plan_epoch
109
+ || ['run_closed', 'intake_frozen'].includes(event.kind)
110
+ || (event.kind === 'intake_resumed' && event.plan_epoch === plan.plan_epoch)
111
+ || (event.kind === 'plan_recompiled' && event.plan_epoch >= plan.plan_epoch
112
+ && (event.plan_epoch !== plan.plan_epoch
113
+ || event.payload.new_plan_digest !== plan.plan_digest
114
+ || event.subject.ref !== plan.plan_ref));
115
+ }
116
+ return ['supervisor_stopped', 'supervisor_recovery_barrier', 'write_gate_committed'].includes(event.kind)
117
+ || (['epoch_activated', 'intake_resumed'].includes(event.kind)
118
+ && event.payload.plan_epoch >= plan.plan_epoch);
119
+ }) : null;
120
+ return {
121
+ expected_tail: expectedDigest, actual_tail: HEX_DIGEST.test(actual ?? '') ? actual : null,
122
+ expected_in_chain: index >= 0, chain_valid: chainValid,
123
+ conflicting_event_digest: conflicting?.event_digest ?? null,
124
+ };
125
+ }
126
+
127
+ function activationEvidence(runEvents, controlEvents, runDigest, controlDigest, runId, plan) {
128
+ return {
129
+ run: activationPrefixEvidence(runEvents, runDigest, { stream: 'run', runId, plan }),
130
+ control: activationPrefixEvidence(controlEvents, controlDigest, { stream: 'control', runId, plan }),
131
+ };
132
+ }
133
+
96
134
  export function validateRuntimeFindingRecord(value) {
97
135
  if (!exactRecord(value, ['schema', 'finding_id', 'run_id', 'plan_epoch',
98
136
  'source_checkpoint_digest', 'observed_event_digest', 'finding', 'recorded_by', 'finding_digest'])
@@ -431,13 +469,12 @@ export async function activateEpochOneStore({
431
469
  }
432
470
  const runEvents = await readRegularJson(path.join(runDir, 'events.json'), 'run events');
433
471
  const controlEvents = await readRegularJson(path.join(runDir, 'control-events.json'), 'runtime control events');
434
- const controlHead = controlEvents.at?.(-1);
435
- if (!Array.isArray(runEvents) || runEvents.at(-1)?.event_digest !== activationRunEventDigest
436
- || !Array.isArray(controlEvents)
437
- || controlHead?.event_digest !== activationControlEventDigest
438
- || controlHead?.kind !== 'supervisor_activated'
439
- || !selfDigestValid(controlHead, 'event_digest')) {
440
- fail('INVALID_RUN_STORE', 'activation pointerがdurable event headへbindしない');
472
+ const evidence = activationEvidence(runEvents, controlEvents, activationRunEventDigest,
473
+ activationControlEventDigest, request?.request_id, compileArtifact?.plan);
474
+ if (!Object.values(evidence).every((entry) => entry.chain_valid && entry.expected_in_chain
475
+ && entry.conflicting_event_digest === null)
476
+ || controlEvents.find((event) => event.event_digest === activationControlEventDigest)?.kind !== 'supervisor_activated') {
477
+ fail('INVALID_RUN_STORE', `activation pointerがdurable event prefixへbindしない: ${JSON.stringify(evidence)}`, evidence);
441
478
  }
442
479
  const normalizedMeta = normalizeActivationMeta(legacyMeta, request, compileArtifact);
443
480
  const bundle = buildEpochOneBundle({ request, compileArtifact, legacyMeta: normalizedMeta });
@@ -507,7 +544,7 @@ export async function activateEpochOneStore({
507
544
  };
508
545
  meta.meta_digest = digestArtifact(meta);
509
546
  await replaceDurableJson(runDir, 'run-meta.json', meta);
510
- return { bundle, meta, pointer };
547
+ return { bundle, meta, pointer, activation_evidence: evidence };
511
548
  }
512
549
 
513
550
  /** pointerを正本としてactive bundleだけを読む。directory最大値へfallbackしない。 */
@@ -697,7 +734,7 @@ export async function stageSuccessorEpoch({ runDir, transactionId, bundle, recom
697
734
  }
698
735
 
699
736
  /**
700
- * staged successorをepoch historyへrenameし、durable event headsを確認してpointerを最後にcommitする。
737
+ * staged successorをepoch historyへrenameし、durable activation prefixを確認してpointerを最後にcommitする。
701
738
  * 同digest retryだけを許し、directory最大値や別transactionへfallbackしない。
702
739
  */
703
740
  export async function commitStagedSuccessorEpoch({ runDir, transactionId,
@@ -746,9 +783,12 @@ export async function commitStagedSuccessorEpoch({ runDir, transactionId,
746
783
  const controlEvents = typeof readActivationControlEvents === 'function'
747
784
  ? await readActivationControlEvents()
748
785
  : await readRegularJson(path.join(runDir, 'control-events.json'), 'runtime control events');
749
- if (!Array.isArray(runEvents) || runEvents.at(-1)?.event_digest !== activationRunEventDigest
750
- || !Array.isArray(controlEvents) || controlEvents.at(-1)?.event_digest !== activationControlEventDigest) {
751
- fail('EPOCH_ACTIVATION_INCOMPLETE', 'successor activation event headが未耐久化');
786
+ const evidence = activationEvidence(runEvents, controlEvents, activationRunEventDigest,
787
+ activationControlEventDigest, bundle.run_id, bundle.plan);
788
+ if (!Object.values(evidence).every((entry) => entry.chain_valid && entry.expected_in_chain
789
+ && entry.conflicting_event_digest === null)) {
790
+ fail('EPOCH_ACTIVATION_INCOMPLETE',
791
+ `successor activation event prefixが未耐久化又は矛盾: ${JSON.stringify(evidence)}`, evidence);
752
792
  }
753
793
  const epochsDir = path.join(runDir, 'epochs');
754
794
  const epochDir = path.join(epochsDir, String(bundle.plan_epoch).padStart(8, '0'));
@@ -776,7 +816,7 @@ export async function commitStagedSuccessorEpoch({ runDir, transactionId,
776
816
  };
777
817
  pointer.pointer_digest = digestArtifact(pointer);
778
818
  await replaceDurableJson(runDir, 'committed-epoch.json', pointer);
779
- return { bundle, pointer };
819
+ return { bundle, pointer, activation_evidence: evidence };
780
820
  }
781
821
 
782
822
  export async function commitReleaseEpochBarrier({ runDir, barrier }) {
@@ -40,7 +40,45 @@ export async function observeStartIdentityRaw(pid) {
40
40
  ? ['-NoProfile', '-NonInteractive', '-Command',
41
41
  `[System.Diagnostics.Process]::GetProcessById(${pid}).StartTime.ToUniversalTime().Ticks`]
42
42
  : ['-o', 'lstart=', '-p', String(pid)];
43
- const { stdout } = await execFileAsync(executable, args, { encoding: 'utf8', env: osObservationEnvironment() });
43
+ try {
44
+ const { stdout } = await execFileAsync(executable, args, { encoding: 'utf8', env: osObservationEnvironment() });
45
+ return stdout.trim();
46
+ } catch (error) {
47
+ // Another account's process denies its handle; its PID may be a reused dead owner's.
48
+ if (process.platform === 'win32') return observeStartIdentitySnapshotRaw(pid);
49
+ throw error;
50
+ }
51
+ }
52
+
53
+ // SYSTEM_PROCESS_INFORMATION: CreateTime at 32, UniqueProcessId at 80 (64-bit) / 68 (32-bit).
54
+ const WINDOWS_PROCESS_SNAPSHOT = `
55
+ using System; using System.Runtime.InteropServices;
56
+ public static class LatticeProcessSnapshot {
57
+ [DllImport("ntdll.dll")] static extern int NtQuerySystemInformation(int c, IntPtr b, int l, out int r);
58
+ public static long CreateTime(long pid) {
59
+ for (int length = 1 << 20; ; length *= 2) {
60
+ IntPtr buffer = Marshal.AllocHGlobal(length);
61
+ try {
62
+ int needed; int status = NtQuerySystemInformation(5, buffer, length, out needed);
63
+ if (status == unchecked((int)0xC0000004)) continue;
64
+ if (status != 0) throw new InvalidOperationException("NtQuerySystemInformation " + status);
65
+ for (IntPtr entry = buffer; ; ) {
66
+ if (Marshal.ReadIntPtr(entry, IntPtr.Size == 8 ? 80 : 68).ToInt64() == pid) return Marshal.ReadInt64(entry, 32);
67
+ int next = Marshal.ReadInt32(entry); if (next == 0) break; entry = IntPtr.Add(entry, next);
68
+ }
69
+ throw new ArgumentException("process not running: " + pid);
70
+ } finally { Marshal.FreeHGlobal(buffer); }
71
+ }
72
+ }
73
+ }`;
74
+
75
+ /** win32: handle-free start identity, identical to StartTime UTC ticks (both are the kernel CreateTime). */
76
+ export async function observeStartIdentitySnapshotRaw(pid) {
77
+ const script = `$ErrorActionPreference='Stop'; Add-Type -TypeDefinition '${WINDOWS_PROCESS_SNAPSHOT}'; `
78
+ + `[DateTime]::FromFileTimeUtc([LatticeProcessSnapshot]::CreateTime(${Number(pid)})).Ticks`;
79
+ // EncodedCommand keeps the C# quotes out of Windows command-line quoting.
80
+ const { stdout } = await execFileAsync('pwsh.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand',
81
+ Buffer.from(script, 'utf16le').toString('base64')], { encoding: 'utf8', env: osObservationEnvironment() });
44
82
  return stdout.trim();
45
83
  }
46
84
 
@@ -0,0 +1,23 @@
1
+ // 席の識別の唯一の置き場。AIは LATTICE_SEAT_ID を言い、機械が seat_id と状態の置き場を導く。
2
+ // 不正な値は拒否せず null に落とす(席が無名になるだけで、何も止めない)。
3
+ import { homedir } from 'node:os';
4
+ import path from 'node:path';
5
+
6
+ const SEAT_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
7
+
8
+ /** @returns {{ seat_id: string|null, state_dir: string }} */
9
+ export function resolveSeatIdentity(env = process.env) {
10
+ const raw = env.LATTICE_SEAT_ID;
11
+ const seat_id = typeof raw === 'string' && SEAT_ID.test(raw) ? raw : null;
12
+ const configured = env.LATTICE_CONFIG_DIR;
13
+ const state_dir = typeof configured === 'string' && path.isAbsolute(configured)
14
+ ? configured
15
+ : seat_id === null ? path.join(homedir(), '.lattice') : path.join(homedir(), '.lattice', 'seats', seat_id);
16
+ return Object.freeze({ seat_id, state_dir });
17
+ }
18
+
19
+ /** status / session-context の top-level へ混ぜる欄。未設定なら空(欄を出さない)。 */
20
+ export function seatIdentityFields(env = process.env) {
21
+ const { seat_id } = resolveSeatIdentity(env);
22
+ return seat_id === null ? {} : { seat_id };
23
+ }
@@ -38,14 +38,16 @@ function identified(owner) {
38
38
  }
39
39
 
40
40
  async function processIsDead(pid, startDigest) {
41
+ // Existence first: a PID freed after a failed observation may be reused before a later check.
42
+ try { process.kill(pid, 0); }
43
+ catch (error) { if (error?.code === 'ESRCH') return true; }
41
44
  try {
42
45
  const observed = await observeStartIdentityRaw(pid);
43
46
  if (observed) return hash(`${process.platform}:${observed}`) !== startDigest;
44
47
  } catch {
45
48
  // A failed observation cannot turn an existing PID into a dead owner.
46
49
  }
47
- try { process.kill(pid, 0); return false; }
48
- catch (error) { return error?.code === 'ESRCH'; }
50
+ return false;
49
51
  }
50
52
 
51
53
  async function readOwner(lockPath) {
@@ -35,6 +35,7 @@ export const AUTHORING_DIGEST_FIELDS = Object.freeze({
35
35
  'lattice.phase_todo_revision.v2': 'revision_digest',
36
36
  'lattice.phase_todo_revision.v3': 'revision_digest',
37
37
  'lattice.phase_todo_revision.v4': 'revision_digest',
38
+ 'lattice.phase_todo_revision.v5': 'revision_digest',
38
39
  'lattice.todo_revision_set.v1': 'revision_set_digest',
39
40
  'lattice.todo_revision_set.v2': 'revision_set_digest',
40
41
  'lattice.todo_revision_set.v3': 'revision_set_digest',
package/src/todo-cli.mjs CHANGED
@@ -191,8 +191,8 @@ const ACTOR_ENV_KEYS = Object.freeze([
191
191
  ]);
192
192
 
193
193
  /**
194
- * `revise` / `revise-set` / `revise-phase` / `migrate`が実際に受理する最新契約のJSON
195
- * Schemaを配布物から読む入口(`project-cli.mjs`の`runPlanCreateSchema`と同じ作法)。
194
+ * `revise` / `revise-set` / `revise-phase` / `migrate`が配布する名前付き入力契約のJSON
195
+ * Schemaを読む入口。受理するartifact版すべての列挙ではない(`project-cli.mjs`の`runPlanCreateSchema`と同じ作法)。
196
196
  *
197
197
  * schemaを取る手段がCLIに無いと、AIはsrcを読んで必須keyを数えるしかなくなる
198
198
  * (実運用で`phase_todo_revision.v3`の必須12 keyを試行錯誤で当てた)。storeは読まない
@@ -3677,6 +3677,7 @@ async function verify({ repoRoot, requestedPlanKey }) {
3677
3677
  case 'lattice.phase_todo_revision.v2':
3678
3678
  case 'lattice.phase_todo_revision.v3':
3679
3679
  case 'lattice.phase_todo_revision.v4':
3680
+ case 'lattice.phase_todo_revision.v5':
3680
3681
  verifiedSourceInventories.set(member.descriptor.plan_key,
3681
3682
  await verifyEffectivePhaseTodoRevisionSources({ repoRoot, member }));
3682
3683
  break;
@@ -3689,7 +3690,8 @@ async function verify({ repoRoot, requestedPlanKey }) {
3689
3690
  const reconciled = member.revision !== null;
3690
3691
  const sourceInventory = verifiedSourceInventories.get(member.descriptor.plan_key) ?? null;
3691
3692
  const phaseRevision = ['lattice.phase_todo_revision.v1', 'lattice.phase_todo_revision.v2',
3692
- 'lattice.phase_todo_revision.v3', 'lattice.phase_todo_revision.v4']
3693
+ 'lattice.phase_todo_revision.v3', 'lattice.phase_todo_revision.v4',
3694
+ 'lattice.phase_todo_revision.v5']
3693
3695
  .includes(member.revision?.schema);
3694
3696
  return {
3695
3697
  plan_key: member.descriptor.plan_key,
@@ -621,9 +621,11 @@ export async function readTodoPlanNotesForStatus(options = {}) {
621
621
  return summaries;
622
622
  }
623
623
 
624
- /** Gantt用に1 planのchain/historyを一度だけ読み、全task contextへ投影する。 */
624
+ /** 1 planを一度だけ読み全taskへ投影する。includeHistoryはbudget前の履歴も返す。 */
625
625
  export async function readTodoNoteContextsForPlan(options = {}) {
626
- if (!exactRecord(options, ['repoRoot', 'store', 'planKey'])
626
+ const keys = ['repoRoot', 'store', 'planKey'];
627
+ if (!(exactRecord(options, keys) || exactRecord(options, [...keys, 'includeHistory']))
628
+ || ('includeHistory' in options && typeof options.includeHistory !== 'boolean')
627
629
  || !isTodoIdentifier(options.planKey)
628
630
  || options.store === null || typeof options.store !== 'object') {
629
631
  throw new TypeError('todo note contexts read options invalid');
@@ -654,5 +656,8 @@ export async function readTodoNoteContextsForPlan(options = {}) {
654
656
  contexts: projected.map(({ context }) => context),
655
657
  archived: projected[0]?.archived ?? [],
656
658
  note_head_digest: chain.head_digest,
659
+ ...(options.includeHistory ? { histories: projected.map(({ context, history }) => ({
660
+ task_id: context.task_id, history,
661
+ })) } : {}),
657
662
  };
658
663
  }
@@ -296,15 +296,16 @@ export function validatePhaseTodoRevision(value) {
296
296
  const revisionV2 = value?.schema === 'lattice.phase_todo_revision.v2';
297
297
  const revisionV3 = value?.schema === 'lattice.phase_todo_revision.v3';
298
298
  const revisionV4 = value?.schema === 'lattice.phase_todo_revision.v4';
299
+ const revisionV5 = value?.schema === 'lattice.phase_todo_revision.v5';
299
300
  const keys = revisionV3 ? PHASE_REVISION_V3_KEYS
300
301
  : revisionV4 ? PHASE_REVISION_V4_KEYS : PHASE_REVISION_KEYS;
301
- if (!exactRecord(value, keys) || (!revisionV1 && !revisionV2 && !revisionV3 && !revisionV4)) return false;
302
+ if (!exactRecord(value, keys) || (!revisionV1 && !revisionV2 && !revisionV3 && !revisionV4 && !revisionV5)) return false;
302
303
  if (!isTodoIdentifier(value.project_id) || !isTodoIdentifier(value.plan_key)) return false;
303
304
  if (!validPredecessor(value.predecessor) || !validateTodoPlan(value.desired_plan)
304
305
  || !(revisionV3
305
306
  ? ['lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value.desired_plan.schema)
306
307
  : value.desired_plan.schema === (revisionV2 ? 'lattice.todo_plan.v5'
307
- : revisionV4 ? 'lattice.todo_plan.v7' : 'lattice.todo_plan.v4'))
308
+ : (revisionV4 || revisionV5) ? 'lattice.todo_plan.v7' : 'lattice.todo_plan.v4'))
308
309
  || value.desired_plan.project_id !== value.project_id
309
310
  || value.desired_plan.plan_key !== value.plan_key
310
311
  || value.desired_plan.predecessor_plan_digest !== value.predecessor.plan_digest
@@ -832,7 +833,7 @@ export function explainTodoRevision(value) {
832
833
  }
833
834
 
834
835
  /**
835
- * `lattice todo revise-phase`が受理する`lattice.phase_todo_revision.v1/v2/v3`を診断する。
836
+ * `lattice todo revise-phase`が受理する`lattice.phase_todo_revision.v1/v2/v3/v4/v5`を診断する。
836
837
  * 方針は`explainTodoRevision`と同じ——desired_planのgraph整合は単一reasonへ丸め、
837
838
  * v3で増える`runtime_task_migration`・`source_cutover_batch`・8-key reconciliationの
838
839
  * 各digestを個別に名指しする。
@@ -844,7 +845,8 @@ export function explainPhaseTodoRevision(value) {
844
845
  const revisionV2 = value.schema === 'lattice.phase_todo_revision.v2';
845
846
  const revisionV3 = value.schema === 'lattice.phase_todo_revision.v3';
846
847
  const revisionV4 = value.schema === 'lattice.phase_todo_revision.v4';
847
- if (!revisionV1 && !revisionV2 && !revisionV3 && !revisionV4) return reject('schema_mismatch', '/schema');
848
+ const revisionV5 = value.schema === 'lattice.phase_todo_revision.v5';
849
+ if (!revisionV1 && !revisionV2 && !revisionV3 && !revisionV4 && !revisionV5) return reject('schema_mismatch', '/schema');
848
850
  const keyCheck = explainKeys(value, revisionV3 ? PHASE_REVISION_V3_KEYS
849
851
  : revisionV4 ? PHASE_REVISION_V4_KEYS : PHASE_REVISION_KEYS, '');
850
852
  if (!keyCheck.valid) return keyCheck;
@@ -855,7 +857,7 @@ export function explainPhaseTodoRevision(value) {
855
857
  if (!validateTodoPlan(value.desired_plan)) return reject('desired_plan_invalid', '/desired_plan');
856
858
  const expectedPlanSchemas = revisionV3 ? ['lattice.todo_plan.v5', 'lattice.todo_plan.v7']
857
859
  : [revisionV2 ? 'lattice.todo_plan.v5'
858
- : revisionV4 ? 'lattice.todo_plan.v7' : 'lattice.todo_plan.v4'];
860
+ : (revisionV4 || revisionV5) ? 'lattice.todo_plan.v7' : 'lattice.todo_plan.v4'];
859
861
  if (!expectedPlanSchemas.includes(value.desired_plan.schema)) {
860
862
  return reject('desired_plan_schema_mismatch', '/desired_plan/schema');
861
863
  }