@quolu/lattice 0.117.0 → 0.118.1

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.
@@ -37,16 +37,21 @@ if (!Number.isSafeInteger(port) || port < 1 || port > 65_535) {
37
37
  fail('LATTICE_HUB_PORT_INVALID', 'LATTICE_HUB_PORT must be an integer in 1..65535');
38
38
  }
39
39
 
40
- const allowedHostsValue = env.LATTICE_HUB_ALLOWED_HOSTS ?? '';
41
- const allowedHosts = new Set(allowedHostsValue.split(',').map((host) => host.trim()).filter((host) => host.length > 0));
40
+ function hostSet(value = '') {
41
+ return new Set(value.split(',').map((host) => host.trim()).filter(Boolean));
42
+ }
43
+
44
+ const allowedHosts = hostSet(env.LATTICE_HUB_ALLOWED_HOSTS);
42
45
  if (allowedHosts.size === 0) {
43
46
  fail('LATTICE_HUB_ALLOWED_HOSTS_REQUIRED',
44
47
  'LATTICE_HUB_ALLOWED_HOSTS must list at least one allowed Host (comma-separated), e.g. lattice.kitepon.dev');
45
48
  }
46
49
 
50
+ const readOnlyHosts = hostSet(env.LATTICE_HUB_READ_ONLY_HOSTS);
51
+
47
52
  let hub;
48
53
  try {
49
- hub = await startBridgeHubServer({ port, allowedHosts, listenAddress, env });
54
+ hub = await startBridgeHubServer({ port, allowedHosts, readOnlyHosts, listenAddress, env });
50
55
  } catch (error) {
51
56
  fail(error?.code ?? 'BRIDGE_HUB_START_FAILED', error?.message ?? 'bridge hub server failed to start');
52
57
  }
@@ -210,6 +210,12 @@ hubへ繋いでいる端末では、`runtime.last_heartbeat`が最後にhubへ
210
210
  無いprojectは配信から外れる。heartbeatの90秒TTLは、配信そのものが止まった時
211
211
  (daemon停止)にofflineへ落とすためのもので、鮮度窓ではない。
212
212
 
