@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,7 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { fsyncDirectory as syncDirectory } from './fs-dir-sync.mjs';
3
3
  import { constants as fsConstants } from 'node:fs';
4
- import { lstat, open, readFile, rename, rm, unlink } from 'node:fs/promises';
4
+ import { link, lstat, open, readdir, readFile, rename, rm, unlink } from 'node:fs/promises';
5
5
  import path from 'node:path';
6
6
 
7
7
  import { canonicalizeArtifact } from './artifact-contracts.mjs';
@@ -11,6 +11,9 @@ const SHA256 = /^[0-9a-f]{64}$/;
11
11
  const ID = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/;
12
12
  const TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
13
13
  const LOCK_NAME = '.lifecycle.lock';
14
+ // Pre-u03 binaries wrote after O_EXCL create; their write finishes well inside this window.
15
+ const UNIDENTIFIED_GRACE_MS = 10_000;
16
+ const NO_HARD_LINK = new Set(['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'EXDEV', 'ENOSYS']);
14
17
 
15
18
  export class RuntimeLifecycleLockError extends Error {
16
19
  constructor(code, detail) {
@@ -84,22 +87,59 @@ async function defaultObserver(pid) {
84
87
  return observeManagedProcessStartIdentity(pid);
85
88
  }
86
89
 
90
+ class UnidentifiedLock extends Error {
91
+ constructor(info) { super('unidentified lifecycle lock'); this.info = info; }
92
+ }
93
+
94
+ // nlink 2 is the publisher's window between link() and unlinking its temporary.
87
95
  async function readLockArtifact(lockPath) {
88
96
  const info = await lstat(lockPath);
89
- if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1) {
90
- fail('RUN_LOCK_INVALID', 'lifecycle lockが単一linkのregular fileでない');
97
+ if (!info.isFile() || info.isSymbolicLink()) {
98
+ fail('RUN_LOCK_INVALID', 'lifecycle lockがregular fileでない');
91
99
  }
92
100
  const bytes = await readFile(lockPath);
93
101
  let value;
94
- try { value = JSON.parse(bytes.toString('utf8')); }
95
- catch { fail('RUN_BUSY', 'lifecycle lock取得処理が進行中'); }
96
- if (!validateRuntimeLifecycleLockArtifact(value)) {
97
- fail('RUN_LOCK_INVALID', 'lifecycle lock artifact不正');
102
+ try { value = JSON.parse(bytes.toString('utf8')); } catch { throw new UnidentifiedLock(info); }
103
+ if (validateRuntimeLifecycleLockArtifact(value)
104
+ && bytes.toString('utf8') === `${canonicalizeArtifact(value)}\n`) return { value, info };
105
+ // Another schema may be a newer binary's live owner: identified but unsupported, never aged out.
106
+ if (plain(value) && value.schema !== 'lattice.runtime_lifecycle_lock.v1') {
107
+ fail('RUN_LOCK_INVALID', `未対応のlifecycle lock schema: ${String(value.schema)}`);
98
108
  }
99
- if (bytes.toString('utf8') !== `${canonicalizeArtifact(value)}\n`) {
100
- fail('RUN_LOCK_INVALID', 'lifecycle lockがcanonical bytesでない');
109
+ throw new UnidentifiedLock(info);
110
+ }
111
+
112
+ /** Empty/torn/invalid bytes name no owner; only their age can show the writer is gone. */
113
+ export async function recoverUnidentifiedLock(lockPath, info) {
114
+ if (Date.now() - info.mtimeMs < UNIDENTIFIED_GRACE_MS) return false;
115
+ await removeJudgedEntry(lockPath, info);
116
+ return true;
117
+ }
118
+
119
+ /**
120
+ * Unlink exactly the entry judged by `info` ({dev,ino,size,mtimeMs}); never a newer one.
121
+ * Returns 'removed', 'absent' or 'replaced' (another entry took the path: put back untouched).
122
+ */
123
+ export async function removeJudgedEntry(lockPath, info) {
124
+ const quarantine = path.join(path.dirname(lockPath),
125
+ `.${path.basename(lockPath)}.${process.pid}.${randomUUID()}.stale`);
126
+ try { await rename(lockPath, quarantine); }
127
+ catch (error) { if (error?.code === 'ENOENT') return 'absent'; throw error; }
128
+ const moved = await lstat(quarantine);
129
+ if (moved.dev !== info.dev || moved.ino !== info.ino || moved.size !== info.size
130
+ || moved.mtimeMs !== info.mtimeMs) {
131
+ // Not the entry we judged (release + fresh acquire raced stat→rename): put it back untouched.
132
+ try { await link(quarantine, lockPath); }
133
+ catch (error) {
134
+ if (error?.code === 'EEXIST') fail('RUN_LOCK_INVALID', `回収競合artifactを保全した: ${quarantine}`);
135
+ throw error;
136
+ }
137
+ await unlink(quarantine);
138
+ return 'replaced';
101
139
  }
102
- return { value, info };
140
+ await unlink(quarantine);
141
+ await syncDirectory(path.dirname(lockPath));
142
+ return 'removed';
103
143
  }
104
144
 
105
145
  async function pidExists(pid) {
@@ -137,7 +177,13 @@ async function recoverStaleLock(lockPath, expectedDigest) {
137
177
  throw error;
138
178
  }
139
179
  try {
140
- const moved = await readLockArtifact(quarantine);
180
+ const moved = await readLockArtifact(quarantine).catch((error) => {
181
+ // Anything but the judged owner (torn, other schema) goes back untouched.
182
+ if (error instanceof UnidentifiedLock || error instanceof RuntimeLifecycleLockError) {
183
+ return { value: { lock_digest: null } };
184
+ }
185
+ throw error;
186
+ });
141
187
  if (moved.value.lock_digest !== expectedDigest) {
142
188
  // stale判定後に別ownerが取得したfileをrenameしてしまった場合は破棄しない。
143
189
  try { await rename(quarantine, lockPath); }
@@ -157,29 +203,66 @@ async function recoverStaleLock(lockPath, expectedDigest) {
157
203
  }
158
204
  }
159
205
 
160
- async function createLock(lockPath, artifact) {
206
+ const TEMPORARY = /^(\d+)\.[0-9a-f-]{36}\.tmp$/u;
207
+
208
+ async function removeDeadTemporaries(lockPath) {
209
+ const prefix = `${path.basename(lockPath)}.`;
210
+ let names;
211
+ try { names = await readdir(path.dirname(lockPath)); }
212
+ catch (error) { if (error?.code === 'ENOENT') return; throw error; }
213
+ for (const name of names) {
214
+ const pid = name.startsWith(prefix) ? Number(name.slice(prefix.length).match(TEMPORARY)?.[1]) : NaN;
215
+ if (Number.isSafeInteger(pid) && pid !== process.pid && !await pidExists(pid)) {
216
+ await rm(path.join(path.dirname(lockPath), name), { force: true });
217
+ }
218
+ }
219
+ }
220
+
221
+ /** Pre-u03 publication, kept for filesystems without hard links; L2 recovers its crash window. */
222
+ async function createLockInPlace(lockPath, artifact) {
161
223
  let handle;
162
- let created = false;
163
224
  try {
164
- handle = await open(lockPath,
165
- fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY, 0o600);
166
- created = true;
225
+ handle = await open(lockPath, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY, 0o600);
226
+ } catch (error) {
227
+ if (error?.code === 'EEXIST') return false;
228
+ throw error;
229
+ }
230
+ try {
167
231
  await handle.writeFile(Buffer.from(`${canonicalizeArtifact(artifact)}\n`, 'utf8'));
168
232
  await handle.sync();
169
- await handle.close();
233
+ } catch (error) {
234
+ await handle.close().catch(() => {});
170
235
  handle = null;
236
+ await unlink(lockPath).catch(() => {});
237
+ throw error;
238
+ } finally {
239
+ if (handle) await handle.close();
240
+ }
241
+ await syncDirectory(path.dirname(lockPath));
242
+ return true;
243
+ }
244
+
245
+ /** The shared path only ever receives complete bytes: write a private temporary, then link it. */
246
+ async function createLock(lockPath, artifact, publishLink = link) {
247
+ const temporary = `${lockPath}.${process.pid}.${randomUUID()}.tmp`;
248
+ try {
249
+ const handle = await open(temporary,
250
+ fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY, 0o600);
251
+ try {
252
+ await handle.writeFile(Buffer.from(`${canonicalizeArtifact(artifact)}\n`, 'utf8'));
253
+ await handle.sync();
254
+ } finally { await handle.close(); }
255
+ try { await publishLink(temporary, lockPath); }
256
+ catch (error) {
257
+ if (error?.code === 'EEXIST') return false;
258
+ if (NO_HARD_LINK.has(error?.code)) return createLockInPlace(lockPath, artifact);
259
+ throw error;
260
+ }
261
+ await unlink(temporary);
171
262
  await syncDirectory(path.dirname(lockPath));
172
263
  return true;
173
- } catch (error) {
174
- if (error?.code === 'EEXIST') return false;
175
- if (handle) {
176
- await handle.close().catch(() => {});
177
- handle = null;
178
- }
179
- if (created) await unlink(lockPath).catch(() => {});
180
- throw error;
181
264
  } finally {
182
- if (handle) await handle.close().catch(() => {});
265
+ await rm(temporary, { force: true }).catch(() => {});
183
266
  }
184
267
  }
185
268
 
@@ -202,6 +285,7 @@ export async function acquireRuntimeLifecycleLock({
202
285
  processStartIdentity = null,
203
286
  observeProcessStartIdentity = null,
204
287
  now = () => new Date(),
288
+ publishLink = link, // test seam: filesystems without hard links
205
289
  } = {}) {
206
290
  const resolvedLockPath = validateOptions({ lockPath, runDir, sessionNonceDigest, operation,
207
291
  requestId, timeoutMs, retryIntervalMs, processStartIdentity, observeProcessStartIdentity, now });
@@ -226,9 +310,10 @@ export async function acquireRuntimeLifecycleLock({
226
310
  };
227
311
  artifact.lock_digest = selfDigest(artifact, 'lock_digest');
228
312
  const deadline = Date.now() + timeoutMs;
313
+ await removeDeadTemporaries(resolvedLockPath);
229
314
 
230
315
  while (true) {
231
- if (await createLock(resolvedLockPath, artifact)) {
316
+ if (await createLock(resolvedLockPath, artifact, publishLink)) {
232
317
  let released = false;
233
318
  return {
234
319
  artifact: structuredClone(artifact),
@@ -247,9 +332,11 @@ export async function acquireRuntimeLifecycleLock({
247
332
  try { existing = await readLockArtifact(resolvedLockPath); }
248
333
  catch (error) {
249
334
  if (error?.code === 'ENOENT') continue;
250
- if (error instanceof RuntimeLifecycleLockError && error.code === 'RUN_BUSY'
251
- && Date.now() < deadline) { await sleep(retryIntervalMs); continue; }
252
- throw error;
335
+ if (!(error instanceof UnidentifiedLock)) throw error;
336
+ if (await recoverUnidentifiedLock(resolvedLockPath, error.info)) continue;
337
+ if (Date.now() >= deadline) fail('RUN_BUSY', 'lifecycle lock取得処理が進行中');
338
+ await sleep(Math.min(retryIntervalMs, Math.max(1, deadline - Date.now())));
339
+ continue;
253
340
  }
254
341
  if (!await ownerIsLive(existing.value, observer)) {
255
342
  await recoverStaleLock(resolvedLockPath, existing.value.lock_digest);
@@ -273,6 +360,7 @@ export async function releaseRuntimeLifecycleLock({ lockPath, ownerDigest } = {}
273
360
  try { existing = await readLockArtifact(lockPath); }
274
361
  catch (error) {
275
362
  if (error?.code === 'ENOENT') fail('RUN_LOCK_OWNER_MISMATCH', 'release対象lockなし');
363
+ if (error instanceof UnidentifiedLock) fail('RUN_LOCK_OWNER_MISMATCH', 'lifecycle lock owner digest不一致');
276
364
  throw error;
277
365
  }
278
366
  if (existing.value.lock_digest !== ownerDigest) {
@@ -976,16 +976,16 @@ async function activateManagedSupervisorController({ repoRoot, runDir, runId, ad
976
976
  if (!socketInfo.isSocket()) fail('ADAPTER_CONTROLLER_UNAVAILABLE', 'controller endpointがsocketでない');
977
977
  // exec後にも同じ実行image bytesを再検証する。PID生存も同時に要求する。
978
978
  try { process.kill(child.pid, 0); } catch { fail('ADAPTER_CONTROLLER_UNAVAILABLE', 'controller process不達'); }
979
- let executedImage;
980
- try {
981
- executedImage = await observeProcessExecutablePath(child.pid);
982
- } catch { fail('ADAPTER_BINARY_IDENTITY_MISMATCH', 'exec後image path観測失敗'); }
983
- if (executedImage !== binaryReal || sha256Bytes(await readFile(executedImage)) !== launch.binary_digest) {
984
- fail('ADAPTER_BINARY_IDENTITY_MISMATCH', 'exec後image path/bytes不一致');
985
- }
986
- if (launch.binary_identity !== null
987
- && canonicalizeArtifact(await binaryIdentityObserver(executedImage)) !== canonicalizeArtifact(launch.binary_identity)) {
988
- fail('ADAPTER_BINARY_IDENTITY_MISMATCH', 'exec後macOS identity不一致');
979
+ // u03 C25: 観測できない時はpre-exec検証だけで進む。観測できて食い違う時だけ止める。
980
+ const executedImage = await observeProcessExecutablePath(child.pid).catch(() => null);
981
+ if (executedImage !== null) {
982
+ if (executedImage !== binaryReal || sha256Bytes(await readFile(executedImage)) !== launch.binary_digest) {
983
+ fail('ADAPTER_BINARY_IDENTITY_MISMATCH', 'exec後image path/bytes不一致');
984
+ }
985
+ if (launch.binary_identity !== null
986
+ && canonicalizeArtifact(await binaryIdentityObserver(executedImage)) !== canonicalizeArtifact(launch.binary_identity)) {
987
+ fail('ADAPTER_BINARY_IDENTITY_MISMATCH', 'exec後macOS identity不一致');
988
+ }
989
989
  }
990
990
  } else {
991
991
  if (!path.isAbsolute(handshakeSocket) || await realpath(path.dirname(handshakeSocket)) !== path.dirname(handshakeSocket)) {
@@ -562,13 +562,13 @@ function packetFor({ meta, taskId, baseSha, manifest }) {
562
562
  return packet;
563
563
  }
564
564
 
565
- async function acquirePullLock(runDir, operation, requestId) {
565
+ async function acquirePullLock(runDir, operation, requestId, timeoutMs = 0) {
566
566
  return acquireRuntimeLifecycleLock({
567
567
  lockPath: path.join(runDir, '.pull-intake.lock'),
568
568
  sessionNonceDigest: digestArtifact({ run_dir: runDir, schema: PULL_RUN_META_SCHEMA }),
569
569
  operation,
570
570
  requestId,
571
- timeoutMs: 0,
571
+ timeoutMs,
572
572
  });
573
573
  }
574
574
 
@@ -582,54 +582,94 @@ async function acquireStartBindingLock(repoRoot, operation) {
582
582
  });
583
583
  }
584
584
 
585
- async function activePullIntakesForStart(repoRoot, { planKey, taskId, activationEventDigest }) {
585
+ function boundIntake(state, { planKey, taskId, activationEventDigest }) {
586
+ if (state.closed || state.plan_key !== planKey) return undefined;
587
+ return state.intakes.find((candidate) => candidate.task_id === taskId
588
+ && candidate.activation_event_digest === activationEventDigest
589
+ && candidate.accepted === null);
590
+ }
591
+
592
+ /** Only readable open pull runs can hold an intake; anything else under runs/ is skipped (u03 X1). */
593
+ async function pullRunsBoundToStart(repoRoot, binding) {
586
594
  const root = path.join(repoRoot, '.lattice', 'runs');
587
- let entries;
588
- try { entries = await readdir(root, { withFileTypes: true }); }
589
- catch (error) {
590
- if (error?.code === 'ENOENT') return [];
591
- fail('INVALID_RUN_STORE', 'run store一覧を読めない');
592
- }
593
- const active = [];
595
+ const entries = await readdir(root, { withFileTypes: true }).catch(() => []);
596
+ const bound = [];
597
+ const unreadable = [];
594
598
  for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
595
- if (!entry.isDirectory() || !identifier(entry.name)) {
596
- fail('INVALID_RUN_STORE', `不正なrun store entry: ${entry.name}`);
597
- }
599
+ if (!entry.isDirectory() || !identifier(entry.name)) continue;
598
600
  const runDir = path.join(root, entry.name);
599
- const mode = await inspectRunMode(runDir);
600
- if (mode.mode !== 'pull') continue;
601
- const stored = await readPullStore(runDir);
602
- const state = project(stored.events, stored.meta);
603
- if (state.closed || state.plan_key !== planKey) continue;
604
- const intake = state.intakes.find((candidate) => candidate.task_id === taskId
605
- && candidate.activation_event_digest === activationEventDigest
606
- && candidate.accepted === null);
607
- if (intake !== undefined) active.push({
608
- run_id: state.run_id,
609
- run_ref: `.lattice/runs/${entry.name}`,
610
- activation_event_digest: intake.activation_event_digest,
611
- });
601
+ try {
602
+ if ((await inspectRunMode(runDir)).mode !== 'pull') continue;
603
+ const stored = await readPullStore(runDir);
604
+ if (boundIntake(project(stored.events, stored.meta), binding) !== undefined) bound.push(runDir);
605
+ } catch { unreadable.push(`.lattice/runs/${entry.name}`); }
606
+ }
607
+ // An unreadable run may still hold an intake for this start: make the leftover visible.
608
+ if (unreadable.length > 0) {
609
+ process.emitWarning(`start撤回で読めないrunを飛ばした: ${unreadable.join(', ')}`,
610
+ { code: 'LATTICE_RETRACT_RUNS_SKIPPED' });
611
+ }
612
+ return bound;
613
+ }
614
+
615
+ /**
616
+ * Detach (resuming a stopped worker first) and release one unaccepted intake under the
617
+ * caller's pull lock, recording each step. A worker that cannot be re-authenticated is
618
+ * not signalled (u03 C25) and the record says so.
619
+ */
620
+ async function releaseIntakeRecorded(runDir, current, intake, actor, reason, detail = {}) {
621
+ if (intake.worker !== null) {
622
+ let resumed = false;
623
+ let signal = intake.worker.stopped ? 'sent' : 'not_needed';
624
+ if (intake.worker.stopped) {
625
+ try { resumed = await signalAttachedWorker(intake, 'SIGCONT'); }
626
+ catch { signal = 'unavailable'; }
627
+ if (signal === 'sent' && !resumed) signal = 'worker_gone';
628
+ }
629
+ if (resumed) {
630
+ current = await appendEvent(runDir, current, buildEvent({
631
+ events: current.events, meta: current.meta, kind: 'worker_resumed', taskId: intake.task_id,
632
+ payload: { released_by: reason },
633
+ }));
634
+ }
635
+ current = await appendEvent(runDir, current, buildEvent({
636
+ events: current.events, meta: current.meta, kind: 'worker_detached', taskId: intake.task_id,
637
+ payload: { detached_by: actor, pid: intake.worker.pid, resumed, reason, signal },
638
+ }));
612
639
  }
613
- return active;
640
+ return appendEvent(runDir, current, buildEvent({
641
+ events: current.events, meta: current.meta, kind: 'intake_released', taskId: intake.task_id,
642
+ payload: { released_by: actor, reason, ...detail },
643
+ }));
614
644
  }
615
645
 
646
+ /**
647
+ * Retracting a start releases every unaccepted intake bound to it and records that (u03 C11).
648
+ * Release happens before Plan's event, so a failed append leaves a start that can be intaken again.
649
+ */
616
650
  export async function withStartRetractionGuard({
617
- repoRoot, planKey, taskId, activationEventDigest, action,
651
+ repoRoot, planKey, taskId, activationEventDigest, action, environment = process.env,
618
652
  }) {
619
653
  if (!identifier(planKey) || !identifier(taskId) || !sha256(activationEventDigest)
620
654
  || typeof action !== 'function') {
621
655
  fail('INVALID_START_RETRACTION', 'start retraction guard入力が不正');
622
656
  }
657
+ const binding = { planKey, taskId, activationEventDigest };
658
+ const actor = optionalActorFromEnvironment(environment);
623
659
  const lock = await acquireStartBindingLock(repoRoot, 'start-retract');
624
660
  try {
625
- const active = await activePullIntakesForStart(repoRoot, {
626
- planKey, taskId, activationEventDigest,
627
- });
628
- if (active.length > 0) {
629
- fail('ACTIVE_PULL_INTAKE', 'active intakeをreleaseしてからstartを撤回すること', {
630
- plan_key: planKey, task_id: taskId, active_intakes: active,
631
- next_action: 'lattice run intake release --run <run_ref> --task <task_id>',
632
- });
661
+ for (const runDir of await pullRunsBoundToStart(repoRoot, binding)) {
662
+ // intake takes pull then binding lock with zero wait, so waiting here cannot deadlock.
663
+ const runLock = await acquirePullLock(runDir, 'retract-release', `retract-${randomUUID()}`, 5000);
664
+ try {
665
+ const current = await readPullStore(runDir);
666
+ const intake = boundIntake(project(current.events, current.meta), binding);
667
+ if (intake !== undefined) {
668
+ await releaseIntakeRecorded(runDir, current, intake, actor, 'start_retracted', {
669
+ target_start_digest: activationEventDigest,
670
+ });
671
+ }
672
+ } finally { await runLock.release(); }
633
673
  }
634
674
  return await action();
635
675
  } finally { await lock.release(); }
@@ -1426,7 +1466,7 @@ export async function landingPullRun({ repoRoot, runDir }) {
1426
1466
  output.result_digest = digestArtifact(output); return output;
1427
1467
  }
1428
1468
 
1429
- export async function closePullRun({ repoRoot, runDir }) {
1469
+ export async function closePullRun({ repoRoot, runDir, environment = process.env }) {
1430
1470
  const lock = await acquirePullLock(runDir, 'close', `close-${randomUUID()}`);
1431
1471
  try {
1432
1472
  let current = await readPullStore(runDir);
@@ -1437,18 +1477,22 @@ export async function closePullRun({ repoRoot, runDir }) {
1437
1477
  landing: await landingPullRun({ repoRoot, runDir }) };
1438
1478
  output.result_digest = digestArtifact(output); return output;
1439
1479
  }
1480
+ // u03 C18: close releases what is still open and records it instead of refusing.
1440
1481
  const incomplete = state.intakes.filter((entry) => entry.accepted === null);
1441
- if (incomplete.length > 0) {
1442
- fail('RUN_NOT_COMPLETE', 'pending/hold中intakeが残っている', {
1443
- task_ids: incomplete.map((entry) => entry.task_id),
1444
- });
1482
+ const actor = optionalActorFromEnvironment(environment);
1483
+ for (const intake of incomplete) {
1484
+ current = await releaseIntakeRecorded(runDir, current, intake, actor, 'run_closed');
1445
1485
  }
1486
+ const releasedTaskIds = incomplete.map((entry) => entry.task_id).sort();
1487
+ const payload = { accepted_task_ids: state.intakes.filter((entry) => entry.accepted !== null)
1488
+ .map((entry) => entry.task_id).sort() };
1489
+ if (releasedTaskIds.length > 0) payload.released_task_ids = releasedTaskIds;
1446
1490
  current = await appendEvent(runDir, current, buildEvent({
1447
- events: current.events, meta: current.meta, kind: 'run_closed',
1448
- payload: { accepted_task_ids: state.intakes.map((entry) => entry.task_id).sort() },
1491
+ events: current.events, meta: current.meta, kind: 'run_closed', payload,
1449
1492
  }));
1450
1493
  const output = { schema: 'lattice.pull_run_close_result.v1', outcome: 'closed',
1451
1494
  run_id: state.run_id, already_closed: false, intake_count: state.intakes.length,
1495
+ released_task_ids: releasedTaskIds,
1452
1496
  landing: await landingPullRun({ repoRoot, runDir }) };
1453
1497
  output.result_digest = digestArtifact(output); return output;
1454
1498
  } finally { await lock.release(); }