@tnunamak/dalan 0.7.0 → 0.8.1
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 +42 -0
- package/CONTRIBUTING.md +4 -0
- package/PROTOCOL.md +8 -0
- package/README.md +68 -28
- package/bin/dalan.mjs +1 -1
- package/bin/dot-worker.mjs +115 -16
- package/contracts/adapter-qualification.schema.json +170 -0
- package/docs/chatgpt-worker-onboarding.md +1 -1
- package/docs/local-agent-requester.md +46 -0
- package/docs/manual-setup.md +1 -1
- package/docs/operations.md +4 -3
- package/docs/pull-workers.md +1 -0
- package/docs/relationships.md +13 -0
- package/docs/service-setup.md +40 -17
- package/docs/setup-reference.md +1 -1
- package/docs/t3-integration.md +2 -0
- package/docs/t3-question-relationship.md +43 -0
- package/docs/t3-reverse-control.md +12 -8
- package/docs/t3-wake-fence-r4.md +42 -0
- package/docs/test-suite-isolation.md +205 -0
- package/docs/usage.md +14 -2
- package/docs/worker-clients.md +3 -1
- package/package.json +6 -3
- package/qualification/README.md +13 -0
- package/qualification/mcp.json +121 -0
- package/qualification/protocol-v0.json +127 -0
- package/src/admin-socket.mjs +2 -1
- package/src/answer-journal.mjs +200 -0
- package/src/auth-check.mjs +8 -2
- package/src/claim-command-ledger.mjs +3 -2
- package/src/cli-help.mjs +19 -10
- package/src/destinations/index.mjs +6 -0
- package/src/destinations/none.mjs +3 -0
- package/src/destinations/t3.mjs +63 -6
- package/src/execution.mjs +20 -2
- package/src/follow-current.mjs +4 -2
- package/src/gozar-routes.mjs +4 -3
- package/src/host-budget.mjs +17 -11
- package/src/host-execution-policy.mjs +2 -2
- package/src/host-stop-reverify.mjs +6 -4
- package/src/inbox.mjs +13 -3
- package/src/integrator.mjs +3 -1
- package/src/lifecycle.mjs +60 -2
- package/src/patch-apply.mjs +74 -13
- package/src/server.mjs +210 -34
- package/src/service-launchd.mjs +28 -8
- package/src/service-migrate-workers.mjs +12 -2
- package/src/service.mjs +52 -16
- package/src/status-summary.mjs +3 -0
- package/src/store.mjs +300 -34
- package/src/submission-policy.mjs +8 -4
- package/src/t3.mjs +21 -2
- package/src/tool-registry.mjs +54 -8
- package/src/workers.mjs +22 -3
- package/src/workspace.mjs +94 -15
package/src/execution.mjs
CHANGED
|
@@ -22,10 +22,13 @@ export const CAPABILITY_NAMES = Object.freeze([
|
|
|
22
22
|
'offline_transition_revokes_connections', 'artifact_export_no_follow', 'runner_observed_evidence', 'native_darwin_execution', 'immutable_input_snapshot']);
|
|
23
23
|
export const CAPABILITY_STATES = Object.freeze(['verified', 'unsupported', 'unknown']);
|
|
24
24
|
|
|
25
|
+
export const ADAPTER_CAPABILITY_NAMES = Object.freeze(['identified_questions']);
|
|
26
|
+
const REQUIRED_CAPABILITY_NAMES = Object.freeze([...CAPABILITY_NAMES, ...ADAPTER_CAPABILITY_NAMES]);
|
|
27
|
+
|
|
25
28
|
export function parseRequiredCapabilities(value) {
|
|
26
29
|
if (value === undefined || value === null) return null;
|
|
27
|
-
if (!Array.isArray(value) || value.length >
|
|
28
|
-
throw new Error(`invalid required_capabilities: expected a list of ${
|
|
30
|
+
if (!Array.isArray(value) || value.length > REQUIRED_CAPABILITY_NAMES.length || value.some(c => !REQUIRED_CAPABILITY_NAMES.includes(c))) {
|
|
31
|
+
throw new Error(`invalid required_capabilities: expected a list of ${REQUIRED_CAPABILITY_NAMES.join(', ')}`);
|
|
29
32
|
}
|
|
30
33
|
return value.length ? [...new Set(value)].sort() : null;
|
|
31
34
|
}
|
|
@@ -110,3 +113,18 @@ export function withEvidence(row) {
|
|
|
110
113
|
const evidence = row.evidence ? JSON.parse(row.evidence) : null;
|
|
111
114
|
return withCheckCoverage({ ...row, evidence, trust: evidence?.trust ?? null });
|
|
112
115
|
}
|
|
116
|
+
|
|
117
|
+
// Committed adapter qualification is independent of per-worker authority grants.
|
|
118
|
+
export const ADAPTER_QUALIFICATIONS = Object.freeze({
|
|
119
|
+
mcp: Object.freeze({capabilities: Object.freeze({})}),
|
|
120
|
+
'protocol-v0': Object.freeze({capabilities: Object.freeze({identified_questions: 'verified'})}),
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
export function admitAdapterCapabilities(adapter, required, catalogProfile) {
|
|
124
|
+
const qualification = Object.hasOwn(ADAPTER_QUALIFICATIONS, adapter) ? ADAPTER_QUALIFICATIONS[adapter] : null;
|
|
125
|
+
for (const name of required ?? []) {
|
|
126
|
+
const state = adapter === 'protocol-v0' && catalogProfile !== 'protocol-v0' ? 'unknown' : qualification?.capabilities[name] ?? 'unknown';
|
|
127
|
+
if (state !== 'verified') throw new Error(
|
|
128
|
+
'capability_not_available: ' + name + ' (adapter ' + (adapter ?? 'undeclared') + ' declares ' + state + ')');
|
|
129
|
+
}
|
|
130
|
+
}
|
package/src/follow-current.mjs
CHANGED
|
@@ -7,9 +7,11 @@ import { readDefaultHome } from './default-home.mjs';
|
|
|
7
7
|
|
|
8
8
|
const real = file => { try { return fs.realpathSync(file); } catch { return null; } };
|
|
9
9
|
|
|
10
|
-
// The entry script to hand over to, or null to stay in this package. `ownBin` is this package's bin/dalan.mjs
|
|
11
|
-
|
|
10
|
+
// The entry script to hand over to, or null to stay in this package. `ownBin` is this package's bin/dalan.mjs; `argv` is the
|
|
11
|
+
// command line after the script. An explicit --home names a home other than the default one, so this package runs it.
|
|
12
|
+
export function followTarget({ ownBin, env = process.env, argv = [] }) {
|
|
12
13
|
if (env.DALAN_NO_FOLLOW === '1' || env.DALAN_FOLLOWED === '1') return null;
|
|
14
|
+
if (argv.some(arg => arg === '--home' || arg.startsWith('--home='))) return null;
|
|
13
15
|
const home = env.DALAN_HOME ? path.resolve(env.DALAN_HOME) : readDefaultHome(env);
|
|
14
16
|
if (!home) return null;
|
|
15
17
|
const target = real(path.join(home, 'current', 'bin', 'dalan.mjs')), own = real(ownBin);
|
package/src/gozar-routes.mjs
CHANGED
|
@@ -110,9 +110,10 @@ const EXPLAIN = {
|
|
|
110
110
|
};
|
|
111
111
|
export function explainRouteError(error) {
|
|
112
112
|
const code = typeof error?.code === 'string' && (FROZEN_CODES.includes(error.code) || error.code === 'runtime_missing') ? error.code : null;
|
|
113
|
-
|
|
114
|
-
const action = error
|
|
115
|
-
const fix = action ? [action.label, action.instructions, action.href].filter(
|
|
113
|
+
// Gozar's next step is shown as text for every code, including one Dalan does not know yet; Dalan never acts on it.
|
|
114
|
+
const action = error?.nextAction ?? null;
|
|
115
|
+
const fix = action ? [action.label, action.instructions, action.href].filter(value => typeof value === 'string' && value.length > 0).map(value => safeDiagnostic(value, 240)).join(' - ') || null : null;
|
|
116
|
+
if (!code) return { code: null, line: safeDiagnostic(String(error?.message ?? error), 240), fix };
|
|
116
117
|
const detail = code === 'runtime_missing' ? error.message : `${EXPLAIN[code]}${error.message && !EXPLAIN[code].includes(error.message) ? ` (${safeDiagnostic(error.message, 160)})` : ''}`;
|
|
117
118
|
return { code, line: detail, fix };
|
|
118
119
|
}
|
package/src/host-budget.mjs
CHANGED
|
@@ -6,9 +6,7 @@ import {prepareHostReceipts,assertHostReceiptIsolation,readVerifiedHostStop} fro
|
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
7
|
import { spawn } from 'node:child_process';
|
|
8
8
|
|
|
9
|
-
//
|
|
10
|
-
// unit name is an atomic reservation; it disappears only after its tree stops.
|
|
11
|
-
export const HOST_UNIT = 'dot-bridge-host-check.service';
|
|
9
|
+
// The fixed production unit reserves one active envelope per Unix user.
|
|
12
10
|
export const HOST_BUDGET_CEILINGS = Object.freeze({ cpu_ms: 120000, wall_ms: 180000, memory_bytes: 1024 ** 3, processes: 128, disk_write_bytes: 256 * 1024 ** 2, output_bytes: 1024 ** 2 });
|
|
13
11
|
const minima = { cpu_ms: 50, wall_ms: 100, memory_bytes: 128 * 1024 ** 2, processes: 16, disk_write_bytes: 1024 ** 2, output_bytes: 1024 };
|
|
14
12
|
const service = fileURLToPath(new URL('./host-budget-service.mjs', import.meta.url));
|
|
@@ -77,12 +75,16 @@ async function runHostBudgetAttempt({ dir, budgets, phases, maskPaths = [], sour
|
|
|
77
75
|
'LimitCORE=0', 'UMask=0077',
|
|
78
76
|
`ExecStopPost=${[process.execPath, stopRecorder,...(receipts?['--check-run-id',receipts.checkRunId,'--receipt-dir',receipts.receiptDir]:[])].map(propertyArg).join(' ')}`,
|
|
79
77
|
];
|
|
80
|
-
|
|
78
|
+
// Test suites isolate their reservation without changing the production default.
|
|
79
|
+
const suffix = process.env.NODE_ENV === 'production' ? undefined : process.env.DALAN_HOST_CHECK_UNIT_SUFFIX;
|
|
80
|
+
if (suffix && !/^[a-zA-Z0-9-]{1,80}$/.test(suffix)) throw new Error('invalid DALAN_HOST_CHECK_UNIT_SUFFIX');
|
|
81
|
+
const unit = `dot-bridge-host-check${suffix ? '-' + suffix : ''}.service`;
|
|
82
|
+
const args = ['--user', '--quiet', '--wait', '--pipe', '--collect', `--unit=${unit}`, ...properties.map(p => `--property=${p}`), '--', process.execPath, service];
|
|
81
83
|
const started=performance.now();
|
|
82
84
|
const child = spawn('/usr/bin/systemd-run', args, { stdio: ['pipe', 'pipe', 'pipe'] });
|
|
83
85
|
onSpawned();
|
|
84
86
|
child.stdin.write(serialized+'\n');
|
|
85
|
-
let buffer = '', message = null, stopped = null, pid = null, diagnostic = '', callbackError = null, cancellationSent = false;
|
|
87
|
+
let buffer = '', message = null, stopped = null, pid = null, diagnostic = '', callbackError = null, cancellationSent = false, cpuExceeded = false;
|
|
86
88
|
const launched = [];
|
|
87
89
|
const partial = new Map();
|
|
88
90
|
let partialUsage = null;
|
|
@@ -106,16 +108,20 @@ async function runHostBudgetAttempt({ dir, budgets, phases, maskPaths = [], sour
|
|
|
106
108
|
if (event.event === 'pid') pid = event.pid;
|
|
107
109
|
if (event.event === 'started' && phases.some(p => p.name === event.phase)) {
|
|
108
110
|
launched.push(event.phase);
|
|
109
|
-
if (onStarted) Promise.resolve(onStarted({ pid, phase: event.phase })).catch(e => { callbackError = e; cancel(); });
|
|
111
|
+
if (onStarted) Promise.resolve(onStarted({ pid, unit, phase: event.phase })).catch(e => { callbackError = e; cancel(); });
|
|
110
112
|
}
|
|
111
|
-
if (event.event === 'output_started' && onOutputStarted) Promise.resolve(onOutputStarted({ pid, phase: event.phase })).catch(e => { callbackError = e; cancel(); });
|
|
113
|
+
if (event.event === 'output_started' && onOutputStarted) Promise.resolve(onOutputStarted({ pid, unit, phase: event.phase })).catch(e => { callbackError = e; cancel(); });
|
|
112
114
|
if (event.event === 'partial' && launched.includes(event.phase)) {
|
|
113
115
|
const chunks = partial.get(event.phase) ?? [];
|
|
114
116
|
chunks.push(Buffer.from(event.output, 'base64'));
|
|
115
117
|
partial.set(event.phase, chunks);
|
|
116
118
|
partialUsage = event.usage;
|
|
117
119
|
}
|
|
118
|
-
if (event.event === 'result')
|
|
120
|
+
if (event.event === 'result') {
|
|
121
|
+
// Both supervisors report here; EOF cleanup cannot undo an observed limit.
|
|
122
|
+
cpuExceeded ||= event.result?.error === 'budget exceeded: cpu';
|
|
123
|
+
message = event.result;
|
|
124
|
+
}
|
|
119
125
|
if (event.event === 'stopped') stopped = event.stop;
|
|
120
126
|
} catch { diagnostic = 'invalid supervisor response'; }
|
|
121
127
|
}
|
|
@@ -129,10 +135,10 @@ async function runHostBudgetAttempt({ dir, budgets, phases, maskPaths = [], sour
|
|
|
129
135
|
if (callbackError) throw callbackError;
|
|
130
136
|
// ExecStopPost runs after systemd has killed/reaped every process in the unit,
|
|
131
137
|
// even on OOM, RuntimeMaxSec, or loss of the main supervisor. No PID sweep or
|
|
132
|
-
// application TTL can
|
|
138
|
+
// application TTL can certify a still-running tree as stopped.
|
|
133
139
|
const stopEvidence=resolveHostStopEvidence(receipts,stopped);
|
|
134
140
|
const stop = { verified: stopEvidence?.verified === true, reason: stopEvidence?.verified ? 'systemd_control_group_stopped' : 'service_stop_not_observed', service_result: stopped?.result ?? null, invocation_id: stopEvidence?.invocationId ?? stopped?.invocation_id ?? null, remaining_pids: stopEvidence?.remaining_pids ?? stopped?.remaining_pids ?? null, oom_kill: stopped?.oom_kill ?? null };
|
|
135
|
-
let error = message?.error ?? null;
|
|
141
|
+
let error = cpuExceeded ? 'budget exceeded: cpu' : message?.error ?? null;
|
|
136
142
|
if (stopped?.oom_kill > 0 || stopped?.result === 'oom-kill') error = 'budget exceeded: memory';
|
|
137
143
|
else if (stopped?.result === 'timeout') error = 'budget exceeded: wall';
|
|
138
144
|
else if (stopped && !message) error = stopped.result === 'signal' ? 'supervisor interrupted' : `host preparation failed: ${diagnostic.trim() || stopped.exit_status || 'supervisor exited without a receipt'}`;
|
|
@@ -145,5 +151,5 @@ async function runHostBudgetAttempt({ dir, budgets, phases, maskPaths = [], sour
|
|
|
145
151
|
const bytes = Buffer.concat(phaseResults.map(p => p.bytes)).subarray(0, budgets.output_bytes);
|
|
146
152
|
const notStarted=provesHostNotStarted({spawnError:exit.error,pid,stopped}); // stderr is not trusted for this decision.
|
|
147
153
|
const usage = message?.usage ? { ...partialUsage, ...message.usage } : partialUsage;
|
|
148
|
-
return { dependencies: dependencies ? {lock_sha256:dependencies.lock_sha256,manifest_sha256:dependencies.manifest_sha256,runtime:dependencies.runtime} : null, exit: error ? { code: 125 } : message?.exit ?? { code: 125 }, error, budgets, usage, usage_complete: !!message?.usage && !!message?.phases?.length && stopped?.result !== 'timeout' && !stopped?.oom_kill, bytes, phases: phaseResults, stop, notStarted, timedOut: error === 'budget exceeded: wall', cancelled: !!message?.cancelled, truncated: error === 'budget exceeded: output', duration_ms: Math.round(performance.now()-started) };
|
|
154
|
+
return { unit, dependencies: dependencies ? {lock_sha256:dependencies.lock_sha256,manifest_sha256:dependencies.manifest_sha256,runtime:dependencies.runtime} : null, exit: error ? { code: 125 } : message?.exit ?? { code: 125 }, error, budgets, usage, usage_complete: !!message?.usage && !!message?.phases?.length && stopped?.result !== 'timeout' && !stopped?.oom_kill, bytes, phases: phaseResults, stop, notStarted, timedOut: error === 'budget exceeded: wall', cancelled: !!message?.cancelled, truncated: error === 'budget exceeded: output', duration_ms: Math.round(performance.now()-started) };
|
|
149
155
|
}
|
|
@@ -20,10 +20,10 @@ export function hostCheckAuthorization(repo, checkId, expectedSpec = null) {
|
|
|
20
20
|
return { spec };
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
-
export function hostCheckRefusal(assignment={}, repo=null, checkId=null, expectedSpec=null) {
|
|
23
|
+
export function hostCheckRefusal(assignment={}, repo=null, checkId=null, expectedSpec=null,excludedPathsAbsent=false) {
|
|
24
24
|
const scope=assignment.scope_paths;
|
|
25
25
|
const narrow=Array.isArray(scope)&&scope.length&&!scope.some(p=>p.replace(/^\.\//,'').replace(/\/$/,'')==='.');
|
|
26
|
-
if(narrow||assignment.scope_excluded?.length) {
|
|
26
|
+
if(narrow||(assignment.scope_excluded?.length&&!excludedPathsAbsent)) {
|
|
27
27
|
return 'scope_paths_read_isolation_unavailable: this executor exposes the whole checkout; a check needs an owner-approved repository-wide read grant';
|
|
28
28
|
}
|
|
29
29
|
if(sensitivePolicyPaths().error) return 'sensitive_policy_unavailable: restore a valid mode-0600 submission policy before running host checks';
|
|
@@ -2,12 +2,11 @@ import fs from 'node:fs';
|
|
|
2
2
|
import {spawnSync} from 'node:child_process';
|
|
3
3
|
import {readHostStart,writeHostReverify,readVerifiedHostStop,validBootId} from './host-budget-receipts.mjs';
|
|
4
4
|
import {readCgroupProcesses} from './host-cgroup.mjs';
|
|
5
|
-
import {HOST_UNIT} from './host-budget.mjs';
|
|
6
5
|
|
|
7
6
|
const currentBootId=()=>fs.readFileSync('/proc/sys/kernel/random/boot_id','utf8').trim();
|
|
8
7
|
// Only "inactive" or "failed" shows the unit is gone. Any other answer, error or timeout counts as still active.
|
|
9
|
-
function hostUnitInactive() {
|
|
10
|
-
const r=spawnSync('/usr/bin/systemctl',['--user','is-active',
|
|
8
|
+
function hostUnitInactive(unit) {
|
|
9
|
+
const r=spawnSync('/usr/bin/systemctl',['--user','is-active',unit],{encoding:'utf8',timeout:5000});
|
|
11
10
|
return !r.error&&['inactive','failed'].includes((r.stdout??'').trim());
|
|
12
11
|
}
|
|
13
12
|
// A missing cgroup directory means no process remains. Any other read error propagates and keeps the stop unverified.
|
|
@@ -32,7 +31,10 @@ export function reverifyHostStop({receiptDir,checkRunId},{bootId=currentBootId,u
|
|
|
32
31
|
if(!validBootId(now)) return null;
|
|
33
32
|
let basis;
|
|
34
33
|
if(now!==start.boot_id) basis='boot_changed';
|
|
35
|
-
else if(typeof start.cgroup==='string'
|
|
34
|
+
else if(typeof start.cgroup==='string') {
|
|
35
|
+
// The trusted start receipt records the exact unit, including legacy names.
|
|
36
|
+
const unit=start.cgroup.split('/').at(-1);
|
|
37
|
+
if(!/^dot-bridge-host-check(?:-[a-zA-Z0-9-]+)?\.service$/.test(unit)||unitInactive(unit)!==true) return null;
|
|
36
38
|
const remaining=scan('/sys/fs/cgroup'+start.cgroup);
|
|
37
39
|
if(Array.isArray(remaining)&&remaining.length===0) basis='cgroup_empty';
|
|
38
40
|
}
|
package/src/inbox.mjs
CHANGED
|
@@ -2,14 +2,23 @@
|
|
|
2
2
|
// bin/dot-worker.mjs does the reads. Nothing here, or in the batch read behind it, records an owner read.
|
|
3
3
|
|
|
4
4
|
import { terminalSafeLine } from './terminal-safe.mjs';
|
|
5
|
-
export const inboxGroups=['finished_unread','question','undecided','cancelled_unread'];
|
|
5
|
+
export const inboxGroups=['finished_unread','question','undecided','cancelled_unread','held_wake'];
|
|
6
6
|
export const decideWords='accepted|applied|useful_no_change|useful_negative|not_useful';
|
|
7
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
8
|
|
|
9
|
-
// One owner-states row to an inbox item, or null when the owner has nothing to do for it.
|
|
9
|
+
// One owner-states row to an inbox item, or null when the owner has nothing to do for it. A wake held because the parent
|
|
10
|
+
// stopped is not owner work: it marks the item the request already has, and only a request with no other item gets its own
|
|
11
|
+
// held_wake line, so the owner can see why a result or question did not reach the parent.
|
|
10
12
|
export function inboxItem(state) {
|
|
11
13
|
const v=state.inbox;
|
|
12
14
|
if(!v||state.error) return null;
|
|
15
|
+
const item=ownerItem(state,v), held=v.held_wake;
|
|
16
|
+
if(!held) return item;
|
|
17
|
+
const wake_held={kind:held.kind,reason:held.reason,detail:held.detail,since:held.since};
|
|
18
|
+
if(item) return {...item,wake_held};
|
|
19
|
+
return {group:'held_wake',request_id:state.request_id,worker:v.target_worker,title:firstLine(v.brief),status:state.status,wake_held,updated_at:held.since,next:[`dalan get ${state.request_id}`]};
|
|
20
|
+
}
|
|
21
|
+
function ownerItem(state,v) {
|
|
13
22
|
const base={request_id:state.request_id,worker:v.target_worker,title:firstLine(v.brief)};
|
|
14
23
|
const failure=v.failure_type?{failure_type:v.failure_type,failure_type_source:v.failure_type_source}:{};
|
|
15
24
|
const get=`dalan get ${state.request_id}`;
|
|
@@ -47,7 +56,8 @@ export function formatInbox(inbox) {
|
|
|
47
56
|
if(!inbox.total) return hidden?`inbox empty\n${hidden}`:'inbox empty';
|
|
48
57
|
const lines=[];
|
|
49
58
|
for(const g of inboxGroups) for(const i of inbox.items.filter(x=>x.group===g)) {
|
|
50
|
-
const
|
|
59
|
+
const held=i.wake_held?` [wake held: ${i.wake_held.reason}${i.wake_held.detail?`, ${i.wake_held.detail}`:''}; it sends when the parent runs again]`:'';
|
|
60
|
+
const why=(i.group==='cancelled_unread'?` (${i.reason??'cancelled'})`:i.group==='question'?` ${i.text}`:'')+held;
|
|
51
61
|
lines.push(terminalSafeLine(`${g} ${i.request_id} ${i.worker} ${i.status} ${i.updated_at??''} ${i.title}${why} -> ${i.next.join(' | ')}`));
|
|
52
62
|
}
|
|
53
63
|
lines.push(`${inbox.total} item${inbox.total===1?'':'s'}: ${inboxGroups.map(g=>`${inbox.counts[g]} ${g}`).join(', ')}${hidden?`; ${hidden}`:''}`);
|
package/src/integrator.mjs
CHANGED
|
@@ -129,8 +129,10 @@ function runIsolatedCheck(check,checkoutDir,runnerRoot,repoName) {
|
|
|
129
129
|
fs.mkdirSync(sourceCopyDir,{mode:0o700});
|
|
130
130
|
const masked=sensitiveMasks(checkoutDir,repoName,sourceCopyDir);
|
|
131
131
|
const request={checkout_dir:checkoutDir,runner_root:root,argv:check.argv,github_repo:repoName,maskPaths:masked.paths,sourceExemptions:masked.sourceExemptions};
|
|
132
|
-
const
|
|
132
|
+
const testSuffix=process.env.NODE_ENV!=='production'&&process.env.DALAN_HOST_CHECK_UNIT_SUFFIX;
|
|
133
|
+
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:testSuffix?'test':'production',DALAN_WORKSPACE_ROOT:path.join(root,'workspace'),DALAN_INTEGRATOR_SCRATCH_ROOT:buildScratch};
|
|
133
134
|
if(readEnv('DALAN_HOST_CHECKS')==='1') env.DALAN_HOST_CHECKS='1';
|
|
135
|
+
if(testSuffix) env.DALAN_HOST_CHECK_UNIT_SUFFIX=testSuffix;
|
|
134
136
|
if(process.env.XDG_RUNTIME_DIR) env.XDG_RUNTIME_DIR=process.env.XDG_RUNTIME_DIR;
|
|
135
137
|
if(process.env.DBUS_SESSION_BUS_ADDRESS) env.DBUS_SESSION_BUS_ADDRESS=process.env.DBUS_SESSION_BUS_ADDRESS;
|
|
136
138
|
fs.mkdirSync(env.HOME,{recursive:true,mode:0o700});
|
package/src/lifecycle.mjs
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
// Append-only lifecycle events: one row per state change, written in the same transaction as the change.
|
|
2
2
|
// Metrics derive from these rows only; anything the rows cannot show is reported as unknown with a reason, never as zero.
|
|
3
3
|
import { fromStoredSource, canonicalObjectiveKey, canonicalKindSql, canonicalKindLabel } from './objectives.mjs';
|
|
4
|
-
|
|
4
|
+
// The control vocabulary: what an owner or operator asked to stop, release or withdraw. Each event names the scope it
|
|
5
|
+
// acted on (scope) and whether that effect is known (outcome). A request to something outside the store is 'unknown'
|
|
6
|
+
// until an observation says otherwise; 'done' means the store itself made the change in the same transaction.
|
|
7
|
+
export const controlTypes=['detach','interrupt_foreground','withdraw_work','revoke_grant'];
|
|
8
|
+
export const controlOutcomes=['done','confirmed','unknown'];
|
|
9
|
+
export const lifecycleTypes=['queued','claimed','working','waiting','blocked','completed','consumed','accepted','integrated','abandoned','cancelled','delivery_sent','delivery_uncertain','reconciled','check_started','check_passed','check_failed','check_skipped','wake_held',...controlTypes];
|
|
5
10
|
export const retentionDays=90;
|
|
6
11
|
// Two consecutive claim activity events no more than this far apart count as working time (see docs/usage.md, "Metrics").
|
|
7
12
|
export const activeGapMs=20*60000;
|
|
@@ -14,7 +19,8 @@ export const progressType=(note,blocker=false)=>blocker||/^\s*BLOCKED:/im.test(n
|
|
|
14
19
|
// Retention deletes go through one guarded path: the trigger admits a DELETE only for rows older than the cutoff that
|
|
15
20
|
// retainLifecycle sets and clears inside its own transaction. This guards against accidental writes, not against a
|
|
16
21
|
// process that can rewrite the schema.
|
|
17
|
-
|
|
22
|
+
const lifecycleTableBody=`id INTEGER PRIMARY KEY AUTOINCREMENT, request_id TEXT NOT NULL, claim_id TEXT, epoch INTEGER, type TEXT NOT NULL CHECK(type IN (${lifecycleTypes.map(t=>`'${t}'`).join(',')})), at TEXT NOT NULL, actor TEXT NOT NULL, source TEXT NOT NULL CHECK(source IN ('live','backfill')), reason TEXT`;
|
|
23
|
+
export const lifecycleSchema=`CREATE TABLE IF NOT EXISTS lifecycle_events (${lifecycleTableBody});
|
|
18
24
|
CREATE INDEX IF NOT EXISTS lifecycle_events_request ON lifecycle_events(request_id,id);
|
|
19
25
|
CREATE INDEX IF NOT EXISTS lifecycle_events_type_at ON lifecycle_events(type,at);
|
|
20
26
|
CREATE TABLE IF NOT EXISTS lifecycle_daily (day TEXT NOT NULL, type TEXT NOT NULL, kind TEXT NOT NULL, count INTEGER NOT NULL, PRIMARY KEY(day,type,kind));
|
|
@@ -23,6 +29,58 @@ export const lifecycleSchema=`CREATE TABLE IF NOT EXISTS lifecycle_events (id IN
|
|
|
23
29
|
CREATE TRIGGER IF NOT EXISTS lifecycle_events_no_update BEFORE UPDATE ON lifecycle_events BEGIN SELECT RAISE(ABORT, 'lifecycle events are append-only'); END;
|
|
24
30
|
CREATE TRIGGER IF NOT EXISTS lifecycle_events_no_delete BEFORE DELETE ON lifecycle_events WHEN NOT EXISTS (SELECT 1 FROM lifecycle_retention WHERE id=1 AND cutoff IS NOT NULL AND old.at<cutoff) BEGIN SELECT RAISE(ABORT, 'lifecycle events are append-only'); END;`;
|
|
25
31
|
|
|
32
|
+
// Migration 72. Control events carry the scope they acted on and an outcome. A table made by an earlier release also
|
|
33
|
+
// lists the old types in its CHECK, and SQLite cannot widen a CHECK in place, so that table is rebuilt: same rows, same
|
|
34
|
+
// ids, and the stored text of its indexes and triggers is carried over unchanged. A table made by this release
|
|
35
|
+
// (a fresh database) already lists every type and only gains the two columns.
|
|
36
|
+
export function addControlColumns(db) {
|
|
37
|
+
const table=db.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name='lifecycle_events'").get();
|
|
38
|
+
if(!table) return;
|
|
39
|
+
const has=name=>!!db.prepare("SELECT 1 FROM pragma_table_info('lifecycle_events') WHERE name=?").get(name);
|
|
40
|
+
// A table is current only when its CHECK lists every type this release writes. Naming one type is not enough: a table
|
|
41
|
+
// built part-way through this change can list wake_held and still lack another.
|
|
42
|
+
if(lifecycleTypes.every(t=>table.sql.includes(`'${t}'`))) {
|
|
43
|
+
for(const name of ['scope','outcome']) if(!has(name)) db.exec(`ALTER TABLE lifecycle_events ADD COLUMN ${name} TEXT`);
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
const attached=db.prepare("SELECT type,name,sql FROM sqlite_master WHERE tbl_name='lifecycle_events' AND type IN ('index','trigger') AND sql IS NOT NULL").all();
|
|
47
|
+
const columns=db.prepare("SELECT name FROM pragma_table_info('lifecycle_events')").all().map(c=>c.name);
|
|
48
|
+
const wanted=['id','request_id','claim_id','epoch','type','at','actor','source','reason','worker'];
|
|
49
|
+
const missing=wanted.filter(c=>!columns.includes(c));
|
|
50
|
+
if(missing.length) throw new Error(`lifecycle_events is missing ${missing.join(', ')}; cannot widen its type list`);
|
|
51
|
+
// The rebuild copies a fixed list of columns. A column it does not know would be dropped with its data, so refuse
|
|
52
|
+
// before any DDL runs and leave the database as it was.
|
|
53
|
+
const known=[...wanted,'scope','outcome'];
|
|
54
|
+
const unknown=columns.filter(c=>!known.includes(c));
|
|
55
|
+
if(unknown.length) throw new Error(`lifecycle_events has columns this release does not know: ${unknown.join(', ')}; refusing to rebuild it because that would drop their data`);
|
|
56
|
+
const copied=known.filter(c=>columns.includes(c));
|
|
57
|
+
for(const a of attached) db.exec(`DROP ${a.type.toUpperCase()} ${a.name}`);
|
|
58
|
+
db.exec('ALTER TABLE lifecycle_events RENAME TO lifecycle_events_pre71');
|
|
59
|
+
db.exec(`CREATE TABLE lifecycle_events (${lifecycleTableBody}, worker TEXT NOT NULL DEFAULT 'unknown', scope TEXT, outcome TEXT)`);
|
|
60
|
+
db.exec(`INSERT INTO lifecycle_events(${copied.join(',')}) SELECT ${copied.join(',')} FROM lifecycle_events_pre71 ORDER BY id`);
|
|
61
|
+
// AUTOINCREMENT remembers the highest id ever issued, which can be above the highest id still stored once retention
|
|
62
|
+
// has removed old events. Copying explicit ids restarts it at the copied max, so carry the old mark over or ids repeat.
|
|
63
|
+
const issued=db.prepare("SELECT seq FROM sqlite_sequence WHERE name='lifecycle_events_pre71'").get()?.seq??0;
|
|
64
|
+
db.exec('DROP TABLE lifecycle_events_pre71');
|
|
65
|
+
const kept=db.prepare("SELECT seq FROM sqlite_sequence WHERE name='lifecycle_events'").get()?.seq??0;
|
|
66
|
+
if(Math.max(issued,kept)>0) {
|
|
67
|
+
if(db.prepare("SELECT 1 FROM sqlite_sequence WHERE name='lifecycle_events'").get()) db.prepare("UPDATE sqlite_sequence SET seq=? WHERE name='lifecycle_events'").run(Math.max(issued,kept));
|
|
68
|
+
else db.prepare("INSERT INTO sqlite_sequence(name,seq) VALUES('lifecycle_events',?)").run(Math.max(issued,kept));
|
|
69
|
+
}
|
|
70
|
+
for(const a of attached) db.exec(a.sql);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// What a control verb controlled and what it left alone, as text for the owner. ref is the stored scope.
|
|
74
|
+
export function controlScopeText(type,{ref,claimed=false}={}) {
|
|
75
|
+
if(type==='withdraw_work') return {ref,controlled:'the job: its authority is withdrawn, so a result sent after this is kept as audit evidence and not accepted',
|
|
76
|
+
not_controlled:claimed?'worker compute: the worker may still run and report late; nothing here proves it stopped':'nothing was running, so there was no worker compute to stop'};
|
|
77
|
+
if(type==='detach') return {ref,controlled:'the claim: it is released and the job goes back to the queue, and the old claim id stops working',
|
|
78
|
+
not_controlled:'the worker session: it is not stopped, and it may still run until it sees the claim is gone'};
|
|
79
|
+
if(type==='interrupt_foreground') return {ref,controlled:'a request to interrupt the foreground run',not_controlled:'whether the run stopped: the outcome stays unknown until an observation confirms it'};
|
|
80
|
+
if(type==='revoke_grant') return {ref,controlled:'the grant: no new call is admitted under it',not_controlled:'a call already in flight under the grant'};
|
|
81
|
+
throw new Error(`unknown control type ${type}`);
|
|
82
|
+
}
|
|
83
|
+
|
|
26
84
|
export const checkOutcome=(job,run)=>{
|
|
27
85
|
const base=`check_id=${job.check_id};check_run_id=${job.id}`;
|
|
28
86
|
const skipped=job.skipped_segments??run?.skipped_segments??(run?.exit_code===77?1:0);
|
package/src/patch-apply.mjs
CHANGED
|
@@ -2,15 +2,60 @@
|
|
|
2
2
|
// adapter's read-only check. Nothing here talks to the bridge.
|
|
3
3
|
import { spawnSync } from 'node:child_process';
|
|
4
4
|
import { createHash } from 'node:crypto';
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
5
7
|
|
|
6
8
|
const git = (dir, args, input, env) => spawnSync('git', ['-C', dir, ...args], { input, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, env });
|
|
7
9
|
|
|
8
10
|
// git apply from a subdirectory can silently skip root-relative paths.
|
|
9
|
-
function worktreeRoot(dir, env) {
|
|
11
|
+
export function worktreeRoot(dir, env) {
|
|
10
12
|
const root = git(dir, ['rev-parse', '--show-toplevel'], undefined, env);
|
|
11
13
|
return root.status === 0 ? root.stdout.replace(/\r?\n$/, '') : null;
|
|
12
14
|
}
|
|
13
15
|
|
|
16
|
+
// What the patch can touch, read before it runs: each named file's bytes, mode or link target, or its absence, and the
|
|
17
|
+
// directories that do not exist yet (a new file may create them).
|
|
18
|
+
function snapshot(root, files) {
|
|
19
|
+
const entries = [], newDirs = new Set();
|
|
20
|
+
for (const file of new Set(files)) {
|
|
21
|
+
const target = path.join(root, file);
|
|
22
|
+
let stat = null;
|
|
23
|
+
try { stat = fs.lstatSync(target); } catch {}
|
|
24
|
+
if (!stat) {
|
|
25
|
+
entries.push({ target, absent: true });
|
|
26
|
+
for (let parent = path.dirname(target); parent.startsWith(root + path.sep) && !fs.existsSync(parent); parent = path.dirname(parent)) newDirs.add(parent);
|
|
27
|
+
} else if (stat.isSymbolicLink()) entries.push({ target, link: fs.readlinkSync(target) });
|
|
28
|
+
else if (stat.isFile()) entries.push({ target, data: fs.readFileSync(target), mode: stat.mode & 0o7777 });
|
|
29
|
+
else entries.push({ target, opaque: true });
|
|
30
|
+
}
|
|
31
|
+
return { entries, newDirs: [...newDirs].sort((a, b) => b.length - a.length) };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Puts every snapshotted file back. A file that already equals its snapshot is not rewritten, so a read-only directory
|
|
35
|
+
// that stopped the patch does not stop the restore. Returns the names it could not restore.
|
|
36
|
+
function restore(snap) {
|
|
37
|
+
const failed = [];
|
|
38
|
+
for (const entry of snap.entries) {
|
|
39
|
+
try {
|
|
40
|
+
let now = null;
|
|
41
|
+
try { now = fs.lstatSync(entry.target); } catch {}
|
|
42
|
+
if (entry.absent) { if (now) fs.rmSync(entry.target, { recursive: true, force: true }); }
|
|
43
|
+
else if (entry.link !== undefined) {
|
|
44
|
+
if (now?.isSymbolicLink() && fs.readlinkSync(entry.target) === entry.link) continue;
|
|
45
|
+
if (now) fs.rmSync(entry.target, { force: true });
|
|
46
|
+
fs.symlinkSync(entry.link, entry.target);
|
|
47
|
+
} else if (entry.data) {
|
|
48
|
+
if (now?.isFile() && (now.mode & 0o7777) === entry.mode && fs.readFileSync(entry.target).equals(entry.data)) continue;
|
|
49
|
+
if (now) fs.rmSync(entry.target, { force: true });
|
|
50
|
+
fs.mkdirSync(path.dirname(entry.target), { recursive: true });
|
|
51
|
+
fs.writeFileSync(entry.target, entry.data, { mode: entry.mode }); fs.chmodSync(entry.target, entry.mode);
|
|
52
|
+
}
|
|
53
|
+
} catch { failed.push(path.basename(entry.target)); }
|
|
54
|
+
}
|
|
55
|
+
for (const dir of snap.newDirs) { try { fs.rmdirSync(dir); } catch {} }
|
|
56
|
+
return failed;
|
|
57
|
+
}
|
|
58
|
+
|
|
14
59
|
// The patch must apply onto the job's base or a descendant of it, so HEAD has to contain base. Returns null when it does,
|
|
15
60
|
// else the reason in one sentence.
|
|
16
61
|
export function baseProblem(dir, baseSha, env) {
|
|
@@ -24,17 +69,8 @@ export function baseProblem(dir, baseSha, env) {
|
|
|
24
69
|
return anc.status === 0 ? null : `could not compare base and HEAD: ${anc.stderr.trim()}`;
|
|
25
70
|
}
|
|
26
71
|
|
|
27
|
-
//
|
|
28
|
-
|
|
29
|
-
export function applyPatch({ dir, patch, sha256, baseSha, env }) {
|
|
30
|
-
const body = Buffer.from(patch);
|
|
31
|
-
if (sha256 && createHash('sha256').update(body).digest('hex') !== sha256) throw new Error('patch sha256 does not match the recorded evidence; not applied');
|
|
32
|
-
const problem = baseProblem(dir, baseSha, env);
|
|
33
|
-
if (problem) throw new Error(`not applied: ${problem}`);
|
|
34
|
-
dir = worktreeRoot(dir, env);
|
|
35
|
-
if (!dir) throw new Error('not applied: could not resolve the repository worktree top level');
|
|
36
|
-
const check = git(dir, ['apply', '--check', '-'], body, env);
|
|
37
|
-
if (check.status !== 0) throw new Error(`not applied: git apply --check failed: ${(check.stderr || '').trim().slice(0, 300)}`);
|
|
72
|
+
// The files a patch names, renames as old and new, read from the patch alone (no check against the tree).
|
|
73
|
+
export function listPatchFiles(dir, body, env) {
|
|
38
74
|
const numstat = git(dir, ['apply', '--numstat', '-z', '-'], body, env);
|
|
39
75
|
if (numstat.error || numstat.status !== 0) throw new Error(`git apply --numstat failed: ${(numstat.stderr || numstat.error?.message || '').trim().slice(0, 300)}`);
|
|
40
76
|
const records = numstat.stdout.split('\0');
|
|
@@ -53,8 +89,33 @@ export function applyPatch({ dir, patch, sha256, baseSha, env }) {
|
|
|
53
89
|
index += 2;
|
|
54
90
|
}
|
|
55
91
|
}
|
|
92
|
+
return files;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Checks the digest, the base and `git apply --check`, then applies. Preflight failures touch nothing; a failed apply
|
|
96
|
+
// process restores the files it touched (a restore that itself fails is named in the error). Returns the list of touched file names. With checkOnly, it stops after
|
|
97
|
+
// the checks and the file list and writes nothing, so a caller can take an authorization between the check and the write.
|
|
98
|
+
export function applyPatch({ dir, patch, sha256, baseSha, env, checkOnly = false }) {
|
|
99
|
+
const body = Buffer.from(patch);
|
|
100
|
+
if (sha256 && createHash('sha256').update(body).digest('hex') !== sha256) throw new Error('patch sha256 does not match the recorded evidence; not applied');
|
|
101
|
+
const problem = baseProblem(dir, baseSha, env);
|
|
102
|
+
if (problem) throw new Error(`not applied: ${problem}`);
|
|
103
|
+
dir = worktreeRoot(dir, env);
|
|
104
|
+
if (!dir) throw new Error('not applied: could not resolve the repository worktree top level');
|
|
105
|
+
const check = git(dir, ['apply', '--check', '-'], body, env);
|
|
106
|
+
if (check.status !== 0) throw new Error(`not applied: git apply --check failed: ${(check.stderr || '').trim().slice(0, 300)}`);
|
|
107
|
+
const files = listPatchFiles(dir, body, env);
|
|
108
|
+
if (checkOnly) return files;
|
|
109
|
+
// git apply checks everything first but writes file by file, so a write error can leave some files changed. Keep what it
|
|
110
|
+
// may touch and put it back on any failure: the tree is the one it was, or the error names what could not be restored.
|
|
111
|
+
const before = snapshot(dir, files);
|
|
56
112
|
const run = git(dir, ['apply', '-'], body, env);
|
|
57
|
-
if (run.status !== 0)
|
|
113
|
+
if (run.status !== 0) {
|
|
114
|
+
const failed = restore(before), reason = (run.stderr || run.error?.message || '').trim().slice(0, 300);
|
|
115
|
+
throw new Error(failed.length
|
|
116
|
+
? `git apply failed after a clean check, and ${failed.join(', ')} could not be restored; the checkout is partially changed: ${reason}`
|
|
117
|
+
: `git apply failed after a clean check; every touched file was restored to its earlier content: ${reason}`);
|
|
118
|
+
}
|
|
58
119
|
return files;
|
|
59
120
|
}
|
|
60
121
|
|