@quolu/lattice 0.99.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quolu/lattice",
3
- "version": "0.99.0",
3
+ "version": "0.100.0",
4
4
  "description": "Schedulability compiler for multi-agent development: observe real code boundaries, refactor the conflicting seam, recompile the plan for parallel execution",
5
5
  "author": {
6
6
  "name": "Quo / クオ at kitepon.dev",
@@ -603,26 +603,23 @@ export function carriedStartActors(member) {
603
603
  export async function rebindCarriedWork({ repoRoot, planKey, env,
604
604
  reason = 'ゴール変更後のplan versionへ作業中ToDoを結び直す',
605
605
  failureCode = 'BACKCHAIN_REBIND_PENDING', carriedActors = new Map() }) {
606
+ // perf-rebind: one store read for every carried task (was 5 full passes per task through rebindStart).
606
607
  const store = await readTodoStore({ repoRoot });
607
608
  const member = store.members.find(({ plan }) => plan.plan_key === planKey);
608
- const rebound = [];
609
- for (const state of member.tasks.filter(({ status }) => status === 'in-progress')) {
610
- const hasCurrentStart = member.journal.events.some((event) => event.kind === 'start'
611
- && event.task_id === state.task_id && event.payload?.start_mode !== 'historical_import');
612
- if (hasCurrentStart) continue;
613
- const { rebindStart } = await import('./todo-cli.mjs');
614
- try {
615
- await rebindStart({ repoRoot, env, planKey, taskId: state.task_id,
616
- reason, actor: carriedActors.get(state.task_id) ?? null });
617
- } catch (error) {
609
+ const rebound = member.tasks.filter(({ status, task_id: taskId }) => status === 'in-progress'
610
+ && !member.journal.events.some((event) => event.kind === 'start'
611
+ && event.task_id === taskId && event.payload?.start_mode !== 'historical_import'))
612
+ .map(({ task_id: taskId }) => taskId);
613
+ const { rebindCarriedStarts } = await import('./todo-cli.mjs');
614
+ await rebindCarriedStarts({ repoRoot, env, store, planKey, reason,
615
+ tasks: rebound.map((taskId) => ({ task_id: taskId, actor: carriedActors.get(taskId) ?? null })),
616
+ onFailure: (taskId, error) => {
618
617
  throw new TodoStoreError(failureCode, 'carried_task_rebind_failed', undefined, {
619
- task_id: state.task_id, plan_version: member.plan.plan_version,
618
+ task_id: taskId, plan_version: member.plan.plan_version,
620
619
  cause_code: error?.code ?? 'unknown',
621
- next_action: `lattice todo start --plan ${planKey} --task ${state.task_id} --rebind --reason <text>`,
620
+ next_action: `lattice todo start --plan ${planKey} --task ${taskId} --rebind --reason <text>`,
622
621
  });
623
- }
624
- rebound.push(state.task_id);
625
- }
622
+ } });
626
623
  return rebound;
627
624
  }
628
625
 
package/src/todo-cli.mjs CHANGED
@@ -174,6 +174,7 @@ import { newTodoNotices, projectTodoNotices, waitInEffect } from './todo-notices
174
174
  import {
175
175
  externalCycle, readTodoExternalChart, readTodoExternalTasks, withTodoExternalTasks,
176
176
  } from './todo-external.mjs';
177
+ import { projectTodoTrees } from './todo-trees.mjs';
177
178
  import { projectTodoBlockers, todoBlockerKey } from './todo-blockers.mjs';
178
179
  import {
179
180
  ackTodoNotices, cancelTodoNoticeWait, readAllTodoNoticeAcks, readAllTodoNoticeWaits, readTodoNoticeAcks, writeTodoNoticeWait,
@@ -976,6 +977,12 @@ function reopenAdvisory(plan, phases, taskId) {
976
977
  };
977
978
  }
978
979
 
980
+ /** The prospective validator with `external` (xchart predecessor states) bound into the locked store. */
981
+ function externalValidator(external) {
982
+ return external.length === 0 ? validateProspectiveEvent
983
+ : (input) => validateProspectiveEvent({ ...input, store: { ...input.store, external_tasks: external } });
984
+ }
985
+
979
986
  async function mutate({
980
987
  repoRoot, env, planKey, taskId, kind, payload, evidenceRef, evidenceMessage = null,
981
988
  advisory = null, noteContext = null, structureContext = null, featureContext = null,
@@ -985,8 +992,7 @@ async function mutate({
985
992
  // xchart: start and authored done check predecessors on other charts too, read before the lock.
986
993
  const external = externalTasks ?? (kind === 'start' || (kind === 'done' && payload === 'authored')
987
994
  ? (await readTodoExternalTasks(await readTodoStore({ repoRoot }), env)).external_tasks : []);
988
- const validator = external.length === 0 ? validateProspectiveEvent
989
- : (input) => validateProspectiveEvent({ ...input, store: { ...input.store, external_tasks: external } });
995
+ const validator = externalValidator(external);
990
996
  const evidence = evidenceRef === null && evidenceMessage === null
991
997
  ? null
992
998
  : await resolveDoneEvidence({
@@ -1398,11 +1404,15 @@ async function startAdvisory({ repoRoot, store, projection, planKey, taskId }) {
1398
1404
  };
1399
1405
  }
1400
1406
 
1401
- /** xchart: the display envelope plus `external_tasks`, so a host computing readiness from it sees other charts too. */
1407
+ /**
1408
+ * xchart: the display envelope plus `external_tasks`, so a host computing readiness from it sees other charts too;
1409
+ * a100: plus `trees`, each task tree and its size, so the host never computes the graph.
1410
+ */
1402
1411
  async function displayRead(repoRoot, env) {
1403
1412
  const display = await readTodoStoreForDisplay({ repoRoot });
1404
1413
  const externalTasks = display.store ? (await readTodoExternalTasks(display.store, env)).external_tasks : [];
1405
- return { schema: 'lattice.todo_display_read_result.v1', ...display, external_tasks: externalTasks };
1414
+ return { schema: 'lattice.todo_display_read_result.v1', ...display, external_tasks: externalTasks,
1415
+ trees: display.store ? projectTodoTrees(display.store) : [] };
1406
1416
  }
1407
1417
 
1408
1418
  /** xchart: the Store plus its external predecessors' states; every readiness reader reads through this. */
@@ -1585,6 +1595,27 @@ export async function rebindStart({ repoRoot, env, planKey, taskId, reason, acto
1585
1595
  });
1586
1596
  }
1587
1597
 
1598
+ /**
1599
+ * perf-rebind: rebind every carried in-progress task after a revision with the same start event and validator as
1600
+ * `rebindStart`, but one store read and one external-chart read for all of them (the caller has the store and drops the
1601
+ * per-task result, so no per-task store or note-context read). Each event is still its own locked append, so a
1602
+ * refusal names its task. `tasks: [{task_id, actor}]`; calls `onFailure(taskId, error)` and stops at the first refusal.
1603
+ */
1604
+ export async function rebindCarriedStarts({ repoRoot, env, store, planKey, tasks, reason, onFailure }) {
1605
+ if (tasks.length === 0) return;
1606
+ const validator = externalValidator((await readTodoExternalTasks(store, env)).external_tasks);
1607
+ const writer = createTodoStoreWriter({ caller: 'g5-authoring' });
1608
+ for (const { task_id: taskId, actor } of tasks) {
1609
+ try {
1610
+ await appendTodoEvent({ validateProspectiveEvent: validator, repoRoot, writer, planKey,
1611
+ event: { kind: 'start', task_id: taskId, actor: actor ?? resolveTodoActor(env),
1612
+ payload: { start_mode: 'rebind', reason } } });
1613
+ } catch (error) {
1614
+ onFailure(taskId, error);
1615
+ }
1616
+ }
1617
+ }
1618
+
1588
1619
  async function retractStart({ repoRoot, env, planKey, taskId, reason }) {
1589
1620
  const store = await readTodoStore({ repoRoot });
1590
1621
  const binding = resolveTodoStartRetractionBinding(store, { planKey, taskId });
@@ -44,6 +44,8 @@ export const TODO_NOTE_EVENT_V2_SCHEMA = 'lattice.todo_note_event.v2';
44
44
  // Per-lane startable-notice ack set and per-plan waits (host-local; todo-notice-store.mjs).
45
45
  export const TODO_NOTICE_ACKS_SCHEMA = 'lattice.todo_notice_acks.v2';
46
46
  export const TODO_NOTICE_WAITS_SCHEMA = 'lattice.todo_notice_waits.v1';
47
+ /** a101 K4: chart identity `.lattice/chart.json` (dfd-charts-read). */
48
+ export const TODO_CHART_META_SCHEMA = 'lattice.chart_meta.v1';
47
49
  /**
48
50
  * v2でnoteの`scope`とplan noteを載せる。v1のままでは`task_id`が identifier 必須・
49
51
  * `full_history_command`が`--task <id>`込みの文字列と完全一致で、どちらもplan noteを表せない。
@@ -846,3 +848,14 @@ export function validateTodoSnapshot(value) {
846
848
  && isTodoDigest(value.snapshot_digest) && value.snapshot_digest === todoSelfDigest(value, 'snapshot_digest');
847
849
  } catch { return false; }
848
850
  }
851
+
852
+ export function validateTodoChartMeta(value) {
853
+ const text = (field) => field === null || (typeof field === 'string' && field.length > 0 && field.length <= 1024);
854
+ const word = (field) => typeof field === 'string' && field.length > 0 && field.length <= 1024;
855
+ const { repo } = value ?? {};
856
+ return exactRecord(value, ['schema', 'name', 'created_by', 'created_at', 'repo'])
857
+ && value.schema === TODO_CHART_META_SCHEMA && text(value.name) && text(value.created_by)
858
+ && (value.created_at === null || isStrictTodoTimestamp(value.created_at))
859
+ && (repo === null || (exactRecord(repo, ['url', 'branch', 'accepted_tip'])
860
+ && word(repo.url) && word(repo.branch) && text(repo.accepted_tip)));
861
+ }
@@ -7,6 +7,7 @@ import path from 'node:path';
7
7
  import { LOCK_WAIT_MS, StoreLockError, withStoreLock } from './store-lock.mjs';
8
8
  import { syncPublishedFile } from './fs-publish.mjs';
9
9
  import { normalizeCheckoutEol } from './todo-store-view.mjs';
10
+ import { memoByFileIdentity } from './todo-version-memo.mjs';
10
11
 
11
12
  import {
12
13
  TODO_LIMITS,
@@ -504,31 +505,38 @@ async function readNoteMigrations(repoRoot, planKey, eventVersions) {
504
505
  fail('NOTE_PROJECTION_INVALID', 'note_plan_history_inventory_invalid', { plan_key: planKey });
505
506
  }
506
507
  const versionRoot = path.join(base, entry.name);
507
- // A revision directory is published before manifest activation. A crash during
508
- // that window can leave an unreferenced directory containing only a journal
509
- // stub. It is not a historical plan until its canonical plan artifact exists.
510
- // Do not make that unreachable residue poison note projection; if a note event
511
- // names this version, the origin-version check below still fails closed.
512
- const plan = await readCanonicalJson(path.join(versionRoot, 'plan.json'), { missing: true });
513
- if (plan === null) continue;
514
- if (!validateTodoPlan(plan) || plan.plan_key !== planKey || plan.plan_version !== entry.name) {
515
- fail('NOTE_PROJECTION_INVALID', 'note_historical_plan_invalid', { plan_version: entry.name });
516
- }
517
- versions.add(entry.name);
518
- const revision = await readCanonicalJson(path.join(versionRoot, 'revision.json'), { missing: true });
519
- if (revision === null) continue;
520
- if (!(validateTodoRevision(revision) || validatePhaseTodoRevision(revision))
521
- || revision.plan_key !== planKey || revision.predecessor?.plan_version === undefined
522
- || !Array.isArray(revision.task_migration)) {
523
- fail('NOTE_PROJECTION_INVALID', 'note_historical_revision_invalid', { plan_version: entry.name });
524
- }
525
- migrations.push({
526
- from_plan_version: revision.predecessor.plan_version,
527
- to_plan_version: entry.name,
528
- task_migration: revision.task_migration.map(({ from_task_id: fromTaskId, to_task_id: toTaskId }) => ({
529
- from_task_id: fromTaskId, to_task_id: toTaskId,
530
- })),
508
+ const planPath = path.join(versionRoot, 'plan.json');
509
+ const revisionPath = path.join(versionRoot, 'revision.json');
510
+ // perf-store: validated once per process while both files are unchanged (todo-version-memo).
511
+ const version = await memoByFileIdentity([planPath, revisionPath], async () => {
512
+ // A revision directory is published before manifest activation. A crash during
513
+ // that window can leave an unreferenced directory containing only a journal
514
+ // stub. It is not a historical plan until its canonical plan artifact exists.
515
+ // Do not make that unreachable residue poison note projection; if a note event
516
+ // names this version, the origin-version check below still fails closed.
517
+ const plan = await readCanonicalJson(planPath, { missing: true });
518
+ if (plan === null) return null;
519
+ if (!validateTodoPlan(plan) || plan.plan_key !== planKey || plan.plan_version !== entry.name) {
520
+ fail('NOTE_PROJECTION_INVALID', 'note_historical_plan_invalid', { plan_version: entry.name });
521
+ }
522
+ const revision = await readCanonicalJson(revisionPath, { missing: true });
523
+ if (revision === null) return { migration: null };
524
+ if (!(validateTodoRevision(revision) || validatePhaseTodoRevision(revision))
525
+ || revision.plan_key !== planKey || revision.predecessor?.plan_version === undefined
526
+ || !Array.isArray(revision.task_migration)) {
527
+ fail('NOTE_PROJECTION_INVALID', 'note_historical_revision_invalid', { plan_version: entry.name });
528
+ }
529
+ return { migration: {
530
+ from_plan_version: revision.predecessor.plan_version,
531
+ to_plan_version: entry.name,
532
+ task_migration: revision.task_migration.map(({ from_task_id: fromTaskId, to_task_id: toTaskId }) => ({
533
+ from_task_id: fromTaskId, to_task_id: toTaskId,
534
+ })),
535
+ } };
531
536
  });
537
+ if (version === null) continue;
538
+ versions.add(entry.name);
539
+ if (version.migration !== null) migrations.push(structuredClone(version.migration));
532
540
  }
533
541
  if ([...eventVersions].some((version) => !versions.has(version))) {
534
542
  fail('NOTE_PROJECTION_INVALID', 'note_origin_plan_version_unknown');
@@ -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
 
@@ -1685,37 +1688,67 @@ async function readTodoStoreView(options = {}) {
1685
1688
  };
1686
1689
  }
1687
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
+
1688
1713
  /** The plan's other retained versions, by plan digest (unreadable ones are skipped). */
1689
1714
  async function retainedPlanVersions(repoRoot, activePlan) {
1690
1715
  const base = `${STORE_ROOT_REF}/plans/${activePlan.plan_key}`;
1691
1716
  const byDigest = new Map();
1692
- let names = [];
1693
- try { names = await readdir(path.resolve(repoRoot, base)); } catch { /* no retained versions */ }
1694
- for (const version of names) {
1695
- if (version === activePlan.plan_version || !isTodoIdentifier(version)) continue;
1696
- const plan = await readArtifact(repoRoot, `${base}/${version}/plan.json`, {
1697
- code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoPlan, missing: true,
1698
- }).catch(() => null);
1699
- 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);
1700
1720
  }
1701
1721
  return byDigest;
1702
1722
  }
1703
1723
 
1704
1724
  /**
1705
1725
  * a35: the coordination declaration belongs to the plan, not to one version (ADR 0160 Decision 2).
1706
- * 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
1707
1727
  * newest declaration along its retained predecessors. Read only: nothing is copied into the new chain.
1708
1728
  * An unreadable predecessor ends the walk as undeclared, which is what the version showed before a35.
1709
1729
  */
1710
1730
  async function inheritedTodoCoordination(repoRoot, plan) {
1711
1731
  if (!plan.predecessor_plan_digest) return null;
1712
- const byDigest = await retainedPlanVersions(repoRoot, plan);
1713
- for (let digest = plan.predecessor_plan_digest, steps = 0; digest && steps < byDigest.size; steps += 1) {
1714
- 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);
1715
1747
  if (predecessor === undefined) return null;
1716
- const chain = await readPlanScopedJournal(repoRoot, predecessor.journalRef).catch(() => null);
1717
- if (chain === null) return null;
1718
- 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;
1719
1752
  if (declared !== null) return declared;
1720
1753
  digest = predecessor.plan.predecessor_plan_digest;
1721
1754
  }
@@ -2575,6 +2608,49 @@ async function appendPlanScopedEvent({ repoRoot, member, input, assertHeld }) {
2575
2608
  };
2576
2609
  }
2577
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
+
2578
2654
  /** Rebind existing connections to a carried source without changing their endpoints. */
2579
2655
  export async function rebindTodoCrossPlanDependencies(options = {}) {
2580
2656
  requireWriter(options.writer, 'g5-authoring');
@@ -3663,11 +3739,96 @@ async function withInitialStoreLocks(stage, currentRoot, callback) {
3663
3739
  }
3664
3740
 
3665
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
+
3666
3826
  export async function initializeAuthoredTodoStore(options = {}) {
3667
3827
  requireWriter(options.writer, 'g5-authoring');
3668
3828
  const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
3669
3829
  const optionKeys = [
3670
3830
  'repoRoot', 'writer', 'projectId', 'repositories', 'plan', 'genesis',
3831
+ ...(options.chartCreator === undefined ? [] : ['chartCreator']),
3671
3832
  ];
3672
3833
  const allowedOptions = options.featureChain === undefined ? optionKeys : [...optionKeys, 'featureChain'];
3673
3834
  if (!(exactRecord(options, allowedOptions)
@@ -3712,8 +3873,9 @@ export async function initializeAuthoredTodoStore(options = {}) {
3712
3873
  await prepareAuthoredStoreRoot(repoRoot, options);
3713
3874
  await mkdir(stage, { mode: 0o700 });
3714
3875
  stageIdentity = await lstat(stage);
3876
+ let created;
3715
3877
  try {
3716
- return await withInitialStoreLocks(stage, async () => {
3878
+ created = await withInitialStoreLocks(stage, async () => {
3717
3879
  const current = renamed ? storeRoot : stage;
3718
3880
  const identity = await lstat(current).catch((error) => {
3719
3881
  if (error?.code !== 'ENOENT') throw error;
@@ -3849,6 +4011,11 @@ export async function initializeAuthoredTodoStore(options = {}) {
3849
4011
  }
3850
4012
  }
3851
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;
3852
4019
  }
3853
4020
 
3854
4021
  async function sourceItemBytes(repoRoot, sourceRef) {
@@ -4873,8 +5040,9 @@ async function applyPhaseTodoRevisionV3(options, revision, repoRoot) {
4873
5040
  verifyPlanNarrativeAnchors(repoRoot, revision.desired_plan, previous.plan);
4874
5041
  const stateMigration = stateMigrationFor(previous, revision);
4875
5042
  const phaseStateMigration = phaseStateMigrationFor(previous, revision);
5043
+ const carriedChain = carriedPlanScopedChain(store, previous, revision.desired_plan, journalRef, stateMigration);
4876
5044
  validateMergedGraph(store.members.map((member) => member === previous
4877
- ? { ...member, plan: revision.desired_plan, plan_scoped: null } : member));
5045
+ ? { ...member, plan: revision.desired_plan, plan_scoped: carriedChain } : member));
4878
5046
  const candidateGenesis = buildPhaseRevisionGenesis(revision.desired_plan, {
4879
5047
  previous_digest: revision.predecessor.journal_head_digest, actor: options.actor,
4880
5048
  recorded_at: options.recordedAt, provenance: options.provenance ?? null,
@@ -4997,6 +5165,7 @@ async function applyPhaseTodoRevisionV3(options, revision, repoRoot) {
4997
5165
  await publishRevisionArtifact(path.join(transaction, 'phase-revision-commit-receipt.json'),
4998
5166
  path.resolve(repoRoot, commitReceiptRef), canonicalLine(commitReceipt));
4999
5167
  await protocolStage(options, 'phase_v3_commit_receipt_durable');
5168
+ await writeCarriedPlanScopedChain(repoRoot, carriedChain);
5000
5169
  const nextManifest = { schema: 'lattice.todo_manifest.v2', project_id: currentManifest.project_id,
5001
5170
  repositories: currentManifest.repositories, members, manifest_digest: '' };
5002
5171
  nextManifest.manifest_digest = todoSelfDigest(nextManifest, 'manifest_digest');
@@ -5043,8 +5212,12 @@ export async function applyPhaseTodoRevision(options = {}) {
5043
5212
  verifyPlanNarrativeAnchors(repoRoot, revision.desired_plan, previous.plan);
5044
5213
  const stateMigration = stateMigrationFor(previous, revision);
5045
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);
5046
5219
  const prospective = store.members.map((member) => member === previous
5047
- ? { ...member, plan: revision.desired_plan, plan_scoped: null } : member);
5220
+ ? { ...member, plan: revision.desired_plan, plan_scoped: carriedChain } : member);
5048
5221
  validateMergedGraph(prospective);
5049
5222
  const candidateGenesis = buildPhaseRevisionGenesis(revision.desired_plan, {
5050
5223
  previous_digest: revision.predecessor.journal_head_digest,
@@ -5071,9 +5244,6 @@ export async function applyPhaseTodoRevision(options = {}) {
5071
5244
  }));
5072
5245
  }
5073
5246
  await protocolStage(options, 'phase_revision_marker_durable');
5074
- const base = `${STORE_ROOT_REF}/plans/${revision.plan_key}/${revision.desired_plan.plan_version}`;
5075
- const revisionRef = `${base}/revision.json`; const planRef = `${base}/plan.json`;
5076
- const journalRef = `${base}/journal/active.jsonl`; const snapshotRef = `${base}/snapshot.json`;
5077
5247
  const tasks = replay(revision.desired_plan, [genesis], {
5078
5248
  now: options.now ? new Date(options.now) : new Date(),
5079
5249
  verifyEvidence: evidenceVerifier(store.manifest, repoRoot, false),
@@ -5096,6 +5266,7 @@ export async function applyPhaseTodoRevision(options = {}) {
5096
5266
  else if (!existing.equals(bytes)) fail('REVISION_CONFLICT', 'revision_bytes_conflict');
5097
5267
  await protocolStage(options, stage);
5098
5268
  }
5269
+ await writeCarriedPlanScopedChain(repoRoot, carriedChain);
5099
5270
  const currentManifest = await readArtifact(repoRoot, MANIFEST_REF, {
5100
5271
  code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoManifest,
5101
5272
  });
@@ -5192,8 +5363,11 @@ export async function applyTodoRevision(options = {}) {
5192
5363
  }
5193
5364
  verifyPlanNarrativeAnchors(repoRoot, revision.desired_plan, previous.plan);
5194
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);
5195
5369
  const prospective = store.members.map((member) => member === previous
5196
- ? { ...member, plan: revision.desired_plan, plan_scoped: null } : member);
5370
+ ? { ...member, plan: revision.desired_plan, plan_scoped: carriedChain } : member);
5197
5371
  validateMergedGraph(prospective);
5198
5372
 
5199
5373
  const candidateGenesis = buildRevisionGenesis(revision.desired_plan, {
@@ -5270,6 +5444,7 @@ export async function applyTodoRevision(options = {}) {
5270
5444
  }
5271
5445
 
5272
5446
  try {
5447
+ await writeCarriedPlanScopedChain(repoRoot, carriedChain);
5273
5448
  const currentManifest = await readArtifact(repoRoot, MANIFEST_REF, {
5274
5449
  code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoManifest,
5275
5450
  });
@@ -5462,13 +5637,16 @@ export async function applyTodoRevisionSet(options = {}) {
5462
5637
  : buildRevisionGenesis(revision.desired_plan, {
5463
5638
  ...commonGenesis, reconciliation_digest: revision.reconciliation.reconciliation_digest,
5464
5639
  });
5465
- 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 });
5466
5644
  }
5467
5645
 
5468
- const desiredByPlan = new Map(prepared.map((entry) => [entry.revision.plan_key,
5469
- entry.revision.desired_plan]));
5646
+ const desiredByPlan = new Map(prepared.map((entry) => [entry.revision.plan_key, entry]));
5470
5647
  validateMergedGraph(store.members.map((member) => desiredByPlan.has(member.descriptor.plan_key)
5471
- ? { ...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));
5472
5650
 
5473
5651
  await ensureSafeStoreDirectory(repoRoot, transaction);
5474
5652
  const mixedPhaseSet = prepared.some(({ revision }) => ([
@@ -5570,6 +5748,7 @@ export async function applyTodoRevisionSet(options = {}) {
5570
5748
  }
5571
5749
 
5572
5750
  try {
5751
+ for (const entry of prepared) await writeCarriedPlanScopedChain(repoRoot, entry.carriedChain);
5573
5752
  const currentManifest = await readArtifact(repoRoot, MANIFEST_REF, {
5574
5753
  code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoManifest,
5575
5754
  });
@@ -5670,10 +5849,11 @@ export async function createSuccessorTodoPlan(options = {}) {
5670
5849
  const genesis = buildPlanGenesis(plan, {
5671
5850
  ...options.genesis, previous_digest: previous.journal.events.at(-1).event_digest,
5672
5851
  });
5673
- const prospective = store.members.map((member) => member === previous ? { ...member, plan, plan_scoped: null } : member);
5674
- validateMergedGraph(prospective);
5675
5852
  const base = `${STORE_ROOT_REF}/plans/${plan.plan_key}/${plan.plan_version}`;
5676
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);
5677
5857
  try { await lstat(path.resolve(repoRoot, planRef)); fail('STORE_WRITE_CONFLICT', 'successor_version_exists'); }
5678
5858
  catch (error) { if (error instanceof TodoStoreError) throw error; if (error?.code !== 'ENOENT') throw error; }
5679
5859
  const tasks = replay(plan, [genesis], { now: options.now ? new Date(options.now) : new Date() });
@@ -5683,6 +5863,7 @@ export async function createSuccessorTodoPlan(options = {}) {
5683
5863
  await atomicWrite(path.resolve(repoRoot, planRef), canonicalLine(plan));
5684
5864
  await atomicWrite(path.resolve(repoRoot, journalRef), canonicalLine(genesis));
5685
5865
  await atomicWrite(path.resolve(repoRoot, snapshotRef), canonicalLine(snapshot));
5866
+ await writeCarriedPlanScopedChain(repoRoot, carriedChain);
5686
5867
  Object.assign(previous.descriptor, {
5687
5868
  active_plan_version: plan.plan_version, plan_ref: planRef, journal_ref: journalRef,
5688
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
+ }