@quolu/lattice 0.82.0 → 0.84.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.
Files changed (77) hide show
  1. package/README.ja.md +7 -6
  2. package/README.md +1 -1
  3. package/bin/lattice-bridge-supervisor.mjs +10 -0
  4. package/bin/lattice-dashboard.mjs +3 -18
  5. package/bin/lattice-mcp.mjs +6 -3
  6. package/bin/lattice.mjs +30 -23
  7. package/docs/schemas/lattice.plan_create_input.v4.schema.json +5 -11
  8. package/docs/schemas/lattice.plan_create_input.v5.schema.json +362 -0
  9. package/docs/schemas/lattice.plan_revise_input.v1.schema.json +38 -11
  10. package/package.json +2 -1
  11. package/sensor/dist/db/index.d.ts +1 -0
  12. package/sensor/dist/db/index.d.ts.map +1 -1
  13. package/sensor/dist/db/index.js +13 -0
  14. package/sensor/dist/db/index.js.map +1 -1
  15. package/sensor/dist/index.d.ts.map +1 -1
  16. package/sensor/dist/index.js +12 -2
  17. package/sensor/dist/index.js.map +1 -1
  18. package/sensor/dist/mcp/answer-freshness.js +1 -1
  19. package/sensor/dist/mcp/answer-freshness.js.map +1 -1
  20. package/sensor/dist/mcp/daemon-paths.d.ts +6 -0
  21. package/sensor/dist/mcp/daemon-paths.d.ts.map +1 -1
  22. package/sensor/dist/mcp/daemon-paths.js +7 -1
  23. package/sensor/dist/mcp/daemon-paths.js.map +1 -1
  24. package/sensor/dist/mcp/engine.d.ts +11 -0
  25. package/sensor/dist/mcp/engine.d.ts.map +1 -1
  26. package/sensor/dist/mcp/engine.js +83 -4
  27. package/sensor/dist/mcp/engine.js.map +1 -1
  28. package/sensor/dist/mcp/index-repair.d.ts +7 -0
  29. package/sensor/dist/mcp/index-repair.d.ts.map +1 -0
  30. package/sensor/dist/mcp/index-repair.js +93 -0
  31. package/sensor/dist/mcp/index-repair.js.map +1 -0
  32. package/sensor/dist/mcp/index.d.ts.map +1 -1
  33. package/sensor/dist/mcp/index.js +12 -7
  34. package/sensor/dist/mcp/index.js.map +1 -1
  35. package/sensor/dist/mcp/tools.d.ts +4 -0
  36. package/sensor/dist/mcp/tools.d.ts.map +1 -1
  37. package/sensor/dist/mcp/tools.js +29 -9
  38. package/sensor/dist/mcp/tools.js.map +1 -1
  39. package/src/bridge-hub-server.mjs +46 -9
  40. package/src/cli-help.mjs +10 -8
  41. package/src/cli-refusal-guidance.mjs +354 -0
  42. package/src/dashboard-delivery.mjs +2 -1
  43. package/src/dashboard-lifecycle-journal.mjs +42 -20
  44. package/src/hooks-cli.mjs +30 -6
  45. package/src/plan-backchain.mjs +95 -41
  46. package/src/plan-revise.mjs +274 -72
  47. package/src/project-cli.mjs +301 -163
  48. package/src/project-identity.mjs +14 -0
  49. package/src/runtime-cli.mjs +38 -29
  50. package/src/runtime-control-store.mjs +22 -1
  51. package/src/runtime-decision-verifier.mjs +27 -8
  52. package/src/runtime-engine.mjs +34 -5
  53. package/src/runtime-hold-recompile.mjs +19 -15
  54. package/src/runtime-kept-worktree.mjs +136 -0
  55. package/src/runtime-lifecycle-lock.mjs +118 -30
  56. package/src/runtime-managed-supervisor.mjs +10 -10
  57. package/src/runtime-pull-intake.mjs +90 -44
  58. package/src/store-lock.mjs +142 -57
  59. package/src/todo-authoring-input.mjs +211 -2
  60. package/src/todo-cli.mjs +554 -200
  61. package/src/todo-contracts.mjs +22 -6
  62. package/src/todo-dashboard-registry.mjs +35 -6
  63. package/src/todo-gantt-display.mjs +259 -0
  64. package/src/todo-gantt-html-independence.mjs +10 -3
  65. package/src/todo-gantt-html-shared.mjs +16 -1
  66. package/src/todo-gantt-html.mjs +74 -53
  67. package/src/todo-gantt-layout.mjs +137 -59
  68. package/src/todo-gantt-live.mjs +6 -3
  69. package/src/todo-independence-guidance.mjs +4 -26
  70. package/src/todo-note-store.mjs +6 -3
  71. package/src/todo-readiness.mjs +83 -20
  72. package/src/todo-revision.mjs +156 -8
  73. package/src/todo-split.mjs +6 -3
  74. package/src/todo-status.mjs +141 -54
  75. package/src/todo-store-cache.mjs +1 -1
  76. package/src/todo-store-view.mjs +20 -2
  77. package/src/todo-store.mjs +562 -444
@@ -376,6 +376,14 @@ function taskV6(value) {
376
376
  && isTodoIdentifier(value.phase_id);
377
377
  }
378
378
 
