@quolu/lattice 0.82.0 → 0.83.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 (66) hide show
  1. package/bin/lattice-bridge-supervisor.mjs +10 -0
  2. package/bin/lattice-dashboard.mjs +3 -18
  3. package/bin/lattice-mcp.mjs +6 -3
  4. package/bin/lattice.mjs +1 -1
  5. package/docs/schemas/lattice.plan_create_input.v5.schema.json +375 -0
  6. package/docs/schemas/lattice.plan_revise_input.v1.schema.json +6 -3
  7. package/package.json +2 -1
  8. package/sensor/dist/db/index.d.ts +1 -0
  9. package/sensor/dist/db/index.d.ts.map +1 -1
  10. package/sensor/dist/db/index.js +13 -0
  11. package/sensor/dist/db/index.js.map +1 -1
  12. package/sensor/dist/index.d.ts.map +1 -1
  13. package/sensor/dist/index.js +12 -2
  14. package/sensor/dist/index.js.map +1 -1
  15. package/sensor/dist/mcp/answer-freshness.js +1 -1
  16. package/sensor/dist/mcp/answer-freshness.js.map +1 -1
  17. package/sensor/dist/mcp/engine.d.ts +11 -0
  18. package/sensor/dist/mcp/engine.d.ts.map +1 -1
  19. package/sensor/dist/mcp/engine.js +83 -4
  20. package/sensor/dist/mcp/engine.js.map +1 -1
  21. package/sensor/dist/mcp/index-repair.d.ts +7 -0
  22. package/sensor/dist/mcp/index-repair.d.ts.map +1 -0
  23. package/sensor/dist/mcp/index-repair.js +93 -0
  24. package/sensor/dist/mcp/index-repair.js.map +1 -0
  25. package/sensor/dist/mcp/index.d.ts.map +1 -1
  26. package/sensor/dist/mcp/index.js +12 -7
  27. package/sensor/dist/mcp/index.js.map +1 -1
  28. package/sensor/dist/mcp/tools.d.ts +4 -0
  29. package/sensor/dist/mcp/tools.d.ts.map +1 -1
  30. package/sensor/dist/mcp/tools.js +29 -9
  31. package/sensor/dist/mcp/tools.js.map +1 -1
  32. package/src/bridge-hub-server.mjs +46 -9
  33. package/src/cli-help.mjs +2 -2
  34. package/src/dashboard-lifecycle-journal.mjs +42 -20
  35. package/src/plan-backchain.mjs +25 -8
  36. package/src/plan-revise.mjs +129 -28
  37. package/src/project-cli.mjs +42 -18
  38. package/src/project-identity.mjs +14 -0
  39. package/src/runtime-cli.mjs +31 -18
  40. package/src/runtime-control-store.mjs +22 -1
  41. package/src/runtime-decision-verifier.mjs +27 -8
  42. package/src/runtime-engine.mjs +34 -5
  43. package/src/runtime-hold-recompile.mjs +19 -15
  44. package/src/runtime-kept-worktree.mjs +136 -0
  45. package/src/runtime-lifecycle-lock.mjs +118 -30
  46. package/src/runtime-managed-supervisor.mjs +10 -10
  47. package/src/runtime-pull-intake.mjs +87 -43
  48. package/src/store-lock.mjs +142 -57
  49. package/src/todo-authoring-input.mjs +56 -2
  50. package/src/todo-cli.mjs +168 -42
  51. package/src/todo-contracts.mjs +22 -6
  52. package/src/todo-dashboard-registry.mjs +31 -4
  53. package/src/todo-gantt-display.mjs +260 -0
  54. package/src/todo-gantt-html-independence.mjs +8 -1
  55. package/src/todo-gantt-html-shared.mjs +2 -1
  56. package/src/todo-gantt-html.mjs +4 -2
  57. package/src/todo-gantt-layout.mjs +7 -36
  58. package/src/todo-gantt-live.mjs +6 -3
  59. package/src/todo-note-store.mjs +6 -3
  60. package/src/todo-readiness.mjs +29 -8
  61. package/src/todo-revision.mjs +9 -8
  62. package/src/todo-split.mjs +6 -3
  63. package/src/todo-status.mjs +53 -9
  64. package/src/todo-store-cache.mjs +1 -1
  65. package/src/todo-store-view.mjs +21 -2
  66. package/src/todo-store.mjs +545 -166
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomBytes } from 'node:crypto';
2
- import { link, lstat, mkdir, open, readFile, readdir, rm, rmdir } from 'node:fs/promises';
2
+ import { link, lstat, mkdir, open, readFile, readdir, rename, rm, rmdir, utimes } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { fsyncDirectory } from './fs-dir-sync.mjs';
5
5
  import { syncPublishedFile } from './fs-publish.mjs';
