@quolu/lattice 0.98.0 → 0.100.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.
@@ -19,11 +19,13 @@ import { randomBytes } from 'node:crypto';
19
19
  import { fsyncDirectory } from './fs-dir-sync.mjs';
20
20
  import { renamePublishedFile, syncPublishedFile } from './fs-publish.mjs';
21
21
  import { LOCK_WAIT_MS, StoreLockError, withStoreLock } from './store-lock.mjs';
22
+ import { memoByFileIdentity } from './todo-version-memo.mjs';
22
23
  import {
23
24
  lstat, mkdir, open, readFile, readdir, realpath, rename, rm, rmdir,
24
25
  } from 'node:fs/promises';
25
26
  import path from 'node:path';
26
27
  import {
28
+ TODO_CHART_META_SCHEMA,
27
29
  TODO_COORDINATION_MODES,
28
30
  TODO_EVENT_KINDS,
29
31
  TODO_LIMITS,
@@ -38,6 +40,7 @@ import {
38
40
  isTodoRef,
39
41
  todoSelfDigest,
40
42
  validateEvidenceDescriptor,
43
+ validateTodoChartMeta,
41
44
  validateTodoImportSource,
42
45
  validateTodoEvent,
43
46
  validateTodoManifest,
@@ -151,7 +154,7 @@ function rejectUnsupportedRevisionSchema(value, { family, supportedSchemas }) {
151
154
 
152
155
  // Reader registration (newer-value-says-upgrade): the newest schema of each Store record family this
153
156
  // reader knows. Bump it in the same diff that teaches the validator a new version.
154
- export const NEWEST_KNOWN_TODO_SCHEMA = Object.freeze({ todo_event: 4, todo_plan: 8, todo_manifest: 2, todo_notice_acks: 2, todo_notice_waits: 1 });
157
+ export const NEWEST_KNOWN_TODO_SCHEMA = Object.freeze({ todo_event: 4, todo_plan: 8, todo_manifest: 2, todo_notice_acks: 2, todo_notice_waits: 1, chart_meta: 1 });
155
158
  const NEWER_SCHEMA_FAMILY = new Map([[validateTodoPlan, 'todo_plan'], [validateTodoManifest, 'todo_manifest']]);
156
159
  const vocabularyWord = (value) => typeof value === 'string' && /^[a-z][a-z0-9_-]{0,63}$/u.test(value);
157
160
 
@@ -1032,6 +1035,8 @@ function validateMergedGraph(members, crossPlanDependencies = projectTodoCrossPl
1032
1035
  const owner = members.find(({ plan }) => plan.project_id === dependency.to.project_id
1033
1036
  && plan.plan_key === dependency.to.plan_key);
1034
1037
  if (owner === undefined) fail('STORE_INCONSISTENT', 'cross_plan_dependency_owner_missing');
1038
+ // xchart S2: a predecessor on another chart is Plan's node (read there); no finding, no adjacency here.
1039
+ if (dependency.from.project_id !== owner.plan.project_id) continue;
1035
1040
  const digest = dependency.event_digest ?? null;
1036
1041
  const from = bind(dependency.from, owner.plan, digest, 'from');
1037
1042
  const to = bind(dependency.to, owner.plan, digest, 'to');
@@ -1077,9 +1082,14 @@ function crossPlanDependencyTask(store, ref) {
1077
1082
  return { member, task };
1078
1083
  }
1079
1084
 
1080
- function validateCrossPlanDependencyTransition(store, owner, input) {
1085
+ /**
1086
+ * xchart S3: only `todo dependency connect` (appendTodoEvent, `foreignFrom`) may record a predecessor on another
1087
+ * chart; Plan checked it there just before. Genesis, import and connectionOnly keep refusing a foreign from.
1088
+ */
1089
+ function validateCrossPlanDependencyTransition(store, owner, input, { foreignFrom = false } = {}) {
1081
1090
  const { from, to } = input.payload;
1082
- if (from.project_id !== store.project_id || to.project_id !== store.project_id) {
1091
+ const foreign = from.project_id !== store.project_id;
1092
+ if ((foreign && !foreignFrom) || to.project_id !== store.project_id) {
1083
1093
  fail('DEPENDENCY_INVALID', 'dependency_project_mismatch');
1084
1094
  }
1085
1095
  // 同一plan内の後追い接続も受ける(2026-08-25 オーナー裁定)。「工程の線を誤ったので足す」という
@@ -1097,7 +1107,7 @@ function validateCrossPlanDependencyTransition(store, owner, input) {
1097
1107
  edge.from.task_id === from.task_id && edge.to.task_id === to.task_id))) {
1098
1108
  fail('DEPENDENCY_EXISTS', 'dependency_already_in_plan', { from, to });
1099
1109
  }
1100
- const source = crossPlanDependencyTask(store, from);
1110
+ if (!foreign) crossPlanDependencyTask(store, from);
1101
1111
  const target = crossPlanDependencyTask(store, to);
1102
1112
  // A completed source already satisfies the prerequisite. Keep the existing
1103
1113
  // completion record as the proof instead of creating a second ledger entry.
@@ -1678,37 +1688,67 @@ async function readTodoStoreView(options = {}) {
1678
1688
  };
1679
1689
  }
1680
1690
 
1691
+ /**
1692
+ * One retained version's plan identity `{plan, journalRef}` (plan = its plan/predecessor/topology digests), or null when
1693
+ * unreadable. perf-store: validated once per process per unchanged plan.json (todo-version-memo).
1694
+ */
1695
+ async function retainedPlanVersion(repoRoot, base, version) {
1696
+ const ref = `${base}/${version}/plan.json`;
1697
+ const plan = await memoByFileIdentity([path.resolve(repoRoot, ref)], async () => {
1698
+ const value = await readArtifact(repoRoot, ref, {
1699
+ code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoPlan, missing: true,
1700
+ }).catch(() => null);
1701
+ return value === null ? null : { plan_digest: value.plan_digest,
1702
+ predecessor_plan_digest: value.predecessor_plan_digest, topology_digest: value.topology_digest };
1703
+ });
1704
+ return plan === null ? null : { plan, journalRef: `${base}/${version}/journal/active.jsonl` };
1705
+ }
1706
+
1707
+ async function retainedVersionNames(repoRoot, base, activePlan) {
1708
+ let names = [];
1709
+ try { names = await readdir(path.resolve(repoRoot, base)); } catch { /* no retained versions */ }
1710
+ return names.filter((version) => version !== activePlan.plan_version && isTodoIdentifier(version));
1711
+ }
1712
+
1681
1713
  /** The plan's other retained versions, by plan digest (unreadable ones are skipped). */
1682
1714
  async function retainedPlanVersions(repoRoot, activePlan) {
1683
1715
  const base = `${STORE_ROOT_REF}/plans/${activePlan.plan_key}`;
1684
1716
  const byDigest = new Map();
1685
- let names = [];
1686
- try { names = await readdir(path.resolve(repoRoot, base)); } catch { /* no retained versions */ }
1687
- for (const version of names) {
1688
- if (version === activePlan.plan_version || !isTodoIdentifier(version)) continue;
1689
- const plan = await readArtifact(repoRoot, `${base}/${version}/plan.json`, {
1690
- code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoPlan, missing: true,
1691
- }).catch(() => null);
1692
- if (plan !== null) byDigest.set(plan.plan_digest, { plan, journalRef: `${base}/${version}/journal/active.jsonl` });
1717
+ for (const version of await retainedVersionNames(repoRoot, base, activePlan)) {
1718
+ const retained = await retainedPlanVersion(repoRoot, base, version);
1719
+ if (retained !== null) byDigest.set(retained.plan.plan_digest, retained);
1693
1720
  }
1694
1721
  return byDigest;
1695
1722
  }
1696
1723
 
1697
1724
  /**
1698
1725
  * a35: the coordination declaration belongs to the plan, not to one version (ADR 0160 Decision 2).
1699
- * A revision starts an empty plan-scoped chain, so a version that has not declared its own reads the
1726
+ * A revision does not copy the declaration into the new plan-scoped chain, so a version that has not declared its own reads the
1700
1727
  * newest declaration along its retained predecessors. Read only: nothing is copied into the new chain.
1701
1728
  * An unreadable predecessor ends the walk as undeclared, which is what the version showed before a35.
1702
1729
  */
1703
1730
  async function inheritedTodoCoordination(repoRoot, plan) {
1704
1731
  if (!plan.predecessor_plan_digest) return null;
1705
- const byDigest = await retainedPlanVersions(repoRoot, plan);
1706
- for (let digest = plan.predecessor_plan_digest, steps = 0; digest && steps < byDigest.size; steps += 1) {
1707
- const predecessor = byDigest.get(digest);
1732
+ // perf-store: versions are read lazily, only until the walk finds the predecessor it needs.
1733
+ const base = `${STORE_ROOT_REF}/plans/${plan.plan_key}`;
1734
+ const names = await retainedVersionNames(repoRoot, base, plan);
1735
+ const byDigest = new Map();
1736
+ let scanned = 0;
1737
+ const find = async (digest) => {
1738
+ while (!byDigest.has(digest) && scanned < names.length) {
1739
+ const retained = await retainedPlanVersion(repoRoot, base, names[scanned]);
1740
+ scanned += 1;
1741
+ if (retained !== null) byDigest.set(retained.plan.plan_digest, retained);
1742
+ }
1743
+ return byDigest.get(digest);
1744
+ };
1745
+ for (let digest = plan.predecessor_plan_digest, steps = 0; digest && steps < names.length; steps += 1) {
1746
+ const predecessor = await find(digest);
1708
1747
  if (predecessor === undefined) return null;
1709
- const chain = await readPlanScopedJournal(repoRoot, predecessor.journalRef).catch(() => null);
1710
- if (chain === null) return null;
1711
- const declared = projectTodoCoordination(chain.events);
1748
+ const declared = await memoByFileIdentity([path.resolve(repoRoot, planScopedJournalRef(predecessor.journalRef))],
1749
+ () => readPlanScopedJournal(repoRoot, predecessor.journalRef)
1750
+ .then((chain) => projectTodoCoordination(chain.events), () => undefined));
1751
+ if (declared === undefined) return null;
1712
1752
  if (declared !== null) return declared;
1713
1753
  digest = predecessor.plan.predecessor_plan_digest;
1714
1754
  }
@@ -1850,6 +1890,16 @@ async function repairCrossPlanBindings(repoRoot, store, { assertHeld, actor, rec
1850
1890
  return repairs;
1851
1891
  }
1852
1892
 
1893
+ /**
1894
+ * xchart S1: read another chart without touching it: the non-recovering view (no lock, no recovery, no write).
1895
+ * Throws where that chart's own writer must recover (manifest_journal_head_mismatch after the stable-read attempts,
1896
+ * cross_plan_import_recovery_required, source_cutover_recovery_required) and STORE_UNINITIALIZED; Plan reads any
1897
+ * throw as "that chart is unreadable" for its edges only.
1898
+ */
1899
+ export async function readTodoStoreReadOnly({ repoRoot }) {
1900
+ return readStoreStableWith({ repoRoot }, readTodoStoreView);
1901
+ }
1902
+
1853
1903
  export async function readTodoStoreStable(options = {}) {
1854
1904
  return readStoreStableWith(options, readTodoStore);
1855
1905
  }
@@ -2409,7 +2459,7 @@ export async function appendTodoEvent(options = {}) {
2409
2459
  // 「作業が進んだ」の意味であり、方式選択や依存接続でそこを動かすと意味がずれる。
2410
2460
  if (TODO_PLAN_SCOPED_EVENT_KINDS.includes(options.event.kind)) {
2411
2461
  if (options.event.kind === 'cross_plan_dependency') {
2412
- validateCrossPlanDependencyTransition(store, member, options.event);
2462
+ validateCrossPlanDependencyTransition(store, member, options.event, { foreignFrom: true });
2413
2463
  }
2414
2464
  if (options.event.kind === 'cross_plan_dependency_removed') {
2415
2465
  const digest = options.event.payload.target_event_digest;
@@ -2558,6 +2608,49 @@ async function appendPlanScopedEvent({ repoRoot, member, input, assertHeld }) {
2558
2608
  };
2559
2609
  }
2560
2610
 
2611
+ /**
2612
+ * edge-carry: a successor's plan-scoped chain starts with the predecessor's live incoming connections, so a revision
2613
+ * no longer drops them. `to` and a same-plan `from` follow the genesis task_migration onto the successor topology; a
2614
+ * removed endpoint, a self edge or a duplicate after mapping drops the edge; any other `from` stays as recorded (its
2615
+ * own plan's revision is the u03 repair's, another chart's is Plan's). Actor, time and provenance stay the
2616
+ * connection's, so the bytes depend only on the predecessor chain and the successor and a resumed transaction rebuilds
2617
+ * them. Coordination declarations are not copied (read-time inheritance, a35).
2618
+ */
2619
+ function carriedPlanScopedChain(store, previous, plan, journalRef, taskMigration) {
2620
+ const live = new Set(projectTodoCrossPlanDependencies(store.members).map(({ event_digest: digest }) => digest));
2621
+ const ids = new Map(taskMigration.map(({ from_task_id: from, to_task_id: to }) => [from, to]));
2622
+ const carry = (ref) => {
2623
+ if (ref.project_id !== plan.project_id || ref.plan_key !== plan.plan_key) return ref;
2624
+ const taskId = ids.get(ref.task_id);
2625
+ return taskId === undefined || taskId === 'removed' ? null
2626
+ : { ...ref, task_id: taskId, expected_topology_digest: plan.topology_digest };
2627
+ };
2628
+ const successor = { plan, plan_scoped: { ref: planScopedJournalRef(journalRef), events: [], activeBytes: Buffer.alloc(0) } };
2629
+ const seen = new Set();
2630
+ for (const event of previous.plan_scoped?.events ?? []) {
2631
+ if (event.kind !== 'cross_plan_dependency' || !live.has(event.event_digest)) continue;
2632
+ const from = carry(event.payload.from); const to = carry(event.payload.to);
2633
+ if (from === null || to === null || mergedTaskKey(from) === mergedTaskKey(to)) continue;
2634
+ const key = `${mergedTaskKey(from)}\0${mergedTaskKey(to)}`;
2635
+ if (seen.has(key)) continue;
2636
+ seen.add(key);
2637
+ const carried = buildPlanScopedEvent(successor, { kind: event.kind, actor: event.actor,
2638
+ recorded_at: event.recorded_at, provenance: event.provenance,
2639
+ payload: { from, to, reason: event.payload.reason } });
2640
+ successor.plan_scoped.activeBytes = Buffer.concat([successor.plan_scoped.activeBytes,
2641
+ planScopedEventBytes(successor, carried)]);
2642
+ successor.plan_scoped.events.push(carried);
2643
+ }
2644
+ return successor.plan_scoped;
2645
+ }
2646
+
2647
+ /** Written before the manifest switch; the version is not active yet, so a retry rewrites it from the current predecessor. */
2648
+ async function writeCarriedPlanScopedChain(repoRoot, chain) {
2649
+ const absolute = path.resolve(repoRoot, chain.ref);
2650
+ if (chain.events.length === 0) await rm(absolute, { force: true });
2651
+ else await atomicWrite(absolute, chain.activeBytes);
2652
+ }
2653
+
2561
2654
  /** Rebind existing connections to a carried source without changing their endpoints. */
2562
2655
  export async function rebindTodoCrossPlanDependencies(options = {}) {
2563
2656
  requireWriter(options.writer, 'g5-authoring');
@@ -3646,11 +3739,96 @@ async function withInitialStoreLocks(stage, currentRoot, callback) {
3646
3739
  }
3647
3740
 
3648
3741
  /** G5-only initial authoring transaction. Store membership appears by one final directory rename. */
3742
+ const CHART_META_REF = '.lattice/chart.json';
3743
+ const CHART_META_MAX_BYTES = 65_536;
3744
+ const CHART_META_PATCH_KEYS = ['name', 'created_by', 'repo'];
3745
+
3746
+ /** The recorded chart identity, or null when `.lattice/chart.json` does not exist. */
3747
+ async function readChartMetaRecord(repoRoot) {
3748
+ const absolute = path.join(repoRoot, CHART_META_REF);
3749
+ const invalid = () => fail('STORE_INCONSISTENT', 'chart_meta_invalid', { ref: CHART_META_REF });
3750
+ let bytes;
3751
+ try {
3752
+ const state = await lstat(absolute);
3753
+ if (state.isSymbolicLink() || !state.isFile() || state.size > CHART_META_MAX_BYTES) invalid();
3754
+ bytes = normalizeCheckoutEol(await readFile(absolute));
3755
+ } catch (error) {
3756
+ if (error instanceof TodoStoreError) throw error;
3757
+ if (error?.code === 'ENOENT') return null;
3758
+ if (error?.code === 'ENOTDIR') invalid();
3759
+ throw error;
3760
+ }
3761
+ let value;
3762
+ try { value = JSON.parse(decodeUtf8(bytes, 'STORE_INCONSISTENT', 'chart_meta_invalid')); }
3763
+ catch (error) { if (error instanceof TodoStoreError) throw error; invalid(); }
3764
+ rejectNewerTodoSchema(value, 'chart_meta', CHART_META_REF);
3765
+ if (!validateTodoChartMeta(value)) invalid();
3766
+ return value;
3767
+ }
3768
+
3769
+ const chartMetaView = (record) => ({ name: record?.name ?? null, created_by: record?.created_by ?? null,
3770
+ created_at: record?.created_at ?? null, repo: record?.repo ?? null });
3771
+
3772
+ /**
3773
+ * a101 K4: chart identity `.lattice/chart.json` (dfd-charts-read). Read only, no lock, no Store needed: a missing file
3774
+ * reads all null; a malformed one STORE_INCONSISTENT/chart_meta_invalid; a newer schema UNSUPPORTED_SCHEMA.
3775
+ */
3776
+ export async function readTodoChartMeta({ repoRoot = process.cwd() } = {}) {
3777
+ return chartMetaView(await readChartMetaRecord(path.resolve(repoRoot)));
3778
+ }
3779
+
3780
+ /**
3781
+ * a101 K4: patch {name?, created_by?, repo?} (absent key = keep). `created_by` applies only while unrecorded and
3782
+ * `created_at` is stamped when the file is first created: the creator is never overwritten. Works before the first plan
3783
+ * (creates `.lattice/`). The read-modify-write holds `.lattice/.chart.write.lock` so two writers cannot both see an
3784
+ * unrecorded creator (identified lock, proven-dead recovery). Name rules are the CLI's.
3785
+ */
3786
+ export async function writeTodoChartMeta({ repoRoot = process.cwd(), patch = {} } = {}) {
3787
+ if (patch === null || typeof patch !== 'object' || Array.isArray(patch)
3788
+ || Object.keys(patch).some((key) => !CHART_META_PATCH_KEYS.includes(key))) {
3789
+ throw new TypeError('chart meta patch invalid');
3790
+ }
3791
+ const root = path.resolve(repoRoot);
3792
+ const latticeRoot = path.join(root, '.lattice');
3793
+ const parent = await lstat(latticeRoot).catch((error) => {
3794
+ if (error?.code !== 'ENOENT') throw error;
3795
+ return null;
3796
+ });
3797
+ if (parent === null) {
3798
+ await mkdir(latticeRoot, { mode: 0o700 }).catch((error) => { if (error?.code !== 'EEXIST') throw error; });
3799
+ } else if (parent.isSymbolicLink() || !parent.isDirectory()) {
3800
+ fail('STORE_INCONSISTENT', 'unsafe_lattice_root');
3801
+ }
3802
+ try {
3803
+ return await withStoreLock({ lockPath: path.join(latticeRoot, '.chart.write.lock'), createParent: false,
3804
+ waitMs: LOCK_WAIT_MS }, async () => {
3805
+ const current = await readChartMetaRecord(root);
3806
+ const next = {
3807
+ schema: TODO_CHART_META_SCHEMA,
3808
+ name: 'name' in patch ? patch.name : current?.name ?? null,
3809
+ created_by: current?.created_by ?? patch.created_by ?? null,
3810
+ created_at: current === null ? new Date().toISOString() : current.created_at,
3811
+ repo: 'repo' in patch ? patch.repo : current?.repo ?? null,
3812
+ };
3813
+ if (!validateTodoChartMeta(next)) throw new TypeError('chart meta patch invalid');
3814
+ if (current !== null && canonicalizeTodoArtifact(next) === canonicalizeTodoArtifact(current)) {
3815
+ return { meta: chartMetaView(current), unchanged: true };
3816
+ }
3817
+ await atomicWrite(path.join(root, CHART_META_REF), canonicalLine(next));
3818
+ return { meta: chartMetaView(next), unchanged: false };
3819
+ });
3820
+ } catch (error) {
3821
+ if (error instanceof StoreLockError) fail('STORE_WRITE_CONFLICT', error.reason, error.detail);
3822
+ throw error;
3823
+ }
3824
+ }
3825
+
3649
3826
  export async function initializeAuthoredTodoStore(options = {}) {
3650
3827
  requireWriter(options.writer, 'g5-authoring');
3651
3828
  const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
3652
3829
  const optionKeys = [
3653
3830
  'repoRoot', 'writer', 'projectId', 'repositories', 'plan', 'genesis',
3831
+ ...(options.chartCreator === undefined ? [] : ['chartCreator']),
3654
3832
  ];
3655
3833
  const allowedOptions = options.featureChain === undefined ? optionKeys : [...optionKeys, 'featureChain'];
3656
3834
  if (!(exactRecord(options, allowedOptions)
@@ -3695,8 +3873,9 @@ export async function initializeAuthoredTodoStore(options = {}) {
3695
3873
  await prepareAuthoredStoreRoot(repoRoot, options);
3696
3874
  await mkdir(stage, { mode: 0o700 });
3697
3875
  stageIdentity = await lstat(stage);
3876
+ let created;
3698
3877
  try {
3699
- return await withInitialStoreLocks(stage, async () => {
3878
+ created = await withInitialStoreLocks(stage, async () => {
3700
3879
  const current = renamed ? storeRoot : stage;
3701
3880
  const identity = await lstat(current).catch((error) => {
3702
3881
  if (error?.code !== 'ENOENT') throw error;
@@ -3832,6 +4011,11 @@ export async function initializeAuthoredTodoStore(options = {}) {
3832
4011
  }
3833
4012
  }
3834
4013
  }
4014
+ // a101 K4: the creating run is the chart's creator (only while unrecorded). After activation, so the rollback above
4015
+ // never meets chart.json; the Store is published, so a chart.json fault is the readers' finding, not this run's failure.
4016
+ try { await writeTodoChartMeta({ repoRoot, patch: { created_by: options.chartCreator ?? null } }); }
4017
+ catch (error) { if (!(error instanceof TodoStoreError)) throw error; }
4018
+ return created;
3835
4019
  }
3836
4020
 
3837
4021
  async function sourceItemBytes(repoRoot, sourceRef) {
@@ -4856,8 +5040,9 @@ async function applyPhaseTodoRevisionV3(options, revision, repoRoot) {
4856
5040
  verifyPlanNarrativeAnchors(repoRoot, revision.desired_plan, previous.plan);
4857
5041
  const stateMigration = stateMigrationFor(previous, revision);
4858
5042
  const phaseStateMigration = phaseStateMigrationFor(previous, revision);
5043
+ const carriedChain = carriedPlanScopedChain(store, previous, revision.desired_plan, journalRef, stateMigration);
4859
5044
  validateMergedGraph(store.members.map((member) => member === previous
4860
- ? { ...member, plan: revision.desired_plan, plan_scoped: null } : member));
5045
+ ? { ...member, plan: revision.desired_plan, plan_scoped: carriedChain } : member));
4861
5046
  const candidateGenesis = buildPhaseRevisionGenesis(revision.desired_plan, {
4862
5047
  previous_digest: revision.predecessor.journal_head_digest, actor: options.actor,
4863
5048
  recorded_at: options.recordedAt, provenance: options.provenance ?? null,
@@ -4980,6 +5165,7 @@ async function applyPhaseTodoRevisionV3(options, revision, repoRoot) {
4980
5165
  await publishRevisionArtifact(path.join(transaction, 'phase-revision-commit-receipt.json'),
4981
5166
  path.resolve(repoRoot, commitReceiptRef), canonicalLine(commitReceipt));
4982
5167
  await protocolStage(options, 'phase_v3_commit_receipt_durable');
5168
+ await writeCarriedPlanScopedChain(repoRoot, carriedChain);
4983
5169
  const nextManifest = { schema: 'lattice.todo_manifest.v2', project_id: currentManifest.project_id,
4984
5170
  repositories: currentManifest.repositories, members, manifest_digest: '' };
4985
5171
  nextManifest.manifest_digest = todoSelfDigest(nextManifest, 'manifest_digest');
@@ -5026,8 +5212,12 @@ export async function applyPhaseTodoRevision(options = {}) {
5026
5212
  verifyPlanNarrativeAnchors(repoRoot, revision.desired_plan, previous.plan);
5027
5213
  const stateMigration = stateMigrationFor(previous, revision);
5028
5214
  const phaseStateMigration = phaseStateMigrationFor(previous, revision);
5215
+ const base = `${STORE_ROOT_REF}/plans/${revision.plan_key}/${revision.desired_plan.plan_version}`;
5216
+ const revisionRef = `${base}/revision.json`; const planRef = `${base}/plan.json`;
5217
+ const journalRef = `${base}/journal/active.jsonl`; const snapshotRef = `${base}/snapshot.json`;
5218
+ const carriedChain = carriedPlanScopedChain(store, previous, revision.desired_plan, journalRef, stateMigration);
5029
5219
  const prospective = store.members.map((member) => member === previous
5030
- ? { ...member, plan: revision.desired_plan, plan_scoped: null } : member);
5220
+ ? { ...member, plan: revision.desired_plan, plan_scoped: carriedChain } : member);
5031
5221
  validateMergedGraph(prospective);
5032
5222
  const candidateGenesis = buildPhaseRevisionGenesis(revision.desired_plan, {
5033
5223
  previous_digest: revision.predecessor.journal_head_digest,
@@ -5054,9 +5244,6 @@ export async function applyPhaseTodoRevision(options = {}) {
5054
5244
  }));
5055
5245
  }
5056
5246
  await protocolStage(options, 'phase_revision_marker_durable');
5057
- const base = `${STORE_ROOT_REF}/plans/${revision.plan_key}/${revision.desired_plan.plan_version}`;
5058
- const revisionRef = `${base}/revision.json`; const planRef = `${base}/plan.json`;
5059
- const journalRef = `${base}/journal/active.jsonl`; const snapshotRef = `${base}/snapshot.json`;
5060
5247
  const tasks = replay(revision.desired_plan, [genesis], {
5061
5248
  now: options.now ? new Date(options.now) : new Date(),
5062
5249
  verifyEvidence: evidenceVerifier(store.manifest, repoRoot, false),
@@ -5079,6 +5266,7 @@ export async function applyPhaseTodoRevision(options = {}) {
5079
5266
  else if (!existing.equals(bytes)) fail('REVISION_CONFLICT', 'revision_bytes_conflict');
5080
5267
  await protocolStage(options, stage);
5081
5268
  }
5269
+ await writeCarriedPlanScopedChain(repoRoot, carriedChain);
5082
5270
  const currentManifest = await readArtifact(repoRoot, MANIFEST_REF, {
5083
5271
  code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoManifest,
5084
5272
  });
@@ -5175,8 +5363,11 @@ export async function applyTodoRevision(options = {}) {
5175
5363
  }
5176
5364
  verifyPlanNarrativeAnchors(repoRoot, revision.desired_plan, previous.plan);
5177
5365
  const stateMigration = stateMigrationFor(previous, revision);
5366
+ const carriedChain = carriedPlanScopedChain(store, previous, revision.desired_plan,
5367
+ `${STORE_ROOT_REF}/plans/${revision.plan_key}/${revision.desired_plan.plan_version}/journal/active.jsonl`,
5368
+ stateMigration);
5178
5369
  const prospective = store.members.map((member) => member === previous
5179
- ? { ...member, plan: revision.desired_plan, plan_scoped: null } : member);
5370
+ ? { ...member, plan: revision.desired_plan, plan_scoped: carriedChain } : member);
5180
5371
  validateMergedGraph(prospective);
5181
5372
 
5182
5373
  const candidateGenesis = buildRevisionGenesis(revision.desired_plan, {
@@ -5253,6 +5444,7 @@ export async function applyTodoRevision(options = {}) {
5253
5444
  }
5254
5445
 
5255
5446
  try {
5447
+ await writeCarriedPlanScopedChain(repoRoot, carriedChain);
5256
5448
  const currentManifest = await readArtifact(repoRoot, MANIFEST_REF, {
5257
5449
  code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoManifest,
5258
5450
  });
@@ -5445,13 +5637,16 @@ export async function applyTodoRevisionSet(options = {}) {
5445
5637
  : buildRevisionGenesis(revision.desired_plan, {
5446
5638
  ...commonGenesis, reconciliation_digest: revision.reconciliation.reconciliation_digest,
5447
5639
  });
5448
- prepared.push({ revision, previous, stateMigration, phaseStateMigration, genesis, cutoverImages });
5640
+ const carriedChain = carriedPlanScopedChain(store, previous, revision.desired_plan,
5641
+ `${STORE_ROOT_REF}/plans/${revision.plan_key}/${revision.desired_plan.plan_version}/journal/active.jsonl`,
5642
+ stateMigration);
5643
+ prepared.push({ revision, previous, stateMigration, phaseStateMigration, genesis, cutoverImages, carriedChain });
5449
5644
  }
5450
5645
 
5451
- const desiredByPlan = new Map(prepared.map((entry) => [entry.revision.plan_key,
5452
- entry.revision.desired_plan]));
5646
+ const desiredByPlan = new Map(prepared.map((entry) => [entry.revision.plan_key, entry]));
5453
5647
  validateMergedGraph(store.members.map((member) => desiredByPlan.has(member.descriptor.plan_key)
5454
- ? { ...member, plan: desiredByPlan.get(member.descriptor.plan_key), plan_scoped: null } : member));
5648
+ ? { ...member, plan: desiredByPlan.get(member.descriptor.plan_key).revision.desired_plan,
5649
+ plan_scoped: desiredByPlan.get(member.descriptor.plan_key).carriedChain } : member));
5455
5650
 
5456
5651
  await ensureSafeStoreDirectory(repoRoot, transaction);
5457
5652
  const mixedPhaseSet = prepared.some(({ revision }) => ([
@@ -5553,6 +5748,7 @@ export async function applyTodoRevisionSet(options = {}) {
5553
5748
  }
5554
5749
 
5555
5750
  try {
5751
+ for (const entry of prepared) await writeCarriedPlanScopedChain(repoRoot, entry.carriedChain);
5556
5752
  const currentManifest = await readArtifact(repoRoot, MANIFEST_REF, {
5557
5753
  code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoManifest,
5558
5754
  });
@@ -5653,10 +5849,11 @@ export async function createSuccessorTodoPlan(options = {}) {
5653
5849
  const genesis = buildPlanGenesis(plan, {
5654
5850
  ...options.genesis, previous_digest: previous.journal.events.at(-1).event_digest,
5655
5851
  });
5656
- const prospective = store.members.map((member) => member === previous ? { ...member, plan, plan_scoped: null } : member);
5657
- validateMergedGraph(prospective);
5658
5852
  const base = `${STORE_ROOT_REF}/plans/${plan.plan_key}/${plan.plan_version}`;
5659
5853
  const planRef = `${base}/plan.json`; const journalRef = `${base}/journal/active.jsonl`; const snapshotRef = `${base}/snapshot.json`;
5854
+ const carriedChain = carriedPlanScopedChain(store, previous, plan, journalRef, migration);
5855
+ const prospective = store.members.map((member) => member === previous ? { ...member, plan, plan_scoped: carriedChain } : member);
5856
+ validateMergedGraph(prospective);
5660
5857
  try { await lstat(path.resolve(repoRoot, planRef)); fail('STORE_WRITE_CONFLICT', 'successor_version_exists'); }
5661
5858
  catch (error) { if (error instanceof TodoStoreError) throw error; if (error?.code !== 'ENOENT') throw error; }
5662
5859
  const tasks = replay(plan, [genesis], { now: options.now ? new Date(options.now) : new Date() });
@@ -5666,6 +5863,7 @@ export async function createSuccessorTodoPlan(options = {}) {
5666
5863
  await atomicWrite(path.resolve(repoRoot, planRef), canonicalLine(plan));
5667
5864
  await atomicWrite(path.resolve(repoRoot, journalRef), canonicalLine(genesis));
5668
5865
  await atomicWrite(path.resolve(repoRoot, snapshotRef), canonicalLine(snapshot));
5866
+ await writeCarriedPlanScopedChain(repoRoot, carriedChain);
5669
5867
  Object.assign(previous.descriptor, {
5670
5868
  active_plan_version: plan.plan_version, plan_ref: planRef, journal_ref: journalRef,
5671
5869
  snapshot_ref: snapshotRef, topology_digest: plan.topology_digest,
@@ -0,0 +1,71 @@
1
+ // Task trees (a100, docs/architecture/dfd-display-trees.md): connected components of this chart's tasks, so a host
2
+ // shows each tree's size without computing the graph itself. Pure; never throws on a malformed member or edge.
3
+
4
+ import { isFinishedTodoTaskState, projectTodoCrossPlanDependencies } from './todo-store-view.mjs';
5
+
6
+ const list = (value) => (Array.isArray(value) ? value : []);
7
+ const isRef = (ref) => ref !== null && typeof ref === 'object';
8
+ const key = (projectId, planKey, taskId) => `${projectId}\0${planKey}\0${taskId}`;
9
+ const byCodeUnit = (left, right) => (left < right ? -1 : left > right ? 1 : 0);
10
+
11
+ // Only well-formed ledger events reach the shared projection, so one bad event never drops the others.
12
+ function wellFormedLedger(member) {
13
+ const events = list(member?.plan_scoped?.events).filter((event) => isRef(event?.payload) && (
14
+ event.kind === 'cross_plan_dependency' ? isRef(event.payload.from) && isRef(event.payload.to)
15
+ : event.kind === 'cross_plan_dependency_removed'));
16
+ return { plan_scoped: { events } };
17
+ }
18
+
19
+ /** `[{tree_id, tasks:[{plan_key, task_id}], total, finished}]` over every task of `store.members`. */
20
+ export function projectTodoTrees(store) {
21
+ const members = list(store?.members).filter((member) => isRef(member?.plan));
22
+ const nodes = new Map();
23
+ const parent = new Map();
24
+ for (const { plan, tasks } of members) {
25
+ const states = new Map(list(tasks).map((state) => [state?.task_id, state]));
26
+ for (const task of list(plan.tasks)) {
27
+ if (typeof task?.task_id !== 'string') continue;
28
+ const id = key(plan.project_id, plan.plan_key, task.task_id);
29
+ nodes.set(id, { plan_key: plan.plan_key, task_id: task.task_id,
30
+ finished: isFinishedTodoTaskState(states.get(task.task_id)) });
31
+ parent.set(id, id);
32
+ }
33
+ }
34
+ const root = (id) => {
35
+ while (parent.get(id) !== id) id = parent.get(id);
36
+ return id;
37
+ };
38
+ // An edge with an endpoint that is not a task here (another chart, a removed task, a bad ref) is skipped.
39
+ const join = (from, to) => {
40
+ if (!isRef(from) || !isRef(to)) return;
41
+ const left = key(from.project_id, from.plan_key, from.task_id);
42
+ const right = key(to.project_id, to.plan_key, to.task_id);
43
+ if (nodes.has(left) && nodes.has(right)) parent.set(root(left), root(right));
44
+ };
45
+ for (const { plan } of members) {
46
+ for (const edge of list(plan.hard_dependencies)) join(edge?.from, edge?.to);
47
+ for (const entry of list(plan.joins)) for (const after of list(entry?.after)) join(after, entry.before);
48
+ for (const task of list(plan.tasks)) {
49
+ const parentId = task?.parent_task_id;
50
+ if (typeof parentId === 'string') join({ ...plan, task_id: parentId }, { ...plan, task_id: task.task_id });
51
+ }
52
+ }
53
+ for (const edge of projectTodoCrossPlanDependencies(members.map(wellFormedLedger))) join(edge.from, edge.to);
54
+
55
+ const trees = new Map();
56
+ for (const id of nodes.keys()) {
57
+ const tree = root(id);
58
+ if (!trees.has(tree)) trees.set(tree, []);
59
+ trees.get(tree).push(nodes.get(id));
60
+ }
61
+ return [...trees.values()].map((members) => {
62
+ const tasks = members.sort((left, right) => byCodeUnit(left.plan_key, right.plan_key)
63
+ || byCodeUnit(left.task_id, right.task_id));
64
+ return {
65
+ tree_id: tasks.map((task) => `${task.plan_key}/${task.task_id}`).sort(byCodeUnit)[0],
66
+ tasks: tasks.map(({ plan_key, task_id }) => ({ plan_key, task_id })),
67
+ total: tasks.length,
68
+ finished: tasks.filter((task) => task.finished).length,
69
+ };
70
+ }).sort((left, right) => byCodeUnit(left.tree_id, right.tree_id));
71
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * perf-store: per-process memo for values derived from retained plan-version files (Store internal).
3
+ *
4
+ * A retained version directory is immutable history, but every Store read used to re-read and strictly re-validate
5
+ * all of them (206 versions on a production plan: one `todo add` spent ~40 s re-digesting the same bytes). The memo
6
+ * keys by absolute file paths and serves a value only while each file's identity (dev, ino, size, mtime, ctime) is
7
+ * unchanged, so a replaced or newly published file is read again. A failing computation is not memoized.
8
+ * Callers keep their own readdir, so new versions appear. Values stay small (digests, migrations), never whole plans.
9
+ */
10
+ import { lstat } from 'node:fs/promises';
11
+
12
+ const memo = new Map();
13
+
14
+ async function fileIdentity(absolute) {
15
+ try {
16
+ const state = await lstat(absolute, { bigint: true });
17
+ return `${state.dev}:${state.ino}:${state.size}:${state.mtimeNs}:${state.ctimeNs}`;
18
+ } catch (error) {
19
+ return error?.code === 'ENOENT' ? '-' : `!${error?.code}`;
20
+ }
21
+ }
22
+
23
+ export async function memoByFileIdentity(files, compute) {
24
+ const key = files.join('\0');
25
+ const identity = (await Promise.all(files.map(fileIdentity))).join('|');
26
+ const hit = memo.get(key);
27
+ if (hit !== undefined && hit.identity === identity) return hit.value;
28
+ const value = await compute();
29
+ memo.set(key, { identity, value });
30
+ return value;
31
+ }