@tnunamak/dalan 0.8.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 +12 -0
- package/PROTOCOL.md +6 -0
- package/bin/dot-worker.mjs +102 -14
- package/docs/local-agent-requester.md +1 -1
- package/docs/operations.md +2 -1
- package/docs/pull-workers.md +1 -0
- package/docs/relationships.md +13 -0
- package/docs/t3-integration.md +2 -0
- package/docs/t3-wake-fence-r4.md +1 -1
- package/docs/test-suite-isolation.md +1 -0
- package/docs/usage.md +14 -2
- package/package.json +2 -2
- package/src/claim-command-ledger.mjs +3 -2
- package/src/cli-help.mjs +15 -7
- package/src/inbox.mjs +13 -3
- package/src/lifecycle.mjs +60 -2
- package/src/patch-apply.mjs +74 -13
- package/src/server.mjs +149 -23
- package/src/status-summary.mjs +3 -0
- package/src/store.mjs +229 -26
- package/src/workers.mjs +20 -2
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/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
|
|
package/src/server.mjs
CHANGED
|
@@ -14,7 +14,7 @@ import fs from 'node:fs';
|
|
|
14
14
|
import path from 'node:path';
|
|
15
15
|
import os from 'node:os';
|
|
16
16
|
import { randomBytes, randomUUID, createHash, timingSafeEqual } from 'node:crypto';
|
|
17
|
-
import { loadWorkers, hasInstalledDatabase, legacyMarkerPath, seedWorkerRepos, resolveWorker, hasCapability, assertTarget, submitTarget } from './workers.mjs';
|
|
17
|
+
import { loadWorkers, loadEffectiveOwnerWorkers, hasInstalledDatabase, legacyMarkerPath, seedWorkerRepos, resolveWorker, hasCapability, assertTarget, submitTarget, ensureWorkerRelationship } from './workers.mjs';
|
|
18
18
|
import { Store, QUESTION_PURPOSES, nonterminalOutcome, validateProtocol, loadRedeliveryLimits, resumeNudge } from './store.mjs';
|
|
19
19
|
import {protocolArtifactChunk} from './protocol-artifact-commands.mjs';
|
|
20
20
|
import { sendWebhook, validSecret } from './webhooks.mjs';
|
|
@@ -38,7 +38,7 @@ import { parseExecution, parseRequiredCapabilities, admitHostExecution, admitAda
|
|
|
38
38
|
import { loadCapacity } from './projects.mjs';
|
|
39
39
|
import { authConfig, assertPublicRouteAuth, isLoopbackBindHost, protectedResource, challenge, verifyBearer, needScope } from './auth.mjs';
|
|
40
40
|
import { beginMcpOutcome, recordMcpResponse, pathShape, uaToken } from './mcp-outcome.mjs';
|
|
41
|
-
import { lifecycleMetrics, retainLifecycle } from './lifecycle.mjs';
|
|
41
|
+
import { lifecycleMetrics, retainLifecycle, controlScopeText } from './lifecycle.mjs';
|
|
42
42
|
import { normalizeMeta } from './objectives.mjs';
|
|
43
43
|
import { createRequestLog } from './request-log.mjs';
|
|
44
44
|
import { logShutdownSignals } from './shutdown-signal.mjs';
|
|
@@ -148,6 +148,9 @@ const store = new Store(path.join(dataDir, 'bridge.db'),{
|
|
|
148
148
|
// Intentional service startup opts past Store's accidental-migration footgun guard.
|
|
149
149
|
deferSubscriptionRetirement:true,markProfileModeSeen:!legacyProfile,allowDefaultHomeMigration:true
|
|
150
150
|
});
|
|
151
|
+
// An offline worker allow can precede the database. Reconcile named profiles at startup;
|
|
152
|
+
// legacy installations retain their pre-relationship behavior until explicitly enrolled.
|
|
153
|
+
if(!legacyProfile) for(const worker of workers.workers.keys()) ensureWorkerRelationship(store.db,worker);
|
|
151
154
|
const ackLedger=new AckLedger(path.join(dataDir,'delivery-acks.db'));
|
|
152
155
|
const notifyLedger=new NotifyLedger(path.join(dataDir,'notify-sent.db'));
|
|
153
156
|
process.on('exit',()=>{try{ackLedger.close();}catch{}try{notifyLedger.close();}catch{}});
|
|
@@ -620,6 +623,78 @@ const listGuidance='Claim every listed assignment you can start now, up to free_
|
|
|
620
623
|
const claimMoreGuidance='If free_lanes > 0 and work is queued, claim more now.';
|
|
621
624
|
// A finishing lane takes the next queued item itself; an error on any claim means the list changed, so list again.
|
|
622
625
|
const finishNextGuidance=next=>`Claim ${next[0].request_id} yourself before you end this run, then keep claiming up to free lanes. After any claim error such as assignment_expired, call list_pending and claim from that list.`;
|
|
626
|
+
// A worker with finish_handoff gets its next job inside the finish reply, or waits a bounded time for work.
|
|
627
|
+
// The claim is the worker's own `claim` call, run by the bridge: same policy, preflight, scope, pause, capacity and
|
|
628
|
+
// connection checks, one claim per job. The claim carries acquisition_id handoff-<finished claim_id>, so a repeated
|
|
629
|
+
// finish gets the same job back, and a second finish by the same claimant name, which would otherwise count as an
|
|
630
|
+
// exact retry of the first claim, is refused that job and takes the next one.
|
|
631
|
+
const HANDOFF_LEASE_MS=600000,HANDOFF_POLL_MS=500,HANDOFF_MAX_ATTEMPTS=5;
|
|
632
|
+
const nap=(ms,signal)=>new Promise(resolve=>{
|
|
633
|
+
const done=()=>{clearTimeout(timer);signal?.removeEventListener('abort',done);resolve();};
|
|
634
|
+
const timer=setTimeout(done,ms);
|
|
635
|
+
signal?.addEventListener('abort',done,{once:true});
|
|
636
|
+
});
|
|
637
|
+
// One handoff per finished claim at a time: a retried finish that arrives while the first is still waiting or
|
|
638
|
+
// claiming queues behind it, then finds the first one's grant instead of taking a second job.
|
|
639
|
+
const handoffsInFlight=new Map();
|
|
640
|
+
async function handOffNextJob(args) {
|
|
641
|
+
const key=`${args.principal.worker}\0${args.principal.subject}\0${args.claimId}`;
|
|
642
|
+
while(handoffsInFlight.has(key)) await handoffsInFlight.get(key);
|
|
643
|
+
const run=runHandoff(args).finally(()=>handoffsInFlight.delete(key));
|
|
644
|
+
handoffsInFlight.set(key,run);
|
|
645
|
+
return run;
|
|
646
|
+
}
|
|
647
|
+
// Returns {job}, {empty,waited_ms} or {} (no handoff: the caller keeps the old hint). Never throws: the finish is stored.
|
|
648
|
+
async function runHandoff({principal,requestId,claimId,waitMs,signal}) {
|
|
649
|
+
try {
|
|
650
|
+
const {worker,subject}=principal;
|
|
651
|
+
const held=store.db.prepare('SELECT claimant FROM claims WHERE request_id=? AND claim_id=?').get(requestId,claimId);
|
|
652
|
+
if(!held) return {};
|
|
653
|
+
const acquisition_id=`handoff-${claimId}`,lease_ms=Math.min(HANDOFF_LEASE_MS,store.limits.leaseMs);
|
|
654
|
+
const claim=async next=>{
|
|
655
|
+
try {
|
|
656
|
+
const job=await tool('claim',{request_id:next,claimant:held.claimant,acquisition_id,lease_ms},principal,undefined,signal);
|
|
657
|
+
return job&&typeof job.error!=='string'&&job.claim_id?job:null;
|
|
658
|
+
} catch { return null; }
|
|
659
|
+
};
|
|
660
|
+
// A repeated finish gets back the job its first reply carried. If that job is gone (finished, expired), this finish
|
|
661
|
+
// already had its handoff: it takes no second job.
|
|
662
|
+
const prior=store.db.prepare("SELECT c.request_id,c.state,a.status FROM claims c JOIN assignments a USING(request_id) WHERE c.worker=? AND c.subject=? AND c.acquisition_id=?").get(worker,subject,acquisition_id);
|
|
663
|
+
if(prior) { const job=prior.state==='active'&&prior.status==='claimed'?await claim(prior.request_id):null; return job?{job}:{}; }
|
|
664
|
+
const started=Date.now(),tried=new Set();
|
|
665
|
+
let sawQueued=false;
|
|
666
|
+
for(;;) {
|
|
667
|
+
if(signal?.aborted||store.paused()) return {};
|
|
668
|
+
const {free_lanes}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
|
|
669
|
+
if(free_lanes<=0) return {};
|
|
670
|
+
if(store.hasQueuedFor([worker])) {
|
|
671
|
+
sawQueued=true;
|
|
672
|
+
const pick=()=>(store.nextQueued(free_lanes+tried.size,null,worker).next_queued??[]).filter(x=>!tried.has(x.request_id));
|
|
673
|
+
// A lost race or an unclaimable head moves on to the next job; an unclaimable queue ends in the old hint.
|
|
674
|
+
for(let fresh=pick();fresh.length&&tried.size<HANDOFF_MAX_ATTEMPTS;fresh=pick()) {
|
|
675
|
+
tried.add(fresh[0].request_id);
|
|
676
|
+
const job=await claim(fresh[0].request_id);
|
|
677
|
+
if(job) return {job};
|
|
678
|
+
}
|
|
679
|
+
if(tried.size) return {};
|
|
680
|
+
}
|
|
681
|
+
const left=started+waitMs-Date.now();
|
|
682
|
+
if(left<=0) return sawQueued?{}:{empty:true,waited_ms:Date.now()-started};
|
|
683
|
+
await nap(Math.min(HANDOFF_POLL_MS,left),signal);
|
|
684
|
+
}
|
|
685
|
+
} catch(error) { log({kind:'finish_handoff_error',request_id:requestId,reason:redactNote(String(error?.message??error))}); return {}; }
|
|
686
|
+
}
|
|
687
|
+
async function finishReply(reply,{principal,requestId,claimId,signal}) {
|
|
688
|
+
const setting=workers.workers.get(principal.worker)?.finishHandoff;
|
|
689
|
+
if(setting&&reply.receipt_id&&!store.isProtocolJob(requestId)) {
|
|
690
|
+
const {job,empty,waited_ms}=await handOffNextJob({principal,requestId,claimId,waitMs:setting.waitMs,signal});
|
|
691
|
+
log({kind:'finish_handoff',request_id:requestId,next_request_id:job?.request_id??null,result:job?'claimed':empty?'empty':'none',waited_ms:waited_ms??0});
|
|
692
|
+
const {next_queued,next_action,...rest}=reply;
|
|
693
|
+
if(job) return {...rest,next_job:job,guidance:`Your next job ${job.request_id} is already claimed for you; its claim result is in next_job. Work on it now, in this turn, and call finish for it. ${job.lease_expires_at?`Its lease ends at ${job.lease_expires_at}`:'Its lease is short'}; every tool call on it renews the lease.`};
|
|
694
|
+
if(empty) return {...rest,queue_empty:true,waited_ms,guidance:waited_ms>=1000?`No job was queued for ${Math.round(waited_ms/1000)} seconds. Nothing is claimed for you. End this run; a new assignment wakes you.`:'No job is queued. Nothing is claimed for you. End this run; a new assignment wakes you.'};
|
|
695
|
+
}
|
|
696
|
+
return reply.next_queued?.length&&!store.paused()?{...reply,guidance:finishNextGuidance(reply.next_queued)}:reply;
|
|
697
|
+
}
|
|
623
698
|
// A loader failure carries host paths or quotes the file. Every caller of this policy gets the Store's fixed error instead.
|
|
624
699
|
function repoPolicyFor(assignment) {
|
|
625
700
|
try { return currentRepoPolicy(); }
|
|
@@ -664,7 +739,7 @@ const policyPage=(worker,cursor=null)=>store.pullQueue.list(worker,admitPolicyWo
|
|
|
664
739
|
async function submitPolicy(body,req,dryRun) {
|
|
665
740
|
if(req.method!=='POST')throw new Error('policy submit requires POST');
|
|
666
741
|
if(body.background!==undefined&&typeof body.background!=='boolean'||body.review!==undefined&&typeof body.review!=='boolean'||body.allow_main!==undefined&&typeof body.allow_main!=='boolean')throw new Error('invalid policy submit flags');
|
|
667
|
-
if(body.worker!==undefined||body.command_key!==undefined||body.supersedes!==undefined||body.required_capabilities!==undefined||body.max_queued!==undefined||body.defer_queued!==undefined||body.destination_revision!==undefined) throw new Error('routing v1 cannot combine single-target, command, supersede or capacity options');
|
|
742
|
+
if(body.worker!==undefined||body.relationship_id!==undefined||body.command_key!==undefined||body.supersedes!==undefined||body.revises!==undefined||body.required_capabilities!==undefined||body.max_queued!==undefined||body.defer_queued!==undefined||body.destination_revision!==undefined) throw new Error('routing v1 cannot combine single-target, relationship, command, supersede, revise or capacity options');
|
|
668
743
|
if(!body.assignment||typeof body.assignment!=='object'||Array.isArray(body.assignment)||typeof body.assignment.request_id!=='string'||!/^[-\w]{8,128}$/.test(body.assignment.request_id)||body.assignment.request_id.startsWith(PULL_PAGE_PREFIX)) throw new Error('invalid assignment request_id');
|
|
669
744
|
if(!Array.isArray(body.assignment.inputs)) throw new Error('invalid assignment inputs');
|
|
670
745
|
if(body.assignment.schema_version!==1||typeof body.assignment.brief!=='string'||!body.assignment.brief.trim()||typeof body.assignment.expected_output!=='string'||typeof body.assignment.execution_scope!=='string')throw new Error('invalid assignment: needs schema_version 1, brief, inputs, expected_output and execution_scope');
|
|
@@ -682,6 +757,7 @@ async function submitPolicy(body,req,dryRun) {
|
|
|
682
757
|
const approvals=body.destination_revisions??{};
|
|
683
758
|
if(!approvals||typeof approvals!=='object'||Array.isArray(approvals)||Object.keys(approvals).some(worker=>!routing.allowed_workers.includes(worker)))throw new Error('invalid destination_revisions');
|
|
684
759
|
const options={delivery,environmentId:oldOptions?.environmentId??'',execution,review:body.review===true,priority,meta};
|
|
760
|
+
if(oldOptions&&Object.hasOwn(oldOptions,'relationships')) options.relationships=oldOptions.relationships;
|
|
685
761
|
if(old)return store.pullQueue.submit(JSON.parse(old.payload),identity,options,routing,approvals,owner,{dryRun});
|
|
686
762
|
let payload=identity,preflight=null;
|
|
687
763
|
// Validate scope under each candidate's current repository policy. No candidate
|
|
@@ -697,16 +773,23 @@ async function submitPolicy(body,req,dryRun) {
|
|
|
697
773
|
preflight=await preflightPR(payload);
|
|
698
774
|
options.environmentId=(await destination.validate(delivery)).environmentId??'';
|
|
699
775
|
for(const worker of routing.allowed_workers)if(!dryRun)admitPolicyWorker(worker,payload,execution,approvals[worker]);
|
|
700
|
-
|
|
701
|
-
//
|
|
702
|
-
|
|
703
|
-
|
|
776
|
+
// Capture each candidate's relationship at the same transaction boundary as admission.
|
|
777
|
+
// Acquisition uses this binding, so ending it later does not revoke accepted work.
|
|
778
|
+
const result=store.inTransaction(()=>{
|
|
779
|
+
const existing=store.pullQueue.row(identity.request_id);
|
|
780
|
+
if(existing) {
|
|
781
|
+
const saved=JSON.parse(existing.options);
|
|
782
|
+
if(Object.hasOwn(saved,'relationships')) options.relationships=saved.relationships;
|
|
783
|
+
} else options.relationships=Object.fromEntries(routing.allowed_workers.map(worker=>[worker,store.relationshipForSubmission(worker)?.relationship_id??null]));
|
|
784
|
+
return store.pullQueue.submit(payload,identity,options,routing,approvals,owner,{dryRun});
|
|
785
|
+
});
|
|
786
|
+
if(dryRun)return {...result,destination_disclosures:disclosures};
|
|
704
787
|
log({kind:'policy_work_submitted',request_id:identity.request_id,work_order_id:result.work_order_id});
|
|
705
788
|
return {...result,execution};
|
|
706
789
|
}
|
|
707
790
|
|
|
708
791
|
// Record the call on the claim it names (one UPDATE); a thrown error or a structured {error} result is kept as the last tool error.
|
|
709
|
-
async function tool(name,a,principal,notifyMeta) {
|
|
792
|
+
async function tool(name,a,principal,notifyMeta,signal) {
|
|
710
793
|
if(!toolNames.has(name)) throw new Error('unknown tool');
|
|
711
794
|
// Refuse hidden names before audits, lease touches, sweeps or repository preparation.
|
|
712
795
|
if(name==='claim'&&typeof a?.request_id==='string'&&store.hasAssignment(a.request_id)&&store.mayAct(principal.worker,a.request_id)&&
|
|
@@ -715,7 +798,7 @@ async function tool(name,a,principal,notifyMeta) {
|
|
|
715
798
|
}
|
|
716
799
|
let error=null;
|
|
717
800
|
try {
|
|
718
|
-
const result=await dispatchTool(name,a,principal,notifyMeta);
|
|
801
|
+
const result=await dispatchTool(name,a,principal,notifyMeta,signal);
|
|
719
802
|
if(typeof result?.error==='string') error=redactNote(result.error);
|
|
720
803
|
return result;
|
|
721
804
|
} catch(e) { error=redactNote(String(e?.message??e)); if(e.destination&&typeof a?.request_id==='string')notifyAttachedWaiter(a.request_id); throw e; }
|
|
@@ -726,7 +809,7 @@ async function tool(name,a,principal,notifyMeta) {
|
|
|
726
809
|
}
|
|
727
810
|
}
|
|
728
811
|
}
|
|
729
|
-
async function dispatchTool(name,a,principal,notifyMeta) {
|
|
812
|
+
async function dispatchTool(name,a,principal,notifyMeta,signal) {
|
|
730
813
|
const t3Audit=(t3Tools.has(name)||notifyTools.has(name))?await loadT3Audit():null;
|
|
731
814
|
if(t3Audit) t3Audit.admitT3Audit(store.db,principal.worker,principal.subject);
|
|
732
815
|
store.recordWorkerCall(principal.subject,toolNames.has(name)?name:'unknown',principal.worker);
|
|
@@ -941,8 +1024,7 @@ async function dispatchTool(name,a,principal,notifyMeta) {
|
|
|
941
1024
|
if(crashAt('after_report_persistence',a.request_id)) process.exit(73);
|
|
942
1025
|
notifyAttachedWaiter(requestId);
|
|
943
1026
|
if(repaired.marks.summary_derived||repaired.marks.summary_truncated) log({kind:'finish_summary_repaired',request_id:requestId,...repaired.marks});
|
|
944
|
-
|
|
945
|
-
return receipt.next_queued?.length&&!store.paused()?{...marked,guidance:finishNextGuidance(receipt.next_queued)}:marked; }
|
|
1027
|
+
return finishReply({...receipt,...repaired.marks},{principal,requestId,claimId,signal}); }
|
|
946
1028
|
case 'list_files': await workspace.makeRoom(id(a.request_id));workspaceFence();return workspace.list(id(a.request_id),id(a.claim_id,'claim_id'),subject,a.path,a.limit??200,worker,a.cursor);
|
|
947
1029
|
case 'read_file': await workspace.makeRoom(id(a.request_id));workspaceFence();return workspace.read(id(a.request_id),id(a.claim_id,'claim_id'),subject,a.path,a.start_line??1,a.max_lines??200,worker);
|
|
948
1030
|
case 'apply_patch': await workspace.makeRoom(id(a.request_id));workspaceFence();return workspace.apply(id(a.request_id),id(a.claim_id,'claim_id'),subject,a.patch,worker);
|
|
@@ -982,7 +1064,7 @@ function publicErrorText(error,what) {
|
|
|
982
1064
|
log({kind:'request_error',what,error_id:errorId,detail:safeDiagnostic(error?.stack??error,4000)});
|
|
983
1065
|
return `Error executing ${what} (error id ${errorId}; details are in the request log)`;
|
|
984
1066
|
}
|
|
985
|
-
async function dispatch(message,principal) {
|
|
1067
|
+
async function dispatch(message,principal,signal) {
|
|
986
1068
|
const p=message.params??{};
|
|
987
1069
|
switch(message.method) {
|
|
988
1070
|
case 'server/discover': return {ttlMs:0,cacheScope:'private',supportedVersions:['2026-07-28'],capabilities:{tools:{},events:{}},_meta:{'io.modelcontextprotocol/serverInfo':serverInfo}};
|
|
@@ -991,7 +1073,7 @@ async function dispatch(message,principal) {
|
|
|
991
1073
|
// Modern catalogs are process-wide. A worker's capability controls tools/call authority, not its cached schemas.
|
|
992
1074
|
// legacy-v46 keeps its pinned per-worker surface for compatibility.
|
|
993
1075
|
case 'tools/list': return {ttlMs:0,cacheScope:'private',tools:catalogProfile==='legacy-v46'?tools.filter(t=>!(t3Tools.has(t.name)||notifyTools.has(t.name))||hasCapability(workers,principal.worker,'t3')):tools};
|
|
994
|
-
case 'tools/call': { try { return {content:[{type:'text',text:JSON.stringify(redactOutput(await tool(p.name,p.arguments??{},principal,notifyTools.has(p.name)?p._meta:undefined)))}],isError:false}; } catch(e) { const error={content:[{type:'text',text:publicErrorText(e,`tool ${toolNames.has(p.name)?p.name:'unknown'}`)}],isError:true};if(oauth&&e.message==='insufficient_scope')error._meta={'mcp/www_authenticate':[[challenge(oauth,scopeFor(p.name)),'error="insufficient_scope"','error_description="Required scope is missing"'].join(', ')]};return error; } }
|
|
1076
|
+
case 'tools/call': { try { return {content:[{type:'text',text:JSON.stringify(redactOutput(await tool(p.name,p.arguments??{},principal,notifyTools.has(p.name)?p._meta:undefined,signal)))}],isError:false}; } catch(e) { const error={content:[{type:'text',text:publicErrorText(e,`tool ${toolNames.has(p.name)?p.name:'unknown'}`)}],isError:true};if(oauth&&e.message==='insufficient_scope')error._meta={'mcp/www_authenticate':[[challenge(oauth,scopeFor(p.name)),'error="insufficient_scope"','error_description="Required scope is missing"'].join(', ')]};return error; } }
|
|
995
1077
|
case 'events/list': return {events:[event]};
|
|
996
1078
|
case 'events/subscribe': if(oauth)needScope(principal,'dalan.read');return subscribe(p,principal);
|
|
997
1079
|
case 'events/unsubscribe': { if(oauth)needScope(principal,'dalan.read');if(!validEventParams(p)) throw new Error('invalid subscription'); store.unsubscribe(subId(p.delivery.url,principal.subject,principal.worker)); return {}; }
|
|
@@ -1034,7 +1116,9 @@ const publicServer=(as?createBuiltinHttpServer:http.createServer)(async(req,res)
|
|
|
1034
1116
|
if(!Object.hasOwn(rpc,'id')) { res.writeHead(202); res.end(); return; }
|
|
1035
1117
|
outcome.state.phase='dispatch';
|
|
1036
1118
|
const eventStream=readEnv('DALAN_TRIAL_SSE')==='1'&&req.method==='POST'&&acceptsMcpEventStream(req.headers.accept)?beginMcpEventStream(res):null;
|
|
1037
|
-
|
|
1119
|
+
// A tool that waits (finish with finish_handoff) stops when the client leaves, so nothing is claimed for nobody.
|
|
1120
|
+
const clientGone=new AbortController();res.once('close',()=>clientGone.abort());if(res.destroyed)clientGone.abort();
|
|
1121
|
+
try { json(res,200,{jsonrpc:'2.0',id:rpc.id,result:{resultType:'complete',...await dispatch(rpc,principal,clientGone.signal)}},eventStream); }
|
|
1038
1122
|
catch(e) { json(res,200,rpcError(rpc.id,e.code||-32602,publicErrorText(e,'request'),e.data),eventStream); }
|
|
1039
1123
|
// Response-byte accounting for the throttle and the break ledger; the response is already written, so a failure only logs.
|
|
1040
1124
|
if(outcome.state.tool) try { store.recordResponseBytes(principal.subject,outcome.state.tool,outcome.state.response_bytes,principal.worker); } catch(e) { log({kind:'response_bytes_error',call_id:outcome.state.call_id,reason:e.message}); }
|
|
@@ -1076,6 +1160,8 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1076
1160
|
if(body.assignment?.request_id===absentId) throw new Error('invalid assignment');
|
|
1077
1161
|
const commandKey=body.command_key===undefined?null:body.command_key;
|
|
1078
1162
|
const supersedes=body.supersedes===undefined?null:body.supersedes;
|
|
1163
|
+
// {prior_id, prior_token}: this job corrects that one. Shape and authority are checked by the Store, in the submit transaction.
|
|
1164
|
+
const revises=body.revises===undefined?null:body.revises;
|
|
1079
1165
|
const destinationRevision=body.destination_revision??null;
|
|
1080
1166
|
if(body.destination_revision!==undefined&&(typeof destinationRevision!=='string'||!/^sha256:[a-f0-9]{64}$/.test(destinationRevision)))throw new Error('invalid destination_revision');
|
|
1081
1167
|
if(body.command_key!==undefined&&(typeof commandKey!=='string'||commandKey.length<1||commandKey.length>128)) throw new Error('invalid command_key: use a nonempty string of at most 128 characters');
|
|
@@ -1131,9 +1217,10 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1131
1217
|
// even when validation changed the stored brief (scope narrowing, the appended allow-list).
|
|
1132
1218
|
const submitted=payload;
|
|
1133
1219
|
const isNew=!store.hasAssignment(payload.request_id);
|
|
1220
|
+
if(isNew&&dryRun) store.relationshipForSubmission(target,body.relationship_id??null);
|
|
1134
1221
|
// Reject immutable retry conflicts using the persisted binding before any external destination inspection.
|
|
1135
1222
|
// A matching retry still validates the current destination below; this does not accept stale environment evidence.
|
|
1136
|
-
store.checkRetry(submitted,delivery,existingRequest?.environment_id,owner,body.review===true,body.background===true?'background':'normal',meta,submitted,target,explicitExecution,requiredCapabilities,commandKey,supersedes,destinationRevision);
|
|
1223
|
+
store.checkRetry(submitted,delivery,existingRequest?.environment_id,owner,body.review===true,body.background===true?'background':'normal',meta,submitted,target,explicitExecution,requiredCapabilities,commandKey,supersedes,destinationRevision,revises);
|
|
1137
1224
|
let order=null;
|
|
1138
1225
|
if(isNew) {
|
|
1139
1226
|
order=await compileWorkOrder({assignment:payload,review:body.review===true,priority:body.background===true?'background':'normal',jobExecution,requiredCapabilities,meta,maxQueued:body.max_queued??null,deferQueued:body.defer_queued??null,
|
|
@@ -1166,7 +1253,7 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1166
1253
|
const {environmentId,generation}=(dryRun&&order&&order.verdict!=='admissible')?{}:await destination.validate(delivery);
|
|
1167
1254
|
// An awaited repository/destination lookup may outlive a host policy edit.
|
|
1168
1255
|
assertRepoAllowed(storedTarget??target??'dot',existingRequest?.assignment??payload);
|
|
1169
|
-
if(dryRun) store.checkRetry(submitted,delivery,environmentId,owner,body.review===true,body.background===true?'background':'normal',meta,submitted,target,explicitExecution,requiredCapabilities,commandKey,supersedes,destinationRevision);
|
|
1256
|
+
if(dryRun) store.checkRetry(submitted,delivery,environmentId,owner,body.review===true,body.background===true?'background':'normal',meta,submitted,target,explicitExecution,requiredCapabilities,commandKey,supersedes,destinationRevision,revises);
|
|
1170
1257
|
const disclosure=isNew?store.destinationSnapshot(target??'dot',jobExecution,payload):existingRequest.destination_approval?.snapshot??null;
|
|
1171
1258
|
if(dryRun) {
|
|
1172
1259
|
log({kind:'submit_dry_run',request_id:submitted.request_id,task_kind:meta.task_kind??null,source:meta.source??null,verdict:order?.verdict??'admissible',reason_codes:(order?.reasons??[]).map(r=>r.code),attempt_latency_ms:Date.now()-requestStartedAt});
|
|
@@ -1181,7 +1268,7 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1181
1268
|
const readiness=order?.check_readiness??null;
|
|
1182
1269
|
const preflight=order?.preflight??null;
|
|
1183
1270
|
const defaultValidity=order?.defaultValidity??null;
|
|
1184
|
-
const result=store.submit(payload,delivery,environmentId,owner,body.review===true,preflight,body.background===true?'background':'normal',meta,(()=>{const r=renderAssignment(submitted);return payload.brief!==r.brief||JSON.stringify(payload.scope_paths)!==JSON.stringify(r.scope_paths);})()?submitted:payload,body.max_queued??null,target,explicitExecution,workers.defaultExecution,requiredCapabilities,defaultValidity?.valid_until??null,commandKey,supersedes,destinationRevision,null,generation??null);
|
|
1271
|
+
const result=store.submit(payload,delivery,environmentId,owner,body.review===true,preflight,body.background===true?'background':'normal',meta,(()=>{const r=renderAssignment(submitted);return payload.brief!==r.brief||JSON.stringify(payload.scope_paths)!==JSON.stringify(r.scope_paths);})()?submitted:payload,body.max_queued??null,target,explicitExecution,workers.defaultExecution,requiredCapabilities,defaultValidity?.valid_until??null,commandKey,supersedes,destinationRevision,null,generation??null,body.relationship_id??null,revises);
|
|
1185
1272
|
// Only a committed first replacement wakes the TARGET's already-attached waiter.
|
|
1186
1273
|
if(supersedes&&!result.duplicate) {
|
|
1187
1274
|
const targetId=supersedes.target_id,waiter=waiters.get(targetId);
|
|
@@ -1275,6 +1362,16 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1275
1362
|
const requestId=id(body.id); adminOwner(req,requestId);
|
|
1276
1363
|
if(body.decision==='stale') throw new Error('stale is recorded by the sweep only');
|
|
1277
1364
|
const via=['cli','apply','adapter'].includes(body.via)?body.via:'cli';
|
|
1365
|
+
// The two-phase apply: reserve (the stale check), then confirm or release once the patch is written or has failed.
|
|
1366
|
+
if(body.phase!==undefined) {
|
|
1367
|
+
if(body.decision!=='applied'||!['reserve','confirm','release'].includes(body.phase)) throw new Error('phase is reserve, confirm or release, and goes with decision applied');
|
|
1368
|
+
// Every attempt reserves and gets a token; confirm and release must present the current one. force releases an
|
|
1369
|
+
// uncertain reservation on purpose (the owner's own capability, no token).
|
|
1370
|
+
if(body.phase==='reserve') return json(res,200,store.reserveApply(requestId));
|
|
1371
|
+
const attempt=body.attempt===undefined||body.attempt===null?undefined:str(body.attempt,'attempt',128);
|
|
1372
|
+
if(body.phase==='release') return json(res,200,store.releaseApply(requestId,{attempt,force:body.force===true,reason:body.reason===undefined||body.reason===null?null:str(body.reason,'reason',512)}));
|
|
1373
|
+
return json(res,200,store.confirmApply(requestId,{attempt,note:body.note===undefined||body.note===null?null:str(body.note,'note',4096),via}));
|
|
1374
|
+
}
|
|
1278
1375
|
return json(res,200,store.decide(requestId,String(body.decision),{note:body.note===undefined||body.note===null?null:str(body.note,'note',4096),via}));
|
|
1279
1376
|
}
|
|
1280
1377
|
if(url.pathname==='/lifecycle'&&req.method==='POST') {
|
|
@@ -1287,6 +1384,29 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1287
1384
|
if(url.pathname==='/questions'&&req.method==='GET') { const requestId=id(url.searchParams.get('id'));adminOwner(req,requestId);return json(res,200,{request_id:requestId,questions:store.questions(requestId)}); }
|
|
1288
1385
|
if(url.pathname==='/tell'&&req.method==='POST') return json(res,200,store.tell(str(body.text,'text',4096),body.worker===undefined&&workers.workers.has('dot')?'dot':submitTarget(workers,body.worker)??assertTarget(workers,'dot')));
|
|
1289
1386
|
if(url.pathname==='/untell'&&req.method==='POST') return json(res,200,store.untell(id(body.message_id,'message_id'),body.worker===undefined?null:assertTarget(workers,body.worker)));
|
|
1387
|
+
if(url.pathname==='/relationships'&&req.method==='GET') { adminOperator(req); return json(res,200,{relationships:store.db.prepare('SELECT * FROM relationships ORDER BY created_at, rowid').all()}); }
|
|
1388
|
+
if(url.pathname==='/relationships/end'&&req.method==='POST') {
|
|
1389
|
+
adminOperator(req);
|
|
1390
|
+
const relationshipId=str(body.relationship_id,'relationship_id',128);
|
|
1391
|
+
const changed=store.db.prepare('UPDATE relationships SET ended_at=COALESCE(ended_at,?) WHERE relationship_id=?').run(new Date(store.nowMs()).toISOString(),relationshipId);
|
|
1392
|
+
if(!changed.changes) throw new Error('relationship_not_found');
|
|
1393
|
+
return json(res,200,{relationship:store.db.prepare('SELECT * FROM relationships WHERE relationship_id=?').get(relationshipId)});
|
|
1394
|
+
}
|
|
1395
|
+
if(url.pathname==='/grants'&&req.method==='GET') {
|
|
1396
|
+
adminOperator(req);
|
|
1397
|
+
const currentWorkers=loadEffectiveOwnerWorkers(workersFile);
|
|
1398
|
+
const grants=[
|
|
1399
|
+
...store.db.prepare("SELECT c.*,a.relationship_id FROM claims c JOIN assignments a USING(request_id) WHERE c.state='active' AND a.status='claimed'").all().filter(row=>!store.leaseExpired(row)).map(row=>({request_id:row.request_id,worker:row.worker,relationship_id:row.relationship_id,expires_at:store.leaseExpiresAt(row),enforcer:'claim_lease'})),
|
|
1400
|
+
...store.db.prepare('SELECT g.tool,g.worker,g.granted_at,g.scope FROM tool_grants g JOIN registered_tools t ON t.name=g.tool WHERE t.enabled=1').all().map(row=>({...row,scope:row.scope===null?null:JSON.parse(row.scope),enforcer:'tool_registry',expires_at:null})),
|
|
1401
|
+
...store.db.prepare('SELECT d.request_id,d.revision,d.approved_at,a.relationship_id FROM destination_approvals d JOIN assignments a USING(request_id)').all().map(row=>({...row,enforcer:'destination_approval',expires_at:null})),
|
|
1402
|
+
...store.activeSubscriptions().map(({id,principal,worker,expires_at})=>({id,principal,worker,expires_at,enforcer:'subscription'})),
|
|
1403
|
+
...store.db.prepare('SELECT request_id,relationship_id FROM assignments WHERE owner_hash IS NOT NULL').all().filter(row=>store.protocolListingLive(row.request_id)).map(row=>({...row,enforcer:'owner_capability',expires_at:store.getProtocol(row.request_id)?new Date(store.getProtocol(row.request_id).retain_until_ms).toISOString():null})),
|
|
1404
|
+
...[...currentWorkers.workers.keys()].flatMap(worker=>(currentWorkers.repoPolicy(worker)?.repos??[]).map(repo=>({worker,repo,enforcer:'repository_policy',expires_at:null}))),
|
|
1405
|
+
...(as?as.store.db.prepare("SELECT c.connection_id,c.worker,c.scopes,c.created_at,o.expires_at FROM connections c JOIN oidc o ON o.model='Grant' AND o.id=c.grant_id WHERE c.revoked_at IS NULL AND (o.expires_at IS NULL OR o.expires_at>?)").all(store.nowMs()).map(row=>({connection_id:row.connection_id,worker:row.worker,scopes:row.scopes.split(' '),created_at:new Date(row.created_at).toISOString(),enforcer:'connection',expires_at:row.expires_at===null?null:new Date(row.expires_at).toISOString()})):
|
|
1406
|
+
[...workers.workers].flatMap(([worker,profile])=>(profile.connections??[]).map(({issuer,subject,client_id,connection_id})=>({worker,issuer,subject,client_id,connection_id,enforcer:'external_connection',expires_at:null,expiry_status:'unknown'})))),
|
|
1407
|
+
];
|
|
1408
|
+
return json(res,200,{relationships:store.db.prepare('SELECT * FROM relationships ORDER BY created_at, rowid').all(),grants});
|
|
1409
|
+
}
|
|
1290
1410
|
if(url.pathname.startsWith('/connect/')) {
|
|
1291
1411
|
adminOperator(req);
|
|
1292
1412
|
if(!as) throw new Error('built-in authorization server is not enabled (DALAN_AUTH_MODE=builtin)');
|
|
@@ -1298,7 +1418,11 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1298
1418
|
if(url.pathname==='/connect/reset'&&req.method==='POST') return json(res,200,ops.reset());
|
|
1299
1419
|
if(url.pathname==='/connect/stop'&&req.method==='POST') return json(res,200,ops.stop());
|
|
1300
1420
|
if(url.pathname==='/connect/pending'&&req.method==='GET') return json(res,200,ops.pending());
|
|
1301
|
-
if(url.pathname==='/connect/approve'&&req.method==='POST')
|
|
1421
|
+
if(url.pathname==='/connect/approve'&&req.method==='POST') {
|
|
1422
|
+
const approval=await ops.approve({code:body.code,worker:body.worker,replace:body.replace===true?true:body.replace===undefined?false:body.replace,confirm_redirect:body.confirm_redirect});
|
|
1423
|
+
ensureWorkerRelationship(store.db,approval.worker);
|
|
1424
|
+
return json(res,200,approval);
|
|
1425
|
+
}
|
|
1302
1426
|
if(url.pathname==='/connect/list'&&req.method==='GET') return json(res,200,ops.list());
|
|
1303
1427
|
if(url.pathname==='/connect/revoke'&&req.method==='POST') return json(res,200,ops.revoke({worker:body.worker}));
|
|
1304
1428
|
if(url.pathname==='/connect/signal-token'&&req.method==='POST') return json(res,200,signal.tokenUrl({worker:body.worker,rotate:body.rotate===true}));
|
|
@@ -1327,17 +1451,19 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1327
1451
|
const requestId=id(body.id),result=store.abandon(requestId,{actor:'operator',reason:body.reason===undefined||body.reason===null?'operator_abandon':str(body.reason,'reason',512)});
|
|
1328
1452
|
log({kind:'claim_abandoned',request_id:requestId,epoch:result.abandoned.epoch,actor:'operator'});
|
|
1329
1453
|
runDrain();
|
|
1330
|
-
return json(res,200,result);
|
|
1454
|
+
return json(res,200,{...result,scope:controlScopeText('detach',{ref:`claim:${result.abandoned.claim_id}@${result.abandoned.epoch}`})});
|
|
1331
1455
|
}
|
|
1332
1456
|
if(url.pathname==='/cancel') {
|
|
1333
1457
|
const requestId=id(body.id); adminOwner(req,requestId);
|
|
1334
|
-
|
|
1458
|
+
// Read before the cancel: the scope text depends on whether a worker held the job.
|
|
1459
|
+
const wasClaimed=store.db.prepare("SELECT 1 FROM assignments WHERE request_id=? AND status='claimed'").get(requestId)!==undefined;
|
|
1460
|
+
const result=store.cancel(requestId,body.reason===undefined||body.reason===null?null:str(body.reason,'reason',64),{key:body.command_key,revision:body.expected_revision},req.headers['x-owner-capability']); const waiter=waiters.get(requestId); if(waiter) { waiters.delete(requestId); clearTimeout(waiter.timer); json(waiter.res,200,waitSummary(requestId)); } return json(res,200,{...result,scope:controlScopeText('withdraw_work',{ref:`job:${requestId}`,claimed:wasClaimed})});
|
|
1335
1461
|
}
|
|
1336
1462
|
if(url.pathname==='/cancel-if-queued'&&req.method==='POST') {
|
|
1337
1463
|
const requestId=id(body.id); adminOwner(req,requestId);
|
|
1338
1464
|
const result=store.cancelIfQueued(requestId);
|
|
1339
1465
|
if(result.cancelled) { const waiter=waiters.get(requestId); if(waiter) { waiters.delete(requestId); clearTimeout(waiter.timer); json(waiter.res,200,waitSummary(requestId)); } }
|
|
1340
|
-
return json(res,200,result);
|
|
1466
|
+
return json(res,200,result.cancelled?{...result,scope:controlScopeText('withdraw_work',{ref:`job:${requestId}`,claimed:false})}:result);
|
|
1341
1467
|
}
|
|
1342
1468
|
if(url.pathname==='/break'&&req.method==='POST') {
|
|
1343
1469
|
adminOperator(req);
|
|
@@ -1378,7 +1504,7 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1378
1504
|
if(rejected) log({kind:'submit_rejected',...rejected,status:infrastructure?503:400,reason:e.message.slice(0,300),...(reasons?{verdict,reason_codes:reasons.map(r=>r.code)}:{}),bytes:e.bytes??null,attempt_latency_ms:Date.now()-requestStartedAt,...(e.suggested_scope_paths?{suggested_scope_count:e.suggested_scope_paths.length}:{})});
|
|
1379
1505
|
if(infrastructure&&!rejected) log({kind:'admin_infrastructure_error',route:String(req.url).split('?')[0],code:e.code??null,reason:e.message.slice(0,300)});
|
|
1380
1506
|
const shown=publicErrorText(e,'admin request');
|
|
1381
|
-
json(res,infrastructure?503:400,{error:infrastructure?'admin service unavailable':shown,...(e.destination?{destination:e.destination}:{}),...(infrastructure?{code:e.code??null,reason:shown.slice(0,300)}:{}),...(!infrastructure&&e.suggested_scope_paths?{suggested_scope_paths:e.suggested_scope_paths}:{}),...(reasons?{verdict,reasons,...(e.bytes?{bytes:e.bytes}:{})}:{})});
|
|
1507
|
+
json(res,infrastructure?503:400,{error:infrastructure?'admin service unavailable':shown,...(e.destination?{destination:e.destination}:{}),...(e.stale?{stale:e.stale}:{}),...(infrastructure?{code:e.code??null,reason:shown.slice(0,300)}:{}),...(!infrastructure&&e.suggested_scope_paths?{suggested_scope_paths:e.suggested_scope_paths}:{}),...(reasons?{verdict,reasons,...(e.bytes?{bytes:e.bytes}:{})}:{})});
|
|
1382
1508
|
}
|
|
1383
1509
|
});
|
|
1384
1510
|
|
package/src/status-summary.mjs
CHANGED
|
@@ -41,6 +41,9 @@ export function formatStatusSummary(status, { home, url = null, trial = false, n
|
|
|
41
41
|
const paused = status?.paused === true;
|
|
42
42
|
const lines = [`Bridge: ${paused ? 'running, paused' : 'running'}${url ? ` on ${url}` : ''} (${trial ? 'trial home' : 'home'} ${home})${paused && status.pause_reason ? `. Pause reason: ${status.pause_reason}` : ''}`,
|
|
43
43
|
...(workers.length ? workers.map(w => w.text) : ['Workers: none yet'])];
|
|
44
|
+
// A wake held because its parent stopped is invisible in the queue counts: it left the send queue and waits for the parent.
|
|
45
|
+
const held = Number.isInteger(status?.held_wakes) ? status.held_wakes : 0;
|
|
46
|
+
if (held > 0) lines.push(`${held} held wake${held === 1 ? '' : 's'}: the parent thread stopped, so the wake waits until it runs again (see: ${cli} inbox --all)`);
|
|
44
47
|
const total = workers.reduce((n, w) => n + w.total, 0) || (status?.counts ?? []).reduce((n, c) => n + c.count, 0);
|
|
45
48
|
const next = paused ? `resume handing out jobs: ${cli} resume`
|
|
46
49
|
: workers.some(w => w.queued) ? `send your worker the queued job (to connect a worker first, see ${CONNECT_URL}); list your jobs: ${cli} inbox --all`
|