@gate-forge/cli 0.6.0 → 0.6.2
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/README.md +50 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +6 -1
- package/dist/cli.js.map +1 -1
- package/dist/commands/blocking.d.ts +3 -0
- package/dist/commands/blocking.d.ts.map +1 -1
- package/dist/commands/blocking.js +38 -2
- package/dist/commands/blocking.js.map +1 -1
- package/dist/commands/check.d.ts +40 -0
- package/dist/commands/check.d.ts.map +1 -1
- package/dist/commands/check.js +35 -1
- package/dist/commands/check.js.map +1 -1
- package/dist/commands/init.d.ts.map +1 -1
- package/dist/commands/init.js +42 -8
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/pre-commit.d.ts +5 -0
- package/dist/commands/pre-commit.d.ts.map +1 -0
- package/dist/commands/pre-commit.js +213 -0
- package/dist/commands/pre-commit.js.map +1 -0
- package/dist/commands/test-gates.d.ts +51 -0
- package/dist/commands/test-gates.d.ts.map +1 -1
- package/dist/commands/test-gates.js +26 -8
- package/dist/commands/test-gates.js.map +1 -1
- package/dist/execution.d.ts +1 -0
- package/dist/execution.d.ts.map +1 -1
- package/dist/execution.js +9 -0
- package/dist/execution.js.map +1 -1
- package/dist/git-hooks.d.ts +7 -2
- package/dist/git-hooks.d.ts.map +1 -1
- package/dist/git-hooks.js +48 -12
- package/dist/git-hooks.js.map +1 -1
- package/dist/input-snapshot.d.ts +5 -1
- package/dist/input-snapshot.d.ts.map +1 -1
- package/dist/input-snapshot.js +6 -3
- package/dist/input-snapshot.js.map +1 -1
- package/dist/pipeline.d.ts.map +1 -1
- package/dist/pipeline.js +34 -8
- package/dist/pipeline.js.map +1 -1
- package/dist/runtime.d.ts +114 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/runtime.js +682 -0
- package/dist/runtime.js.map +1 -0
- package/dist/staged-candidate.d.ts +1 -1
- package/dist/staged-candidate.d.ts.map +1 -1
- package/dist/staged-candidate.js +5 -4
- package/dist/staged-candidate.js.map +1 -1
- package/package.json +9 -9
package/dist/runtime.js
ADDED
|
@@ -0,0 +1,682 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Staged-runtime supervision (plan 2026-09-21 witnessed pre-commit).
|
|
3
|
+
*
|
|
4
|
+
* Prepares a materialized staged candidate for execution and owns the
|
|
5
|
+
* candidate's application/database/worker processes end to end:
|
|
6
|
+
*
|
|
7
|
+
* - `prepare` runs the tracked preparation command INSIDE the checkout
|
|
8
|
+
* (frozen/offline installs, builds) with a bounded timeout and
|
|
9
|
+
* captured logs; `prepare.reuse` names the dependency directories
|
|
10
|
+
* explicitly allowed to be LINKED from the user repository — the only
|
|
11
|
+
* sanctioned dependency bridge (the old unconditional node_modules
|
|
12
|
+
* symlink is gone).
|
|
13
|
+
* - `services` start candidate-owned processes from the checkout bytes
|
|
14
|
+
* (never the worktree), each in its own process group, readiness-
|
|
15
|
+
* probed, log-captured, and cleaned up on every exit path.
|
|
16
|
+
* - The attested target service is fronted by the gate's loopback
|
|
17
|
+
* attestation proxy (GF-13): the stamped environment marker binds the
|
|
18
|
+
* witnessed UI/adapter reads to ONE environment, and that environment
|
|
19
|
+
* is the one this module started from the frozen candidate.
|
|
20
|
+
*
|
|
21
|
+
* The document (`.gateforge/runtime.yml`) is security-sensitive: it is
|
|
22
|
+
* hashed into the trusted policy digest and the authenticated input
|
|
23
|
+
* snapshot, so a candidate cannot change its own runtime commands and
|
|
24
|
+
* approve the change in the same commit.
|
|
25
|
+
*/
|
|
26
|
+
import { createHash } from 'node:crypto';
|
|
27
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
28
|
+
import net from 'node:net';
|
|
29
|
+
import { existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, symlinkSync, } from 'node:fs';
|
|
30
|
+
import { isAbsolute, join, relative, resolve } from 'node:path';
|
|
31
|
+
import { parse as parseYaml } from 'yaml';
|
|
32
|
+
import { DEFAULT_PREPARE_TIMEOUT_SECONDS, DEFAULT_READY_TIMEOUT_SECONDS, RuntimeConfigSchema, isNormalizedRepoRelativePath, sha256Canonical, } from '@gate-forge/core';
|
|
33
|
+
import { startAttestationProxy } from '@gate-forge/pack-playwright';
|
|
34
|
+
import { resolveStateDir } from './state.js';
|
|
35
|
+
/** Operator env vars always available to preparation commands and services. */
|
|
36
|
+
const RUNTIME_ENV_BASE = ['PATH', 'HOME', 'LANG', 'LC_ALL', 'SHELL', 'TMPDIR'];
|
|
37
|
+
/** Grace period between SIGTERM and SIGKILL when stopping a service group. */
|
|
38
|
+
const SERVICE_STOP_GRACE_MS = 5_000;
|
|
39
|
+
/** Delay between readiness probe iterations. */
|
|
40
|
+
const READY_POLL_INTERVAL_MS = 200;
|
|
41
|
+
/**
|
|
42
|
+
* Every live child this module spawned (prepare + services). The registry
|
|
43
|
+
* backs the interruption path: a SIGINT arriving BEFORE the services
|
|
44
|
+
* handle exists still tears the detached process groups down.
|
|
45
|
+
*/
|
|
46
|
+
const activeChildren = new Set();
|
|
47
|
+
/**
|
|
48
|
+
* Registers a spawned child for interruption teardown and forgets it
|
|
49
|
+
* once it exits.
|
|
50
|
+
*
|
|
51
|
+
* Args:
|
|
52
|
+
* child: the freshly spawned child.
|
|
53
|
+
*/
|
|
54
|
+
function trackChild(child) {
|
|
55
|
+
activeChildren.add(child);
|
|
56
|
+
const forget = () => {
|
|
57
|
+
activeChildren.delete(child);
|
|
58
|
+
};
|
|
59
|
+
child.once('exit', forget);
|
|
60
|
+
child.once('error', forget);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Tears down EVERY registered child's process group (interruption path).
|
|
64
|
+
*
|
|
65
|
+
* Returns:
|
|
66
|
+
* Promise<void>: resolved when all groups have been signalled.
|
|
67
|
+
*/
|
|
68
|
+
export async function stopRuntimeChildren() {
|
|
69
|
+
for (const child of [...activeChildren])
|
|
70
|
+
stopProcessGroup(child);
|
|
71
|
+
activeChildren.clear();
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Promise-with-resolvers equivalent (the repo lib target predates
|
|
75
|
+
* `Promise.withResolvers`): externally settleable one-shot slot.
|
|
76
|
+
*
|
|
77
|
+
* Args:
|
|
78
|
+
* T: the resolved value type.
|
|
79
|
+
*
|
|
80
|
+
* Returns:
|
|
81
|
+
* object: `promise` plus its `resolve`/`reject`.
|
|
82
|
+
*/
|
|
83
|
+
function deferred() {
|
|
84
|
+
let resolve = () => undefined;
|
|
85
|
+
let reject = () => undefined;
|
|
86
|
+
const promise = new Promise((res, rej) => {
|
|
87
|
+
resolve = res;
|
|
88
|
+
reject = rej;
|
|
89
|
+
});
|
|
90
|
+
return { promise, resolve, reject };
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Typed runtime failure: preparation or readiness broke — the gate must
|
|
94
|
+
* block with a precise cause and next action, never degrade to the
|
|
95
|
+
* worktree runtime.
|
|
96
|
+
*/
|
|
97
|
+
export class RuntimeBlockError extends Error {
|
|
98
|
+
/** The stable cause code rendered by the caller. */
|
|
99
|
+
causeCode;
|
|
100
|
+
/**
|
|
101
|
+
* Builds one typed runtime block.
|
|
102
|
+
*
|
|
103
|
+
* Args:
|
|
104
|
+
* causeCode: preparation vs readiness failure class.
|
|
105
|
+
* message: precise, actionable detail (no stack dumps).
|
|
106
|
+
*/
|
|
107
|
+
constructor(causeCode, message) {
|
|
108
|
+
super(message);
|
|
109
|
+
this.name = 'RuntimeBlockError';
|
|
110
|
+
this.causeCode = causeCode;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Loads and validates the tracked staged-runtime document.
|
|
115
|
+
*
|
|
116
|
+
* Args:
|
|
117
|
+
* runtimePath: repo-relative runtime document path from the
|
|
118
|
+
* validated `.gateforge.yml` (`runtime` key), or undefined when the
|
|
119
|
+
* owner declared none.
|
|
120
|
+
* cwd: absolute repository root (the candidate checkout when
|
|
121
|
+
* orchestrating a staged run — the candidate carries its own
|
|
122
|
+
* reviewed runtime bytes).
|
|
123
|
+
*
|
|
124
|
+
* Returns:
|
|
125
|
+
* RuntimeConfig | null: the parsed document, or null when no runtime
|
|
126
|
+
* document is configured (staged runtime off — fail closed).
|
|
127
|
+
*
|
|
128
|
+
* Throws:
|
|
129
|
+
* RuntimeBlockError: on a missing, unparsable, or schema-violating
|
|
130
|
+
* document that the config DOES declare (fail closed, never ignored).
|
|
131
|
+
*/
|
|
132
|
+
export function loadRuntimeConfigAt(cwd, runtimePath) {
|
|
133
|
+
if (runtimePath === undefined)
|
|
134
|
+
return null;
|
|
135
|
+
const absolute = join(cwd, ...runtimePath.split('/'));
|
|
136
|
+
if (!existsSync(absolute)) {
|
|
137
|
+
throw new RuntimeBlockError('RUNTIME_PREPARATION_FAILED', `the staged-runtime document '${runtimePath}' is configured but missing from the candidate — ` +
|
|
138
|
+
'the runtime commands are part of the trusted revision and cannot vanish');
|
|
139
|
+
}
|
|
140
|
+
let document;
|
|
141
|
+
try {
|
|
142
|
+
document = parseYaml(readFileSync(absolute, 'utf8'));
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
throw new RuntimeBlockError('RUNTIME_PREPARATION_FAILED', `the staged-runtime document '${runtimePath}' is not parsable YAML: ${error.message}`);
|
|
146
|
+
}
|
|
147
|
+
const parsed = RuntimeConfigSchema.safeParse(document);
|
|
148
|
+
if (!parsed.success) {
|
|
149
|
+
const first = parsed.error.issues[0];
|
|
150
|
+
const path = first === undefined ? '(root)' : first.path.map(String).join('.');
|
|
151
|
+
throw new RuntimeBlockError('RUNTIME_PREPARATION_FAILED', `the staged-runtime document '${runtimePath}' violates its schema at '${path}': ` +
|
|
152
|
+
`${first?.message ?? 'unknown schema error'}`);
|
|
153
|
+
}
|
|
154
|
+
return parsed.data;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Builds the child environment for preparation commands and services:
|
|
158
|
+
* a fixed safe base plus the owner-allowlisted operator names plus the
|
|
159
|
+
* supervisor-injected service coordinates. Everything else (credentials,
|
|
160
|
+
* orchestrator state, candidate-controlled names) stays out.
|
|
161
|
+
*
|
|
162
|
+
* Args:
|
|
163
|
+
* allowlist: owner-declared operator env names (`envAllowlist`).
|
|
164
|
+
* ioEnv: the operator process environment.
|
|
165
|
+
* injected: supervisor-computed variables (service ports/URLs).
|
|
166
|
+
*
|
|
167
|
+
* Returns:
|
|
168
|
+
* NodeJS.ProcessEnv: the child environment.
|
|
169
|
+
*/
|
|
170
|
+
function runtimeChildEnv(allowlist, ioEnv, injected) {
|
|
171
|
+
const child = {};
|
|
172
|
+
for (const name of RUNTIME_ENV_BASE) {
|
|
173
|
+
const value = ioEnv[name];
|
|
174
|
+
if (value !== undefined)
|
|
175
|
+
child[name] = value;
|
|
176
|
+
}
|
|
177
|
+
for (const name of allowlist) {
|
|
178
|
+
const value = ioEnv[name];
|
|
179
|
+
if (value !== undefined)
|
|
180
|
+
child[name] = value;
|
|
181
|
+
}
|
|
182
|
+
return { ...child, ...injected };
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Substitutes `${service:<id>:port}` / `${service:<id>:url}` placeholders.
|
|
186
|
+
*
|
|
187
|
+
* Args:
|
|
188
|
+
* template: config string possibly containing placeholders.
|
|
189
|
+
* ports: assigned port per service id.
|
|
190
|
+
*
|
|
191
|
+
* Returns:
|
|
192
|
+
* string: the substituted string (a reference to an unknown service
|
|
193
|
+
* stays literal — the spawn/readiness then fails observably).
|
|
194
|
+
*/
|
|
195
|
+
function substitute(template, ports) {
|
|
196
|
+
return template.replace(/\$\{service:([a-z0-9-]+):(port|url)\}/g, (match, id, kind) => {
|
|
197
|
+
const port = ports.get(id);
|
|
198
|
+
if (port === undefined)
|
|
199
|
+
return match;
|
|
200
|
+
return kind === 'port' ? String(port) : `http://127.0.0.1:${String(port)}`;
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Allocates one free loopback port by binding port 0 and releasing it.
|
|
205
|
+
*
|
|
206
|
+
* Returns:
|
|
207
|
+
* number: a port that was free at allocation time.
|
|
208
|
+
*
|
|
209
|
+
* Throws:
|
|
210
|
+
* RuntimeBlockError: when no port can be bound at all.
|
|
211
|
+
*/
|
|
212
|
+
async function allocatePort() {
|
|
213
|
+
const server = net.createServer();
|
|
214
|
+
const listening = deferred();
|
|
215
|
+
server.once('listening', () => listening.resolve());
|
|
216
|
+
server.once('error', (error) => listening.reject(error));
|
|
217
|
+
server.listen(0, '127.0.0.1');
|
|
218
|
+
try {
|
|
219
|
+
await listening.promise;
|
|
220
|
+
}
|
|
221
|
+
catch {
|
|
222
|
+
throw new RuntimeBlockError('RUNTIME_READINESS_FAILED', 'no free loopback port could be allocated');
|
|
223
|
+
}
|
|
224
|
+
const address = server.address();
|
|
225
|
+
const port = address !== null && typeof address !== 'string' ? address.port : 0;
|
|
226
|
+
// Closing releases the port for the service to bind; the OS keeps
|
|
227
|
+
// short-lived TIME_WAIT sockets from colliding on 127.0.0.1:0 reuse.
|
|
228
|
+
await new Promise((resolveClose) => server.close(() => resolveClose()));
|
|
229
|
+
if (port === 0) {
|
|
230
|
+
throw new RuntimeBlockError('RUNTIME_READINESS_FAILED', 'no free loopback port could be allocated');
|
|
231
|
+
}
|
|
232
|
+
return port;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Links one explicitly sanctioned dependency directory from the user
|
|
236
|
+
* repository into the checkout (junction on Windows, symlink elsewhere).
|
|
237
|
+
* The link is RUNTIME identity (recorded in the candidate tree), never
|
|
238
|
+
* candidate source.
|
|
239
|
+
*
|
|
240
|
+
* Args:
|
|
241
|
+
* sourceRoot: user repository root.
|
|
242
|
+
* checkoutRoot: materialized candidate root.
|
|
243
|
+
* relative: repo-relative dependency directory (`prepare.reuse` entry).
|
|
244
|
+
*
|
|
245
|
+
* Throws:
|
|
246
|
+
* RuntimeBlockError: when the source directory is missing (the
|
|
247
|
+
* declared reuse is part of the reviewed runtime contract).
|
|
248
|
+
*/
|
|
249
|
+
function pathInside(root, candidate) {
|
|
250
|
+
const rel = relative(resolve(root), resolve(candidate));
|
|
251
|
+
return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
|
|
252
|
+
}
|
|
253
|
+
/** Resolves and validates one configured reuse path under both roots. */
|
|
254
|
+
function reusePaths(sourceRoot, checkoutRoot, path) {
|
|
255
|
+
if (!isNormalizedRepoRelativePath(path)) {
|
|
256
|
+
throw new RuntimeBlockError('RUNTIME_PREPARATION_FAILED', `runtime prepare.reuse path '${path}' is not a normalized repository-relative path — ` +
|
|
257
|
+
'absolute paths and traversal are rejected');
|
|
258
|
+
}
|
|
259
|
+
const source = resolve(sourceRoot, ...path.split('/'));
|
|
260
|
+
const target = resolve(checkoutRoot, ...path.split('/'));
|
|
261
|
+
if (!pathInside(sourceRoot, source) || !pathInside(checkoutRoot, target)) {
|
|
262
|
+
throw new RuntimeBlockError('RUNTIME_PREPARATION_FAILED', `runtime prepare.reuse path '${path}' resolves outside the source or candidate root — refusing the link`);
|
|
263
|
+
}
|
|
264
|
+
return { source, target };
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Collects deterministic identity records for one reused dependency tree.
|
|
268
|
+
* Symlinks are followed, including sanctioned links to an external
|
|
269
|
+
* dependency store, so the digest covers the bytes a candidate can execute.
|
|
270
|
+
*
|
|
271
|
+
* Args:
|
|
272
|
+
* absolute: current filesystem entry.
|
|
273
|
+
* logicalPath: stable path label in the reuse manifest.
|
|
274
|
+
* active: real paths on the current recursion stack.
|
|
275
|
+
* entries: output records.
|
|
276
|
+
*/
|
|
277
|
+
function collectReuseEntries(absolute, logicalPath, active, entries) {
|
|
278
|
+
let stat;
|
|
279
|
+
try {
|
|
280
|
+
stat = lstatSync(absolute);
|
|
281
|
+
}
|
|
282
|
+
catch (error) {
|
|
283
|
+
throw new RuntimeBlockError('RUNTIME_PREPARATION_FAILED', `runtime prepare.reuse cannot inspect '${logicalPath}': ${error.message}`);
|
|
284
|
+
}
|
|
285
|
+
if (stat.isSymbolicLink()) {
|
|
286
|
+
let target;
|
|
287
|
+
let resolvedTarget;
|
|
288
|
+
try {
|
|
289
|
+
target = readlinkSync(absolute);
|
|
290
|
+
resolvedTarget = realpathSync(absolute);
|
|
291
|
+
}
|
|
292
|
+
catch (error) {
|
|
293
|
+
throw new RuntimeBlockError('RUNTIME_PREPARATION_FAILED', `runtime prepare.reuse cannot resolve symlink '${logicalPath}': ${error.message}`);
|
|
294
|
+
}
|
|
295
|
+
entries.push({
|
|
296
|
+
path: logicalPath,
|
|
297
|
+
type: 'symlink',
|
|
298
|
+
target,
|
|
299
|
+
});
|
|
300
|
+
if (active.has(resolvedTarget)) {
|
|
301
|
+
entries.push({ path: `${logicalPath}=>cycle`, type: 'cycle' });
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
collectReuseEntries(resolvedTarget, `${logicalPath}=>${target.split('\\').join('/')}`, new Set([...active, resolvedTarget]), entries);
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
let resolved;
|
|
308
|
+
try {
|
|
309
|
+
resolved = realpathSync(absolute);
|
|
310
|
+
}
|
|
311
|
+
catch (error) {
|
|
312
|
+
throw new RuntimeBlockError('RUNTIME_PREPARATION_FAILED', `runtime prepare.reuse cannot resolve '${logicalPath}': ${error.message}`);
|
|
313
|
+
}
|
|
314
|
+
if (active.has(resolved)) {
|
|
315
|
+
entries.push({ path: logicalPath, type: 'cycle' });
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
if (stat.isDirectory()) {
|
|
319
|
+
entries.push({ path: logicalPath, type: 'directory' });
|
|
320
|
+
let children;
|
|
321
|
+
try {
|
|
322
|
+
children = readdirSync(absolute).sort();
|
|
323
|
+
}
|
|
324
|
+
catch (error) {
|
|
325
|
+
throw new RuntimeBlockError('RUNTIME_PREPARATION_FAILED', `runtime prepare.reuse cannot read '${logicalPath}': ${error.message}`);
|
|
326
|
+
}
|
|
327
|
+
for (const child of children) {
|
|
328
|
+
collectReuseEntries(join(absolute, child), `${logicalPath}/${child}`, new Set([...active, resolved]), entries);
|
|
329
|
+
}
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
if (!stat.isFile()) {
|
|
333
|
+
throw new RuntimeBlockError('RUNTIME_PREPARATION_FAILED', `runtime prepare.reuse entry '${logicalPath}' is not a regular file, directory, or safe symlink`);
|
|
334
|
+
}
|
|
335
|
+
let bytes;
|
|
336
|
+
try {
|
|
337
|
+
bytes = readFileSync(absolute);
|
|
338
|
+
}
|
|
339
|
+
catch (error) {
|
|
340
|
+
throw new RuntimeBlockError('RUNTIME_PREPARATION_FAILED', `runtime prepare.reuse cannot read '${logicalPath}': ${error.message}`);
|
|
341
|
+
}
|
|
342
|
+
entries.push({
|
|
343
|
+
path: logicalPath,
|
|
344
|
+
type: 'file',
|
|
345
|
+
mode: stat.mode & 0o777,
|
|
346
|
+
digest: createHash('sha256').update(bytes).digest('hex'),
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Computes the deterministic digest bound to a staged run for reused
|
|
351
|
+
* dependency bytes. A changed dependency therefore changes the run's input
|
|
352
|
+
* identity even though the candidate checkout contains a symlink.
|
|
353
|
+
*
|
|
354
|
+
* Args:
|
|
355
|
+
* sourceRoot: user repository root that supplies reuse bytes.
|
|
356
|
+
* runtime: validated staged-runtime configuration.
|
|
357
|
+
*
|
|
358
|
+
* Returns:
|
|
359
|
+
* string | null: the reuse digest, or null when no reuse is configured.
|
|
360
|
+
*/
|
|
361
|
+
export function runtimeReuseDigest(sourceRoot, runtime) {
|
|
362
|
+
const paths = runtime.prepare?.reuse ?? [];
|
|
363
|
+
if (paths.length === 0)
|
|
364
|
+
return null;
|
|
365
|
+
let sourceRootReal;
|
|
366
|
+
try {
|
|
367
|
+
sourceRootReal = realpathSync(resolve(sourceRoot));
|
|
368
|
+
}
|
|
369
|
+
catch (error) {
|
|
370
|
+
throw new RuntimeBlockError('RUNTIME_PREPARATION_FAILED', `runtime prepare.reuse cannot resolve the user repository root: ${error.message}`);
|
|
371
|
+
}
|
|
372
|
+
const entries = [];
|
|
373
|
+
for (const path of paths) {
|
|
374
|
+
const { source } = reusePaths(sourceRootReal, sourceRootReal, path);
|
|
375
|
+
if (!existsSync(source)) {
|
|
376
|
+
// A staged candidate may carry its own dependency bytes. In that case
|
|
377
|
+
// linkReuseDir leaves them in place and the candidate tree identity
|
|
378
|
+
// binds those bytes; record the absent external source explicitly.
|
|
379
|
+
entries.push({ path, type: 'source-absent' });
|
|
380
|
+
continue;
|
|
381
|
+
}
|
|
382
|
+
collectReuseEntries(source, path, new Set(), entries);
|
|
383
|
+
}
|
|
384
|
+
return sha256Canonical({ domain: 'gateforge.runtime-reuse.v1', entries });
|
|
385
|
+
}
|
|
386
|
+
function linkReuseDir(sourceRoot, checkoutRoot, path) {
|
|
387
|
+
const { source, target } = reusePaths(sourceRoot, checkoutRoot, path);
|
|
388
|
+
if (existsSync(target))
|
|
389
|
+
return; // candidate carries its own bytes — never overridden
|
|
390
|
+
if (!existsSync(source)) {
|
|
391
|
+
throw new RuntimeBlockError('RUNTIME_PREPARATION_FAILED', `runtime prepare.reuse names '${path}' but the user repository has no such directory — ` +
|
|
392
|
+
'install dependencies in the user repository or fix the tracked runtime document');
|
|
393
|
+
}
|
|
394
|
+
mkdirSync(join(target, '..'), { recursive: true });
|
|
395
|
+
symlinkSync(source, target, process.platform === 'win32' ? 'junction' : 'dir');
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* Stops one child's whole process group (POSIX) or the process tree
|
|
399
|
+
* (Windows): SIGTERM first, SIGKILL after the grace period.
|
|
400
|
+
*
|
|
401
|
+
* Args:
|
|
402
|
+
* child: the spawned child (may already be dead — always safe).
|
|
403
|
+
*/
|
|
404
|
+
function stopProcessGroup(child) {
|
|
405
|
+
if (child.pid === undefined || child.exitCode !== null || child.signalCode !== null)
|
|
406
|
+
return;
|
|
407
|
+
if (process.platform === 'win32') {
|
|
408
|
+
spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
const pid = child.pid;
|
|
412
|
+
try {
|
|
413
|
+
process.kill(-pid, 'SIGTERM');
|
|
414
|
+
}
|
|
415
|
+
catch {
|
|
416
|
+
return; // group already gone
|
|
417
|
+
}
|
|
418
|
+
const timer = setTimeout(() => {
|
|
419
|
+
try {
|
|
420
|
+
process.kill(-pid, 'SIGKILL');
|
|
421
|
+
}
|
|
422
|
+
catch {
|
|
423
|
+
// already gone
|
|
424
|
+
}
|
|
425
|
+
}, SERVICE_STOP_GRACE_MS);
|
|
426
|
+
timer.unref();
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* Runs the tracked preparation command inside the checkout.
|
|
430
|
+
*
|
|
431
|
+
* Args:
|
|
432
|
+
* checkoutRoot: materialized candidate root (the command's cwd).
|
|
433
|
+
* runtime: the parsed staged-runtime document.
|
|
434
|
+
* io: process context (env allowlist source).
|
|
435
|
+
* logPath: absolute log file the command's output is captured to.
|
|
436
|
+
*
|
|
437
|
+
* Throws:
|
|
438
|
+
* RuntimeBlockError: on spawn error, nonzero exit, or timeout, with
|
|
439
|
+
* the log path named for debugging.
|
|
440
|
+
*/
|
|
441
|
+
async function runPrepareCommand(checkoutRoot, runtime, io, logPath) {
|
|
442
|
+
const prepare = runtime.prepare;
|
|
443
|
+
if (prepare === undefined || prepare.command === undefined)
|
|
444
|
+
return;
|
|
445
|
+
const timeoutSeconds = prepare.timeoutSeconds ?? DEFAULT_PREPARE_TIMEOUT_SECONDS;
|
|
446
|
+
const logFd = openSync(logPath, 'w');
|
|
447
|
+
const child = spawn(prepare.command, {
|
|
448
|
+
cwd: checkoutRoot,
|
|
449
|
+
env: runtimeChildEnv(runtime.envAllowlist ?? [], io.env, {}),
|
|
450
|
+
shell: true,
|
|
451
|
+
// Each invocation owns a fresh log. Appending would let a stale copied
|
|
452
|
+
// readiness line authorize a new process before it emits anything.
|
|
453
|
+
stdio: ['ignore', logFd, logFd],
|
|
454
|
+
detached: process.platform !== 'win32',
|
|
455
|
+
});
|
|
456
|
+
trackChild(child);
|
|
457
|
+
const exit = deferred();
|
|
458
|
+
const timer = setTimeout(() => {
|
|
459
|
+
stopProcessGroup(child);
|
|
460
|
+
exit.resolve({ timedOut: true });
|
|
461
|
+
}, timeoutSeconds * 1_000);
|
|
462
|
+
child.once('exit', () => exit.resolve({ timedOut: false }));
|
|
463
|
+
child.once('error', () => exit.resolve({ timedOut: false }));
|
|
464
|
+
const outcome = await exit.promise;
|
|
465
|
+
clearTimeout(timer);
|
|
466
|
+
if (outcome.timedOut) {
|
|
467
|
+
// The SIGTERM grace is still running: wait for the group to die so
|
|
468
|
+
// a failing gate never leaves grandchildren behind.
|
|
469
|
+
const reaped = deferred();
|
|
470
|
+
child.once('exit', () => reaped.resolve());
|
|
471
|
+
const reapTimer = setTimeout(() => {
|
|
472
|
+
try {
|
|
473
|
+
if (child.pid !== undefined && process.platform !== 'win32')
|
|
474
|
+
process.kill(-child.pid, 'SIGKILL');
|
|
475
|
+
}
|
|
476
|
+
catch {
|
|
477
|
+
// already gone
|
|
478
|
+
}
|
|
479
|
+
}, SERVICE_STOP_GRACE_MS);
|
|
480
|
+
await Promise.race([reaped.promise, new Promise((resolveGrace) => setTimeout(resolveGrace, SERVICE_STOP_GRACE_MS * 2))]);
|
|
481
|
+
clearTimeout(reapTimer);
|
|
482
|
+
reaped.resolve();
|
|
483
|
+
throw new RuntimeBlockError('RUNTIME_PREPARATION_FAILED', `runtime prepare command exceeded ${String(timeoutSeconds)}s: '${prepare.command}' — full log: ${logPath}`);
|
|
484
|
+
}
|
|
485
|
+
if (child.exitCode !== 0) {
|
|
486
|
+
throw new RuntimeBlockError('RUNTIME_PREPARATION_FAILED', `runtime prepare command failed (exit ${String(child.exitCode ?? 'error')}): '${prepare.command}' — ` +
|
|
487
|
+
`full log: ${logPath}`);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* Waits for one service's readiness with a hard deadline: a log line
|
|
492
|
+
* matching the declared regex source, an HTTP probe returning 2xx, or
|
|
493
|
+
* the child's early exit (typed failure naming the log).
|
|
494
|
+
*
|
|
495
|
+
* Args:
|
|
496
|
+
* child: the spawned service process.
|
|
497
|
+
* service: the declaration (probe kind + budget).
|
|
498
|
+
* ports: assigned ports (placeholder substitution for http probes).
|
|
499
|
+
* logPath: the service's captured log.
|
|
500
|
+
*/
|
|
501
|
+
async function awaitReadiness(child, service, ports, logPath) {
|
|
502
|
+
const timeoutSeconds = service.ready.timeoutSeconds ?? DEFAULT_READY_TIMEOUT_SECONDS;
|
|
503
|
+
const deadline = Date.now() + timeoutSeconds * 1_000;
|
|
504
|
+
const logPattern = service.ready.log !== undefined ? new RegExp(service.ready.log, 'u') : null;
|
|
505
|
+
let seenBytes = 0;
|
|
506
|
+
for (;;) {
|
|
507
|
+
if (child.exitCode !== null || child.signalCode !== null) {
|
|
508
|
+
throw new RuntimeBlockError('RUNTIME_READINESS_FAILED', `service '${service.id}' exited (code ${String(child.exitCode ?? child.signalCode)}) before becoming ` +
|
|
509
|
+
`ready — full log: ${logPath}`);
|
|
510
|
+
}
|
|
511
|
+
if (logPattern !== null && existsSync(logPath)) {
|
|
512
|
+
const bytes = readFileSync(logPath);
|
|
513
|
+
if (bytes.length > seenBytes) {
|
|
514
|
+
seenBytes = bytes.length;
|
|
515
|
+
if (logPattern.test(bytes.toString('utf8')))
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
if (service.ready.http !== undefined && (await probeHttp(substitute(service.ready.http, ports))))
|
|
520
|
+
return;
|
|
521
|
+
if (Date.now() > deadline) {
|
|
522
|
+
throw new RuntimeBlockError('RUNTIME_READINESS_FAILED', `service '${service.id}' was not ready within ${String(timeoutSeconds)}s — full log: ${logPath}`);
|
|
523
|
+
}
|
|
524
|
+
await new Promise((resolveSleep) => setTimeout(resolveSleep, READY_POLL_INTERVAL_MS));
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* Performs one 2xx check against a readiness URL.
|
|
529
|
+
*
|
|
530
|
+
* Args:
|
|
531
|
+
* url: the (substituted) readiness URL.
|
|
532
|
+
*
|
|
533
|
+
* Returns:
|
|
534
|
+
* boolean: true when the fetch returned status 200–299.
|
|
535
|
+
*/
|
|
536
|
+
async function probeHttp(url) {
|
|
537
|
+
try {
|
|
538
|
+
const controller = new AbortController();
|
|
539
|
+
const timer = setTimeout(() => controller.abort(), 2_000);
|
|
540
|
+
try {
|
|
541
|
+
const response = await fetch(url, { signal: controller.signal });
|
|
542
|
+
return response.ok;
|
|
543
|
+
}
|
|
544
|
+
finally {
|
|
545
|
+
clearTimeout(timer);
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
catch {
|
|
549
|
+
return false;
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* Prepares the candidate checkout runtime: sanctioned dependency reuse
|
|
554
|
+
* links, then the tracked preparation command. Logs land under the
|
|
555
|
+
* run-state `runtime/` directory (audit artifacts the caller copies
|
|
556
|
+
* back to the user repository).
|
|
557
|
+
*
|
|
558
|
+
* Args:
|
|
559
|
+
* sourceRoot: user repository root (reuse-link source).
|
|
560
|
+
* checkoutRoot: materialized candidate root.
|
|
561
|
+
* runtime: the parsed staged-runtime document.
|
|
562
|
+
* io: process context.
|
|
563
|
+
* stateDir: run-state directory for logs.
|
|
564
|
+
*
|
|
565
|
+
* Returns:
|
|
566
|
+
* object: the digest of reused dependency bytes, when configured.
|
|
567
|
+
*
|
|
568
|
+
* Throws:
|
|
569
|
+
* RuntimeBlockError: typed preparation failures.
|
|
570
|
+
*/
|
|
571
|
+
export async function prepareRuntime(sourceRoot, checkoutRoot, runtime, io, stateDir) {
|
|
572
|
+
const logDir = join(stateDir, 'runtime');
|
|
573
|
+
mkdirSync(logDir, { recursive: true });
|
|
574
|
+
for (const relative of runtime.prepare?.reuse ?? []) {
|
|
575
|
+
linkReuseDir(sourceRoot, checkoutRoot, relative);
|
|
576
|
+
}
|
|
577
|
+
await runPrepareCommand(checkoutRoot, runtime, io, join(logDir, 'prepare.log'));
|
|
578
|
+
// Bind the bytes that the witnessed runtime will actually execute. A
|
|
579
|
+
// trusted prepare command may materialize or update a reused dependency;
|
|
580
|
+
// hashing after it completes prevents check/reuse from carrying a
|
|
581
|
+
// pre-prepare digest over post-prepare bytes.
|
|
582
|
+
const reuseDigest = runtimeReuseDigest(sourceRoot, runtime);
|
|
583
|
+
return { reuseDigest };
|
|
584
|
+
}
|
|
585
|
+
/**
|
|
586
|
+
* Starts the declared candidate-owned services from the checkout bytes,
|
|
587
|
+
* probes readiness, and fronts the attested target with the gate's
|
|
588
|
+
* attestation proxy. Services run in their own process groups; `stop`
|
|
589
|
+
* tears everything down (reverse order, SIGTERM then SIGKILL) and is
|
|
590
|
+
* idempotent — the caller MUST call it on every exit path.
|
|
591
|
+
*
|
|
592
|
+
* Args:
|
|
593
|
+
* checkoutRoot: materialized candidate root (services run from HERE).
|
|
594
|
+
* runtime: the parsed staged-runtime document.
|
|
595
|
+
* io: process context (env allowlist source).
|
|
596
|
+
* stateDir: run-state directory (runtime logs land under runtime/).
|
|
597
|
+
*
|
|
598
|
+
* Returns:
|
|
599
|
+
* RunningRuntime: handles + attested target binding (null target when
|
|
600
|
+
* no service declares `target: true`).
|
|
601
|
+
*
|
|
602
|
+
* Throws:
|
|
603
|
+
* RuntimeBlockError: when a service fails to spawn or readiness is
|
|
604
|
+
* not reached in time; every already-started service is stopped
|
|
605
|
+
* before the error propagates.
|
|
606
|
+
*/
|
|
607
|
+
export async function startRuntimeServices(checkoutRoot, runtime, io, stateDir) {
|
|
608
|
+
const services = runtime.services ?? [];
|
|
609
|
+
const logDir = join(stateDir, 'runtime');
|
|
610
|
+
mkdirSync(logDir, { recursive: true });
|
|
611
|
+
const ports = new Map();
|
|
612
|
+
for (const service of services)
|
|
613
|
+
ports.set(service.id, await allocatePort());
|
|
614
|
+
// Coordinates are injected into EVERY service's environment so a
|
|
615
|
+
// database/worker peer can be addressed deterministically.
|
|
616
|
+
const injected = {};
|
|
617
|
+
for (const service of services) {
|
|
618
|
+
const port = ports.get(service.id);
|
|
619
|
+
if (port === undefined)
|
|
620
|
+
continue;
|
|
621
|
+
const key = service.id.toUpperCase().replace(/-/g, '_');
|
|
622
|
+
injected[`GATEFORGE_SERVICE_PORT_${key}`] = String(port);
|
|
623
|
+
injected[`GATEFORGE_SERVICE_URL_${key}`] = `http://127.0.0.1:${String(port)}`;
|
|
624
|
+
}
|
|
625
|
+
const children = [];
|
|
626
|
+
const proxies = [];
|
|
627
|
+
let targetBaseUrl = null;
|
|
628
|
+
let targetFingerprint = null;
|
|
629
|
+
let stopped = false;
|
|
630
|
+
const stop = async () => {
|
|
631
|
+
if (stopped)
|
|
632
|
+
return;
|
|
633
|
+
stopped = true;
|
|
634
|
+
for (const proxy of proxies.reverse())
|
|
635
|
+
await proxy.stop().catch(() => undefined);
|
|
636
|
+
for (const child of children.reverse())
|
|
637
|
+
stopProcessGroup(child);
|
|
638
|
+
};
|
|
639
|
+
try {
|
|
640
|
+
for (const service of services) {
|
|
641
|
+
const logPath = join(logDir, `${service.id}.log`);
|
|
642
|
+
const logFd = openSync(logPath, 'w');
|
|
643
|
+
const port = ports.get(service.id);
|
|
644
|
+
let baseUrl = `http://127.0.0.1:${String(port)}`;
|
|
645
|
+
if (service.attested === true) {
|
|
646
|
+
// The proxy fronts the service so EVERY response carries the
|
|
647
|
+
// reviewed environment marker (GF-13); the runner env points at
|
|
648
|
+
// the proxy, never at the raw service.
|
|
649
|
+
const proxy = await startAttestationProxy(baseUrl, substitute(service.fingerprint, ports));
|
|
650
|
+
proxies.push(proxy);
|
|
651
|
+
baseUrl = proxy.url;
|
|
652
|
+
}
|
|
653
|
+
const child = spawn(substitute(service.command, ports), {
|
|
654
|
+
cwd: checkoutRoot,
|
|
655
|
+
env: runtimeChildEnv(runtime.envAllowlist ?? [], io.env, service.env === undefined
|
|
656
|
+
? injected
|
|
657
|
+
: {
|
|
658
|
+
...injected,
|
|
659
|
+
...Object.fromEntries(Object.entries(service.env).map(([key, value]) => [key, substitute(value, ports)])),
|
|
660
|
+
}),
|
|
661
|
+
shell: true,
|
|
662
|
+
// Readiness must observe this run's output only; stale copied logs
|
|
663
|
+
// cannot satisfy a new service declaration.
|
|
664
|
+
stdio: ['ignore', logFd, logFd],
|
|
665
|
+
detached: process.platform !== 'win32',
|
|
666
|
+
});
|
|
667
|
+
children.push(child);
|
|
668
|
+
trackChild(child);
|
|
669
|
+
await awaitReadiness(child, service, ports, logPath);
|
|
670
|
+
if (service.target === true && targetBaseUrl === null) {
|
|
671
|
+
targetBaseUrl = baseUrl;
|
|
672
|
+
targetFingerprint = substitute(service.fingerprint, ports);
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
return { targetBaseUrl, targetFingerprint, stop };
|
|
676
|
+
}
|
|
677
|
+
catch (error) {
|
|
678
|
+
await stop();
|
|
679
|
+
throw error;
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
//# sourceMappingURL=runtime.js.map
|