@juangcarmona/lighthouse-sdlc 0.23.2 → 0.23.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/README.md CHANGED
@@ -119,6 +119,7 @@ Install `--with-unattended` explicitly to add fast-forward and test-first hotfix
119
119
  - [Commands](contract.json) and [aliases](command-aliases.json): CLI utilities and agent commands; the configured host exposes aliases.
120
120
  - [Operator reference](github-actions.md): installation, credentials, receipts, runtime limits, maintenance and recovery.
121
121
  - [Execution environments](execution-environments.md) and [model profiles](model-profiles.md): optional runtime configuration.
122
+ - [Execution cleanup](src/execution-cleanup.md): workspace ownership, interrupted recovery and local retention limits.
122
123
  - [External host contract](host-contract.md): legacy host integration; enable only one router for the same events.
123
124
  - [Evidence](commands/evidence.md) and [browser evidence](commands/browser-e2e.md): validation contracts. Missing evidence, unavailable checks and pending review remain separate from success.
124
125
  - [Scoped memory](commands/memory.md): opt-in host-side SQLite retention and selective recall, independent of worker storage and approval authority.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juangcarmona/lighthouse-sdlc",
3
- "version": "0.23.2",
3
+ "version": "0.23.3",
4
4
  "type": "module",
5
5
  "description": "Provider-neutral SDLC skills, commands and route contracts for Lighthouse adopters",