@@ -7,6 +7,13 @@ import { observeStartIdentityRaw, observeProcessHostIdentityRaw } from './runtim
7
7
 
8
8
  const hash = (value) => createHash('sha256').update(value).digest('hex');
9
9
  const CLAIM = /^([0-9a-f]{64})-([1-9][0-9]*)-([0-9a-f]{64})-([0-9a-f]{16})$/u;
10
+ // u03 N1/N2: an owner that cannot be proven dead (foreign host, legacy, weak) is abandoned once
11
+ // its heartbeat mtime is older than LOCK_STALE_MS; every holder touches its lock and claim.
12
+ export const LOCK_STALE_MS = 10 * 60_000;
13
+ export const LOCK_HEARTBEAT_MS = 30_000;
14
+ // Weak identity when own observation is unavailable: never PID-recovered, only heartbeat-stale.
15
+ const WEAK = 'unobserved';
16
+ const NO_HARD_LINK = ['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'EXDEV', 'ENOSYS'];
10
17
  let ownStart;
11
18
  let ownHost;
12
19
 
@@ -17,9 +24,7 @@ export class StoreLockError extends Error {
17
24
  this.reason = reason;
18
25
  this.detail = {
19
26
  lock_path: lockPath,
20
- next_action: reason === 'lock_owner_unidentified'
21
- ? `Confirm no writer is running, then manually remove the unidentified lock: ${lockPath}`
22
- : `Retry after the owner releases ${lockPath}; if it cannot, confirm no writer on the recorded host before manually clearing the abandoned lock.`,
27
+ next_action: `Retry after the owner releases ${lockPath}; an owner that stops refreshing it is recovered automatically after ${LOCK_STALE_MS / 60_000} minutes.`,
23
28
  ...detail,
24
29
  };
25
30
  }
@@ -45,46 +50,96 @@ async function processIsDead(pid, startDigest) {
45
50
  const observed = await observeStartIdentityRaw(pid);
46
51
  if (observed) return hash(`${process.platform}:${observed}`) !== startDigest;
47
52
  } catch {
48
- // A failed observation cannot turn an existing PID into a dead owner.
53
+ // A failed observation cannot turn an existing PID into a dead owner, but a PID that
54
+ // vanished meanwhile was a short-lived reuser (Windows reuses PIDs at once): the owner is gone.
55
+ try { process.kill(pid, 0); }
56
+ catch (error) { if (error?.code === 'ESRCH') return true; }
49
57
  }
50
58
  return false;
51
59
  }
52
60
 
