@ordewell/core 0.13.2 → 0.13.3
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.
- package/dist/{ModeResolver-BmG9O08A.d.ts → ModeResolver-CXGnEhbN.d.ts} +1 -1
- package/dist/{ModeResolver-CNKcOksr.d.mts → ModeResolver-DqpwKbfJ.d.mts} +1 -1
- package/dist/{Task-CH1z4L3h.d.mts → Task-TFPWtKoz.d.mts} +2 -0
- package/dist/{Task-CH1z4L3h.d.ts → Task-TFPWtKoz.d.ts} +2 -0
- package/dist/{chunk-7ACNW5CD.mjs → chunk-4OARA73Z.mjs} +2 -2
- package/dist/{chunk-3P5UIXTR.mjs → chunk-5ETS2NIB.mjs} +13 -3
- package/dist/{chunk-3P5UIXTR.mjs.map → chunk-5ETS2NIB.mjs.map} +1 -1
- package/dist/{chunk-I436RXQT.mjs → chunk-62MSJNOG.mjs} +3 -3
- package/dist/{chunk-I436RXQT.mjs.map → chunk-62MSJNOG.mjs.map} +1 -1
- package/dist/{chunk-MGMQKUIJ.mjs → chunk-DFRDXOEG.mjs} +15 -5
- package/dist/chunk-DFRDXOEG.mjs.map +1 -0
- package/dist/{chunk-O52PN7P2.mjs → chunk-FOGPFLRO.mjs} +4 -4
- package/dist/chunk-FOGPFLRO.mjs.map +1 -0
- package/dist/daemon-client.js +14 -4
- package/dist/daemon-client.js.map +1 -1
- package/dist/daemon-client.mjs +1 -1
- package/dist/{eventStore-ClHaWY9b.d.mts → eventStore-D9Kv5dTu.d.mts} +27 -2
- package/dist/{eventStore-s1fpKwFe.d.ts → eventStore-DeuZxnKm.d.ts} +27 -2
- package/dist/index.d.mts +21 -12
- package/dist/index.d.ts +21 -12
- package/dist/index.js +1487 -1362
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1104 -1002
- package/dist/index.mjs.map +1 -1
- package/dist/{maxParallel-fSAdLIMh.d.mts → maxParallel-CSTmqKeu.d.mts} +44 -8
- package/dist/{maxParallel-DXvhdlD5.d.ts → maxParallel-Ds9VI1KO.d.ts} +44 -8
- package/dist/parsing.d.mts +2 -2
- package/dist/parsing.d.ts +2 -2
- package/dist/parsing.js +1 -1
- package/dist/parsing.js.map +1 -1
- package/dist/parsing.mjs +3 -3
- package/dist/plan-utils.d.mts +4 -4
- package/dist/plan-utils.d.ts +4 -4
- package/dist/plan-utils.js.map +1 -1
- package/dist/plan-utils.mjs +3 -3
- package/dist/testing.d.mts +4 -2
- package/dist/testing.d.ts +4 -2
- package/dist/testing.js +2 -0
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +3 -1
- package/dist/testing.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-MGMQKUIJ.mjs.map +0 -1
- package/dist/chunk-O52PN7P2.mjs.map +0 -1
- /package/dist/{chunk-7ACNW5CD.mjs.map → chunk-4OARA73Z.mjs.map} +0 -0
|
@@ -164,7 +164,9 @@ function isConnectionRefused(err) {
|
|
|
164
164
|
return message.includes("ECONNREFUSED");
|
|
165
165
|
}
|
|
166
166
|
function daemonHttpGet(port, path6, timeoutMs = 2e3) {
|
|
167
|
-
|
|
167
|
+
return httpGetWithToken(port, path6, timeoutMs, readDaemonToken(port));
|
|
168
|
+
}
|
|
169
|
+
function httpGetWithToken(port, path6, timeoutMs, token) {
|
|
168
170
|
const headers = token ? { Authorization: bearerHeaderValue(token) } : {};
|
|
169
171
|
return new Promise((resolvePromise, reject) => {
|
|
170
172
|
const req = http.get({ host: "127.0.0.1", port, path: path6, timeout: timeoutMs, headers }, (res) => {
|
|
@@ -192,13 +194,21 @@ async function isDaemonRunning(port = DEFAULT_DAEMON_PORT) {
|
|
|
192
194
|
var DAEMON_REFUSAL_MARK = "bearer token";
|
|
193
195
|
async function probeDaemon(port, timeoutMs = 2e3) {
|
|
194
196
|
let res;
|
|
197
|
+
let token = readDaemonToken(port);
|
|
195
198
|
try {
|
|
196
|
-
res = await
|
|
199
|
+
res = await httpGetWithToken(port, "/api/server", timeoutMs, token);
|
|
200
|
+
if (res.status === 401 && res.data.includes(DAEMON_REFUSAL_MARK)) {
|
|
201
|
+
const fresh = readDaemonToken(port);
|
|
202
|
+
if (fresh !== void 0 && fresh !== token) {
|
|
203
|
+
token = fresh;
|
|
204
|
+
res = await httpGetWithToken(port, "/api/server", timeoutMs, token);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
197
207
|
} catch (err) {
|
|
198
208
|
return isConnectionRefused(err) ? { kind: "unreachable" } : { kind: "unverifiable" };
|
|
199
209
|
}
|
|
200
210
|
if (res.status === 401 && res.data.includes(DAEMON_REFUSAL_MARK)) {
|
|
201
|
-
return { kind: "unauthorized", tokenPresented:
|
|
211
|
+
return { kind: "unauthorized", tokenPresented: token !== void 0 };
|
|
202
212
|
}
|
|
203
213
|
if (res.status !== 200) return { kind: "unverifiable" };
|
|
204
214
|
const identity = parseIdentity(res.data);
|
|
@@ -331,7 +341,7 @@ async function loginShellPath(execImpl) {
|
|
|
331
341
|
const shell = process.env.SHELL || "/bin/sh";
|
|
332
342
|
try {
|
|
333
343
|
const { stdout } = await execImpl(
|
|
334
|
-
`${shell} -l -c 'echo "${PATH_MARKER}
|
|
344
|
+
`${shell} -l -c 'echo "${PATH_MARKER}\${PATH}${PATH_MARKER}"'`,
|
|
335
345
|
{ timeout: LOGIN_SHELL_TIMEOUT_MS }
|
|
336
346
|
);
|
|
337
347
|
const match = stdout.match(new RegExp(`${PATH_MARKER}([^\\n]*)${PATH_MARKER}`));
|
|
@@ -756,4 +766,4 @@ export {
|
|
|
756
766
|
holderLives,
|
|
757
767
|
readLiveHolder
|
|
758
768
|
};
|
|
759
|
-
//# sourceMappingURL=chunk-
|
|
769
|
+
//# sourceMappingURL=chunk-DFRDXOEG.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/globalDataDir.ts","../src/utils/privateFile.ts","../src/utils/daemonToken.ts","../src/utils/daemonProcess.ts","../src/utils/shellPath.ts","../src/utils/version.ts","../src/utils/processTree.ts","../src/utils/fsHelpers.ts","../src/utils/sessionDir.ts","../src/utils/leaseRecord.ts"],"sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\n\n/**\n * Where Ordewell keeps machine-global data (settings, daemon tokens, caches,\n * credentials). A single home for everything not tied to a project directory,\n * so per-project state in `.ordewell/` and global state never collide.\n */\nexport function globalDataDir(): string {\n return path.join(os.homedir(), '.ordewell');\n}\n\nlet migrated = false;\n\n/**\n * One-time lift of a pre-`.ordewell` install's files into the new location.\n * Each file/dir is checked independently — old exists, new doesn't — rather\n * than gating the whole thing on \"new dir doesn't exist yet\". A machine that\n * migrated `settings.json` under an earlier release already has `globalDataDir()`\n * on disk, which would otherwise permanently skip lifting anything added to\n * this list later (`.env` did exactly that: real API keys stranded in the old\n * dir because the settings.json move had already made the new dir exist).\n *\n * Best-effort: a home it cannot write (read-only, full disk) must not take the\n * CLI down before `--help`, and the old file stays where it is.\n */\nexport function migrateOldConfigDir(): void {\n if (migrated) return;\n migrated = true;\n\n const oldDir = path.join(os.homedir(), '.config', 'ordewell');\n if (!fs.existsSync(oldDir)) return;\n const newDir = globalDataDir();\n\n const liftFile = (name: string): void => {\n const oldFile = path.join(oldDir, name);\n const newFile = path.join(newDir, name);\n if (!fs.existsSync(oldFile) || fs.existsSync(newFile)) return;\n try {\n fs.mkdirSync(newDir, { recursive: true });\n fs.copyFileSync(oldFile, newFile);\n } catch (err) {\n console.warn(`Could not move ${oldFile} to ${newFile}: ${String(err)}`);\n }\n };\n\n liftFile('settings.json');\n liftFile('.env');\n}\n","import { closeSync, mkdirSync, openSync, renameSync, unlinkSync, writeSync } from 'fs';\nimport { basename, dirname, join } from 'path';\nimport { randomBytes } from 'crypto';\n\n/**\n * Files only their owner may read: API keys in `~/.ordewell/.env`, the daemon's\n * bearer token. A `mode` argument to `writeFileSync` is honoured only when the\n * file is *created*, so a plain write over an existing file — or one another\n * process pre-created — keeps that file's old permissions. Writing a fresh temp\n * file and renaming it over the target sidesteps this: the replacement is\n * always 0600 whatever the old mode was, and a symlink planted at the target is\n * replaced rather than followed. The rename is atomic within a directory, so a\n * reader never observes a half-written secret.\n */\n\nconst DIR_MODE = 0o700;\nconst FILE_MODE = 0o600;\n\n// POSIX permission bits mean nothing on Windows; asking for them there is\n// harmless but has no effect, so the platform check documents the intent.\nconst POSIX_MODES = process.platform !== 'win32';\n\n/** Create `dir` (and its parents) owner-only, leaving any existing directory at its own mode. */\nexport function ensurePrivateDir(dir: string): void {\n if (POSIX_MODES) {\n mkdirSync(dir, { recursive: true, mode: DIR_MODE });\n return;\n }\n mkdirSync(dir, { recursive: true });\n}\n\n/** Write `content` to `filePath`, atomically, ending at 0600 on POSIX. */\nexport function writePrivateFile(filePath: string, content: string): void {\n const dir = dirname(filePath);\n ensurePrivateDir(dir);\n\n // Same directory as the target so the rename stays on one filesystem; random\n // so the name can never be pre-planted.\n const tempPath = join(dir, `.${basename(filePath)}.${randomBytes(8).toString('hex')}.tmp`);\n const fd = openSync(tempPath, 'wx', POSIX_MODES ? FILE_MODE : undefined);\n try {\n writeSync(fd, content);\n } finally {\n closeSync(fd);\n }\n\n try {\n renameSync(tempPath, filePath);\n } catch (err) {\n try {\n unlinkSync(tempPath);\n } catch {\n // Already gone; the rename error is the one worth reporting.\n }\n throw err;\n }\n}\n","/**\n * The daemon's bearer token: minted at startup, written beside the per-port\n * process-id file, read by the CLI.\n *\n * Header validation defends against browsers and nothing else. This is what\n * stops another process running as the same user — an install script in the\n * very repository the planner was pointed at, say — from driving the daemon\n * just because it can see the port.\n *\n * Both ends of the wire live here so the carrier encodings cannot drift: the\n * daemon extracts with the same functions the CLI attaches with.\n */\n\nimport { randomBytes, timingSafeEqual } from 'crypto';\nimport { readFileSync, unlinkSync } from 'fs';\nimport { join } from 'path';\nimport { globalDataDir } from './globalDataDir';\nimport { writePrivateFile } from './privateFile';\n\nconst BEARER_PREFIX = 'bearer ';\n\n/**\n * The subprotocol the token rides on during the WebSocket upgrade. A query\n * parameter would land in access logs and in `ps`; a subprotocol travels in a\n * request header like the HTTP `Authorization` it stands in for.\n */\nexport const DAEMON_TOKEN_SUBPROTOCOL_PREFIX = 'ordewell.token.';\n\n/**\n * Offered alongside the token subprotocol, and the one the server selects, so\n * the 101 response never echoes the secret back.\n */\nexport const DAEMON_SUBPROTOCOL = 'ordewell.v1';\n\nfunction configDir(): string {\n return globalDataDir();\n}\n\n/**\n * One token file per port, with no default-port special case: unlike the\n * process-id file there is no legacy name to preserve, and naming every file\n * after its port is what stops a second daemon clobbering the first's token.\n */\nexport function daemonTokenPath(port: number): string {\n return join(configDir(), `server-${port}.token`);\n}\n\n/**\n * Mint this daemon's token and hand it off through the filesystem.\n *\n * The write goes through `writePrivateFile` rather than a plain write because\n * `mode` is ignored when the file already exists: writing over a pre-created\n * file would leave the token at whatever permissions that file already had, and\n * an existing symlink would carry the write somewhere else entirely. The helper\n * writes a fresh 0600 temp file and renames it into place, so neither applies.\n */\nexport function mintDaemonToken(port: number): { token: string; file: string } {\n const token = randomBytes(32).toString('base64url');\n const file = daemonTokenPath(port);\n writePrivateFile(file, token);\n return { token, file };\n}\n\n/** The token a client should present to the daemon on `port`, if one has been minted. */\nexport function readDaemonToken(port: number): string | undefined {\n try {\n const token = readFileSync(daemonTokenPath(port), 'utf8').trim();\n return token === '' ? undefined : token;\n } catch {\n return undefined;\n }\n}\n\n/** Best-effort cleanup on shutdown, so a dead daemon leaves no usable-looking token behind. */\nexport function clearDaemonToken(port: number): void {\n try {\n unlinkSync(daemonTokenPath(port));\n } catch {\n // Already gone, or never written.\n }\n}\n\n/** The `Authorization` header value for HTTP requests. */\nexport function bearerHeaderValue(token: string): string {\n return `Bearer ${token}`;\n}\n\n/** What a client offers on the upgrade: the real subprotocol first, the token second. */\nexport function tokenSubprotocols(token: string): string[] {\n return [DAEMON_SUBPROTOCOL, `${DAEMON_TOKEN_SUBPROTOCOL_PREFIX}${token}`];\n}\n\nexport interface TokenCarriers {\n /** `Authorization: Bearer <token>` — the HTTP carrier. */\n authorization?: string | null;\n /** `Sec-WebSocket-Protocol` — the upgrade carrier. */\n secWebSocketProtocol?: string | null;\n}\n\n/** Pull the token out of whichever carrier it arrived on. */\nexport function extractPresentedToken(carriers: TokenCarriers): string | undefined {\n const authorization = carriers.authorization;\n if (authorization && authorization.toLowerCase().startsWith(BEARER_PREFIX)) {\n const value = authorization.slice(BEARER_PREFIX.length).trim();\n if (value !== '') return value;\n }\n\n for (const offered of (carriers.secWebSocketProtocol ?? '').split(',')) {\n const value = offered.trim();\n if (!value.startsWith(DAEMON_TOKEN_SUBPROTOCOL_PREFIX)) continue;\n const token = value.slice(DAEMON_TOKEN_SUBPROTOCOL_PREFIX.length);\n if (token !== '') return token;\n }\n\n return undefined;\n}\n\n/** Constant-time comparison, so a wrong token leaks no information about the right one. */\nexport function tokensMatch(presented: string | undefined, expected: string): boolean {\n if (presented === undefined) return false;\n const a = Buffer.from(presented, 'utf8');\n const b = Buffer.from(expected, 'utf8');\n // timingSafeEqual throws on a length mismatch; the length is not the secret.\n if (a.length !== b.length) return false;\n return timingSafeEqual(a, b);\n}\n","/**\n * How a client finds, probes and stops the local daemon: its port, its PID\n * file, its log, and the `GET /api/server` handshake. The CLI and the desktop\n * app both read these files, and they must read them the same way, or one of\n * them stops a daemon the other cannot see (ADR-0063 H2).\n *\n * Starting a daemon is not here: the CLI spawns its own Node binary and the\n * desktop app forks a utility process, and neither can do the other's.\n */\n\nimport http from 'http';\nimport { existsSync, readFileSync, unlinkSync } from 'fs';\nimport { homedir } from 'os';\nimport { join } from 'path';\nimport { globalDataDir } from './globalDataDir';\nimport { bearerHeaderValue, clearDaemonToken, readDaemonToken } from './daemonToken';\n\nexport const DEFAULT_DAEMON_PORT = 3742;\n\n/**\n * The daemon contract's number, answered by `GET /api/server` and compared by\n * a client before it drives a daemon it did not start (ADR-0063 H3). Raise it\n * whenever a body in `daemonContract.ts` or a socket frame changes in a way an\n * older client or daemon would misread, and whenever a client comes to need a\n * route, or a value on an existing route, that an older daemon lacks or\n * refuses: the same contract attaches, so such a client would drive that\n * daemon into a 404 or a refusal it cannot tell from a real one. A field only\n * added, which an older side ignores or does without, need not.\n *\n * 2: the desktop's card edits go to `plans.cardEdit`, which no contract-1\n * daemon serves.\n * 3: the desktop's Explorer reads the workspace folder itself, as repo `.`,\n * which a contract-2 daemon refuses in a folder that is not a repository.\n */\nexport const DAEMON_CONTRACT = 3;\n\n// Paths are read at call time, not import time: a test (and a shell that\n// re-exports HOME) changes the home directory after this module loads.\n\n/**\n * One PID file per port so a second daemon doesn't clobber the first one's\n * entry (and `stop --server --port N` kills the daemon the user meant).\n */\nexport function daemonPidFilePath(port: number): string {\n return pidFileIn(globalDataDir(), port);\n}\n\n/**\n * Pre-`.ordewell` install: a daemon spawned by old code wrote its PID file\n * here, so a stop falls back to it rather than orphaning that daemon behind a\n * path it doesn't know moved.\n */\nexport function legacyDaemonPidFilePath(port: number): string {\n return pidFileIn(join(homedir(), '.config', 'ordewell'), port);\n}\n\nfunction pidFileIn(dir: string, port: number): string {\n return port === DEFAULT_DAEMON_PORT ? join(dir, 'server.pid') : join(dir, `server-${port}.pid`);\n}\n\nexport function daemonLogPath(): string {\n return join(globalDataDir(), 'server.log');\n}\n\n/** The PID a file names, or undefined when it is missing or not a positive integer. */\nexport function readPidFile(file: string): number | undefined {\n try {\n const pid = parseInt(readFileSync(file, 'utf8').trim(), 10);\n return Number.isInteger(pid) && pid > 0 ? pid : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Which daemon a client should talk to: an explicit port, else ORDEWELL_PORT,\n * else the default. Lets a client target an isolated second daemon instead of\n * whatever is already on 3742.\n */\nexport function resolveDaemonPort(\n explicit?: string | number,\n env: NodeJS.ProcessEnv = process.env,\n): number {\n const parsedArg = typeof explicit === 'number' ? explicit : parseInt(explicit ?? '', 10);\n if (Number.isInteger(parsedArg) && parsedArg > 0) return parsedArg;\n const fromEnv = parseInt(env.ORDEWELL_PORT ?? '', 10);\n if (!isNaN(fromEnv) && fromEnv > 0) return fromEnv;\n return DEFAULT_DAEMON_PORT;\n}\n\n/**\n * True when this error means \"nothing was listening\", as opposed to \"the\n * server answered badly\" or \"the connection broke mid-flight\".\n *\n * The distinction is what makes an automatic retry safe. ECONNREFUSED is\n * refused at the TCP handshake, so the request was never delivered and cannot\n * have been half-applied — replaying it is not a second execution. ECONNRESET\n * and EPIPE are deliberately *not* included: those can arrive after the server\n * read the request, so a retry could start a second plan or a second run.\n */\nexport function isConnectionRefused(err: unknown): boolean {\n const code = (err as { code?: unknown } | null)?.code;\n if (code === 'ECONNREFUSED') return true;\n // The code survives a normal reject, but not every layer preserves it —\n // `String(err)` through a worker boundary keeps only the message.\n const message = err instanceof Error ? err.message : String(err ?? '');\n return message.includes('ECONNREFUSED');\n}\n\nexport interface DaemonHttpResponse {\n status: number;\n data: string;\n}\n\n/**\n * A GET to the daemon on `port`, carrying the token file's bearer when there\n * is one. No `Origin` is ever sent: admission refuses any request with one.\n */\nexport function daemonHttpGet(\n port: number,\n path: string,\n timeoutMs: number = 2000,\n): Promise<DaemonHttpResponse> {\n return httpGetWithToken(port, path, timeoutMs, readDaemonToken(port));\n}\n\nfunction httpGetWithToken(port: number, path: string, timeoutMs: number, token: string | undefined): Promise<DaemonHttpResponse> {\n const headers: Record<string, string> = token ? { Authorization: bearerHeaderValue(token) } : {};\n return new Promise((resolvePromise, reject) => {\n const req = http.get({ host: '127.0.0.1', port, path, timeout: timeoutMs, headers }, (res) => {\n // Decoded once the body is whole: a multi-byte character split across two\n // chunks would otherwise turn into U+FFFD at the seam.\n const chunks: Buffer[] = [];\n res.on('data', (chunk: Buffer) => { chunks.push(chunk); });\n res.on('end', () => resolvePromise({ status: res.statusCode || 0, data: Buffer.concat(chunks).toString('utf8') }));\n });\n req.on('error', reject);\n req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); });\n });\n}\n\nexport async function isDaemonRunning(port: number = DEFAULT_DAEMON_PORT): Promise<boolean> {\n try {\n const res = await daemonHttpGet(port, '/api/workspaces');\n // 401 still means a daemon owns this port. Reporting it as absent would\n // send a caller to spawn a second one that cannot bind; reporting it as\n // present lets the next real request answer with the token-file message.\n return res.status === 200 || res.status === 401;\n } catch {\n return false;\n }\n}\n\n/** What `GET /api/server` said about the process that owns the port. */\nexport interface DaemonIdentity {\n pid: number;\n /** The daemon's package version; absent from a daemon older than the field. */\n version?: string;\n /** The daemon contract it speaks (ADR-0063 H3); absent from a daemon older than the field. */\n contract?: number;\n /** Work is under way in a session it holds; absent from a daemon older than the field, which cannot say. */\n live?: boolean;\n}\n\nexport type DaemonProbe =\n | { kind: 'daemon'; identity: DaemonIdentity }\n /** Nothing owns the port: a stale PID file and token are safe to remove. */\n | { kind: 'unreachable' }\n /**\n * The daemon's own refusal of the token presented, or of none: it runs, but\n * for another user or install, or its token file has gone stale.\n */\n | { kind: 'unauthorized'; tokenPresented: boolean }\n /** Something owns the port, but it cannot prove which process it is. Never signal it. */\n | { kind: 'unverifiable' };\n\n// The daemon's 401 body names its token file; a stranger's 401 does not. That\n// is what tells \"a daemon that refuses us\" from \"some other server\".\nconst DAEMON_REFUSAL_MARK = 'bearer token';\n\n/**\n * Ask the daemon on `port` which process it is. A daemon older than this\n * route answers 404, and anything that is not a daemon answers whatever it\n * answers: both are `unverifiable`.\n */\nexport async function probeDaemon(port: number, timeoutMs: number = 2000): Promise<DaemonProbe> {\n let res: DaemonHttpResponse;\n let token = readDaemonToken(port);\n try {\n res = await httpGetWithToken(port, '/api/server', timeoutMs, token);\n if (res.status === 401 && res.data.includes(DAEMON_REFUSAL_MARK)) {\n const fresh = readDaemonToken(port);\n // A startup can bind between reading the old credential and sending\n // this request. Recheck once with a changed token; a stable refusal stays one.\n if (fresh !== undefined && fresh !== token) {\n token = fresh;\n res = await httpGetWithToken(port, '/api/server', timeoutMs, token);\n }\n }\n } catch (err) {\n return isConnectionRefused(err) ? { kind: 'unreachable' } : { kind: 'unverifiable' };\n }\n if (res.status === 401 && res.data.includes(DAEMON_REFUSAL_MARK)) {\n return { kind: 'unauthorized', tokenPresented: token !== undefined };\n }\n if (res.status !== 200) return { kind: 'unverifiable' };\n const identity = parseIdentity(res.data);\n return identity ? { kind: 'daemon', identity } : { kind: 'unverifiable' };\n}\n\nfunction parseIdentity(body: string): DaemonIdentity | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n return undefined;\n }\n if (typeof parsed !== 'object' || parsed === null) return undefined;\n const fields = parsed as Partial<Record<'pid' | 'version' | 'contract' | 'live', unknown>>;\n const { pid, version, contract, live } = fields;\n if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0) return undefined;\n return {\n pid,\n ...(typeof version === 'string' ? { version } : {}),\n ...(typeof contract === 'number' && Number.isInteger(contract) ? { contract } : {}),\n ...(typeof live === 'boolean' ? { live } : {}),\n };\n}\n\nexport type DaemonStopOutcome =\n | { kind: 'no-pid-file' }\n /** The file named no PID; it and the token were removed. */\n | { kind: 'unreadable-pid-file' }\n /** Something owns the port but cannot name itself: nothing was signalled. */\n | { kind: 'unverifiable'; filePid: number }\n /** Nothing was running; the stale PID file (and token) were removed. */\n | { kind: 'stale' }\n | { kind: 'stopped'; pid: number; filePid: number };\n\n/**\n * Stop the daemon on `port` the way `ordewell stop --server` does: signal the\n * PID the daemon itself reports, and only when the PID file can be checked\n * against it, so a stale file never terminates an unrelated process.\n */\nexport async function stopDaemonAt(port: number = DEFAULT_DAEMON_PORT): Promise<DaemonStopOutcome> {\n let pidFile = daemonPidFilePath(port);\n if (!existsSync(pidFile) && existsSync(legacyDaemonPidFilePath(port))) pidFile = legacyDaemonPidFilePath(port);\n if (!existsSync(pidFile)) return { kind: 'no-pid-file' };\n\n const filePid = readPidFile(pidFile);\n if (!filePid) {\n removeQuietly(pidFile);\n clearDaemonToken(port);\n return { kind: 'unreadable-pid-file' };\n }\n\n const probe = await probeDaemon(port);\n if (probe.kind === 'unreachable') {\n removeQuietly(pidFile);\n // A daemon killed outright never ran its own shutdown, so its token file\n // may still be sitting there looking usable.\n clearDaemonToken(port);\n return { kind: 'stale' };\n }\n if (probe.kind !== 'daemon') {\n // A PID from an unverified file may now belong to any process the OS has\n // recycled it for. Refuse rather than risk killing something unrelated.\n return { kind: 'unverifiable', filePid };\n }\n\n const pid = probe.identity.pid;\n try {\n process.kill(pid, 'SIGTERM');\n } catch (err) {\n const code = (err as Error & { code?: string }).code;\n if (code !== 'ESRCH') throw err;\n removeQuietly(pidFile);\n return { kind: 'stale' };\n }\n removeQuietly(pidFile);\n return { kind: 'stopped', pid, filePid };\n}\n\nfunction removeQuietly(file: string): void {\n try { unlinkSync(file); } catch { /* already gone */ }\n}\n","import { exec } from 'child_process';\nimport { promisify } from 'util';\nimport * as os from 'os';\nimport * as path from 'path';\n\nconst execAsync = promisify(exec);\n\n/**\n * GUI-launched processes (the VS Code extension host, a desktop-spawned web\n * server) often inherit a minimal PATH that misses user-level install dirs\n * (~/.local/bin, ~/.opencode/bin, nvm shims, …), so spawning `claude` or\n * `opencode` fails even though the user has them installed. This module\n * resolves an augmented PATH once per process: the interactive login shell's\n * PATH (which runs the user's profile, covering nvm/volta/asdf and friends)\n * merged over the current PATH, plus the well-known per-user bin dirs as a\n * final safety net when the login shell itself can't be queried. On Windows\n * there is no login shell to query, so the well-known dirs are the whole net —\n * see {@link windowsBinDirs}.\n *\n * {@link withPath} is the other half: handing the resolved PATH to a child\n * without accidentally giving it two.\n */\n\nconst LOGIN_SHELL_TIMEOUT_MS = 5000;\nconst PATH_MARKER = '__ORDEWELL_PATH__';\n\ntype ExecFn = (command: string, options?: { timeout?: number }) => Promise<{ stdout: string }>;\n\nconst defaultExec: ExecFn = async (command, options) => {\n const { stdout } = await execAsync(command, options);\n return { stdout: String(stdout) };\n};\n\nfunction posixBinDirs(): string[] {\n const home = os.homedir();\n return [\n path.join(home, '.local', 'bin'),\n path.join(home, '.opencode', 'bin'),\n path.join(home, '.claude', 'bin'),\n path.join(home, '.bun', 'bin'),\n path.join(home, '.volta', 'bin'),\n path.join(home, '.npm-global', 'bin'),\n path.join(home, 'bin'),\n '/usr/local/bin',\n '/opt/homebrew/bin',\n ];\n}\n\n/**\n * The Windows counterpart of {@link posixBinDirs}. There is no login shell to\n * ask on Windows, so this list is the only safety net when a runner was\n * installed after the host process started (the registry PATH a GUI-launched\n * VS Code inherited is a snapshot from launch time) or by an installer that\n * writes its own directory rather than amending PATH.\n *\n * The three built-in runners can each arrive by several routes, and the list\n * has to cover all of them or the picker greys out a CLI the user just\n * installed:\n *\n * - **PowerShell one-liner installers.** `irm https://claude.ai/install.ps1 |\n * iex` writes a native `claude.exe` to `%USERPROFILE%\\.local\\bin`, and\n * OpenCode's writes to `%USERPROFILE%\\.opencode\\bin`. `.local\\bin` was the\n * conspicuous omission — it is in {@link posixBinDirs}, where the same\n * installer puts the same binary, and its absence here meant the officially\n * documented Windows install of the flagship runner was the one Ordewell\n * could not find.\n * - **Node package managers.** npm's global prefix, and pnpm's and Yarn's,\n * which are not under it.\n * - **Windows package managers.** Scoop and Chocolatey shim directories, and\n * WinGet's `Links` folder for portable packages (distinct from\n * `WindowsApps`, which is MSIX only).\n * - **Version managers.** Volta spells its home `%LOCALAPPDATA%\\Volta` here,\n * not `~/.volta` as it does on POSIX.\n */\nfunction windowsBinDirs(env: NodeJS.ProcessEnv, home: string): string[] {\n const join = (...parts: string[]) => path.win32.join(...parts);\n const under = (base: string | undefined, ...parts: string[]) => (base ? [join(base, ...parts)] : []);\n const appData = env.APPDATA;\n const localAppData = env.LOCALAPPDATA;\n const programData = env.ProgramData;\n\n return [\n // Native per-user installers, PowerShell-driven and otherwise.\n join(home, '.local', 'bin'),\n join(home, '.opencode', 'bin'),\n join(home, '.claude', 'bin'),\n join(home, '.codex', 'bin'),\n ...under(localAppData, 'Programs', 'claude'),\n\n // Node package managers. npm's global prefix is `%APPDATA%\\npm`; the\n // literal spelling is kept as a fallback for a host that does not export\n // APPDATA (a service account, a stripped CI container).\n ...under(appData, 'npm'),\n join(home, 'AppData', 'Roaming', 'npm'),\n ...under(localAppData, 'pnpm'),\n ...under(localAppData, 'Yarn', 'bin'),\n join(home, '.bun', 'bin'),\n\n // Windows package managers.\n join(home, 'scoop', 'shims'),\n ...under(env.SCOOP, 'shims'),\n ...under(env.SCOOP_GLOBAL ?? programData, 'scoop', 'shims'),\n ...under(programData, 'chocolatey', 'bin'),\n // WinGet portable packages land here; `WindowsApps` only ever holds MSIX\n // aliases, so both are needed and neither substitutes for the other.\n ...under(localAppData, 'Microsoft', 'WinGet', 'Links'),\n ...under(localAppData, 'Microsoft', 'WindowsApps'),\n\n // Version managers. Volta's Windows home is not the POSIX `~/.volta`.\n ...under(localAppData, 'Volta', 'bin'),\n join(home, '.volta', 'bin'),\n ];\n}\n\n/**\n * Exported for test: the Windows arm cannot be exercised from a Linux CI box\n * through {@link augmentedPath}, which reads `process.platform` and the real\n * environment. Production always calls it through the no-argument form.\n */\nexport function wellKnownBinDirs(deps: { platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv; home?: string } = {}): string[] {\n const platform = deps.platform ?? process.platform;\n if (platform !== 'win32') return posixBinDirs();\n return [...new Set(windowsBinDirs(deps.env ?? process.env, deps.home ?? os.homedir()))];\n}\n\nasync function loginShellPath(execImpl: ExecFn): Promise<string | null> {\n if (process.platform === 'win32') return null;\n const shell = process.env.SHELL || '/bin/sh';\n try {\n // Markers isolate $PATH from any profile noise (motd, echo in .zprofile…).\n const { stdout } = await execImpl(\n `${shell} -l -c 'echo \"${PATH_MARKER}\\${PATH}${PATH_MARKER}\"'`,\n { timeout: LOGIN_SHELL_TIMEOUT_MS },\n );\n const match = stdout.match(new RegExp(`${PATH_MARKER}([^\\\\n]*)${PATH_MARKER}`));\n return match?.[1] || null;\n } catch {\n return null;\n }\n}\n\nlet cachedPath: Promise<string> | null = null;\n\n/**\n * The augmented PATH for spawning user-installed CLI tools. Resolved once per\n * process and cached (the login shell query costs ~50-200ms).\n */\nexport function augmentedPath(execImpl: ExecFn = defaultExec): Promise<string> {\n if (!cachedPath) {\n cachedPath = (async () => {\n const segments: string[] = [];\n const push = (p: string | null | undefined) => {\n if (!p) return;\n for (const seg of p.split(path.delimiter)) {\n if (seg && !segments.includes(seg)) segments.push(seg);\n }\n };\n push(process.env.PATH);\n push(await loginShellPath(execImpl));\n for (const dir of wellKnownBinDirs()) push(dir);\n return segments.join(path.delimiter);\n })();\n }\n return cachedPath;\n}\n\n/** Test seam: drop the per-process cache so the next call re-resolves. */\nexport function clearAugmentedPathCache(): void {\n cachedPath = null;\n}\n\n/**\n * The value `env` gives `name`, read as `platform` reads it: on Windows a name\n * in any case is the same variable, and the last spelling is the one\n * {@link withPath} keeps.\n */\nexport function envValue(env: Readonly<Record<string, string | undefined>>, name: string, platform: NodeJS.Platform = process.platform): string | undefined {\n if (platform !== 'win32') return env[name];\n const wanted = name.toLowerCase();\n let found: string | undefined;\n for (const [key, value] of Object.entries(env)) if (key.toLowerCase() === wanted) found = value;\n return found;\n}\n\n/**\n * Build a child environment whose PATH is `resolvedPath`, with exactly one\n * PATH-ish key in it.\n *\n * `{ ...process.env, PATH }` is the obvious spelling and it is wrong on\n * Windows. Node's `process.env` is a case-insensitive proxy, but spreading it\n * yields the OS's actual casing — `Path` — so adding `PATH` produces an\n * environment block carrying both. Which one the child sees is undefined, and\n * the loser is silently discarded. Every existing site passed the same value\n * under both keys, so the bug was latent rather than live; this makes it\n * impossible instead of unlikely.\n */\nexport function withPath(\n base: NodeJS.ProcessEnv,\n resolvedPath: string,\n overrides: Record<string, string> = {},\n platform: NodeJS.Platform = process.platform,\n): NodeJS.ProcessEnv {\n // Windows names a variable in any case, and Node hands a child only the first\n // spelling in sort order, so a host's `FOO` would silently beat an override's\n // `foo`: a later spelling has to replace an earlier one, not sit beside it,\n // whether the earlier came from `base` or from `overrides` itself.\n const name = platform === 'win32' ? (key: string) => key.toLowerCase() : (key: string) => key;\n const entries = new Map<string, [string, string | undefined]>();\n // Both sources are filtered, not just `base`: an `overrides` map carrying its\n // own PATH is exactly how the duplicate reappears.\n for (const source of [base, overrides]) {\n for (const [key, value] of Object.entries(source)) {\n if (key.toLowerCase() === 'path') continue;\n entries.set(name(key), [key, value]);\n }\n }\n const env: NodeJS.ProcessEnv = Object.fromEntries(entries.values());\n // Windows canonically spells it `Path`; POSIX requires `PATH`. Matching the\n // platform keeps anything downstream that reads the raw block unsurprised.\n env[platform === 'win32' ? 'Path' : 'PATH'] = resolvedPath;\n return env;\n}\n","/**\n * A dotted numeric version, compared the way a harness reports it: `2.1.304`.\n * A missing component counts as zero, so `2.1` and `2.1.0` are the same\n * version, and a `v` prefix is not part of it. A prerelease (`2.1.304-beta`)\n * sorts before the release it names, so a build the live checks did not cover\n * is never mistaken for the checked one.\n */\ninterface Version {\n numbers: number[];\n /** Everything after the first `-`, without the build suffix; null for a release. */\n prerelease: string | null;\n}\n\nfunction parse(version: string): Version | null {\n const match = /^v?(\\d+(?:\\.\\d+)*)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/i.exec(version.trim());\n if (!match) return null;\n return { numbers: match[1].split('.').map(Number), prerelease: match[2] ?? null };\n}\n\n/** The numeric components of a version, or null when it cannot be read. */\nexport function parseVersion(version: string): number[] | null {\n return parse(version)?.numbers ?? null;\n}\n\n/** Negative, zero or positive as `a` is older than, the same as, or newer than `b`; an unreadable version sorts oldest. */\nexport function compareVersions(a: string, b: string): number {\n const left = parse(a);\n const right = parse(b);\n if (!left || !right) return left ? 1 : right ? -1 : 0;\n const length = Math.max(left.numbers.length, right.numbers.length);\n for (let i = 0; i < length; i++) {\n const one = left.numbers[i] ?? 0;\n const other = right.numbers[i] ?? 0;\n if (one !== other) return one < other ? -1 : 1;\n }\n if (left.prerelease === right.prerelease) return 0;\n if (left.prerelease === null) return 1;\n if (right.prerelease === null) return -1;\n return left.prerelease < right.prerelease ? -1 : 1;\n}\n","import { ChildProcess, execFile, spawn as spawnProcess } from 'child_process';\nimport type { Socket } from 'net';\n\n/**\n * Stopping an agent process, on every platform.\n *\n * POSIX gets SIGTERM, then SIGKILL after a grace period — sent to the runner's\n * whole process group when it was started by {@link spawnInOwnGroup}, because\n * the direct child is a CLI and what kept running after Stop was everything it\n * had started: shells, MCP servers, test runs, dev servers. Windows has no signals — `ChildProcess.kill` calls TerminateProcess\n * on the direct child only — and on Windows the direct child is frequently not\n * the agent. A `claude.cmd` shim launched through cmd.exe puts an interpreter\n * between Ordewell and the `node cli.js` doing the work, so terminating the child\n * left the real agent running: still holding the workspace, still spending the\n * user's subscription, invisible to the surface that thought it had stopped.\n * `taskkill /T` walks the tree instead.\n *\n * Both paths are best-effort and idempotent by construction. A process that has\n * already exited is not an error here — every caller is on a dispose path.\n */\n\n/** Grace period between the polite stop and the forced one. */\nconst HARD_KILL_DELAY_MS = 5000;\n\nfunction isNoSuchProcess(err: unknown): boolean {\n return typeof err === 'object' && err !== null && 'code' in err && err.code === 'ESRCH';\n}\n\n/**\n * Whether `proc` has reported its own end. A process killed by a signal\n * reports `exitCode` null and `signalCode` set, and is as gone as one that\n * exited with a code. Only a reported value counts: an object that reports\n * neither is treated as running — the cost of a redundant kill is nothing,\n * the cost of skipping a live one is an orphaned agent.\n */\nfunction hasExited(proc: ChildProcess): boolean {\n return typeof proc.exitCode === 'number' || typeof proc.signalCode === 'string';\n}\n\nexport interface KillTreeDeps {\n platform?: NodeJS.Platform;\n /** Runs `taskkill`. Injected so the Windows path is testable off Windows. */\n execFileImpl?: (file: string, args: string[], cb: (err: Error | null) => void) => void;\n /** Schedules the forced kill. Injected so tests need no timers. */\n setTimeoutImpl?: (fn: () => void, ms: number) => { unref?: () => void };\n clearTimeoutImpl?: (handle: unknown) => void;\n /** Signals a pid, or a process group as its negated id. Injected so the group path needs no real processes. */\n killImpl?: (pid: number, signal: NodeJS.Signals | 0) => void;\n}\n\n/** Processes {@link spawnInOwnGroup} made group leaders. */\nconst groupLeaders = new WeakSet<ChildProcess>();\n/** Leaders already signalled: a group signal leaves `proc.killed` false, so it cannot say. */\nconst stopping = new WeakSet<ChildProcess>();\n/**\n * Groups led by a runner, by id, for the host's teardown. Kept while the group\n * still has members, which a leader's exit does not end: a runner that crashes\n * leaves its shells and dev servers behind, and those are what teardown has to\n * reach. Dropped when the group is empty (its id is recyclable then, and no\n * longer ours to vouch for) or when {@link killTree} takes it over.\n */\nconst ownGroups = new Map<number, ChildProcess>();\nlet hostTeardownHooked = false;\n/** What stops each runner group if the host dies without running any of its code; see {@link watchForHostDeath}. */\nconst hostWatches = new Map<number, ChildProcess>();\n/** Told of each runner group as it starts, so a session lease records it at once (ADR-0049). */\nconst groupStartListeners = new Set<() => void>();\n/** What else goes with the host: see {@link onHostTeardown}. */\nconst teardownListeners = new Set<() => void>();\n\n/**\n * Start a runner as the leader of a new process group, so {@link killTree}\n * reaches everything it starts. `spawn` is handed the `detached` flag to pass\n * to Node, which on POSIX is what makes a child a group (and session) leader.\n * Stdio pipes and the host's event loop are unaffected; only `unref` changes\n * the latter, and nothing here calls it.\n *\n * Not on Windows: there `detached` gives the child a console of its own, and\n * `taskkill /T` already walks the tree.\n */\nexport function spawnInOwnGroup(spawn: (detached: boolean) => ChildProcess, platform: NodeJS.Platform = process.platform): ChildProcess {\n if (platform === 'win32') return spawn(false);\n const proc = spawn(true);\n const pgid = proc.pid;\n // No pid: the spawn failed, and its 'error' event reports that.\n if (typeof pgid !== 'number') return proc;\n groupLeaders.add(proc);\n ownGroups.set(pgid, proc);\n if (proc instanceof ChildProcess) watchForHostDeath(pgid);\n // The leader's exit does not end the group: the shells, MCP servers and dev\n // servers it started outlive it, and those are exactly what Stop and host\n // teardown still have to reach. The entry is dropped only once the group is\n // empty — an id with no members left can be recycled, and is no longer ours\n // to signal.\n proc.once('exit', () => { if (!groupHasMembers(pgid)) forgetGroup(proc, pgid); });\n hookHostTeardown();\n for (const listener of groupStartListeners) listener();\n return proc;\n}\n\n/**\n * Stop `pgid` when this host is gone, however it went. SIGKILL and a crash run\n * none of its code, so nothing in it can do this, and a runner in a group of\n * its own would go on editing, committing and spending with nobody to see\n * (ADR-0049 L3). A shell waits on a pipe only this host writes: the kernel\n * closes that as the host dies, and the shell stops the group as `killTree`\n * would. A line down the pipe is a host going politely, which has asked already\n * and cannot stay for the forced stop, so that one is all the shell owes. Started\n * in `/` so no worktree is held open.\n */\nfunction watchForHostDeath(pgid: number): void {\n const group = `-- -${pgid}`;\n const seconds = HARD_KILL_DELAY_MS / 1000;\n const stop = `read _ || kill -s TERM ${group} 2>/dev/null; i=0; while [ \"$i\" -lt ${seconds} ] && kill -s 0 ${group} 2>/dev/null; do sleep 1; i=$((i + 1)); done; kill -s 0 ${group} 2>/dev/null && kill -s KILL ${group} 2>/dev/null`;\n const watch = spawnProcess('/bin/sh', ['-c', stop], { detached: true, cwd: '/', stdio: ['pipe', 'ignore', 'ignore'] });\n // No shell to watch with leaves the runner as it was; the lease still names it.\n watch.on('error', () => { hostWatches.delete(pgid); });\n watch.stdin?.on('error', () => undefined);\n (watch.stdin as Socket | null)?.unref();\n watch.unref();\n hostWatches.set(pgid, watch);\n}\n\nfunction endHostWatch(pgid: number): void {\n hostWatches.get(pgid)?.kill('SIGKILL');\n hostWatches.delete(pgid);\n}\n\n/**\n * The process groups this host's runners lead that still have members. A\n * session lease records them (ADR-0049): the teardown below cannot run for a\n * host killed outright, and {@link watchForHostDeath} may not have finished as\n * a new host looks. Asked on every heartbeat, which is also where a group that\n * outlived its leader and has since emptied is let go.\n */\nexport function runnerGroups(): number[] {\n for (const [pgid, proc] of ownGroups) {\n if (hasExited(proc) && !groupHasMembers(pgid)) forgetGroup(proc, pgid);\n }\n return [...ownGroups.keys()];\n}\n\n/** Hear of each runner group {@link spawnInOwnGroup} starts; the returned function stops it. */\nexport function onRunnerGroupStarted(listener: () => void): () => void {\n groupStartListeners.add(listener);\n return () => { groupStartListeners.delete(listener); };\n}\n\n/**\n * Stop something else as the host goes, with its runner groups but not among\n * them: {@link runnerGroups} never names it, so no lease is held by it. Here\n * rather than in a hook of the caller's, because two signal hooks would each\n * read the other as the host's own handler, and neither would end the host.\n * The returned function stops it being called. Nothing runs for a host killed\n * outright, as for the groups.\n */\nexport function onHostTeardown(stop: () => void): () => void {\n teardownListeners.add(stop);\n hookHostTeardown();\n return () => { teardownListeners.delete(stop); };\n}\n\n/** Whether a process answers to `pid`: one owned by another user, which refuses the signal, is alive too. */\nexport function processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n return (err as NodeJS.ErrnoException).code === 'EPERM';\n }\n}\n\n/** Whether any process is left in the group `pgid` leads. */\nexport function groupAlive(pgid: number): boolean {\n return groupHasMembers(pgid);\n}\n\n/** Whether any process still answers to `pgid`, as `kill(2)` sees it. */\nfunction groupHasMembers(pgid: number, killImpl: (pid: number, signal: 0) => void = (pid, signal) => { process.kill(pid, signal); }): boolean {\n try {\n killImpl(-pgid, 0);\n return true;\n } catch (err) {\n return !isNoSuchProcess(err);\n }\n}\n\n/**\n * An empty group's id is recyclable, so it is no longer ours to signal: from\n * here on `proc` is an ordinary exited process to {@link killTree}.\n */\nfunction forgetGroup(proc: ChildProcess, pgid: number): void {\n if (ownGroups.get(pgid) === proc) ownGroups.delete(pgid);\n groupLeaders.delete(proc);\n endHostWatch(pgid);\n}\n\n/**\n * A detached runner has left the terminal's foreground group, so Ctrl-C (or a\n * closed terminal) no longer reaches it — the host has to pass that on to the\n * groups it leads. Polite only, and not again to a group already asked: a\n * host disposing its sessions on the way out has just sent SIGTERM, and a\n * second one reads to some CLIs as \"quit without cleaning up\".\n */\nfunction hookHostTeardown(): void {\n if (hostTeardownHooked) return;\n hostTeardownHooked = true;\n const stopAll = () => {\n for (const [pgid, leader] of ownGroups) {\n if (stopping.has(leader)) continue;\n if (hasExited(leader) && !groupHasMembers(pgid)) continue;\n try { process.kill(-pgid, 'SIGTERM'); } catch { /* already gone */ }\n }\n ownGroups.clear();\n for (const watch of hostWatches.values()) watch.stdin?.write('\\n');\n hostWatches.clear();\n for (const stop of teardownListeners) {\n try { stop(); } catch { /* already gone */ }\n }\n teardownListeners.clear();\n };\n process.on('exit', stopAll);\n for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP'] as const) {\n const onSignal = () => {\n stopAll();\n // A host with a handler of its own decides how to exit. One without was\n // relying on the default, which listening has replaced, so this listener\n // steps aside and the signal is raised again to end the host as before.\n if (process.listenerCount(signal) > 1) return;\n process.removeListener(signal, onSignal);\n process.kill(process.pid, signal);\n };\n process.on(signal, onSignal);\n }\n}\n\nfunction defaultExecFile(file: string, args: string[], cb: (err: Error | null) => void): void {\n execFile(file, args, (err) => cb(err ?? null));\n}\n\n/**\n * Terminate `proc` and everything it started.\n *\n * Returns immediately; the forced follow-up (SIGKILL, or `taskkill /F`) is\n * scheduled and unref'd, so a disposed session is never the reason the host\n * process refuses to exit.\n */\nexport function killTree(proc: ChildProcess | null, deps: KillTreeDeps = {}): void {\n if (!proc) return;\n\n const platform = deps.platform ?? process.platform;\n // A group leader is the exception: its group outlives it, so a crashed\n // runner's shells, dev servers and MCP servers are still there to stop even\n // though the runner is not. That case falls through to the group path below.\n if (!groupLeaders.has(proc) && (proc.killed || hasExited(proc))) return;\n\n const setTimeoutImpl = deps.setTimeoutImpl ?? ((fn, ms) => setTimeout(fn, ms) as unknown as { unref?: () => void });\n const clearTimeoutImpl = deps.clearTimeoutImpl ?? ((h) => clearTimeout(h as NodeJS.Timeout));\n\n if (platform === 'win32') {\n // No pid means the process never started; there is no tree to walk.\n if (typeof proc.pid !== 'number') return;\n const pid = proc.pid;\n const run = deps.execFileImpl ?? defaultExecFile;\n\n // `/T` is the whole point: without it this is the TerminateProcess call\n // that already failed to reach the agent. The unforced pass only asks a\n // window to close, so a console process — every runner — refuses it, and\n // is forced at once: left for the grace, it would go on writing to a\n // workspace the user has stopped it in, and holding it from removal.\n // `/F` follows on the timer too, for one that agreed and did not go.\n const force = () => run('taskkill', ['/pid', String(pid), '/T', '/F'], () => { /* already gone */ });\n // A pass that failed because the process had already gone forces nothing:\n // its pid may be another's by then.\n run('taskkill', ['/pid', String(pid), '/T'], (err) => { if (err && !hasExited(proc)) force(); });\n const hardKill = setTimeoutImpl(force, HARD_KILL_DELAY_MS);\n hardKill.unref?.();\n proc.once('exit', () => clearTimeoutImpl(hardKill));\n return;\n }\n\n if (groupLeaders.has(proc) && typeof proc.pid === 'number') {\n if (stopping.has(proc)) return;\n const pgid = proc.pid;\n const killImpl = deps.killImpl ?? ((pid: number, signal: NodeJS.Signals | 0) => { process.kill(pid, signal); });\n // Never signal a group we can't vouch for. While the leader lives its pid\n // holds the id; once it is gone, only a member still in the group does,\n // and an empty group's id may already be a stranger's. So once the leader\n // has exited, every signal is preceded by asking.\n const vouched = () => !hasExited(proc) || groupHasMembers(pgid, killImpl);\n if (!vouched()) {\n forgetGroup(proc, pgid);\n return;\n }\n stopping.add(proc);\n // Taken over here, so the host's teardown and this path do not both signal\n // it (from here on `stopping`, not `ownGroups`, is what says so).\n ownGroups.delete(pgid);\n const signalGroup = (signal: NodeJS.Signals) => {\n try {\n killImpl(-pgid, signal);\n } catch {\n try { proc.kill(signal); } catch { /* already gone */ }\n }\n };\n signalGroup('SIGTERM');\n // Survives the leader's exit: what it started can outlive it, and a\n // process ignoring SIGTERM is exactly the one that does. Asked again when\n // it fires, so a group that emptied during the grace period is left alone;\n // a stranger taking the id between that probe and the signal is the\n // residual risk.\n const hardKill = setTimeoutImpl(() => {\n if (vouched()) signalGroup('SIGKILL');\n endHostWatch(pgid);\n }, HARD_KILL_DELAY_MS);\n hardKill.unref?.();\n if (!hasExited(proc)) {\n proc.once('exit', () => { if (!groupHasMembers(pgid, killImpl)) clearTimeoutImpl(hardKill); });\n }\n return;\n }\n\n try {\n proc.kill('SIGTERM');\n const hardKill = setTimeoutImpl(() => {\n try { proc.kill('SIGKILL'); } catch { /* already gone */ }\n }, HARD_KILL_DELAY_MS);\n hardKill.unref?.();\n proc.once('exit', () => clearTimeoutImpl(hardKill));\n } catch {\n // Process already gone — nothing to clean up.\n }\n}\n","import * as fs from 'fs';\nimport * as path from 'path';\nimport { randomUUID } from 'crypto';\n\nexport const STATE_DIR = '.ordewell';\n\nexport function ensureDir(dir: string): void {\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n}\n\n/**\n * Replace `filePath` with `content` in one step. Writing in place truncates\n * the old bytes first, so a crash, power loss or a full disk mid-write leaves\n * an empty or half-written file where the last good one was — silent loss of\n * the only copy, for a session or a saved plan. The bytes go to a fresh temp\n * file beside the target and a rename swaps it in; within one directory that\n * is atomic, so a reader sees the old file or the new one.\n */\nexport function writeFileAtomic(filePath: string, content: string): void {\n const dir = path.dirname(filePath);\n ensureDir(dir);\n // Same directory, so the rename stays on one filesystem; random, so the name\n // can never collide with another process writing the same file.\n const tempPath = path.join(dir, `.${path.basename(filePath)}.${randomUUID()}.tmp`);\n fs.writeFileSync(tempPath, content, { flag: 'wx' });\n try {\n fs.renameSync(tempPath, filePath);\n } catch (err) {\n try {\n fs.unlinkSync(tempPath);\n } catch {\n // Already gone; the rename error is the one worth reporting.\n }\n throw err;\n }\n}\n\nexport function getStateDir(baseDir?: string): string {\n return path.join(baseDir ?? process.cwd(), STATE_DIR);\n}\n\nconst IGNORE_FILE = '.gitignore';\n\n/**\n * Ignores the state directory's contents except this file and `skills/`, so a\n * project's skills are committed and reach every task worktree through git —\n * the bootstrap never links `.ordewell/` (ADR-0013). Plans and sessions stay\n * uncommittable without touching a file the developer wrote; editing their\n * root `.gitignore` would be the intrusive version of this.\n */\nexport const STATE_DIR_IGNORE = '*\\n!.gitignore\\n!skills/\\n!skills/**\\n';\n\n/** What older builds wrote: everything ignored, the rules file included. */\nconst LEGACY_IGNORES = new Set(['*', '*\\n']);\n\n/**\n * Idempotent, and never overwrites a file the developer customised (to commit\n * their plans deliberately, say). Only the exact legacy rule is upgraded.\n */\nexport function ensureStateDirIgnored(baseDir?: string): void {\n const dir = getStateDir(baseDir);\n ensureDir(dir);\n const file = path.join(dir, IGNORE_FILE);\n try {\n // `wx` rather than an existsSync check: two surfaces can save concurrently,\n // and the loser of that race must not clobber the winner's file.\n fs.writeFileSync(file, STATE_DIR_IGNORE, { flag: 'wx' });\n return;\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;\n }\n if (LEGACY_IGNORES.has(fs.readFileSync(file, 'utf8'))) fs.writeFileSync(file, STATE_DIR_IGNORE);\n}\n","import * as path from 'path';\nimport { getStateDir } from './fsHelpers';\n\n/**\n * Where sessions keep their state, apart from the store that reads it: a\n * client that is no host (the desktop app's main process) finds a session's\n * lease here without loading the plan model the store brings with it.\n */\n\nconst SESSIONS_SUBDIR = 'sessions';\n\nexport function getSessionsDir(baseDir?: string): string {\n return path.join(getStateDir(baseDir), SESSIONS_SUBDIR);\n}\n\n/**\n * A path segment for an id that came from outside — a session id from a URL,\n * a task id a planner wrote. A plain id is used as is; anything that could\n * climb out of its directory, or is not portable as a file name, is hex-encoded.\n */\nexport function idSegment(id: string): string {\n return /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,127}$/.test(id) ? id : `~${Buffer.from(id, 'utf-8').toString('hex')}`;\n}\n","import * as fs from 'fs';\nimport * as path from 'path';\nimport { processAlive } from './processTree';\nimport { getSessionsDir, idSegment } from './sessionDir';\n\n/**\n * A session's lease file as any process reads it (ADR-0049): the record a\n * host writes, and the judgement of whether that host still lives. The hosts\n * themselves take and refresh it in `services/sessionLease`; this half is\n * apart so a client that is no host can read it through `daemon-client`.\n */\n\n/**\n * A lease not refreshed for this long is stale: its holder is gone, or its pid\n * now names another process. Several heartbeats, so a host whose event loop is\n * busy for a moment keeps its session.\n */\nexport const LEASE_STALE_MS = 60_000;\n\n/**\n * What kind of process a host is, for the words a refusal names it in and the\n * surface the planner is told its user has. `ownerPid` is the TUI a private\n * daemon serves; `app` marks the daemon the desktop app forked.\n */\nexport type LeaseHostKind =\n | { kind: 'daemon'; port: number; ownerPid?: number; app?: 'desktop' }\n | { kind: 'vscode' };\n\n/** A session's lease as its file records it. */\nexport interface SessionLeaseRecord {\n /** Minted once per host, so a restarted process at a reused pid is not mistaken for the holder. */\n hostId: string;\n pid: number;\n host?: LeaseHostKind;\n /** When this host took the lease. */\n since: string;\n /** Refreshed every heartbeat; stale past {@link LEASE_STALE_MS}. */\n heartbeatAt: string;\n /**\n * The process groups of the runners the holder had started and not seen\n * end. A host killed outright cannot stop them, and they go on writing in\n * the session's worktrees, so a takeover waits for them.\n */\n runnerGroups: number[];\n /**\n * Whether the holder's run is live: an attempt at work, a start pending, a\n * landing or Merge all under way. Much of that is only in the holder's\n * memory, so it says it here, for another host's landing interlock\n * (ADR-0062 G7). Absent from a holder that predates it.\n */\n runLive?: boolean;\n}\n\nconst LEASE_FILE = 'lease.json';\n\n/** A root session's lease file; a child writes none (ADR-0055 D13). */\nexport function leaseFile(sessionId: string, workspace: string): string {\n return path.join(getSessionsDir(workspace), idSegment(sessionId), LEASE_FILE);\n}\n\nfunction isRecord(value: unknown): value is SessionLeaseRecord {\n if (typeof value !== 'object' || value === null) return false;\n const r = value as Record<string, unknown>;\n return typeof r.hostId === 'string' && typeof r.pid === 'number' && typeof r.since === 'string'\n && typeof r.heartbeatAt === 'string' && Array.isArray(r.runnerGroups) && r.runnerGroups.every((g) => typeof g === 'number');\n}\n\n/** The record on disk; null when there is none, or none any host could have written (every write is a rename). */\nexport function readLeaseRecord(file: string): SessionLeaseRecord | null {\n let raw: string;\n try {\n raw = fs.readFileSync(file, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;\n throw err;\n }\n try {\n const parsed: unknown = JSON.parse(raw);\n return isRecord(parsed) ? parsed : null;\n } catch {\n return null;\n }\n}\n\n/** Whether the host that wrote `record` lives, judged by its heartbeat and its pid. */\nexport function holderLives(record: SessionLeaseRecord, now: number, alive: (pid: number) => boolean): boolean {\n const beat = Date.parse(record.heartbeatAt);\n if (Number.isNaN(beat) || now - beat > LEASE_STALE_MS) return false;\n return alive(record.pid);\n}\n\nexport interface LiveHolderProbes {\n now?: () => number;\n alive?: (pid: number) => boolean;\n}\n\n/**\n * The host that holds `sessionId` in `workspace` now, or null when none does.\n * For a client that holds no lease of its own and only needs to know whom to\n * reach: it does not weigh orphaned runners, which only a host taking over must.\n */\nexport function readLiveHolder(sessionId: string, workspace: string, probes: LiveHolderProbes = {}): SessionLeaseRecord | null {\n const record = readLeaseRecord(leaseFile(sessionId, workspace));\n if (!record) return null;\n return holderLives(record, (probes.now ?? Date.now)(), probes.alive ?? processAlive) ? record : null;\n}\n"],"mappings":";AAAA,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,YAAY,QAAQ;AAOb,SAAS,gBAAwB;AACtC,SAAY,UAAQ,WAAQ,GAAG,WAAW;AAC5C;AAEA,IAAI,WAAW;AAcR,SAAS,sBAA4B;AAC1C,MAAI,SAAU;AACd,aAAW;AAEX,QAAM,SAAc,UAAQ,WAAQ,GAAG,WAAW,UAAU;AAC5D,MAAI,CAAI,cAAW,MAAM,EAAG;AAC5B,QAAM,SAAS,cAAc;AAE7B,QAAM,WAAW,CAAC,SAAuB;AACvC,UAAM,UAAe,UAAK,QAAQ,IAAI;AACtC,UAAM,UAAe,UAAK,QAAQ,IAAI;AACtC,QAAI,CAAI,cAAW,OAAO,KAAQ,cAAW,OAAO,EAAG;AACvD,QAAI;AACF,MAAG,aAAU,QAAQ,EAAE,WAAW,KAAK,CAAC;AACxC,MAAG,gBAAa,SAAS,OAAO;AAAA,IAClC,SAAS,KAAK;AACZ,cAAQ,KAAK,kBAAkB,OAAO,OAAO,OAAO,KAAK,OAAO,GAAG,CAAC,EAAE;AAAA,IACxE;AAAA,EACF;AAEA,WAAS,eAAe;AACxB,WAAS,MAAM;AACjB;;;ACjDA,SAAS,WAAW,aAAAA,YAAW,UAAU,YAAY,YAAY,iBAAiB;AAClF,SAAS,UAAU,SAAS,QAAAC,aAAY;AACxC,SAAS,mBAAmB;AAa5B,IAAM,WAAW;AACjB,IAAM,YAAY;AAIlB,IAAM,cAAc,QAAQ,aAAa;AAGlC,SAAS,iBA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AO,EAAE,QAAQ,YAAY,OAAO,EAAE,UAAU,YAClF,OAAO,EAAE,gBAAgB,YAAY,MAAM,QAAQ,EAAE,YAAY,KAAK,EAAE,aAAa,MAAM,CAAC,MAAM,OAAO,MAAM,QAAQ;AAC9H;AAGO,SAAS,gBAAgB,MAAyC;AACvE,MAAI;AACJ,MAAI;AACF,UAAS,iBAAa,MAAM,MAAM;AAAA,EACpC,SAAS,KAAK;AACZ,QAAK,IAA8B,SAAS,SAAU,QAAO;AAC7D,UAAM;AAAA,EACR;AACA,MAAI;AACF,UAAM,SAAkB,KAAK,MAAM,GAAG;AACtC,WAAO,SAAS,MAAM,IAAI,SAAS;AAAA,EACrC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGO,SAAS,YAAY,QAA4B,KAAa,OAA0C;AAC7G,QAAM,OAAO,KAAK,MAAM,OAAO,WAAW;AAC1C,MAAI,OAAO,MAAM,IAAI,KAAK,MAAM,OAAO,eAAgB,QAAO;AAC9D,SAAO,MAAM,OAAO,GAAG;AACzB;AAYO,SAAS,eAAe,WAAmB,WAAmB,SAA2B,CAAC,GAA8B;AAC7H,QAAM,SAAS,gBAAgB,UAAU,WAAW,SAAS,CAAC;AAC9D,MAAI,CAAC,OAAQ,QAAO;AACpB,SAAO,YAAY,SAAS,OAAO,OAAO,KAAK,KAAK,GAAG,OAAO,SAAS,YAAY,IAAI,SAAS;AAClG;","names":["mkdirSync","join","randomBytes","unlinkSync","join","join","randomBytes","unlinkSync","existsSync","readFileSync","unlinkSync","homedir","join","join","homedir","readFileSync","path","existsSync","unlinkSync","os","path","join","fs","path","path","fs","path"]}
|
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
loopSpec,
|
|
8
8
|
scriptBodyErrors,
|
|
9
9
|
splitLines
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-4OARA73Z.mjs";
|
|
11
11
|
import {
|
|
12
12
|
DEFAULT_RUNNERS,
|
|
13
13
|
TASK_KINDS,
|
|
@@ -22,7 +22,7 @@ import {
|
|
|
22
22
|
taskKinds,
|
|
23
23
|
unknownTypeRefusal,
|
|
24
24
|
writtenForbiddenFields
|
|
25
|
-
} from "./chunk-
|
|
25
|
+
} from "./chunk-5ETS2NIB.mjs";
|
|
26
26
|
|
|
27
27
|
// src/services/JsonExtractor.ts
|
|
28
28
|
var PLAN_ENVELOPE_KEY = "tasks";
|
|
@@ -640,7 +640,7 @@ function scopeOverlaps(tasks) {
|
|
|
640
640
|
for (const b of scoped.slice(i + 1)) {
|
|
641
641
|
if (ordered(tasks, a, b)) continue;
|
|
642
642
|
const declared = (a.scope?.paths ?? []).flatMap((one) => (b.scope?.paths ?? []).filter((other) => pathsMeet(one, other)).map((other) => narrower(one, other)));
|
|
643
|
-
if (declared.length > 0) said.push(`Tasks "${a.title}" and "${b.title}" both declare ${[...new Set(declared)].join(", ")}, and nothing orders them:
|
|
643
|
+
if (declared.length > 0) said.push(`Tasks "${a.title}" and "${b.title}" both declare ${[...new Set(declared)].join(", ")}, and nothing orders them: name one owner, or, where one consumes what the other makes, give it a dependency on that one.`);
|
|
644
644
|
for (const name of a.scope?.provides ?? []) {
|
|
645
645
|
if (b.scope?.provides?.includes(name)) said.push(`Tasks "${a.title}" and "${b.title}" both provide "${name}", and nothing orders them: name one owner.`);
|
|
646
646
|
}
|
|
@@ -1327,4 +1327,4 @@ export {
|
|
|
1327
1327
|
validatePlanTasks,
|
|
1328
1328
|
looksLikePlanAttempt
|
|
1329
1329
|
};
|
|
1330
|
-
//# sourceMappingURL=chunk-
|
|
1330
|
+
//# sourceMappingURL=chunk-FOGPFLRO.mjs.map
|