@tnunamak/dalan 0.0.0-stage → 0.6.0
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/CHANGELOG.md +176 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +204 -0
- package/PROTOCOL.md +351 -0
- package/README.md +215 -2
- package/SECURITY.md +30 -0
- package/bin/dalan.mjs +43 -0
- package/bin/dot-acp-agent.mjs +377 -0
- package/bin/dot-alert.mjs +9 -0
- package/bin/dot-deadman.mjs +82 -0
- package/bin/dot-heartbeat.mjs +29 -0
- package/bin/dot-pr-reviewer.mjs +32 -0
- package/bin/dot-worker.mjs +764 -0
- package/docs/chatgpt-worker-onboarding.md +112 -0
- package/docs/claude-worker-onboarding.md +113 -0
- package/docs/codex-to-muse.md +175 -0
- package/docs/connect-chatgpt.md +83 -0
- package/docs/connection-longevity.md +43 -0
- package/docs/dalan-upgrade.md +246 -0
- package/docs/deadman.md +61 -0
- package/docs/dot-pr-reviewer.config.example.json +9 -0
- package/docs/durability-audit.md +27 -0
- package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
- package/docs/keycloak-oauth-setup.md +30 -0
- package/docs/local-agent-mcp.md +41 -0
- package/docs/manual-setup.md +135 -0
- package/docs/mirror-fetch.md +97 -0
- package/docs/operations.md +799 -0
- package/docs/operator-duties.md +68 -0
- package/docs/owner-integrator.md +27 -0
- package/docs/portable-auth-profile.md +107 -0
- package/docs/pr-head-reviewer.md +70 -0
- package/docs/pr-preflight.md +28 -0
- package/docs/pull-queue.md +131 -0
- package/docs/pull-workers.md +94 -0
- package/docs/redaction.md +27 -0
- package/docs/service-setup.md +219 -0
- package/docs/setup-reference.md +80 -0
- package/docs/t3-connector-icon.png +0 -0
- package/docs/t3-integration.md +51 -0
- package/docs/t3-result-retry-delivery.md +41 -0
- package/docs/t3-reverse-control.md +107 -0
- package/docs/usage.md +443 -0
- package/docs/worker-clients.md +290 -0
- package/integrations/t3/acp-kit/src/capability.mjs +25 -0
- package/integrations/t3/acp-kit/src/errors.mjs +13 -0
- package/integrations/t3/acp-kit/src/index.mjs +5 -0
- package/integrations/t3/acp-kit/src/lock.mjs +155 -0
- package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
- package/package.json +67 -4
- package/packages/job-core/README.md +18 -0
- package/packages/job-core/index.mjs +2 -0
- package/packages/job-core/package.json +8 -0
- package/packages/job-core/protocol/canonical.mjs +11 -0
- package/packages/job-core/protocol/v0/command.schema.json +1154 -0
- package/packages/job-core/protocol/v0/event.schema.json +77 -0
- package/packages/job-core/protocol/v0/reply.schema.json +59 -0
- package/packages/job-core/transitions.mjs +25 -0
- package/scripts/daily-selfcheck.mjs +135 -0
- package/scripts/dalan-try-selfcheck.mjs +29 -0
- package/scripts/lib/expose-tailscale.mjs +408 -0
- package/scripts/live-trial/common.mjs +272 -0
- package/scripts/monitor-targets.mjs +44 -0
- package/scripts/upgrade-drain.mjs +39 -0
- package/scripts/worker-bridge-setup.mjs +925 -0
- package/src/ack-ledger.mjs +37 -0
- package/src/acp-bridge.mjs +418 -0
- package/src/acp-context.mjs +138 -0
- package/src/admin-socket.mjs +14 -0
- package/src/alerts.mjs +147 -0
- package/src/artifact-journal.mjs +75 -0
- package/src/as-files.mjs +347 -0
- package/src/as-store.mjs +456 -0
- package/src/as.mjs +538 -0
- package/src/auth.mjs +166 -0
- package/src/builtin-http.mjs +22 -0
- package/src/check-coverage.mjs +38 -0
- package/src/check-lint.mjs +88 -0
- package/src/check-readiness.mjs +112 -0
- package/src/check-response.mjs +19 -0
- package/src/child-exit.mjs +18 -0
- package/src/child-registry.mjs +94 -0
- package/src/claim-command-ledger.mjs +51 -0
- package/src/cli-help.mjs +186 -0
- package/src/cli-name.mjs +16 -0
- package/src/connect-cli.mjs +126 -0
- package/src/consumers.mjs +61 -0
- package/src/deadman.mjs +329 -0
- package/src/delivery.mjs +19 -0
- package/src/demo-worker.mjs +150 -0
- package/src/destinations/index.mjs +23 -0
- package/src/destinations/none.mjs +15 -0
- package/src/destinations/t3.mjs +109 -0
- package/src/diagnostic.mjs +78 -0
- package/src/docs-url.mjs +9 -0
- package/src/drain-runner.mjs +9 -0
- package/src/drained-owner.mjs +26 -0
- package/src/drained-slot.mjs +70 -0
- package/src/drained.mjs +40 -0
- package/src/durable-waiters.mjs +236 -0
- package/src/env.mjs +19 -0
- package/src/execution.mjs +112 -0
- package/src/failure-type.mjs +28 -0
- package/src/get-summary.mjs +32 -0
- package/src/git-env.mjs +15 -0
- package/src/host-budget-receipts.mjs +154 -0
- package/src/host-budget-seccomp.py +33 -0
- package/src/host-budget-service.mjs +54 -0
- package/src/host-budget-stop.mjs +26 -0
- package/src/host-budget-storage.py +259 -0
- package/src/host-budget.mjs +149 -0
- package/src/host-cgroup.mjs +23 -0
- package/src/host-check-allowlist.mjs +42 -0
- package/src/host-execution-policy.mjs +38 -0
- package/src/host-health.mjs +34 -0
- package/src/host-stop-reverify.mjs +44 -0
- package/src/inbox.mjs +55 -0
- package/src/integrator.mjs +322 -0
- package/src/job-retention.mjs +69 -0
- package/src/legacy-names.mjs +8 -0
- package/src/lifecycle.mjs +291 -0
- package/src/limits.mjs +31 -0
- package/src/loopback.mjs +9 -0
- package/src/mcp-outcome.mjs +79 -0
- package/src/mcp-sse.mjs +62 -0
- package/src/mcp-stdio.mjs +191 -0
- package/src/mirror-fetch-lock.py +164 -0
- package/src/mirror-fetch.mjs +174 -0
- package/src/notify-ledger.mjs +82 -0
- package/src/objectives.mjs +129 -0
- package/src/owner-report-artifact.mjs +66 -0
- package/src/patch-apply.mjs +84 -0
- package/src/path-syntax.mjs +16 -0
- package/src/paths.mjs +67 -0
- package/src/pr-head-reviewer.mjs +596 -0
- package/src/pr-preflight.mjs +51 -0
- package/src/prepared-node-modules.mjs +129 -0
- package/src/process-inspection.mjs +36 -0
- package/src/projects.mjs +480 -0
- package/src/protocol-artifact-commands.mjs +52 -0
- package/src/protocol-delivery-driver.mjs +167 -0
- package/src/protocol-finish.mjs +100 -0
- package/src/protocol-owner-command.mjs +35 -0
- package/src/protocol-owner-mutations.mjs +22 -0
- package/src/protocol-owner-waiters.mjs +67 -0
- package/src/protocol-retention.mjs +52 -0
- package/src/protocol-services.mjs +61 -0
- package/src/protocol-stop-observer.mjs +131 -0
- package/src/publish-plan.mjs +245 -0
- package/src/pull-queue.mjs +159 -0
- package/src/redaction.mjs +763 -0
- package/src/rejections.mjs +18 -0
- package/src/request-log.mjs +102 -0
- package/src/restore-check.mjs +90 -0
- package/src/result-binding.mjs +65 -0
- package/src/route-setting.mjs +24 -0
- package/src/runtime-check.mjs +13 -0
- package/src/sandbox-supervisor.mjs +105 -0
- package/src/schema-subset.mjs +186 -0
- package/src/scopes.mjs +15 -0
- package/src/server.mjs +1468 -0
- package/src/service-migrate-workers.mjs +113 -0
- package/src/service.mjs +388 -0
- package/src/setup.mjs +63 -0
- package/src/shutdown-signal.mjs +12 -0
- package/src/signal-sandbox-processes.py +56 -0
- package/src/signal.mjs +119 -0
- package/src/status-evidence.mjs +47 -0
- package/src/status-summary.mjs +54 -0
- package/src/store.mjs +3069 -0
- package/src/submission-policy.mjs +623 -0
- package/src/subscription-storage.mjs +64 -0
- package/src/t3-audit.mjs +120 -0
- package/src/t3-control.mjs +102 -0
- package/src/t3-transport.mjs +158 -0
- package/src/t3.mjs +209 -0
- package/src/terminal-safe.mjs +19 -0
- package/src/tool-registry.mjs +453 -0
- package/src/try-command.mjs +11 -0
- package/src/try-exposure.mjs +908 -0
- package/src/try-hosted-clients.mjs +46 -0
- package/src/try-hosted.mjs +444 -0
- package/src/try-selfcheck.mjs +168 -0
- package/src/try.mjs +635 -0
- package/src/webhooks.mjs +86 -0
- package/src/work-order.mjs +265 -0
- package/src/worker-instructions.mjs +26 -0
- package/src/worker-prompt.mjs +4 -0
- package/src/workers.mjs +632 -0
- package/src/workspace.mjs +1065 -0
- package/systemd/dot-bridge-heartbeat.service +18 -0
- package/systemd/dot-bridge-heartbeat.timer +10 -0
- package/systemd/dot-bridge-selfcheck.service +12 -0
- package/systemd/dot-bridge-selfcheck.timer +11 -0
- package/systemd/dot-bridge.service +17 -0
- package/systemd/dot-deadman.service +30 -0
- package/systemd/dot-pr-reviewer.service +11 -0
- package/systemd/dot-pr-reviewer.timer +10 -0
package/src/inbox.mjs
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// `dalan inbox`: what of mine finished, is unread, or needs an answer. Pure classification of /owner-states rows;
|
|
2
|
+
// bin/dot-worker.mjs does the reads. Nothing here, or in the batch read behind it, records an owner read.
|
|
3
|
+
|
|
4
|
+
import { terminalSafeLine } from './terminal-safe.mjs';
|
|
5
|
+
export const inboxGroups=['finished_unread','question','undecided','cancelled_unread'];
|
|
6
|
+
export const decideWords='accepted|applied|useful_no_change|useful_negative|not_useful';
|
|
7
|
+
const firstLine=text=>{ const line=String(text).split('\n').find(l=>l.trim())?.trim()??''; return line.length>100?line.slice(0,97)+'...':line; };
|
|
8
|
+
|
|
9
|
+
// One owner-states row to an inbox item, or null when the owner has nothing to do for it.
|
|
10
|
+
export function inboxItem(state) {
|
|
11
|
+
const v=state.inbox;
|
|
12
|
+
if(!v||state.error) return null;
|
|
13
|
+
const base={request_id:state.request_id,worker:v.target_worker,title:firstLine(v.brief)};
|
|
14
|
+
const failure=v.failure_type?{failure_type:v.failure_type,failure_type_source:v.failure_type_source}:{};
|
|
15
|
+
const get=`dalan get ${state.request_id}`;
|
|
16
|
+
if(state.status==='finished'&&!v.consumed&&!v.delivered_t3) return {group:'finished_unread',...base,...failure,status:v.outcome==='blocked'?'blocked':'finished',finished_at:v.finished_at,updated_at:v.finished_at,next:[get]};
|
|
17
|
+
// Read (or delivered to T3) and not decided: the inbox asks for one word. A stale expiry counts as decided; the owner may still overwrite it.
|
|
18
|
+
if(state.status==='finished'&&(v.consumed||v.delivered_t3)&&v.decision===null) return {group:'undecided',...base,...failure,status:v.outcome==='blocked'?'blocked':'finished',finished_at:v.finished_at,updated_at:v.finished_at,next:[`dalan decide ${state.request_id} ${decideWords}`]};
|
|
19
|
+
if(state.status==='cancelled'&&!v.read&&!v.cancelled_by_owner) return {group:'cancelled_unread',...base,...failure,...(v.failure_type==='expired'?{expired:true}:{}),status:state.status,reason:v.cancelled_reason,updated_at:v.cancelled_at,next:[get]};
|
|
20
|
+
if(state.status!=='finished'&&state.status!=='cancelled'&&v.unanswered_blocker) return {group:'question',...base,status:/^\s*QUESTION:/im.test(v.unanswered_blocker.text)?'question':'blocker',text:firstLine(v.unanswered_blocker.text),updated_at:v.unanswered_blocker.at,next:[get,`dalan note ${state.request_id} "..."`]};
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// '72h', '3d', an RFC3339 time, or 'all' (null: no limit) to a cutoff in ms since the epoch. Anything else throws.
|
|
25
|
+
export function parseWhen(text,now=Date.now()) {
|
|
26
|
+
if(text==='all') return null;
|
|
27
|
+
const rel=/^(\d+)([hd])$/.exec(text??'');
|
|
28
|
+
if(rel) return now-Number(rel[1])*(rel[2]==='h'?3600000:86400000);
|
|
29
|
+
const ms=/^\d{4}-\d\d-\d\dT[\d:.]+(?:Z|[+-]\d\d:\d\d)$/.test(text??'')?Date.parse(text):NaN;
|
|
30
|
+
if(Number.isNaN(ms)) throw new Error(`invalid time '${text}': use Nh, Nd, an RFC3339 time (--since also takes all)`);
|
|
31
|
+
return ms;
|
|
32
|
+
}
|
|
33
|
+
const stale=(item,cutoff)=>cutoff!==null&&item.group!=='question'&&Date.parse(item.updated_at)<cutoff;
|
|
34
|
+
|
|
35
|
+
// Unread finished results older than the window are counted, not listed. Unanswered questions are always listed.
|
|
36
|
+
export function buildInbox(states,scope,{cutoff=null}={}) {
|
|
37
|
+
const all=states.map(inboxItem).filter(Boolean).sort((a,b)=>String(a.updated_at).localeCompare(String(b.updated_at)));
|
|
38
|
+
const items=all.filter(i=>!stale(i,cutoff)), hidden_older=all.length-items.length;
|
|
39
|
+
const delivered_t3=states.filter(s=>!s.error&&s.status==='finished'&&s.inbox&&!s.inbox.consumed&&s.inbox.delivered_t3).length;
|
|
40
|
+
const unknown=states.filter(s=>s.error).map(s=>s.request_id);
|
|
41
|
+
const counts=Object.fromEntries(inboxGroups.map(g=>[g,items.filter(i=>i.group===g).length]));
|
|
42
|
+
return {scope,total:items.length,counts,hidden_older,delivered_t3,items,...(unknown.length?{unknown}:{})};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function formatInbox(inbox) {
|
|
46
|
+
const hidden=inbox.hidden_older?`${inbox.hidden_older} older item${inbox.hidden_older===1?'':'s'} hidden (--since all to show)`:'';
|
|
47
|
+
if(!inbox.total) return hidden?`inbox empty\n${hidden}`:'inbox empty';
|
|
48
|
+
const lines=[];
|
|
49
|
+
for(const g of inboxGroups) for(const i of inbox.items.filter(x=>x.group===g)) {
|
|
50
|
+
const why=i.group==='cancelled_unread'?` (${i.reason??'cancelled'})`:i.group==='question'?` ${i.text}`:'';
|
|
51
|
+
lines.push(terminalSafeLine(`${g} ${i.request_id} ${i.worker} ${i.status} ${i.updated_at??''} ${i.title}${why} -> ${i.next.join(' | ')}`));
|
|
52
|
+
}
|
|
53
|
+
lines.push(`${inbox.total} item${inbox.total===1?'':'s'}: ${inboxGroups.map(g=>`${inbox.counts[g]} ${g}`).join(', ')}${hidden?`; ${hidden}`:''}`);
|
|
54
|
+
return lines.join('\n');
|
|
55
|
+
}
|
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
import { readEnv } from './env.mjs';
|
|
2
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import { applyPatch } from './patch-apply.mjs';
|
|
9
|
+
import { gitEnv } from './git-env.mjs';
|
|
10
|
+
import { MAX_INTEGRATION_PATCH_BYTES, Store } from './store.mjs';
|
|
11
|
+
import { TRUST } from './execution.mjs';
|
|
12
|
+
import { availableChecks, detectCheckWithOrigin, CHECK_INPUT_FILES } from './projects.mjs';
|
|
13
|
+
import { redactSecrets, redactOutput } from './redaction.mjs';
|
|
14
|
+
import { safeDiagnostic } from './diagnostic.mjs';
|
|
15
|
+
import { withCheckCoverage } from './check-coverage.mjs';
|
|
16
|
+
import { sensitiveMasks, validateIntegrationPatch } from './workspace.mjs';
|
|
17
|
+
|
|
18
|
+
const modulePath=fileURLToPath(import.meta.url);
|
|
19
|
+
const buildScratch=path.join(os.homedir(),'.tmp','dalan-integrator');
|
|
20
|
+
const digest=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
21
|
+
const fullSha=/^[0-9a-f]{40,64}$/;
|
|
22
|
+
const shortJson=(value,max=4000)=>String(value??'').slice(0,max);
|
|
23
|
+
// Owner-side verification uses a fixed ceiling; a worker's evidence plan cannot
|
|
24
|
+
// raise it or enable host execution. Each check gets its own service envelope.
|
|
25
|
+
export const INTEGRATOR_HOST_BUDGET=Object.freeze({cpu_ms:30000,wall_ms:60000,memory_bytes:512*1024*1024,processes:64,disk_write_bytes:64*1024*1024,output_bytes:262144});
|
|
26
|
+
|
|
27
|
+
function withinBuildScratch(candidate) {
|
|
28
|
+
const resolved=path.resolve(candidate);
|
|
29
|
+
const allowed=path.resolve(process.argv[2]==='--confined-check-runner'&&readEnv('DALAN_INTEGRATOR_SCRATCH_ROOT')||buildScratch);
|
|
30
|
+
if(resolved!==allowed&&!resolved.startsWith(allowed+path.sep)) throw new Error(`scratch paths must stay under ${allowed}`);
|
|
31
|
+
return resolved;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function makeHostEnv(root) {
|
|
35
|
+
const home=path.join(root,'host-home'),tmp=path.join(root,'host-tmp');
|
|
36
|
+
fs.mkdirSync(home,{recursive:true,mode:0o700});
|
|
37
|
+
fs.mkdirSync(tmp,{recursive:true,mode:0o700});
|
|
38
|
+
return gitEnv({PATH:'/usr/bin:/bin',HOME:home,TMPDIR:tmp,LANG:'C.UTF-8',LC_ALL:'C.UTF-8',TZ:'UTC',GIT_ASKPASS:'/usr/bin/false',GIT_TERMINAL_PROMPT:'0'});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function git(dir,args,{env,input,timeout=30000}={}) {
|
|
42
|
+
const result=spawnSync('git',['-C',dir,...args],{input,encoding:'utf8',timeout,maxBuffer:64*1024*1024,env});
|
|
43
|
+
if(result.error||result.status!==0) {
|
|
44
|
+
// Mask the whole stderr, then clip: a credential crossing the cut leaves no prefix.
|
|
45
|
+
throw new Error(`git ${args[0]} failed: ${safeDiagnostic(String(result.stderr||result.error?.message||'').trim(),500)}`);
|
|
46
|
+
}
|
|
47
|
+
return result.stdout.trim();
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function resolveCheckout(repoDir,env) {
|
|
51
|
+
const top=git(repoDir,['rev-parse','--show-toplevel'],{env});
|
|
52
|
+
return fs.realpathSync(top);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function resolveTarget(repoDir,ref,env) {
|
|
56
|
+
if(typeof ref!=='string'||!ref.trim()||ref.length>1024||ref.includes('\0')||ref.startsWith('-')) throw new Error('invalid target base ref');
|
|
57
|
+
const sha=git(repoDir,['rev-parse','--verify','--end-of-options',`${ref}^{commit}`],{env});
|
|
58
|
+
if(!fullSha.test(sha)) throw new Error('target base ref did not resolve to a full commit SHA');
|
|
59
|
+
return sha;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function filterSafeCheckoutEnv(checkoutDir,env) {
|
|
63
|
+
const result=spawnSync('git',['-C',checkoutDir,'config','--null','--get-regexp','^filter\\..*\\.(smudge|clean|process)$'],
|
|
64
|
+
{encoding:'utf8',timeout:30000,maxBuffer:1024*1024,env});
|
|
65
|
+
if(result.error||result.status!==0&&!(result.status===1&&!result.stdout&&!result.stderr))
|
|
66
|
+
throw new Error(`could not inspect Git filter configuration: ${(result.stderr||result.error?.message||'').trim().slice(0,500)}`);
|
|
67
|
+
if(result.status===1) return env;
|
|
68
|
+
const keys=[...new Set(result.stdout.split('\0').filter(Boolean).map(entry=>{
|
|
69
|
+
const separator=entry.indexOf('\n');
|
|
70
|
+
if(separator<1) throw new Error('could not parse Git filter configuration');
|
|
71
|
+
return entry.slice(0,separator);
|
|
72
|
+
}))];
|
|
73
|
+
const first=Number(env.GIT_CONFIG_COUNT??0);
|
|
74
|
+
if(!Number.isInteger(first)||first<0||first+keys.length>256) throw new Error('too many Git filter settings to disable safely');
|
|
75
|
+
const isolated={...env,GIT_CONFIG_COUNT:String(first+keys.length)};
|
|
76
|
+
keys.forEach((key,index)=>{
|
|
77
|
+
const slot=first+index;
|
|
78
|
+
isolated[`GIT_CONFIG_KEY_${slot}`]=key;
|
|
79
|
+
isolated[`GIT_CONFIG_VALUE_${slot}`]='';
|
|
80
|
+
});
|
|
81
|
+
return isolated;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function checkoutWorktreeWithoutFilters(checkoutDir,sha,env) {
|
|
85
|
+
const safeEnv=filterSafeCheckoutEnv(checkoutDir,env);
|
|
86
|
+
git(checkoutDir,['checkout','--detach',sha],{env:safeEnv});
|
|
87
|
+
return safeEnv;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function worktree(repoDir,sha,root,env,label) {
|
|
91
|
+
const dir=path.join(root,`${label}-${randomUUID()}`);
|
|
92
|
+
git(repoDir,['worktree','add','--no-checkout','--detach',dir,sha],{env});
|
|
93
|
+
const checkoutEnv=checkoutWorktreeWithoutFilters(dir,sha,env);
|
|
94
|
+
return {dir,env:checkoutEnv};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function candidateId(requestId,patchDigest,baseSha,targetSha) {
|
|
98
|
+
const body=[requestId,patchDigest,baseSha,targetSha].join('\0');
|
|
99
|
+
return `cand_${digest(Buffer.from(body)).slice(0,32)}`;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function validateEvidencePlan(plan) {
|
|
103
|
+
if(!plan||typeof plan!=='object'||Array.isArray(plan)||Object.keys(plan).some(key=>!['schema_version','checks'].includes(key))||plan.schema_version!==1||!Array.isArray(plan.checks)||plan.checks.length>30) throw new Error('invalid evidence plan: expected schema_version 1 and at most 30 checks');
|
|
104
|
+
const allowed=new Set(['id','argv','issuer','trust_profile']);
|
|
105
|
+
for(const [index,check] of plan.checks.entries()) {
|
|
106
|
+
if(!check||typeof check!=='object'||Array.isArray(check)||Object.keys(check).some(key=>!allowed.has(key))||Object.keys(check).length!==allowed.size) throw new Error(`invalid evidence plan check ${index}: expected id, argv, issuer, and trust_profile only`);
|
|
107
|
+
if(typeof check.id!=='string'||check.id.length>128||!/^[A-Za-z0-9_.-]+$/.test(check.id)) throw new Error(`invalid evidence plan check ${index}: invalid id`);
|
|
108
|
+
if(!Array.isArray(check.argv)||check.argv.length<1||check.argv.length>64||check.argv.some(arg=>typeof arg!=='string'||!arg||arg.length>8192||arg.includes('\0'))) throw new Error(`invalid evidence plan check ${check.id}: invalid argv`);
|
|
109
|
+
if(typeof check.issuer!=='string'||!check.issuer.trim()||check.issuer.length>200) throw new Error(`invalid evidence plan check ${check.id}: invalid issuer`);
|
|
110
|
+
if(typeof check.trust_profile!=='string'||!check.trust_profile.trim()||check.trust_profile.length>200) throw new Error(`invalid evidence plan check ${check.id}: invalid trust_profile`);
|
|
111
|
+
}
|
|
112
|
+
return plan.checks;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function copyForCheck(source,root,checkId,index) {
|
|
116
|
+
const dir=path.join(root,`check-${index}-${digest(Buffer.from(checkId)).slice(0,12)}`);
|
|
117
|
+
fs.cpSync(source,dir,{recursive:true,dereference:false,errorOnExist:true});
|
|
118
|
+
return dir;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function defaultRunnerRoot(checkoutDir) {
|
|
122
|
+
return withinBuildScratch(path.join(path.dirname(checkoutDir),`integrator-runner-${randomUUID()}`));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function runIsolatedCheck(check,checkoutDir,runnerRoot,repoName) {
|
|
126
|
+
const root=withinBuildScratch(runnerRoot);
|
|
127
|
+
fs.mkdirSync(root,{recursive:true,mode:0o700});
|
|
128
|
+
const sourceCopyDir=path.join(root,'source-exemptions');
|
|
129
|
+
fs.mkdirSync(sourceCopyDir,{mode:0o700});
|
|
130
|
+
const masked=sensitiveMasks(checkoutDir,repoName,sourceCopyDir);
|
|
131
|
+
const request={checkout_dir:checkoutDir,runner_root:root,argv:check.argv,github_repo:repoName,maskPaths:masked.paths,sourceExemptions:masked.sourceExemptions};
|
|
132
|
+
const env={PATH:'/usr/bin:/bin',HOME:path.join(root,'home'),TMPDIR:path.join(root,'tmp'),LANG:'C.UTF-8',LC_ALL:'C.UTF-8',TZ:'UTC',NODE_ENV:'production',DALAN_WORKSPACE_ROOT:path.join(root,'workspace'),DALAN_INTEGRATOR_SCRATCH_ROOT:buildScratch};
|
|
133
|
+
if(readEnv('DALAN_HOST_CHECKS')==='1') env.DALAN_HOST_CHECKS='1';
|
|
134
|
+
if(process.env.XDG_RUNTIME_DIR) env.XDG_RUNTIME_DIR=process.env.XDG_RUNTIME_DIR;
|
|
135
|
+
if(process.env.DBUS_SESSION_BUS_ADDRESS) env.DBUS_SESSION_BUS_ADDRESS=process.env.DBUS_SESSION_BUS_ADDRESS;
|
|
136
|
+
fs.mkdirSync(env.HOME,{recursive:true,mode:0o700});
|
|
137
|
+
fs.mkdirSync(env.TMPDIR,{recursive:true,mode:0o700});
|
|
138
|
+
return new Promise((resolve,reject)=>{
|
|
139
|
+
const child=spawn(process.execPath,[modulePath,'--confined-check-runner'],{env,stdio:['pipe','pipe','pipe'],detached:true});
|
|
140
|
+
let stdout='',stderr='',stderrTruncated=false,settled=false;
|
|
141
|
+
const finish=(error,value)=>{if(settled)return;settled=true;clearTimeout(timer);if(error)reject(error);else resolve(value);};
|
|
142
|
+
child.stdout.setEncoding('utf8');child.stderr.setEncoding('utf8');
|
|
143
|
+
child.stdout.on('data',chunk=>{if(stdout.length<1024*1024) stdout+=chunk;});
|
|
144
|
+
child.stderr.on('data',chunk=>{if(stderr.length+chunk.length>4000) stderrTruncated=true;else if(!stderrTruncated) stderr+=chunk;});
|
|
145
|
+
child.on('error',error=>finish(error));
|
|
146
|
+
child.on('close',code=>{
|
|
147
|
+
if(code!==0) return finish(new Error(`confined check runner exited ${code}: ${stderrTruncated?'[runner error output withheld]':shortJson(redactSecrets(stderr).text,1000)}`));
|
|
148
|
+
try {
|
|
149
|
+
const result=JSON.parse(stdout);
|
|
150
|
+
finish(null,{...result,bytes:Buffer.from(result.bytes??'','base64')});
|
|
151
|
+
} catch { finish(new Error('confined check runner returned invalid output')); }
|
|
152
|
+
});
|
|
153
|
+
const timer=setTimeout(()=>{try{process.kill(-child.pid,'SIGKILL');}catch{};finish(new Error('confined check runner timed out'));},180000);
|
|
154
|
+
child.stdin.end(JSON.stringify(request));
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export function evidenceCheckResult(check,raw) {
|
|
159
|
+
const bytes=Buffer.from(raw.bytes??'');
|
|
160
|
+
const output=redactSecrets(bytes.toString('utf8')).text;
|
|
161
|
+
const successful=[0,77].includes(raw.exit?.code)&&!raw.timedOut&&!raw.cancelled&&raw.stop?.verified===true;
|
|
162
|
+
const row={id:check.id,check_id:check.id,argv:check.argv,issuer:check.issuer,trust_profile:check.trust_profile,status:successful?'completed':'failed',exit_code:raw.exit?.code??null,
|
|
163
|
+
timed_out:!!raw.timedOut,cancelled:!!raw.cancelled,stop_verified:raw.stop?.verified===true,duration_ms:Number(raw.duration_ms)||0,
|
|
164
|
+
output_sha256:digest(Buffer.from(output)),output_bytes:Buffer.byteLength(output),output_preview:shortJson(output),output_redaction_version:1,...(raw.host_budget?{host_budget:raw.host_budget}:{}),...(raw.error?{error:redactSecrets(String(raw.error)).text}:{})};
|
|
165
|
+
const result=withCheckCoverage(row,output);
|
|
166
|
+
if(result.status==='completed') result.status='passed';
|
|
167
|
+
return redactOutput(result);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function evidencePlanStatus(checks) {
|
|
171
|
+
if(!checks.length||checks.some(check=>!['passed','skipped'].includes(check.status))) return 'failed';
|
|
172
|
+
if(checks.some(check=>check.status==='skipped')) return 'skipped';
|
|
173
|
+
return checks.every(check=>check.status==='passed')?'verified':'failed';
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export async function runEvidencePlan(plan,checkoutDir,repoName='integrator/local') {
|
|
177
|
+
const checks=validateEvidencePlan(plan);
|
|
178
|
+
if(checks.length===0) return [{id:'evidence-plan',issuer:'assignment',trust_profile:TRUST.bridge,status:'failed',error:'no checks are declared'}];
|
|
179
|
+
const resolvedCheckout=withinBuildScratch(checkoutDir);
|
|
180
|
+
if(!fs.statSync(resolvedCheckout).isDirectory()) throw new Error('checkoutDir must be a directory');
|
|
181
|
+
const root=defaultRunnerRoot(resolvedCheckout);
|
|
182
|
+
fs.mkdirSync(root,{recursive:true,mode:0o700});
|
|
183
|
+
const results=[];
|
|
184
|
+
for(const [index,check] of checks.entries()) {
|
|
185
|
+
try {
|
|
186
|
+
const perCheck=copyForCheck(resolvedCheckout,root,check.id,index);
|
|
187
|
+
const raw=await runIsolatedCheck(check,perCheck,path.join(root,`runner-${index}`),repoName);
|
|
188
|
+
results.push(evidenceCheckResult(check,raw));
|
|
189
|
+
} catch(error) {
|
|
190
|
+
const message=redactSecrets(String(error?.message??error)).text;
|
|
191
|
+
results.push(evidenceCheckResult(check,{bytes:Buffer.from(message),error:message}));
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return results;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export async function loadSealedResult(store,requestId) {
|
|
198
|
+
const result=store.get(requestId),evidence=result.report?.workspace_evidence;
|
|
199
|
+
const artifactId=evidence?.patch_artifact?.artifact_id;
|
|
200
|
+
if(!artifactId) throw new Error('stored report has no patch artifact');
|
|
201
|
+
const { Workspace }=await import('./workspace.mjs');
|
|
202
|
+
const reader=Object.create(Workspace.prototype);reader.store=store;
|
|
203
|
+
const artifact=reader.artifact(artifactId,requestId);
|
|
204
|
+
if(artifact.row.kind!=='patch'||artifact.row.sealed!==1) throw new Error('stored result artifact is not a sealed patch');
|
|
205
|
+
const input=result.assignment?.inputs?.find(item=>item.github_repo);
|
|
206
|
+
const baseSha=evidence.base_sha??input?.base_sha;
|
|
207
|
+
if(!fullSha.test(baseSha??'')||input?.base_sha&&input.base_sha!==baseSha) throw new Error('stored patch base SHA is missing or inconsistent');
|
|
208
|
+
if(evidence.patch_artifact.sha256!==artifact.row.sha256) throw new Error('stored report patch digest is inconsistent');
|
|
209
|
+
return {request_id:requestId,assignment:result.assignment,review:result.review,patch:artifact.bytes,patch_sha256:artifact.row.sha256,patch_base_sha:baseSha,
|
|
210
|
+
github_repo:input?.github_repo};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function failedCheck(id,error,issuer='dot-bridge') {
|
|
214
|
+
const bytes=Buffer.from(String(error));
|
|
215
|
+
return {id,issuer,trust_profile:TRUST.bridge,status:'failed',exit_code:null,timed_out:false,cancelled:false,stop_verified:false,duration_ms:0,
|
|
216
|
+
output_sha256:digest(bytes),output_bytes:bytes.length,output_preview:shortJson(redactSecrets(bytes.toString('utf8')).text),output_redaction_version:1,error:redactSecrets(String(error)).text};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function defaultEvidencePlan(repoName,repoDir,baseSha,scratchRoot,env) {
|
|
220
|
+
const metadataCheckout=worktree(repoDir,baseSha,scratchRoot,env,'assignment-checks').dir;
|
|
221
|
+
const ids=availableChecks(repoName,metadataCheckout);
|
|
222
|
+
const checks=ids.map(id=>{
|
|
223
|
+
const resolved=detectCheckWithOrigin(repoName,metadataCheckout,id);
|
|
224
|
+
if(!resolved?.spec) throw new Error(`assignment check ${id} could not be resolved at ${baseSha}`);
|
|
225
|
+
return {id,argv:resolved.spec.argv,install_argv:resolved.spec.install_argv,issuer:resolved.from==='owner_config'?'owner-config':resolved.from==='workspace_file'?'repository-config':`repository:${resolved.from}`,trust_profile:TRUST.bridge};
|
|
226
|
+
});
|
|
227
|
+
return {schema_version:1,checks};
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function changedCheckInputs(files,plan) {
|
|
231
|
+
const named=new Set(CHECK_INPUT_FILES);
|
|
232
|
+
for(const check of plan.checks) {
|
|
233
|
+
const commands=[check.argv,...(check.install_argv?[check.install_argv]:[])];
|
|
234
|
+
for(const argv of commands) for(const arg of argv) for(const word of arg.split(/[\s'"=;&|()<>]+/)) {
|
|
235
|
+
const file=word.replace(/^\.\//,'').replace(/^\/workspace\//,'');
|
|
236
|
+
if(file&&!file.startsWith('/')&&!file.startsWith('-')) named.add(file);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
return files.filter(file=>named.has(file)).sort();
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function isPatchConflict(error) {
|
|
243
|
+
const message=String(error?.message??error);
|
|
244
|
+
if(/whitespace/i.test(message)) return false;
|
|
245
|
+
return /not applied:|git apply --check failed|different line of history|not an ancestor|base [0-9a-f]{12} is not in this checkout/i.test(message);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
export async function verifySealedResult({store,sealedResult,repoDir,targetBaseRef,scratchRoot=path.join(buildScratch,'integrator')}) {
|
|
249
|
+
if(!store||typeof store.putIntegrationCandidate!=='function'||typeof store.beginIntegrationVerification!=='function') throw new Error('a migration-ready Store is required');
|
|
250
|
+
const requestId=sealedResult?.request_id,assignment=sealedResult?.assignment;
|
|
251
|
+
if(typeof requestId!=='string'||!requestId||!assignment||sealedResult.review===true||assignment.execution_scope!=='implementation') throw new Error('only implementation patch results can be verified');
|
|
252
|
+
const input=assignment.inputs?.find(item=>item.github_repo);
|
|
253
|
+
const repoName=sealedResult.github_repo??input?.github_repo;
|
|
254
|
+
if(typeof repoName!=='string'||!repoName) throw new Error('sealed result has no repository identity');
|
|
255
|
+
const patch=Buffer.from(sealedResult.patch??[]),patchDigest=sealedResult.patch_sha256,patchBaseSha=sealedResult.patch_base_sha;
|
|
256
|
+
if(patch.length>MAX_INTEGRATION_PATCH_BYTES) throw new Error(`sealed patch too large (maximum ${MAX_INTEGRATION_PATCH_BYTES} bytes)`);
|
|
257
|
+
if(!patch.length||!fullSha.test(patchBaseSha??'')||!/^[a-f0-9]{64}$/.test(patchDigest??'')||digest(patch)!==patchDigest) throw new Error('sealed patch digest or recorded base SHA is invalid');
|
|
258
|
+
const scratch=withinBuildScratch(scratchRoot);
|
|
259
|
+
fs.mkdirSync(scratch,{recursive:true,mode:0o700});
|
|
260
|
+
const baseEnv=makeHostEnv(scratch);
|
|
261
|
+
const repository=resolveCheckout(repoDir,baseEnv);
|
|
262
|
+
const targetSha=resolveTarget(repository,targetBaseRef,baseEnv);
|
|
263
|
+
const originalId=candidateId(requestId,patchDigest,patchBaseSha,patchBaseSha);
|
|
264
|
+
const originalCandidate={candidate_id:originalId,request_id:requestId,kind:'patch',linked_from:null,patch,patch_digest:patchDigest,
|
|
265
|
+
patch_base_sha:patchBaseSha,target_sha:patchBaseSha,github_repo:repoName};
|
|
266
|
+
const changedBase=targetSha!==patchBaseSha;
|
|
267
|
+
const currentId=changedBase?candidateId(requestId,patchDigest,patchBaseSha,targetSha):originalId;
|
|
268
|
+
const candidateInput=changedBase?{candidate_id:currentId,request_id:requestId,kind:'patch',linked_from:originalId,patch,patch_digest:patchDigest,
|
|
269
|
+
patch_base_sha:patchBaseSha,target_sha:targetSha,github_repo:repoName}:originalCandidate;
|
|
270
|
+
const {candidates:storedCandidates}=store.beginIntegrationVerification(changedBase?[originalCandidate,candidateInput]:[originalCandidate],{
|
|
271
|
+
candidate_id:currentId,patch_digest:patchDigest,patch_base_sha:patchBaseSha,target_sha:targetSha,target_ref:targetBaseRef,status:'failed',checks:[],
|
|
272
|
+
error:'verification interrupted before completion',
|
|
273
|
+
});
|
|
274
|
+
const original=storedCandidates[0],candidate=changedBase?storedCandidates[1]:original;
|
|
275
|
+
let checkoutDir=null,status='failed',checks=[],error=null,plan=null;
|
|
276
|
+
try {
|
|
277
|
+
const checkout=worktree(repository,targetSha,scratch,baseEnv,'candidate');
|
|
278
|
+
checkoutDir=checkout.dir;
|
|
279
|
+
const files=validateIntegrationPatch(checkoutDir,patch,assignment);
|
|
280
|
+
applyPatch({dir:checkoutDir,patch,sha256:patchDigest,baseSha:patchBaseSha,env:checkout.env});
|
|
281
|
+
plan=defaultEvidencePlan(repoName,repository,patchBaseSha,scratch,baseEnv);
|
|
282
|
+
const changedInputs=changedCheckInputs(files,plan);
|
|
283
|
+
if(changedInputs.length) {
|
|
284
|
+
status='owner_approval_required';
|
|
285
|
+
error='patch changes how it is checked';
|
|
286
|
+
checks=[{id:'check-inputs',issuer:'dot-bridge',trust_profile:TRUST.bridge,status,changed_inputs:changedInputs}];
|
|
287
|
+
} else {
|
|
288
|
+
checks=await runEvidencePlan({schema_version:1,checks:plan.checks.map(({install_argv,...check})=>check)},checkoutDir,repoName);
|
|
289
|
+
status=evidencePlanStatus(checks);
|
|
290
|
+
}
|
|
291
|
+
} catch(caught) {
|
|
292
|
+
error=redactSecrets(String(caught?.message??caught)).text;
|
|
293
|
+
if(isPatchConflict(caught)) status='conflict';
|
|
294
|
+
else if(checks.length===0) checks=[failedCheck('integration',error)];
|
|
295
|
+
}
|
|
296
|
+
const record={candidate_id:currentId,patch_digest:patchDigest,patch_base_sha:patchBaseSha,target_sha:targetSha,target_ref:targetBaseRef,status,checks,error};
|
|
297
|
+
let stored=null,recordingError=null;
|
|
298
|
+
try { stored=store.recordIntegrationVerification(record); }
|
|
299
|
+
catch(caught) { recordingError=String(caught?.message??caught); }
|
|
300
|
+
const verification=stored?{...stored,checks}:{...record,verification_id:null,recorded:false,recording_error:recordingError};
|
|
301
|
+
return {status,candidate,original_candidate_id:original.candidate_id,verification,verification_recorded:!!stored,scratch_dir:checkoutDir};
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
async function confinedCheckRunner() {
|
|
305
|
+
let input='';for await(const chunk of process.stdin) input+=chunk;
|
|
306
|
+
const request=JSON.parse(input),root=withinBuildScratch(request.runner_root),checkoutDir=withinBuildScratch(request.checkout_dir);
|
|
307
|
+
process.env.DALAN_WORKSPACE_ROOT=path.join(root,'workspace');
|
|
308
|
+
const store=new Store(':memory:',{deferSubscriptionRetirement:true});
|
|
309
|
+
const requestId=`integrator_${randomUUID()}`;
|
|
310
|
+
const payload={inputs:[{github_repo:request.github_repo,base_sha:'0'.repeat(40)}],execution_scope:'implementation'};
|
|
311
|
+
store.insertConfinedCheckAssignment(requestId,payload);
|
|
312
|
+
const { Workspace }=await import('./workspace.mjs');
|
|
313
|
+
const workspace=new Workspace(store,false);
|
|
314
|
+
const raw=await workspace.runConfined(requestId,checkoutDir,request.argv,{timeout_ms:INTEGRATOR_HOST_BUDGET.wall_ms,output_bytes:INTEGRATOR_HOST_BUDGET.output_bytes,host_budget:INTEGRATOR_HOST_BUDGET,network:false,maskPaths:request.maskPaths,sourceExemptions:request.sourceExemptions},{cancelled:()=>false});
|
|
315
|
+
const bytes=Buffer.from(raw.bytes??'');
|
|
316
|
+
process.stdout.write(JSON.stringify({exit:raw.exit,timedOut:raw.timedOut,cancelled:raw.cancelled,stop:raw.stop,duration_ms:raw.duration_ms,bytes:bytes.toString('base64'),truncated:raw.truncated,error:raw.error??null,host_budget:{limits:raw.budgets,usage:raw.usage}}));
|
|
317
|
+
store.db.close();
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
if(process.argv[1]===modulePath&&process.argv[2]==='--confined-check-runner') {
|
|
321
|
+
confinedCheckRunner().catch(error=>{process.stderr.write(safeDiagnostic(error?.stack??error,4000));process.exitCode=1;});
|
|
322
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// Logical deletion/fencing, not secure byte erasure. Parent owns audit/payload tables.
|
|
2
|
+
const fail=c=>{throw Object.assign(new Error(c),{code:c});};
|
|
3
|
+
const str=v=>typeof v==='string'&&v.length>0&&v.length<=512;
|
|
4
|
+
const nat=v=>Number.isSafeInteger(v)&&v>=0;
|
|
5
|
+
export function migrateJobRetention(db){
|
|
6
|
+
if(!db.isTransaction)fail('transaction_required');
|
|
7
|
+
db.exec(`CREATE TABLE IF NOT EXISTS job_retention_policy(
|
|
8
|
+
job TEXT PRIMARY KEY,owner TEXT NOT NULL,worker TEXT NOT NULL,retain_until INTEGER NOT NULL);
|
|
9
|
+
CREATE TABLE IF NOT EXISTS job_retention_tombstones(
|
|
10
|
+
job TEXT PRIMARY KEY,owner TEXT NOT NULL,worker TEXT NOT NULL,retain_until INTEGER NOT NULL,
|
|
11
|
+
deleted_at INTEGER NOT NULL,native_status TEXT NOT NULL,purge_pending INTEGER NOT NULL);`);
|
|
12
|
+
}
|
|
13
|
+
export function createJobRetention({db,authorize,clock=Date.now,readState,fence,purge}){
|
|
14
|
+
if([authorize,clock,readState,fence,purge].some(f=>typeof f!=='function'))fail('callbacks_required');
|
|
15
|
+
const tx=()=>{if(!db.isTransaction)fail('transaction_required');};
|
|
16
|
+
const now=()=>{const n=clock();if(!nat(n))fail('invalid_clock');return n;};
|
|
17
|
+
const policy=job=>db.prepare('SELECT * FROM job_retention_policy WHERE job=?').get(job);
|
|
18
|
+
function guard(job,owner,worker,operation){
|
|
19
|
+
if(![job,owner,worker].every(str)||authorize({job,owner,worker,operation})!==true)fail('unauthorized');
|
|
20
|
+
const p=policy(job);
|
|
21
|
+
if(p&&(p.owner!==owner||p.worker!==worker))fail('unauthorized');
|
|
22
|
+
return p;
|
|
23
|
+
}
|
|
24
|
+
// Call on lookup AND before submission idempotency/reuse handling.
|
|
25
|
+
function assertAvailable({job,owner,worker}){
|
|
26
|
+
const p=guard(job,owner,worker,'access');
|
|
27
|
+
if(db.prepare('SELECT 1 FROM job_retention_tombstones WHERE job=?').get(job)||(p&&now()>=p.retain_until))fail('TOMBSTONE');
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
function define({job,owner,worker,retainUntil}){
|
|
31
|
+
tx();assertAvailable({job,owner,worker});
|
|
32
|
+
if(!nat(retainUntil)||retainUntil<=now())fail('invalid_retention');
|
|
33
|
+
const p=policy(job);
|
|
34
|
+
if(p){if(p.retain_until!==retainUntil)fail('retention_conflict');return {...p};}
|
|
35
|
+
db.prepare('INSERT INTO job_retention_policy VALUES(?,?,?,?)').run(job,owner,worker,retainUntil);
|
|
36
|
+
return {...policy(job)};
|
|
37
|
+
}
|
|
38
|
+
function expire({job,owner,worker}){
|
|
39
|
+
tx();const p=guard(job,owner,worker,'expire');if(!p)fail('retention_not_found');
|
|
40
|
+
const at=now();if(at<p.retain_until)return {deleted:false};
|
|
41
|
+
let tomb=db.prepare('SELECT * FROM job_retention_tombstones WHERE job=?').get(job);
|
|
42
|
+
if(tomb)return {...tomb,deleted:true};
|
|
43
|
+
const state=readState(job);
|
|
44
|
+
if(!state||!str(state.status))fail('native_state_required');
|
|
45
|
+
// Install the durable logical fence before the trusted hook observes it.
|
|
46
|
+
// Every parent entrypoint must call assertAvailable; this is not a physical stop.
|
|
47
|
+
const terminal=['finished','cancelled','deleted'].includes(state.status);
|
|
48
|
+
const canPurge=terminal&&state.compute_stopped===true;
|
|
49
|
+
db.prepare('INSERT INTO job_retention_tombstones VALUES(?,?,?,?,?,?,?)')
|
|
50
|
+
.run(job,owner,worker,p.retain_until,at,state.status,Number(!canPurge));
|
|
51
|
+
// Synchronous hook validates/enforces this fence in the same transaction.
|
|
52
|
+
// Throwing or returning anything other than true rolls the tombstone back.
|
|
53
|
+
if(fence({job,owner,worker,reason:'retention'})!==true)fail('fence_not_confirmed');
|
|
54
|
+
if(canPurge&&purge({job,owner,worker,retainAudit:true})!==true)fail('purge_not_confirmed');
|
|
55
|
+
return {...db.prepare('SELECT * FROM job_retention_tombstones WHERE job=?').get(job),deleted:true};
|
|
56
|
+
}
|
|
57
|
+
function completePurge({job,owner,worker}){
|
|
58
|
+
tx();guard(job,owner,worker,'purge');
|
|
59
|
+
const tomb=db.prepare('SELECT * FROM job_retention_tombstones WHERE job=?').get(job);
|
|
60
|
+
if(!tomb)fail('tombstone_required');
|
|
61
|
+
if(!tomb.purge_pending)return {purged:true};
|
|
62
|
+
const state=readState(job);
|
|
63
|
+
if(!state||!['finished','cancelled','deleted'].includes(state.status)||state.compute_stopped!==true)return {purged:false};
|
|
64
|
+
if(purge({job,owner,worker,retainAudit:true})!==true)fail('purge_not_confirmed');
|
|
65
|
+
db.prepare('UPDATE job_retention_tombstones SET purge_pending=0 WHERE job=?').run(job);
|
|
66
|
+
return {purged:true};
|
|
67
|
+
}
|
|
68
|
+
return {assertAvailable,define,expire,completePurge};
|
|
69
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Names that earlier releases wrote into databases, receipts and request ids. They keep working as input and are still the
|
|
2
|
+
// stored form of `assignments.source`, whose CHECK constraint lists them. New code uses the neutral names in objectives.mjs.
|
|
3
|
+
// This is the only module that spells the old names.
|
|
4
|
+
export const legacyFixLoopName = 'dot-fix';
|
|
5
|
+
// Directory of the fix ledger that `dalan backfill-objectives` reads when no path is given.
|
|
6
|
+
export const legacyFixLedgerPath = `.local/share/${legacyFixLoopName}/ledger.jsonl`;
|
|
7
|
+
// Earlier name of the `report_thread_id` key in the PR-head reviewer config. Still read; `report_thread_id` wins when both are set.
|
|
8
|
+
export const legacyReportThreadKey = 'lead_thread_id';
|