feat(tasks): the Vikunja v2 adapter, broker task verbs and sync (row 38, S3, darkwing)

packages/tasks adds the Vikunja v2 client, the eight task verbs, the
board-plus-cursor poll with its 60 s window and the digest. The broker
gains the task verbs and boots trackers from the boot config (lead
decisions 66 to 68). Due dates are truncated to the second and recorded
as truncated (B1). A write that lands but whose final read fails counts
as landed, in update and in create (B2).

Candidate agents/darkwing/work/slice1-s3, build-r2.patch 71ce87e6,
manifest e10e30e3 (28 files). Filbert approved round 2 on #1520
(comment 26853). Darkwing's post-reset rerun: test-release 14/14,
test-task 98/98 (comment 26857).

Integration gate in a worktree on c4baf779 with the patch applied:
bus 67, business 60, control-board 124, discord 173, ledger 78,
mosaic 69, queue 148, seat 19, tasks 51 and webui 14, all with no
failures. Conversation is 149/3. The three cohort kill cases (K1, K3,
K10) fail the same on the unpatched base, and the patch doesn't touch
the package. Every scripts/test-*.sh is green. test-release 14/14 and
test-task 98/98 ran on the existing gate2 compose network, because the
host's Docker address pools are exhausted. No network was created or
pruned.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-09 07:40:48 -05:00
co-authored by Claude Opus 5.5
parent c4baf77916
commit 7e73c2cd13
28 changed files with 6504 additions and 25 deletions
+121 -19
View File
@@ -38,6 +38,19 @@ const GATED = new Set([
'role.revoke',
]);
const CLOSED = "('resolved','withdrawn','expired')";
export const TASK_VERBS = Object.freeze(ACTIONS.filter((a) => a.startsWith('task.')));
const SELF_KINDS = new Set(['task.created', 'task.assigned', 'task.state', 'task.closed', 'task.conflict']);
const POLL_KINDS = new Set([
'task.changed.external',
'task.missing',
'credential.expiring',
'credential.expired',
'credential.changed',
]);
const canonical = (x) =>
typeof x === 'string' && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(x) &&
Number.isFinite(Date.parse(x)) &&
new Date(x).toISOString() === x;
export class BusError extends Error {
constructor(code) {
super(code);
@@ -321,6 +334,95 @@ export class Broker {
return this.#event(s, kind, body, subject);
});
}
// Trusted S3 adapter only. With a cap it records a role's own completed write: the external call
// already happened, so this records and does not re-authorize. Without one it records sync reads.
recordTask({ cap = null, business, snapshots = [], events = [] }) {
const s = cap === null ? { business, role: null, run: null } : this.#session(cap);
this.#business(business);
if (cap !== null && (s.human || s.reader || s.business !== business)) fail('agent-required');
if (!Array.isArray(snapshots) || !Array.isArray(events)) fail('invalid-request');
const kinds = cap === null ? POLL_KINDS : SELF_KINDS;
this.#secretCheck({ snapshots, events });
return this.#store.transaction(() => ({
snapshots: snapshots.map((x) => this.#snapshot(s, x)),
events: events.map((e) => {
keys(e, ['kind', 'body', 'subject'], ['kind', 'body']);
if (!kinds.has(e.kind)) fail('reserved-event');
if (!object(e.body)) fail('invalid-request');
return this.#event(s, e.kind, e.body, e.subject ?? null);
}),
}));
}
#snapshot(s, x) {
const poll = s.role === null;
keys(
x,
['task_ref', 'updated', 'etag', 'digest', 'fields', ...(poll ? ['via', 'read_at'] : [])],
['task_ref', 'updated', 'digest', 'fields', ...(poll ? ['via', 'read_at'] : [])],
);
if (!taskRef(x.task_ref) || !object(x.fields) || !/^[0-9a-f]{64}$/.test(x.digest ?? ''))
fail('invalid-snapshot');
string(x.updated, 64);
if (x.etag !== undefined && x.etag !== null) string(x.etag, 256);
if (poll && (!['board', 'cursor', 'task', 'reconcile'].includes(x.via) || !canonical(x.read_at)))
fail('invalid-snapshot');
return this.#store.run(
'INSERT INTO task_snapshots(at,business,task_ref,updated,etag,digest,fields,source,via,read_at,role,run) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)',
this.#now(),
s.business,
x.task_ref,
x.updated,
x.etag ?? null,
x.digest,
JSON.stringify(x.fields),
poll ? 'poll' : 'self',
poll ? x.via : null,
poll ? x.read_at : null,
s.role,
s.run,
).lastInsertRowid;
}
// Trusted S3 reads. Agents read the same rows through the 'tasks' view verb.
taskView(business, view, arg = null) {
this.#business(business);
const parse = (r) => ({ ...r, fields: JSON.parse(r.fields) });
if (view === 'current' && arg === null)
return this.#store.all('SELECT * FROM task_current WHERE business=? ORDER BY task_ref', business).map(parse);
if (view === 'current') {
if (!taskRef(arg)) fail('invalid-request');
const r = this.#store.get('SELECT * FROM task_current WHERE business=? AND task_ref=?', business, arg);
return r ? parse(r) : null;
}
if (view === 'open')
return this.#store.all('SELECT task_ref,bucket FROM tasks_open WHERE business=? ORDER BY task_ref', business);
if (view === 'input')
return Boolean(
typeof arg === 'string' &&
this.#store.get("SELECT 1 FROM events WHERE business=? AND kind='human.input' AND id=?", business, arg),
);
fail('invalid-request');
}
#refused(s, e, request, other = 'storage-refused') {
const error = e instanceof BusError ? e : new BusError(other);
// No request content or raw exception text in refusal evidence.
try {
this.#store.transaction(() =>
this.#event(
s,
'action.refused',
{ code: error.code },
taskRef(request?.args?.task_ref)
? request.args.task_ref
: taskRef(request?.args?.target)
? request.args.target
: null,
),
);
} catch {
return new BusError('storage-unavailable');
}
return error;
}
request(cap, request) {
const s = this.#session(cap);
try {
@@ -336,25 +438,25 @@ export class Broker {
return result;
});
} catch (e) {
const error = e instanceof BusError ? e : new BusError('storage-refused');
// No request content or raw exception text in refusal evidence.
try {
this.#store.transaction(() =>
this.#event(
s,
'action.refused',
{ code: error.code },
taskRef(request?.args?.task_ref)
? request.args.task_ref
: taskRef(request?.args?.target)
? request.args.target
: null,
),
);
} catch {
throw new BusError('storage-unavailable');
}
throw error;
throw this.#refused(s, e, request);
}
}
// The eight task verbs reach the trusted S3 handler here. It runs outside any transaction, gets the
// cap to authorize and record through authorize() and recordTask(); refusals are recorded as in request().
async requestTask(cap, request, handler) {
const s = this.#session(cap);
try {
keys(request, ['verb', 'args'], ['verb']);
if (!TASK_VERBS.includes(request.verb)) fail('unknown-verb');
const args = request.args ?? {};
if (!object(args)) fail('invalid-request');
this.#secretCheck(args);
this.#store.transaction(() => this.#agent(s));
const result = await handler(cap, request.verb, args);
this.#secretCheck(result);
return result;
} catch (e) {
throw this.#refused(s, e, request, 'adapter-failed');
}
}
#dispatch(s, verb, a) {
+1 -1
View File
@@ -1,4 +1,4 @@
export { Broker, BusError, ACTIONS } from './broker.mjs';
export { Broker, BusError, ACTIONS, TASK_VERBS } from './broker.mjs';
export { startBroker } from './runtime.mjs';
export { Client } from './client.mjs';
export { views } from './views.mjs';
+7 -1
View File
@@ -39,7 +39,13 @@ if (!process.send) {
if (message?.op !== 'boot' || booted) throw new BusError('invalid-host-request');
booted = true;
clearTimeout(timer);
runtime = await startBroker(message.config);
// `trackers` is S3's plain-data boot config; the adapter is loaded only when a business has one.
const { trackers, ...config } = message.config ?? {};
if (trackers) {
const { tasksAdapter } = await import('../../tasks/src/adapter.mjs');
config.tasks = tasksAdapter({ trackers });
}
runtime = await startBroker(config);
if (closing) {
await runtime.close();
return;
+18 -2
View File
@@ -7,8 +7,16 @@ import { serve } from './server.mjs';
import { verifyHuman } from './human.mjs';
// Trusted host API. S1 supplies resolved definitions, S6 supplies launch records.
// Neither a business-file writer nor a socket-accessible configuration endpoint.
export async function startBroker({ dataRoot, businesses, launches = [], readers = [], repoRoots = [] }) {
let store, credentials, server;
// `tasks` is S3's adapter factory: ({broker, credentials, businesses}) => {handle, timeout, close}.
export async function startBroker({
dataRoot,
businesses,
launches = [],
readers = [],
repoRoots = [],
tasks = null,
}) {
let store, credentials, server, adapter;
try {
const references = {};
for (const [business, b] of Object.entries(businesses)) {
@@ -40,8 +48,14 @@ export async function startBroker({ dataRoot, businesses, launches = [], readers
}
const bound = launches.map(bindLaunch);
const readCaps = readers.map((business) => ({ business, cap: broker.bindReader({ business }) }));
if (tasks) {
adapter = await tasks({ broker, credentials, businesses });
if (typeof adapter?.handle !== 'function' || !Number.isSafeInteger(adapter.timeout) || adapter.timeout < 1)
throw new BusError('invalid-adapter');
}
const path = join(store.directory, 'broker.sock');
server = await serve({
tasks: adapter ? { handle: adapter.handle, timeout: adapter.timeout } : null,
broker,
path,
authenticateHuman: (proof) => {
@@ -63,12 +77,14 @@ export async function startBroker({ dataRoot, businesses, launches = [], readers
readers: readCaps,
async close() {
await server.close();
await adapter?.close?.();
store.close();
credentials.close();
},
};
} catch (e) {
await server?.close();
await adapter?.close?.();
store?.close();
credentials?.close();
throw e;
+19 -2
View File
@@ -1,9 +1,10 @@
import { createServer } from 'node:net';
import { lstatSync, chmodSync, unlinkSync } from 'node:fs';
import { BusError } from './broker.mjs';
import { BusError, TASK_VERBS } from './broker.mjs';
const LIMIT = 65536;
// One request per connection. There is deliberately no reconnect/retry or SQL verb.
export async function serve({ broker, path, authenticateHuman = null, timeout = 5000 }) {
// `tasks` ({handle, timeout}) is the trusted S3 adapter; only the eight task verbs reach it.
export async function serve({ broker, path, authenticateHuman = null, timeout = 5000, tasks = null }) {
try {
lstatSync(path);
throw new BusError('socket-exists');
@@ -54,6 +55,22 @@ export async function serve({ broker, path, authenticateHuman = null, timeout =
transient = cap = authenticateHuman(r.human);
}
if (typeof cap !== 'string') throw new BusError('unauthenticated');
if (tasks && TASK_VERBS.includes(r.verb)) {
const own = transient;
transient = null;
// A Vikunja write can outlast the idle timeout; a late reply is still outcome-unknown to the client.
socket.setTimeout(tasks.timeout);
broker
.requestTask(cap, { verb: r.verb, args: r.args ?? {} }, tasks.handle)
.then(
(result) => finish({ ok: true, result }),
(e) => finish({ ok: false, error: e instanceof BusError ? e.code : 'adapter-failed' }),
)
.finally(() => {
if (own) broker.disconnect(own);
});
return;
}
const result = broker.request(cap, { verb: r.verb, args: r.args ?? {} });
finish({ ok: true, result });
} catch (e) {