@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.
@@ -0,0 +1,125 @@
1
+ // Cross-chart predecessors (xchart, docs/architecture/dfd-plan-revise.md#cross-chart-dependency-xchart-2026-11-13):
2
+ // a ledger edge whose `from` is a task of another chart (another project's Store under LATTICE_CHARTS_ROOT).
3
+ // Plan reads the other chart read-only; an unreadable one only keeps its waiters waiting.
4
+
5
+ import path from 'node:path';
6
+
7
+ import { createTodoReadiness } from './todo-readiness.mjs';
8
+ import { isFinishedTodoTaskState, projectTodoCrossPlanDependencies } from './todo-store-view.mjs';
9
+ import { readTodoStoreReadOnly, TodoStoreError } from './todo-store.mjs';
10
+
11
+ export const TODO_CHARTS_ROOT_ENV = 'LATTICE_CHARTS_ROOT';
12
+
13
+ /** Live ledger edges of `store` whose predecessor is on another chart. */
14
+ export function externalTodoDependencies(store) {
15
+ return projectTodoCrossPlanDependencies(store.members)
16
+ .filter(({ from }) => from.project_id !== store.project_id);
17
+ }
18
+
19
+ /** The other chart's Store, or a reason it cannot be read: `{store}` | `{reason, path}`. Never throws. */
20
+ async function readChart(env, projectId) {
21
+ const root = env?.[TODO_CHARTS_ROOT_ENV];
22
+ if (typeof root !== 'string' || root === '') return { reason: 'charts_root_unset', path: null };
23
+ // project ids are identifiers (no separators), so the join stays inside the root.
24
+ const chartPath = path.join(path.resolve(root), projectId);
25
+ try {
26
+ const store = await readTodoStoreReadOnly({ repoRoot: chartPath });
27
+ // A chart that says it is another project is the wrong target, not this one.
28
+ return store.project_id === projectId ? { store } : { reason: 'chart_unreadable', path: chartPath };
29
+ } catch {
30
+ return { reason: 'chart_unreadable', path: chartPath };
31
+ }
32
+ }
33
+
34
+ /** Connect-time read: the other chart's Store, or a refusal that names the env var or the chart. */
35
+ export async function readTodoExternalChart(env, projectId) {
36
+ const chart = await readChart(env, projectId);
37
+ if (chart.store !== undefined) return chart.store;
38
+ if (chart.reason === 'charts_root_unset') {
39
+ throw new TodoStoreError('DEPENDENCY_INVALID', 'charts_root_unset', undefined, {
40
+ project_id: projectId,
41
+ next_action: `Set ${TODO_CHARTS_ROOT_ENV} to the directory whose children are chart directories named by`
42
+ + ` project id (${projectId} is read from <${TODO_CHARTS_ROOT_ENV}>/${projectId}/.lattice), then connect again.`,
43
+ });
44
+ }
45
+ throw new TodoStoreError('DEPENDENCY_INVALID', 'chart_unreadable', undefined, {
46
+ project_id: projectId, path: chart.path,
47
+ next_action: `No readable Lattice chart for project ${projectId} at ${chart.path}; check the project id`
48
+ + ` (\`lattice status --json\` in that chart) and ${TODO_CHARTS_ROOT_ENV}.`,
49
+ });
50
+ }
51
+
52
+ function taskTrigger(member, taskId) {
53
+ const event = member.journal.events.findLast((entry) => entry.task_id === taskId);
54
+ return event === undefined ? null
55
+ : { kind: event.kind, event_digest: event.event_digest, recorded_at: event.recorded_at, actor: event.actor ?? null };
56
+ }
57
+
58
+ /**
59
+ * The states of every external predecessor of `store`, one read per other project:
60
+ * `{external_tasks, findings}`; nothing is read when there is no external edge.
61
+ */
62
+ export async function readTodoExternalTasks(store, env) {
63
+ const dependencies = externalTodoDependencies(store);
64
+ const charts = new Map();
65
+ for (const { from } of dependencies) {
66
+ if (!charts.has(from.project_id)) charts.set(from.project_id, await readChart(env, from.project_id));
67
+ }
68
+ const tasks = new Map();
69
+ const findings = [];
70
+ for (const dependency of dependencies) {
71
+ const { from } = dependency;
72
+ const chart = charts.get(from.project_id);
73
+ const member = chart.store?.members.find(({ plan }) => plan.plan_key === from.plan_key);
74
+ const state = member?.tasks.find(({ task_id: id }) => id === from.task_id);
75
+ const reason = chart.store === undefined ? chart.reason : state === undefined ? 'endpoint_missing' : null;
76
+ if (reason !== null) {
77
+ findings.push({ owner_plan_key: dependency.to.plan_key, event_digest: dependency.event_digest,
78
+ side: 'from', ref: structuredClone(from), reason });
79
+ }
80
+ tasks.set(`${from.project_id}\0${from.plan_key}\0${from.task_id}`, {
81
+ project_id: from.project_id, plan_key: from.plan_key, task_id: from.task_id,
82
+ status: state?.status ?? null, finished: isFinishedTodoTaskState(state), reason,
83
+ trigger: state === undefined ? null : taskTrigger(member, from.task_id),
84
+ });
85
+ }
86
+ return { external_tasks: [...tasks.values()], findings };
87
+ }
88
+
89
+ /** `store` plus `external_tasks` and their findings, so every readiness reader sees one predicate. */
90
+ export async function withTodoExternalTasks(store, env) {
91
+ if (store.external_tasks !== undefined || externalTodoDependencies(store).length === 0) return store;
92
+ const { external_tasks: externalTasks, findings } = await readTodoExternalTasks(store, env);
93
+ return { ...store, external_tasks: externalTasks,
94
+ cross_plan_findings: [...(store.cross_plan_findings ?? []), ...findings] };
95
+ }
96
+
97
+ /**
98
+ * Connect-time cycle check through readable charts: walk `from`'s predecessors (in-chart and cross-chart) from
99
+ * `fromStore`; reaching `to` closes a cycle. Returns the closed path (from … to) or null. Unreadable charts end
100
+ * their branch (a cycle nobody can see is not refused).
101
+ */
102
+ export async function externalCycle({ env, fromStore, from, to, localStore }) {
103
+ const key = (ref) => `${ref.project_id}\0${ref.plan_key}\0${ref.task_id}`;
104
+ const stores = new Map([[localStore.project_id, localStore], [fromStore.project_id, fromStore]]);
105
+ const target = key(to);
106
+ const seen = new Set();
107
+ const walk = async (ref, trail) => {
108
+ if (key(ref) === target) return [...trail, ref];
109
+ if (seen.has(key(ref))) return null;
110
+ seen.add(key(ref));
111
+ if (!stores.has(ref.project_id)) stores.set(ref.project_id, (await readChart(env, ref.project_id)).store ?? null);
112
+ const store = stores.get(ref.project_id);
113
+ if (store === null) return null;
114
+ const readiness = createTodoReadiness(store);
115
+ for (const pred of readiness.prerequisiteRefs(readiness.key(ref)).tasks) {
116
+ const found = await walk({ project_id: pred.project_id ?? store.project_id, plan_key: pred.plan_key,
117
+ task_id: pred.task_id }, [...trail, ref]);
118
+ if (found !== null) return found;
119
+ }
120
+ return null;
121
+ };
122
+ const closed = await walk({ project_id: from.project_id, plan_key: from.plan_key, task_id: from.task_id }, []);
123
+ return closed === null ? null : [to, ...closed.slice(0, -1).reverse(), to]
124
+ .map(({ project_id: projectId, plan_key: planKey, task_id: taskId }) => ({ project_id: projectId, plan_key: planKey, task_id: taskId }));
125
+ }
@@ -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');
@@ -59,6 +59,8 @@ function noticeSummary(planKey, task, waiting) {
59
59
  export function projectTodoNotices(store, { lane = null, declared = () => true, waits = [] } = {}) {
60
60
  const readiness = createTodoReadiness(store);
61
61
  const members = new Map(store.members.map((member) => [member.plan.plan_key, member]));
62
+ const external = new Map((store.external_tasks ?? []).map((entry) => [
63
+ `${entry.project_id}\0${entry.plan_key}\0${entry.task_id}`, entry]));
62
64
  const notices = [];
63
65
  for (const ready of projectTodoStatus(store, TODO_STATUS_DISPATCH_ONLY).next_ready) {
64
66
  const member = members.get(ready.plan_key);
@@ -67,6 +69,12 @@ export function projectTodoNotices(store, { lane = null, declared = () => true,
67
69
  const refs = readiness.prerequisiteRefs(readiness.key({ ...member.plan, ...task }));
68
70
  const triggers = [];
69
71
  for (const ref of refs.tasks) {
72
+ if (ref.project_id !== undefined) {
73
+ // xchart: the done was written in the other chart; its latest event is read there (withTodoExternalTasks).
74
+ const trigger = external.get(`${ref.project_id}\0${ref.plan_key}\0${ref.task_id}`)?.trigger ?? null;
75
+ if (trigger !== null) triggers.push({ project_id: ref.project_id, plan_key: ref.plan_key, task_id: ref.task_id, ...trigger });
76
+ continue;
77
+ }
70
78
  const event = latestEvent(members.get(ref.plan_key), (entry) => entry.task_id === ref.task_id);
71
79
  if (event !== null) triggers.push(triggerOf(members.get(ref.plan_key), event, { task_id: ref.task_id }));
72
80
  }
@@ -50,9 +50,21 @@ export function createTodoReadiness(store) {
50
50
  acceptanceIncoming.set(key, new Set());
51
51
  }
52
52
  }
53
+ // xchart: predecessors on other charts, as their chart reports them (`withTodoExternalTasks`); never phase-gated.
54
+ for (const entry of store.external_tasks ?? []) {
55
+ nodes.set(taskKey(entry), { status: entry.status, task_id: entry.task_id, finished: entry.finished === true,
56
+ schema: null, plan_key: entry.plan_key, project_id: entry.project_id, phase_id: null, reason: entry.reason });
57
+ }
58
+ // An external edge whose state was not loaded waits (fail closed), named `chart_not_read`.
59
+ const external = new Map();
60
+ const predecessorNode = (source) => nodes.get(source) ?? (external.has(source)
61
+ ? { ...external.get(source), status: null, finished: false, schema: null, reason: 'chart_not_read' } : undefined);
53
62
  const connect = (from, to) => {
54
63
  const source = taskKey(from);
55
64
  const target = taskKey(to);
65
+ if (from.project_id !== to.project_id) {
66
+ external.set(source, { project_id: from.project_id, plan_key: from.plan_key, task_id: from.task_id });
67
+ }
56
68
  incoming.get(target)?.add(source);
57
69
  outgoing.get(source)?.add(target);
58
70
  };
@@ -85,7 +97,7 @@ export function createTodoReadiness(store) {
85
97
 
86
98
  function prerequisites(key) {
87
99
  // u03 A24: 消えた端点(Storeのendpoint_missing finding)は後続を止めない。Store replayも同じ規則。
88
- const predecessors = [...(incoming.get(key) ?? [])].map((source) => nodes.get(source))
100
+ const predecessors = [...(incoming.get(key) ?? [])].map(predecessorNode)
89
101
  .filter((node) => node !== undefined);
90
102
  const unfinished = predecessors.filter((node) => node.finished !== true);
91
103
  const unreadyPhases = predecessors.filter((node) => !dependencyPhaseReady(node, nodes.get(key)));
@@ -107,7 +119,7 @@ export function createTodoReadiness(store) {
107
119
  cause,
108
120
  // a12: a refusal names what blocks, not only why.
109
121
  blocking: cause === 'predecessor_unfinished'
110
- ? { blocking_tasks: unfinished.map(({ plan_key, task_id, status }) => ({ plan_key, task_id, status })).sort(byRef) }
122
+ ? { blocking_tasks: unfinished.map(blockingTask).sort(byRef) }
111
123
  : cause === 'acceptance_edge'
112
124
  ? { blocking_phases: uniqueRefs(blockingPhases).map((phase) => ({ ...phase })).sort(byRef) } : {},
113
125
  };
@@ -133,8 +145,10 @@ export function createTodoReadiness(store) {
133
145
  /** notice-impl: what a task waits on — predecessor tasks, phases whose accept it needs, and its own phase. */
134
146
  function prerequisiteRefs(key) {
135
147
  const node = nodes.get(key);
136
- const tasks = [...(incoming.get(key) ?? [])].map((source) => nodes.get(source))
137
- .filter((pred) => pred !== undefined).map(({ plan_key, task_id }) => ({ plan_key, task_id }));
148
+ const tasks = [...(incoming.get(key) ?? [])].map(predecessorNode)
149
+ .filter((pred) => pred !== undefined).map(({ project_id: projectId, plan_key, task_id }) => (
150
+ external.has(taskKey({ project_id: projectId, plan_key, task_id }))
151
+ ? { project_id: projectId, plan_key, task_id } : { plan_key, task_id }));
138
152
  const phaseRefs = [...(acceptanceIncoming.get(key) ?? [])].map((source) => phases.get(source))
139
153
  .filter((phase) => phase !== undefined).map(({ plan_key, phase_id }) => ({ plan_key, phase_id }));
140
154
  for (const source of incoming.get(key) ?? []) {
@@ -172,7 +186,13 @@ export function createTodoReadiness(store) {
172
186
  };
173
187
  }
174
188
 
175
- const refId = (ref) => `${ref.plan_key}\0${ref.task_id ?? ref.phase_id}`;
189
+ const refId = (ref) => `${ref.project_id ?? ''}\0${ref.plan_key}\0${ref.task_id ?? ref.phase_id}`;
190
+
191
+ /** a12 blocking entry; an external predecessor also names its project and why it waits (null when readable). */
192
+ function blockingTask({ project_id: projectId, plan_key, task_id, status, reason }) {
193
+ return projectId === undefined ? { plan_key, task_id, status }
194
+ : { project_id: projectId, plan_key, task_id, status, reason: reason ?? null };
195
+ }
176
196
  function byRef(left, right) {
177
197
  return refId(left) < refId(right) ? -1 : refId(left) > refId(right) ? 1 : 0;
178
198
  }
@@ -330,7 +330,7 @@ function crossPlanFindingEntry(value) {
330
330
  || !isTodoIdentifier(value.owner_plan_key)
331
331
  || !(value.event_digest === null || isTodoDigest(value.event_digest))
332
332
  || !['from', 'to'].includes(value.side)
333
- || !['binding_stale', 'endpoint_missing'].includes(value.reason)) return false;
333
+ || !['binding_stale', 'endpoint_missing', 'charts_root_unset', 'chart_unreadable'].includes(value.reason)) return false;
334
334
  const { ref } = value;
335
335
  const common = (keys) => exactRecord(ref, keys) && isTodoIdentifier(ref.project_id)
336
336
  && isTodoIdentifier(ref.plan_key)
@@ -534,6 +534,8 @@ function buildTodoGraph(readModel) {
534
534
  // active plan topologyは追記改変しない。開発中に接続したplan-scoped edgeを同じincomingへ
535
535
  // 合成することで、projectTodoStatusとcomputeReadyFrontierが同じ待機判定を即座に読む。
536
536
  for (const dependency of projectTodoCrossPlanDependencies(members)) {
537
+ // xchart: a predecessor on another chart is not a node here; readiness (external_tasks) decides next_ready.
538
+ if (dependency.from.project_id !== dependency.to.project_id) continue;
537
539
  addPredecessor(dependency.from, dependency.to);
538
540
  }
539
541