@quolu/lattice 0.111.5 → 0.113.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.111.5",
3
+ "version": "0.113.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",
package/src/cli-help.mjs CHANGED
@@ -96,7 +96,8 @@ Read commands:
96
96
  notice list [--lane <lane>] [--include-acked] [--json] # 着手できるようになった工程の知らせ(既定は未ackだけ。lane省略で全lane)
97
97
  blockers [--json] # ブロック中の工程を全部返す(題・担当・理由の全文・ブロックした時刻と者・外すコマンド。読むだけ。外すのは誰でも todo unblock)
98
98
  bindings [--plan <key>] [--json] # compile_binding付きTaskをTODO identityつきで投影する
99
- display read [--json] # host表示用の工程表読取(lattice.todo_display_read_result.v1)。不整合でも断らずstateで返す
99
+ display read [--json] [--compact] [--open] # host表示用の工程表読取(lattice.todo_display_read_result.v1)。不整合でも断らずstateで返す。--compact は journal を activity、plan_scoped を cross_plan_dependencies に絞った lattice.todo_display_compact_result.v1(大きさは task と生きた線に比例)。--open は --compact を含み、task ごとの一覧を開いた木の task だけに絞って closed {trees, tasks} を足す lattice.todo_display_open_result.v1
100
+ display history [--json] [--limit <n>] [--before <cursor>] # 閉じた木の task を終了の新しい順に1ページ返す(lattice.todo_display_history_result.v1。limit 既定50・最大500、next_cursor を --before へ渡して次頁)
100
101
  display source [--json] # 安い変更検知(lattice.todo_store_display_source.v1)。変わった時だけreadする
101
102
  independence [--plan <key>] [--json] # readyを検証済み並列・要直列・未検査へ分けて投影する
102
103
  structure --schema --json # plan定義後に入力する論理dataflow契約をstore非依存で返す