61
+ /** Returns null (absent) or {owner (null when unidentified), stale, info: the judged lstat}. */
53
62
  async function readOwner(lockPath) {
54
63
  try {
55
64
  const info = await lstat(lockPath);
56
- if (!info.isFile() || info.isSymbolicLink() || info.size > 8192) {
57
- throw new StoreLockError('lock_owner_unidentified', lockPath);
58
- }
65
+ const stale = info.mtimeMs < Date.now() - LOCK_STALE_MS;
66
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 8192) return { owner: null, stale, info };
59
67
  let owner;
60
68
  try { owner = JSON.parse(await readFile(lockPath, 'utf8')); }
61
69
  catch (error) {
62
70
  if (error?.code === 'ENOENT') return null;
63
71
  if (!(error instanceof SyntaxError)) throw error;
64
- throw new StoreLockError('lock_owner_unidentified', lockPath);
72
+ return { owner: null, stale, info };
65
73
  }
66
- if (!identified(owner)) throw new StoreLockError('lock_owner_unidentified', lockPath);
67
- return owner;
74
+ return { owner: identified(owner) ? owner : null, stale, info };
68
75
  } catch (error) {
69
76
  if (error?.code === 'ENOENT') return null;
70
77
  throw error;
71
78
  }
72
79
  }
73
80
 
