@quolu/lattice 0.81.0 → 0.82.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.
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * Windows bridge supervisor (bh6 prep). Startup-folder items only run once at
3
+ * Windows/Linux bridge supervisor (bh6 prep). Startup-folder items only run once at
4
4
  * logon — nothing like launchd's KeepAlive exists to restart a crashed
5
5
  * process. This script is that supervision, written in JS instead of a batch
6
6
  * GOTO loop because a loop's own process (and therefore its killability) is
@@ -10,7 +10,8 @@
10
10
  * The descriptor supplies the environment `lattice-bridge.mjs` needs (it is
11
11
  * never inherited from the Startup-folder launch context) and the path to
12
12
  * write this supervisor's own pid to, so `bridge-startup-folder.mjs` can find
13
- * and stop the whole tree later via `taskkill /T /F`.
13
+ * and stop the whole tree later via `taskkill /T /F`. Linux records process
14
+ * birth alongside the PID so its detached adapter can reject PID reuse.
14
15
  */
15
16
 
16
17
  import { spawn } from 'node:child_process';
@@ -18,6 +19,8 @@ import { writeFile } from 'node:fs/promises';
18
19
  import { readFileSync } from 'node:fs';
19
20
  import path from 'node:path';
20
21
 
22
+ import { observeDashboardProcess } from '../src/dashboard-process-control.mjs';
23
+
21
24
  const RESTART_DELAY_MS = 3_000;
22
25
 
23
26
  const descriptorPath = process.argv[2];
@@ -33,7 +36,9 @@ if (descriptor?.schema !== 'lattice.bridge_supervisor_descriptor.v1'
33
36
  process.exit(2);
34
37
  }
35
38
 
36
- await writeFile(descriptor.pidPath, String(process.pid), { encoding: 'utf8', flag: 'w' });
39
+ const identity = process.platform === 'win32' ? String(process.pid)
40
+ : JSON.stringify(await observeDashboardProcess(process.pid) ?? { pid: process.pid, birth: null });
41
+ await writeFile(descriptor.pidPath, identity, { encoding: 'utf8', flag: 'w', mode: 0o600 });
37
42
 
38
43
  let stopping = false;
39
44
  let child = null;
package/bin/lattice.mjs CHANGED
@@ -112,6 +112,34 @@ if (help !== null) {
112
112
  } catch (error) {
113
113
  process.exitCode = projectCliFailure(process.stderr, error);
114
114
  }
