salvage 2026-11-06: uncommitted work from scratch/darkwing-scratch/r137/wt3 (disk cleanup #824)

This commit is contained in:
mos committed 2026-11-06 10:03:55 -06:00
1 parent 63c82f1c47
commit d28d930c99
31 files changed
+2115 -255

No files matched your search

+41
View File
@@ -106,6 +106,47 @@ as `action.refused` on the task's trail.
addressed to (`request-not-found` otherwise). Returns the request's
`{project,commit,ref}`, which the host bundles for the reviewer.
Row 137 (#1631) adds four ops for a landing on a working repository's
`main` through the same git socket. The decision checks are land-work's,
in `src/landing.mjs` (`readLanding`), which `scripts/land-work/read.mjs`
also calls. Each caller names its branch, `refactor` for land-work and
the task ref for an agent's landing, and the decision's target has to
match it. So a decision raised for one can't land the other. land-work
accepts only a decision the human resolved through the CLI (`human/cli`).
The broker passes `arbiter: true`, which also accepts a `cross-role`
decision its arbiter resolved (REQ-DEC-2). It refuses a decision of class
`gated` with `not-authorized` (REQ-LAND-1): only a role granted
`git.merge.protected` cross-role lands, whoever resolved the decision.
- `{op:'checkLand',cap,args}`: `args` is `{task_ref,decision}`. The caller
must hold its claim and the decision: `git.merge.protected`, raised by
this role in this thread with the task ref as its target, of class
`cross-role` (`not-authorized` otherwise), resolved with its approval
option and not yet used (`decision-consumed` otherwise).
Then `readLanding`'s checks, and the verdict's commit must be the task's
latest push (`ref-moved`). A landing with no subject refuses
`no-subject`, since an agent has no `--subject` to pass. Returns a
ticket with what the host needs: the project, the work ref, the commit,
the verdict and the resolution. It records nothing unless it refuses.
- `{op:'recordLand',ticket,land}`: `land` is `{commit,previous,reviewed,
base,patch_id}` once `main` moved. The checks run again inside the
transaction. It writes the `action.allowed` for `git.merge.protected`
on the task's trail, which spends the decision, and sends the role a
RESULT in the decision's thread. When it refuses, the host moves `main`
back.
- `{op:'landRefused',ticket,args}`: `args` is `{code,detail,notify}`. It
writes `action.refused` with the code on the task's trail and ends the
landing. With `notify` the role gets a RESULT too, since the git socket
had already answered `started`.
- `{op:'landHeld',record}`: `record` is `{business,role,thread}`. True when
the role, in that thread (null for a role run), holds a `cross-role`
merge decision a landing could use. The launcher binds the git socket's land op only
then; `checkLand` still checks everything.
A ticket lives in the broker's memory from `checkLand` until `recordLand`
or `landRefused` ends it, so either may run after the run ended. An
unknown ticket refuses `land-unknown`.
`{op:'close'}`, SIGTERM and SIGINT close the socket and DB and remove the owned
writer lock. Losing the host IPC channel closes with exit 2. Startup or host
protocol failures return a static error code and exit 2, never a raw exception.
+173 -18
View File
@@ -1,5 +1,6 @@
import { randomUUID, randomBytes } from 'node:crypto';
import { loadRequirements } from '../../tasks/src/requirements.mjs';
import { MERGE, LandingRefusal, readLanding } from './landing.mjs';
// Kept closed while S1 lands; its vocabulary is the integration authority.
export const ACTIONS = Object.freeze([
@@ -158,6 +159,8 @@ export class Broker {
#sessions = new Map();
#runs = new Map();
#ended = new Set();
// Row 137 (#1631): landings checkLand let start, by ticket, until recordLand or landRefused ends them.
#landings = new Map();
#secretCheck;
#credentialStatus;
#requirements;
@@ -648,8 +651,13 @@ export class Broker {
const tasks = rest.slice(0, limit);
return { tasks, total: matched.length, next: rest.length > limit ? tasks.at(-1).task_ref : null };
}
#checkAuthority(s, action, { decision = null, target = null } = {}) {
#checkAuthority(s, action, context = {}) {
this.#agent(s);
return this.#authorityFor(s, action, context);
}
// #checkAuthority less the holder check. A landing's record and refusal use it alone: the run
// that asked held its claim at checkLand, and may have ended while the gate ran (row 137).
#authorityFor(s, action, { decision = null, target = null } = {}) {
if (
action === 'role.launch' &&
this.#store.get('SELECT state FROM launch_state WHERE business=?', s.business)?.state === 'revoked'
@@ -660,12 +668,7 @@ export class Broker {
if (!decision) fail('decision-required');
const d = this.#decision(s, decision),
r = this.#closed(d.id);
const evidence = this.#store.get(
"SELECT body FROM events WHERE business=? AND json_extract(body,'$.decision')=? AND json_extract(body,'$.operation')='decision.raise' AND kind='action.allowed' ORDER BY seq LIMIT 1",
s.business,
d.id,
);
const context = evidence ? JSON.parse(evidence.body) : null;
const context = this.#raised(s.business, d.id);
// Row 136 (#1630): bound to the role instance and its thread, not the run, so an approval
// outlives a restart. Single use is #consumeAuthority's.
if (
@@ -683,20 +686,29 @@ export class Broker {
fail('decision-mismatch');
return { class: cls, decision: d.id };
}
// The raise's context: its target and approval option, from the decision.raise action.allowed.
#raised(business, decision) {
const evidence = this.#store.get(
"SELECT body FROM events WHERE business=? AND json_extract(body,'$.decision')=? AND json_extract(body,'$.operation')='decision.raise' AND kind='action.allowed' ORDER BY seq LIMIT 1",
business,
decision,
);
return evidence ? JSON.parse(evidence.body) : null;
}
// Whether an executor already used the decision. decision.raise records context, not permission
// consumed by an executor.
#spent(business, decision) {
return !!this.#store.get(
"SELECT 1 FROM events WHERE business=? AND kind='action.allowed' AND json_extract(body,'$.decision')=? AND json_extract(body,'$.operation') IS NOT 'decision.raise' LIMIT 1",
business,
decision,
);
}
// Caller owns the transaction: authority, consumption and effect commit together.
// detail adds to the action.allowed body: a push's commit (row 93).
#consumeAuthority(s, action, context = {}, detail = {}) {
const result = this.#checkAuthority(s, action, context);
// decision.raise records context, not permission consumed by an executor.
if (
result.decision &&
this.#store.get(
"SELECT 1 FROM events WHERE business=? AND kind='action.allowed' AND json_extract(body,'$.decision')=? AND json_extract(body,'$.operation') IS NOT 'decision.raise' LIMIT 1",
s.business,
result.decision,
)
)
fail('decision-consumed');
if (result.decision && this.#spent(s.business, result.decision)) fail('decision-consumed');
this.#event(
s,
'action.allowed',
@@ -774,6 +786,149 @@ export class Broker {
return { task_ref, commit };
});
}
// Row 137 (#1631): the bus host's git socket lands a task on its working repository's main.
// checkLand runs before the host touches the repository. The run must hold its claim and the
// decision: git.merge.protected, raised by this role in this thread with the task ref as its
// target, resolved with its approval option and not yet used. Then land-work's checks
// (landing.mjs, into 'main'), and the verdict's commit must be the task's latest push, whose
// project the landing uses. A refusal is a code; nothing is recorded unless it refuses.
// The ticket names the landing to recordLand and landRefused, which may run after the run ended.
checkLand(cap, args) {
const s = this.#session(cap);
return this.#store.transaction(() => {
keys(args, ['task_ref', 'decision'], ['task_ref', 'decision']);
if (!taskRef(args.task_ref) || !id(args.decision)) fail('invalid-request');
const { task_ref, decision } = args;
const { class: cls } = this.#checkAuthority(s, MERGE, { decision, target: task_ref });
const facts = this.#landFacts(s, task_ref, decision, cls);
const ticket = randomUUID();
this.#landings.set(ticket, { s, task_ref, decision });
return { ticket, ...facts };
});
}
// What a landing needs, checked again at recordLand. PRD 1.5 REQ-LAND-1: only a role granted
// git.merge.protected cross-role lands, so a decision of class gated refuses, whoever resolved
// it. A cross-role one may be resolved by the human through the CLI or by its arbiter
// (REQ-DEC-2, landing.mjs `arbiter`). The decision's own project, when it names one, must be
// the push's.
#landFacts(s, task_ref, decision, cls) {
if (cls === 'gated') fail('not-authorized');
if (this.#spent(s.business, decision)) fail('decision-consumed');
let l;
try {
l = readLanding(this.#store, this.#business(s.business), decision, { into: 'main', arbiter: true });
} catch (e) {
if (e instanceof LandingRefusal) fail(e.reason);
throw e;
}
if (l.task_ref !== task_ref) fail('work-ref');
const push = this.#latestPush(s.business, task_ref);
if (!push || push.commit !== l.commit) fail('ref-moved');
if (l.project && l.project !== push.project) fail('work-ref');
// land-work refuses a landing with no subject; an agent has no --subject to pass.
if (!l.subject) fail('no-subject');
return {
task_ref,
work_ref: l.work_ref,
decision,
project: push.project,
ref: push.ref,
commit: l.commit,
verdict: l.verdict,
subject: l.subject,
choice: l.choice,
by: l.by,
resolved_at: l.resolved_at,
};
}
#landing(ticket) {
return (typeof ticket === 'string' && this.#landings.get(ticket)) || fail('land-unknown');
}
// Records a landing the git socket made (working.mjs finishLand) as the action.allowed for
// git.merge.protected that spends the decision, on the task's trail, and tells the role. The
// checks run again inside the transaction; a refusal here moves main back. Trusted host only.
recordLand(ticket, land) {
const t = this.#landing(ticket);
const { s, task_ref, decision } = t;
const done = this.#store.transaction(() => {
const all = ['commit', 'previous', 'reviewed', 'base', 'patch_id'];
keys(land, all, all);
if (!all.every((k) => oid(land[k]))) fail('invalid-request');
const result = this.#authorityFor(s, MERGE, { decision, target: task_ref });
const facts = this.#landFacts(s, task_ref, decision, result.class);
if (facts.commit !== land.reviewed) fail('ref-moved');
const { commit, previous, reviewed, base, patch_id } = land;
this.#event(
s,
'action.allowed',
{ project: facts.project, ref: 'refs/heads/main', commit, previous, reviewed, base, patch_id, verdict: facts.verdict, action: MERGE, ...result, target: task_ref },
task_ref,
);
this.#landMessage(s, decision, `Landed ${task_ref} on ${facts.project} main under decision ${decision}: main moved from ${previous} to ${commit}, the squash of reviewed ${reviewed}.`);
return { task_ref, commit };
});
this.#landings.delete(ticket);
return done;
}
// Ends a landing that didn't land: action.refused with the code on the task's trail, as a
// refusal of the run's own request is filed. With notify, the role is told too: the git socket
// had already answered "started" and the run has no other way to learn it. Trusted host only.
landRefused(ticket, { code, detail = null, notify = false } = {}) {
const t = this.#landing(ticket);
if (!/^[a-z-]{1,64}$/.test(code ?? '') || (detail !== null && !text(detail, 1000)) || typeof notify !== 'boolean')
fail('invalid-request');
this.#secretCheck({ detail });
this.#store.transaction(() => {
this.#event(t.s, 'action.refused', { code }, t.task_ref);
if (notify)
this.#landMessage(t.s, t.decision, `Landing of ${t.task_ref} under decision ${t.decision} refused: ${code}.${detail === null ? '' : `\n${detail}`}`);
});
this.#landings.delete(ticket);
return code;
}
// The outcome as a RESULT from the bus, as #notice sends: the runner takes a turn on it and sends
// no automatic reply. It goes to the role in the thread the decision was raised in.
#landMessage(s, decision, body) {
const mid = randomUUID();
this.#store.run(
'INSERT INTO messages(id,at,business,from_role,from_run,to_role,class,in_reply_to,decision,corrects,body) VALUES(?,?,?,?,?,?,?,?,?,?,?)',
mid,
this.#now(),
s.business,
NOTICE_ROLE,
NOTICE_RUN,
s.role,
'RESULT',
null,
decision,
null,
body,
);
this.#route(s.business, mid, s.role, s.thread);
}
// Trusted launcher API: whether the role, in the thread (null for a role run), holds a merge
// decision a landing could use: cross-role, raised there with a task ref as its target, resolved
// with its approval option, not yet used. The launcher binds the git socket's land op only then;
// checkLand still checks everything.
landHeld(record) {
keys(record, ['business', 'role', 'thread'], ['business', 'role', 'thread']);
this.#business(identifier(record.business));
identifier(record.role);
if (record.thread !== null) identifier(record.thread);
for (const d of this.#store.all(
'SELECT * FROM decisions WHERE business=? AND action=? AND raised_by_role=? ORDER BY seq',
record.business,
MERGE,
record.role,
)) {
if (d.class !== 'cross-role' || this.#raisedThread(d) !== record.thread) continue;
const context = this.#raised(d.business, d.id);
const r = this.#closed(d.id);
if (context && taskRef(context.target) && r?.op === 'resolved' && r.choice === context.approvalChoice && !this.#spent(d.business, d.id))
return true;
}
return false;
}
// Row 93: what the git socket's fetch for a reviewer may send, from the review.requested event the
// reviewer cites. The caller must hold review.verdict and be the request's reviewer. Trusted host only.
reviewFetch(cap, { task_ref, request } = {}) {
@@ -804,7 +959,7 @@ export class Broker {
return this.#store.transaction(() => {
this.#agent(s);
if (['human.input', 'launch.revoked', 'launch.restored', ...REVIEW_KINDS].includes(kind)) fail('reserved-event');
if (kind === 'action.allowed' && body?.action === 'git.push.working') fail('reserved-event');
if (kind === 'action.allowed' && ['git.push.working', MERGE].includes(body?.action)) fail('reserved-event');
return this.#event(s, kind, body, subject);
});
}
+156
View File
@@ -0,0 +1,156 @@
// The checks a landing makes on its merge decision and the task's review
// (row 137, #1631). Two callers: scripts/land-work/read.mjs, which lands on
// canonical refactor from a read-only copy of the bus, and the broker's
// checkLand and recordLand, which land on a working repository's main.
// Moved here from read.mjs (row 116, #1610); every query is a SELECT.
//
// readLanding(q, business, id, { into, arbiter }) runs over q.get(sql, ...params)
// and q.all(sql, ...params). It throws a LandingRefusal with land-work's reason
// codes, or returns what the landing needs.
//
// `into` is the branch the caller lands on, and the raise's target must
// match it: 'refactor' for land-work, the task ref for a working repository's
// main. So a decision raised for one can't be used for the other, and a
// decision raised by an agent for its task never names refactor.
//
// Without `arbiter`, the human must have resolved the decision through the
// CLI: land-work leaves it out, because canonical refactor stays the lead's
// landing (PRD 1.5). The broker passes `arbiter: true` (REQ-DEC-2), which
// also accepts a cross-role decision routed to an arbiter and resolved by it.
// The broker lets only a run of the route_to role resolve one, and a hard wait
// is never cross-role, so no hard wait passes here (row 139 routes them to the
// human).
export const MERGE = 'git.merge.protected';
const WORK_REF = /^work\/vikunja-([1-9][0-9]*)-([1-9][0-9]*)$/;
const ANY_WORK_REF = /\bwork\/[A-Za-z0-9._/-]*[A-Za-z0-9_]/g;
const OID = /^[0-9a-f]{40}([0-9a-f]{24})?$/;
export class LandingRefusal extends Error {
constructor(reason, detail) {
super(detail);
this.reason = reason;
}
}
const refuse = (reason, detail) => {
throw new LandingRefusal(reason, detail);
};
const json = (text) => {
try {
return JSON.parse(text);
} catch {
return null;
}
};
// The queries. Each takes the business so one bus can't answer for another.
const queries = {
decision: (q, b, id) => q.get('SELECT * FROM decisions WHERE business = ? AND id = ?', b, id),
// The broker files a raise under its task ref when it has one, else under the decision id
// (decision.raise), so the raise is found by the decision its body names.
raise: (q, b, id) =>
q.all(
`SELECT * FROM events WHERE business = ? AND kind = 'action.allowed'
AND json_extract(body, '$.operation') = 'decision.raise' AND json_extract(body, '$.decision') = ?
ORDER BY seq`,
b,
id,
),
closes: (q, id) =>
q.all(`SELECT * FROM decision_events WHERE decision = ? AND op IN ('resolved','withdrawn','expired') ORDER BY seq`, id),
answer: (q, b, id) =>
q.all(
`SELECT * FROM events WHERE business = ? AND kind = 'human.input' AND subject = ?
AND json_extract(body, '$.kind') = 'answer' AND json_extract(body, '$.decision') = ?
AND json_extract(body, '$.op') = 'resolved'
ORDER BY seq`,
b,
id,
id,
),
later: (q, b, d) =>
q.all(
`SELECT * FROM decisions WHERE business = ? AND id <> ?
AND (supersedes = ? OR (seq > ? AND action = ?)) ORDER BY seq`,
b,
d.id,
d.id,
d.seq,
MERGE,
),
verdict: (q, b, task) =>
q.get(`SELECT * FROM events WHERE business = ? AND kind = 'review.verdict' AND subject = ? ORDER BY seq DESC LIMIT 1`, b, task),
};
// The task ref a work ref names, or null.
export function workTask(workRef) {
const m = WORK_REF.exec(workRef ?? '');
return m ? `vikunja:${m[1]}/${m[2]}` : null;
}
export function readLanding(q, business, id, { into, arbiter = false }) {
const b = business.id;
const d = queries.decision(q, b, id);
const raises = queries.raise(q, b, id);
if (!d || raises.length !== 1) refuse('decision-not-found', `no decision ${id} with one raise in business ${b}`);
const raise = json(raises[0].body) ?? {};
if (d.action !== MERGE || raise.action !== MERGE) refuse('not-a-merge', `action ${d.action}`);
const closes = queries.closes(q, id);
if (closes.length !== 1 || closes[0].op !== 'resolved')
refuse('not-resolved', closes.length ? closes.map((r) => r.op).join(',') : 'open');
const res = closes[0];
const answers = queries.answer(q, b, id);
const answer = answers.length === 1 ? answers[0] : null;
const human =
res.by === business.human &&
res.via === 'cli' &&
answer &&
answer.actor_role === null &&
answer.actor_run === null &&
json(answer.body)?.choice === res.choice;
const arbitrated = arbiter && d.class === 'cross-role' && d.route_to !== 'human' && res.via === 'broker' && !answers.length;
if (!human && !arbitrated)
refuse('not-human', `resolved by ${res.by} via ${res.via}, ${answers.length} human answer(s)`);
const options = json(d.options) ?? [];
const merge = options.find((o) => o?.key === raise.approvalChoice);
if (!raise.approvalChoice || !merge) refuse('not-merge-option', 'the raise names no approval option');
if (res.choice !== raise.approvalChoice)
refuse('not-merge-option', `chose ${res.choice}, the merge option is ${raise.approvalChoice}`);
// The work ref comes from the question: decisions don't carry it.
const named = [...new Set(d.question.match(ANY_WORK_REF) ?? [])];
const task = named.length === 1 ? workTask(named[0]) : null;
if (!task) refuse('work-ref', `the question names ${named.join(', ') || 'no work ref'}`);
const workRef = named[0];
for (const ref of [d.task_ref, raise.task_ref])
if (ref != null && ref !== task) refuse('work-ref', `the decision cites ${ref}, the question ${workRef}`);
// The target is the raise's: refactor for land-work, the task itself for a working repository.
const want = into === 'refactor' ? 'refactor' : into === 'main' ? task : null;
if (want === null || raise.target !== want)
refuse('target-branch', `the raise targets ${raise.target}, landing on ${into} needs ${want}`);
const later = queries.later(q, b, d).filter(
(r) => r.supersedes === id || r.task_ref === task || (r.question.match(ANY_WORK_REF) ?? []).includes(workRef),
);
if (later.length) refuse('superseded', `later decision ${later.map((r) => r.id).join(', ')} on ${workRef}`);
const v = queries.verdict(q, b, task);
if (!v) refuse('no-verdict', `no review.verdict for ${task}`);
const vb = json(v.body) ?? {};
if (vb.verdict !== 'approve' || vb.task_ref !== task || !OID.test(vb.commit ?? ''))
refuse('not-approved', `latest verdict ${v.id} is ${vb.verdict} on ${vb.commit}`);
return {
task_ref: task,
work_ref: workRef,
commit: vb.commit,
verdict: v.id,
project: d.project ?? '',
choice: res.choice,
by: res.by,
resolved_at: res.at,
subject: String(merge.text ?? '').split('\n')[0].trim(),
};
}
+9
View File
@@ -11,6 +11,10 @@ const LAUNCH_OPS = new Set([
'checkPush',
'recordPush',
'reviewFetch',
'checkLand',
'recordLand',
'landRefused',
'landHeld',
'threadsState',
'threadIdle',
]);
@@ -23,6 +27,11 @@ function launchOp(m) {
if (m.op === 'checkPush') return runtime.checkPush(m.cap, m.task_ref);
if (m.op === 'recordPush') return runtime.recordPush(m.cap, m.push);
if (m.op === 'reviewFetch') return runtime.reviewFetch(m.cap, m.args);
// Row 137 (#1631): the git socket's land op, and the launcher's question whether to bind it.
if (m.op === 'checkLand') return runtime.checkLand(m.cap, m.args);
if (m.op === 'recordLand') return runtime.recordLand(m.ticket, m.land);
if (m.op === 'landRefused') return runtime.landRefused(m.ticket, m.args);
if (m.op === 'landHeld') return runtime.landHeld(m.record);
// Row 121 (#1615): the launcher's view of the business's threads, and its idle release.
if (m.op === 'threadsState') return runtime.threadsState(m.business);
if (m.op === 'threadIdle') return runtime.threadIdle(m.record);
+7
View File
@@ -141,6 +141,9 @@ export async function startBroker({
// and recorded once the ref moved; a reviewer's fetch is checked against its review.requested.
const checkPush = (cap, task_ref) => refusing(cap, () => broker.checkPush(cap, task_ref), task_ref);
const reviewFetch = (cap, args) => refusing(cap, () => broker.reviewFetch(cap, args), args?.task_ref);
// Row 137 (#1631): the git socket's land op. checkLand's refusal is the run's, like checkPush's.
// A landing then ends in recordLand or landRefused under its ticket, which outlive the run's cap.
const checkLand = (cap, args) => refusing(cap, () => broker.checkLand(cap, args), args?.task_ref);
// Metadata only (service, date, state); the token stays in Credentials.
function credentialStatus(business, role) {
return credentials
@@ -161,6 +164,10 @@ export async function startBroker({
checkPush,
recordPush: (cap, push) => refusing(cap, () => broker.recordPush(cap, push), push?.task_ref),
reviewFetch,
checkLand,
recordLand: (ticket, land) => broker.recordLand(ticket, land),
landRefused: (ticket, args) => broker.landRefused(ticket, args),
landHeld: (record) => broker.landHeld(record),
refuse: (cap, code, subject) => broker.refuse(cap, code, subject),
credentialStatus,
launches: bound,
+343
View File
@@ -0,0 +1,343 @@
// Row 137 (#1631): the broker's side of an agent's landing. The git socket asks
// checkLand before it touches the working repository, then ends the landing
// with recordLand, which spends the merge decision, or landRefused. landHeld is
// the launcher's question whether to offer land_work at all.
//
// The lander is merge-gate, granted git.merge.protected cross-role (PRD 1.5
// REQ-LAND-1), and its raise goes to the arbiter pm (REQ-DEC-2). The coder
// pushes; its own merge raise is gated, and gated never lands.
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Store } from '../src/store.mjs';
import { Broker } from '../src/broker.mjs';
import { readLanding } from '../src/landing.mjs';
import { fixture } from './spec-fixtures.mjs';
const TASK = 'vikunja:1/2';
const MERGE = 'git.merge.protected';
const A = 'a'.repeat(40);
const B = 'b'.repeat(40);
const C = 'c'.repeat(40);
const roles = {
pm: { authority: { withinRole: ['message.send'], crossRole: [] } },
coder: { authority: { withinRole: ['git.push.working', 'review.request', 'message.send'], crossRole: [] } },
reviewer: { authority: { withinRole: ['review.verdict', 'message.send'], crossRole: [] } },
'merge-gate': { authority: { withinRole: [], crossRole: [MERGE] } },
};
const demo = (arbiters = { technical: 'pm', delivery: 'pm' }) => ({
id: 'demo',
human: 'jason',
arbiters,
projects: { stack: { root: '/nonexistent' } },
roles,
});
const options = [
{ key: 'yes', text: 'Land the parser fix\nIt is reviewed.' },
{ key: 'no', text: 'Not yet' },
];
const merge = { action: MERGE, target: TASK, question: 'Squash-merge work/vikunja-1-2 into main?', options, recommendation: 'yes', blocking: false };
function setup(t, { arbiters } = {}) {
const root = mkdtempSync(join(tmpdir(), 'bus-land-'));
const store = new Store(root);
const businesses = { demo: demo(arbiters) };
const b = new Broker({ store, businesses });
t.after(() => {
store.close();
rmSync(root, { recursive: true, force: true });
});
const caps = { human: b.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true }) };
for (const role of Object.keys(businesses.demo.roles)) {
caps[role] = b.bindLaunch({ business: 'demo', role, run: `${role}-run`, harness: 'pi' });
b.request(caps[role], { verb: 'role.claim', args: {} });
}
const call = (who, verb, args = {}) => b.request(caps[who], { verb, args });
const push = (commit, previous = null) => {
b.checkPush(caps.coder, TASK);
return b.recordPush(caps.coder, { task_ref: TASK, project: 'stack', branch: 'feat', ref: 'work/vikunja-1-2', commit, previous });
};
const approve = (commit) => {
const r = call('coder', 'review.request', { task_ref: TASK, commit, to: 'reviewer' });
return call('reviewer', 'review.verdict', { task_ref: TASK, request: r.request, verdict: 'approve', body: 'good' });
};
const raise = (who = 'merge-gate', extra = {}) => call(who, 'decision.raise', { ...merge, ...extra });
// The arbiter resolves by default; a decision routed to the human needs who = 'human'.
const resolve = (d, choice = 'yes', who = 'pm') => call(who, 'decision.resolve', { id: d.id, choice });
// A pushed, approved task with a merge decision its arbiter approved.
const ready = () => {
push(A);
const v = approve(A);
const d = raise();
resolve(d);
return { d, v };
};
const land = { commit: B, previous: C, reviewed: A, base: C, patch_id: 'd'.repeat(40) };
const events = (kind) => store.all('SELECT * FROM events WHERE kind=? ORDER BY seq', kind).map((e) => ({ ...e, body: JSON.parse(e.body) }));
const merges = () => events('action.allowed').filter((e) => e.body.action === MERGE && e.body.operation !== 'decision.raise');
// The landing's RESULTs; a #notice is a RESULT too.
const results = () =>
store.all("SELECT * FROM messages WHERE class='RESULT' AND (body LIKE 'Landed %' OR body LIKE 'Landing of %') ORDER BY at, id").map((m) => ({ ...m }));
const held = (role = 'merge-gate', thread = null) => b.landHeld({ business: 'demo', role, thread });
const check = (args) => b.checkLand(caps['merge-gate'], args);
const routed = (d) => ({ ...store.get('SELECT class, route_to FROM decisions WHERE id=?', d.id) });
return { b, store, businesses, caps, call, push, approve, raise, resolve, ready, land, events, merges, results, held, check, routed };
}
test('REQ-DEC-2: a merge-gate raise its arbiter resolved lands through the host op: checkLand answers the facts and a ticket, records nothing, and recordLand spends the decision once', (t) => {
const w = setup(t);
const { d, v } = w.ready();
assert.deepEqual(w.routed(d), { class: 'cross-role', route_to: 'pm' });
assert.deepEqual({ ...w.store.get('SELECT "by", via FROM decision_events WHERE decision=? AND op=\'resolved\'', d.id) }, { by: 'pm-run', via: 'broker' });
// land-work's copy of the check, without `arbiter`, still wants the human.
assert.throws(() => readLanding(w.store, w.businesses.demo, d.id, { into: 'main' }), { reason: 'not-human' });
const r = w.check({ task_ref: TASK, decision: d.id });
const { ticket, resolved_at, ...facts } = r;
assert.match(ticket, /^[0-9a-f-]{36}$/);
assert.match(resolved_at, /^\d{4}-/);
assert.deepEqual(facts, {
task_ref: TASK,
work_ref: 'work/vikunja-1-2',
decision: d.id,
project: 'stack',
ref: 'work/vikunja-1-2',
commit: A,
verdict: v.verdict,
subject: 'Land the parser fix',
choice: 'yes',
by: 'pm-run',
});
assert.deepEqual(w.merges(), []);
assert.deepEqual(w.events('action.refused'), []);
assert.deepEqual(w.b.recordLand(ticket, w.land), { task_ref: TASK, commit: B });
const [e] = w.merges();
assert.equal(e.subject, TASK);
assert.equal(e.actor_role, 'merge-gate');
assert.deepEqual(e.body, {
project: 'stack',
ref: 'refs/heads/main',
commit: B,
previous: C,
reviewed: A,
base: C,
patch_id: 'd'.repeat(40),
verdict: v.verdict,
action: MERGE,
class: 'cross-role',
decision: d.id,
target: TASK,
});
const [m] = w.results();
assert.equal(m.to_role, 'merge-gate');
assert.equal(m.decision, d.id);
assert.match(m.body, new RegExp(`^Landed ${TASK} on stack main under decision ${d.id}: main moved from ${C} to ${B}`));
// Spent: a second landing, and the old ticket, refuse.
assert.throws(() => w.check({ task_ref: TASK, decision: d.id }), /decision-consumed/);
assert.throws(() => w.b.recordLand(ticket, w.land), /land-unknown/);
assert.equal(w.held(), false);
});
test('checkLand refuses on the decision and the review', (t) => {
const w = setup(t);
const { check } = w;
assert.throws(() => check({ task_ref: TASK }), /invalid-request/);
assert.throws(() => check({ task_ref: 'gitea:1', decision: 'x' }), /invalid-request/);
assert.throws(() => check({ task_ref: TASK, decision: 'x', extra: 1 }), /invalid-request/);
// No decision yet, then one that isn't resolved.
assert.throws(() => check({ task_ref: TASK, decision: 'no-such' }), /decision-not-found/);
w.push(A);
const open = w.raise();
assert.throws(() => check({ task_ref: TASK, decision: open.id }), /decision-not-approved/);
w.resolve(open, 'no');
assert.throws(() => check({ task_ref: TASK, decision: open.id }), /decision-not-approved/);
// Approved, but by another role's raise, or for another target. pm's raise is gated and
// uncited, so it goes to the human.
const pmRaise = w.raise('pm');
w.resolve(pmRaise, 'yes', 'human');
assert.throws(() => check({ task_ref: TASK, decision: pmRaise.id }), /decision-mismatch/);
const other = w.raise('merge-gate', { target: 'vikunja:1/3' });
w.resolve(other);
assert.throws(() => check({ task_ref: TASK, decision: other.id }), /decision-mismatch/);
// Approved for this task, but nothing reviewed it yet.
const d = w.raise();
w.resolve(d);
assert.throws(() => check({ task_ref: TASK, decision: d.id }), /no-verdict/);
// The reviewer approved A, then the coder pushed B.
w.approve(A);
w.push(B, A);
assert.throws(() => check({ task_ref: TASK, decision: d.id }), /ref-moved/);
assert.deepEqual(w.merges(), []);
});
// PRD 1.5 REQ-LAND-1. The coder has no cross-role grant, so its merge raise is gated: cited, it
// goes to the arbiter (row 139); uncited, to the human. Approved either way, it never lands.
test('REQ-LAND-1: a gated merge decision refuses not-authorized, cited and approved by the arbiter or uncited and approved by the human', async (t) => {
const f = await fixture(t, { roles, arbiters: { technical: 'pm', delivery: 'pm' } });
const pm = f.agent('pm');
f.broker.checkPush(f.coder, TASK);
f.broker.recordPush(f.coder, { task_ref: TASK, project: 'stack', branch: 'feat', ref: 'work/vikunja-1-2', commit: A, previous: null });
const r = f.call(f.coder, 'review.request', { task_ref: TASK, commit: A, to: 'reviewer' });
f.call(f.reviewer, 'review.verdict', { task_ref: TASK, request: r.request, verdict: 'approve', body: 'good' });
const d = await f.call(f.coder, 'decision.raise', { ...merge, project: 'stack', spec_path: 'spec/north-star.md', spec_commit: f.commit });
assert.deepEqual({ ...f.store.get('SELECT class, route_to FROM decisions WHERE id=?', d.id) }, { class: 'gated', route_to: 'pm' });
f.call(pm, 'decision.resolve', { id: d.id, choice: 'yes' });
assert.throws(() => f.broker.checkLand(f.coder, { task_ref: TASK, decision: d.id }), /not-authorized/);
// The shared check refuses it too: its arbiter path takes only a cross-role decision.
assert.throws(() => readLanding(f.store, f.business, d.id, { into: 'main', arbiter: true }), { reason: 'not-human' });
assert.equal(f.broker.landHeld({ business: 'demo', role: 'coder', thread: null }), false);
const w = setup(t);
w.push(A);
w.approve(A);
const human = w.raise('coder');
assert.deepEqual(w.routed(human), { class: 'gated', route_to: 'human' });
w.resolve(human, 'yes', 'human');
assert.throws(() => w.b.checkLand(w.caps.coder, { task_ref: TASK, decision: human.id }), /not-authorized/);
assert.deepEqual([...w.merges(), ...w.events('action.refused')], []);
});
test('a cross-role merge that routes to the human, because merge-gate is its own arbiter, lands on the human\'s CLI answer', (t) => {
const w = setup(t, { arbiters: { technical: 'merge-gate', delivery: 'merge-gate' } });
w.push(A);
w.approve(A);
const d = w.raise();
assert.deepEqual(w.routed(d), { class: 'cross-role', route_to: 'human' });
assert.throws(() => w.resolve(d), /human-required/);
w.resolve(d, 'yes', 'human');
const { ticket, by } = w.check({ task_ref: TASK, decision: d.id });
assert.equal(by, 'jason');
w.b.recordLand(ticket, w.land);
assert.equal(w.merges()[0].body.class, 'cross-role');
});
test('a merge option with no first line refuses no-subject, as land-work does', (t) => {
const w = setup(t);
w.push(A);
w.approve(A);
const d = w.raise('merge-gate', {
options: [
{ key: 'yes', text: '\nLand it' },
{ key: 'no', text: 'Not yet' },
],
});
w.resolve(d);
assert.throws(() => w.check({ task_ref: TASK, decision: d.id }), /no-subject/);
});
// The codes readLanding gives once #checkAuthority has passed, on the 'main'
// side. scripts/test-land-work.sh runs every code on the 'refactor' side.
// not-human can't reach checkLand: a gated decision refuses not-authorized
// first, and the broker resolves a cross-role one the two ways readLanding
// takes with `arbiter`. The REQ-LAND-1 test calls readLanding for it.
test("checkLand refuses with land-work's codes past the authority check, and a decision raised for refactor never lands", (t) => {
const w = setup(t);
const check = (d) => () => w.check({ task_ref: TASK, decision: d.id });
w.push(A);
w.approve(A);
const approved = (extra) => {
const d = w.raise('merge-gate', extra);
w.resolve(d);
return d;
};
assert.throws(check(approved({ question: 'Squash-merge work/vikunja-1-2 and work/vikunja-1-3 into main?' })), /work-ref/);
assert.throws(check(approved({ question: 'Squash-merge work/vikunja-1-2 into main?', task_ref: 'vikunja:1/3' })), /work-ref/);
// The raise targets this task, but the question names another.
assert.throws(check(approved({ question: 'Squash-merge work/vikunja-1-3 into main?' })), /target-branch/);
// land-work's kind of decision: the authority check wants the task as the target.
assert.throws(check(approved({ target: 'refactor' })), /decision-mismatch/);
// A later merge decision on the same work ref supersedes an approved one.
const first = approved();
w.raise();
assert.throws(check(first), /superseded/);
// A later verdict asks for changes on the same commit.
const v = setup(t);
v.push(A);
v.approve(A);
const d = v.raise();
v.resolve(d);
const r = v.call('coder', 'review.request', { task_ref: TASK, commit: A, to: 'reviewer' });
v.call('reviewer', 'review.verdict', { task_ref: TASK, request: r.request, verdict: 'changes', body: 'one more thing' });
assert.throws(() => v.check({ task_ref: TASK, decision: d.id }), /not-approved/);
assert.deepEqual([...w.merges(), ...v.merges()], []);
});
test('a ticket outlives the run that asked, and recordLand checks the task again', (t) => {
const w = setup(t);
const { d } = w.ready();
const { ticket } = w.check({ task_ref: TASK, decision: d.id });
// A bad record refuses and keeps the ticket.
assert.throws(() => w.b.recordLand(ticket, { ...w.land, commit: 'x' }), /invalid-request/);
const { patch_id, ...short } = w.land;
assert.throws(() => w.b.recordLand(ticket, short), /invalid-request/);
assert.throws(() => w.b.recordLand(ticket, { ...w.land, reviewed: C }), /ref-moved/);
// The run ends while the gate runs; the landing is still recorded as merge-gate's.
w.b.endLaunch({ business: 'demo', run: 'merge-gate-run', reason: 'exited' });
assert.deepEqual(w.b.recordLand(ticket, w.land), { task_ref: TASK, commit: B });
assert.equal(w.merges()[0].actor_role, 'merge-gate');
assert.throws(() => w.b.recordLand('no-such-ticket', w.land), /land-unknown/);
assert.throws(() => w.b.landRefused(ticket, { code: 'gate-failed' }), /land-unknown/);
});
test('landRefused files the code on the task, tells the role only with notify, and ends the ticket', (t) => {
const w = setup(t);
const { d } = w.ready();
const first = w.check({ task_ref: TASK, decision: d.id });
assert.throws(() => w.b.landRefused(first.ticket, { code: 'Not A Code' }), /invalid-request/);
assert.throws(() => w.b.landRefused(first.ticket, { code: 'x', detail: '' }), /invalid-request/);
assert.throws(() => w.b.landRefused(first.ticket, { code: 'x', notify: 'yes' }), /invalid-request/);
assert.equal(w.b.landRefused(first.ticket, { code: 'unknown-project' }), 'unknown-project');
assert.deepEqual(w.results(), []);
const second = w.check({ task_ref: TASK, decision: d.id });
w.b.landRefused(second.ticket, { code: 'gate-failed', detail: 'pkg-bus failed, see x.log', notify: true });
const [m] = w.results();
assert.equal(m.to_role, 'merge-gate');
assert.equal(m.body, `Landing of ${TASK} under decision ${d.id} refused: gate-failed.\npkg-bus failed, see x.log`);
assert.deepEqual(
w.events('action.refused').map((e) => [e.subject, e.actor_role, e.body.code]),
[
[TASK, 'merge-gate', 'unknown-project'],
[TASK, 'merge-gate', 'gate-failed'],
],
);
// A refusal spends nothing: the decision still lands.
assert.equal(w.held(), true);
const third = w.check({ task_ref: TASK, decision: d.id });
w.b.recordLand(third.ticket, w.land);
assert.throws(() => w.b.landRefused(second.ticket, { code: 'x' }), /land-unknown/);
});
test('landHeld is true only for an approved, unspent cross-role merge decision this role raised for a task in this thread', (t) => {
const w = setup(t);
assert.equal(w.held(), false);
w.push(A);
const d = w.raise();
assert.equal(w.held(), false, 'open');
w.resolve(d, 'no');
assert.equal(w.held(), false, 'declined');
const notTask = w.raise('merge-gate', { target: 'main' });
w.resolve(notTask);
assert.equal(w.held(), false, 'a target that is not a task ref');
const gated = w.raise('coder');
w.resolve(gated, 'yes', 'human');
assert.equal(w.held('coder'), false, 'gated');
const ok = w.raise();
w.resolve(ok);
assert.equal(w.held(), true);
assert.equal(w.held('pm'), false, 'another role');
assert.equal(w.held('merge-gate', 'thread-1'), false, 'another thread');
assert.throws(() => w.b.landHeld({ business: 'demo', role: 'merge-gate' }), /invalid-request/);
assert.throws(() => w.b.landHeld({ business: 'nope', role: 'merge-gate', thread: null }));
});
test('no run may write the action.allowed for git.merge.protected itself', (t) => {
const w = setup(t);
assert.throws(
() => w.b.recordEvent(w.caps.coder, { kind: 'action.allowed', body: { action: MERGE, target: TASK, commit: B }, subject: TASK }),
/reserved-event/,
);
});
@@ -14,8 +14,11 @@ test('Broker keeps the existing sandbox client import closure: no new imports or
assert.deepEqual([...source.matchAll(/^import .*;$/gm)].map(m => m[0]), [
"import { randomUUID, randomBytes } from 'node:crypto';",
"import { loadRequirements } from '../../tasks/src/requirements.mjs';",
// Row 137 (#1631): land-work's checks, in RUNNER_FILES beside the broker. They import nothing.
"import { MERGE, LandingRefusal, readLanding } from './landing.mjs';",
]);
assert.doesNotMatch(source, /\bimport\s*\(/);
assert.doesNotMatch(readFileSync(new URL('../src/landing.mjs', import.meta.url), 'utf8'), /\bimport\b/);
});
test('without a trusted project adapter all three async paths refuse project-not-configured', async t => {