@quolu/lattice 0.83.0 → 0.84.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.
@@ -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) {
@@ -7,7 +7,7 @@
7
7
  */
8
8
  import { readTodoStoreDisplaySource, readTodoStoreForDisplay } from './todo-store.mjs';
9
9
  import { digestTodoArtifact } from './todo-contracts.mjs';
10
- import { escapeHtmlText } from './todo-gantt-html-shared.mjs';
10
+ import { BANNER_STYLE, escapeHtmlText } from './todo-gantt-html-shared.mjs';
11
11
 
12
12
  export const GANTT_DISPLAY_REVALIDATE_MS = 30_000;
13
13
  export const GANTT_DISPLAY_OMITTED_OVERLAYS = Object.freeze([
@@ -156,7 +156,6 @@ export function publicDiagnostic(inconsistency) {
156
156
  return { code, reason };
157
157
  }
158
158
 
159
- 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';
160
159
 
161
160
  function droppedMarkup(dropped) {
162
161
  if (dropped.length === 0) return '';
@@ -262,7 +262,7 @@ export function renderRightPane(
262
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>`;
263
263
  }
264
264
 
265
- export function renderDiagramLegend(presentation, layout = null, expandable = false) {
265
+ export function renderDiagramLegend(presentation, layout = null, expandable = false, noticesBanner = '') {
266
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('');
267
267
  const categoryDetails = categories === '' ? '' : `<details class="category-legend"><summary>カテゴリ説明</summary><dl>${categories}</dl></details>`;
268
268
  const foldedCount = layout?.scope?.folded_task_count ?? 0;
@@ -283,5 +283,5 @@ export function renderDiagramLegend(presentation, layout = null, expandable = fa
283
283
  const dispatchSentence = layout.independence === null
284
284
  ? 'ready frontierは全件同時dispatchが既定です。未登録の資源・host制約によりsubsetだけを選ぶ場合は理由を記録します。'
285
285
  : '同時着手できるかはカードの並列可否で判断してください。未検査の工程は依存線が無くても並列可の根拠になりません。';
286
- 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>`;
287
287
  }
@@ -17,6 +17,20 @@ export function escapeHtmlText(value) {
17
17
  return String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
18
18
  }
19
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
+
20
34
  export function refKey(ref) {
21
35
  return JSON.stringify([ref.project_id, ref.plan_key, ref.task_id]);
22
36
  }
@@ -4,13 +4,14 @@ import { auditPendingPhasesOf } from './todo-audit-pending.mjs';
4
4
  import { serializeJsonForScript } from './todo-markdown-renderer.mjs';
5
5
  import { renderTodoGanttSvg, TODO_GANTT_STATUS_PRESENTATION } from './todo-gantt-svg.mjs';
6
6
  import { renderDiagramLegend, renderRightPane } from './todo-gantt-html-independence.mjs';
7
- import { escapeHtmlAttribute, escapeHtmlText, refKey } from './todo-gantt-html-shared.mjs';
7
+ import { escapeHtmlAttribute, escapeHtmlText, noticesBannerHtml, refKey } from './todo-gantt-html-shared.mjs';
8
8
  import { CSS, NESTED_CSS } from './todo-gantt-html-style.mjs';
9
9
  import { TODO_STRUCTURE_PRESENTATION_SCHEMA } from './todo-structure-presentation.mjs';
10
10
 
11
11
  export const TODO_GANTT_RENDERER_VERSION = 'lattice.todo_gantt_renderer.v20';
12
12
  export const TODO_GANTT_PROSE_MAX_BYTES = 8 * 1024 * 1024;
13
13
  export const TODO_GANTT_HTML_MAX_BYTES = 24 * 1024 * 1024;
14
+ const PROSE_OMITTED_TEXT = '(表示上限のため省略)';
14
15
 
15
16
  function projectDisplayName(readModel, metadata) {
16
17
  for (const candidate of [metadata?.project_display_name, metadata?.project_name]) {
@@ -69,7 +70,7 @@ function digest(value) {
69
70
  * still read, because anchor verification needs them, and their size is still
70
71
  * bounded — but they are not rendered into the page.
71
72
  */
72
- function normalizeSections(readModel, narratives, anchorOutcomes, noteContexts) {
73
+ function normalizeSections(readModel, narratives, anchorOutcomes, noteContexts, omitProse = false) {
73
74
  const supplied = new Map(narratives.map((entry) => [refKey(entry.ref), entry]));
74
75
  const outcomes = new Map(anchorOutcomes.map((entry) => [refKey(entry.ref), entry]));
75
76
  const notes = noteContexts === null ? null : new Map(noteContexts.map((entry) => [
@@ -78,6 +79,13 @@ function normalizeSections(readModel, narratives, anchorOutcomes, noteContexts)
78
79
  const result = [];
79
80
  const counted = new Set();
80
81
  let proseBytes = 0;
82
+ // u03 D-gantt: prose over the budget is left out of the page (and counted here), never refused.
83
+ const omitted = { design_memo: 0, done_condition: 0, narrative: 0, notes: 0 };
84
+ const fits = (bytes) => {
85
+ if (omitProse || proseBytes + bytes > TODO_GANTT_PROSE_MAX_BYTES) return false;
86
+ proseBytes += bytes;
87
+ return true;
88
+ };
81
89
  for (const member of readModel.members) {
82
90
  const states = new Map(member.tasks.map((state) => [state.task_id, state]));
83
91
  for (const task of member.plan.tasks) {
@@ -88,48 +96,45 @@ function normalizeSections(readModel, narratives, anchorOutcomes, noteContexts)
88
96
  const markdown = narrative?.markdown ?? '';
89
97
  const narrativeRef = narrative?.narrative_ref ?? task.narrative_ref;
90
98
  // 終了条件(u12)も設計メモと同じ埋め込み散文として数える。
91
- for (const prose of [task.design_memo, task.done_condition]) {
92
- if (typeof prose !== 'string') continue;
93
- proseBytes += Buffer.byteLength(prose, 'utf8');
94
- if (proseBytes > TODO_GANTT_PROSE_MAX_BYTES) {
95
- throw new TodoGanttRenderError('TODO_SCALE_EXCEEDED', 'todo gantt embedded prose limit exceeded', {
96
- prose_bytes: proseBytes, prose_limit: TODO_GANTT_PROSE_MAX_BYTES,
97
- });
98
- }
99
+ let shownTask = task;
100
+ for (const field of ['design_memo', 'done_condition']) {
101
+ if (typeof task[field] !== 'string' || fits(Buffer.byteLength(task[field], 'utf8'))) continue;
102
+ omitted[field] += 1;
103
+ shownTask = { ...shownTask, [field]: PROSE_OMITTED_TEXT };
99
104
  }
100
105
  // ToDos that share one narrative document count its bytes once.
101
106
  const documentKey = narrativeRef === null
102
107
  ? refKey(ref) : JSON.stringify([member.plan.plan_key, narrativeRef, digest(markdown)]);
103
108
  if (!counted.has(documentKey)) {
104
109
  counted.add(documentKey);
105
- proseBytes += Buffer.byteLength(markdown, 'utf8');
106
- if (proseBytes > TODO_GANTT_PROSE_MAX_BYTES) {
107
- throw new TodoGanttRenderError('TODO_SCALE_EXCEEDED', 'todo gantt embedded prose limit exceeded', {
108
- prose_bytes: proseBytes, prose_limit: TODO_GANTT_PROSE_MAX_BYTES,
109
- });
110
- }
110
+ // The narrative is never rendered into the page, so leaving it out changes nothing visible.
111
+ if (!fits(Buffer.byteLength(markdown, 'utf8'))) omitted.narrative += 1;
111
112
  }
112
113
  const anchorOutcome = outcomes.get(refKey(ref)) ?? {
113
114
  ref, narrative_ref: narrativeRef, anchored: false, reason: 'anchor_missing',
114
115
  origin_line: task.narrative_anchor?.origin_line ?? null,
115
116
  };
116
- const noteContext = notes?.get(refKey(ref)) ?? null;
117
- if (noteContext !== null) {
118
- proseBytes += noteContext.notes.reduce((bytes, note) => (
119
- bytes + Buffer.byteLength(note.body, 'utf8')
120
- ), 0);
121
- if (proseBytes > TODO_GANTT_PROSE_MAX_BYTES) {
122
- throw new TodoGanttRenderError('TODO_SCALE_EXCEEDED', 'todo gantt embedded prose limit exceeded', {
123
- prose_bytes: proseBytes, prose_limit: TODO_GANTT_PROSE_MAX_BYTES,
124
- });
125
- }
117
+ let noteContext = notes?.get(refKey(ref)) ?? null;
118
+ if (noteContext !== null && !fits(noteContext.notes.reduce((bytes, note) => (
119
+ bytes + Buffer.byteLength(note.body, 'utf8')
120
+ ), 0))) {
121
+ omitted.notes += 1;
122
+ noteContext = null;
126
123
  }
127
124
  result.push({
128
- ref, task, state: states.get(task.task_id), narrativeRef, anchorOutcome, noteContext,
125
+ ref, task: shownTask, state: states.get(task.task_id), narrativeRef, anchorOutcome, noteContext,
129
126
  });
130
127
  }
131
128
  }
132
- return { sections: result, proseBytes };
129
+ const omittedCount = Object.values(omitted).reduce((total, count) => total + count, 0);
130
+ const notices = omittedCount === 0 ? [] : [{
131
+ code: 'TODO_SCALE_EXCEEDED',
132
+ message: omitProse
133
+ ? 'ページ全体の大きさが上限を超えたため、設計メモ・終了条件・作業記録を省いて描いています'
134
+ : '埋め込み文章が上限を超えたため、超えた分の設計メモ・終了条件・作業記録を省いて描いています',
135
+ detail: { prose_bytes: proseBytes, prose_limit: TODO_GANTT_PROSE_MAX_BYTES, omitted },
136
+ }];
137
+ return { sections: result, proseBytes, notices };
133
138
  }
134
139
 
135
140
  const CONTROLLER = `
@@ -211,6 +216,7 @@ const NESTED_CONTROLLER = `
211
216
  export function renderTodoGanttHtml({
212
217
  readModel, layout, narratives = [], anchorOutcomes = [], presentation = null, metadata = {},
213
218
  expandedLayout = null, noteContexts = null, noteWarnings = [], structurePresentation = null,
219
+ notices = [],
214
220
  }) {
215
221
  if (readModel?.schema !== 'lattice.todo_store_read.v1' || !Array.isArray(readModel.members)) {
216
222
  throw new TypeError('readModel must be lattice.todo_store_read.v1');
@@ -221,6 +227,7 @@ export function renderTodoGanttHtml({
221
227
  throw new TypeError('noteContexts must be null or an array');
222
228
  }
223
229
  if (!Array.isArray(noteWarnings)) throw new TypeError('noteWarnings must be an array');
230
+ if (!Array.isArray(notices)) throw new TypeError('notices must be an array');
224
231
  if (presentation !== null
225
232
  && (presentation?.schema !== 'lattice.todo_gantt_presentation_model.v1'
226
233
  || presentation.project_id !== readModel.project_id)) {
@@ -231,32 +238,44 @@ export function renderTodoGanttHtml({
231
238
  || structurePresentation.project_id !== readModel.project_id)) {
232
239
  throw new TypeError('structurePresentation must be lattice.todo_structure_presentation.v1');
233
240
  }
234
- const normalized = normalizeSections(readModel, narratives, anchorOutcomes, noteContexts);
235
- const displayName = projectDisplayName(readModel, metadata);
236
- const hasHierarchy = layout?.hierarchy?.schema === 'lattice.todo_gantt_hierarchy.v1';
237
- const svg = renderTodoGanttSvg(layout, { presentation });
238
- // The expanded diagram travels with the page so the badge can bring the
239
- // history back without a round trip. A file:// artifact has nowhere to ask.
240
- const expandedSvg = expandedLayout === null ? '' : renderTodoGanttSvg(expandedLayout, { presentation });
241
- const diagrams = expandedSvg === ''
242
- ? `<div data-diagram="live">${svg}</div>`
243
- : `<div data-diagram="live">${svg}</div><div data-diagram="expanded" hidden>${expandedSvg}</div>`;
244
- const rightPane = renderRightPane(
245
- normalized.sections, layout, presentation, readModel, noteContexts !== null, noteWarnings,
246
- expandedSvg !== '', structurePresentation,
247
- );
248
- const staticData = serializeJsonForScript({
249
- renderer_version: TODO_GANTT_RENDERER_VERSION,
250
- metadata,
251
- presentation,
252
- structure_presentation: structurePresentation,
253
- });
254
- const html = `<!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 — ${escapeHtmlText(displayName)} 依存工程図</title><style>${CSS}${hasHierarchy ? NESTED_CSS : ''}</style></head><body data-gantt-root data-view-state="overview"><main class="shell"><section class="gantt-pane" aria-label="${escapeHtmlAttribute(displayName)} 依存工程図"><div class="diagram-toolbar" role="group" aria-label="図のズーム"><strong class="project-heading">${escapeHtmlText(displayName)} 依存工程図</strong>${renderAuditPendingChip(readModel)}<button type="button" data-zoom-action="out" aria-label="縮小">−</button><button type="button" data-zoom-action="reset">等倍</button><button type="button" data-zoom-action="in" aria-label="拡大">+</button><button type="button" data-zoom-action="fit">全体表示</button><output class="zoom-readout" data-zoom-output aria-live="polite">100%</output><span class="diagram-note">縦=依存段階(時間ではない)</span></div>${renderDiagramLegend(presentation, layout, expandedSvg !== '')}<div class="diagram-scroll" data-diagram-scroll tabindex="0" aria-label="縦方向を主にスクロール可能な依存工程図">${diagrams}</div></section><div class="pane-divider" data-pane-divider aria-hidden="true"></div><aside class="narrative-pane" aria-label="選択工程の詳細と全工程一覧">${rightPane}</aside></main><script type="application/json" id="todo-gantt-data">${staticData}</script><script>${CONTROLLER}${hasHierarchy ? NESTED_CONTROLLER : ''}</script></body></html>`;
255
- const htmlBytes = Buffer.byteLength(html, 'utf8');
256
- if (htmlBytes > TODO_GANTT_HTML_MAX_BYTES) {
257
- throw new TodoGanttRenderError('TODO_SCALE_EXCEEDED', 'todo gantt HTML limit exceeded', {
258
- html_bytes: htmlBytes, html_limit: TODO_GANTT_HTML_MAX_BYTES,
241
+ const build = (normalized, pageNotices) => {
242
+ const displayName = projectDisplayName(readModel, metadata);
243
+ const hasHierarchy = layout?.hierarchy?.schema === 'lattice.todo_gantt_hierarchy.v1';
244
+ const svg = renderTodoGanttSvg(layout, { presentation });
245
+ // The expanded diagram travels with the page so the badge can bring the
246
+ // history back without a round trip. A file:// artifact has nowhere to ask.
247
+ const expandedSvg = expandedLayout === null ? '' : renderTodoGanttSvg(expandedLayout, { presentation });
248
+ const diagrams = expandedSvg === ''
249
+ ? `<div data-diagram="live">${svg}</div>`
250
+ : `<div data-diagram="live">${svg}</div><div data-diagram="expanded" hidden>${expandedSvg}</div>`;
251
+ const rightPane = renderRightPane(
252
+ normalized.sections, layout, presentation, readModel, noteContexts !== null, noteWarnings,
253
+ expandedSvg !== '', structurePresentation,
254
+ );
255
+ const staticData = serializeJsonForScript({
256
+ renderer_version: TODO_GANTT_RENDERER_VERSION,
257
+ metadata,
258
+ presentation,
259
+ structure_presentation: structurePresentation,
259
260
  });
261
+ const html = `<!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 — ${escapeHtmlText(displayName)} 依存工程図</title><style>${CSS}${hasHierarchy ? NESTED_CSS : ''}</style></head><body data-gantt-root data-view-state="overview"><main class="shell"><section class="gantt-pane" aria-label="${escapeHtmlAttribute(displayName)} 依存工程図"><div class="diagram-toolbar" role="group" aria-label="図のズーム"><strong class="project-heading">${escapeHtmlText(displayName)} 依存工程図</strong>${renderAuditPendingChip(readModel)}<button type="button" data-zoom-action="out" aria-label="縮小">−</button><button type="button" data-zoom-action="reset">等倍</button><button type="button" data-zoom-action="in" aria-label="拡大">+</button><button type="button" data-zoom-action="fit">全体表示</button><output class="zoom-readout" data-zoom-output aria-live="polite">100%</output><span class="diagram-note">縦=依存段階(時間ではない)</span></div>${renderDiagramLegend(presentation, layout, expandedSvg !== '', noticesBannerHtml(pageNotices))}<div class="diagram-scroll" data-diagram-scroll tabindex="0" aria-label="縦方向を主にスクロール可能な依存工程図">${diagrams}</div></section><div class="pane-divider" data-pane-divider aria-hidden="true"></div><aside class="narrative-pane" aria-label="選択工程の詳細と全工程一覧">${rightPane}</aside></main><script type="application/json" id="todo-gantt-data">${staticData}</script><script>${CONTROLLER}${hasHierarchy ? NESTED_CONTROLLER : ''}</script></body></html>`;
262
+ return html;
263
+ };
264
+ const layoutNotices = [...(layout?.notices ?? []), ...notices];
265
+ let normalized = normalizeSections(readModel, narratives, anchorOutcomes, noteContexts);
266
+ let pageNotices = [...layoutNotices, ...normalized.notices];
267
+ let html = build(normalized, pageNotices);
268
+ let htmlBytes = Buffer.byteLength(html, 'utf8');
269
+ if (htmlBytes > TODO_GANTT_HTML_MAX_BYTES) {
270
+ // u03 D-gantt: draw the page without the embedded prose; if it is still over, serve it with the notice.
271
+ normalized = normalizeSections(readModel, narratives, anchorOutcomes, noteContexts, true);
272
+ pageNotices = [...layoutNotices, { code: 'TODO_SCALE_EXCEEDED',
273
+ message: 'ページ全体の大きさが上限を超えたため、設計メモ・終了条件・作業記録を省いて描いています',
274
+ detail: { html_bytes: htmlBytes, html_limit: TODO_GANTT_HTML_MAX_BYTES } }];
275
+ html = build(normalized, pageNotices);
276
+ htmlBytes = Buffer.byteLength(html, 'utf8');
260
277
  }
261
- return { html, html_digest: digest(html), prose_bytes: normalized.proseBytes, html_bytes: htmlBytes };
278
+ return {
279
+ html, html_digest: digest(html), prose_bytes: normalized.proseBytes, html_bytes: htmlBytes, notices: pageNotices,
280
+ };
262
281
  }
@@ -7,6 +7,8 @@ import { createTodoReadiness } from './todo-readiness.mjs';
7
7
  const TASK_LIMIT = 2_000;
8
8
  const EDGE_LIMIT = 8_000;
9
9
  const SWEEP_ROUNDS = 4;
10
+ // A notice names at most this many refs; the count always covers all of them.
11
+ const NOTICE_SAMPLE = 20;
10
12
 
11
13
  /** Columns for a stage made only of ToDos with no registered dependency. */
12
14
  const LOOSE_COLUMNS_MINIMUM = 8;
@@ -108,11 +110,10 @@ function compareText(left, right) {
108
110
  return left < right ? -1 : left > right ? 1 : 0;
109
111
  }
110
112
 
111
- function refOf(value, context) {
113
+ // null when the value is not a task ref; the caller skips what it cannot draw.
114
+ function refOf(value) {
112
115
  if (!plain(value) || typeof value.project_id !== 'string'
113
- || typeof value.plan_key !== 'string' || typeof value.task_id !== 'string') {
114
- fail('TODO_LAYOUT_INVALID_INPUT', `${context} must be a task ref`);
115
- }
116
+ || typeof value.plan_key !== 'string' || typeof value.task_id !== 'string') return null;
116
117
  return { project_id: value.project_id, plan_key: value.plan_key, task_id: value.task_id };
117
118
  }
118
119
 
@@ -136,6 +137,7 @@ function normalizeInput(readModel) {
136
137
  fail('TODO_LAYOUT_INVALID_INPUT', 'read model must be lattice.todo_store_read.v1');
137
138
  }
138
139
 
140
+ const notices = []; // u03 D-gantt: a read-only drawing draws what it can and says what it left out
139
141
  const nodesByKey = new Map();
140
142
  const retiredKeys = new Set(); // 撤去済みtask。端点に持つ辺は図から一緒に消す
141
143
  const members = [...readModel.members].sort((left, right) => {
@@ -192,22 +194,30 @@ function normalizeInput(readModel) {
192
194
  });
193
195
  }
194
196
  }
197
+ const droppedKeys = new Set(); // 上限で描かないtask。端点に持つ辺は黙って除く(通知は件数で済む)
195
198
  if (nodesByKey.size > TASK_LIMIT) {
196
- fail('TODO_SCALE_EXCEEDED', 'todo gantt task limit exceeded', {
197
- task_count: nodesByKey.size, task_limit: TASK_LIMIT, edge_count: null, edge_limit: EDGE_LIMIT,
199
+ const kept = [...nodesByKey.values()].sort((left, right) => compareRefs(left.ref, right.ref));
200
+ for (const node of kept.slice(TASK_LIMIT)) { nodesByKey.delete(node.key); droppedKeys.add(node.key); }
201
+ notices.push({
202
+ code: 'TODO_SCALE_EXCEEDED',
203
+ message: `工程数が上限を超えたため、並び順の先頭${TASK_LIMIT}件だけを描いています(${droppedKeys.size}件を除外)`,
204
+ detail: { task_count: kept.length, task_limit: TASK_LIMIT, dropped_task_count: droppedKeys.size },
198
205
  });
199
206
  }
200
207
 
201
208
  const edgeMap = new Map();
209
+ const skippedEdges = [];
210
+ const skipEdge = (from, to, reason) => skippedEdges.push({ from, to, reason });
202
211
  const addEdge = (fromValue, toValue, kind, joinIdentity = null) => {
203
- const fromRef = refOf(fromValue, 'edge.from');
204
- const toRef = refOf(toValue, 'edge.to');
212
+ const fromRef = refOf(fromValue);
213
+ const toRef = refOf(toValue);
214
+ if (fromRef === null || toRef === null) return skipEdge(fromRef && refKey(fromRef), toRef && refKey(toRef), 'not_a_task_ref');
205
215
  const from = refKey(fromRef);
206
216
  const to = refKey(toRef);
207
217
  if (retiredKeys.has(from) || retiredKeys.has(to)) return; // 撤去済み端点の辺は描かない
208
- if (!nodesByKey.has(from) || !nodesByKey.has(to) || from === to) {
209
- fail('TODO_LAYOUT_INVALID_INPUT', 'edge must connect two distinct read-model tasks');
210
- }
218
+ if (droppedKeys.has(from) || droppedKeys.has(to)) return;
219
+ if (from === to) return skipEdge(from, to, 'self_edge');
220
+ if (!nodesByKey.has(from) || !nodesByKey.has(to)) return skipEdge(from, to, 'endpoint_not_in_read_model');
211
221
  const key = JSON.stringify([from, to]);
212
222
  let edge = edgeMap.get(key);
213
223
  if (edge === undefined) {
@@ -223,10 +233,11 @@ function normalizeInput(readModel) {
223
233
  }
224
234
  };
225
235
  for (const member of members) {
226
- for (const edge of member.plan.hard_dependencies) addEdge(edge.from, edge.to, 'hard');
236
+ for (const edge of member.plan.hard_dependencies) addEdge(edge?.from, edge?.to, 'hard');
227
237
  for (const join of member.plan.joins) {
228
238
  if (!plain(join) || !Array.isArray(join.after) || typeof join.id !== 'string') {
229
- fail('TODO_LAYOUT_INVALID_INPUT', 'join has an invalid shape');
239
+ skipEdge(null, null, 'join_invalid_shape');
240
+ continue;
230
241
  }
231
242
  const identity = { project_id: member.plan.project_id, plan_key: member.plan.plan_key,
232
243
  join_id: join.id };
@@ -236,22 +247,105 @@ function normalizeInput(readModel) {
236
247
  for (const dependency of projectTodoCrossPlanDependencies(members)) {
237
248
  addEdge(dependency.from, dependency.to, 'cross_plan');
238
249
  }
239
- if (edgeMap.size > EDGE_LIMIT) {
240
- fail('TODO_SCALE_EXCEEDED', 'todo gantt edge limit exceeded', {
241
- task_count: nodesByKey.size, task_limit: TASK_LIMIT,
242
- edge_count: edgeMap.size, edge_limit: EDGE_LIMIT,
250
+ if (skippedEdges.length > 0) {
251
+ notices.push({
252
+ code: 'TODO_LAYOUT_INVALID_INPUT',
253
+ message: `端点を図に描けない依存${skippedEdges.length}件を除いて描いています`,
254
+ detail: { skipped_edge_count: skippedEdges.length, skipped_edges: skippedEdges.slice(0, NOTICE_SAMPLE) },
243
255
  });
244
256
  }
245
257
 
246
258
  const nodes = [...nodesByKey.values()].sort((left, right) => compareRefs(left.ref, right.ref));
247
- const edges = [...edgeMap.values()].sort((left, right) => compareText(left.key, right.key));
248
- return { nodes, nodesByKey, edges, retiredKeys };
259
+ let edges = [...edgeMap.values()].sort((left, right) => compareText(left.key, right.key));
260
+ if (edges.length > EDGE_LIMIT) {
261
+ notices.push({
262
+ code: 'TODO_SCALE_EXCEEDED',
263
+ message: `依存数が上限を超えたため、並び順の先頭${EDGE_LIMIT}本だけを描いています(${edges.length - EDGE_LIMIT}本を除外)`,
264
+ detail: { edge_count: edges.length, edge_limit: EDGE_LIMIT, dropped_edge_count: edges.length - EDGE_LIMIT },
265
+ });
266
+ edges = edges.slice(0, EDGE_LIMIT);
267
+ }
268
+ edges = breakCycles(nodes, nodesByKey, edges, notices);
269
+ return { nodes, nodesByKey, edges, retiredKeys, notices };
270
+ }
271
+
272
+ /**
273
+ * u03 D-gantt: a cycle is drawn, not refused. Nodes the topological pass cannot reach (the
274
+ * cycle part, with what hangs off it) are reduced to the tasks that can reach back into a
275
+ * cycle; among those, taken in ref order, each edge that points back to an earlier one is left
276
+ * out, so the rest is acyclic and every later step terminates. The notice names every cut edge.
277
+ */
278
+ function breakCycles(nodes, nodesByKey, edges, notices) {
279
+ const indegree = new Map(nodes.map(({ key }) => [key, 0]));
280
+ const outgoing = new Map(nodes.map(({ key }) => [key, []]));
281
+ for (const edge of edges) { indegree.set(edge.to, indegree.get(edge.to) + 1); outgoing.get(edge.from).push(edge.to); }
282
+ const queue = nodes.filter(({ key }) => indegree.get(key) === 0).map(({ key }) => key);
283
+ const visited = new Set();
284
+ while (queue.length > 0) {
285
+ const current = queue.pop();
286
+ visited.add(current);
287
+ for (const next of outgoing.get(current)) {
288
+ indegree.set(next, indegree.get(next) - 1);
289
+ if (indegree.get(next) === 0) queue.push(next);
290
+ }
291
+ }
292
+ if (visited.size === nodes.length) return edges;
293
+ // Peel what only hangs below a cycle (no way back into it), so only cycle tasks lose edges.
294
+ const core = new Set(nodes.filter(({ key }) => !visited.has(key)).map(({ key }) => key));
295
+ const outdegree = new Map([...core].map((key) => [key, 0]));
296
+ const incoming = new Map([...core].map((key) => [key, []]));
297
+ for (const edge of edges) {
298
+ if (core.has(edge.from) && core.has(edge.to)) {
299
+ outdegree.set(edge.from, outdegree.get(edge.from) + 1); incoming.get(edge.to).push(edge.from);
300
+ }
301
+ }
302
+ const leaves = [...core].filter((key) => outdegree.get(key) === 0);
303
+ while (leaves.length > 0) {
304
+ const leaf = leaves.pop();
305
+ core.delete(leaf);
306
+ for (const from of incoming.get(leaf)) {
307
+ outdegree.set(from, outdegree.get(from) - 1);
308
+ if (outdegree.get(from) === 0) leaves.push(from);
309
+ }
310
+ }
311
+ const rank = new Map(nodes.filter(({ key }) => core.has(key)).map(({ key }, index) => [key, index]));
312
+ const cut = [];
313
+ const kept = edges.filter((edge) => {
314
+ if (!rank.has(edge.from) || !rank.has(edge.to) || rank.get(edge.from) < rank.get(edge.to)) return true;
315
+ cut.push(edge);
316
+ return false;
317
+ });
318
+ notices.push({
319
+ code: 'TODO_LAYOUT_CYCLE',
320
+ message: `依存が循環しているため、循環部分の工程${rank.size}件の戻り方向の依存${cut.length}本を除いて描いています`,
321
+ detail: {
322
+ cycle_task_count: rank.size,
323
+ cycle_tasks: [...rank.keys()].slice(0, NOTICE_SAMPLE).map((key) => nodesByKey.get(key).ref),
324
+ cut_edge_count: cut.length,
325
+ cut_edges: cut.slice(0, NOTICE_SAMPLE).map((edge) => ({
326
+ from: nodesByKey.get(edge.from).ref, to: nodesByKey.get(edge.to).ref,
327
+ })),
328
+ },
329
+ });
330
+ return kept;
249
331
  }
250
332
 
251
333
  // u03 D-gantt: the drawing never decides readiness itself. Lattice's readiness (the same one
252
334
  // status and start use) decides, so a successor of a retired-not-done task is not drawn ready.
253
335
  function readyTaskKeys(readModel, nodes) {
254
- const readiness = createTodoReadiness(readModel);
336
+ // Readiness reads the raw edge lists; hand it only the edges normalizeInput can draw, so a
337
+ // malformed one (skipped with a notice) does not stop the page here.
338
+ const drawable = (edge) => refOf(edge?.from) !== null && refOf(edge?.to) !== null;
339
+ const members = readModel.members.map((member) => ({
340
+ ...member,
341
+ plan: {
342
+ ...member.plan,
343
+ hard_dependencies: member.plan.hard_dependencies.filter(drawable),
344
+ joins: member.plan.joins.filter((join) => plain(join) && Array.isArray(join.after)
345
+ && join.after.every((after) => refOf(after) !== null) && refOf(join.before) !== null),
346
+ },
347
+ }));
348
+ const readiness = createTodoReadiness({ ...readModel, members });
255
349
  return new Set(nodes.filter((node) => readiness.isReady(readiness.key(node.ref))).map(({ key }) => key));
256
350
  }
257
351
 
@@ -282,6 +376,7 @@ function assignWaves(nodes, nodesByKey, edges) {
282
376
  }
283
377
  }
284
378
  }
379
+ // normalizeInput's breakCycles leaves no cycle; this only guards that invariant.
285
380
  if (visited !== nodes.length) fail('TODO_LAYOUT_CYCLE', 'todo layout input contains a cycle');
286
381
  return { incoming, outgoing, wave };
287
382
  }
@@ -370,13 +465,14 @@ function crossingCount(edges, wave, transversePosition) {
370
465
  * 読み出しはasync I/Oとgit実行を伴うためCLI層が行い、ここへは値として渡る。
371
466
  * layoutは同期pureのままに保つ。
372
467
  */
373
- function normalizeIndependence(value, nodesByKey) {
468
+ function normalizeIndependence(value, nodesByKey, notices) {
374
469
  if (value === null || value === undefined) return { stateByKey: new Map(), summary: null };
375
470
  if (!Array.isArray(value)) {
376
471
  fail('TODO_LAYOUT_INVALID_INPUT', 'independence must be an array of plan projections');
377
472
  }
378
473
  const stateByKey = new Map();
379
474
  const plans = [];
475
+ const drifted = [];
380
476
  for (const projection of value) {
381
477
  if (!plain(projection) || typeof projection.plan_key !== 'string'
382
478
  || typeof projection.coverage !== 'string' || !plain(projection.frontier)) {
@@ -388,11 +484,10 @@ function normalizeIndependence(value, nodesByKey) {
388
484
  project_id: projection.project_id, plan_key: planKey, task_id: taskId,
389
485
  });
390
486
  // 図に無いtaskへ状態を付けない。layoutのready判定と投影のready判定が食い違えば、
391
- // 静かに無視するのでなくここで露見させる。
487
+ // 印を付けずに通知で露見させる(読むだけの図は拒まない)。
392
488
  if (!nodesByKey.has(key)) {
393
- fail('TODO_LAYOUT_INDEPENDENCE_DRIFT', 'independence references a task absent from layout', {
394
- plan_key: planKey, task_id: taskId,
395
- });
489
+ drifted.push({ plan_key: planKey, task_id: taskId });
490
+ return;
396
491
  }
397
492
  stateByKey.set(key, state);
398
493
  };
@@ -423,6 +518,13 @@ function normalizeIndependence(value, nodesByKey) {
423
518
  });
424
519
  }
425
520
  plans.sort((left, right) => compareText(left.plan_key, right.plan_key));
521
+ if (drifted.length > 0) {
522
+ notices.push({
523
+ code: 'TODO_LAYOUT_INDEPENDENCE_DRIFT',
524
+ message: `独立性の記録が図に無い工程${drifted.length}件を指しているため、その工程には印を付けていません`,
525
+ detail: { drifted_count: drifted.length, drifted_tasks: drifted.slice(0, NOTICE_SAMPLE) },
526
+ });
527
+ }
426
528
  return { stateByKey, summary: { plans } };
427
529
  }
428
530
 
@@ -519,7 +621,7 @@ function layoutTodoGanttFlat(readModel, options = {}) {
519
621
  const longestNodeKeys = new Set(chain.longest_chain_node_refs.map(refKey));
520
622
  const longestEdgeKeys = new Set(chain.longest_chain_edges.map(edge => JSON.stringify([refKey(edge.from), refKey(edge.to)])));
521
623
  const readyKeys = readyTaskKeys(readModel, full.nodes);
522
- const independence = normalizeIndependence(options.independence ?? null, full.nodesByKey);
624
+ const independence = normalizeIndependence(options.independence ?? null, full.nodesByKey, full.notices);
523
625
  const seamProposals = normalizeSeamProposals(options.seamProposals ?? null);
524
626
 
525
627
  // Only the geometry stage below sees the narrowed graph.
@@ -859,6 +961,9 @@ function layoutTodoGanttFlat(readModel, options = {}) {
859
961
  .map((taskKey) => JSON.parse(taskKey))
860
962
  .map(([project_id, plan_key, task_id]) => ({ project_id, plan_key, task_id }))
861
963
  .sort(compareRefs),
964
+ // u03 D-gantt: what the drawing left out or bent instead of refusing, each as {code, message, detail}.
965
+ // Absent when there is nothing to say, so a clean layout keeps its bytes (and digest).
966
+ ...(full.notices.length > 0 ? { notices: full.notices } : {}),
862
967
  metrics: {
863
968
  crossing_count: crossingCount(edges, wave, transversePosition),
864
969
  visible_node_count: visibleKeys.size,
@@ -914,11 +1019,13 @@ export function layoutTodoGantt(readModel, options = {}) {
914
1019
  ? fullLayout : layoutTodoGanttFlat(readModel, { ...options, scope: 'all' });
915
1020
  const semanticByKey = new Map(semanticLayout.nodes.map((node) => [refKey(node.ref), node]));
916
1021
  const semanticRoot = applyHierarchySemantics(nested.root, semanticByKey);
917
- const rootLayout = semanticRoot.layout;
1022
+ // The levels' own notices repeat or partly cover the whole graph's; the whole graph's are the ones to show.
1023
+ const { notices: _levelNotices, ...rootLayout } = semanticRoot.layout;
918
1024
  return {
919
1025
  ...rootLayout,
920
1026
  full_edges: fullLayout.full_edges,
921
1027
  groups: fullLayout.groups,
1028
+ ...(fullLayout.notices === undefined ? {} : { notices: fullLayout.notices }),
922
1029
  scope: fullLayout.scope,
923
1030
  folded: fullLayout.folded,
924
1031
  hierarchy_nodes: descendantNodes(semanticRoot),
@@ -6,8 +6,7 @@
6
6
  *
7
7
  * 文は事実と次の一歩だけを述べ、指示しない。どのreadyを取るかはhostが所有する
8
8
  * (ADR 0063 Decision 5)。命令形にするとLatticeがagentを統制する面へ滑る。
9
- * ただし記録があるのに対象工程が未検証なら start は拒否する(ADR 0182)。
10
- * それは配車ではなく、intakeが hold する着手を journal へ書かない。
9
+ * 未検証の工程も start は拒否しない(u03 B1–B6、ADR 0182 を置き換える)。助言として返す。
11
10
  */
12
11
 
13
12
  export const TODO_INDEPENDENCE_GUIDANCE_CODES = Object.freeze([
@@ -83,7 +82,7 @@ const CATALOG = Object.freeze({
83
82
  next_action: 'declare_witness_set_then_compile',
84
83
  }),
85
84
  independence_task_undeclared: Object.freeze({
86
- message: 'この工程はwitness setで宣言されていないため、記録には含まれていない。startは拒否する。',
85
+ message: 'この工程はwitness setで宣言されていないため、記録には含まれていない。',
87
86
  next_action: 'add_task_to_witness_set_then_compile',
88
87
  }),
89
88
  independence_contract_superseded: Object.freeze({
@@ -175,27 +174,6 @@ const SEVERABILITY_HINT = Object.freeze({
175
174
  serial: '共有stateまたはeffectの衝突なので、分割では切り離せない。',
176
175
  });
177
176
 
178
- /**
179
- * 記録があるのに対象工程が未検証なら start を拒否する code。
180
- * 記録が無い(independence_unrecorded)は従来どおり助言だけで通す。
181
- * 競合(conflict_*)はどの ready を取るかの dispatch なので拒否しない。
182
- */
183
- export const INDEPENDENCE_START_REFUSAL_CODES = Object.freeze([
184
- 'independence_task_undeclared',
185
- 'independence_stale_for_task',
186
- 'independence_superseded',
187
- 'independence_contract_superseded',
188
- 'independence_verdicts_absent',
189
- ]);
190
-
191
- export function independenceStartRefusal(guidance) {
192
- if (guidance === null || typeof guidance !== 'object' || Array.isArray(guidance)) {
193
- throw new TypeError('independence start refusal guidance is invalid');
194
- }
195
- if (!INDEPENDENCE_START_REFUSAL_CODES.includes(guidance.code)) return null;
196
- return guidance;
197
- }
198
-
199
177
  export function todoIndependenceGuidance(code, { severability = null } = {}) {
200
178
  const entry = CATALOG[code];
201
179
  if (entry === undefined) {
@@ -328,11 +306,11 @@ export function selectSeamProposalGuidance({ coverage, unknownKinds = [] }) {
328
306
  export const TODO_INDEPENDENCE_WORKFLOW = Object.freeze([
329
307
  '1. 宣言する: .lattice/todo/witness/<plan_key>.json へ、ToDoごとのowns/reads/writes/affected_testsを書く',
330
308
  ' 係争資源しか所有していないToDoは、ownsまたはwritesの内側で自分が触るsymbolをconcern_anchorsへ宣言できる(witness set v2)。並列可否の判定には写らず、切断候補の束縛だけに効く',
331
- ' remaining の A 工程(まだ done でない ready / blocked)も同じ witness に含める。現在の ready だけを compile すると、次の frontier の start が INDEPENDENCE_UNVERIFIED になる',
309
+ ' remaining の A 工程(まだ done でない ready / blocked)も同じ witness に含める。現在の ready だけを compile すると、次の frontier の start の助言が未検証(independence_task_undeclared)になる',
332
310
  '2. 判定する: lattice todo independence compile --plan <key> --input <ref>(実sensorを引く。pretty-printやdigest未計算の下書きは機械が直す)。next_ready が witness に無い compile は拒否する',
333
311
  '3. 読む: lattice todo independence --plan <key> --json(sensorを引かず、記録とHEAD照合だけで返る)',
334
312
  '4. 追従する: plan改訂後は lattice todo independence witness migrate --plan <key> で宣言を写してから再compileする',
335
- '5. 記録があるのに対象工程が未宣言・失効なら todo start は拒否する。競合の同時起動は助言のまま',
313
+ '5. 記録があるのに対象工程が未宣言・失効でも todo start は止まらず、助言として返る。競合の同時起動も助言のまま',
336
314
  ]);
337
315
 
338
316
  /**