115
+ } else if (args.length === 4 && args[0] === 'plan' && args[1] === 'revise'
116
+ && args[2] === '--schema' && args[3] === '--json') {
117
+ const { planReviseSchema } = await import('../src/plan-revise.mjs');
118
+ const { projectCliFailure } = await import('../src/project-cli.mjs');
119
+ try {
120
+ process.stdout.write(`${JSON.stringify(await planReviseSchema())}\n`);
121
+ process.exitCode = 0;
122
+ } catch (error) {
123
+ process.exitCode = projectCliFailure(process.stderr, error);
124
+ }
125
+ } else if (args[0] === 'plan' && args[1] === 'revise') {
126
+ const { matchFlagCommand } = await import('../src/todo-authoring-input.mjs');
127
+ const flags = matchFlagCommand(args, ['plan', 'revise'], {
128
+ known: ['input', 'dry-run', 'json'], required: ['input'], booleans: ['dry-run', 'json'],
129
+ });
130
+ if (flags === null || flags.json !== true) {
131
+ process.stderr.write(`lattice: unsupported command or arguments: ${args.join(' ')}\n`);
132
+ process.exitCode = 2;
133
+ } else {
134
+ const { runPlanRevise } = await import('../src/plan-revise.mjs');
135
+ const { projectCliFailure } = await import('../src/project-cli.mjs');
136
+ try {
137
+ process.exitCode = await runPlanRevise({ cwd: process.cwd(), inputRef: flags.input,
138
+ dryRun: flags['dry-run'] === true, stdout: process.stdout, env: process.env });
139
+ } catch (error) {
140
+ process.exitCode = projectCliFailure(process.stderr, error);
141
+ }
142
+ }
115
143
  } else if (args.length === 4 && args[0] === 'plan' && args[1] === 'backchain'
116
144
  && args[2] === '--schema' && args[3] === '--json') {
117
145
  const { backchainSchema } = await import('../src/plan-backchain.mjs');
@@ -0,0 +1,32 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://github.com/kitepon/Lattice/blob/main/docs/schemas/lattice.plan_revise_input.v1.schema.json",
4
+ "title": "lattice.plan_revise_input.v1",
5
+ "description": "工程全体のdesired stateと、全ての旧taskの明示的な状態移行。predecessor/CAS/digest/後継versionは機械が算出する。旧版は保持し、作業の意味が同じかを暗黙に推定しない。",
6
+ "type": "object",
7
+ "additionalProperties": false,
8
+ "required": ["schema", "desired", "continuity"],
9
+ "properties": {
10
+ "schema": { "const": "lattice.plan_revise_input.v1" },
11
+ "desired": {
12
+ "$ref": "lattice.plan_create_input.v4.schema.json",
13
+ "description": "同じproject_idとplan_keyのcreate-v4入力。input_digestは通常のauthoring正規化で補う。plan_versionは入力形を保つために記載し、後継versionは機械算出値に置き換える。新taskはpending。消すtaskへの参照も明示的に取り除く。"
14
+ },
15
+ "continuity": {
16
+ "type": "array",
17
+ "minItems": 1,
18
+ "maxItems": 512,
19
+ "description": "旧task全件をtask_idごとに一度ずつ選ぶ。新taskへのentryは書かない。配列の順序は問わない。carryは既存Storeの意味・依存整合チェックを保ち、resetはpendingへ戻し、retireはdesiredに存在しないtaskだけに使う。各判断の理由をreasonに記録する。",
20
+ "items": {
21
+ "type": "object",
22
+ "additionalProperties": false,
23
+ "required": ["task_id", "policy", "reason"],
24
+ "properties": {
25
+ "task_id": { "type": "string", "pattern": "^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$" },
26
+ "policy": { "enum": ["carry", "reset", "retire"] },
27
+ "reason": { "type": "string", "minLength": 1, "pattern": "\\S" }
28
+ }
29
+ }
30
+ }
31
+ }
32
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quolu/lattice",
3
- "version": "0.81.0",
3
+ "version": "0.82.0",
4
4
  "description": "Schedulability compiler for multi-agent development: observe real code boundaries, refactor the conflicting seam, recompile the plan for parallel execution",
5
5
  "author": {
6
6
  "name": "Quo / クオ at kitepon.dev",
@@ -29,6 +29,7 @@
29
29
  "docs/schemas/lattice.plan_create_input.v2.schema.json",
30
30
  "docs/schemas/lattice.plan_create_input.v3.schema.json",
31
31
  "docs/schemas/lattice.plan_create_input.v4.schema.json",
32
+ "docs/schemas/lattice.plan_revise_input.v1.schema.json",
32
33
  "docs/schemas/lattice.plan_scope_review.v1.schema.json",
33
34
  "docs/schemas/lattice.plan_backchain.v1.schema.json",
34
35
  "docs/schemas/lattice.todo_revision.v2.schema.json",
@@ -84,7 +85,7 @@
84
85
  "test:profile": "npm --prefix sensor ci && npm --prefix sensor run build && node scripts/run-product-tests.mjs",
85
86
  "test:sensor": "npm --prefix sensor test",
86
87
  "check": "node scripts/check-syntax.mjs",
87
- "ci": "npm run check:docs && npm run test && npm run test:sensor && npm run check && npm run check:cli-surface && npm run check:open-questions && npm run check:reachability && npm run verify:todo-store",
88
+ "ci": "node scripts/run-ci.mjs",
88
89
  "verify:todo-store": "node bin/lattice.mjs todo verify --json",
89
90
  "check:cli-surface": "node scripts/verify-cli-surface.mjs",
90
91
  "check:open-questions": "node scripts/verify-open-questions.mjs",
@@ -26,6 +26,10 @@ import {
26
26
  describeBridgeStartupFolder, disableBridgeStartupFolder, installBridgeStartupFolder,
27
27
  restoreBridgeStartupFolder, snapshotBridgeStartupFolder,
28
28
  } from './bridge-startup-folder.mjs';
29
+ import {
30
+ describeBridgeDetachedSupervisor, disableBridgeDetachedSupervisor, installBridgeDetachedSupervisor,
31
+ restoreBridgeDetachedSupervisor, snapshotBridgeDetachedSupervisor,
32
+ } from './bridge-detached-supervisor.mjs';
29
33
 
30
34
  // v2 adds the liveness fields. `enabled` only says the configuration is on;
31
35
  // it never said the bridge could actually be reached, which let a DHCP lease
@@ -86,16 +90,24 @@ async function bridgeLiveness(config, { interfaces = networkInterfaces(), probe
86
90
  // what lets `lattice bridge setup` on Windows persist via the Startup folder
87
91
  // exactly the way it persists via a LaunchAgent on macOS, with no separate
88
92
  // command or manual step (see bridge-startup-folder.mjs's module doc for why
89
- // Task Scheduler's ONLOGON trigger could not be used instead).
93
+ // Task Scheduler's ONLOGON trigger could not be used instead). Every other OS
94
+ // (Linux seats in containers) gets the detached supervisor: the adapter is the
95
+ // only code that touches its OS tool, so `dashboard ensure` on Linux never
96
+ // probes launchctl (docs/architecture/dfd-bridge-persistence.md).
90
97
  function platformLaunchAgent() {
91
98
  if (process.platform === 'win32') {
92
99
  return { snapshot: snapshotBridgeStartupFolder, install: installBridgeStartupFolder,
93
100
  disable: disableBridgeStartupFolder, restore: restoreBridgeStartupFolder,
94
101
  describe: describeBridgeStartupFolder };
95
102
  }
96
- return { snapshot: snapshotBridgeLaunchAgent, install: installBridgeLaunchAgent,
97
- disable: disableBridgeLaunchAgent, restore: restoreBridgeLaunchAgent,
98
- describe: describeBridgeLaunchAgent };
103
+ if (process.platform === 'darwin') {
104
+ return { snapshot: snapshotBridgeLaunchAgent, install: installBridgeLaunchAgent,
105
+ disable: disableBridgeLaunchAgent, restore: restoreBridgeLaunchAgent,
106
+ describe: describeBridgeLaunchAgent };
107
+ }
108
+ return { snapshot: snapshotBridgeDetachedSupervisor, install: installBridgeDetachedSupervisor,
109
+ disable: disableBridgeDetachedSupervisor, restore: restoreBridgeDetachedSupervisor,
110
+ describe: describeBridgeDetachedSupervisor };
99
111
  }
100
112
 
101
113
  const UNREADABLE_PERSISTENCE = Object.freeze({ loaded: null, node_path: null, node_exists: false,
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Bridge persistence for Linux and any other OS without launchd or a Startup
3
+ * folder: the third adapter behind `bridge-cli.mjs`'s `platformLaunchAgent`,
4
+ * with the same contract (`snapshot`/`describe`/`install`/`disable`/`restore`)
5
+ * as `bridge-launch-agent.mjs` (macOS) and `bridge-startup-folder.mjs`
6
+ * (Windows). State is a supervisor descriptor plus pidfile under
7
+ * `<seat root>/bridge-linux/`; `install` spawns `bin/lattice-bridge-supervisor.mjs`
8
+ * detached, and that supervisor restarts a crashed bridge. Nothing here runs
9
+ * another OS's tool, so `lattice todo dashboard ensure` on a Linux seat no
10
+ * longer probes `/bin/launchctl` inside delivery recovery.
11
+ *
12
+ * shortcut: no boot/login persistence on Linux (a BellTeam seat is a container
13
+ * whose setup re-runs `bridge reconfigure` after restart), upgrade to a
14
+ * `systemd --user` unit when a seat runs on a host with a user session manager.
15
+ * Flow: docs/architecture/dfd-bridge-persistence.md.
16
+ */
17
+
18
+ import { spawn } from 'node:child_process';
19
+ import { randomBytes } from 'node:crypto';
20
+ import { mkdir, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
21
+ import path from 'node:path';
22
+
23
+ import { BridgeConfigError, bridgeConfigPaths } from './bridge-config.mjs';
24
+ import { DEFAULT_BRIDGE_PATH, DEFAULT_SUPERVISOR_PATH } from './bridge-executable.mjs';
25
+ import { observeDashboardProcess } from './dashboard-process-control.mjs';
26
+ import { supervisorDescriptor, waitForBridgeStartupReady } from './bridge-startup-folder.mjs';
27
+
28
+ const START_FAILED = 'BRIDGE_DETACHED_SUPERVISOR_START_FAILED';
29
+ const STOP_TIMEOUT_MS = 10_000;
30
+ const SOCKET_TIMEOUT_MS = 3_000;
31
+
32
+ function fail(code, message, cause = undefined) {
33
+ return new BridgeConfigError(code, message, undefined, cause);
34
+ }
35
+
36
+ export function bridgeDetachedSupervisorPaths(env = process.env) {
37
+ const directory = path.join(bridgeConfigPaths(env).root, 'bridge-linux');
38
+ return Object.freeze({
39
+ directory,
40
+ descriptor: path.join(directory, 'descriptor.json'),
41
+ pidfile: path.join(directory, 'supervisor.pid'),
42
+ });
43
+ }
44
+
45
+ async function optionalFile(ref) {
46
+ try { return await readFile(ref, 'utf8'); } catch (error) {
47
+ if (error?.code === 'ENOENT') return null;
48
+ throw error;
49
+ }
50
+ }
51
+
52
+ async function atomicFile(ref, content) {
53
+ const temporary = `${ref}.${process.pid}.${randomBytes(8).toString('hex')}.tmp`;
54
+ try {
55
+ await writeFile(temporary, content, { encoding: 'utf8', flag: 'wx', mode: 0o600 });
56
+ await rename(temporary, ref);
57
+ } finally {
58
+ await rm(temporary, { force: true });
59
+ }
60
+ }
61
+
62
+ async function present(ref) {
63
+ if (typeof ref !== 'string') return false;
64
+ try { await stat(ref); return true; } catch { return false; }
65
+ }
66
+
67
+ async function executablePath(ref, label) {
68
+ if (typeof ref !== 'string' || !path.isAbsolute(ref)) {
69
+ throw fail('BRIDGE_DETACHED_SUPERVISOR_EXECUTABLE_INVALID', `${label} path must be absolute`);
70
+ }
71
+ try {
72
+ const resolved = await realpath(ref);
73
+ if (!(await stat(resolved)).isFile()) throw new Error('not a file');
74
+ return resolved;
75
+ } catch (error) {
76
+ throw fail('BRIDGE_DETACHED_SUPERVISOR_EXECUTABLE_INVALID', `${label} is unavailable`, error);
77
+ }
78
+ }
79
+
80
+ function healthHost(address) {
81
+ if (address === '0.0.0.0') return '127.0.0.1';
82
+ if (address === '::') return '[::1]';
83
+ return address.includes(':') ? `[${address}]` : address;
84
+ }
85
+
86
+ /** The old bridge must have released its socket before the new one binds it. */
87
+ async function defaultWaitStopped({ listen, timeoutMs = SOCKET_TIMEOUT_MS }) {
88
+ if (!listen) return;
89
+ const deadline = Date.now() + timeoutMs;
90
+ while (Date.now() < deadline) {
91
+ try {
92
+ await fetch(`http://${healthHost(listen.address)}:${listen.port}/__lattice/bridge-health`,
93
+ { signal: AbortSignal.timeout(300) });
94
+ } catch { return; }
95
+ await new Promise((resolve) => setTimeout(resolve, 50));
96
+ }
97
+ throw fail('BRIDGE_DETACHED_SUPERVISOR_STOP_FAILED', 'bridge socket did not stop');
98
+ }
99
+
100
+ async function stopRunning({ refs, listen, waitStopped, observeProcess = observeDashboardProcess }) {
101
+ // shortcut: live numeric-only supervisors require owner-authenticated retirement before upgrading.
102
+ const content = await optionalFile(refs.pidfile);
103
+ let identity;
104
+ let stopped = false;
105
+ try { identity = JSON.parse(content); } catch {}
106
+ if (Number.isSafeInteger(identity?.pid) && identity.pid > 0
107
+ && typeof identity.birth === 'string' && identity.birth.length > 0) {
108
+ const observe = async () => {
109
+ try { return await observeProcess(identity.pid); }
110
+ catch { return { pid: identity.pid, birth: null }; }
111
+ };
112
+ if ((await observe())?.birth === identity.birth) {
113
+ try { process.kill(identity.pid, 'SIGTERM'); } catch (error) {
114
+ if (error?.code !== 'ESRCH') throw error;
115
+ }
116
+ const deadline = Date.now() + STOP_TIMEOUT_MS;
117
+ let observed = await observe();
118
+ while (observed?.birth === identity.birth && Date.now() < deadline) {
119
+ await new Promise((resolve) => setTimeout(resolve, 50));
120
+ observed = await observe();
121
+ }
122
+ if (observed?.birth === identity.birth) {
123
+ throw fail('BRIDGE_DETACHED_SUPERVISOR_STOP_FAILED', 'bridge supervisor did not stop');
124
+ }
125
+ stopped = observed === null || (typeof observed?.birth === 'string' && observed.birth.length > 0);
126
+ if (stopped) await waitStopped({ listen });
127
+ }
128
+ }
129
+ await rm(refs.pidfile, { force: true });
130
+ return stopped;
131
+ }
132
+
133
+ export function defaultDetachedLaunch({ nodePath, supervisorPath, descriptorPath, env }) {
134
+ const child = spawn(nodePath, [supervisorPath, descriptorPath], { env, detached: true, stdio: 'ignore' });
135
+ child.unref();
136
+ }
137
+
138
+ export async function snapshotBridgeDetachedSupervisor({ env = process.env } = {}) {
139
+ const refs = bridgeDetachedSupervisorPaths(env);
140
+ await mkdir(refs.directory, { recursive: true, mode: 0o700 });
141
+ const descriptorContent = await optionalFile(refs.descriptor);
142
+ return Object.freeze({ installed: descriptorContent !== null, split: false,
143
+ launcherContent: null, descriptorContent });
144
+ }
145
+
146
+ export async function describeBridgeDetachedSupervisor({ snapshot } = {}) {
147
+ if (snapshot?.installed !== true) return null;
148
+ const descriptor = JSON.parse(snapshot.descriptorContent);
149
+ const nodePath = typeof descriptor.nodePath === 'string' ? descriptor.nodePath : null;
150
+ return { node_path: nodePath, node_exists: await present(nodePath),
151
+ bridge_path: descriptor.bridgePath, bridge_exists: await present(descriptor.bridgePath) };
152
+ }
153
+
154
+ export async function installBridgeDetachedSupervisor({ config, env = process.env,
155
+ nodePath = process.execPath, bridgePath = DEFAULT_BRIDGE_PATH, supervisorPath = DEFAULT_SUPERVISOR_PATH,
156
+ launch = defaultDetachedLaunch, waitReady = waitForBridgeStartupReady,
157
+ waitStopped = defaultWaitStopped, previousListen = null } = {}) {
158
+ if (config?.enabled !== true) throw fail('BRIDGE_DISABLED', 'bridge is disabled');
159
+ const refs = bridgeDetachedSupervisorPaths(env);
160
+ await mkdir(refs.directory, { recursive: true, mode: 0o700 });
161
+ const resolvedNode = await executablePath(nodePath, 'node executable');
162
+ const resolvedBridge = await executablePath(bridgePath, 'bridge executable');
163
+ const resolvedSupervisor = await executablePath(supervisorPath, 'supervisor executable');
164
+ const instanceToken = randomBytes(32).toString('hex');
165
+ const descriptorContent = supervisorDescriptor({
166
+ bridgePath: resolvedBridge, pidfile: refs.pidfile, instanceToken, env, nodePath: resolvedNode,
167
+ });
168
+ await stopRunning({ refs, listen: previousListen, waitStopped });
169
+ await atomicFile(refs.descriptor, descriptorContent);
170
+ await launch({ nodePath: resolvedNode, supervisorPath: resolvedSupervisor, descriptorPath: refs.descriptor, env });
171
+ return waitReady({ config, instanceToken, env, failureCode: START_FAILED });
172
+ }
173
+
174
+ export async function disableBridgeDetachedSupervisor({ snapshot, listen, env = process.env,
175
+ waitStopped = defaultWaitStopped, observeProcess = observeDashboardProcess } = {}) {
176
+ if (!snapshot || typeof snapshot.installed !== 'boolean') {
177
+ throw new TypeError('bridge detached supervisor snapshot required');
178
+ }
179
+ const refs = bridgeDetachedSupervisorPaths(env);
180
+ const stopped = snapshot.installed ? await stopRunning({ refs, listen, waitStopped, observeProcess }) : false;
181
+ await rm(refs.descriptor, { force: true });
182
+ await rm(refs.pidfile, { force: true });
183
+ return { removed: snapshot.installed, stopped };
184
+ }
185
+
186
+ export async function restoreBridgeDetachedSupervisor({ snapshot, listen = null, env = process.env,
187
+ launch = defaultDetachedLaunch, waitStopped = defaultWaitStopped, config = undefined,
188
+ supervisorPath = DEFAULT_SUPERVISOR_PATH, waitReady = waitForBridgeStartupReady } = {}) {
189
+ if (!snapshot || typeof snapshot.installed !== 'boolean'
190
+ || (snapshot.installed && typeof snapshot.descriptorContent !== 'string')) {
191
+ throw new TypeError('bridge detached supervisor snapshot required');
192
+ }
193
+ const refs = bridgeDetachedSupervisorPaths(env);
194
+ await mkdir(refs.directory, { recursive: true, mode: 0o700 });
195
+ await stopRunning({ refs, listen, waitStopped });
196
+ if (!snapshot.installed) return;
197
+ await atomicFile(refs.descriptor, snapshot.descriptorContent);
198
+ const descriptor = JSON.parse(snapshot.descriptorContent);
199
+ await launch({ nodePath: descriptor.nodePath ?? process.execPath, supervisorPath, descriptorPath: refs.descriptor, env });
200
+ if (config !== undefined) {
201
+ await waitReady({ config, instanceToken: descriptor.env?.LATTICE_BRIDGE_INSTANCE_TOKEN, env,
202
+ failureCode: 'BRIDGE_DETACHED_SUPERVISOR_ROLLBACK_FAILED' });
203
+ }
204
+ }
@@ -161,7 +161,8 @@ function launcherScript({ nodePath, supervisorPath, descriptorPath }) {
161
161
  return `Set shell = CreateObject("WScript.Shell")\r\nshell.Run ${command}, 0, False\r\n`;
162
162
  }
163
163
 
164
- function supervisorDescriptor({ bridgePath, pidfile, instanceToken, env }) {
164
+ /** Shared with `bridge-detached-supervisor.mjs`; `nodePath` is recorded only where no launcher file holds it. */
165
+ export function supervisorDescriptor({ bridgePath, pidfile, instanceToken, env, nodePath = undefined }) {
165
166
  const forwarded = { LATTICE_BRIDGE_INSTANCE_TOKEN: instanceToken };
166
167
  if (env.LATTICE_CONFIG_DIR !== undefined) {
167
168
  if (typeof env.LATTICE_CONFIG_DIR !== 'string' || !path.isAbsolute(env.LATTICE_CONFIG_DIR)) {
@@ -177,7 +178,8 @@ function supervisorDescriptor({ bridgePath, pidfile, instanceToken, env }) {
177
178
  forwarded.LATTICE_BRIDGE_REGISTRAR_SSH_HOST = registrar.host;
178
179
  forwarded.LATTICE_BRIDGE_REGISTRAR_SCRIPT = registrar.script;
179
180
  }
180
- return JSON.stringify({ schema: DESCRIPTOR_SCHEMA, bridgePath, pidPath: pidfile, env: forwarded });
181
+ return JSON.stringify({ schema: DESCRIPTOR_SCHEMA, bridgePath, pidPath: pidfile, env: forwarded,
182
+ ...(nodePath === undefined ? {} : { nodePath }) });
181
183
  }
182
184
 
183
185
  export async function defaultStartupRunner(args) {
@@ -198,7 +200,8 @@ function healthHost(address) {
198
200
  return address.includes(':') ? `[${address}]` : address;
199
201
  }
200
202
 
201
- export async function waitForBridgeStartupReady({ config, instanceToken, env, timeoutMs = START_TIMEOUT_MS }) {
203
+ export async function waitForBridgeStartupReady({ config, instanceToken, env, timeoutMs = START_TIMEOUT_MS,
204
+ failureCode = 'BRIDGE_STARTUP_FOLDER_START_FAILED' }) {
202
205
  const deadline = Date.now() + timeoutMs;
203
206
  while (Date.now() < deadline) {
204
207
  const descriptor = await readBridgeDaemonDescriptor({ env });
@@ -217,7 +220,7 @@ export async function waitForBridgeStartupReady({ config, instanceToken, env, ti
217
220
  }
218
221
  await new Promise((resolve) => setTimeout(resolve, 50));
219
222
  }
220
- throw fail('BRIDGE_STARTUP_FOLDER_START_FAILED', 'bridge startup process did not become healthy');
223
+ throw fail(failureCode, 'bridge startup process did not become healthy');
221
224
  }
222
225
 
223
226
  async function defaultWaitStopped({ listen, timeoutMs = STOP_TIMEOUT_MS }) {
package/src/cli-help.mjs CHANGED
@@ -30,6 +30,8 @@ Commands:
30
30
  create --schema --json # 既定は最新版(v4)のJSON Schemaを返す
31
31
  create --schema-version <1|2|3|4> --json
32
32
  backchain --schema --json # 最終成果から必要な機能を逆算する入力契約
33
+ revise --input <file> [--dry-run] --json # 工程の全体と明示した状態移行から改訂する
34
+ revise --schema --json
33
35
  backchain --input <file> [--dry-run] --json
34
36
  # 各工程の必要・提供機能を照合し、初回又は既存storeへのplan登録まで行う
35
37
  show <plan_key> --json # task・依存・phase・状態をplan本体から1コマンドで投影する
@@ -235,6 +237,7 @@ const SUBCOMMAND_USAGE = Object.freeze({
235
237
  'plan show': 'plan show <plan_key> --json',
236
238
  'plan scope-review': 'plan scope-review --plan-input <plan-create-or-extraction.json> --review <scope-review.json> --json | --schema --json',
237
239
  'plan backchain': 'plan backchain --input <file> [--dry-run] --json | --schema --json',
240
+ 'plan revise': 'plan revise --input <file> [--dry-run] --json | --schema --json',
238
241
  'plan compile': 'plan compile --request <request.json> | --schema --json',
239
242
  'plan verify': 'plan verify --request <request.json> --plan <plan.json>',
240
243
  'run start': 'run start --request <request.json> --executor <adapter>'
@@ -342,7 +342,7 @@ async function verifyExistingFeatureReferences(repoRoot, chain) {
342
342
  }
343
343
  }
344
344
 
345
- function planSeed(authoring, predecessorPlanDigest) {
345
+ export function planSeed(authoring, predecessorPlanDigest) {
346
346
  return {
347
347
  schema: 'lattice.todo_plan.v7', project_id: authoring.project_id,
348
348
  plan_key: authoring.plan_key, predecessor_plan_digest: predecessorPlanDigest,
@@ -408,7 +408,7 @@ function compileTaskMigration(previousPlan, oldChain, desiredSeed, newChain) {
408
408
  }).sort((left, right) => left.from_task_id.localeCompare(right.from_task_id));
409
409
  }
410
410
 
411
- function compilePhaseMigration(previousPlan, desiredSeed, taskMigration) {
411
+ export function compilePhaseMigration(previousPlan, desiredSeed, taskMigration) {
412
412
  const nextPhases = new Map(desiredSeed.phases.map((phase) => [phase.phase_id, phase]));
413
413
  const oldPhases = new Set(previousPlan.phases.map(({ phase_id: id }) => id));
414
414
  const affected = new Set(taskMigration.filter(({ state_policy }) =>
@@ -492,7 +492,9 @@ async function activeIntentUnchanged({ repoRoot, member, chain, authoring }) {
492
492
  });
493
493
  }
494
494
 
495
- async function rebindCarriedWork({ repoRoot, planKey, env }) {
495
+ export async function rebindCarriedWork({ repoRoot, planKey, env,
496
+ reason = 'ゴール変更後のplan versionへ作業中ToDoを結び直す',
497
+ failureCode = 'BACKCHAIN_REBIND_PENDING' }) {
496
498
  const store = await readTodoStore({ repoRoot });
497
499
  const member = store.members.find(({ plan }) => plan.plan_key === planKey);
498
500
  const rebound = [];
@@ -503,9 +505,9 @@ async function rebindCarriedWork({ repoRoot, planKey, env }) {
503
505
  const { rebindStart } = await import('./todo-cli.mjs');
504
506
  try {
505
507
  await rebindStart({ repoRoot, env, planKey, taskId: state.task_id,
506
- reason: 'ゴール変更後のplan versionへ作業中ToDoを結び直す' });
508
+ reason });
507
509
  } catch (error) {
508
- throw new TodoStoreError('BACKCHAIN_REBIND_PENDING', 'carried_task_rebind_failed', undefined, {
510
+ throw new TodoStoreError(failureCode, 'carried_task_rebind_failed', undefined, {
509
511
  task_id: state.task_id, plan_version: member.plan.plan_version,
510
512
  cause_code: error?.code ?? 'unknown',
511
513
  next_action: `lattice todo start --plan ${planKey} --task ${state.task_id} --rebind --reason <text>`,
@@ -0,0 +1,60 @@
1
+ // Plan-owned continuity semantics for incoming cross-plan connections whose source
2
+ // plan was revised (Snow White coordination decision 2026-11-07, w1b first use).
3
+ // Pure: no I/O, no Store mutation. Store's rebindTodoCrossPlanDependencies calls it
4
+ // under lock with the active source member, the live dependencies to carry and the
5
+ // retained predecessor plan's identity, and only rebinds when it answers ok.
6
+ const CARRIED_POLICIES = new Set(['carry', 'carry_reconciled_metadata']);
7
+
8
+ export function validateBindingCarry({ store, source, dependencies, predecessor }) {
9
+ // Refusal shape is Store's typed refusal: code = error class, detail.reason = rule.
10
+ const refuse = (code, reason, detail = {}) => ({ ok: false, code, detail: { reason, ...detail } });
11
+ const { plan, revision } = source;
12
+ // shortcut: only the immediate predecessor hop is carried; a connection two or more
13
+ // revisions behind needs a chained check, add it when such a store actually exists.
14
+ if (revision?.predecessor?.plan_version !== predecessor.plan_version
15
+ || revision?.predecessor?.plan_digest !== predecessor.plan_digest) {
16
+ return refuse('DEPENDENCY_STALE', 'binding_carry_hop_unlinked', { predecessor,
17
+ revision_predecessor: revision?.predecessor ?? null });
18
+ }
19
+ if (revision.desired_plan?.topology_digest !== plan.topology_digest) {
20
+ return refuse('DEPENDENCY_STALE', 'binding_carry_successor_mismatch', { plan_version: plan.plan_version });
21
+ }
22
+ const migration = new Map(revision.task_migration.map((row) => [row.from_task_id, row]));
23
+ const seen = new Set();
24
+ const rebound = [];
25
+ for (const dependency of dependencies) {
26
+ const { from, to } = dependency;
27
+ const edge = { from_task_id: from.task_id, to: { plan_key: to.plan_key, task_id: to.task_id } };
28
+ if (from.project_id !== plan.project_id || from.plan_key !== plan.plan_key) {
29
+ return refuse('DEPENDENCY_INVALID', 'binding_carry_source_mismatch', edge);
30
+ }
31
+ if (from.expected_topology_digest !== predecessor.topology_digest) {
32
+ return refuse('DEPENDENCY_STALE', 'binding_carry_predecessor_mismatch', { ...edge,
33
+ expected_topology_digest: from.expected_topology_digest });
34
+ }
35
+ const row = migration.get(from.task_id) ?? null;
36
+ if (row === null || row.to_task_id !== from.task_id || !CARRIED_POLICIES.has(row.state_policy)) {
37
+ return refuse('DEPENDENCY_INVALID', 'binding_carry_task_not_carried', { ...edge, migration: row });
38
+ }
39
+ if (!plan.tasks.some(({ task_id: taskId }) => taskId === from.task_id)) {
40
+ return refuse('DEPENDENCY_INVALID', 'binding_carry_task_missing', edge);
41
+ }
42
+ const owner = store.members.find((member) => member.plan.project_id === to.project_id
43
+ && member.plan.plan_key === to.plan_key) ?? null;
44
+ if (owner === null || !owner.plan.tasks.some(({ task_id: taskId }) => taskId === to.task_id)) {
45
+ return refuse('DEPENDENCY_INVALID', 'binding_carry_target_missing', edge);
46
+ }
47
+ if (to.expected_topology_digest !== owner.plan.topology_digest) {
48
+ return refuse('DEPENDENCY_STALE', 'binding_carry_target_changed', { ...edge,
49
+ expected_topology_digest: to.expected_topology_digest,
50
+ actual_topology_digest: owner.plan.topology_digest });
51
+ }
52
+ const key = `${from.task_id}\0${to.project_id}\0${to.plan_key}\0${to.task_id}`;
53
+ if (seen.has(key)) return refuse('DEPENDENCY_INVALID', 'binding_carry_duplicate', edge);
54
+ seen.add(key);
55
+ rebound.push({ event_digest: dependency.event_digest ?? null, ...edge,
56
+ predecessor_topology_digest: from.expected_topology_digest, successor_topology_digest: plan.topology_digest });
57
+ }
58
+ return { ok: true, detail: { plan_version: plan.plan_version,
59
+ successor_topology_digest: plan.topology_digest, rebound } };
60
+ }
@@ -0,0 +1,175 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+
4
+ import { canonicalizeTodoArtifact, exactRecord, isTodoIdentifier, todoSelfDigest } from './todo-contracts.mjs';
5
+ import { gitSync } from './git-process.mjs';
6
+ import { readAuthoringJsonFile, repairAuthoringArtifact } from './todo-authoring-input.mjs';
7
+ import { validatePlanCreateInput } from './project-cli.mjs';
8
+ import {
9
+ compilePhaseMigration, planSeed, readPlanBackchainBinding, rebindCarriedWork,
10
+ } from './plan-backchain.mjs';
11
+ import {
12
+ applyPhaseTodoRevision, buildTodoPlan, createTodoStoreWriter, readTodoStore, TodoStoreError,
13
+ } from './todo-store.mjs';
14
+ import { phaseTodoRevisionPlanVersion, validatePhaseTodoRevision } from './todo-revision.mjs';
15
+
16
+ export { validateBindingCarry } from './plan-binding-carry.mjs';
17
+
18
+ const INPUT_SCHEMA = 'lattice.plan_revise_input.v1';
19
+
20
+ function fail(reason, pointer, detail = {}) {
21
+ throw new TodoStoreError('INPUT_INVALID', reason, undefined, { pointer, ...detail });
22
+ }
23
+
24
+ export function compilePlanRevision({ member, input }) {
25
+ if (!exactRecord(input, ['schema', 'desired', 'continuity']) || input.schema !== INPUT_SCHEMA) {
26
+ fail('plan_revise_schema_invalid', '/', { expected: INPUT_SCHEMA });
27
+ }
28
+ const desired = repairAuthoringArtifact(input.desired);
29
+ try { validatePlanCreateInput(desired); }
30
+ catch (error) {
31
+ if (typeof error?.detail?.pointer === 'string') {
32
+ error.detail.pointer = `/desired${error.detail.pointer === '/' ? '' : error.detail.pointer}`;
33
+ }
34
+ throw error;
35
+ }
36
+ if (member === undefined) fail('plan_not_active', '/desired/plan_key');
37
+ if (member.plan.schema === 'lattice.todo_plan.v6'
38
+ || member.journal.events[0].schema === 'lattice.todo_event.v2'
39
+ || [...member.plan.tasks, ...desired.tasks].some((task) => task.narrative_anchor !== null)) {
40
+ fail('plan_revise_requires_source_revision', '/desired/tasks', {
41
+ next_action: `lattice todo revise-phase --plan ${desired.plan_key} --input <phase-revision.json>`,
42
+ });
43
+ }
44
+ if (member.plan.schema !== 'lattice.todo_plan.v7') {
45
+ fail('predecessor_plan_schema_unsupported', '/desired/plan_key');
46
+ }
47
+ if (desired.project_id !== member.plan.project_id || desired.plan_key !== member.plan.plan_key) {
48
+ fail('plan_revise_identity_mismatch', '/desired/plan_key');
49
+ }
50
+ if (!Array.isArray(input.continuity) || input.continuity.length !== member.plan.tasks.length) {
51
+ fail('plan_revise_continuity_incomplete', '/continuity', {
52
+ expected: { task_ids: member.plan.tasks.map(({ task_id }) => task_id) },
53
+ });
54
+ }
55
+ const oldIds = new Set(member.plan.tasks.map(({ task_id }) => task_id));
56
+ const decisions = new Map();
57
+ for (const [index, entry] of input.continuity.entries()) {
58
+ if (!exactRecord(entry, ['task_id', 'policy', 'reason']) || !isTodoIdentifier(entry.task_id)
59
+ || !['carry', 'reset', 'retire'].includes(entry.policy)
60
+ || typeof entry.reason !== 'string' || entry.reason.trim().length === 0
61
+ || !oldIds.has(entry.task_id) || decisions.has(entry.task_id)) {
62
+ fail('plan_revise_continuity_invalid', `/continuity/${index}`);
63
+ }
64
+ decisions.set(entry.task_id, entry.policy);
65
+ }
66
+ const desiredIds = new Set(desired.tasks.map(({ task_id }) => task_id));
67
+ const taskMigration = member.plan.tasks.map(({ task_id: id }) => {
68
+ const policy = decisions.get(id);
69
+ if ((policy === 'retire') === desiredIds.has(id)) {
70
+ fail('plan_revise_removed_task_mismatch', '/continuity', { task_id: id });
71
+ }
72
+ return { from_task_id: id, to_task_id: policy === 'retire' ? 'removed' : id,
73
+ state_policy: policy === 'retire' ? 'removed'
74
+ : policy === 'carry' ? 'carry_reconciled_metadata' : 'reset_pending' };
75
+ });
76
+ const predecessor = {
77
+ plan_digest: member.plan.plan_digest,
78
+ journal_head_digest: member.journal.events.at(-1).event_digest,
79
+ plan_version: member.plan.plan_version,
80
+ };
81
+ const seed = planSeed(desired, predecessor.plan_digest);
82
+ const phaseMigration = compilePhaseMigration(member.plan, seed, taskMigration);
83
+ const version = phaseTodoRevisionPlanVersion({
84
+ projectId: desired.project_id, planKey: desired.plan_key, predecessor,
85
+ desiredPlan: seed, taskMigration, phaseMigration,
86
+ });
87
+ const revision = {
88
+ schema: 'lattice.phase_todo_revision.v5', project_id: desired.project_id,
89
+ plan_key: desired.plan_key, predecessor,
90
+ desired_plan: buildTodoPlan({ ...seed, plan_version: version }),
91
+ task_migration: taskMigration, phase_migration: phaseMigration, revision_digest: '',
92
+ };
93
+ revision.revision_digest = todoSelfDigest(revision, 'revision_digest');
94
+ return revision;
95
+ }
96
+
97
+ export async function planReviseSchema() {
98
+ return JSON.parse(await readFile(new URL('../docs/schemas/lattice.plan_revise_input.v1.schema.json', import.meta.url)));
99
+ }
100
+
101
+ export async function runPlanRevise({ cwd, inputRef, stdout, dryRun = false, env = process.env }) {
102
+ let repoRoot;
103
+ try {
104
+ repoRoot = path.resolve(gitSync(['rev-parse', '--show-toplevel'], {
105
+ cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'],
106
+ }).replace(/\r?\n$/u, ''));
107
+ } catch { throw new TodoStoreError('REPO_UNRESOLVED', 'git_toplevel_unresolved'); }
108
+ const input = await readAuthoringJsonFile(repoRoot, inputRef, { invalidCode: 'INPUT_INVALID' });
109
+ const store = await readTodoStore({ repoRoot });
110
+ const member = store.members.find(({ plan }) => plan.plan_key === input?.desired?.plan_key);
111
+ const revision = compilePlanRevision({ member, input });
112
+ if (await readPlanBackchainBinding({ repoRoot, plan: member.plan }) !== null) {
113
+ fail('plan_revise_requires_backchain', '/desired/plan_key', {
114
+ next_action: 'lattice plan backchain --input <file> --json',
115
+ });
116
+ }
117
+ const unchanged = input.continuity.every(({ policy }) => policy === 'carry')
118
+ && canonicalizeTodoArtifact(planSeed(input.desired, null))
119
+ === canonicalizeTodoArtifact(planSeed(member.plan, null));
120
+ if (!unchanged && !validatePhaseTodoRevision(revision)) fail('plan_revise_artifact_invalid', '/');
121
+ if (!unchanged) {
122
+ const { todoTaskCarrySemantics } = await import('./todo-store-view.mjs');
123
+ const idMap = new Map(revision.task_migration.map(({ from_task_id, to_task_id }) => [from_task_id, to_task_id]));
124
+ const removedTaskIds = new Set(revision.task_migration.filter(({ state_policy }) => state_policy === 'removed')
125
+ .map(({ from_task_id }) => from_task_id));
126
+ for (const [index, entry] of input.continuity.entries()) {
127
+ if (entry.policy !== 'carry') continue;
128
+ const before = todoTaskCarrySemantics(member.plan, entry.task_id, idMap,
129
+ { reconciliationMetadata: true, includeDesignMemo: false, removedTaskIds });
130
+ const after = todoTaskCarrySemantics(revision.desired_plan, entry.task_id, new Map(),
131
+ { reconciliationMetadata: true, includeDesignMemo: false });
132
+ if (canonicalizeTodoArtifact(before) !== canonicalizeTodoArtifact(after)) {
133
+ throw new TodoStoreError('REVISION_INVALID', 'carry_semantics_changed', undefined, {
134
+ pointer: `/continuity/${index}`, task_id: entry.task_id,
135
+ expected: { policy: 'reset' }, actual: { policy: 'carry' },
136
+ next_action: 'set_the_reported_continuity_policy_to_reset_then_rerun_plan_revise_dry_run',
137
+ });
138
+ }
139
+ }
140
+ }
141
+ let applied = null;
142
+ let reboundTaskIds = [];
143
+ if (!dryRun) {
144
+ if (!unchanged) {
145
+ applied = await applyPhaseTodoRevision({ repoRoot,
146
+ writer: createTodoStoreWriter({ caller: 'g5-authoring' }), revision,
147
+ actor: input.desired.actor, recordedAt: input.desired.recorded_at,
148
+ });
149
+ }
150
+ try {
151
+ reboundTaskIds = await rebindCarriedWork({ repoRoot, planKey: revision.plan_key, env,
152
+ reason: '工程改訂後のplan versionへ作業中ToDoを結び直す',
153
+ failureCode: 'PLAN_REBIND_PENDING' });
154
+ } catch (error) {
155
+ // 公開後に起きたStoreの失敗は、改訂が確定済みであることを必ず報告する(2026-11-07
156
+ // 初回使用: rebind読込の素のbinding_staleが公開済み事実を隠した)
157
+ if (error instanceof TodoStoreError) {
158
+ error.detail = { ...error.detail, revision_applied: !unchanged,
159
+ revision_digest: unchanged ? null : revision.revision_digest,
160
+ plan_version: unchanged ? member.plan.plan_version : revision.desired_plan.plan_version };
161
+ }
162
+ throw error;
163
+ }
164
+ }
165
+ const result = {
166
+ schema: unchanged ? 'lattice.plan_revise_unchanged.v1' : 'lattice.plan_revise_result.v1',
167
+ project_id: revision.project_id, plan_key: revision.plan_key,
168
+ plan_version: unchanged ? member.plan.plan_version : revision.desired_plan.plan_version,
169
+ dry_run: dryRun, revision: unchanged ? null : revision, applied,
170
+ continuity: input.continuity, rebound_task_ids: reboundTaskIds, result_digest: '',
171
+ };
172
+ result.result_digest = todoSelfDigest(result, 'result_digest');
173
+ stdout.write(`${JSON.stringify(result)}\n`);
174
+ return 0;
175
+ }
@@ -601,10 +601,7 @@ function describeCreateInputViolation(value) {
601
601
  return null;
602
602
  }
603
603
 
604
- export async function runPlanCreate({ cwd, inputRef, stdout, inputValue = null, featureChain = null }) {
605
- const repoRoot = resolveRepoRoot(cwd);
606
- if (repoRoot === null) throw new TodoStoreError('REPO_UNRESOLVED', 'git_toplevel_unresolved');
607
- const input = inputValue ?? await readCanonicalInput(repoRoot, inputRef);
604
+ export function validatePlanCreateInput(input) {
608
605
  if (input?.schema !== MEMO_PHASE_CREATE_INPUT_SCHEMA) {
609
606
  throw new TodoStoreError('INPUT_INVALID', 'plan_create_schema_retired', undefined, {
610
607
  violation_kind: 'const_mismatch', pointer: '/schema',
@@ -636,6 +633,13 @@ export async function runPlanCreate({ cwd, inputRef, stdout, inputValue = null,
636
633
  next_action: 'correct_the_reported_pointer_then_rerun_plan_create',
637
634
  });
638
635
  }
636
+ }
637
+
638
+ export async function runPlanCreate({ cwd, inputRef, stdout, inputValue = null, featureChain = null }) {
639
+ const repoRoot = resolveRepoRoot(cwd);
640
+ if (repoRoot === null) throw new TodoStoreError('REPO_UNRESOLVED', 'git_toplevel_unresolved');
641
+ const input = inputValue ?? await readCanonicalInput(repoRoot, inputRef);
642
+ validatePlanCreateInput(input);
639
643
  // dispatch_shapeは結果へ載せる観測であり、直列度では初期化を拒まない(ADR 0180)。
640
644
  const dispatchShape = computeTodoDispatchShapeForPlan({
641
645
  projectId: input.project_id,
@@ -40,7 +40,45 @@ export async function observeStartIdentityRaw(pid) {
40
40
  ? ['-NoProfile', '-NonInteractive', '-Command',
41
41
  `[System.Diagnostics.Process]::GetProcessById(${pid}).StartTime.ToUniversalTime().Ticks`]
42
42
  : ['-o', 'lstart=', '-p', String(pid)];
43
- const { stdout } = await execFileAsync(executable, args, { encoding: 'utf8', env: osObservationEnvironment() });
43
+ try {
44
+ const { stdout } = await execFileAsync(executable, args, { encoding: 'utf8', env: osObservationEnvironment() });
45
+ return stdout.trim();
46
+ } catch (error) {
47
+ // Another account's process denies its handle; its PID may be a reused dead owner's.
48
+ if (process.platform === 'win32') return observeStartIdentitySnapshotRaw(pid);
49
+ throw error;
50
+ }
51
+ }
52
+
53
+ // SYSTEM_PROCESS_INFORMATION: CreateTime at 32, UniqueProcessId at 80 (64-bit) / 68 (32-bit).
54
+ const WINDOWS_PROCESS_SNAPSHOT = `
55
+ using System; using System.Runtime.InteropServices;
56
+ public static class LatticeProcessSnapshot {
57
+ [DllImport("ntdll.dll")] static extern int NtQuerySystemInformation(int c, IntPtr b, int l, out int r);
58
+ public static long CreateTime(long pid) {
59
+ for (int length = 1 << 20; ; length *= 2) {
60
+ IntPtr buffer = Marshal.AllocHGlobal(length);
61
+ try {
62
+ int needed; int status = NtQuerySystemInformation(5, buffer, length, out needed);
63
+ if (status == unchecked((int)0xC0000004)) continue;
64
+ if (status != 0) throw new InvalidOperationException("NtQuerySystemInformation " + status);
65
+ for (IntPtr entry = buffer; ; ) {
66
+ if (Marshal.ReadIntPtr(entry, IntPtr.Size == 8 ? 80 : 68).ToInt64() == pid) return Marshal.ReadInt64(entry, 32);
67
+ int next = Marshal.ReadInt32(entry); if (next == 0) break; entry = IntPtr.Add(entry, next);
68
+ }
69
+ throw new ArgumentException("process not running: " + pid);
70
+ } finally { Marshal.FreeHGlobal(buffer); }
71
+ }
72
+ }
73
+ }`;
74
+
75
+ /** win32: handle-free start identity, identical to StartTime UTC ticks (both are the kernel CreateTime). */
76
+ export async function observeStartIdentitySnapshotRaw(pid) {
77
+ const script = `$ErrorActionPreference='Stop'; Add-Type -TypeDefinition '${WINDOWS_PROCESS_SNAPSHOT}'; `
78
+ + `[DateTime]::FromFileTimeUtc([LatticeProcessSnapshot]::CreateTime(${Number(pid)})).Ticks`;
79
+ // EncodedCommand keeps the C# quotes out of Windows command-line quoting.
80
+ const { stdout } = await execFileAsync('pwsh.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand',
81
+ Buffer.from(script, 'utf16le').toString('base64')], { encoding: 'utf8', env: osObservationEnvironment() });
44
82
  return stdout.trim();
45
83
  }
46
84
 
@@ -38,14 +38,16 @@ function identified(owner) {
38
38
  }
39
39
 
40
40
  async function processIsDead(pid, startDigest) {
41
+ // Existence first: a PID freed after a failed observation may be reused before a later check.
42
+ try { process.kill(pid, 0); }
43
+ catch (error) { if (error?.code === 'ESRCH') return true; }
41
44
  try {
42
45
  const observed = await observeStartIdentityRaw(pid);
43
46
  if (observed) return hash(`${process.platform}:${observed}`) !== startDigest;
44
47
  } catch {
45
48
  // A failed observation cannot turn an existing PID into a dead owner.
46
49
  }
47
- try { process.kill(pid, 0); return false; }
48
- catch (error) { return error?.code === 'ESRCH'; }
50
+ return false;
49
51
  }
50
52
 
51
53
  async function readOwner(lockPath) {
@@ -35,6 +35,7 @@ export const AUTHORING_DIGEST_FIELDS = Object.freeze({
35
35
  'lattice.phase_todo_revision.v2': 'revision_digest',
36
36
  'lattice.phase_todo_revision.v3': 'revision_digest',
37
37
  'lattice.phase_todo_revision.v4': 'revision_digest',
38
+ 'lattice.phase_todo_revision.v5': 'revision_digest',
38
39
  'lattice.todo_revision_set.v1': 'revision_set_digest',
39
40
  'lattice.todo_revision_set.v2': 'revision_set_digest',
40
41
  'lattice.todo_revision_set.v3': 'revision_set_digest',
package/src/todo-cli.mjs CHANGED
@@ -191,8 +191,8 @@ const ACTOR_ENV_KEYS = Object.freeze([
191
191
  ]);
192
192
 
193
193
  /**
194
- * `revise` / `revise-set` / `revise-phase` / `migrate`が実際に受理する最新契約のJSON
195
- * Schemaを配布物から読む入口(`project-cli.mjs`の`runPlanCreateSchema`と同じ作法)。
194
+ * `revise` / `revise-set` / `revise-phase` / `migrate`が配布する名前付き入力契約のJSON
195
+ * Schemaを読む入口。受理するartifact版すべての列挙ではない(`project-cli.mjs`の`runPlanCreateSchema`と同じ作法)。
196
196
  *
197
197
  * schemaを取る手段がCLIに無いと、AIはsrcを読んで必須keyを数えるしかなくなる
198
198
  * (実運用で`phase_todo_revision.v3`の必須12 keyを試行錯誤で当てた)。storeは読まない
@@ -3677,6 +3677,7 @@ async function verify({ repoRoot, requestedPlanKey }) {
3677
3677
  case 'lattice.phase_todo_revision.v2':
3678
3678
  case 'lattice.phase_todo_revision.v3':
3679
3679
  case 'lattice.phase_todo_revision.v4':
3680
+ case 'lattice.phase_todo_revision.v5':
3680
3681
  verifiedSourceInventories.set(member.descriptor.plan_key,
3681
3682
  await verifyEffectivePhaseTodoRevisionSources({ repoRoot, member }));
3682
3683
  break;
@@ -3689,7 +3690,8 @@ async function verify({ repoRoot, requestedPlanKey }) {
3689
3690
  const reconciled = member.revision !== null;
3690
3691
  const sourceInventory = verifiedSourceInventories.get(member.descriptor.plan_key) ?? null;
3691
3692
  const phaseRevision = ['lattice.phase_todo_revision.v1', 'lattice.phase_todo_revision.v2',
3692
- 'lattice.phase_todo_revision.v3', 'lattice.phase_todo_revision.v4']
3693
+ 'lattice.phase_todo_revision.v3', 'lattice.phase_todo_revision.v4',
3694
+ 'lattice.phase_todo_revision.v5']
3693
3695
  .includes(member.revision?.schema);
3694
3696
  return {
3695
3697
  plan_key: member.descriptor.plan_key,
@@ -621,9 +621,11 @@ export async function readTodoPlanNotesForStatus(options = {}) {
621
621
  return summaries;
622
622
  }
623
623
 
624
- /** Gantt用に1 planのchain/historyを一度だけ読み、全task contextへ投影する。 */
624
+ /** 1 planを一度だけ読み全taskへ投影する。includeHistoryはbudget前の履歴も返す。 */
625
625
  export async function readTodoNoteContextsForPlan(options = {}) {
626
- if (!exactRecord(options, ['repoRoot', 'store', 'planKey'])
626
+ const keys = ['repoRoot', 'store', 'planKey'];
627
+ if (!(exactRecord(options, keys) || exactRecord(options, [...keys, 'includeHistory']))
628
+ || ('includeHistory' in options && typeof options.includeHistory !== 'boolean')
627
629
  || !isTodoIdentifier(options.planKey)
628
630
  || options.store === null || typeof options.store !== 'object') {
629
631
  throw new TypeError('todo note contexts read options invalid');
@@ -654,5 +656,8 @@ export async function readTodoNoteContextsForPlan(options = {}) {
654
656
  contexts: projected.map(({ context }) => context),
655
657
  archived: projected[0]?.archived ?? [],
656
658
  note_head_digest: chain.head_digest,
659
+ ...(options.includeHistory ? { histories: projected.map(({ context, history }) => ({
660
+ task_id: context.task_id, history,
661
+ })) } : {}),
657
662
  };
658
663
  }
@@ -871,12 +871,9 @@ function snapshotFor(plan, events, tasks) {
871
871
  return snapshot;
872
872
  }
873
873
 
874
- function validateMergedGraph(members, crossPlanDependencies = [], options = {}) {
875
- // tolerateStaleBindings は dependency disconnect 専用の修理扉。plan revise が越境依存の
876
- // 固定digestを陳腐化させると、通常loadは binding_stale で fail closed するが、その修理
877
- // コマンド自身も load を要するため、扉が無いと修理経路が存在しない(実被弾 2026-08-29:
878
- // evidence-2 改訂で store 全体が読めなくなり、disconnect も同エラーで詰んだ)。
879
- // 許容するのは digest 不一致だけで、dangling / missing は修理扉でも fail する。
874
+ function validateMergedGraph(members, crossPlanDependencies = projectTodoCrossPlanDependencies(members), options = {}) {
875
+ // Only disconnect and the locked identity-preserving repair tolerate stale digests.
876
+ // Missing endpoints and bindings remain invalid on both repair paths.
880
877
  const tolerateStale = options.tolerateStaleBindings === true;
881
878
  const tasks = new Map();
882
879
  for (const member of members) for (const task of member.plan.tasks) {
@@ -2045,6 +2042,100 @@ async function appendPlanScopedEvent({ repoRoot, member, input }) {
2045
2042
  };
2046
2043
  }
2047
2044
 
2045
+ /** Rebind existing connections to a carried source without changing their endpoints. */
2046
+ export async function rebindTodoCrossPlanDependencies(options = {}) {
2047
+ requireWriter(options.writer, 'g5-authoring');
2048
+ if (typeof options.validateBindingCarry !== 'function'
2049
+ || !isTodoIdentifier(options.planKey) || !isTodoIdentifier(options.sourcePlanKey)
2050
+ || !isTodoDigest(options.expectedManifestDigest)
2051
+ || !isTodoDigest(options.expectedPlanScopedHeadDigest)
2052
+ || !Array.isArray(options.eventDigests) || options.eventDigests.length === 0
2053
+ || !options.eventDigests.every(isTodoDigest)
2054
+ || new Set(options.eventDigests).size !== options.eventDigests.length
2055
+ || typeof options.reason !== 'string' || options.reason.length === 0) {
2056
+ throw new TypeError('dependency rebind requires exact bindings and a Plan carry validator');
2057
+ }
2058
+ const repoRoot = path.resolve(options.repoRoot ?? process.cwd());
2059
+ return withLock(repoRoot, async () => {
2060
+ // The repair read must not publish derived state before the complete strict graph check.
2061
+ const store = await readTodoStoreView({ repoRoot, now: options.now,
2062
+ tolerateStaleBindings: true });
2063
+ const owner = store.members.find(({ plan }) => plan.plan_key === options.planKey);
2064
+ const source = store.members.find(({ plan }) => plan.plan_key === options.sourcePlanKey);
2065
+ if (store.manifest.manifest_digest !== options.expectedManifestDigest
2066
+ || owner?.plan_scoped.events.at(-1)?.event_digest !== options.expectedPlanScopedHeadDigest) {
2067
+ fail('STORE_WRITE_CONFLICT', 'dependency_rebind_binding_changed');
2068
+ }
2069
+ if (!source || source === owner) fail('DEPENDENCY_INVALID', 'dependency_rebind_source_invalid');
2070
+ const dependencies = projectTodoCrossPlanDependencies(store.members)
2071
+ .filter(({ event_digest: digest }) => options.eventDigests.includes(digest));
2072
+ if (dependencies.length !== options.eventDigests.length || dependencies.some(({ from, to, event_digest: digest }) => (
2073
+ from.project_id !== source.plan.project_id || from.plan_key !== source.plan.plan_key
2074
+ || from.expected_topology_digest === source.plan.topology_digest
2075
+ || to.project_id !== owner.plan.project_id || to.plan_key !== owner.plan.plan_key
2076
+ || !owner.plan_scoped.events.some((event) => event.event_digest === digest)
2077
+ ))) fail('DEPENDENCY_INVALID', 'dependency_rebind_original_mismatch');
2078
+ const predecessorBinding = source.revision?.predecessor;
2079
+ if (!predecessorBinding) fail('DEPENDENCY_INVALID', 'dependency_rebind_predecessor_missing');
2080
+ const predecessor = await readArtifact(repoRoot,
2081
+ `${STORE_ROOT_REF}/plans/${source.plan.plan_key}/${predecessorBinding.plan_version}/plan.json`, {
2082
+ code: 'STORE_INCONSISTENT', maxBytes: TODO_LIMITS.snapshotBytes, validate: validateTodoPlan,
2083
+ });
2084
+ if (predecessor.project_id !== source.plan.project_id || predecessor.plan_key !== source.plan.plan_key
2085
+ || predecessor.plan_version !== predecessorBinding.plan_version
2086
+ || predecessor.plan_digest !== predecessorBinding.plan_digest) {
2087
+ fail('STORE_INCONSISTENT', 'dependency_rebind_predecessor_mismatch');
2088
+ }
2089
+ const validation = await options.validateBindingCarry({ store, source, dependencies,
2090
+ predecessor: { plan_version: predecessor.plan_version, plan_digest: predecessor.plan_digest,
2091
+ topology_digest: predecessor.topology_digest } });
2092
+ if (validation?.ok === false) {
2093
+ if (typeof validation.code !== 'string' || typeof validation.detail?.reason !== 'string') {
2094
+ throw new TypeError('binding carry validator must return a typed refusal');
2095
+ }
2096
+ const { reason, ...detail } = validation.detail;
2097
+ fail(validation.code, reason, detail);
2098
+ }
2099
+ if (validation?.ok !== true) throw new TypeError('binding carry validator must return an ok result');
2100
+ const staged = { ...owner, plan_scoped: { ...owner.plan_scoped,
2101
+ events: [...owner.plan_scoped.events] } };
2102
+ const replacements = [];
2103
+ for (const dependency of dependencies) {
2104
+ for (const input of [
2105
+ { kind: 'cross_plan_dependency_removed', payload: {
2106
+ target_event_digest: dependency.event_digest, reason: options.reason,
2107
+ } },
2108
+ { kind: 'cross_plan_dependency', payload: {
2109
+ from: { ...dependency.from, expected_topology_digest: source.plan.topology_digest },
2110
+ to: dependency.to, reason: dependency.reason,
2111
+ } },
2112
+ ]) {
2113
+ const event = buildPlanScopedEvent(staged, { ...input, actor: options.actor,
2114
+ recorded_at: options.recordedAt ?? new Date().toISOString() });
2115
+ const bytes = planScopedEventBytes(staged, event);
2116
+ staged.plan_scoped.events.push(event);
2117
+ staged.plan_scoped.activeBytes = Buffer.concat([staged.plan_scoped.activeBytes, bytes]);
2118
+ }
2119
+ replacements.push({ original_event_digest: dependency.event_digest,
2120
+ replacement_event_digest: staged.plan_scoped.events.at(-1).event_digest });
2121
+ }
2122
+ const prospective = store.members.map((member) => member === owner ? staged : member);
2123
+ const projected = projectTodoCrossPlanDependencies(prospective);
2124
+ const edgeKeys = projected.map(({ from, to }) => `${mergedTaskKey(from)}\0${mergedTaskKey(to)}`);
2125
+ if (new Set(edgeKeys).size !== edgeKeys.length) {
2126
+ fail('DEPENDENCY_EXISTS', 'cross_plan_dependency_duplicate');
2127
+ }
2128
+ validateMergedGraph(prospective, projected);
2129
+ await protocolStage(options, 'dependency_rebind_validated');
2130
+ await atomicWrite(path.resolve(repoRoot, owner.plan_scoped.ref), staged.plan_scoped.activeBytes);
2131
+ await protocolStage(options, 'dependency_rebind_published');
2132
+ return { schema: 'lattice.todo_dependency_rebind_result.v1', project_id: store.project_id,
2133
+ plan_key: owner.plan.plan_key, source_plan_key: source.plan.plan_key,
2134
+ source_topology_digest: source.plan.topology_digest, replacements,
2135
+ plan_scoped_head_digest: staged.plan_scoped.events.at(-1).event_digest };
2136
+ });
2137
+ }
2138
+
2048
2139
  export function buildTodoPlan(input) {
2049
2140
  const plan = { ...input, topology_digest: '', plan_digest: '' };
2050
2141
  plan.topology_digest = digestTodoArtifact({
@@ -4464,7 +4555,7 @@ async function applyPhaseTodoRevisionV3(options, revision, repoRoot) {
4464
4555
  const stateMigration = stateMigrationFor(previous, revision);
4465
4556
  const phaseStateMigration = phaseStateMigrationFor(previous, revision);
4466
4557
  validateMergedGraph(store.members.map((member) => member === previous
4467
- ? { ...member, plan: revision.desired_plan } : member));
4558
+ ? { ...member, plan: revision.desired_plan, plan_scoped: null } : member));
4468
4559
  const candidateGenesis = buildPhaseRevisionGenesis(revision.desired_plan, {
4469
4560
  previous_digest: revision.predecessor.journal_head_digest, actor: options.actor,
4470
4561
  recorded_at: options.recordedAt, provenance: options.provenance ?? null,
@@ -4635,7 +4726,7 @@ export async function applyPhaseTodoRevision(options = {}) {
4635
4726
  const stateMigration = stateMigrationFor(previous, revision);
4636
4727
  const phaseStateMigration = phaseStateMigrationFor(previous, revision);
4637
4728
  const prospective = store.members.map((member) => member === previous
4638
- ? { ...member, plan: revision.desired_plan } : member);
4729
+ ? { ...member, plan: revision.desired_plan, plan_scoped: null } : member);
4639
4730
  validateMergedGraph(prospective);
4640
4731
  const candidateGenesis = buildPhaseRevisionGenesis(revision.desired_plan, {
4641
4732
  previous_digest: revision.predecessor.journal_head_digest,
@@ -4782,7 +4873,7 @@ export async function applyTodoRevision(options = {}) {
4782
4873
  verifyPlanNarrativeAnchors(repoRoot, revision.desired_plan, previous.plan);
4783
4874
  const stateMigration = stateMigrationFor(previous, revision);
4784
4875
  const prospective = store.members.map((member) => member === previous
4785
- ? { ...member, plan: revision.desired_plan } : member);
4876
+ ? { ...member, plan: revision.desired_plan, plan_scoped: null } : member);
4786
4877
  validateMergedGraph(prospective);
4787
4878
 
4788
4879
  const candidateGenesis = buildRevisionGenesis(revision.desired_plan, {
@@ -5055,7 +5146,7 @@ export async function applyTodoRevisionSet(options = {}) {
5055
5146
  const desiredByPlan = new Map(prepared.map((entry) => [entry.revision.plan_key,
5056
5147
  entry.revision.desired_plan]));
5057
5148
  validateMergedGraph(store.members.map((member) => desiredByPlan.has(member.descriptor.plan_key)
5058
- ? { ...member, plan: desiredByPlan.get(member.descriptor.plan_key) } : member));
5149
+ ? { ...member, plan: desiredByPlan.get(member.descriptor.plan_key), plan_scoped: null } : member));
5059
5150
 
5060
5151
  await ensureSafeStoreDirectory(repoRoot, transaction);
5061
5152
  const mixedPhaseSet = prepared.some(({ revision }) => ([
@@ -5248,7 +5339,7 @@ export async function createSuccessorTodoPlan(options = {}) {
5248
5339
  const genesis = buildPlanGenesis(plan, {
5249
5340
  ...options.genesis, previous_digest: previous.journal.events.at(-1).event_digest,
5250
5341
  });
5251
- const prospective = store.members.map((member) => member === previous ? { ...member, plan } : member);
5342
+ const prospective = store.members.map((member) => member === previous ? { ...member, plan, plan_scoped: null } : member);
5252
5343
  validateMergedGraph(prospective);
5253
5344
  const base = `${STORE_ROOT_REF}/plans/${plan.plan_key}/${plan.plan_version}`;
5254
5345
  const planRef = `${base}/plan.json`; const journalRef = `${base}/journal/active.jsonl`; const snapshotRef = `${base}/snapshot.json`;