@@ -347,7 +348,7 @@ const SUBCOMMAND_USAGE = Object.freeze({
347
348
  'todo blockers': 'todo blockers [--json] # lattice.todo_blockers_result.v1 {blockers: [{plan_key, task_id, title, lane, reason, blocked_at, blocked_by, unblock_action}]}',
348
349
  'todo wait': 'todo wait --plan <key> --task <id> [--reason <text>] | --cancel [--json] # 廃止予定の別名: todo connect priority',
349
350
  'todo bindings': 'todo bindings [--plan <key>] [--json]',
350
- 'todo display': 'todo display read [--json] | source [--json] # host表示用の読取。不整合でも断らずstateで返す',
351
+ 'todo display': 'todo display read [--json] [--compact] [--open] | history [--json] [--limit <n>] [--before <cursor>] | source [--json] # host表示用の読取。不整合でも断らずstateで返す',
351
352
  charts: 'charts list [--json] | source [--project <id>]... [--json] # LATTICE_CHARTS_ROOT配下の全工程表を1プロセスで読む',
352
353
  'charts list': 'charts list [--json] # lattice.charts_list_result.v1 {charts_root, charts:[{project_id, name, created_by, created_at, source}], findings}',
353
354
  'charts source': 'charts source [--project <id>]... [--json] # lattice.charts_source_result.v1 {charts:{<id>: <source>|null}}(--project無し=全工程表)',
@@ -356,7 +357,8 @@ const SUBCOMMAND_USAGE = Object.freeze({
356
357
  'chart repo': 'chart repo bind --url <url> --branch <branch> [--json] | sync [--json] # lattice.chart_repo_result.v1',
357
358
  'chart repo bind': 'chart repo bind --url <url> --branch <branch> [--json] # コード工程表のrepoを記録する',
358
359
  'chart repo sync': 'chart repo sync [--json] # depth-1 fetch、accepted_tipからだけ前進(reset/forceしない)、その後sensor。status current|synced|dirty|diverged|failed',
359
- 'todo display read': 'todo display read [--json] # lattice.todo_display_read_result.v1(state: verified|unverified|last_verified|unavailable)',
360
+ 'todo display read': 'todo display read [--json] [--compact] [--open] # lattice.todo_display_read_result.v1(state: verified|unverified|last_verified|unavailable)。--compact: lattice.todo_display_compact_result.v1(journal→activity、plan_scoped→cross_plan_dependencies)。--open: lattice.todo_display_open_result.v1(--compact を含み、開いた木の task だけ + closed {trees, tasks})',
361
+ 'todo display history': 'todo display history [--json] [--limit <n>] [--before <cursor>] # lattice.todo_display_history_result.v1 {state, verified_at, source, inconsistency, dropped_members, closed:{trees,tasks}, tasks:[{tree_id, plan_key, task_id, title, lane, phase_id, parent_task_id, design_memo, done_condition, status, done_at, finished_at, activity:{changed_at, started}}], next_cursor}(閉じた木だけ。finished_at の新しい順。limit 既定50・最大500。不正な cursor は INVALID_ARGUMENTS)',
360
362
  'todo display source': 'todo display source [--json] # lattice.todo_store_display_source.v1(安い変更検知。変わった時だけreadする)',
361
363
  'todo independence': 'todo independence [--plan <key>] [--json] | mode --plan <key> --set <witness|conversation|enforced> --reason <text>'
362
364
  + ' | compile --plan <key> --input <file> | compile --schema --json | witness migrate --plan <key>'
package/src/todo-cli.mjs CHANGED
@@ -173,6 +173,7 @@ import {
173
173
  externalCycle, readTodoExternalChart, readTodoExternalTasks, withTodoExternalTasks,
174
174
  } from './todo-external.mjs';
175
175
  import { projectTodoTrees } from './todo-trees.mjs';
176
+ import { closedDisplayHistory, compactDisplayStore, decodeHistoryCursor, openDisplayResult } from './todo-store-view.mjs';
176
177
  import { projectTodoBlockers, todoBlockerKey } from './todo-blockers.mjs';
177
178
  import {
178
179
  ackTodoNotices, cancelTodoNoticeWait, readAllTodoNoticeAcks, readAllTodoNoticeWaits, readTodoNoticeAcks, writeTodoNoticeWait,
@@ -371,6 +372,7 @@ const TODO_FLAG_SPECS = Object.freeze({
371
372
  'phase accept': Object.freeze({ known: ['plan', 'phase', 'evidence', 'message'], required: ['plan', 'phase'] }),
372
373
  'phase reject': Object.freeze({ known: ['plan', 'phase', 'evidence', 'message', 'reason'], required: ['plan', 'phase'] }),
373
374
  'phase reopen': Object.freeze({ known: ['plan', 'phase', 'reason', 'override-reason'], required: ['plan', 'phase', 'reason'] }),
375
+ 'display history': Object.freeze({ known: ['json', 'limit', 'before'], booleans: ['json'] }),
374
376
  'independence compile': Object.freeze({ known: ['plan', 'input'], required: ['plan', 'input'] }),
375
377
  'independence mode': Object.freeze({ known: ['plan', 'set', 'reason'], required: ['plan', 'set', 'reason'] }),
376
378
  'independence witness scaffold': Object.freeze({ known: ['plan', 'input'], required: ['plan', 'input'] }),
@@ -1280,13 +1282,37 @@ async function startAdvisory({ repoRoot, store, projection, planKey, taskId }) {
1280
1282
  * xchart: the display envelope plus `external_tasks`, so a host computing readiness from it sees other charts too;
1281
1283
  * a100: plus `trees`, each task tree and its size, so the host never computes the graph.
1282
1284
  */
1283
- async function displayRead(repoRoot, env) {
1285
+ async function displayRead(repoRoot, env, { compact = false, open = false } = {}) {
1284
1286
  const display = await readTodoStoreForDisplay({ repoRoot });
1285
1287
  const externalTasks = display.store ? (await readTodoExternalTasks(display.store, env)).external_tasks : [];
1286
- return { schema: 'lattice.todo_display_read_result.v1', ...display, external_tasks: externalTasks,
1288
+ const result = { schema: 'lattice.todo_display_read_result.v1', ...display, external_tasks: externalTasks,
1287
1289
  trees: display.store ? projectTodoTrees(display.store) : [],
1288
1290
  ...(display.store && splitLabels(display.store).length > 0 ? { labels: splitLabels(display.store) } : {}),
1289
1291
  connections: display.store ? await displayConnections(repoRoot, { ...display.store, external_tasks: externalTasks }) : [] };
1292
+ // trees, labels and connections are read from the full view above; only the shipped store is compacted
1293
+ const light = compact || open ? { ...result, schema: 'lattice.todo_display_compact_result.v1', store: result.store && compactDisplayStore(result.store) } : result;
1294
+ return open ? openDisplayResult(light) : light;
1295
+ }
1296
+
1297
+ const HISTORY_DEFAULT_LIMIT = 50;
1298
+ const HISTORY_MAX_LIMIT = 500;
1299
+
1300
+ /** `todo display history`: the display envelope plus one page of the tasks of closed trees (newest finish first). */
1301
+ async function displayHistory(repoRoot, { limit, before }) {
1302
+ const display = await readTodoStoreForDisplay({ repoRoot });
1303
+ const trees = display.store ? projectTodoTrees(display.store) : [];
1304
+ const { state, verified_at: verifiedAt, source, inconsistency, dropped_members: dropped } = display;
1305
+ return { schema: 'lattice.todo_display_history_result.v1', state, verified_at: verifiedAt, source, inconsistency,
1306
+ dropped_members: dropped, ...closedDisplayHistory({ store: display.store, trees }, { limit, before }) };
1307
+ }
1308
+
1309
+ /** `display history` flags by name (--json optional): `{limit, before}`, or null for an unknown flag, a bad limit or an unparsable cursor. */
1310
+ function historyFlags(argv) {
1311
+ const flags = matchFlagCommand(argv, ['display', 'history'], TODO_FLAG_SPECS['display history']);
1312
+ if (flags === null || (flags.limit !== undefined && !/^[1-9][0-9]*$/.test(flags.limit))) return null;
1313
+ const before = flags.before === undefined ? null : decodeHistoryCursor(flags.before);
1314
+ return flags.before !== undefined && before === null ? null
1315
+ : { limit: Math.min(flags.limit === undefined ? HISTORY_DEFAULT_LIMIT : Number(flags.limit), HISTORY_MAX_LIMIT), before };
1290
1316
  }
1291
1317
 
1292
1318
  /** 接続: `[{plan_key, task_id, connections}]` for every task that has any (the one list: 他条件に接続 and 優先接続). */
@@ -5460,11 +5486,16 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
5460
5486
  && (argv.length === 3 || argv[3] === '--json')) {
5461
5487
  action = (repoRoot) => bindings({ repoRoot, requestedPlanKey: argv[2] });
5462
5488
  } else if (argv[0] === 'display' && (argv[1] === 'read' || argv[1] === 'source')
5463
- && (argv.length === 2 || (argv.length === 3 && argv[2] === '--json'))) {
5489
+ && (argv.length === 2 || (argv.length === 3 && argv[2] === '--json')
5490
+ || (argv[1] === 'read' && argv.slice(2).every((flag) => flag === '--json' || flag === '--compact' || flag === '--open')
5491
+ && new Set(argv.slice(2)).size === argv.length - 2))) {
5464
5492
  // Host display read (BellTeam module): a typed inconsistency is a state, never a refusal.
5465
5493
  action = argv[1] === 'read'
5466
- ? async (repoRoot) => displayRead(repoRoot, env)
5494
+ ? async (repoRoot) => displayRead(repoRoot, env, { compact: argv.includes('--compact'), open: argv.includes('--open') })
5467
5495
  : (repoRoot) => readTodoStoreDisplaySource({ repoRoot });
5496
+ } else if (argv[0] === 'display' && argv[1] === 'history' && historyFlags(argv) !== null) {
5497
+ const flags = historyFlags(argv);
5498
+ action = (repoRoot) => displayHistory(repoRoot, flags);
5468
5499
  } else if (argv[0] === 'note' && argv[1] !== 'list') {
5469
5500
  const flags = matchFlagCommand(argv, ['note'], NOTE_FLAG_SPEC);
5470
5501
  const hasMessage = typeof flags?.message === 'string' && flags.message.length > 0;
@@ -76,6 +76,147 @@ export function projectTodoCrossPlanDependencies(members) {
76
76
  });
77
77
  }
78
78
 
79
+ /**
80
+ * A member's journal as the host reads it: `{first: {at, agent}|null, last_at, tasks: [{task_id, changed_at, started: {at, agent}|null}]}`
81
+ * (`started` = the last `start`; only tasks with an event). One loop for the compact read and the closed history.
82
+ */
83
+ function journalActivity(events) {
84
+ const tasks = new Map();
85
+ let first = null;
86
+ let last = null;
87
+ for (const event of events) {
88
+ if (first === null || event.recorded_at < first.recorded_at) first = event;
89
+ if (last === null || event.recorded_at > last) last = event.recorded_at;
90
+ if (event.task_id === undefined || event.task_id === null) continue;
91
+ const entry = tasks.get(event.task_id) ?? { task_id: event.task_id, changed_at: event.recorded_at, started: null };
92
+ if (event.recorded_at > entry.changed_at) entry.changed_at = event.recorded_at;
93
+ if (event.kind === 'start') entry.started = { at: event.recorded_at, agent: event.actor?.agent ?? null };
94
+ tasks.set(event.task_id, entry);
95
+ }
96
+ return { first: first === null ? null : { at: first.recorded_at, agent: first.actor?.agent ?? null },
97
+ last_at: last, tasks: [...tasks.values()] };
98
+ }
99
+
100
+ /**
101
+ * Compact display read (host surface, `todo display read --compact`): each member's `journal` and `plan_scoped` are replaced by
102
+ * what a chart host uses, so the size grows with tasks and live edges, never with notes, evidence or repeated events.
103
+ * `activity` = `journalActivity`; `cross_plan_dependencies` = the live
104
+ * `[{event_digest, from, to}]` of the member's plan-scoped chain (a removal in any member's chain drops it).
105
+ * A member with neither (the unverified raw read) is returned as it is.
106
+ */
107
+ export function compactDisplayStore(store) {
108
+ const removed = new Set(store.members.flatMap((member) => (member.plan_scoped?.events ?? [])
109
+ .filter((event) => event.kind === 'cross_plan_dependency_removed').map((event) => event.payload.target_event_digest)));
110
+ return { ...store, members: store.members.map(({ journal, plan_scoped: planScoped, ...member }) => {
111
+ if (journal === undefined && planScoped === undefined) return member;
112
+ return { ...member,
113
+ activity: journalActivity(journal?.events ?? []),
114
+ cross_plan_dependencies: (planScoped?.events ?? [])
115
+ .filter((event) => event.kind === 'cross_plan_dependency' && !removed.has(event.event_digest))
116
+ .map((event) => ({ event_digest: event.event_digest, from: event.payload.from, to: event.payload.to })) };
117
+ }) };
118
+ }
119
+
120
+ const isObject = (value) => value !== null && typeof value === 'object';
121
+ const taskKeyOf = (planKey, taskId) => `${planKey}\0${taskId}`;
122
+ const isOpenTree = ({ finished, total }) => finished < total;
123
+
124
+ /**
125
+ * Open display read (`todo display read --open`): the compact result with every per-task list limited to the tasks of open
126
+ * trees (`finished < total` in the result's own `trees`, the one source) and `closed: {trees, tasks}` over the chart.
127
+ * Pure. `plan.phases`, descriptors and `activity.first/last_at` stay whole. A ref of another chart is never a task of
128
+ * this chart here, so a join or dependency naming one keeps it.
129
+ */
130
+ export function openDisplayResult(result) {
131
+ const trees = result.trees ?? [];
132
+ const closedTrees = trees.filter((tree) => !isOpenTree(tree));
133
+ const kept = new Set(trees.filter(isOpenTree).flatMap(({ tasks }) => tasks.map((task) => taskKeyOf(task.plan_key, task.task_id))));
134
+ const closed = { trees: closedTrees.length, tasks: closedTrees.reduce((sum, { total }) => sum + total, 0) };
135
+ const connections = (result.connections ?? []).filter(({ plan_key: planKey, task_id: taskId }) => kept.has(taskKeyOf(planKey, taskId)));
136
+ const referred = new Set(connections.flatMap((entry) => entry.connections.map(({ ref }) => ref)));
137
+ const base = { ...result, schema: 'lattice.todo_display_open_result.v1',
138
+ trees: trees.filter(isOpenTree), connections, closed,
139
+ external_tasks: (result.external_tasks ?? []).filter(({ project_id: projectId, plan_key: planKey, task_id: taskId }) => referred.has(`${projectId}/${planKey}/${taskId}`)) };
140
+ if (!isObject(result.store)) return base;
141
+ const { store } = result;
142
+ return { ...base, store: { ...store, members: store.members.map((member) => {
143
+ const planKey = member.descriptor?.plan_key ?? member.plan?.plan_key;
144
+ const projectId = member.plan?.project_id ?? store.project_id;
145
+ const keptTask = ({ task_id: taskId }) => kept.has(taskKeyOf(planKey, taskId));
146
+ const local = (ref) => (ref.project_id ?? projectId) === projectId;
147
+ const keepRef = (ref) => isObject(ref) && (!local(ref) || kept.has(taskKeyOf(ref.plan_key, ref.task_id)));
148
+ const next = { ...member };
149
+ if (Array.isArray(member.tasks)) next.tasks = member.tasks.filter(keptTask);
150
+ if (Array.isArray(member.snapshot?.tasks)) next.snapshot = { ...member.snapshot, tasks: member.snapshot.tasks.filter(keptTask) };
151
+ if (isObject(member.plan)) {
152
+ next.plan = { ...member.plan };
153
+ if (Array.isArray(member.plan.tasks)) next.plan.tasks = member.plan.tasks.filter(keptTask);
154
+ if (Array.isArray(member.plan.hard_dependencies)) next.plan.hard_dependencies = member.plan.hard_dependencies.filter((edge) => keepRef(edge?.to));
155
+ if (Array.isArray(member.plan.joins)) {
156
+ next.plan.joins = member.plan.joins.filter((entry) => keepRef(entry?.before))
157
+ .map((entry) => ({ ...entry, after: (entry.after ?? []).filter(keepRef) }));
158
+ }
159
+ }
160
+ if (isObject(member.activity)) next.activity = { ...member.activity, tasks: member.activity.tasks.filter(keptTask) };
161
+ if (Array.isArray(member.cross_plan_dependencies)) {
162
+ next.cross_plan_dependencies = member.cross_plan_dependencies
163
+ .filter(({ from, to }) => [from, to].some((ref) => isObject(ref) && local(ref) && kept.has(taskKeyOf(ref.plan_key, ref.task_id))));
164
+ }
165
+ return next;
166
+ }) } };
167
+ }
168
+
169
+ const compareCodeUnit = (left, right) => (left < right ? -1 : left > right ? 1 : 0);
170
+ // History order: finished_at newest first (no time last), then plan_key, task_id ascending.
171
+ const compareHistory = (left, right) => compareCodeUnit(right.finished_at ?? '', left.finished_at ?? '')
172
+ || compareCodeUnit(left.plan_key, right.plan_key) || compareCodeUnit(left.task_id, right.task_id);
173
+ const CURSOR_PREFIX = 'h1.';
174
+ const encodeHistoryCursor = ({ finished_at: finishedAt, plan_key: planKey, task_id: taskId }) =>
175
+ CURSOR_PREFIX + Buffer.from(JSON.stringify([finishedAt, planKey, taskId])).toString('base64url');
176
+
177
+ /** The position a `next_cursor` names as a row-shaped key, or null when it does not parse. */
178
+ export function decodeHistoryCursor(cursor) {
179
+ if (typeof cursor !== 'string' || !cursor.startsWith(CURSOR_PREFIX)) return null;
180
+ try {
181
+ const [finishedAt, planKey, taskId] = JSON.parse(Buffer.from(cursor.slice(CURSOR_PREFIX.length), 'base64url').toString('utf8'));
182
+ return (finishedAt === null || typeof finishedAt === 'string') && typeof planKey === 'string' && typeof taskId === 'string'
183
+ ? { finished_at: finishedAt, plan_key: planKey, task_id: taskId } : null;
184
+ } catch { return null; }
185
+ }
186
+
187
+ /**
188
+ * Closed history (`todo display history`): the tasks of closed trees (`finished >= total`), newest finish first, one page.
189
+ * `{closed: {trees, tasks}, tasks: [...], next_cursor}`; `before` is a decoded cursor (rows after it), `limit` a clamped count.
190
+ * `finished_at` = `done_at` of a done task, else the task's latest journal event. Pure; reads the full (not compact) store.
191
+ */
192
+ export function closedDisplayHistory({ store, trees }, { limit, before = null }) {
193
+ const closedTrees = trees.filter((tree) => !isOpenTree(tree));
194
+ const members = new Map((store?.members ?? []).map((member) => {
195
+ const planKey = member.descriptor?.plan_key ?? member.plan?.plan_key;
196
+ return [planKey, {
197
+ plan: new Map((member.plan?.tasks ?? []).map((task) => [task.task_id, task])),
198
+ state: new Map((member.tasks ?? member.snapshot?.tasks ?? []).map((task) => [task.task_id, task])),
199
+ activity: new Map(journalActivity(member.journal?.events ?? []).tasks.map((entry) => [entry.task_id, entry])),
200
+ }];
201
+ }));
202
+ const rows = closedTrees.flatMap((tree) => tree.tasks.map(({ plan_key: planKey, task_id: taskId }) => {
203
+ const member = members.get(planKey);
204
+ const task = member?.plan.get(taskId);
205
+ const state = member?.state.get(taskId);
206
+ const activity = member?.activity.get(taskId);
207
+ return { tree_id: tree.tree_id, plan_key: planKey, task_id: taskId,
208
+ title: task?.title ?? null, lane: task?.lane ?? null, phase_id: task?.phase_id ?? null,
209
+ parent_task_id: task?.parent_task_id ?? null, design_memo: task?.design_memo ?? null,
210
+ done_condition: task?.done_condition ?? null, status: state?.status ?? null, done_at: state?.done_at ?? null,
211
+ finished_at: state?.status === 'done' && state.done_at ? state.done_at : activity?.changed_at ?? null,
212
+ activity: { changed_at: activity?.changed_at ?? null, started: activity?.started ?? null } };
213
+ })).sort(compareHistory);
214
+ const rest = before === null ? rows : rows.filter((row) => compareHistory(row, before) > 0);
215
+ const page = rest.slice(0, limit);
216
+ return { closed: { trees: closedTrees.length, tasks: rows.length }, tasks: page,
217
+ next_cursor: rest.length > page.length ? encodeHistoryCursor(page.at(-1)) : null };
218
+ }
219
+
79
220
  /**
80
221
  * 接続 (schedule): one plan chain's connection_added events with how each ended. `ended` is 'removed' or
81
222
  * 'resolved' (an add has at most one end, which Store append enforces); a state of 'removed' is not shown.