74
- async function ownerIsDead(owner, host) {
75
- return owner.host === host && owner.process_start.platform === process.platform
76
- && processIsDead(owner.pid,
81
+ /** A local identified owner is judged by PID + start only; any other owner by heartbeat staleness. */
82
+ async function abandoned({ owner, stale }, host) {
83
+ if (owner !== null && host !== WEAK && owner.host === host
84
+ && owner.process_start.platform === process.platform) {
85
+ return processIsDead(owner.pid,
77
86
  hash(`${owner.process_start.platform}:${owner.process_start.identity}`));
87
+ }
88
+ return stale;
89
+ }
90
+
91
+ /**
92
+ * Remove only the entry that was judged abandoned. A stale owner may still be alive and
93
+ * release, letting a new owner link in between judgement and removal; that one goes back.
94
+ */
95
+ async function removeJudged(lockPath, judged) {
96
+ const quarantine = `${lockPath}.${randomBytes(8).toString('hex')}.stale`;
97
+ try { await rename(lockPath, quarantine); }
98
+ catch (error) { if (error?.code === 'ENOENT') return; throw error; }
99
+ const moved = await lstat(quarantine).catch((error) => {
100
+ if (error?.code !== 'ENOENT') throw error;
101
+ return null;
102
+ });
103
+ // Swept concurrently: only an entry older than LOCK_STALE_MS is swept, so it was abandoned too.
104
+ if (moved === null) return;
105
+ if (moved.dev === judged.dev && moved.ino === judged.ino && moved.size === judged.size
106
+ && moved.mtimeMs === judged.mtimeMs) {
107
+ await rm(quarantine);
108
+ return;
109
+ }
110
+ try { await link(quarantine, lockPath); }
111
+ catch (error) {
112
+ if (error?.code !== 'EEXIST' && !NO_HARD_LINK.includes(error?.code)) throw error;
113
+ // Both owners stay on disk; the displaced one fails its held-check (lock_lost).
114
+ throw new StoreLockError('store_locked', lockPath, {
115
+ cause: 'lock_recovery_raced', quarantine_path: quarantine,
116
+ next_action: `Retry; ${quarantine} keeps the owner displaced by a racing recovery and is removed by hand only after that owner exits.`,
117
+ });
118
+ }
119
+ await rm(quarantine);
120
+ }
121
+
122
+ function busy(state, lockPath) {
123
+ return new StoreLockError(state.owner === null ? 'lock_owner_unidentified' : 'store_locked', lockPath);
124
+ }
125
+
126
+ async function isStale(entryPath) {
127
+ const info = await lstat(entryPath).catch((error) => {
128
+ if (error?.code !== 'ENOENT') throw error;
129
+ return null;
130
+ });
131
+ return info !== null && info.mtimeMs < Date.now() - LOCK_STALE_MS;
78
132
  }
79
133
 
80
134
  async function removeDeadTemporaries(lockPath, hostDigest) {
81
135
  const prefix = `${path.basename(lockPath)}.`;
82
136
  for (const name of await readdir(path.dirname(lockPath))) {
83
- if (!name.startsWith(prefix) || !name.endsWith('.tmp')) continue;
84
- const parsed = name.slice(prefix.length, -4).match(CLAIM);
85
- if (parsed && parsed[1] === hostDigest && Number.isSafeInteger(Number(parsed[2]))
86
- && await processIsDead(Number(parsed[2]), parsed[3])) {
87
- const temporary = path.join(path.dirname(lockPath), name);
137
+ if (!name.startsWith(prefix) || !(name.endsWith('.tmp') || name.endsWith('.stale'))) continue;
138
+ const parsed = name.endsWith('.tmp') ? name.slice(prefix.length, -4).match(CLAIM) : null;
139
+ const temporary = path.join(path.dirname(lockPath), name);
140
+ // A `.stale` quarantine's owner already fails assertHeld; it goes once older than LOCK_STALE_MS.
141
+ const local = parsed && parsed[1] === hostDigest && Number.isSafeInteger(Number(parsed[2]));
142
+ if (local ? await processIsDead(Number(parsed[2]), parsed[3]) : await isStale(temporary)) {
88
143
  const info = await lstat(temporary).catch((error) => {
89
144
  if (error?.code !== 'ENOENT') throw error;
90
145
  return null;
@@ -107,7 +162,7 @@ async function recoveryClaim(claimsPath, owner, lockPath) {
107
162
  catch (error) { if (error?.code !== 'ENOENT') throw error; }
108
163
  }
109
164
  try {
110
- await removeDeadClaims(claimsPath, hostDigest, lockPath);
165
+ await removeDeadClaims(claimsPath, owner.host === WEAK ? null : hostDigest, lockPath);
111
166
  // All claimants publish before inspection; only a sole claimant may recover.
112
167
  // Timestamp ordering could let a delayed earlier publisher enter twice.
113
168
  const candidates = await readdir(claimsPath);
@@ -133,9 +188,9 @@ async function removeDeadClaims(claimsPath, hostDigest, lockPath) {
133
188
  }
134
189
  for (const entry of await readdir(claimsPath, { withFileTypes: true })) {
135
190
  const parsed = entry.name.match(CLAIM);
136
- if (entry.isDirectory() && parsed && parsed[1] === hostDigest
137
- && Number.isSafeInteger(Number(parsed[2]))
138
- && await processIsDead(Number(parsed[2]), parsed[3])) {
191
+ const local = parsed && parsed[1] === hostDigest && Number.isSafeInteger(Number(parsed[2]));
192
+ if (entry.isDirectory() && (local ? await processIsDead(Number(parsed[2]), parsed[3])
193
+ : await isStale(path.join(claimsPath, entry.name)))) {
139
194
  try { await rmdir(path.join(claimsPath, entry.name)); }
140
195
  catch (error) { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error?.code)) throw error; }
141
196
  }
@@ -161,28 +216,40 @@ export async function withStoreLock({ lockPath, recoveryClaimsPath = `${lockPath
161
216
  let identity;
162
217
  let host;
163
218
  try { [identity, host] = await Promise.all([ownStart, ownHost]); }
164
- catch {
165
- throw new StoreLockError('store_locked', lockPath, {
166
- cause: 'lock_identity_unavailable',
167
- next_action: `Restore platform host-domain and process-start observation, then retry ${lockPath}`,
168
- });
169
- }
170
- const owner = { pid: process.pid,
219
+ catch { identity = WEAK; host = WEAK; }
220
+ let owner = { pid: process.pid,
171
221
  process_start: { platform: process.platform, identity }, host };
172
- if (!identified(owner)) throw new StoreLockError('store_locked', lockPath, {
173
- cause: 'lock_identity_unavailable',
174
- next_action: `Restore platform host-domain and process-start observation, then retry ${lockPath}`,
175
- });
222
+ if (!identified(owner)) {
223
+ host = WEAK;
224
+ owner = { pid: process.pid, process_start: { platform: process.platform, identity: WEAK }, host };
225
+ }
176
226
  const ownerBytes = `${JSON.stringify(owner)}\n`;
177
227
  const temporary = `${lockPath}.${hash(host)}-${owner.pid}-${hash(`${owner.process_start.platform}:${owner.process_start.identity}`)}-${randomBytes(8).toString('hex')}.tmp`;
178
228
  let claimPath = null;
179
229
  let acquired = false;
180
230
  let fileIdentity = null;
181
231
  let callbackEntered = false;
232
+ let heartbeat = null;
233
+ let lost = false;
234
+ const stillOwned = async (current) => {
235
+ if (current === null || !acquired) return false;
236
+ const info = await lstat(current).catch((error) => {
237
+ if (error?.code === 'ENOENT') return null;
238
+ throw error;
239
+ });
240
+ return info !== null && info.isFile() && !info.isSymbolicLink()
241
+ && info.dev === fileIdentity.dev && info.ino === fileIdentity.ino
242
+ && await readFile(current, 'utf8').catch((error) => {
243
+ if (error?.code === 'ENOENT') return null;
244
+ throw error;
245
+ }) === ownerBytes;
246
+ };
182
247
  try {
183
- await removeDeadTemporaries(lockPath, hash(host));
248
+ // A weak writer cannot prove anyone dead by PID; it only clears stale entries.
249
+ const hostDigest = host === WEAK ? null : hash(host);
250
+ await removeDeadTemporaries(lockPath, hostDigest);
184
251
  for (const claimsPath of new Set([recoveryClaimsPath, `${lockPath}.recovery`])) {
185
- await removeDeadClaims(claimsPath, hash(host), lockPath);
252
+ await removeDeadClaims(claimsPath, hostDigest, lockPath);
186
253
  try { await rmdir(claimsPath); }
187
254
  catch (error) { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error?.code)) throw error; }
188
255
  }
@@ -195,31 +262,57 @@ export async function withStoreLock({ lockPath, recoveryClaimsPath = `${lockPath
195
262
  for (;;) {
196
263
  try { await link(temporary, lockPath); acquired = true; break; }
197
264
  catch (error) {
198
- if (['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'EXDEV', 'ENOSYS'].includes(error?.code)) {
199
- throw new StoreLockError('store_locked', lockPath, {
200
- cause: 'lock_publication_unavailable',
201
- next_action: `Use a filesystem permitting atomic hard-link publication for ${lockPath}, then retry`,
202
- });
203
- }
204
- if (error?.code !== 'EEXIST') throw error;
265
+ if (NO_HARD_LINK.includes(error?.code)) {
266
+ // u03: without hard links publish in place; a torn record reads as unidentified and goes stale.
267
+ let direct = null;
268
+ try { direct = await open(lockPath, 'wx', 0o600); }
269
+ catch (openError) { if (openError?.code !== 'EEXIST') throw openError; }
270
+ if (direct !== null) {
271
+ try {
272
+ await direct.writeFile(ownerBytes); await syncPublishedFile(direct, lockPath);
273
+ fileIdentity = await direct.stat();
274
+ } finally { await direct.close(); }
275
+ acquired = true;
276
+ break;
277
+ }
278
+ } else if (error?.code !== 'EEXIST') throw error;
205
279
  }
206
280
  const existing = await readOwner(lockPath);
207
281
  if (existing === null) continue;
208
- if (!await ownerIsDead(existing, host)) throw new StoreLockError('store_locked', lockPath);
282
+ if (!await abandoned(existing, host)) throw busy(existing, lockPath);
209
283
  if (claimPath === null) {
210
284
  claimPath = await recoveryClaim(recoveryClaimsPath, owner, lockPath);
211
285
  if (onRecoveryClaim) await onRecoveryClaim();
212
286
  }
213
287
  const fresh = await readOwner(lockPath);
214
288
  if (fresh !== null) {
215
- if (!await ownerIsDead(fresh, host)) throw new StoreLockError('store_locked', lockPath);
216
- await rm(lockPath);
289
+ if (!await abandoned(fresh, host)) throw busy(fresh, lockPath);
290
+ await removeJudged(lockPath, fresh.info);
217
291
  }
218
292
  }
219
293
  await rm(temporary);
220
294
  await fsyncDirectory(path.dirname(lockPath));
295
+ // Touch only our own entry: a resumed old holder must not keep a replacement lock fresh.
296
+ heartbeat = setInterval(() => {
297
+ Promise.resolve(releasePath()).then(async (current) => {
298
+ if (current === null) return;
299
+ if (!await stillOwned(current)) { lost = true; clearInterval(heartbeat); return; }
300
+ const now = new Date();
301
+ await Promise.all([utimes(current, now, now),
302
+ claimPath === null ? null : utimes(claimPath, now, now)]);
303
+ }).catch(() => {});
304
+ }, LOCK_HEARTBEAT_MS);
305
+ heartbeat.unref();
221
306
  callbackEntered = true;
222
- return await callback();
307
+ // Callers check right before publishing; the check-to-rename gap is a named residual.
308
+ return await callback(async () => {
309
+ if (!lost && await stillOwned(await releasePath())) return;
310
+ lost = true;
311
+ throw new StoreLockError('store_locked', lockPath, {
312
+ cause: 'lock_lost',
313
+ next_action: `Retry; ${lockPath} was recovered by another writer while this one held it, and nothing was published after the check.`,
314
+ });
315
+ });
223
316
  } catch (error) {
224
317
  if (!callbackEntered && error?.code === 'ENOENT') {
225
318
  throw new StoreLockError('store_locked', lockPath, {
@@ -229,18 +322,10 @@ export async function withStoreLock({ lockPath, recoveryClaimsPath = `${lockPath
229
322
  }
230
323
  throw error;
231
324
  } finally {
325
+ clearInterval(heartbeat);
232
326
  try {
233
327
  const currentLockPath = await releasePath();
234
- const currentIdentity = currentLockPath === null ? null : await lstat(currentLockPath).catch((error) => {
235
- if (error?.code === 'ENOENT') return null;
236
- throw error;
237
- });
238
- if (acquired && currentIdentity?.isFile() && !currentIdentity.isSymbolicLink()
239
- && currentIdentity.dev === fileIdentity.dev && currentIdentity.ino === fileIdentity.ino
240
- && await readFile(currentLockPath, 'utf8').catch((error) => {
241
- if (error?.code === 'ENOENT') return null;
242
- throw error;
243
- }) === ownerBytes) {
328
+ if (await stillOwned(currentLockPath)) {
244
329
  await rm(currentLockPath);
245
330
  await fsyncDirectory(path.dirname(currentLockPath));
246
331
  }
@@ -10,7 +10,7 @@ import { lstat, readFile, realpath } from 'node:fs/promises';
10
10
  import path from 'node:path';
11
11
  import { parseTree } from 'jsonc-parser';
12
12
 
13
- import { todoSelfDigest } from './todo-contracts.mjs';
13
+ import { canonicalizeTodoArtifact, todoSelfDigest } from './todo-contracts.mjs';
14
14
  import { TodoStoreError } from './todo-store.mjs';
15
15
 
16
16
  const MAX_AUTHORING_INPUT_BYTES = 8_388_608;
@@ -29,6 +29,7 @@ export const AUTHORING_DIGEST_FIELDS = Object.freeze({
29
29
  'lattice.plan_create_input.v2': 'input_digest',
30
30
  'lattice.plan_create_input.v3': 'input_digest',
31
31
  'lattice.plan_create_input.v4': 'input_digest',
32
+ 'lattice.plan_create_input.v5': 'input_digest',
32
33
  'lattice.todo_revision.v1': 'revision_digest',
33
34
  'lattice.todo_revision.v2': 'revision_digest',
34
35
  'lattice.phase_todo_revision.v1': 'revision_digest',
@@ -85,11 +86,64 @@ export function parseAuthoringJson(text, { invalidCode = 'INVALID_JSON' } = {})
85
86
  return null;
86
87
  }
87
88
 
89
+ // todo-contractsのcompareText/refKey/phaseRefKeyと同じ比較。validatorが要求する正準順そのもの。
90
+ const compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
91
+ const refKey = (value) => `${value?.project_id}\0${value?.plan_key}\0${value?.task_id}`;
92
+ const phaseRefKey = (value) => `${value?.project_id}\0${value?.plan_key}\0${value?.phase_id}`;
93
+
94
+ /** 正準順へ整列し、完全一致の重複だけを落とす。同じkeyで内容が違うものは残し、validatorに拒否させる。 */
95
+ function sortUnique(list, key) {
96
+ if (!Array.isArray(list)) return list;
97
+ const seen = new Set();
98
+ const kept = [];
99
+ for (const entry of list) {
100
+ const identity = canonicalizeTodoArtifact(entry);
101
+ if (seen.has(identity)) continue;
102
+ seen.add(identity);
103
+ kept.push({ entry, sortKey: key(entry), index: kept.length });
104
+ }
105
+ return kept.sort((left, right) => compareText(left.sortKey, right.sortKey) || left.index - right.index)
106
+ .map(({ entry }) => entry);
107
+ }
108
+
109
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
110
+
111
+ /**
112
+ * plan_create_input.v5だけ: 並びに作成者の意味が無い集合を、入力順に依らず正準形へ寄せる。
113
+ * tasksと他の配列は並べ替えない。形が壊れていれば触らず、validatorの指摘に任せる。
114
+ */
115
+ function normalizeCreateInputV5(value) {
116
+ const normalizers = {
117
+ hard_dependencies: (list) => sortUnique(list, (edge) => `${refKey(edge?.from)}\0${refKey(edge?.to)}`),
118
+ phase_accept_dependencies: (list) => sortUnique(list,
119
+ (edge) => `${phaseRefKey(edge?.from)}\0${refKey(edge?.to)}`),
120
+ joins: (list) => (Array.isArray(list)
121
+ ? sortUnique(list.map((join) => (isRecord(join)
122
+ ? { ...join, after: sortUnique(join.after, refKey) } : join)), (join) => join?.id) : list),
123
+ phases: (list) => (Array.isArray(list)
124
+ ? sortUnique(list.map((phase) => (isRecord(phase) ? {
125
+ ...phase,
126
+ predecessor_phase_ids: sortUnique(phase.predecessor_phase_ids, (id) => id),
127
+ required_evidence_slots: sortUnique(phase.required_evidence_slots, (id) => id),
128
+ } : phase)), (phase) => phase?.phase_id) : list),
129
+ };
130
+ try {
131
+ const next = { ...value };
132
+ for (const [field, normalize] of Object.entries(normalizers)) {
133
+ if (field in next) next[field] = normalize(next[field]);
134
+ }
135
+ return next;
136
+ } catch {
137
+ return value;
138
+ }
139
+ }
140
+
88
141
  export function repairAuthoringArtifact(value) {
89
142
  if (value === null || typeof value !== 'object' || Array.isArray(value)) return value;
90
143
  const field = AUTHORING_DIGEST_FIELDS[value.schema];
91
144
  if (field === undefined) return value;
92
- const next = { ...value, [field]: typeof value[field] === 'string' ? value[field] : '' };
145
+ const base = value.schema === 'lattice.plan_create_input.v5' ? normalizeCreateInputV5(value) : value;
146
+ const next = { ...base, [field]: typeof base[field] === 'string' ? base[field] : '' };
93
147
  next[field] = todoSelfDigest(next, field);
94
148
  return next;
95
149
  }