379
+ function taskV8(value) {
380
+ const { done_condition: doneCondition, ...rest } = value ?? {};
381
+ return exactRecord(value, [
382
+ 'task_id', 'title', 'lane', 'design_memo', 'narrative_ref', 'narrative_anchor',
383
+ 'compile_binding', 'parent_task_id', 'phase_id', 'done_condition',
384
+ ]) && taskV6(rest) && (doneCondition === null || isTodoDesignMemo(doneCondition));
385
+ }
386
+
379
387
  function phaseV1(value) {
380
388
  return exactRecord(value, [
381
389
  'phase_id', 'title', 'gate_policy', 'predecessor_phase_ids', 'required_evidence_slots',
@@ -445,14 +453,16 @@ export function explainTodoPlan(value) {
445
453
  : value?.schema === 'lattice.todo_plan.v3' ? taskV3
446
454
  : ['lattice.todo_plan.v4', 'lattice.todo_plan.v5'].includes(value?.schema) ? taskV4
447
455
  : value?.schema === 'lattice.todo_plan.v6' ? taskV5
448
- : value?.schema === 'lattice.todo_plan.v7' ? taskV6 : null;
456
+ : value?.schema === 'lattice.todo_plan.v7' ? taskV6
457
+ : value?.schema === 'lattice.todo_plan.v8' ? taskV8 : null;
449
458
  const planKeys = [
450
459
  'schema', 'project_id', 'plan_key', 'plan_version', 'predecessor_plan_digest',
451
460
  'tasks', 'hard_dependencies', 'joins', 'topology_digest', 'plan_digest',
452
461
  ];
453
- const phased = ['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7']
462
+ const phased = ['lattice.todo_plan.v4', 'lattice.todo_plan.v5', 'lattice.todo_plan.v7',
463
+ 'lattice.todo_plan.v8'].includes(value?.schema);
464
+ const decoupled = ['lattice.todo_plan.v5', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8']
454
465
  .includes(value?.schema);
455
- const decoupled = ['lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(value?.schema);
456
466
  if (phased) planKeys.push('phases');
457
467
  if (decoupled) planKeys.push('phase_accept_dependencies');
458
468
  if (!exactRecord(value, planKeys)) return reject('unexpected_or_missing_keys', '/');
@@ -485,7 +495,7 @@ export function explainTodoPlan(value) {
485
495
  if (!isTodoDigest(value[field])) return reject('digest_invalid', `/${field}`);
486
496
  }
487
497
  if (['lattice.todo_plan.v3', 'lattice.todo_plan.v4', 'lattice.todo_plan.v5',
488
- 'lattice.todo_plan.v6', 'lattice.todo_plan.v7'].includes(value.schema)
498
+ 'lattice.todo_plan.v6', 'lattice.todo_plan.v7', 'lattice.todo_plan.v8'].includes(value.schema)
489
499
  && !validParentGraph(value.tasks)) return reject('parent_graph_invalid', '/tasks');
490
500
  if (phased) {
491
501
  if (!Array.isArray(value.phases) || value.phases.length === 0
@@ -591,7 +601,12 @@ function validPayload(event) {
591
601
  if (event.kind === 'unblock') return exactRecord(payload, []);
592
602
  // retire: 消費計画が消えた工程の恒久除去(ADR 0147系の状態遷移に足す軽量kind・2026-08-29オーナー裁定)。
593
603
  // 理由必須。blocked_reasonのfieldを理由の置き場として再利用し、state recordの形を変えない。
594
- if (event.kind === 'retire') return exactRecord(payload, ['reason']) && nullableText(payload.reason) && payload.reason !== null;
604
+ if (event.kind === 'retire') {
605
+ return (exactRecord(payload, ['reason'])
606
+ || (exactRecord(payload, ['reason', 'prior_status'])
607
+ && ['pending', 'blocked', 'in-progress', 'done'].includes(payload.prior_status)))
608
+ && nullableText(payload.reason) && payload.reason !== null;
609
+ }
595
610
  if (event.kind === 'done' && payload?.done_mode === 'authored') {
596
611
  return (exactRecord(payload, ['done_mode', 'imported', 'evidence'])
597
612
  || exactRecord(payload, ['done_mode', 'imported', 'evidence', 'test_result']))
@@ -662,7 +677,8 @@ function validCarriedState(value) {
662
677
  if (value.status === 'blocked') return value.done_at === null && value.blocked_reason !== null
663
678
  && activeEvidenceValid && testResult === null;
664
679
  // retired: 実行されないまま恒久に閉じた工程。理由はblocked_reasonが持ち、証拠・試験結果は持たない。
665
- if (value.status === 'retired') return value.done_at === null && value.blocked_reason !== null
680
+ // done_at is kept only when retired from done (u12).
681
+ if (value.status === 'retired') return value.blocked_reason !== null
666
682
  && value.evidence === null && testResult === null;
667
683
  return value.blocked_reason === null && value.evidence !== null
668
684
  // importedは完了状態の来歴を表す。evidence_promotion後もtrueを維持するため、
@@ -1,5 +1,4 @@
1
1
  import { randomBytes } from 'node:crypto';
2
- import { homedir } from 'node:os';
3
2
  import {
4
3
  mkdir, open, readdir, readFile, realpath, rename, rm, stat, writeFile,
5
4
  } from 'node:fs/promises';
@@ -9,6 +8,7 @@ import packageJson from '../package.json' with { type: 'json' };
9
8
  import { isAuditPendingPhaseStatus } from './todo-audit-pending.mjs';
10
9
  import { observeStartIdentityEpochMs } from './runtime-os-observation.mjs';
11
10
  import { spawnSupervisedDashboard } from './dashboard-supervisor.mjs';
11
+ import { resolveSeatIdentity } from './seat-identity.mjs';
12
12
  import { reconcileLifecycleRuns, readDashboardLifecycleStatus,
13
13
  recordDashboardEnsureDecision } from './dashboard-lifecycle-journal.mjs';
14
14
  import { observeDashboardProcess } from './dashboard-process-control.mjs';
@@ -37,7 +37,9 @@ function identifier(value) {
37
37
  function runtimeDir(env) {
38
38
  const configured = env.LATTICE_DASHBOARD_RUNTIME_DIR;
39
39
  return typeof configured === 'string' && path.isAbsolute(configured)
40
- ? configured : path.join(homedir(), '.lattice', 'dashboard');
40
+ ? configured
41
+ // Same seat root as bridge-server.mjs, so CLI and bridge find one daemon per seat (seat-contract.md).
42
+ : path.join(resolveSeatIdentity(env).state_dir, 'dashboard');
41
43
  }
42
44
 
43
45
  function paths(env) {
@@ -87,6 +89,33 @@ function validateRegistry(value) {
87
89
  return value;
88
90
  }
89
91
 
92
+ const QUARANTINE_KEEP = 3;
93
+
94
+ /**
95
+ * u03 D22: the registry is rebuilt by every `todo start/done` and `dashboard ensure`, so an
96
+ * invalid one (not JSON, wrong schema, duplicate project) is moved aside as
97
+ * `projects.json.invalid-<UTC>` (newest 3 kept) and read as empty instead of stopping the
98
+ * dashboard. A failed move leaves the file; the next read retries.
99
+ */
100
+ async function readRegistry(ref) {
101
+ try {
102
+ return validateRegistry(await readJson(ref, { schema: REGISTRY_SCHEMA, projects: [] }));
103
+ } catch (error) {
104
+ if (error?.code !== 'DASHBOARD_REGISTRY_INVALID') throw error;
105
+ }
106
+ // The random tail keeps two moves in the same millisecond from overwriting each other.
107
+ const stamp = `${new Date().toISOString().replace(/[:.]/gu, '-')}-${randomBytes(4).toString('hex')}`;
108
+ try {
109
+ await rename(ref, `${ref}.invalid-${stamp}`);
110
+ process.emitWarning(`dashboard registry was invalid and moved aside: ${ref}.invalid-${stamp}`,
111
+ { code: 'LATTICE_DASHBOARD_REGISTRY_QUARANTINED' });
112
+ const prefix = `${path.basename(ref)}.invalid-`;
113
+ const names = (await readdir(path.dirname(ref))).filter((name) => name.startsWith(prefix)).sort().reverse();
114
+ for (const name of names.slice(QUARANTINE_KEEP)) await rm(path.join(path.dirname(ref), name), { force: true });
115
+ } catch { /* best-effort: the next read tries again */ }
116
+ return { schema: REGISTRY_SCHEMA, projects: [] };
117
+ }
118
+
90
119
  async function readJson(ref, missing) {
91
120
  let bytes;
92
121
  try { bytes = await readFile(ref, 'utf8'); } catch (error) {
@@ -152,7 +181,7 @@ async function withLock(lockRef, action) {
152
181
 
153
182
  export async function readActiveTodoDashboardProjects({ env = process.env, now = Date.now() } = {}) {
154
183
  const ref = paths(env).registry;
155
- const document = validateRegistry(await readJson(ref, { schema: REGISTRY_SCHEMA, projects: [] }));
184
+ const document = await readRegistry(ref);
156
185
  return document.projects.filter((entry) => now - Date.parse(entry.last_seen_at) <= TODO_DASHBOARD_STALE_MS)
157
186
  .sort((left, right) => left.display_name.localeCompare(right.display_name, 'ja')
158
187
  || left.project_id.localeCompare(right.project_id, 'en'));
@@ -163,7 +192,7 @@ export async function readVisibleTodoDashboardProjects({
163
192
  } = {}) {
164
193
  if (typeof projectHasActiveRun !== 'function') throw new TypeError('projectHasActiveRun required');
165
194
  const ref = paths(env).registry;
166
- const document = validateRegistry(await readJson(ref, { schema: REGISTRY_SCHEMA, projects: [] }));
195
+ const document = await readRegistry(ref);
167
196
  const visible = [];
168
197
  for (const entry of document.projects) {
169
198
  if (now - Date.parse(entry.last_seen_at) <= TODO_DASHBOARD_STALE_MS
@@ -226,7 +255,7 @@ export async function registerTodoDashboardActivity({
226
255
  await mkdir(refs.root, { recursive: true, mode: 0o700 });
227
256
  const pruned = [];
228
257
  await withLock(refs.lock, async () => {
229
- const current = validateRegistry(await readJson(refs.registry, { schema: REGISTRY_SCHEMA, projects: [] }));
258
+ const current = await readRegistry(refs.registry);
230
259
  const existing = current.projects.find((entry) => entry.project_id === projectId);
231
260
  if (existing !== undefined && existing.repo_root !== canonicalRoot && !adopt) {
232
261
  const error = new Error('project id is already owned by another canonical root');
@@ -266,7 +295,7 @@ export async function removeTodoDashboardProject({ projectId, env = process.env
266
295
  const refs = paths(env);
267
296
  await mkdir(refs.root, { recursive: true, mode: 0o700 });
268
297
  await withLock(refs.lock, async () => {
269
- const current = validateRegistry(await readJson(refs.registry, { schema: REGISTRY_SCHEMA, projects: [] }));
298
+ const current = await readRegistry(refs.registry);
270
299
  const projects = current.projects.filter((entry) => entry.project_id !== projectId);
271
300
  if (projects.length === current.projects.length) {
272
301
  const error = new Error('dashboard project is not registered');
@@ -0,0 +1,259 @@
1
+ /**
2
+ * Display-side rendering states for the gantt serving paths
3
+ * (docs/architecture/dfd-display-gantt-read.md). A read-only view writes nothing,
4
+ * so a Store inconsistency is shown as a typed state instead of refused as a 500.
5
+ * Store owns the read, the checkpoint and the typed result; this module owns the
6
+ * tolerant projection, the banner/empty-state markup and the per-project memo.
7
+ */
8
+ import { readTodoStoreDisplaySource, readTodoStoreForDisplay } from './todo-store.mjs';
9
+ import { digestTodoArtifact } from './todo-contracts.mjs';
10
+ import { BANNER_STYLE, escapeHtmlText } from './todo-gantt-html-shared.mjs';
11
+
12
+ export const GANTT_DISPLAY_REVALIDATE_MS = 30_000;
13
+ export const GANTT_DISPLAY_OMITTED_OVERLAYS = Object.freeze([
14
+ 'presentation', 'independence frontier', 'seam proposals', 'notes', 'structures', 'narratives',
15
+ ]);
16
+
17
+ const TASK_STATUSES = ['pending', 'in-progress', 'blocked', 'retired', 'done'];
18
+ const PHASE_STATUSES = ['locked', 'active', 'gate_ready', 'reviewing', 'accepted', 'rejected',
19
+ 'closed_unaudited'];
20
+ const CODE = /^[A-Z][A-Z0-9_]{0,63}$/u;
21
+ const SLUG = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/u;
22
+
23
+ const plain = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
24
+ const text = (value) => (typeof value === 'string' && value.length > 0 ? value : null);
25
+
26
+ /**
27
+ * Raw `{project_id, manifest, members:[{descriptor, plan, snapshot}]}` -> the renderer's
28
+ * read model. Task states and phase states come from the snapshot; titles, lanes, phases
29
+ * and dependency edges from `plan` when the Store could read it (`plan:null` falls back to
30
+ * ids in one lane without edges). Whatever cannot be projected is dropped and named; this
31
+ * never throws, and no edge that would make the layout fail (unknown endpoint, self edge,
32
+ * cycle) is kept.
33
+ */
34
+ export function projectUnverifiedStore(raw) {
35
+ const dropped = [];
36
+ const members = [];
37
+ const projectId = text(raw?.project_id) ?? text(raw?.manifest?.project_id) ?? 'unknown';
38
+ const taskKey = (planKey, taskId) => JSON.stringify([planKey, taskId]);
39
+ const known = new Set();
40
+ const edgesOf = []; // {planKey, from, to, kind}
41
+ const refKeyOf = (ref) => (plain(ref) && ref.project_id === projectId && text(ref.plan_key) !== null
42
+ && text(ref.task_id) !== null ? taskKey(ref.plan_key, ref.task_id) : null);
43
+ for (const entry of Array.isArray(raw?.members) ? raw.members : []) {
44
+ const planKey = text(entry?.descriptor?.plan_key);
45
+ const drop = (reason, extra = {}) => dropped.push({ plan_key: planKey,
46
+ code: 'DISPLAY_PROJECTION_DROPPED', reason, ...extra });
47
+ try {
48
+ if (planKey === null) { drop('descriptor_plan_key_invalid'); continue; }
49
+ const snapshot = entry.snapshot;
50
+ if (!plain(snapshot) || !Array.isArray(snapshot.tasks)) { drop('snapshot_tasks_invalid'); continue; }
51
+ const states = new Map();
52
+ for (const task of snapshot.tasks) {
53
+ const taskId = text(task?.task_id);
54
+ if (taskId === null || !TASK_STATUSES.includes(task.status)) {
55
+ drop('task_invalid', { task_id: taskId }); continue;
56
+ }
57
+ if (states.has(taskId)) { drop('task_duplicate', { task_id: taskId }); continue; }
58
+ states.set(taskId, { task_id: taskId, status: task.status, started_at: text(task.started_at),
59
+ done_at: text(task.done_at), blocked_reason: text(task.blocked_reason), evidence: null,
60
+ evidence_unverified: false, imported: false, test_result: null });
61
+ }
62
+ const plan = plain(entry.plan) && Array.isArray(entry.plan.tasks) ? entry.plan : null;
63
+ const planTasks = new Map();
64
+ for (const task of plan?.tasks ?? []) {
65
+ const taskId = text(task?.task_id);
66
+ if (taskId === null || planTasks.has(taskId)) { drop('plan_task_invalid', { task_id: taskId }); continue; }
67
+ if (!states.has(taskId)) { drop('task_state_missing', { task_id: taskId }); continue; }
68
+ planTasks.set(taskId, { task_id: taskId, title: text(task.title) ?? taskId,
69
+ lane: text(task.lane) ?? 'unverified', narrative_ref: null,
70
+ ...(text(task.phase_id) === null ? {} : { phase_id: task.phase_id }) });
71
+ }
72
+ // snapshot states the plan does not name still show, by id
73
+ for (const taskId of states.keys()) {
74
+ if (!planTasks.has(taskId)) planTasks.set(taskId, { task_id: taskId, title: taskId,
75
+ lane: 'unverified', narrative_ref: null });
76
+ }
77
+ if (planTasks.size === 0) { drop('no_projectable_task'); continue; }
78
+ const phases = [];
79
+ for (const phase of Array.isArray(snapshot.phases) ? snapshot.phases : []) {
80
+ const phaseId = text(phase?.phase_id);
81
+ if (phaseId === null || !PHASE_STATUSES.includes(phase.status)) {
82
+ drop('phase_invalid', { phase_id: phaseId }); continue;
83
+ }
84
+ phases.push({ phase_id: phaseId, status: phase.status, review_event_digest: null,
85
+ decision_event_digest: null, decision_evidence: null });
86
+ }
87
+ const phaseMeta = [];
88
+ for (const phase of Array.isArray(plan?.phases) ? plan.phases : []) {
89
+ const phaseId = text(phase?.phase_id);
90
+ if (phaseId === null) { drop('plan_phase_invalid'); continue; }
91
+ phaseMeta.push({ phase_id: phaseId, title: text(phase.title) ?? phaseId,
92
+ gate_policy: text(phase.gate_policy) ?? 'heavy' });
93
+ }
94
+ for (const taskId of planTasks.keys()) known.add(taskKey(planKey, taskId));
95
+ for (const edge of Array.isArray(plan?.hard_dependencies) ? plan.hard_dependencies : []) {
96
+ edgesOf.push({ planKey, kind: 'hard', from: edge?.from, to: edge?.to });
97
+ }
98
+ for (const join of Array.isArray(plan?.joins) ? plan.joins : []) {
99
+ edgesOf.push({ planKey, kind: 'join', join, from: join?.after, to: join?.before });
100
+ }
101
+ const descriptor = entry.descriptor;
102
+ members.push({
103
+ descriptor: { plan_key: planKey, active_plan_version: text(descriptor.active_plan_version),
104
+ topology_digest: text(descriptor.topology_digest) },
105
+ plan: { schema: 'lattice.todo_plan.v1', project_id: projectId, plan_key: planKey,
106
+ plan_version: text(snapshot.plan_version) ?? text(descriptor.active_plan_version) ?? 'unknown',
107
+ topology_digest: text(descriptor.topology_digest), hard_dependencies: [], joins: [],
108
+ phases: phaseMeta, tasks: [...planTasks.values()] },
109
+ tasks: [...planTasks.keys()].map((taskId) => states.get(taskId)), phases,
110
+ journal: { events: [] }, plan_scoped: { events: [] }, revision: null,
111
+ coordination: null, snapshot_stale: false,
112
+ });
113
+ } catch {
114
+ drop('projection_failed');
115
+ }
116
+ }
117
+ // Edges last: an endpoint must be a projected task, and no edge may close a cycle.
118
+ const successors = new Map();
119
+ const reaches = (from, to, seen = new Set()) => {
120
+ if (from === to) return true;
121
+ if (seen.has(from)) return false;
122
+ seen.add(from);
123
+ return (successors.get(from) ?? []).some((next) => reaches(next, to, seen));
124
+ };
125
+ const byPlan = new Map(members.map((member) => [member.plan.plan_key, member.plan]));
126
+ for (const { planKey, kind, join, from, to } of edgesOf) {
127
+ const targetKey = refKeyOf(to);
128
+ const sources = (kind === 'join' ? (Array.isArray(from) ? from : [null]) : [from]).map(refKeyOf);
129
+ const refOf = (ref) => ({ project_id: ref.project_id, plan_key: ref.plan_key, task_id: ref.task_id });
130
+ const valid = targetKey !== null && known.has(targetKey)
131
+ && sources.every((key) => key !== null && known.has(key) && key !== targetKey)
132
+ && (kind !== 'join' || text(join?.id) !== null);
133
+ // a join with any bad endpoint is dropped whole; a cycle drops only the closing edge
134
+ if (!valid || sources.some((key) => reaches(targetKey, key))) {
135
+ dropped.push({ plan_key: planKey, code: 'DISPLAY_PROJECTION_DROPPED',
136
+ reason: kind === 'join' ? 'join_invalid' : 'dependency_invalid', task_id: text(to?.task_id) });
137
+ continue;
138
+ }
139
+ for (const key of sources) successors.set(key, [...(successors.get(key) ?? []), targetKey]);
140
+ const plan = byPlan.get(planKey);
141
+ if (kind === 'hard') plan.hard_dependencies.push({ from: refOf(from), to: refOf(to) });
142
+ else plan.joins.push({ id: join.id, after: from.map(refOf), before: refOf(to) });
143
+ }
144
+ return {
145
+ store: { schema: 'lattice.todo_store_read.v1', project_id: projectId,
146
+ manifest: { manifest_digest: text(raw?.manifest?.manifest_digest) }, members,
147
+ snapshot_stale: false },
148
+ dropped,
149
+ };
150
+ }
151
+
152
+ // Only these two slugs of an inconsistency leave the server; everything else in `detail` stays.
153
+ export function publicDiagnostic(inconsistency) {
154
+ const code = CODE.test(inconsistency?.code) ? inconsistency.code : '-';
155
+ const reason = SLUG.test(inconsistency?.detail?.reason) ? inconsistency.detail.reason : '-';
156
+ return { code, reason };
157
+ }
158
+
159
+
160
+ function droppedMarkup(dropped) {
161
+ if (dropped.length === 0) return '';
162
+ const items = dropped.map((entry) => `<li><code>${escapeHtmlText(entry.plan_key ?? '-')}</code>${entry.task_id ? ` / <code>${escapeHtmlText(entry.task_id)}</code>` : ''}${entry.phase_id ? ` / <code>${escapeHtmlText(entry.phase_id)}</code>` : ''}: <code>${escapeHtmlText(CODE.test(entry.code) ? entry.code : 'DISPLAY_DROPPED')}</code> / <code>${escapeHtmlText(SLUG.test(entry.reason) ? entry.reason : '-')}</code></li>`).join('');
163
+ return `<p>表示から除いた対象:</p><ul>${items}</ul>`;
164
+ }
165
+
166
+ function omittedMarkup() {
167
+ return `<p>表示していない情報: ${GANTT_DISPLAY_OMITTED_OVERLAYS.map((name) => `<code>${escapeHtmlText(name)}</code>`).join(' · ')}</p>`;
168
+ }
169
+
170
+ /** `dropped` = Store dropped_members plus projection drops. Never claims validation. */
171
+ export function degradedBannerHtml({ state, verifiedAt = null, inconsistency, dropped = [] }) {
172
+ const { code, reason } = publicDiagnostic(inconsistency);
173
+ const lead = state === 'last_verified'
174
+ ? `最後に確認できた状態(${escapeHtmlText(verifiedAt ?? '-')})を表示中。現在の計画は整合していない`
175
+ : '未検証の現在の状態を表示中。計画は整合していない';
176
+ return `<aside role="status" data-display-state="${escapeHtmlText(state)}" style="${BANNER_STYLE}"><strong>${lead}: <code>${escapeHtmlText(code)}</code> / <code>${escapeHtmlText(reason)}</code></strong>${omittedMarkup()}${droppedMarkup(dropped)}</aside>`;
177
+ }
178
+
179
+ /** HTTP 200 page for `unavailable` (and an unverified view with nothing projectable). */
180
+ export function emptyStateHtml({ inconsistency, dropped = [] }) {
181
+ const { code, reason } = publicDiagnostic(inconsistency);
182
+ return `<!doctype html><html lang="ja"><head><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Lattice — 表示できる工程がありません</title></head><body><main data-display-state="unavailable" style="max-width:720px;margin:48px auto;padding:0 16px;font:16px/1.7 system-ui,-apple-system,'Hiragino Sans','Yu Gothic UI',sans-serif;color:#201d19"><h1>表示できる工程データがありません</h1><p>計画の状態を読み取れませんでした: <code>${escapeHtmlText(code)}</code> / <code>${escapeHtmlText(reason)}</code></p><p>読み取れるようになると、このページは自動で更新されます。</p>${droppedMarkup(dropped)}</main></body></html>`;
183
+ }
184
+
185
+ /** Live head: source + state + inconsistency code; overlay digests only when verified. */
186
+ export function displayHeadDigest(result, overlayHead = null) {
187
+ return digestTodoArtifact({
188
+ schema: 'lattice.todo_gantt_display_head.v1',
189
+ state: result.state,
190
+ source: result.source ?? null,
191
+ inconsistency_code: result.inconsistency?.code ?? null,
192
+ overlay_head: result.state === 'verified' ? overlayHead : null,
193
+ });
194
+ }
195
+
196
+ const PROJECT_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
197
+
198
+ /** Project id and plan keys a display result carries; unavailable carries neither. */
199
+ export function displayResultBinding(result) {
200
+ let projectId = null;
201
+ let planKeys = [];
202
+ if (result.state === 'unverified') {
203
+ const { store } = projectUnverifiedStore(result.store);
204
+ projectId = text(result.store?.project_id) ?? text(result.store?.manifest?.project_id);
205
+ planKeys = store.members.map(({ plan }) => plan.plan_key);
206
+ } else if (result.state === 'verified' || result.state === 'last_verified') {
207
+ projectId = text(result.store?.project_id);
208
+ planKeys = (Array.isArray(result.store?.members) ? result.store.members : [])
209
+ .map((member) => member?.descriptor?.plan_key).filter((key) => typeof key === 'string');
210
+ }
211
+ return { projectId: PROJECT_ID.test(projectId) ? projectId : null, planKeys: planKeys.sort() };
212
+ }
213
+
214
+ /**
215
+ * One per project, shared by every client. The memo is keyed by the source token
216
+ * observed at the last full-read attempt (not result.source, which is the
217
+ * checkpoint's in last_verified and null in unavailable), so a degraded but
218
+ * unchanged store is not fully re-read every poll. A probe failure is its own key:
219
+ * one full read, then reuse until the revalidation ceiling.
220
+ */
221
+ export function createTodoGanttDisplayReader({
222
+ repoRoot, readForDisplay = readTodoStoreForDisplay, readDisplaySource = readTodoStoreDisplaySource,
223
+ revalidateMs = GANTT_DISPLAY_REVALIDATE_MS, now = Date.now,
224
+ }) {
225
+ let memo = null;
226
+ let inflight = null;
227
+ const observe = async () => {
228
+ try { return `ok:${digestTodoArtifact(await readDisplaySource({ repoRoot }))}`; }
229
+ catch (error) { return `fail:${error?.code ?? 'PROBE_FAILED'}`; }
230
+ };
231
+ const load = async () => {
232
+ const key = await observe();
233
+ if (memo !== null && memo.valid && memo.key === key && now() - memo.at < revalidateMs) {
234
+ if (memo.fault !== undefined) throw memo.fault;
235
+ return memo.result;
236
+ }
237
+ const at = now();
238
+ memo = null;
239
+ // A token change during the attempt leaves the memo invalid for the next poll.
240
+ const settle = async (outcome) => {
241
+ memo = { key, at, valid: (await observe()) === key, ...outcome };
242
+ };
243
+ let result;
244
+ try { result = await readForDisplay({ repoRoot }); } catch (fault) {
245
+ // A real fault (not a typed result) is bounded like a probe failure: an unchanged token
246
+ // with a persisting fault is not re-read every poll; the revalidation ceiling still applies.
247
+ await settle({ fault });
248
+ throw fault;
249
+ }
250
+ await settle({ result });
251
+ return result;
252
+ };
253
+ return {
254
+ read() {
255
+ inflight ??= load().finally(() => { inflight = null; });
256
+ return inflight;
257
+ },
258
+ };
259
+ }
@@ -69,6 +69,13 @@ function renderDesignMemo(task) {
69
69
  return `<section class="design-memo"><h2>設計メモ</h2><div class="design-memo-body">${rendered.html}</div>${filtering}</section>`;
70
70
  }
71
71
 
72
+ /** 作成者が書いた終了条件(u12)。プレーンテキストをescapeして出し、文字列でなければ何も出さない。 */
73
+ function renderDoneCondition(task) {
74
+ if (typeof task.done_condition !== 'string') return '';
75
+ const text = escapeHtmlText(task.done_condition).replace(/\r\n|\r|\n/gu, '<br>');
76
+ return `<section><h2>終了条件</h2><p class="done-condition-body">${text}</p></section>`;
77
+ }
78
+
72
79
  /**
73
80
  * 図の外が語るための独立性要約を、plan単位の投影から引ける形へ畳む(ADR 0129 Decision 3)。
74
81
  */
@@ -246,7 +253,7 @@ export function renderRightPane(
246
253
  ? '<p class="fold-note">完走済みのため既定の図には描いていません。左上の「完走済み」バッジを押すと、このページ内で表示できます。</p>'
247
254
  : '<p class="fold-note">完走済みのため図には描いていません。図に出すには動的dashboardを <code>lattice todo gantt serve --port &lt;port&gt; --scope all</code> で起動してください。</p>';
248
255
  const workLog = notesEnabled ? renderNoteContext(section.noteContext, hostDisplayNames) : '';
249
- const designMemo = renderDesignMemo(section.task);
256
+ const designMemo = renderDesignMemo(section.task) + renderDoneCondition(section.task);
250
257
  return `<article class="task-detail" data-detail-key="${escapeHtmlAttribute(key)}" hidden><header><span class="detail-status status-${escapeHtmlAttribute(section.state.status)}">${escapeHtmlText(status.mark)} ${escapeHtmlText(status.label)}</span><span class="detail-reference">${escapeHtmlText(taskReference(section, lookup))}</span></header><h1>${escapeHtmlText(section.task.title)}</h1><p class="detail-category"><strong>カテゴリ:</strong> ${escapeHtmlText(category)}</p>${categoryDescription}<p><strong>正規ID:</strong> <code>${escapeHtmlText(`${section.ref.plan_key}/${section.task.task_id}`)}</code></p>${blockedReason}${readiness}${independenceNote}${foldedNote}${designMemo}<section><h2>前提工程</h2>${renderRelationList(incoming.get(key), sectionByKey, lookup, '登録済みの前提工程はありません。', folds)}</section><section><h2>後続工程</h2>${renderRelationList(outgoing.get(key), sectionByKey, lookup, '登録済みの後続工程はありません。', folds)}</section>${workLog}<p class="anchor-status">${escapeHtmlText(anchorText)}</p><details class="task-diagnostics"><summary>開発者向け診断</summary><dl><dt>canonical ref</dt><dd><code>${escapeHtmlText(`${section.ref.project_id}/${section.ref.plan_key}/${section.task.task_id}`)}</code></dd><dt>anchor</dt><dd>${escapeHtmlText(section.anchorOutcome.anchored ? 'verified' : section.anchorOutcome.reason)}</dd></dl></details></article>`;
251
258
  }).join('');
252
259
  const taskIndex = renderTaskIndex(sections, lookup, folds, planActivity(readModel));
@@ -255,7 +262,7 @@ export function renderRightPane(
255
262
  return `<div class="right-toolbar"><button type="button" data-show-overview>概要</button><button type="button" data-show-selected hidden>選択工程へ戻る</button><button type="button" data-show-task-index>全工程一覧</button>${structureButton}</div><div class="right-content">${overview}<div data-right-panel="details" hidden>${details}</div><section class="task-index" data-right-panel="task-index" hidden><h1>全工程</h1><p>Latticeに登録された全工程を現在の状態とともに表示しています。planは動いているものを最終活動の新しい順で上に、完走したものを古い順で下にまとめ、plan内は登録順です。</p>${taskIndex}</section>${renderTodoStructurePanel(structurePresentation)}${renderTodoStructureNoscript(structurePresentation)}</div>`;
256
263
  }
257
264
 
258
- export function renderDiagramLegend(presentation, layout = null, expandable = false) {
265
+ export function renderDiagramLegend(presentation, layout = null, expandable = false, noticesBanner = '') {
259
266
  const categories = (presentation?.lanes ?? []).map((lane) => `<div class="category-entry"><dt><code>${escapeHtmlText(lane.lane)}</code> — ${escapeHtmlText(lane.name)}</dt><dd>${escapeHtmlText(lane.description)}</dd></div>`).join('');
260
267
  const categoryDetails = categories === '' ? '' : `<details class="category-legend"><summary>カテゴリ説明</summary><dl>${categories}</dl></details>`;
261
268
  const foldedCount = layout?.scope?.folded_task_count ?? 0;
@@ -276,5 +283,5 @@ export function renderDiagramLegend(presentation, layout = null, expandable = fa
276
283
  const dispatchSentence = layout.independence === null
277
284
  ? 'ready frontierは全件同時dispatchが既定です。未登録の資源・host制約によりsubsetだけを選ぶ場合は理由を記録します。'
278
285
  : '同時着手できるかはカードの並列可否で判断してください。未検査の工程は依存線が無くても並列可の根拠になりません。';
279
- return `<div class="diagram-legend" aria-label="工程図の凡例"><span>${statusMarkup('pending', ' 未着手')}</span><span>${statusMarkup('in-progress', ' 作業中')}</span><span>${statusMarkup('done', ' 完了')}</span><span>${statusMarkup('blocked', ' ブロック中')}</span><span>破線枠: ready frontier</span>${independenceLegend}<span>太線: 構造上の最長依存鎖</span><span>半円: 非接触の線交差</span><span>黒丸: 論理上の合流</span>${foldChip}${categoryDetails}${foldNote}<p>縦方向は時間ではなく、登録済み依存関係による工程段階です。${dispatchSentence}構造上の最長依存鎖は各工程を同じ重みとして数え、実時間・工数・納期を表しません。</p></div>`;
286
+ return `<div class="diagram-legend" aria-label="工程図の凡例">${noticesBanner}<span>${statusMarkup('pending', ' 未着手')}</span><span>${statusMarkup('in-progress', ' 作業中')}</span><span>${statusMarkup('done', ' 完了')}</span><span>${statusMarkup('blocked', ' ブロック中')}</span><span>破線枠: ready frontier</span>${independenceLegend}<span>太線: 構造上の最長依存鎖</span><span>半円: 非接触の線交差</span><span>黒丸: 論理上の合流</span>${foldChip}${categoryDetails}${foldNote}<p>縦方向は時間ではなく、登録済み依存関係による工程段階です。${dispatchSentence}構造上の最長依存鎖は各工程を同じ重みとして数え、実時間・工数・納期を表しません。</p></div>`;
280
287
  }
@@ -1,4 +1,5 @@
1
1
  import { renderTodoGanttSvg, TODO_GANTT_STATUS_PRESENTATION } from './todo-gantt-svg.mjs';
2
+ import { isDecoupledPhaseTodoPlanSchema } from './todo-store-view.mjs';
2
3
 
3
4
  export const DOCUMENT_STATUS = TODO_GANTT_STATUS_PRESENTATION;
4
5
 
@@ -16,6 +17,20 @@ export function escapeHtmlText(value) {
16
17
  return String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
17
18
  }
18
19
 
20
+ // One banner look for every "shown with a caveat" state (display states and render notices).
21
+ export const BANNER_STYLE = 'margin:0;padding:10px 16px;border-bottom:2px solid #e85f2a;background:#fff4e8;color:#201d19;font:13px/1.6 system-ui,-apple-system,"Hiragino Sans","Yu Gothic UI",sans-serif';
22
+
23
+ /** Visible list of render notices ({code, message, detail}); empty string when there are none. */
24
+ export function noticesBannerHtml(notices) {
25
+ if (!Array.isArray(notices) || notices.length === 0) return '';
26
+ const items = notices.map(({ code, message, detail }) => {
27
+ const text = detail === undefined || detail === null ? '' : JSON.stringify(detail);
28
+ const shown = text.length > 600 ? `${text.slice(0, 600)}…` : text;
29
+ return `<li><code>${escapeHtmlText(code)}</code> ${escapeHtmlText(message)}${shown === '' ? '' : ` <code>${escapeHtmlText(shown)}</code>`}</li>`;
30
+ }).join('');
31
+ return `<aside role="status" data-render-notices style="${BANNER_STYLE}"><strong>一部を省いて表示しています</strong><ul>${items}</ul></aside>`;
32
+ }
33
+
19
34
  export function refKey(ref) {
20
35
  return JSON.stringify([ref.project_id, ref.plan_key, ref.task_id]);
21
36
  }
@@ -158,7 +173,7 @@ export function renderPhaseProgress(readModel) {
158
173
  }
159
174
  }
160
175
  const decoupled = readModel.members.some(({ plan }) => (
161
- ['lattice.todo_plan.v5', 'lattice.todo_plan.v7'].includes(plan.schema)
176
+ isDecoupledPhaseTodoPlanSchema(plan.schema)
162
177
  ));
163
178
  const guidance = decoupled
164
179
  ? 'ToDo完了とPhase受理は別です。Phaseは重監査の順序を表し、通常ToDoの開始順はToDo依存だけで決まります。'