6
6
  "repository": {
@@ -0,0 +1,31 @@
1
+ # Execution resource ownership and retention
2
+
3
+ The OpenCode adapter cleans each admitted attempt, not each issue. Its host engine slot serializes admission; its ownership journal binds the repository, run, workflow attempt and Linux process identity. Cleanup must prove absence, and an error remains visible in `runtime.json`. Historical resources without that proof are not cleanup targets.
4
+
5
+ ## Resource boundary
6
+
7
+ | Resource | Owner and disposal boundary | Retained or excluded state |
8
+ | --- | --- | --- |
9
+ | `RUNNER_TEMP/lighthouse-engine-<owner digest>` | Adapter allocation, recorded before worker access with parent and root device/inode identity; removed only after runtime absence and successful local retention | A replaced root, unknown owner, incomplete allocation or failed collection is preserved and blocks admission |
10
+ | Snapshot `source`, validation `candidate`, workspace `node_modules` and `.cache` | Children of that exact disposable workspace; disposed with the workspace | The original checkout, manual checkouts, modified source outside the snapshot and other runs are never inferred owned |
11
+ | Container `/tmp`, npm command scratch and private cache tmpfs | Existing command/container lifecycle; unchanged by this correction | Inherited host caches, provider paths, NuGet state and caller-selected paths outside the workspace are not swept |
12
+ | Containers, anonymous volumes and private networks | Existing durable Docker ownership and inventory checks; container removal includes anonymous volumes | Named authentication/data volumes and foreign resources remain preserved; no host-wide prune |
13
+ | Child processes | Existing command process-group cleanup, container init and runner Tini | No process-name matching or host-wide process termination |
14
+ | Recovery baseline | Adapter-private, digest-bound copy of bounded original source, tracked paths and admitted policy | Never mounted writable into the worker; used only to retain diagnostic changes, not authorize publication |
15
+ | Local recovery bundles | `resources/retained/<owner digest>` beside ownership journals; candidate changes, bounded worker evidence and an ownership receipt | At most 32 bundles, 512 MiB of content and 8,192 filesystem entries including directories; reaching a limit blocks admission rather than evicting source |
16
+ | Delivery outputs and event logs | Caller-owned `RUNNER_TEMP/lighthouse-<workflow>-<attempt>` and `gh-aw` outputs remain available to publication/artifact collection | Remote artifact lifetime does not delete local files; operators must explicitly archive and release local delivery outputs with their matching recovery bundle |
17
+ | Provider-owned state and historical unowned resources | Outside adapter disposal authority | Separate provider maintenance or migration; never inspect authentication data to decide disposability |
18
+
19
+ ## Recovery and local retention
20
+
21
+ After taking the host slot, a new adapter first runs the existing stopped-owner Docker recovery. It then recovers journaled workspaces only when the original process is confirmed stopped and that owner's runtime receipt is clean. Active or unknown process identities stop admission. Journals from older releases without a workspace record remain Docker-only; directory names do not retroactively establish ownership.
22
+
23
+ Before disposal, the adapter collects candidate edits through its existing bounded source and scope validation and collects worker evidence under the existing 200-file/64-MiB limit. It seals and synchronizes the recovery bundle before recording retention, then removes the workspace and checks absence. A failed or unsafe collection leaves the workspace intact. An interrupted removal can retry from the sealed bundle without requiring the partially removed source tree to be readable. A changed retained bundle blocks removal.
24
+
25
+ Local retention has no automatic age-based eviction. Admission stops at 32 bundles, 512 MiB of content or 8,192 filesystem entries, reserving the minimum three entries for another bundle and its two receipt files. An operator must first reconcile publication and candidate recovery, archive needed local diagnostics, and explicitly release only the matching stopped attempt's bundle and delivery outputs. A completed journal can be archived with that bundle only after confirming its workspace and runtime resources absent. Do not release a bundle still referenced by an incomplete workspace cleanup. Do not infer local deletion authority from a successful remote artifact upload. Unknown or unsafe state requires reconciliation, not additional allocation.
26
+
27
+ ## Verification and adoption
28
+
29
+ The admitted unit and adapter tests cover normal/failure/cancellation paths, stopped and unknown owners, substituted paths, failed collection, interrupted removal and retention limits. Real-process filesystem tests retain five before/during/after byte and inode observations with test-owned dependencies and caches. Complete adapter repetitions use a Docker shim and remain source-level evidence, not native execution qualification.
30
+
31
+ After review and CI, publish the SDLC patch and adopt its released package or immutable source harness through the existing workflow installation route. This host-side change needs no new runner image; preserve the previously adopted Tini image. Confirm installed adoption separately, then qualify repeated complete native implementation workers on an appropriate operator host, retaining byte/inode/resource inventories and evidence-retention outcomes. Real-Docker scenarios require the existing test image and idle-host conditions; do not run global recovery against unrelated active work. Rollback must preserve the ownership journals and recovery bundles for reconciliation.
@@ -3,6 +3,7 @@ import { createHash } from 'node:crypto';
3
3
  import { execFileSync } from 'node:child_process';
4
4
  import { mkdirSync, readFileSync, writeFileSync, renameSync, lstatSync, statSync, readdirSync, openSync, fsyncSync, closeSync } from 'node:fs';
5
5
  import { join, dirname, isAbsolute } from 'node:path';
6
+ import { allocateWorkspace, checkpointWorkspace, disposeWorkspace, checkRetentionCapacity } from './execution-workspace.mjs';
6
7
 
7
8
  const label = 'io.lighthouse.execution';
8
9
  const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
@@ -52,6 +53,9 @@ function openOwner(path, record, run) {
52
53
  const prefix = `lighthouse-${record.key.slice(0, 24)}`;
53
54
  return {
54
55
  prefix,
56
+ allocateWorkspace(parent) { return allocateWorkspace(record, parent, () => persist(path, record), dirname(path)); },
57
+ checkpointWorkspace(baseline, tracked, policy) { return checkpointWorkspace(record, baseline, tracked, policy, () => persist(path, record)); },
58
+ cleanupWorkspace(options) { return disposeWorkspace(record, () => persist(path, record), dirname(path), options); },
55
59
  prepare(args) {
56
60
  const removing = args[0] === 'rm' || args[0] === 'container' && args[1] === 'rm' ? 'container' : args[0] === 'network' && args[1] === 'rm' ? 'network' : null;
57
61
  if (removing) {
@@ -158,6 +162,19 @@ export function recoverExecutionOwners(directory, { run = docker, isStopped = st
158
162
  return receipts;
159
163
  }
160
164
  export const ownedDockerArgs = (config, args) => config.resourceOwner?.prepare(args) ?? args;
165
+ export async function recoverExecutionWorkspaces(directory, { isStopped = stopped } = {}) {
166
+ for (const name of readdirSync(directory).filter(name => name.endsWith('.json'))) {
167
+ const path = join(directory, name), stat = lstatSync(path);
168
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024 * 1024) throw Error('Unsafe execution ownership journal');
169
+ const record = JSON.parse(readFileSync(path, 'utf8')); validate(record);
170
+ if (name !== `${record.key}.json`) throw Error('Execution ownership journal identity mismatch');
171
+ if (!record.workspace || record.workspace.status === 'clean') continue;
172
+ if (isStopped(record.process) !== true) throw Error('Workspace owner is active or unknown; retain its state');
173
+ if (record.cleanup?.status !== 'clean') throw Error('Owned runtime resources must be absent before workspace recovery');
174
+ await disposeWorkspace(record, () => persist(path, record), directory);
175
+ }
176
+ await checkRetentionCapacity(directory);
177
+ }
161
178
  export function runOwnedDocker(config, args, options = {}) {
162
179
  const owned = ownedDockerArgs(config, args);
163
180
  if (!owned.length) return options.encoding ? '' : Buffer.alloc(0);
@@ -0,0 +1,145 @@
1
+ // Host-side only. Never infer disposable ownership from a directory name alone.
2
+ import { mkdir, lstat, realpath, readFile, writeFile, rename, rm, readdir, open } from 'node:fs/promises';
3
+ import { join, dirname, resolve } from 'node:path';
4
+ import { createHash } from 'node:crypto';
5
+
6
+ const hash = bytes => createHash('sha256').update(bytes).digest('hex');
7
+ const maxBundles = 32, maxBytes = 512 * 1024 * 1024, maxEntries = 8192;
8
+ const identity = stat => ({ dev: stat.dev, ino: stat.ino });
9
+ const matches = (stat, expected) => stat.isDirectory() && !stat.isSymbolicLink() && stat.dev === expected.dev && stat.ino === expected.ino;
10
+ async function sync(path) {
11
+ const fd = await open(path, 'r');
12
+ try { await fd.sync(); } finally { await fd.close(); }
13
+ }
14
+ async function seal(root) {
15
+ const files = []; let bytes = 0, entries = 0;
16
+ async function visit(path, relative = '') {
17
+ if (++entries > maxEntries) throw Error('Retained workspace evidence exceeds entry bounds');
18
+ const stat = await lstat(path);
19
+ if (stat.isSymbolicLink() || !stat.isFile() && !stat.isDirectory()) throw Error('Unsafe retained workspace evidence');
20
+ if (stat.isDirectory()) {
21
+ for (const name of (await readdir(path)).sort()) await visit(join(path, name), join(relative, name));
22
+ } else {
23
+ bytes += stat.size;
24
+ if (bytes > 90 * 1024 * 1024 || files.length >= 202) throw Error('Retained workspace evidence exceeds bounds');
25
+ files.push([relative, hash(await readFile(path))]);
26
+ }
27
+ await sync(path);
28
+ }
29
+ await visit(root);
30
+ return hash(JSON.stringify(files));
31
+ }
32
+ async function size(path, total = { bytes: 0, entries: 0 }) {
33
+ if (++total.entries > maxEntries) throw Error('Local recovery retention entry limit reached; operator must archive and explicitly release retained bundles before admission');
34
+ const stat = await lstat(path);
35
+ if (stat.isSymbolicLink() || !stat.isDirectory() && !stat.isFile()) throw Error('Unsafe local recovery storage');
36
+ if (stat.isFile()) total.bytes += stat.size;
37
+ else for (const name of await readdir(path)) await size(join(path, name), total);
38
+ return total;
39
+ }
40
+ export async function checkRetentionCapacity(directory, additionalBytes = 0, additionalBundles = 1) {
41
+ const root = join(directory, 'retained');
42
+ await mkdir(root, { recursive: true, mode: 0o700 });
43
+ const stat = await lstat(root);
44
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw Error('Unsafe local recovery storage');
45
+ const entries = await readdir(root);
46
+ const usage = await size(root);
47
+ if (entries.length + additionalBundles > maxBundles || usage.bytes + additionalBytes > maxBytes || usage.entries + additionalBundles * 3 > maxEntries) throw Error('Local recovery retention limit reached; operator must archive and explicitly release retained bundles before admission');
48
+ }
49
+ export async function allocateWorkspace(record, parent, persist, directory) {
50
+ await checkRetentionCapacity(directory);
51
+ if (record.workspace) throw Error('Workspace ownership already allocated');
52
+ const root = await realpath(parent);
53
+ if (resolve(parent) !== root) throw Error('Workspace parent must be canonical');
54
+ const path = join(root, `lighthouse-engine-${record.key}`);
55
+ record.workspace = { path, parent: identity(await lstat(root)), status: 'allocating' };
56
+ persist(); // Intent before allocation; a lost acknowledgement remains unknown.
57
+ await mkdir(path, { mode: 0o755 });
58
+ await sync(root);
59
+ record.workspace.root = identity(await lstat(path));
60
+ record.workspace.status = 'allocated'; persist();
61
+ return path;
62
+ }
63
+ async function verify(record) {
64
+ const workspace = record.workspace;
65
+ if (!workspace || !workspace.root || !workspace.parent || !workspace.path || workspace.path !== join(dirname(workspace.path), `lighthouse-engine-${record.key}`) || !workspace.path.startsWith('/')) throw Error('Workspace ownership is unknown; operator reconciliation required');
66
+ if (!matches(await lstat(dirname(workspace.path)), workspace.parent)) throw Error('Workspace parent identity changed');
67
+ if (!matches(await lstat(workspace.path), workspace.root)) throw Error('Workspace filesystem identity changed; preserve substituted path');
68
+ return workspace;
69
+ }
70
+ export async function checkpointWorkspace(record, baseline, tracked, policy, persist) {
71
+ const workspace = await verify(record);
72
+ const content = JSON.stringify({ baseline: baseline ? [...baseline].map(([path, file]) => [path, { ...file, content: file.content.toString('base64') }]) : null, tracked: tracked ? [...tracked.keys()] : null, policy });
73
+ if (Buffer.byteLength(content) > 90 * 1024 * 1024) throw Error('Workspace recovery baseline exceeds bounds');
74
+ await writeFile(join(workspace.path, 'recovery.json'), content, { mode: 0o600 });
75
+ await sync(join(workspace.path, 'recovery.json')); await sync(workspace.path);
76
+ workspace.checkpoint = hash(content); persist();
77
+ }
78
+ export async function disposeWorkspace(record, persist, directory, { remove = rm } = {}) {
79
+ if (!record.workspace) return { status: 'not-applicable' };
80
+ const workspace = record.workspace;
81
+ if (record.cleanup?.status !== 'clean') throw Error('Owned runtime cleanup must be clean before workspace disposal');
82
+ try {
83
+ if (workspace.status === 'retaining') {
84
+ await verify(record);
85
+ const staging = join(directory, 'retained', `${record.key}.pending`);
86
+ const destination = join(directory, 'retained', record.key);
87
+ const committed = await lstat(destination).then(() => true, error => { if (error.code === 'ENOENT') return false; throw error; });
88
+ if (await seal(committed ? destination : staging) !== workspace.retentionDigest) throw Error('Retained workspace evidence changed; preserve source');
89
+ if (!committed) { await rename(staging, destination); await sync(dirname(destination)); }
90
+ workspace.status = 'retained'; persist();
91
+ }
92
+ // A committed retention bundle makes an interrupted remove retryable without recollecting a partial tree.
93
+ if (workspace.status === 'retained') {
94
+ if (workspace.retained !== join(directory, 'retained', record.key) || await seal(workspace.retained) !== workspace.retentionDigest) throw Error('Retained workspace evidence changed; preserve source');
95
+ try { await verify(record); } catch (error) {
96
+ if (error.code !== 'ENOENT' || await lstat(workspace.path).then(() => true, e => { if (e.code === 'ENOENT') return false; throw e; })) throw error;
97
+ workspace.status = 'clean'; persist(); return { status: 'clean', retained: workspace.retained };
98
+ }
99
+ } else {
100
+ await verify(record);
101
+ const { copyEvidence } = await import('./implementation-runtime.mjs');
102
+ const { sourceFiles, collectChanges } = await import('./implementation.mjs');
103
+ let changes = [];
104
+ if (workspace.checkpoint) {
105
+ const path = join(workspace.path, 'recovery.json'), stat = await lstat(path);
106
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 90 * 1024 * 1024) throw Error('Unsafe workspace recovery baseline');
107
+ const raw = await readFile(path);
108
+ if (hash(raw) !== workspace.checkpoint) throw Error('Workspace recovery baseline changed');
109
+ const checkpoint = JSON.parse(raw);
110
+ if (checkpoint.baseline) {
111
+ const baseline = new Map(checkpoint.baseline.map(([path, file]) => [path, { ...file, content: Buffer.from(file.content, 'base64') }]));
112
+ const tracked = new Map(checkpoint.tracked.map(path => [path, baseline.get(path) ?? {}]));
113
+ changes = collectChanges(baseline, await sourceFiles(join(workspace.path, 'source'), tracked), checkpoint.policy);
114
+ }
115
+ } else {
116
+ // Preparation never exposed a worker; any source present must still be retained, not guessed disposable.
117
+ const source = join(workspace.path, 'source');
118
+ if (await readdir(source).then(names => names.length > 0, e => { if (e.code === 'ENOENT') return false; throw e; })) throw Error('Workspace has source but no recovery checkpoint; preserve for operator reconciliation');
119
+ }
120
+ const root = join(directory, 'retained'), staging = join(root, `${record.key}.pending`), destination = join(root, record.key);
121
+ // Staging is itself journal-owned and never follows an outside path.
122
+ await checkRetentionCapacity(directory, 0, 0);
123
+ try { await mkdir(staging, { mode: 0o700 }); } catch (error) { if (error.code !== 'EEXIST') throw error; throw Error('Interrupted retention staging requires operator reconciliation'); }
124
+ try {
125
+ await copyEvidence(join(workspace.path, 'output/evidence'), join(staging, 'evidence'));
126
+ await writeFile(join(staging, 'changes.json'), JSON.stringify(changes), { mode: 0o600 });
127
+ await writeFile(join(staging, 'receipt.json'), JSON.stringify({ identity: record.identity, owner: record.key, recoveredAt: new Date().toISOString(), candidateFiles: changes.length }), { mode: 0o600 });
128
+ await checkRetentionCapacity(directory, 0, 0);
129
+ workspace.retained = destination; workspace.retentionDigest = await seal(staging); workspace.status = 'retaining'; persist();
130
+ await rename(staging, destination); await sync(root);
131
+ } catch (error) { if (workspace.status !== 'retaining') await rm(staging, { recursive: true, force: true }); throw error; }
132
+ workspace.retained = destination; workspace.status = 'retained'; persist();
133
+ }
134
+ if (workspace.retained !== join(directory, 'retained', record.key) || await seal(workspace.retained) !== workspace.retentionDigest) throw Error('Retained workspace evidence changed; preserve source');
135
+ await verify(record);
136
+ await remove(workspace.path, { recursive: true, force: true });
137
+ await lstat(workspace.path).then(() => { throw Error('Workspace remains after removal'); }, error => { if (error.code !== 'ENOENT') throw error; });
138
+ await sync(dirname(workspace.path));
139
+ workspace.status = 'clean'; persist();
140
+ return { status: 'clean', retained: workspace.retained };
141
+ } catch (error) {
142
+ workspace.error = 'Workspace retention or disposal failed; preserve state for operator reconciliation'; persist();
143
+ throw error;
144
+ }
145
+ }
@@ -17,7 +17,7 @@ import { selectEnvironment, startEnvironment, environmentArgs, environmentReceip
17
17
  import { resolveModelProfile, modelExecutionReceipt } from './model-profiles.mjs';
18
18
  import { executionLimits, resourceArgs, imageCommand, executionReceipt, executionFailure } from './execution-resources.mjs';
19
19
  import { codegraphSelection, startCodegraph, stopCodegraph } from './codegraph-runtime.mjs';
20
- import { createExecutionOwner, recoverExecutionOwners, ownedDockerArgs, runOwnedDocker } from './execution-cleanup.mjs';
20
+ import { createExecutionOwner, recoverExecutionOwners, recoverExecutionWorkspaces, ownedDockerArgs, runOwnedDocker } from './execution-cleanup.mjs';
21
21
  import { harnessIdentity } from './harness-identity.mjs';
22
22
  import { verificationIntegrity } from './verification-integrity.mjs';
23
23
  import { implementationPlanMetadata, prepareImplementationPlanMetadata } from './implementation-plan.mjs';
@@ -142,10 +142,7 @@ async function main() {
142
142
  config.image = config.implementationImage;
143
143
  }
144
144
  if (!/^[a-f0-9]{64}$/.test(request.runId)) throw Error('Invalid execution identity');
145
- const dir = await mkdtemp(join(env.RUNNER_TEMP, 'lighthouse-engine-'));
146
- await chmod(dir, 0o755);
147
- const source = join(dir, 'source'), output = join(dir, 'output');
148
- await mkdir(source); await mkdir(output); await chmod(output, 0o777);
145
+ let dir, source, output;
149
146
  let name;
150
147
  const harness = resolve(dirname(fileURLToPath(import.meta.url)), '..');
151
148
  const runtimeReceipt = { ...await harnessIdentity(harness), image: config.image, limits, environment: environmentReceipt(selected), model: modelSelection.model, modelExecution: modelExecutionReceipt(modelSelection, request.modelSelection), engine: 'OpenCode 2.1.0', isolation: 'Docker; no AWF egress filtering', skills: await readdir(join(harness, 'skills')), sourceRevision: request.sourceRevision, seed: request.implementation?.policy.seed ?? null, seedDigest: request.seedDigest ?? null, phases: {} };
@@ -175,8 +172,12 @@ async function main() {
175
172
  telemetry.emit('execution.host-wait.ended', { status: 'acquired', durationMs: Date.now() - waitStarted });
176
173
  const ownershipDirectory = `${config.lock}.resources`;
177
174
  runtimeReceipt.recoveredCleanup = recoverExecutionOwners(ownershipDirectory);
175
+ await recoverExecutionWorkspaces(ownershipDirectory);
178
176
  const command = imageCommand(config.image);
179
177
  config.resourceOwner = createExecutionOwner(ownershipDirectory, { repository: request.repository ?? env.GITHUB_REPOSITORY, runId: request.runId, workflowRunId: String(env.GITHUB_RUN_ID), attempt: Number(env.GITHUB_RUN_ATTEMPT) });
178
+ dir = await config.resourceOwner.allocateWorkspace(env.RUNNER_TEMP);
179
+ source = join(dir, 'source'); output = join(dir, 'output');
180
+ await mkdir(source); await mkdir(output); await chmod(output, 0o777);
180
181
  name = `${config.resourceOwner.prefix}-engine`;
181
182
  await recordPhase('running');
182
183
  runtime = await startEnvironment({ selected, image: config.image, commands: implementing ? [['git'], ['sh'], ...(request.implementation.policy.checks ?? [])] : [], name: `${name}-agent`, uid: config.uid, run: args => runOwnedDocker(config, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 30000 }) });
@@ -184,12 +185,14 @@ async function main() {
184
185
  if (cancelled || !checkController()) throw Error('Execution cancelled before agent startup');
185
186
  console.log('Engine slot acquired; starting isolated OpenCode');
186
187
  await snapshotSource(env.GITHUB_WORKSPACE, source);
188
+ if (!implementing) await config.resourceOwner.checkpointWorkspace(null, null, undefined);
187
189
  if (request.worker === 'product-change') {
188
190
  if (!/^[a-f0-9]{64}$/.test(request.baselineDigest ?? '')) throw Error('ProductShape evidence lacks its authenticated baseline');
189
191
  await installProductEvidence(join(runDir, 'product-evidence'), source, request.baselineDigest);
190
192
  } else if (!implementing) runtimeReceipt.productEvidence = await preparePlanningProductEvidence(source, runDir, { signal: preparation.signal });
191
193
  baseline = implementing ? await sourceFiles(source) : null;
192
194
  trackedSource = baseline ? new Map(baseline) : null;
195
+ if (implementing) await config.resourceOwner.checkpointWorkspace(baseline, trackedSource, request.implementation.policy);
193
196
  if (implementing) {
194
197
  if (request.sourceSynchronization) {
195
198
  if (!isVerificationOnlyCorrection(request) || request.epic || request.productResume || request.productAlignment || request.seedDigest || request.implementation.policy.verification?.synchronizeBase !== true || request.sourceSynchronization.source !== request.sourceRevision || request.sourceSynchronization.base !== request.baseRevision) throw Error('Unauthorized source synchronization');
@@ -219,6 +222,7 @@ async function main() {
219
222
  }
220
223
  await prepareImplementationWorkspace(source, config, request.issue, repository);
221
224
  }
225
+ await config.resourceOwner.checkpointWorkspace(baseline, trackedSource, request.implementation?.policy);
222
226
  const context = join(dir, 'context.json');
223
227
  await copyFile(join(runDir, 'context.json'), context); await chmod(context, 0o444);
224
228
  if (reviewOutput) {
@@ -376,6 +380,8 @@ async function main() {
376
380
  telemetry.emit('execution.result', { status: outcome, reasonCode: outcome === 'blocked' ? envelope.result.pendingReview.length ? 'pending-review' : 'missing-evidence' : 'validated-result' });
377
381
  } catch (error) {
378
382
  error.phase = phase;
383
+ runtimeReceipt.failure = { phase, message: redactLog(error.message).slice(0, 3000) };
384
+ console.error(progressText('Failure', runtimeReceipt.failure.message));
379
385
  await recordPhase('failed');
380
386
  if (implementing && baseline) {
381
387
  try {
@@ -407,10 +413,19 @@ async function main() {
407
413
  try {
408
414
  if (config.resourceOwner) { runtimeReceipt.cleanup = config.resourceOwner.cleanup(); await writeFile(join(runDir, 'runtime.json'), JSON.stringify(runtimeReceipt)); }
409
415
  try { await mkdir(join(runDir, 'evidence/host'), { recursive: true }); await copyFile(join(output, 'execution/native-events.jsonl'), join(runDir, 'evidence/host/native-events.jsonl')); } catch { telemetry.emit('collection.capability', { capability: 'opencode-native', status: 'unavailable', reasonCode: 'native-file-unavailable' }); }
416
+ let workspaceCleanupError;
417
+ if (config.resourceOwner) {
418
+ try { runtimeReceipt.workspaceCleanup = await config.resourceOwner.cleanupWorkspace(); }
419
+ catch (error) {
420
+ runtimeReceipt.workspaceCleanup = { status: 'failed', action: 'Retain the workspace and reconcile local evidence and candidate recovery before retrying.' };
421
+ workspaceCleanupError = Object.assign(Error(`Workspace cleanup is not verified: ${error.message}`), { phase: 'cleanup' });
422
+ }
423
+ await writeFile(join(runDir, 'runtime.json'), JSON.stringify(runtimeReceipt));
424
+ }
410
425
  if (runtimeReceipt.execution?.resourceSamplesDropped) telemetry.emit('collection.gap', { reasonCode: 'resource-sample-capacity', omittedEvents: runtimeReceipt.execution.resourceSamplesDropped });
411
426
  telemetry.emit('execution.resources', { ...runtimeReceipt.execution?.resources });
412
- telemetry.emit('execution.cleanup', { status: runtimeReceipt.cleanup?.status ?? 'unknown' });
413
- telemetry.emit('execution.ended', { status: stopReason ?? (runtimeReceipt.cleanup && runtimeReceipt.cleanup.status !== 'clean' ? 'cleanup-failed' : outcome), exitCode: runtimeReceipt.execution?.exitCode, signal: runtimeReceipt.execution?.signal });
427
+ telemetry.emit('execution.cleanup', { status: workspaceCleanupError ? 'failed' : runtimeReceipt.cleanup?.status ?? 'unknown' });
428
+ telemetry.emit('execution.ended', { status: workspaceCleanupError ? 'cleanup-failed' : stopReason ?? (runtimeReceipt.cleanup && runtimeReceipt.cleanup.status !== 'clean' ? 'cleanup-failed' : outcome), exitCode: runtimeReceipt.execution?.exitCode, signal: runtimeReceipt.execution?.signal });
414
429
  telemetry.close(outcome);
415
430
  try {
416
431
  const events = readTelemetry(telemetry.directory, { stream: telemetry.stream });
@@ -419,7 +434,7 @@ async function main() {
419
434
  await writeFile(join(runDir, 'evidence/host/telemetry-usage.json'), JSON.stringify(usageSummary(events, { health: [telemetry.health()] })));
420
435
  runtimeReceipt.telemetry = telemetry.health(); await writeFile(join(runDir, 'runtime.json'), JSON.stringify(runtimeReceipt));
421
436
  } catch { console.error('Telemetry retention incomplete; inspect collector health.'); }
422
- await rm(dir, { recursive: true, force: true });
437
+ if (workspaceCleanupError) throw workspaceCleanupError;
423
438
  } finally { if (slot !== undefined) closeSync(slot); }
424
439
  if (runtimeReceipt.cleanup && runtimeReceipt.cleanup.status !== 'clean') throw Object.assign(Error('Execution cleanup is not verified; inspect runtime.json and the operator ownership journal before retrying'), { phase: 'cleanup' });
425
440
  }