@loucompanion/forge-bridge 0.2.1-dev.17ad6c965e41 → 0.2.1-dev.4f11ffc822f9

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.
@@ -5,6 +5,8 @@ export interface HostParallelPromotionRecord {
5
5
  readonly runtimeContractFingerprint: string;
6
6
  readonly inputCommitSha?: string | null;
7
7
  readonly sourceFingerprint?: string;
8
+ /** Identity of the isolation inputs the probe ran with; lets other heads with identical inputs reuse it. */
9
+ readonly isolationFingerprint?: string;
8
10
  readonly runtimeContractSource?: "project" | "derived";
9
11
  readonly observedAt: string;
10
12
  readonly observedDispatchAttemptId: string;
@@ -14,19 +16,93 @@ export interface HostParallelProofIdentity {
14
16
  readonly runtimeContractFingerprint: string;
15
17
  readonly inputCommitSha: string;
16
18
  readonly sourceFingerprint?: string;
19
+ readonly isolationFingerprint?: string;
17
20
  }
18
21
  /** Persists only observed, contract-bound host parallel-safety evidence. */
19
22
  export declare class HostParallelPromotionStore {
20
23
  private readonly stateRoot;
24
+ /**
25
+ * Repositories whose full invalidation has started but not been confirmed on disk. They
26
+ * have no proof until a retried invalidation succeeds, so a failed delete cannot leave
27
+ * stale records admitting shared runs. A tombstone file beside the records carries the same
28
+ * state to other store instances and across restarts.
29
+ */
30
+ private readonly revoked;
31
+ /** Bumped by every full invalidation, so a read that raced one is discarded. */
32
+ private readonly revocations;
33
+ /** How long an isolation violation keeps its runtime contract from earning parallel proof again. */
34
+ quarantineMs: number;
35
+ /** Quarantines this instance holds whether or not they reached disk: a failed write cannot lift one. */
36
+ private readonly heldQuarantines;
37
+ /** Per repository, so concurrent invalidations and quarantine writes cannot lose each other's entries. */
38
+ private readonly serialQueues;
21
39
  constructor(stateRoot: string);
40
+ /**
41
+ * With an identity, returns proof for it: first a proof observed for the same isolation
42
+ * inputs (runtime contract plus launch-relevant files) at any commit, then a proof for the
43
+ * exact prepared source. The record keeps the commit it was observed at for audit.
44
+ */
22
45
  load(repoId: string, identity?: HostParallelProofIdentity): Promise<HostParallelPromotionRecord | null>;
46
+ private readProof;
47
+ private isRevoked;
48
+ private readRecord;
23
49
  list(): Promise<readonly HostParallelPromotionRecord[]>;
24
- observe(repoId: string, runtimeContract: LoadedHostRuntimeContract, dispatchAttemptId: string, verifiedPortNames: readonly string[], inputCommitSha?: string, sourceFingerprint?: string): Promise<HostParallelPromotionRecord>;
50
+ observe(repoId: string, runtimeContract: LoadedHostRuntimeContract, dispatchAttemptId: string, verifiedPortNames: readonly string[], inputCommitSha?: string, sourceFingerprint?: string, isolationFingerprint?: string, revocationGeneration?: string): Promise<HostParallelPromotionRecord>;
51
+ /** Deletes each record file that still holds this record; one a newer proof has since replaced is left alone. */
52
+ private withdrawRecords;
53
+ /**
54
+ * The repository's revocation generation. A probe captures it at admission and passes it to
55
+ * observe, which then refuses to record if any full invalidation happened since: a violation by
56
+ * the probe itself or by a sibling means the run it watched does not prove isolation. It joins this
57
+ * instance's counter (bumped before any record is touched) with the repository's durable epoch, which
58
+ * every full invalidation bumps before deleting records, so one by another instance fences it too.
59
+ */
60
+ revocationGeneration(repoId: string): Promise<string>;
61
+ /** A missing epoch is "0"; an unreadable one throws, so a caller fails closed rather than fencing nothing. */
62
+ private readEpoch;
63
+ /** A fresh random epoch rather than a read-modify-write, so concurrent bumps by two processes cannot cancel out. */
64
+ private bumpEpoch;
65
+ private epochPath;
66
+ /**
67
+ * Called on an isolation violation, before the proofs are revoked. A launch-time audit cannot see
68
+ * a listener bound later, and ordinary source is not an isolation input, so without this the next
69
+ * exclusive run of the same contract would re-earn proof at launch and readmit the shared runs that
70
+ * just collided. A quarantine lasts quarantineMs, or until the runtime contract changes.
71
+ */
72
+ quarantine(repoId: string, runtimeContractFingerprint: string): Promise<void>;
73
+ /** Whether the contract is quarantined, so callers can skip a probe or launch that could never earn proof. */
74
+ quarantined(repoId: string, runtimeContractFingerprint: string): Promise<boolean>;
75
+ private serialized;
76
+ private holdQuarantine;
77
+ private persistQuarantine;
78
+ private isQuarantined;
79
+ /** Unreadable or malformed quarantine state reads as empty; a missing file is the normal case. */
80
+ private readQuarantine;
81
+ private quarantinePath;
82
+ private revokedSince;
25
83
  private writeRecord;
26
84
  private pruneVersions;
27
- invalidate(repoId: string, scope?: "all" | "discovery"): Promise<void>;
85
+ /**
86
+ * Deletes the repository's proofs. A full invalidation revokes them in memory first and
87
+ * lifts that only once every record is confirmed deleted, so it fails closed: until then
88
+ * load and list return nothing for the repository and observe refuses to record.
89
+ */
90
+ invalidate(repoId: string, scope?: "all" | "discovery", quarantineFingerprints?: readonly string[]): Promise<void>;
91
+ private revokeAll;
92
+ private writeTombstone;
93
+ /** The quarantine a tombstone carries; an older plain-timestamp tombstone, or none, carries nothing. */
94
+ private readTombstoneQuarantine;
95
+ private tombstonePath;
96
+ private removeRecords;
28
97
  private recordPath;
98
+ private isolationRecordPath;
29
99
  }
100
+ /**
101
+ * Whether a stored proof admits this identity. An identity with isolation inputs (a prepared
102
+ * proof) needs the same isolation inputs, at any commit; one without them (an unprepared run)
103
+ * needs the same commit.
104
+ */
105
+ export declare function hostParallelPromotionMatches(record: HostParallelPromotionRecord | null, identity: HostParallelProofIdentity): boolean;
30
106
  export declare function hostRuntimeContractFingerprint(runtimeContract: LoadedHostRuntimeContract): string;
31
107
  export interface ReadmittedHostRuntimeContract {
32
108
  readonly runtimeContract: LoadedHostRuntimeContract;
@@ -5,15 +5,71 @@ import { ForgeFailureError } from "../session/session.types.js";
5
5
  /** Persists only observed, contract-bound host parallel-safety evidence. */
6
6
  export class HostParallelPromotionStore {
7
7
  stateRoot;
8
+ /**
9
+ * Repositories whose full invalidation has started but not been confirmed on disk. They
10
+ * have no proof until a retried invalidation succeeds, so a failed delete cannot leave
11
+ * stale records admitting shared runs. A tombstone file beside the records carries the same
12
+ * state to other store instances and across restarts.
13
+ */
14
+ revoked = new Set();
15
+ /** Bumped by every full invalidation, so a read that raced one is discarded. */
16
+ revocations = new Map();
17
+ /** How long an isolation violation keeps its runtime contract from earning parallel proof again. */
18
+ quarantineMs = 24 * 60 * 60 * 1000;
19
+ /** Quarantines this instance holds whether or not they reached disk: a failed write cannot lift one. */
20
+ heldQuarantines = new Map();
21
+ /** Per repository, so concurrent invalidations and quarantine writes cannot lose each other's entries. */
22
+ serialQueues = new Map();
8
23
  constructor(stateRoot) {
9
24
  this.stateRoot = stateRoot;
10
25
  }
26
+ /**
27
+ * With an identity, returns proof for it: first a proof observed for the same isolation
28
+ * inputs (runtime contract plus launch-relevant files) at any commit, then a proof for the
29
+ * exact prepared source. The record keeps the commit it was observed at for audit.
30
+ */
11
31
  async load(repoId, identity) {
12
32
  const normalizedRepoId = normalizeRepoId(repoId);
33
+ if (await this.isRevoked(normalizedRepoId)) {
34
+ // Retry the revocation; whatever its outcome, nothing on disk may be trusted yet.
35
+ await this.invalidate(normalizedRepoId).catch(() => undefined);
36
+ return null;
37
+ }
38
+ const generation = this.revocations.get(normalizedRepoId) ?? 0;
39
+ const record = await this.readProof(normalizedRepoId, identity);
40
+ // A full invalidation that started while the records were being read revokes what was read.
41
+ if (!record || (this.revocations.get(normalizedRepoId) ?? 0) !== generation
42
+ || await this.isRevoked(normalizedRepoId)
43
+ || await this.isQuarantined(normalizedRepoId, record.runtimeContractFingerprint))
44
+ return null;
45
+ return record;
46
+ }
47
+ async readProof(normalizedRepoId, identity) {
48
+ if (identity?.isolationFingerprint) {
49
+ const reusable = await this.readRecord(this.isolationRecordPath(normalizedRepoId, identity.runtimeContractFingerprint, identity.isolationFingerprint), normalizedRepoId);
50
+ if (reusable && matchesIsolation(reusable, identity))
51
+ return reusable;
52
+ }
53
+ const parsed = await this.readRecord(this.recordPath(normalizedRepoId, identity), normalizedRepoId);
54
+ return parsed && (!identity || matchesIdentity(parsed, identity)) ? parsed : null;
55
+ }
56
+ async isRevoked(normalizedRepoId) {
57
+ if (this.revoked.has(normalizedRepoId))
58
+ return true;
13
59
  try {
14
- const parsed = JSON.parse(await fs.readFile(this.recordPath(normalizedRepoId, identity), "utf8"));
15
- return validRecord(parsed, normalizedRepoId)
16
- && (!identity || matchesIdentity(parsed, identity)) ? parsed : null;
60
+ await fs.access(this.tombstonePath(normalizedRepoId));
61
+ return true;
62
+ }
63
+ catch (error) {
64
+ if (error.code === "ENOENT")
65
+ return false;
66
+ throw error;
67
+ }
68
+ }
69
+ async readRecord(target, normalizedRepoId) {
70
+ try {
71
+ const parsed = JSON.parse(await fs.readFile(target, "utf8"));
72
+ return validRecord(parsed, normalizedRepoId) ? parsed : null;
17
73
  }
18
74
  catch (error) {
19
75
  if (error.code === "ENOENT" || error instanceof SyntaxError)
@@ -32,12 +88,15 @@ export class HostParallelPromotionStore {
32
88
  return [];
33
89
  throw error;
34
90
  }
91
+ const tombstones = new Set(entries.filter(value => /^[0-9a-f]{64}\.revoked$/u.test(value))
92
+ .map(value => value.slice(0, 64)));
35
93
  const records = [];
36
94
  for (const entry of entries.filter(value => /^[0-9a-f]{64}\.json$/u.test(value)).slice(0, 4096)) {
37
95
  try {
38
96
  const parsed = JSON.parse(await fs.readFile(path.join(root, entry), "utf8"));
39
97
  const repoId = typeof parsed.repoId === "string" ? normalizeRepoId(parsed.repoId) : "";
40
- if (repoId && validRecord(parsed, repoId))
98
+ if (repoId && !this.revoked.has(repoId) && !tombstones.has(repoKey(repoId))
99
+ && validRecord(parsed, repoId))
41
100
  records.push(parsed);
42
101
  }
43
102
  catch (error) {
@@ -47,10 +106,16 @@ export class HostParallelPromotionStore {
47
106
  }
48
107
  return records.sort((left, right) => left.repoId.localeCompare(right.repoId));
49
108
  }
50
- async observe(repoId, runtimeContract, dispatchAttemptId, verifiedPortNames, inputCommitSha, sourceFingerprint) {
109
+ async observe(repoId, runtimeContract, dispatchAttemptId, verifiedPortNames, inputCommitSha, sourceFingerprint, isolationFingerprint, revocationGeneration) {
51
110
  if (!hostRuntimeParallelEligible(runtimeContract)) {
52
111
  throw new Error("host_parallel_promotion_ineligible: the runtime contract is not eligible for parallel host execution.");
53
112
  }
113
+ if (await this.revokedSince(normalizeRepoId(repoId), revocationGeneration)) {
114
+ throw new Error("host_parallel_promotion_revoked: the repository was revoked, or its previous proofs could not be confirmed deleted.");
115
+ }
116
+ if (await this.isQuarantined(normalizeRepoId(repoId), hostRuntimeContractFingerprint(runtimeContract))) {
117
+ throw new Error("host_parallel_promotion_revoked: this runtime contract bound an unbrokered listener recently, so it is quarantined from parallel proof.");
118
+ }
54
119
  const requiredPorts = configuredLaunchPortNames(runtimeContract);
55
120
  const observedPorts = [...new Set(verifiedPortNames)].sort((left, right) => left.localeCompare(right));
56
121
  if (requiredPorts.length !== observedPorts.length
@@ -64,20 +129,148 @@ export class HostParallelPromotionStore {
64
129
  runtimeContractFingerprint: hostRuntimeContractFingerprint(runtimeContract),
65
130
  inputCommitSha: inputCommitSha ?? null,
66
131
  ...(sourceFingerprint ? { sourceFingerprint } : {}),
132
+ ...(isolationFingerprint ? { isolationFingerprint } : {}),
67
133
  runtimeContractSource: runtimeContract.source === "project" ? "project" : "derived",
68
134
  observedAt: new Date().toISOString(),
69
135
  observedDispatchAttemptId: normalizedUuid(dispatchAttemptId, "dispatch attempt"),
70
136
  verifiedPortNames: observedPorts,
71
137
  };
72
- if (inputCommitSha) {
73
- await this.writeRecord(this.recordPath(normalizedRepoId, {
74
- runtimeContractFingerprint: record.runtimeContractFingerprint, inputCommitSha, sourceFingerprint,
75
- }), record);
76
- }
77
- await this.writeRecord(this.recordPath(normalizedRepoId), record);
138
+ const written = [
139
+ ...(inputCommitSha ? [this.recordPath(normalizedRepoId, {
140
+ runtimeContractFingerprint: record.runtimeContractFingerprint, inputCommitSha, sourceFingerprint
141
+ })] : []),
142
+ ...(isolationFingerprint ? [this.isolationRecordPath(normalizedRepoId, record.runtimeContractFingerprint, isolationFingerprint)] : []),
143
+ this.recordPath(normalizedRepoId),
144
+ ];
145
+ for (const target of written)
146
+ await this.writeRecord(target, record);
78
147
  await this.pruneVersions(normalizedRepoId);
148
+ // A revocation that landed while the records were written may have deleted before them. Only this
149
+ // call's own records are withdrawn: a full invalidation here would bump the epoch and delete fresh
150
+ // proofs recorded since the revocation. If they cannot be withdrawn, fall back to revoking all.
151
+ if (await this.revokedSince(normalizedRepoId, revocationGeneration)) {
152
+ await this.withdrawRecords(written, record).catch(async () => await this.invalidate(normalizedRepoId).catch(() => undefined));
153
+ throw new Error("host_parallel_promotion_revoked: the repository was revoked while its proof was being recorded.");
154
+ }
79
155
  return record;
80
156
  }
157
+ /** Deletes each record file that still holds this record; one a newer proof has since replaced is left alone. */
158
+ async withdrawRecords(targets, record) {
159
+ for (const target of targets) {
160
+ const current = await this.readRecord(target, record.repoId);
161
+ if (current?.observedDispatchAttemptId === record.observedDispatchAttemptId && current.observedAt === record.observedAt) {
162
+ await fs.rm(target, { force: true });
163
+ }
164
+ }
165
+ }
166
+ /**
167
+ * The repository's revocation generation. A probe captures it at admission and passes it to
168
+ * observe, which then refuses to record if any full invalidation happened since: a violation by
169
+ * the probe itself or by a sibling means the run it watched does not prove isolation. It joins this
170
+ * instance's counter (bumped before any record is touched) with the repository's durable epoch, which
171
+ * every full invalidation bumps before deleting records, so one by another instance fences it too.
172
+ */
173
+ async revocationGeneration(repoId) {
174
+ const normalizedRepoId = normalizeRepoId(repoId);
175
+ return `${this.revocations.get(normalizedRepoId) ?? 0}:${await this.readEpoch(normalizedRepoId)}`;
176
+ }
177
+ /** A missing epoch is "0"; an unreadable one throws, so a caller fails closed rather than fencing nothing. */
178
+ async readEpoch(normalizedRepoId) {
179
+ try {
180
+ const epoch = (await fs.readFile(this.epochPath(normalizedRepoId), "utf8")).trim();
181
+ if (!/^[0-9a-f-]{1,64}$/u.test(epoch))
182
+ throw new Error("host_parallel_promotion_invalid: revocation epoch is malformed.");
183
+ return epoch;
184
+ }
185
+ catch (error) {
186
+ if (error.code === "ENOENT")
187
+ return "0";
188
+ throw error;
189
+ }
190
+ }
191
+ /** A fresh random epoch rather than a read-modify-write, so concurrent bumps by two processes cannot cancel out. */
192
+ async bumpEpoch(normalizedRepoId) {
193
+ const target = this.epochPath(normalizedRepoId), next = randomUUID();
194
+ await ensurePrivateDirectory(path.dirname(target));
195
+ const temporary = `${target}.${randomUUID()}.tmp`;
196
+ await fs.writeFile(temporary, `${next}
197
+ `, { encoding: "utf8", mode: 0o600, flag: "wx" });
198
+ await fs.rename(temporary, target).catch(async (error) => {
199
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
200
+ throw error;
201
+ });
202
+ }
203
+ epochPath(normalizedRepoId) {
204
+ return path.join(this.stateRoot, "runtime-promotion", "host", `${repoKey(normalizedRepoId)}.epoch`);
205
+ }
206
+ /**
207
+ * Called on an isolation violation, before the proofs are revoked. A launch-time audit cannot see
208
+ * a listener bound later, and ordinary source is not an isolation input, so without this the next
209
+ * exclusive run of the same contract would re-earn proof at launch and readmit the shared runs that
210
+ * just collided. A quarantine lasts quarantineMs, or until the runtime contract changes.
211
+ */
212
+ async quarantine(repoId, runtimeContractFingerprint) {
213
+ const normalizedRepoId = normalizeRepoId(repoId);
214
+ const entry = this.holdQuarantine(normalizedRepoId, runtimeContractFingerprint);
215
+ await this.serialized(normalizedRepoId, () => this.persistQuarantine(normalizedRepoId, entry));
216
+ }
217
+ /** Whether the contract is quarantined, so callers can skip a probe or launch that could never earn proof. */
218
+ async quarantined(repoId, runtimeContractFingerprint) {
219
+ return await this.isQuarantined(normalizeRepoId(repoId), runtimeContractFingerprint);
220
+ }
221
+ async serialized(normalizedRepoId, operation) {
222
+ const run = (this.serialQueues.get(normalizedRepoId) ?? Promise.resolve()).catch(() => undefined).then(operation);
223
+ this.serialQueues.set(normalizedRepoId, run);
224
+ try {
225
+ return await run;
226
+ }
227
+ finally {
228
+ if (this.serialQueues.get(normalizedRepoId) === run)
229
+ this.serialQueues.delete(normalizedRepoId);
230
+ }
231
+ }
232
+ holdQuarantine(normalizedRepoId, runtimeContractFingerprint) {
233
+ const entry = { [runtimeContractFingerprint]: Date.now() + this.quarantineMs };
234
+ this.heldQuarantines.set(normalizedRepoId, { ...this.heldQuarantines.get(normalizedRepoId), ...entry });
235
+ return entry;
236
+ }
237
+ async persistQuarantine(normalizedRepoId, added) {
238
+ const entries = { ...await this.readQuarantine(normalizedRepoId), ...added };
239
+ const live = Object.fromEntries(Object.entries(entries).filter(([, until]) => until > Date.now()).slice(-64));
240
+ const target = this.quarantinePath(normalizedRepoId);
241
+ await ensurePrivateDirectory(path.dirname(target));
242
+ const temporary = `${target}.${randomUUID()}.tmp`;
243
+ await fs.writeFile(temporary, `${JSON.stringify(live)}\n`, { encoding: "utf8", mode: 0o600, flag: "wx" });
244
+ await fs.rename(temporary, target).catch(async (error) => {
245
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
246
+ throw error;
247
+ });
248
+ }
249
+ async isQuarantined(normalizedRepoId, runtimeContractFingerprint) {
250
+ const until = Math.max(this.heldQuarantines.get(normalizedRepoId)?.[runtimeContractFingerprint] ?? 0, (await this.readQuarantine(normalizedRepoId))[runtimeContractFingerprint] ?? 0);
251
+ return until > Date.now();
252
+ }
253
+ /** Unreadable or malformed quarantine state reads as empty; a missing file is the normal case. */
254
+ async readQuarantine(normalizedRepoId) {
255
+ try {
256
+ const parsed = JSON.parse(await fs.readFile(this.quarantinePath(normalizedRepoId), "utf8"));
257
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
258
+ return {};
259
+ return Object.fromEntries(Object.entries(parsed).filter((entry) => typeof entry[1] === "number"));
260
+ }
261
+ catch (error) {
262
+ if (error.code === "ENOENT" || error instanceof SyntaxError)
263
+ return {};
264
+ throw error;
265
+ }
266
+ }
267
+ quarantinePath(normalizedRepoId) {
268
+ return path.join(this.stateRoot, "runtime-promotion", "host", `${repoKey(normalizedRepoId)}.quarantine`);
269
+ }
270
+ async revokedSince(normalizedRepoId, generation) {
271
+ return (generation !== undefined && await this.revocationGeneration(normalizedRepoId) !== generation)
272
+ || await this.isRevoked(normalizedRepoId);
273
+ }
81
274
  async writeRecord(target, record) {
82
275
  const root = path.dirname(target);
83
276
  await ensurePrivateDirectory(root);
@@ -112,8 +305,76 @@ export class HostParallelPromotionStore {
112
305
  await fs.rm(path.join(root, entry.name), { force: true });
113
306
  }
114
307
  }
115
- async invalidate(repoId, scope = "all") {
116
- const target = this.recordPath(normalizeRepoId(repoId));
308
+ /**
309
+ * Deletes the repository's proofs. A full invalidation revokes them in memory first and
310
+ * lifts that only once every record is confirmed deleted, so it fails closed: until then
311
+ * load and list return nothing for the repository and observe refuses to record.
312
+ */
313
+ async invalidate(repoId, scope = "all", quarantineFingerprints = []) {
314
+ const normalizedRepoId = normalizeRepoId(repoId);
315
+ if (scope === "discovery") {
316
+ await this.removeRecords(normalizedRepoId, scope);
317
+ return;
318
+ }
319
+ this.revoked.add(normalizedRepoId);
320
+ this.revocations.set(normalizedRepoId, (this.revocations.get(normalizedRepoId) ?? 0) + 1);
321
+ for (const fingerprint of quarantineFingerprints)
322
+ this.holdQuarantine(normalizedRepoId, fingerprint);
323
+ // Serialized, so a concurrent invalidation can neither drop this one's tombstone quarantine nor
324
+ // lift the revocation while this one still depends on it.
325
+ await this.serialized(normalizedRepoId, () => this.revokeAll(normalizedRepoId));
326
+ }
327
+ async revokeAll(normalizedRepoId) {
328
+ this.revoked.add(normalizedRepoId);
329
+ // The tombstone goes down before any record is deleted, so a restart part-way through still
330
+ // finds the repository revoked. If it cannot be written, deleting the records still revokes.
331
+ // It also carries any quarantine not yet on disk (this one, or one an earlier attempt left in
332
+ // it), and is lifted only once that quarantine is written: until then every instance and a
333
+ // restarted bridge find the repository revoked, so the quarantined contract cannot re-earn proof.
334
+ const tombstone = this.tombstonePath(normalizedRepoId);
335
+ const pending = Object.fromEntries(Object.entries({ ...await this.readTombstoneQuarantine(tombstone),
336
+ ...this.heldQuarantines.get(normalizedRepoId) }).filter(([, until]) => until > Date.now()));
337
+ await this.writeTombstone(tombstone, pending).catch(() => undefined);
338
+ // Before any record is deleted, so another instance's lease admitted earlier sees the change even
339
+ // once this invalidation completes and the tombstone is gone. A failed bump keeps the revocation.
340
+ await this.bumpEpoch(normalizedRepoId);
341
+ await this.removeRecords(normalizedRepoId, "all");
342
+ if (Object.keys(pending).length > 0)
343
+ await this.persistQuarantine(normalizedRepoId, pending);
344
+ await fs.rm(tombstone, { force: true });
345
+ this.revoked.delete(normalizedRepoId);
346
+ }
347
+ async writeTombstone(target, quarantine) {
348
+ await ensurePrivateDirectory(path.dirname(target));
349
+ const handle = await fs.open(target, "w", 0o600);
350
+ try {
351
+ await handle.writeFile(`${JSON.stringify({ revokedAt: new Date().toISOString(), quarantine })}\n`, "utf8");
352
+ await handle.sync();
353
+ }
354
+ finally {
355
+ await handle.close();
356
+ }
357
+ }
358
+ /** The quarantine a tombstone carries; an older plain-timestamp tombstone, or none, carries nothing. */
359
+ async readTombstoneQuarantine(target) {
360
+ try {
361
+ const parsed = JSON.parse(await fs.readFile(target, "utf8"));
362
+ const quarantine = parsed && typeof parsed === "object" ? parsed.quarantine : undefined;
363
+ if (!quarantine || typeof quarantine !== "object" || Array.isArray(quarantine))
364
+ return {};
365
+ return Object.fromEntries(Object.entries(quarantine).filter((entry) => typeof entry[1] === "number"));
366
+ }
367
+ catch (error) {
368
+ if (error.code === "ENOENT" || error instanceof SyntaxError)
369
+ return {};
370
+ throw error;
371
+ }
372
+ }
373
+ tombstonePath(normalizedRepoId) {
374
+ return path.join(this.stateRoot, "runtime-promotion", "host", `${repoKey(normalizedRepoId)}.revoked`);
375
+ }
376
+ async removeRecords(normalizedRepoId, scope) {
377
+ const target = this.recordPath(normalizedRepoId);
117
378
  await fs.rm(target, { force: true });
118
379
  // Background/default-branch discovery must not erase proofs bound to other
119
380
  // prepared sources. Actual containment/cleanup degradation invalidates all.
@@ -136,11 +397,43 @@ export class HostParallelPromotionStore {
136
397
  ])).digest("hex")}` : "";
137
398
  return path.join(this.stateRoot, "runtime-promotion", "host", `${key}${version}.json`);
138
399
  }
400
+ // Same <repo>.<version>.json shape as exact proofs, so pruning and invalidation cover it.
401
+ isolationRecordPath(normalizedRepoId, runtimeContractFingerprint, isolationFingerprint) {
402
+ const key = createHash("sha256").update(normalizedRepoId).digest("hex");
403
+ const version = createHash("sha256").update(JSON.stringify([
404
+ "isolation", runtimeContractFingerprint, isolationFingerprint,
405
+ ])).digest("hex");
406
+ return path.join(this.stateRoot, "runtime-promotion", "host", `${key}.${version}.json`);
407
+ }
408
+ }
409
+ function repoKey(normalizedRepoId) {
410
+ return createHash("sha256").update(normalizedRepoId).digest("hex");
139
411
  }
140
412
  function matchesIdentity(record, identity) {
413
+ // An identity that carries isolation inputs needs a record proven with the same ones: an
414
+ // ignored launch input can change while commit and source stay the same, and a legacy record
415
+ // (no isolation fingerprint) says nothing about those inputs.
141
416
  return record.runtimeContractFingerprint === identity.runtimeContractFingerprint
142
417
  && record.inputCommitSha === identity.inputCommitSha
143
- && record.sourceFingerprint === identity.sourceFingerprint;
418
+ && record.sourceFingerprint === identity.sourceFingerprint
419
+ && (identity.isolationFingerprint === undefined || record.isolationFingerprint === identity.isolationFingerprint);
420
+ }
421
+ function matchesIsolation(record, identity) {
422
+ return Boolean(identity.isolationFingerprint)
423
+ && record.runtimeContractFingerprint === identity.runtimeContractFingerprint
424
+ && record.isolationFingerprint === identity.isolationFingerprint;
425
+ }
426
+ /**
427
+ * Whether a stored proof admits this identity. An identity with isolation inputs (a prepared
428
+ * proof) needs the same isolation inputs, at any commit; one without them (an unprepared run)
429
+ * needs the same commit.
430
+ */
431
+ export function hostParallelPromotionMatches(record, identity) {
432
+ if (!record || record.runtimeContractFingerprint !== identity.runtimeContractFingerprint)
433
+ return false;
434
+ return identity.isolationFingerprint !== undefined
435
+ ? matchesIsolation(record, identity)
436
+ : record.inputCommitSha === identity.inputCommitSha;
144
437
  }
145
438
  export function hostRuntimeContractFingerprint(runtimeContract) {
146
439
  const canonical = JSON.stringify({
@@ -4,3 +4,7 @@ export interface PreparedRuntimeIdentityDiagnostics {
4
4
  }
5
5
  /** Bind evidence to the prepared source, including unstaged replacements, not just HEAD. */
6
6
  export declare function preparedRuntimeIdentity(worktreePath: string, signal?: AbortSignal, diagnostics?: PreparedRuntimeIdentityDiagnostics): Promise<HostParallelProofIdentity>;
7
+ /** Total bytes of git-ignored launch inputs one identity pass may read. */
8
+ export declare const ignoredLaunchInputByteBudget: number;
9
+ /** Whether a worktree-relative path is an isolation input (see isolationInputBasenames). */
10
+ export declare function isIsolationInputPath(name: string): boolean;