@quolu/lattice 0.114.4 → 0.116.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.
@@ -2010,6 +2010,132 @@ export async function readTodoCarriedBlocks({ repoRoot = process.cwd(), member,
2010
2010
  return found;
2011
2011
  }
2012
2012
 
2013
+ /**
2014
+ * A retained version's genesis, shape-only (a read never re-validates history, k4): the first line of its first journal
2015
+ * segment (a sealed one when the journal was split, else the active file, plain or gzip-packed). Null when unreadable.
2016
+ */
2017
+ async function readRetainedGenesis(repoRoot, journalRef) {
2018
+ const directory = path.posix.dirname(journalRef);
2019
+ const sealed = (await readdir(path.resolve(repoRoot, directory, 'sealed')).catch(() => [])).sort()[0];
2020
+ let bytes;
2021
+ if (sealed !== undefined) bytes = normalizeCheckoutEol(await readFile((await pathState(repoRoot, path.posix.join(directory, 'sealed', sealed), 'STORE_CORRUPT')).absolute));
2022
+ else {
2023
+ const plain = await pathState(repoRoot, journalRef, 'STORE_CORRUPT', { missing: true });
2024
+ bytes = plain === null ? gunzipSync(await readFile((await pathState(repoRoot, `${journalRef}.gz`, 'STORE_CORRUPT')).absolute),
2025
+ { maxOutputLength: TODO_LIMITS.snapshotBytes }) : normalizeCheckoutEol(await readFile(plain.absolute));
2026
+ }
2027
+ // The line's weight is `state_migration` (one state per task); canonical keys put it after everything this needs, so cut it off unparsed.
2028
+ const end = bytes.indexOf('\n');
2029
+ const cut = bytes.indexOf(',"state_migration":', 0, 'utf8');
2030
+ return taskAddedGenesis(JSON.parse(cut >= 0 && cut < end ? `${bytes.toString('utf8', 0, cut)}}` : bytes.toString('utf8', 0, end)));
2031
+ }
2032
+
2033
+ /** What the added-by walk needs of a plan_genesis: `{at, agent, predecessor, moves}`, or null when it is not one. */
2034
+ function taskAddedGenesis(event) {
2035
+ const moves = event?.payload?.task_migration;
2036
+ if (event?.kind !== 'plan_genesis' || typeof event.recorded_at !== 'string' || !Array.isArray(moves)) return null;
2037
+ return { at: event.recorded_at, agent: typeof event.actor?.agent === 'string' ? event.actor.agent : null,
2038
+ predecessor: event.payload.predecessor_plan_digest ?? null, moves };
2039
+ }
2040
+
2041
+ const TASK_ADDED_CACHE_DIRECTORY = '.lattice/generated/store-task-added';
2042
+ const TASK_ADDED_CACHE_SCHEMA = 'lattice.todo_task_added_cache.v2'; // v1 held null for plan-create tasks; a v1 file is a miss
2043
+
2044
+ /**
2045
+ * A derived per-plan cache file `<directory>/<plan_key>.json` (a body plus its `cache_digest`), or null for any miss: absent,
2046
+ * unreadable, wrong schema or plan, bad digest. Derived data is never truth: a miss is a recomputation (n3, w2).
2047
+ */
2048
+ export async function readDerivedPlanCache(root, directory, schema, planKey) {
2049
+ try {
2050
+ const bytes = await readFile(path.resolve(root, directory, `${planKey}.json`));
2051
+ if (bytes.length > TODO_LIMITS.snapshotBytes) return null;
2052
+ const { cache_digest: digest, ...body } = JSON.parse(bytes.toString('utf8'));
2053
+ return body.schema === schema && body.plan_key === planKey && digest === sha256Bytes(Buffer.from(JSON.stringify(body), 'utf8')) ? body : null;
2054
+ } catch { return null; }
2055
+ }
2056
+
2057
+ /** Atomically writes `body` (with `schema` and `plan_key`) as the derived cache of its plan. Callers ignore a failure: a lost write is a later recomputation. */
2058
+ export async function publishDerivedPlanCache(repoRoot, directory, body) {
2059
+ const root = await canonicalRepoRoot(repoRoot); // macOS tmp is a symlink: ensureGeneratedDirectory wants the real path
2060
+ const ref = `${directory}/${body.plan_key}.json`;
2061
+ await ensureGeneratedDirectory(root, ref);
2062
+ const text = JSON.stringify(body);
2063
+ await atomicWrite(path.resolve(root, ref), Buffer.from(`${text.slice(0, -1)},"cache_digest":"${sha256Bytes(Buffer.from(text, 'utf8'))}"}`, 'utf8'));
2064
+ }
2065
+
2066
+ /** The cached `task_id -> [at, agent] | null` of one plan head, or null for any miss. */
2067
+ async function readTaskAddedCache(root, planKey) {
2068
+ const body = await readDerivedPlanCache(root, TASK_ADDED_CACHE_DIRECTORY, TASK_ADDED_CACHE_SCHEMA, planKey);
2069
+ if (body === null || typeof body.head_plan_digest !== 'string' || body.tasks === null || typeof body.tasks !== 'object') return null;
2070
+ return { head: body.head_plan_digest, tasks: new Map(Object.entries(body.tasks)) };
2071
+ }
2072
+
2073
+ function publishTaskAddedCache(repoRoot, plan, added) {
2074
+ return publishDerivedPlanCache(repoRoot, TASK_ADDED_CACHE_DIRECTORY, { schema: TASK_ADDED_CACHE_SCHEMA, plan_key: plan.plan_key,
2075
+ head_plan_digest: plan.plan_digest,
2076
+ tasks: Object.fromEntries(plan.tasks.map(({ task_id: id }) => [id, added.has(id) ? [added.get(id).at, added.get(id).agent] : null])) });
2077
+ }
2078
+
2079
+ /**
2080
+ * n3-store-task-added: who added each task and when, for the member's active plan, from the retained revisions. A task is
2081
+ * new in a version when it is not a `to_task_id` of that version's genesis `task_migration`; a carried one follows
2082
+ * `to_task_id` -> `from_task_id` into the predecessor (two from ids onto one id: the first wins). One pass back along
2083
+ * `predecessor_plan_digest` resolves every task: `{at, agent}` = that genesis's `recorded_at` and `actor.agent` (null
2084
+ * when absent). A task that came with plan create gets the first version's genesis (the plan's creator). Read only for the Store: a missing or unreadable version ends
2085
+ * the walk and leaves the tasks not yet resolved without an entry. A walk that reached the first version is kept in the
2086
+ * derived `.lattice/generated/store-task-added/<plan_key>.json` (best effort, never truth: a miss walks), so the next
2087
+ * revision's read stops at the cached head after its own genesis. Memoized per process by the active plan.json's identity.
2088
+ */
2089
+ export async function readTodoTaskAdded({ repoRoot = process.cwd(), member }) {
2090
+ const { plan } = member;
2091
+ const root = path.resolve(repoRoot);
2092
+ return memoByFileIdentity([path.resolve(root, member.descriptor.plan_ref)], async () => {
2093
+ const added = new Map();
2094
+ let genesis = taskAddedGenesis(member.journal.events[0]);
2095
+ if (genesis === null) return added;
2096
+ const created = (tasks) => { for (const task of tasks) added.set(task, { at: genesis.at, agent: genesis.agent }); };
2097
+ if (genesis.predecessor === null) { created(plan.tasks.map(({ task_id: id }) => id)); return added; }
2098
+ const cache = await readTaskAddedCache(root, plan.plan_key);
2099
+ const fromCache = (id, tasks) => {
2100
+ const entry = cache.tasks.get(id);
2101
+ if (Array.isArray(entry)) for (const task of tasks) added.set(task, { at: entry[0], agent: entry[1] });
2102
+ };
2103
+ if (cache?.head === plan.plan_digest) {
2104
+ for (const { task_id: id } of plan.tasks) fromCache(id, [id]);
2105
+ return added;
2106
+ }
2107
+ let complete = false;
2108
+ try {
2109
+ let byDigest = null;
2110
+ let open = new Map(plan.tasks.map(({ task_id: id }) => [id, [id]]));
2111
+ for (let steps = 0; ; steps += 1) {
2112
+ const from = new Map();
2113
+ for (const move of genesis.moves) if (open.has(move.to_task_id) && !from.has(move.to_task_id)) from.set(move.to_task_id, move.from_task_id);
2114
+ const next = new Map();
2115
+ for (const [id, tasks] of open) {
2116
+ if (from.has(id)) next.set(from.get(id), [...(next.get(from.get(id)) ?? []), ...tasks]);
2117
+ else for (const task of tasks) added.set(task, { at: genesis.at, agent: genesis.agent });
2118
+ }
2119
+ open = next;
2120
+ if (cache?.head === genesis.predecessor) {
2121
+ for (const [id, tasks] of open) fromCache(id, tasks);
2122
+ complete = true;
2123
+ break;
2124
+ }
2125
+ if (open.size === 0) { complete = true; break; }
2126
+ byDigest ??= await retainedPlanVersions(root, plan);
2127
+ const predecessor = byDigest.get(genesis.predecessor);
2128
+ const prior = predecessor === undefined || steps > byDigest.size ? null : await readRetainedGenesis(root, predecessor.journalRef);
2129
+ if (prior === null) break;
2130
+ genesis = prior;
2131
+ if (prior.predecessor === null) { created([...open.values()].flat()); complete = true; break; } // the first version: its tasks came with plan create, by its creator
2132
+ }
2133
+ } catch { /* an unreadable version leaves the tasks not yet resolved without an entry */ }
2134
+ if (complete) await publishTaskAddedCache(root, plan, added).catch(() => {}); // derived: a lost write is a later walk
2135
+ return added;
2136
+ }, 'task-added');
2137
+ }
2138
+
2013
2139
  /**
2014
2140
  * Composes the source plan's recorded task migrations back to the version whose topology the
2015
2141
  * connection names (u03): returns the source task id it maps to now, 'removed', or null (unknown).
@@ -2368,10 +2494,10 @@ async function publishDisplayCheckpointHead(repoRoot, source) {
2368
2494
  }), 'utf8'));
2369
2495
  }
2370
2496
 
2371
- async function publishDisplayCheckpoint(repoRoot, { verified_at: verifiedAt, source, store }) {
2372
- const root = await canonicalRepoRoot(repoRoot);
2497
+ /** The derived directory `dirname(ref)` under `root`, made when absent; a symlink or alias on the way is refused. */
2498
+ async function ensureGeneratedDirectory(root, ref) {
2373
2499
  let directory = root;
2374
- for (const segment of path.posix.dirname(DISPLAY_CHECKPOINT_REF).split('/')) {
2500
+ for (const segment of path.posix.dirname(ref).split('/')) {
2375
2501
  directory = path.join(directory, segment);
2376
2502
  if (segment !== '.lattice') await mkdir(directory).catch((error) => { if (error?.code !== 'EEXIST') throw error; });
2377
2503
  const stats = await lstat(directory);
@@ -2379,6 +2505,11 @@ async function publishDisplayCheckpoint(repoRoot, { verified_at: verifiedAt, sou
2379
2505
  fail('STORE_DISPLAY_CHECKPOINT_UNSAFE', 'unsafe_checkpoint_directory', { ref: path.relative(root, directory) });
2380
2506
  }
2381
2507
  }
2508
+ }
2509
+
2510
+ async function publishDisplayCheckpoint(repoRoot, { verified_at: verifiedAt, source, store }) {
2511
+ const root = await canonicalRepoRoot(repoRoot);
2512
+ await ensureGeneratedDirectory(root, DISPLAY_CHECKPOINT_REF);
2382
2513
  // s5: the store is serialized once (37.8 MB on bellteam): the digest covers the object without checkpoint_digest, the file adds it last.
2383
2514
  const body = JSON.stringify({ schema: DISPLAY_CHECKPOINT_SCHEMA, verified_at: verifiedAt, source, store });
2384
2515
  const digest = sha256Bytes(Buffer.from(body, 'utf8'));
@@ -2420,6 +2551,44 @@ export async function readTodoStoreDisplaySource({ repoRoot = process.cwd() } =
2420
2551
  return observeDisplaySource(root, manifest);
2421
2552
  }
2422
2553
 
2554
+ /**
2555
+ * n2-store-outgoing: the live cross-project edges a chart waits on, `{project_id, edges}`, without a Store replay.
2556
+ * Edges live only in each member's plan-scoped chain (the consumer's); this reads the manifest and those chains
2557
+ * (`verify: false`, as every read) and skips the lifecycle replay, snapshots, phases and graph validation. An edge is
2558
+ * the same record as `projectTodoCrossPlanDependencies` (tombstones applied, same order) whose `from` is another
2559
+ * project. A chart with no Store is `{project_id: null, edges: []}`; a corrupt chain throws the typed Store error, so a
2560
+ * caller can tell "unread" from "no edges". Read-only, no on-disk change; the filtered events are memoized per process.
2561
+ */
2562
+ export async function readTodoOutgoingConnections({ repoRoot = process.cwd() } = {}) {
2563
+ try {
2564
+ const { project_id: projectId, edges } = await readStoreStableWith({ repoRoot: path.resolve(repoRoot) }, readOutgoingConnections);
2565
+ return { project_id: projectId, edges };
2566
+ } catch (error) {
2567
+ if (error?.code === 'STORE_UNINITIALIZED') return { project_id: null, edges: [] };
2568
+ throw error;
2569
+ }
2570
+ }
2571
+
2572
+ const OUTGOING_EVENT_KINDS = new Set(['cross_plan_dependency', 'cross_plan_dependency_removed']);
2573
+
2574
+ async function readOutgoingConnections({ repoRoot }) {
2575
+ const manifest = await readManifest(repoRoot);
2576
+ const members = [];
2577
+ for (const { journal_ref: journalRef } of manifest.members) {
2578
+ const files = [path.resolve(repoRoot, planScopedJournalRef(journalRef)),
2579
+ path.resolve(repoRoot, path.dirname(journalRef), PLAN_SCOPED_SEALED_DIRECTORY)];
2580
+ const events = await memoByFileIdentity(files, async () => (
2581
+ await readPlanScopedJournal(repoRoot, journalRef, { verify: false })
2582
+ ).events.filter(({ kind }) => OUTGOING_EVENT_KINDS.has(kind)), 'outgoing');
2583
+ members.push({ plan_scoped: { events } });
2584
+ }
2585
+ const edges = projectTodoCrossPlanDependencies(members)
2586
+ .filter(({ from }) => from.project_id !== manifest.project_id)
2587
+ .map(({ from, to, reason, event_digest: eventDigest, connected_at: connectedAt }) => (
2588
+ { from, to, reason, event_digest: eventDigest, connected_at: connectedAt }));
2589
+ return { project_id: manifest.project_id, manifest, edges };
2590
+ }
2591
+
2423
2592
  /** Display-only envelope: verified > unverified current raw > last_verified > unavailable. */
2424
2593
  export async function readTodoStoreForDisplay({ repoRoot = process.cwd(), now } = {}) {
2425
2594
  const root = path.resolve(repoRoot);
@@ -0,0 +1,62 @@
1
+ // n2: who waits on a task through 接続, across charts and projects (docs/architecture/dfd-connect.md, n1).
2
+ // The edges live in the waiting charts' plan-scoped chains; this reads them through the Store's cheap outgoing reader
3
+ // (no replay of the other charts) and judges each against the target's state in THIS chart. Read-only, no watcher.
4
+
5
+ import path from 'node:path';
6
+
7
+ import { chartIds } from './chart-cli.mjs';
8
+ import { TODO_CHARTS_ROOT_ENV } from './todo-external.mjs';
9
+ import { judgeTaskConnection } from './todo-store-view.mjs';
10
+ import { readTodoOutgoingConnections } from './todo-store.mjs';
11
+
12
+ const byText = (left, right) => (left < right ? -1 : left > right ? 1 : 0);
13
+
14
+ /**
15
+ * `{waiters: Map<'plan\0task', waiter[]>, unread: [{project_id, reason}]}` for every task of `store` that another chart
16
+ * waits on. A waiter: `{project_id, plan_key, task_id, kind: 'task', state, state_reason?, reason, since, event_digest}`
17
+ * (project/plan/task name the WAITING task; `state` is the 接続's judgment against the target now). An unreadable chart
18
+ * is named in `unread`, never read as "no waiters".
19
+ */
20
+ export async function listTodoConnectionWaiters(store, env) {
21
+ const root = env?.[TODO_CHARTS_ROOT_ENV];
22
+ const waiters = new Map();
23
+ // No charts root = a single chart: there is no other chart to wait from (not an unread chart).
24
+ if (typeof root !== 'string' || root === '') return { waiters, unread: [] };
25
+ const unread = [];
26
+ const states = new Map(store.members.flatMap((member) => member.tasks.map((task) => [
27
+ `${member.plan.plan_key}\0${task.task_id}`, task])));
28
+ for (const id of await chartIds(path.resolve(root))) {
29
+ if (id === store.project_id) continue;
30
+ let outgoing;
31
+ try { outgoing = await readTodoOutgoingConnections({ repoRoot: path.join(path.resolve(root), id) }); } catch (error) {
32
+ unread.push({ project_id: id, reason: error?.detail?.reason ?? error?.code ?? 'chart_unreadable' });
33
+ continue;
34
+ }
35
+ for (const edge of outgoing.edges) {
36
+ if (edge.from.project_id !== store.project_id) continue;
37
+ const target = states.get(`${edge.from.plan_key}\0${edge.from.task_id}`);
38
+ const key = `${edge.from.plan_key}\0${edge.from.task_id}`;
39
+ const { state, state_reason: stateReason } = judgeTaskConnection(
40
+ target === undefined ? { status: null, missing: true } : { status: target.status });
41
+ waiters.set(key, [...(waiters.get(key) ?? []), {
42
+ project_id: edge.to.project_id, plan_key: edge.to.plan_key, task_id: edge.to.task_id, kind: 'task', state,
43
+ ...(stateReason === undefined ? {} : { state_reason: stateReason }),
44
+ reason: edge.reason, since: edge.connected_at, event_digest: edge.event_digest }]);
45
+ }
46
+ }
47
+ for (const [key, list] of waiters) {
48
+ waiters.set(key, list.sort((left, right) => byText(`${left.project_id}\0${left.plan_key}\0${left.task_id}`,
49
+ `${right.project_id}\0${right.plan_key}\0${right.task_id}`)));
50
+ }
51
+ return { waiters, unread };
52
+ }
53
+
54
+ /** `[{plan_key, task_id, waiters}]` sorted, for every task that has any (`open` keeps only the ones still waiting). */
55
+ export function waitersByTask(waiters, { open = false, planKey = null, taskId = null } = {}) {
56
+ return [...waiters].map(([key, list]) => {
57
+ const [plan, task] = key.split('\0');
58
+ return { plan_key: plan, task_id: task, waiters: open ? list.filter(({ state }) => state === 'open') : list };
59
+ }).filter((entry) => entry.waiters.length > 0 && (planKey === null || entry.plan_key === planKey)
60
+ && (taskId === null || entry.task_id === taskId))
61
+ .sort((left, right) => byText(`${left.plan_key}\0${left.task_id}`, `${right.plan_key}\0${right.task_id}`));
62
+ }