213
+ The hub keeps the offline status for one further heartbeat interval (30 seconds).
214
+ Starting at 120 seconds since the last heartbeat, its startup or next 30-second
215
+ cleanup removes the route from `terminals.json`. A returning terminal advertises
216
+ its projects again through the normal heartbeat. See the
217
+ [hub registry data flow](https://github.com/kitepon/Lattice/blob/main/docs/architecture/dfd-bridge-persistence.md#public-hub-terminal-registry).
218
+
213
219
  ### 焼き込むnode pathの選び方(ADR 0163)
214
220
 
215
221
  常駐設定へ焼くnodeのpathは、版付きの実体(homebrewの`Cellar/node/<version>/bin/node`、nvm-windowsの
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quolu/lattice",
3
- "version": "0.117.0",
3
+ "version": "0.118.1",
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",
@@ -25,9 +25,8 @@
25
25
  * - A project_id already owned by a *different* terminal is a conflict unless
26
26
  * named in `adopt`. Conflicts are collected and reported together — a batch
27
27
  * never partially lands, so a caller is never left unsure which half won.
28
- * - Staleness is read-time only. `projectBridgeHubRegistry` marks an entry
29
- * 'offline' once `last_seen_at` exceeds the TTL; it never deletes the entry.
30
- * The plan's fail-closed requirement is "show offline", not "make it vanish".
28
+ * - `projectBridgeHubRegistry` marks a retained entry 'offline' once its
29
+ * `last_seen_at` exceeds the TTL. The hub server separately expires entries.
31
30
  */
32
31
 
33
32
  const IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
@@ -128,7 +127,7 @@ export function applyBridgeHubRegistration({ registry, request, remoteAddress, n
128
127
  //
129
128
  // owner offline (no heartbeat within the TTL) — the entry is very likely a
130
129
  // leftover from a terminal that moved on, so the live claimant takes it
131
- // over. Nothing else ever retracts it: entries are never expired.
130
+ // over. The hub server also sweeps expired entries from disk.
132
131
  // owner online — the project genuinely belongs to another live terminal.
133
132
  // Reject just that id and report it, so the operator can adopt on purpose.
134
133
  // Handing it over unconditionally would make two live terminals trade
@@ -190,10 +189,7 @@ export function applyBridgeHubRegistration({ registry, request, remoteAddress, n
190
189
 
191
190
  /**
192
191
  * Read-time projection for the aggregate `/projects/` view and per-project
193
- * routing. Never mutates or drops entries — a terminal that stopped
194
- * heartbeating shows as 'offline' forever, not gone, until it re-registers, a
195
- * different terminal explicitly adopts the project, or a different terminal
196
- * claims it while this one is past the TTL (see applyBridgeHubRegistration).
192
+ * routing. Marks retained routes offline without mutating the registry.
197
193
  */
198
194
  export function projectBridgeHubRegistry({ registry, now = new Date(), ttlMs = BRIDGE_HUB_HEARTBEAT_TTL_MS }) {
199
195
  if (!validRegistry(registry)) {
@@ -32,7 +32,7 @@ import path from 'node:path';
32
32
  import { domainToASCII } from 'node:url';
33
33
 
34
34
  import {
35
- applyBridgeHubRegistration, BRIDGE_HUB_HEARTBEAT_TTL_MS, BridgeHubProtocolError,
35
+ applyBridgeHubRegistration, BRIDGE_HUB_HEARTBEAT_INTERVAL_MS, BRIDGE_HUB_HEARTBEAT_TTL_MS, BridgeHubProtocolError,
36
36
  projectBridgeHubRegistry, validateBridgeHubRegistryEntry,
37
37
  } from './bridge-hub-protocol.mjs';
38
38
  import { escapeHtml, renderBridgeHubLanding } from './bridge-hub-landing.mjs';
@@ -198,11 +198,9 @@ function respondProjectStatus(incoming, response, status, code, projectId, reque
198
198
  response.end(html);
199
199
  }
200
200
 
201
- // --- A single async mutex guarding the registration critical section
202
- // (read -> apply -> write) against two concurrent registration requests
203
- // racing each other's read before either has written, which would lose one
204
- // terminal's update. File-level durability (atomic rename, 0600, a lock
205
- // file) is a separate concern owned by writeBridgeHubRegistry below. ---
201
+ // Registration and expiry share the read -> apply -> write critical section
202
+ // so a sweep cannot erase a heartbeat it has not seen. File durability is
203
+ // owned by writeBridgeHubRegistry below.
206
204
 
207
205
  function createMutex() {
208
206
  let queue = Promise.resolve();
@@ -426,7 +424,7 @@ export async function writeBridgeHubRegistry({ env = process.env, entries }) {
426
424
  // === HTTP server ===
427
425
 
428
426
  export async function startBridgeHubServer({
429
- registryStore, port = 0, allowedHosts, env = process.env, fetchImpl = fetch,
427
+ registryStore, port = 0, allowedHosts, readOnlyHosts = new Set(), env = process.env, fetchImpl = fetch,
430
428
  now = () => new Date(), ttlMs = BRIDGE_HUB_HEARTBEAT_TTL_MS, listenAddress = LOOPBACK,
431
429
  } = {}) {
432
430
  // fetchImpl is accepted for DI parity with the rest of this codebase's bridge
@@ -450,11 +448,24 @@ export async function startBridgeHubServer({
450
448
  throw new BridgeHubServerError('BRIDGE_HUB_CONFIG_INVALID', 'listenAddress must be an IP literal');
451
449
  }
452
450
  const normalizedAllowedHosts = new Set([...allowedHosts].map(normalizeHubAllowedHost));
451
+ const normalizedReadOnlyHosts = new Set([...readOnlyHosts].map(normalizeHubAllowedHost));
453
452
  const store = registryStore ?? {
454
453
  read: () => readBridgeHubRegistry({ env }),
455
454
  write: (entries) => writeBridgeHubRegistry({ env, entries }),
456
455
  };
457
- const registrationLock = createMutex();
456
+ const registryLock = createMutex();
457
+
458
+ function expireRegistrations() {
459
+ return registryLock(async () => {
460
+ const entries = await store.read();
461
+ const cutoff = now().getTime() - ttlMs - BRIDGE_HUB_HEARTBEAT_INTERVAL_MS;
462
+ const retained = entries.filter((entry) => !(Date.parse(entry.last_seen_at) <= cutoff));
463
+ if (retained.length < entries.length) await store.write(retained);
464
+ }).catch(() => {
465
+ process.emitWarning('hub could not remove expired terminal registrations',
466
+ { code: 'LATTICE_BRIDGE_HUB_EXPIRY_FAILED' });
467
+ });
468
+ }
458
469
 
459
470
  async function handleRegister(incoming, response) {
460
471
  if (incoming.method !== 'POST') {
@@ -480,7 +491,7 @@ export async function startBridgeHubServer({
480
491
  }
481
492
  let result;
482
493
  try {
483
- result = await registrationLock(async () => {
494
+ result = await registryLock(async () => {
484
495
  const entries = await store.read();
485
496
  const applied = applyBridgeHubRegistration({
486
497
  registry: entries, request, remoteAddress, now: now(), ttlMs,
@@ -616,13 +627,19 @@ export async function startBridgeHubServer({
616
627
  respondError(response, 421, 'BRIDGE_HOST_NOT_ALLOWED');
617
628
  return;
618
629
  }
630
+ const readOnly = normalizedReadOnlyHosts.has(host.hostname);
631
+ if (readOnly && incoming.method !== 'GET') {
632
+ response.setHeader('allow', 'GET');
633
+ respondError(response, 405, 'BRIDGE_HUB_METHOD_NOT_ALLOWED');
634
+ return;
635
+ }
619
636
  let requestUrl;
620
637
  try { requestUrl = validatedHubRequestTarget(incoming.url); } catch (error) {
621
638
  respondError(response, 400, error?.code ?? 'BRIDGE_HUB_REQUEST_TARGET_INVALID');
622
639
  return;
623
640
  }
624
641
  const rawPath = requestUrl.split('?', 1)[0];
625
- if (rawPath === '/__lattice/hub/register') { await handleRegister(incoming, response); return; }
642
+ if (!readOnly && rawPath === '/__lattice/hub/register') { await handleRegister(incoming, response); return; }
626
643
  // The landing (ADR 0164) serves the same page at `/` and `/projects/`
627
644
  // (the old `/` -> `/projects/` 301 is retired: both public inbound links
628
645
  // land on the product face), with the EN variant path-separated under
@@ -658,15 +675,29 @@ export async function startBridgeHubServer({
658
675
  const boundAddress = server.address();
659
676
  const actualPort = typeof boundAddress === 'object' && boundAddress !== null ? boundAddress.port : port;
660
677
  let closed = false;
678
+ let expiryTimer;
679
+ let expiry;
680
+ function scheduleExpiry() {
681
+ expiryTimer = setTimeout(() => {
682
+ expiry = expireRegistrations().then(() => {
683
+ if (!closed) scheduleExpiry();
684
+ });
685
+ }, BRIDGE_HUB_HEARTBEAT_INTERVAL_MS);
686
+ expiryTimer.unref();
687
+ }
688
+ await expireRegistrations();
689
+ scheduleExpiry();
661
690
  return Object.freeze({
662
691
  host: listenAddress,
663
692
  port: actualPort,
664
693
  close: async () => {
665
694
  if (closed) return;
666
695
  closed = true;
696
+ clearTimeout(expiryTimer);
667
697
  const completion = new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
668
698
  server.closeAllConnections?.();
669
699
  await completion;
700
+ await expiry;
670
701
  },
671
702
  });
672
703
  }
@@ -11,6 +11,7 @@ import {
11
11
  readTodoStore, TodoStoreError,
12
12
  } from './todo-store.mjs';
13
13
  import { gitSync } from './git-process.mjs';
14
+ import { findingHandoff, planEditAdvice } from './plan-edit-advice.mjs';
14
15
  import { completeCreateInput, readAuthoringJsonFile } from './todo-authoring-input.mjs';
15
16
  import {
16
17
  explainPhaseTodoRevision, phaseTodoRevisionPlanVersion, validatePhaseTodoRevision,
@@ -635,7 +636,8 @@ export async function rebindCarriedWork({ repoRoot, planKey, env,
635
636
  return rebound;
636
637
  }
637
638
 
638
- const draftOutput = (report) => (report === null ? {} : { draft: report.summary, draft_findings: report.findings });
639
+ const draftOutput = async (report, repoRoot) => (report === null ? {} : { draft: report.summary, draft_findings: report.findings,
640
+ finding_handoff: await findingHandoff({ repoRoot, planKey: report.summary.plan_key, findings: report.findings }) });
639
641
 
640
642
  export async function runPlanBackchain({ cwd, inputRef = null, draftRef = null, stdout, dryRun = false, env = process.env }) {
641
643
  const repoRoot = gitRoot(cwd);
@@ -698,6 +700,9 @@ export async function runPlanBackchain({ cwd, inputRef = null, draftRef = null,
698
700
  try { buildTodoPlan({ ...planSeed(amended, null), plan_version: chain.plan_version }); }
699
701
  catch { fail('authoring_plan_invalid', '/authoring_ref'); }
700
702
  }
703
+ // A finished chain revised through --input gets the same cut-off advisory; a draft already carries draft_findings + handoff.
704
+ const editAdvice = draftReport === null && revision !== null
705
+ ? Object.fromEntries([['advice', await planEditAdvice({ repoRoot, before: member.plan, after: revision.desired_plan, states: member.tasks })]].filter(([, v]) => v !== null)) : {};
701
706
  const unknownFeatureIds = chain.features.filter(({ provider: source }) => source.kind === 'unknown')
702
707
  .map(({ feature_id: id }) => id).sort();
703
708
  if (dryRun) {
@@ -711,7 +716,8 @@ export async function runPlanBackchain({ cwd, inputRef = null, draftRef = null,
711
716
  : store === null ? 'create' : 'add',
712
717
  task_migration: revision?.task_migration ?? null,
713
718
  feature_chain_findings: featureChainFindings,
714
- ...draftOutput(draftReport),
719
+ ...await draftOutput(draftReport, repoRoot),
720
+ ...editAdvice,
715
721
  result_digest: '',
716
722
  };
717
723
  checked.result_digest = todoSelfDigest(checked, 'result_digest');
@@ -769,7 +775,8 @@ export async function runPlanBackchain({ cwd, inputRef = null, draftRef = null,
769
775
  chain_digest: effectiveChain.chain_digest, authoring_result: created,
770
776
  rebound_task_ids: reboundTaskIds,
771
777
  feature_chain_findings: featureChainFindings,
772
- ...draftOutput(draftReport),
778
+ ...await draftOutput(draftReport, repoRoot),
779
+ ...editAdvice,
773
780
  operation: unchanged ? 'unchanged' : revision !== null ? 'revise'
774
781
  : store === null ? 'create' : 'add',
775
782
  journal_head_digest: finalMember.journal.events.at(-1).event_digest,
@@ -343,7 +343,7 @@ export async function compilePlanDraft({ repoRoot, draft, draftRef, member, stor
343
343
  const pairs = (keys) => keys.map((key) => { const [from, to] = key.split('->'); return { from: from.split('/')[1], to: to.split('/')[1] }; });
344
344
  return { chain, authoring, report: {
345
345
  summary: {
346
- mode: plan === null ? (store === null ? 'create' : 'add') : 'revise',
346
+ mode: plan === null ? (store === null ? 'create' : 'add') : 'revise', plan_key: planKey,
347
347
  added_task_ids: [...tasks.keys()].filter((id) => !baseIds.has(id)),
348
348
  retired_task_ids: [...retired].sort(),
349
349
  edge_changes: {
@@ -392,10 +392,14 @@ async function draftFindings({ repoRoot, draft, chain, member, baseIds, scope, e
392
392
  const byCapability = new Map();
393
393
  for (const feature of chain.features.filter(inScope)) {
394
394
  const key = `${feature.capability.trim()}\u0000${feature.acceptance.trim()}`; // same capability with another acceptance/scope is a different result
395
- byCapability.set(key, [...(byCapability.get(key) ?? []), feature.feature_id]);
395
+ byCapability.set(key, [...(byCapability.get(key) ?? []), feature]);
396
396
  }
397
- for (const [capability, ids] of byCapability) {
398
- if (ids.length > 1) found.push({ reason: 'duplicate_result', pointer: '/features', capability: capability.split('\u0000')[0], feature_ids: ids.sort() });
397
+ for (const [capability, group] of byCapability) {
398
+ if (group.length > 1) {
399
+ found.push({ reason: 'duplicate_result', pointer: '/features', capability: capability.split('\u0000')[0],
400
+ feature_ids: group.map((f) => f.feature_id).sort(),
401
+ task_ids: group.filter((f) => f.provider.kind === 'task').map((f) => f.provider.task_id).sort() });
402
+ }
399
403
  }
400
404
  const canonicalRoot = await realpath(repoRoot);
401
405
  for (const [index, entry] of (draft.observations ?? []).entries()) {
@@ -0,0 +1,144 @@
1
+ import { readTodoChartMeta } from './todo-store.mjs';
2
+
3
+ // Advisory only (never a gate, never a message sent): what an edit cut off from its goals, and who to tell.
4
+ // Contract: docs/architecture/dfd-finding-handoff.md.
5
+ export const ADVICE_SCHEMA = 'lattice.plan_edit_advice.v1';
6
+ export const HANDOFF_SCHEMA = 'lattice.finding_handoff.v1';
7
+ // Missing or unreadable evidence alone is never a retirement candidate, so it is not handed off.
8
+ const HANDOFF_REASONS = new Set(['unused_output', 'duplicate_result', 'planned_provider_has_observation', 'completed_result_matches_planned']);
9
+
10
+ /** Prerequisite lists inside one plan: hard edges, joins (before waits for each after) and phase accepts. */
11
+ function prerequisites(plan) {
12
+ const into = new Map(plan.tasks.map(({ task_id: id }) => [id, new Set()]));
13
+ const wait = (to, from) => { if (into.has(to) && into.has(from)) into.get(to).add(from); };
14
+ const mine = (ref) => ref?.plan_key === plan.plan_key;
15
+ for (const { from, to } of plan.hard_dependencies ?? []) if (mine(from) && mine(to)) wait(to.task_id, from.task_id);
16
+ for (const { before, after } of plan.joins ?? []) {
17
+ if (mine(before)) for (const ref of after) if (mine(ref)) wait(before.task_id, ref.task_id);
18
+ }
19
+ for (const { from, to } of plan.phase_accept_dependencies ?? []) if (mine(from) && mine(to)) wait(to.task_id, from.task_id);
20
+ return into;
21
+ }
22
+
23
+ function served(into, goals) {
24
+ const seen = new Set();
25
+ const stack = goals.filter((id) => into.has(id));
26
+ while (stack.length > 0) {
27
+ const id = stack.pop();
28
+ if (seen.has(id)) continue;
29
+ seen.add(id);
30
+ stack.push(...into.get(id));
31
+ }
32
+ return seen;
33
+ }
34
+
35
+ /**
36
+ * Tasks of `before` that served one of its goals (a goal = a task nothing waits for) and no longer serve a goal in `after`.
37
+ * Only the span the edit cut off is returned; new tasks and unrelated purposes are not judged.
38
+ */
39
+ export function cutOffByEdit(before, after) {
40
+ const was = prerequisites(before);
41
+ const waited = new Set([...was.values()].flatMap((set) => [...set]));
42
+ const goals = [...was.keys()].filter((id) => !waited.has(id));
43
+ const now = served(prerequisites(after), goals);
44
+ const earlier = served(was, goals);
45
+ return after.tasks.map(({ task_id: id }) => id).filter((id) => earlier.has(id) && !now.has(id));
46
+ }
47
+
48
+ /** The advisory returned with an ordinary plan edit; null when nothing was cut off. */
49
+ export async function planEditAdvice({ repoRoot, before, after, states = [] }) {
50
+ const state = new Map(states.map((task) => [task.task_id, task.status]));
51
+ const findings = cutOffByEdit(before, after).filter((id) => state.get(id) !== 'retired').map((id) => ({
52
+ reason: 'unused_output', pointer: `/tasks/${id}`, task_id: id, task_state: state.get(id) ?? null,
53
+ candidate: 'retirement', cause: 'cut_off_by_edit' }));
54
+ if (findings.length === 0) return null;
55
+ return { schema: ADVICE_SCHEMA, advisory: true, plan_key: after.plan_key, findings,
56
+ handoff: await findingHandoff({ repoRoot, planKey: after.plan_key, findings }) };
57
+ }
58
+
59
+ const WHY = {
60
+ unused_output: (f) => f.cause === 'cut_off_by_edit'
61
+ ? 'this edit left nothing waiting for its result, so no goal of the plan needs it any more'
62
+ : 'no goal result of the plan reaches its result',
63
+ planned_provider_has_observation: (f) => `its result was matched to the observation ${f.evidence_ref}`,
64
+ completed_result_matches_planned: (f) => `${f.completed_task} already completed a result with the identical capability and acceptance and recorded completion evidence (an evidence file or message alone does not prove equivalence)`,
65
+ };
66
+ const PROPOSE = (planKey) => ({
67
+ unused_output: (f) => `if it has no other purpose, retire it (lattice todo retire --plan ${planKey} --task ${f.task_id} --reason <text>); otherwise link a task that needs its result`,
68
+ duplicate_result: () => 'keep one provider of the result and retire or re-link the other',
69
+ completed_result_matches_planned: (f) => `compare the completion evidence of ${f.completed_task} with this task's scope (version, environment, behavior); if it already covers the result, retire this task`,
70
+ planned_provider_has_observation: () => 'compare that observation with the planned result (version, environment, behavior); if it already covers the result, retire the planned task',
71
+ });
72
+
73
+ /**
74
+ * Who to tell and what to say. Recipient = the chart representative = K4 `readTodoChartMeta({repoRoot}).created_by`
75
+ * (K1 `charts list --json` `charts[].created_by`); unreadable or unrecorded stays an advisory with a manual lookup.
76
+ * Returns null when no finding is a candidate. Nothing is sent and nothing waits for an answer.
77
+ */
78
+ export async function findingHandoff({ repoRoot, planKey, findings }) {
79
+ const eligible = findings.filter(({ reason }) => HANDOFF_REASONS.has(reason));
80
+ const items = eligible.flatMap((finding) => {
81
+ if (finding.reason === 'duplicate_result') {
82
+ // One item per provider task; results provided by an observation or an open question have no task to change.
83
+ const others = (tid) => finding.task_ids.filter((id) => id !== tid);
84
+ return (finding.task_ids ?? []).map((tid) => ({ task_id: tid, finding: finding.reason,
85
+ why: `${tid} provides the result "${finding.capability}" (${finding.feature_ids.join(', ')}), declared with the identical capability and acceptance${others(tid).length > 0 ? ` as ${others(tid).join(', ')}` : ' by another result'}`,
86
+ proposed_change: PROPOSE(planKey).duplicate_result() }));
87
+ }
88
+ return [{ task_id: finding.task_id ?? null, finding: finding.reason,
89
+ why: WHY[finding.reason](finding), proposed_change: PROPOSE(planKey)[finding.reason](finding),
90
+ ...(finding.task_state === undefined ? {} : { task_state: finding.task_state }) }];
91
+ });
92
+ if (items.length === 0) return null;
93
+ const meta = await readTodoChartMeta({ repoRoot }).catch(() => null);
94
+ const createdBy = typeof meta?.created_by === 'string' && meta.created_by !== '' ? meta.created_by : null;
95
+ return {
96
+ schema: HANDOFF_SCHEMA, request: 'advisory', delivery: 'none',
97
+ recipient: {
98
+ role: 'chart_representative', created_by: createdBy,
99
+ source: 'readTodoChartMeta({repoRoot}).created_by; lattice charts list --json charts[].created_by',
100
+ lookup: createdBy === null
101
+ ? 'created_by is not recorded here: read charts[].created_by of this chart in `lattice charts list --json`, or ask who created the chart' : null,
102
+ },
103
+ items,
104
+ ask: `Advisory, not a gate: tell ${createdBy ?? 'the chart representative'} the affected task, why it was flagged and the proposed change: `
105
+ + items.map((item) => `${item.task_id ?? '(result)'}: ${item.why}; ${item.proposed_change}`).join(' | '),
106
+ };
107
+ }
108
+
109
+ /**
110
+ * `todo done`: the tasks the completion makes unnecessary, from the completed task and the evidence recorded with it.
111
+ * With recorded evidence and a feature chain, a live task that
112
+ * provides a feature with the identical capability and acceptance as one the completed task provides. Scope differences keep
113
+ * results distinct; missing evidence never creates a candidate. Null when nothing is affected. The completion itself is untouched.
114
+ * `plan` and `states` are the committed completion version (what the Store returned from the write), so no chart read is added
115
+ * and a concurrent edit cannot make the advisory describe another version.
116
+ */
117
+ export async function completionAdvice({ repoRoot, plan, states, taskId, planVersion, evidence }) {
118
+ const state = new Map(states.map((task) => [task.task_id, task.status]));
119
+ const live = (id) => id !== taskId && !['done', 'retired'].includes(state.get(id));
120
+ const findings = [];
121
+ const binding = evidence === null ? null
122
+ : await (await import('./plan-backchain.mjs')).readPlanBackchainBinding({ repoRoot, plan }).catch(() => null);
123
+ if (binding !== null) {
124
+ const features = new Map(binding.chain.features.map((f) => [f.feature_id, f]));
125
+ const doneTask = binding.chain.tasks.find((t) => t.task_id === taskId);
126
+ for (const id of doneTask?.provides_feature_ids ?? []) {
127
+ const done = features.get(id);
128
+ for (const other of binding.chain.tasks) {
129
+ if (!live(other.task_id)) continue;
130
+ for (const fid of other.provides_feature_ids) {
131
+ const twin = features.get(fid);
132
+ if (twin?.capability.trim() === done.capability.trim() && twin.acceptance.trim() === done.acceptance.trim()) {
133
+ findings.push({ reason: 'completed_result_matches_planned', pointer: `/tasks/${other.task_id}`, task_id: other.task_id,
134
+ task_state: state.get(other.task_id) ?? null, candidate: 'retirement', completed_task: taskId,
135
+ feature_id: fid, completed_feature_id: id, evidence });
136
+ }
137
+ }
138
+ }
139
+ }
140
+ }
141
+ if (findings.length === 0) return null;
142
+ return { schema: ADVICE_SCHEMA, advisory: true, trigger: 'done', plan_key: plan.plan_key, plan_version: planVersion, completed_task: taskId, findings,
143
+ handoff: await findingHandoff({ repoRoot, planKey: plan.plan_key, findings }) };
144
+ }
@@ -1,4 +1,5 @@
1
1
  import { readFile } from 'node:fs/promises';
2
+ import { planEditAdvice } from './plan-edit-advice.mjs';
2
3
  import path from 'node:path';
3
4
 
4
5
  import { canonicalizeTodoArtifact, exactRecord, isTodoIdentifier, todoSelfDigest } from './todo-contracts.mjs';
@@ -413,6 +414,8 @@ export async function applyPlanRevision({
413
414
  }
414
415
  const declarations = dryRun || touches.length === 0 ? null
415
416
  : await (await import('./todo-cli.mjs')).declareTouches({ repoRoot, planKey: revision.plan_key, touches });
417
+ const advice = unchanged ? null : await planEditAdvice({ repoRoot, before: member.plan,
418
+ after: revision.desired_plan, states: member.tasks });
416
419
  const result = {
417
420
  schema: unchanged ? 'lattice.plan_revise_unchanged.v1' : 'lattice.plan_revise_result.v1',
418
421
  project_id: revision.project_id, plan_key: revision.plan_key,
@@ -420,6 +423,7 @@ export async function applyPlanRevision({
420
423
  dry_run: dryRun, revision: unchanged ? null : revision, applied,
421
424
  continuity, rebound_task_ids: reboundTaskIds,
422
425
  ...(featureChainFindings === null ? {} : { feature_chain_findings: featureChainFindings }),
426
+ ...(advice === null ? {} : { advice }),
423
427
  ...(declarations === null ? {} : { declarations }),
424
428
  result_digest: '',
425
429
  };
package/src/todo-cli.mjs CHANGED
@@ -922,6 +922,17 @@ async function mutate({
922
922
  // 導出ビュー`phases`から読む。
923
923
  const resolvedAdvisory = advisory ?? (kind === 'done' ? terminalAuditDoneAdvisory(plan, phases)
924
924
  : kind === 'reopen' ? reopenAdvisory(plan, phases, event.task_id) : null);
925
+ // The completion advisory reads what this write committed (plan version + task states returned by the Store), so it adds
926
+ // no chart read and cannot describe another version. Evidence-free completion skips it; it never changes the completion.
927
+ const recordedMessage = kind === 'done' && payload === 'authored' && message !== DONE_WITHOUT_MESSAGE ? message : null;
928
+ const completionAdvice = recordedMessage === null && testResult === null ? null
929
+ : kind !== 'done' || payload !== 'authored' ? null
930
+ : await (await import('./plan-edit-advice.mjs')).completionAdvice({
931
+ repoRoot, plan, states: snapshot.tasks, taskId: event.task_id, planVersion: event.plan_version,
932
+ evidence: { event_digest: event.event_digest,
933
+ message: recordedMessage === null ? null : recordedMessage.slice(0, 400),
934
+ test_result: testResult === null ? null : String(testResult).slice(0, 400) },
935
+ }).catch(() => null);
925
936
  const includesNoteContext = kind === 'start';
926
937
  if (includesNoteContext && noteContext === null) {
927
938
  throw new TypeError('start mutation requires note context');
@@ -941,6 +952,7 @@ async function mutate({
941
952
  snapshot_digest: snapshot.snapshot_digest,
942
953
  status: task.status,
943
954
  advisory: resolvedAdvisory,
955
+ ...(completionAdvice === null ? {} : { advice: completionAdvice }),
944
956
  ...(includesNoteContext ? {
945
957
  design_memo: designMemoProjection(authoredTask),
946
958
  done_condition: authoredTask.done_condition ?? null,
@@ -1783,7 +1795,8 @@ async function dependencyRevision({
1783
1795
  schema: 'lattice.todo_dependency_revision_result.v1', project_id: store.project_id,
1784
1796
  plan_key: planKey, operation, from, to, reason, actor: desired.actor,
1785
1797
  plan_version: applied.plan_version, revision_digest: applied.revision.revision_digest,
1786
- rebound_task_ids: applied.rebound_task_ids, result_digest: '',
1798
+ rebound_task_ids: applied.rebound_task_ids, ...(applied.advice === undefined ? {} : { advice: applied.advice }),
1799
+ result_digest: '',
1787
1800
  };
1788
1801
  result.result_digest = todoSelfDigest(result, 'result_digest');
1789
1802
  return result;
@@ -1848,7 +1861,8 @@ async function addTask({ repoRoot, env, planKey, flags }) {
1848
1861
  schema: 'lattice.todo_task_add_result.v2', project_id: store.project_id, plan_key: planKey,
1849
1862
  task_id: taskId, after, before, reason, actor: desired.actor, declaration,
1850
1863
  plan_version: applied.plan_version, revision_digest: applied.revision?.revision_digest ?? null,
1851
- rebound_task_ids: applied.rebound_task_ids, result_digest: '',
1864
+ rebound_task_ids: applied.rebound_task_ids, ...(applied.advice === undefined ? {} : { advice: applied.advice }),
1865
+ result_digest: '',
1852
1866
  };
1853
1867
  result.result_digest = todoSelfDigest(result, 'result_digest');
1854
1868
  return result;
@@ -2725,10 +2739,22 @@ async function revise({ repoRoot, env, planKey, inputRef }) {
2725
2739
  if (revision.plan_key !== planKey) {
2726
2740
  throw new TodoStoreError('REVISION_INVALID', 'requested_plan_mismatch');
2727
2741
  }
2728
- return applyTodoRevision({
2742
+ const member = (await readTodoStore({ repoRoot }).catch(() => null))?.members.find(({ plan }) => plan.plan_key === planKey);
2743
+ return withEditAdvice({ repoRoot, member, desired: revision.desired_plan, receipt: await applyTodoRevision({
2729
2744
  repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }), revision,
2730
2745
  actor: resolveTodoActor(env), recordedAt: new Date().toISOString(),
2731
- });
2746
+ }) });
2747
+ }
2748
+
2749
+ /** The advisory of an ordinary plan edit (docs/architecture/dfd-finding-handoff.md) rides on the receipt; it never changes the write. */
2750
+ async function withEditAdvice({ repoRoot, member, desired, receipt }) {
2751
+ if (member === undefined || desired === undefined) return receipt;
2752
+ const { planEditAdvice } = await import('./plan-edit-advice.mjs');
2753
+ const advice = await planEditAdvice({ repoRoot, before: member.plan, after: desired, states: member.tasks }).catch(() => null);
2754
+ if (advice === null) return receipt;
2755
+ const next = { ...receipt, advice };
2756
+ if (typeof receipt.result_digest === 'string') next.result_digest = todoSelfDigest({ ...next, result_digest: '' }, 'result_digest');
2757
+ return next;
2732
2758
  }
2733
2759
 
2734
2760
  async function reviseSet({ repoRoot, env, inputRef }) {
@@ -2760,8 +2786,10 @@ async function revisePhase({ repoRoot, env, planKey, inputRef }) {
2760
2786
  },
2761
2787
  });
2762
2788
  if (revision.plan_key !== planKey) throw new TodoStoreError('REVISION_INVALID', 'requested_plan_mismatch');
2763
- return applyPhaseTodoRevision({ repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }),
2764
- revision, actor: resolveTodoActor(env), recordedAt: new Date().toISOString() });
2789
+ const member = (await readTodoStore({ repoRoot }).catch(() => null))?.members.find(({ plan }) => plan.plan_key === planKey);
2790
+ return withEditAdvice({ repoRoot, member, desired: revision.desired_plan, receipt: await applyPhaseTodoRevision({
2791
+ repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }),
2792
+ revision, actor: resolveTodoActor(env), recordedAt: new Date().toISOString() }) });
2765
2793
  }
2766
2794
 
2767
2795
  async function splitTodo({ repoRoot, env, planKey, inputRef }) {