| 1 | import { createHash } from 'node:crypto'; |
| 2 | import { join, resolve } from 'node:path'; |
| 3 | import { Worker } from 'node:worker_threads'; |
| 4 | import { deliveryArtifactPaths, deliveryScopePatterns } from "./quality-gates.js"; |
| 5 | import { readTeam } from "./state.js"; |
| 6 | function incomplete(reason) { |
| 7 | return { artifacts: [], expandedScope: [], gaps: [{ pattern: '(workspace audit)', reason }] }; |
| 8 | } |
| 9 | function isAudit(value) { |
| 10 | if (typeof value !== 'object' || value === null) |
| 11 | return false; |
| 12 | const audit = value; |
| 13 | return Array.isArray(audit.artifacts) |
| 14 | && audit.artifacts.every(item => typeof item?.path === 'string' && typeof item.present === 'boolean' |
| 15 | && (item.present !== true || (typeof item.sha256 === 'string' && /^[a-f0-9]{64}$/.test(item.sha256)))) |
| 16 | && Array.isArray(audit.expandedScope) |
| 17 | && audit.expandedScope.every(item => typeof item?.path === 'string' && typeof item.present === 'boolean') |
| 18 | && (audit.gaps === undefined || (Array.isArray(audit.gaps) |
| 19 | && audit.gaps.every(gap => typeof gap?.pattern === 'string' && typeof gap.reason === 'string'))); |
| 20 | } |
| 21 | /** |
| 22 | * One lazy, reusable worker per plugin owner. Identical requests may share a |
| 23 | * queued audit until it is dispatched. Every later request needs a read that |
| 24 | * starts after it arrives. |
| 25 | */ |
| 26 | export class WorkspaceAuditService { |
| 27 | options; |
| 28 | worker; |
| 29 | active; |
| 30 | timer; |
| 31 | idleTimer; |
| 32 | jobs = new Set(); |
| 33 | queue = []; |
| 34 | sequence = 0; |
| 35 | closed = false; |
| 36 | constructor(options = {}) { |
| 37 | this.options = options; |
| 38 | } |
| 39 | audit(workspace, team, stateRoot = join(workspace, '.agent-teams')) { |
| 40 | if (this.closed) |
| 41 | return Promise.resolve(incomplete('workspace audit service was disposed; retry after reload')); |
| 42 | if (deliveryArtifactPaths(team).length === 0 && deliveryScopePatterns(team).length === 0) { |
| 43 | return Promise.resolve({ artifacts: [], expandedScope: [] }); |
| 44 | } |
| 45 | const source = JSON.stringify(team); |
| 46 | const key = `${resolve(workspace)}\0${resolve(stateRoot)}\0${team.id}\0${createHash('sha256').update(source).digest('hex')}`; |
| 47 | const existing = this.queue.find(job => job.key === key); |
| 48 | if (existing !== undefined) |
| 49 | return existing.promise; |
| 50 | if (this.jobs.size >= (this.options.maxPending ?? 16)) { |
| 51 | return Promise.resolve(incomplete('workspace audit queue is full; retry instead of treating unaudited bytes as verified')); |
| 52 | } |
| 53 | let complete; |
| 54 | const promise = new Promise(done => { complete = done; }); |
| 55 | const job = { id: ++this.sequence, key, workspace, stateRoot, source, team: JSON.parse(source), promise, complete }; |
| 56 | this.jobs.add(job); |
| 57 | this.queue.push(job); |
| 58 | this.pump(); |
| 59 | return promise; |
| 60 | } |
| 61 | pump() { |
| 62 | if (this.closed || this.active !== undefined || this.queue.length === 0) |
| 63 | return; |
| 64 | clearTimeout(this.idleTimer); |
| 65 | this.idleTimer = undefined; |
| 66 | const job = this.queue.shift(); |
| 67 | this.active = job; |
| 68 | try { |
| 69 | if (this.worker === undefined) { |
| 70 | const worker = new Worker(this.options.workerUrl ?? new URL('./workspace-audit-worker.js', import.meta.url)); |
| 71 | this.worker = worker; |
| 72 | worker.on('message', (message) => { |
| 73 | if (this.worker !== worker) |
| 74 | return; |
| 75 | const reply = message; |
| 76 | if (reply === null || typeof reply !== 'object' || reply.id !== this.active?.id) { |
| 77 | this.failWorker('workspace audit worker returned an invalid response'); |
| 78 | return; |
| 79 | } |
| 80 | const current = this.active; |
| 81 | this.active = undefined; |
| 82 | clearTimeout(this.timer); |
| 83 | this.timer = undefined; |
| 84 | worker.unref(); |
| 85 | const audit = isAudit(reply.audit) |
| 86 | ? reply.audit |
| 87 | : incomplete(typeof reply.error === 'string' ? `workspace audit failed: ${reply.error}` : 'workspace audit worker returned incomplete evidence'); |
| 88 | void this.finish(current, audit); |
| 89 | this.pump(); |
| 90 | if (this.active === undefined) { |
| 91 | this.idleTimer = setTimeout(() => { |
| 92 | if (this.worker === worker && this.active === undefined) { |
| 93 | this.worker = undefined; |
| 94 | void worker.terminate(); |
| 95 | } |
| 96 | }, 10_000); |
| 97 | this.idleTimer.unref(); |
| 98 | } |
| 99 | }); |
| 100 | worker.on('error', error => { if (this.worker === worker) |
| 101 | this.failWorker(`workspace audit worker failed: ${error.message}`); }); |
| 102 | worker.on('exit', code => { if (this.worker === worker) |
| 103 | this.failWorker(`workspace audit worker exited (${code}) before completing its evidence`); }); |
| 104 | } |
| 105 | this.worker.ref(); |
| 106 | this.timer = setTimeout(() => this.failWorker('workspace audit timed out; current bytes could not be verified'), this.options.timeoutMs ?? 120_000); |
| 107 | this.worker.postMessage({ id: job.id, workspace: job.workspace, team: job.team }); |
| 108 | } |
| 109 | catch (error) { |
| 110 | this.failWorker(`workspace audit could not start: ${String(error)}`); |
| 111 | } |
| 112 | } |
| 113 | async finish(job, audit) { |
| 114 | try { |
| 115 | // Hashing yields the host thread, so a newer task attempt, edit, archive |
| 116 | // or replacement team can win while the worker is running. Never apply |
| 117 | // the old answer to that new record, even when its artifact paths match. |
| 118 | const current = await readTeam(job.stateRoot, job.team.id); |
| 119 | if (current === undefined || JSON.stringify(current) !== job.source) { |
| 120 | audit = { ...audit, gaps: [...audit.gaps ?? [], { pattern: '(team revision)', reason: 'team state changed during the workspace audit; retry the current revision' }] }; |
| 121 | } |
| 122 | } |
| 123 | catch (error) { |
| 124 | audit = { ...audit, gaps: [...audit.gaps ?? [], { pattern: '(team revision)', reason: `team state could not be revalidated after the workspace audit: ${String(error)}` }] }; |
| 125 | } |
| 126 | if (!this.jobs.delete(job)) |
| 127 | return; |
| 128 | job.complete(this.closed ? incomplete('workspace audit service was disposed before its result could be applied') : audit); |
| 129 | } |
| 130 | failWorker(reason) { |
| 131 | const worker = this.worker; |
| 132 | this.worker = undefined; |
| 133 | this.active = undefined; |
| 134 | clearTimeout(this.timer); |
| 135 | clearTimeout(this.idleTimer); |
| 136 | this.timer = undefined; |
| 137 | this.idleTimer = undefined; |
| 138 | this.queue.length = 0; |
| 139 | for (const job of this.jobs) |
| 140 | job.complete(incomplete(reason)); |
| 141 | this.jobs.clear(); |
| 142 | return worker?.terminate(); |
| 143 | } |
| 144 | /** Unload cancels active/queued work; late replies can never restore a pass. */ |
| 145 | async dispose() { |
| 146 | this.closed = true; |
| 147 | await this.failWorker('workspace audit was cancelled when its owner unloaded'); |
| 148 | } |
| 149 | } |
| 150 | const owners = new WeakMap(); |
| 151 | /** Share tools/panel work and release the worker with its Cordis owner. */ |
| 152 | export function workspaceAuditor(ctx) { |
| 153 | let service = owners.get(ctx); |
| 154 | if (service !== undefined) |
| 155 | return service; |
| 156 | service = new WorkspaceAuditService(); |
| 157 | owners.set(ctx, service); |
| 158 | const owned = service; |
| 159 | ctx.effect(() => () => { |
| 160 | // A reloaded Cordis fiber gets a new Context. Keep this disposed owner's |
| 161 | // service so a late callback cannot start new work after unload. |
| 162 | return owned.dispose(); |
| 163 | }, 'agent-teams: workspace audit worker'); |
| 164 | return service; |
| 165 | } |
| 166 |