diff --git a/agents/honker/work/queue-194/BUILD.md b/agents/honker/work/queue-194/BUILD.md index f6c7d45f3..55b28ec7c 100644 --- a/agents/honker/work/queue-194/BUILD.md +++ b/agents/honker/work/queue-194/BUILD.md @@ -577,3 +577,116 @@ business file. A failed revoke stops the verb with `credential-revoke-failed` an file). M67 treat any `credential-unknown` as nothing to revoke (the token-on-disk case writes the file). M64-M66 run against fire and delete, M67 against fire only (see sage-1593 above): M64a-b to M66a-b, M67. + +## b3 notes (items 7 and 8 on row 199's landing cb5fdb064, sage-1601) + +Branch `honker/row194-b3`, a new name per sage-1601. Its first commit 589ae2c1d squashes honker/row194-b2 +85edab7c7 onto cb5fdb064. A rebase of b2's commits stopped on the same five files many times, so I +squashed. The five conflicts kept both sides: + +- broker imports, constructor, dispatch, and the credential and lifecycle verbs +- runtime imports +- the organization write, which takes detail and context +- cli credentials and veto dispatch +- the vocabulary comment, as row 199 wrote it + +Line numbers below are the b3 tip's. + +### Deviations from brief 722136772 and plan 85edab7c7 + +1. Item 7 dates, sage-1605 pick (a). The human create writes the UTC create day as `rotateBy` and `expires` + (`instance-settings.mjs:118-120`). `checkCredentialRef` skips both date checks only for a store + reference with no file (ENOENT), and keeps the "not issued" warning (`business/src/credentials.mjs:73, + 79-81, 110-113`). Every other reference keeps the checks. Tests: `business/tests/cli.test.mjs` "validate: + a not-issued store agent dated today passes, and an issued one with a past expiry fails", and T19 in + `instance-settings.test.mjs` (validate exits 0 with "not issued"). +2. fixedRole, sage-1605. A reference compares by kind and path only (`runtime.mjs:154-167`), because row + 199's issue rewrites the date in the file outside the reload. Test: T19 in `bus/tests/reload.test.mjs` + (add, restart, issue, then a vars change goes live with restart false). The T14 date-only test stays. +3. Delete takes all-store references, sage-1605. `deleteRefusal` refuses only when some reference isn't + `store: true` (`instance-settings.mjs:43-49`). A file or env reference refuses + `organization-credentials-out-of-scope` at the request, before any take (T20 delete case 2). +4. Fire on a file or env reference revokes in memory, sage-1605. The result's `credentials.outsideStore` + names the services whose reference is outside the store (`runtime.mjs:122-124, 141-142`). T20 fire + case 1 checks `outsideStore: ['vikunja']` for coder. +5. The `credential-revoke-failed` store-dir check stays, sage-1605 (`runtime.mjs:132-140`). It now runs after + delete's `remove` too. `remove` already leaves no token, so on delete it only refuses a name `remove` + would itself have refused. +6. Tracker on add, honker-0049 and sage-1610 (a). A human add takes an optional `tracker: {bot, botId}`. + It is required for a definition with a vikunja credential (`organization-tracker-required`) and refused + for any other (`invalid-request`). checkBot and the bot uniqueness rule (other instances and + `tracker.sync`) run on the add path (`instance-settings.mjs:88-124`, `organization-tracker-bot-taken`). + `change` with a tracker refuses (`instance-settings.mjs:214`). The broker passes `tracker` through + (`broker.mjs:193-194`). CLI: `instance add ... [--bot BOT --bot-id N]` (`cli/src/instances.mjs:13, 73, + 87-90, 107`, reasons at 22-27). The Console doesn't take a tracker: `INSTANCE_KEYS` in serve.mjs is + unchanged, the Agents and Settings forms still list credentialed definitions as not accepted, and a + vikunja add from the Console answers `organization-tracker-required` with a reason that names the CLI + (`webui/src/serve.mjs:332-333`, `webui/tests/instances.test.mjs`). +7. Delete with a tracker bot, sage-1610 (b). The delete's result names the bot and says to remove the + Vikunja bot user and any token by hand (199 A5) (`instance-settings.mjs:199-202`). `lifecycleDelete` + returns `bot` (`broker.mjs:1386-1387`), the launcher carries it to `lifecycleDone` + (`cli/src/launcher.mjs:752-767`), `lifecycleDone` takes `bot` checked against BOT_NAME + (`broker.mjs:132, 1392-1393`), and `lifecycleView` shows it (`broker.mjs:147`). The CLI line + (`cli/src/instances.mjs:177-180`) and the Agents receipt (`webui/src/public/agents.js:113-115`) name it. + Tests: T20 bus delete case 1, T20 in `cli/tests/lifecycle.test.mjs`, and `agents-browser.test.mjs`. +8. No Vikunja account. The create makes none and the delete removes none. Q188 and the `account.create` + hard wait aren't touched (sage-1610). +9. The tester's add keeps the credential refusal. Row 175 W2 (`bus/tests/tester-writes.test.mjs:91`) + says the tester refuses credentials, and items 7 and sage-1610 name the human's add. The writer lifts + the refusal only when the actor isn't `tester` (`instance-settings.mjs` add, the `definitionFor` call). + The broker reserves that name: no human or role may be called `tester` (`broker.mjs:234, 237`). W2 has a + new case, a tester add with a valid tracker, which still refuses `organization-credentials-out-of-scope`. +10. The commit hook is `beforeWrite` (`instance-settings.mjs:332-360`). A first draft named it `before` + beside a `let before`, a SyntaxError, so I renamed it. +11. A failed delete revokes first. `Credentials.remove` revokes every service it knows before it reads the + directory (row 199 `bus/src/credentials.mjs` remove). When the directory then holds a name `remove` + refuses, the delete stops with the business file unchanged and the tokens already gone. That is the safe + side and matches item 8's note on a revision race. T20 delete case 1 asserts it. +12. T20 uses real failures, not a stub store: a 0500 agent directory (fire) and a foreign file in the + store (delete). The revoke-before-write order is checked by the failing cases: a revoke after the write + would leave the file changed (M65). + +### Hunks for Duckworth's scoped check (sage-1605) + +- `packages/business/src/credentials.mjs`: 12 (DATE_KEY exported), 73, 79-81 (notIssued), 110-113 (the + no-file skip). +- Credential verbs: `packages/bus/src/credential-verbs.mjs` and `bus/src/credentials.mjs` are unchanged from + cb5fdb064. The broker's `#requestCredential` (`broker.mjs:1679-1709`) is row 199's text as merged in the + 589ae2c1d squash. b3's own credential hunks: the runtime revoke callback (`runtime.mjs:109-143`) and the + broker's `credential-revoke-failed` mapping (`broker.mjs:1816-1817`). +- fixedRole: `packages/bus/src/runtime.mjs:154-167`. + +### Mutants to run on Sage's slot (after M1-M60) + +- M61 the human create keeps the credential refusal (T19 business and bus fail at create). +- M62 `fixedRole` ignores `credentials` (bus T19 fails: restart false). +- M63 the Agents create receipt drops the restart text (agents-browser fails). +- M64a/b drop the revoke call on fire and delete (T20 success cases fail). +- M65a/b move the revoke after the write (T20 failing cases see the file changed). +- M66a/b ignore the revoke's failure (T20 failing cases write the file). +- M67 any `credential-unknown` counts as nothing to revoke, with the store-dir check dropped (T20 fire + case 2 writes the file). +- M68 fixedRole compares the whole reference, dates included (bus T19 fails: restart true after issue). +- M69 `checkCredentialRef` drops the no-file condition (the issued-past-expiry validate test passes wrongly). +- M70 drop the vikunja tracker requirement (T19 business and the CLI tracker-required case fail). +- M71 `deleteRefusal` refuses a tracker bot again (T20 delete cases and CLI T20 fail). +- M72 skip checkBot on the add path (T19 business bad name and bad botId fail). +- M73 the tester's add binds credentials too (tester-writes W2 fails on both reviewer-2 cases). + +### Pins and a missed failure + +- `bus/tests/channel-proof.test.mjs` pins `webui/src/bus.mjs`. b3 adds two STATUS entries, so it is repinned + with a comment, as rows 165 and 171 did. No proof or transport change. +- `bus/tests/project-runtime.test.mjs` pins the broker's vocabulary import. b2 imported `unhireableAction` + and never updated the pin, so the test fails on b2 too. I have no log of it running on b2. b3 fixes the pin. +- `bus/tests/tester-writes.test.mjs` W2 caught the tester binding credentials through a tracker add. The + writer now lifts the credential refusal only when the actor is not `tester` (deviation 9), and W2 has a + case with a valid bot that still refuses. + +### b3 singles (2026-10-21T01:02Z) + +Every test file under `packages/{business,bus,harness,cli,webui}/tests`, run singly with `node --test`: +158 files, 1501 pass, 0 fail. The first pass failed channel-proof, project-runtime and tester-writes (fixed +above). After the fixes and the tester change in `instance-settings.mjs`, 17 files reran singly: 167 pass, +0 fail. The total uses the rerun counts for those 17, summed by awk over the logs. Suites and mutants +M1-M73 wait on Sage's slot. diff --git a/packages/bus/src/broker.mjs b/packages/bus/src/broker.mjs index 277a7dca8..f13f31fb1 100644 --- a/packages/bus/src/broker.mjs +++ b/packages/bus/src/broker.mjs @@ -147,6 +147,7 @@ const LIFECYCLE_STEPS = ['lifecycle.taken', 'lifecycle.done', 'lifecycle.cancell // limit: the launcher checks each run's start time before it signals. export const LIFECYCLE_REQUEST_MS = 60_000; const LIFECYCLE_CODE = /^[a-z-]{1,64}$/; +const BOT_NAME = /^bot-[a-z0-9][a-z0-9._-]{0,60}$/; // Row 194 (#1692, D2.1, D2.2, PRD 1.7 REQ-COS-3): the chief's hire and fire arguments, allowed then // required. Each carries the reason the log records. const HIRE_FIRE_ARGS = Object.freeze({ @@ -161,7 +162,7 @@ const lifecycleView = (r) => ({ ...('revision' in r ? { revision: r.revision, retry: r.retry === true } : {}), ...('runs' in r ? { runs: r.runs } : {}), ...(r.kill === true ? { kill: true } : {}), - done: r.done ? { run: r.done.run ?? null, transaction: r.done.transaction ?? null, refusal: r.done.refusal ?? null } : null, + done: r.done ? { run: r.done.run ?? null, transaction: r.done.transaction ?? null, refusal: r.done.refusal ?? null, ...(r.done.bot ? { bot: r.done.bot } : {}) } : null, cancelled: r.cancelled ? { by: r.cancelled.by } : null, }); const SELF_KINDS = new Set(['task.created', 'task.assigned', 'task.state', 'task.closed', 'task.conflict']); @@ -207,7 +208,8 @@ const oid = (x) => typeof x === 'string' && /^[0-9a-f]{40}([0-9a-f]{24})?$/.test // Row 155 (#1649) adds assistants: an assistant instance's vars, tracker and definition. export const ORGANIZATION_KEYS = ['revision', 'limits', 'models', 'instances', 'reset', 'assistants']; // Row 165 (#1662): the keys of the human-only instances.set (business instance-settings.mjs). -const INSTANCE_KEYS = ['revision', 'instance', 'op', 'definition', 'vars', 'launch']; +// Row 194 (brief item 7, sage-1610 a): add takes tracker, an existing Vikunja bot. +const INSTANCE_KEYS = ['revision', 'instance', 'op', 'definition', 'vars', 'launch', 'tracker']; const VETO_KEYS = ['revision', 'op', 'name']; // Row 123 (#1617): role.end never reaches the caller's own run. END_PROTECTED (vocabulary.mjs, row // 155): only the chief of staff, or a decision the human resolved through the CLI, ends or revokes @@ -2302,12 +2304,14 @@ export class Broker { } catch (e) { this.#organizationFail(e, 'instances.set'); } - return { transaction: out.transaction, retry: false }; + // sage-1610 (b): a deleted agent's Vikunja bot is named, so the human removes it in Vikunja. + return { transaction: out.transaction, retry: false, ...(out.tracker ? { bot: out.tracker.bot } : {}) }; } // The close of a taken request, with the run it started, the delete's transaction or the code - // that stopped it. + // that stopped it. A delete also names the agent's Vikunja bot (sage-1610 b). lifecycleDone(record) { - keys(record, ['business', 'request', 'run', 'transaction', 'refusal'], ['business', 'request']); + keys(record, ['business', 'request', 'run', 'transaction', 'refusal', 'bot'], ['business', 'request']); + if ('bot' in record && (typeof record.bot !== 'string' || !BOT_NAME.test(record.bot))) fail('invalid-request'); this.#business(identifier(record.business)); identifier(record.request); for (const k of ['run', 'transaction']) if (k in record) identifier(record[k]); @@ -2749,6 +2753,8 @@ export class Broker { if (e.code === "invalid-plugins" || e.code === "unknown-plugin") fail(e.code); // Row 194: the writer's own copy of the hire and fire checks, against the file as it stands. if ((verb === "instance.hire" || verb === "instance.fire") && ["definition-not-hireable", "instance-kept"].includes(e.code)) fail(e.code); + // Row 194 (brief item 8): a fire's or a delete's revoke failed, and nothing was written. + if ((verb === "instance.fire" || verb === "instances.set") && e.code === "credential-revoke-failed") fail(e.code); // Row 65: the route checks every write of an instance's route vars runs. if (["harness-off", "harness-refused", "thinking-unsupported"].includes(e.code)) fail(e.code); // The routing table names a model the table lacks; the older verbs keep invalid-request. diff --git a/packages/bus/src/runtime.mjs b/packages/bus/src/runtime.mjs index b836e488f..12d70e247 100644 --- a/packages/bus/src/runtime.mjs +++ b/packages/bus/src/runtime.mjs @@ -13,7 +13,7 @@ import { publishRemote, workingRepo, WorkingError } from '../../seat/src/working import { createLoader, hasModule } from '../../plugins/src/loader.mjs'; import { pluginSettings } from '../../business/src/plugin-settings.mjs'; import { instanceSettings } from '../../business/src/instance-settings.mjs'; -import { organizationWriter } from '../../business/src/organization.mjs'; +import { organizationWriter, OrganizationError } from '../../business/src/organization.mjs'; import { credentialVerbs } from './credential-verbs.mjs'; import { loadBusiness } from '../../business/src/business.mjs'; import { loadRole } from '../../business/src/role.mjs'; @@ -134,8 +134,43 @@ export async function startBroker({ const plugins=organization?pluginSettings({dir:organization.dir,rolesDir:organization.rolesDir,exists:hasModule}):null; const levels=organization?await harnessLevels():()=>null; const settings=organization?launchSettings({...organization,sessions:()=>readSessions(dataRoot),levels}):null; + // Row 194 (#1692, brief item 8, row 199 D13): a fire or a delete revokes the agent's credentials + // after the writer's checks and before its write. Fire revokes each service of the entry and keeps + // the store directory, delete calls remove (sage-1593). A service the running bus doesn't know (an + // agent created since the start) has nothing in memory, so it goes on, and then no token or tmp + // file may remain in the agent's store directory (sage-1592). Any failure stops the verb with the + // file unchanged. + const revokeFailed = (message) => new OrganizationError('credential-revoke-failed', message); + function revoke(business, agent, how, services) { + const instance = business + '/' + agent; + const outside = []; + try { + if (how === 'delete' && storeRoot) credentials.remove(instance); + else + for (const service of services) { + try { + if (!credentials.revoke(instance, service).file) outside.push(service); + } catch (e) { + if (e.code !== 'credential-unknown') throw e; + } + } + } catch (e) { + throw revokeFailed(`${agent}: ${e.code ?? 'credential-file'}`); + } + if (storeRoot) { + let left = []; + try { + left = readdirSync(join(storeRoot, business, agent)); + } catch (e) { + if (e.code !== 'ENOENT') throw revokeFailed(`${agent}: store directory can't be read`); + } + if (left.length > 0) throw revokeFailed(`${agent}: ${left.sort().join(' and ')} still in the store`); + } + // A file or env reference outside the store keeps its token for a restart (row 199 section 6). + return { revoked: services, outsideStore: how === 'fire' ? outside : [] }; + } // Row 165 (#1662): the human adds and changes role instances through instances and instances.set. - const instances=organization?instanceSettings({dir:organization.dir,rolesDir:organization.rolesDir,system:organization.system,levels}):null; + const instances=organization?instanceSettings({dir:organization.dir,rolesDir:organization.rolesDir,system:organization.system,levels,revoke}):null; const usage = await createUsage({ store, dataRoot, businesses, log: entry => process.stderr.write(`usage: ${JSON.stringify(entry)}\n`) }); // Row 125 (#1619, REQ-LIMIT-3, REQ-LIMIT-4): the limit checks read the organization file at @@ -171,10 +206,16 @@ export async function startBroker({ // would load it. The credential references, the project roots the Credentials store protects // and the tracker bots are fixed at start (the Credentials store, the tasks adapter), so a file // whose references, roots or bots differ from the boot copy isn't reloaded, and the write - // answers restart: true. Create and hire add neither, - // because credentialed definitions are refused. - // A role not in the boot copy matches only with no references and no bot. - const fixedRole = r => canonicalJson({ credentials: r?.credentials ?? {}, tracker: r?.tracker ?? null }); + // answers restart: true. Hire adds neither. A human create of a credentialed definition adds + // references, so it answers restart: true, and issue works after the restart (brief item 7). + // A role not in the boot copy matches only with no references and no bot. A reference compares + // by its kind and path only: row 199's issue rewrites the date in the file outside this reload, + // Credentials keeps its own copy of the date, and the broker never reads it. + const fixedRef = ({ file, env, store }) => ({ file, env, store }); + const fixedRole = r => canonicalJson({ + credentials: Object.fromEntries(Object.entries(r?.credentials ?? {}).map(([service, ref]) => [service, fixedRef(ref)])), + tracker: r?.tracker ?? null, + }); const fixedAtStart = b => ({ roles: Object.fromEntries(Object.entries(b.roles).map(([role, r]) => [role, fixedRole(r)])), sync: canonicalJson(b.tracker?.sync ?? null), diff --git a/packages/bus/tests/channel-proof.test.mjs b/packages/bus/tests/channel-proof.test.mjs index 809f6de5c..2e467ce8f 100644 --- a/packages/bus/tests/channel-proof.test.mjs +++ b/packages/bus/tests/channel-proof.test.mjs @@ -21,7 +21,9 @@ const baselines = { // organization-no-change, organization-project-mismatch, organization-unresolvable-instance), no proof or // transport change. Row 155 (#1649) added eight for the assistant routes. // Row 171 (#1668): project-name-is-repo maps to 409; no proof or transport change. - "packages/webui/src/bus.mjs": "e69d17d4385a4d190d15373ed1a26e270a5c6906eec9e61fcc2bb6b05849cabb", + // Row 194 (#1692, brief item 7, sage-1610 a): organization-tracker-required 400 and + // organization-tracker-bot-taken 409; no proof or transport change. + "packages/webui/src/bus.mjs": "15e8123ffdbb6d067e8a516f5823efdb5de3c869963764f27cd14bb9e4ce3313", }; const repoFile = path => new URL("../../../" + path, import.meta.url); diff --git a/packages/bus/tests/instances-verb.test.mjs b/packages/bus/tests/instances-verb.test.mjs index 607b0c2c1..08c10eb03 100644 --- a/packages/bus/tests/instances-verb.test.mjs +++ b/packages/bus/tests/instances-verb.test.mjs @@ -86,7 +86,8 @@ test('row 165 runtime: an add and a change reach the organization file with the const before = readFileSync(file, 'utf8'); const entries = log().length; const code = (args) => { try { bus.broker.request(human, { verb: 'instances.set', args: { revision: changed.revision, ...args } }); } catch (e) { return e.code; } return null; }; - assert.equal(code({ instance: 'reviewer-2', op: 'add', definition: 'reviewer' }), 'organization-credentials-out-of-scope'); + // Row 194 (brief item 7, sage-1610 a): an add of a vikunja definition needs its bot. + assert.equal(code({ instance: 'reviewer-2', op: 'add', definition: 'reviewer' }), 'organization-tracker-required'); assert.equal(code({ instance: 'sec-1', op: 'change', definition: 'coder' }), 'organization-credentials-out-of-scope'); assert.equal(code({ instance: 'sec-1', op: 'add', definition: 'merge-gate' }), 'organization-instance-exists'); assert.equal(code({ instance: 'ghost', op: 'change', vars: {} }), 'organization-unknown-instance'); diff --git a/packages/bus/tests/lifecycle-revoke.test.mjs b/packages/bus/tests/lifecycle-revoke.test.mjs new file mode 100644 index 000000000..464885fe4 --- /dev/null +++ b/packages/bus/tests/lifecycle-revoke.test.mjs @@ -0,0 +1,144 @@ +// Row 194 (#1692, brief item 8, row 199 D13, T20): fire and delete revoke the agent's credentials +// after the writer's checks and before the write. Fire revokes each service and keeps the store +// directory. Delete calls remove (sage-1593). A failed revoke stops the verb with +// credential-revoke-failed and the business file's bytes unchanged. Fake tokens in a scratch root. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { busBusiness } from '../src/business.mjs'; +import { startBroker } from '../src/runtime.mjs'; +import { loadBusiness } from '../../business/src/business.mjs'; +import { resolveInstance } from '../../business/src/resolve.mjs'; +import { businessDoc, FAR_DATE, rolesCopy, systemFor, writeJson } from '../../business/tests/helpers.mjs'; + +const TOKEN = 'fake_issued_token_0123456789'; +const store = (agent, service) => ({ store: true, [service === 'gitea' ? 'rotateBy' : 'expires']: FAR_DATE }); + +// coder: gitea in the store, vikunja a file reference. rev-2 and rev-3: both in the store, with a +// tracker bot. `drop` names instances whose credentials the boot copy leaves out, as a restart that +// dropped the entry would: the running bus then has no entry for a file on disk (sage-1592). +async function setup(t, { drop = [] } = {}) { + const root = mkdtempSync(join(tmpdir(), 'bus-lifecycle-revoke-')); + const rolesDir = rolesCopy(root); + const doc = { ...businessDoc(root, 'demo'), plugins: { harness: ['pi'] } }; + doc.roles.coder.credentials.gitea = store('coder', 'gitea'); + for (const [name, botId] of [['rev-2', 40], ['rev-3', 41]]) { + doc.roles[name] = { definition: 'reviewer', tracker: { bot: `bot-demo-${name}`, botId }, credentials: { gitea: store(name, 'gitea'), vikunja: store(name, 'vikunja') } }; + } + doc.launch.instances.push('rev-2', 'rev-3'); + const file = writeJson(join(root, 'businesses/demo.json'), doc); + mkdirSync(join(root, 'data'), { mode: 0o700 }); + mkdirSync(join(root, 'secrets', 'agents'), { recursive: true, mode: 0o700 }); + const b = loadBusiness('demo', { dir: root, rolesDir }); + const resolved = {}; + for (const i of Object.keys(b.roles)) resolved[i] = resolveInstance({ system: systemFor(root), business: b, instance: i }); + const boot = busBusiness(b, resolved); + for (const name of drop) delete boot.roles[name].credentials; + const bus = await startBroker({ dataRoot: join(root, 'data'), businesses: { demo: boot }, organization: { dir: root, rolesDir, system: systemFor(root) } }); + t.after(async () => { + await bus.close(); + chmodSync(join(root, 'secrets', 'agents'), 0o700); + rmSync(root, { recursive: true, force: true }); + }); + const human = bus.broker.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true }); + const chief = bus.broker.bindLaunch({ business: 'demo', role: 'chief', run: 'chief-run', harness: 'pi' }); + bus.broker.request(chief, { verb: 'role.claim' }); + const ask = (verb, args) => bus.broker.request(human, { verb, args }); + const fire = (name) => bus.broker.request(chief, { verb: 'instance.fire', args: { name, reason: 'the work is done' } }); + const agentDir = (agent) => join(root, 'secrets', 'agents', 'demo', agent); + const plant = (agent, service) => { + mkdirSync(agentDir(agent), { recursive: true, mode: 0o700 }); + writeFileSync(join(agentDir(agent), service), TOKEN + '\n', { mode: 0o600 }); + }; + // A delete runs as the launcher's pass would: the verb's request, the take, then lifecycleDelete. + // A refused delete closes the request with its code, as the launcher does. + const remove = (instance) => { + const { request } = ask('instances.set', { revision: ask('instances').revision, instance, op: 'delete' }); + assert.equal(bus.lifecycleTake({ business: 'demo', request }).go, true); + try { + return { request, ...bus.lifecycleDelete({ business: 'demo', request }) }; + } catch (e) { + bus.lifecycleDone({ business: 'demo', request, refusal: e.code }); + throw e; + } + }; + const bytes = () => readFileSync(file, 'utf8'); + const code = (fn) => { try { fn(); } catch (e) { return e.code; } return null; }; + const status = (agent) => Object.fromEntries(bus.credentialStatus('demo', agent).map((e) => [e.service, e.state])); + return { root, bus, ask, fire, remove, agentDir, plant, bytes, code, status, file }; +} + +test('T20 fire: a revoke that fails stops the fire with the file unchanged; one that succeeds revokes, keeps the directory and names the services outside the store', async (t) => { + const f = await setup(t); + f.ask('credentials.issue', { agent: 'coder', service: 'gitea', token: TOKEN, date: '2099-01-01' }); + assert.ok(existsSync(join(f.agentDir('coder'), 'gitea'))); + // The revoke can't unlink the token, so it fails before the write: the file still lists coder. + const before = f.bytes(); + chmodSync(f.agentDir('coder'), 0o500); + assert.equal(f.code(() => f.fire('coder')), 'credential-revoke-failed'); + chmodSync(f.agentDir('coder'), 0o700); + assert.equal(f.bytes(), before); + assert.ok(JSON.parse(before).launch.instances.includes('coder')); + + const fired = f.fire('coder'); + assert.equal(fired.delisted, true); + assert.deepEqual(fired.credentials, { revoked: ['gitea', 'vikunja'], outsideStore: ['vikunja'] }); + assert.ok(!JSON.parse(f.bytes()).launch.instances.includes('coder')); + assert.deepEqual(f.status('coder'), { gitea: 'revoked', vikunja: 'revoked' }); + // The directory stays, empty, so the status reads revoked and the human removes the remote token. + assert.deepEqual(readdirSync(f.agentDir('coder')), []); +}); + +test('T20 fire: with no entry in the running bus, a token on disk refuses and an empty store goes on', async (t) => { + const f = await setup(t, { drop: ['rev-2'] }); + f.plant('rev-2', 'gitea'); + const before = f.bytes(); + assert.equal(f.code(() => f.fire('rev-2')), 'credential-revoke-failed'); + assert.equal(f.bytes(), before); + rmSync(join(f.agentDir('rev-2'), 'gitea')); + const fired = f.fire('rev-2'); + assert.equal(fired.delisted, true); + assert.deepEqual(fired.credentials, { revoked: ['gitea', 'vikunja'], outsideStore: [] }); +}); + +test('T20 delete: a revoke that fails keeps the file; one that succeeds clears the store, deletes, and names the tracker bot', async (t) => { + const f = await setup(t); + f.ask('credentials.issue', { agent: 'rev-2', service: 'vikunja', token: TOKEN, date: '2099-01-01' }); + // remove refuses a name it doesn't own (credential-file), so the delete stops with the file unchanged. + writeFileSync(join(f.agentDir('rev-2'), 'notes'), 'x'); + const before = f.bytes(); + assert.equal(f.code(() => f.remove('rev-2')), 'credential-revoke-failed'); + assert.equal(f.bytes(), before); + // remove revokes the services it knows before it reads the directory (row 199), so the token is + // already gone: a failed delete leaves the agent listed with nothing it can use. + assert.equal(existsSync(join(f.agentDir('rev-2'), 'vikunja')), false); + assert.deepEqual(f.status('rev-2'), { gitea: 'revoked', vikunja: 'revoked' }); + rmSync(join(f.agentDir('rev-2'), 'notes')); + + const out = f.remove('rev-2'); + assert.equal(out.bot, 'bot-demo-rev-2'); + assert.equal(existsSync(f.agentDir('rev-2')), false); + assert.deepEqual(f.status('rev-2'), { gitea: 'revoked', vikunja: 'revoked' }); + const after = JSON.parse(f.bytes()); + assert.equal(Object.hasOwn(after.roles, 'rev-2'), false); + assert.ok(after.retired.includes('rev-2')); + // The launcher's close carries the bot, so the CLI and the Console name it. + const done = f.bus.lifecycleDone({ business: 'demo', request: out.request, transaction: out.transaction, bot: out.bot }); + assert.equal(done.done.bot, 'bot-demo-rev-2'); +}); + +test('T20 delete: with no entry in the running bus, a token file is cleared and the delete goes on; a file reference refuses', async (t) => { + const f = await setup(t, { drop: ['rev-3'] }); + f.plant('rev-3', 'gitea'); + const out = f.remove('rev-3'); + assert.equal(out.bot, 'bot-demo-rev-3'); + assert.equal(existsSync(f.agentDir('rev-3')), false); + assert.equal(Object.hasOwn(JSON.parse(f.bytes()).roles, 'rev-3'), false); + // coder's vikunja is a file reference: deleting it stays a hand edit, refused at the request. + const before = f.bytes(); + assert.equal(f.code(() => f.remove('coder')), 'organization-credentials-out-of-scope'); + assert.equal(f.bytes(), before); + assert.deepEqual(f.status('coder'), { gitea: 'not-issued', vikunja: 'valid' }); +}); diff --git a/packages/bus/tests/project-runtime.test.mjs b/packages/bus/tests/project-runtime.test.mjs index 60f90ace5..43e6690c1 100644 --- a/packages/bus/tests/project-runtime.test.mjs +++ b/packages/bus/tests/project-runtime.test.mjs @@ -28,8 +28,9 @@ test('Broker keeps the sandbox client import closure: only the listed imports, n // from it too. Row 199 (#1697) reads the D9c fork parse, forkProblem and forkUrl, from it. // Row 210 (#1707) reads credentialKind and the D6 argv check, validArgv and commandAllowed, from it. // Row 234 (#1740) reads HOST_ID for the hosts verbs. - // Row 213 (#1714) reads CREATIVE_DEFINITIONS for the creative raise refusal (M6). - "import { ID_PATTERN, THREAD_DEFINITION, END_PROTECTED, forkProblem, forkUrl, credentialKind, validArgv, commandAllowed, HOST_ID, CREATIVE_DEFINITIONS } from '../../business/src/vocabulary.mjs';", + // Row 213 (#1714) reads CREATIVE_DEFINITIONS for the creative raise refusal (M6). Row 194 + // (#1692, D2.4) reads unhireableAction, the hire veto's action name. + "import { ID_PATTERN, THREAD_DEFINITION, END_PROTECTED, forkProblem, forkUrl, credentialKind, validArgv, commandAllowed, HOST_ID, CREATIVE_DEFINITIONS, unhireableAction } from '../../business/src/vocabulary.mjs';", ]); assert.doesNotMatch(source, /\bimport\s*\(/); assert.doesNotMatch(readFileSync(new URL('../src/landing.mjs', import.meta.url), 'utf8'), /\bimport\b/); diff --git a/packages/bus/tests/reload.test.mjs b/packages/bus/tests/reload.test.mjs index 7b00a4cfc..8fd964095 100644 --- a/packages/bus/tests/reload.test.mjs +++ b/packages/bus/tests/reload.test.mjs @@ -98,6 +98,48 @@ test('T14 a file whose credential references differ from the boot copy is not re assert.equal(code(() => bind(f.bus, 'sec-1')), 'unknown-role'); }); +test('T14 a date-only change to a credential reference still reloads: row 199 issue rewrites the date outside the reload', async (t) => { + const f = await setup(t); + const doc = JSON.parse(readFileSync(f.file, 'utf8')); + doc.roles.coder.credentials.gitea.rotateBy = '2098-06-01'; + doc.roles.coder.credentials.vikunja.expires = '2098-06-01'; + writeFileSync(f.file, JSON.stringify(doc, null, 2) + '\n', { mode: 0o600 }); + const changed = f.ask('instances.set', { revision: f.revision(), instance: 'coder', op: 'change', vars: { harness: 'pi', model: 'claude-sonnet-5-5' } }); + assert.equal(changed.restart, false); + assert.equal(f.reloads.length, 1); + assert.equal(f.reloads[0].roles.coder.vars.model, 'claude-sonnet-5-5'); +}); + +// Row 194 (brief item 7, T19, sage-1605, sage-1610 a): a human create of a credentialed definition +// answers restart true, because credential references are fixed at start. issue refuses until a +// restart loads the entry. After one, issue works, the status reads valid, and a vars change after +// the issue goes live: issue rewrites the date, and the fixed-at-start compare ignores dates. +test('T19 a credentialed create answers restart true; issue works only after a restart, and a later vars change goes live', async (t) => { + const f = await setup(t); + mkdirSync(join(f.root, 'secrets', 'agents'), { recursive: true, mode: 0o700 }); + const added = f.ask('instances.set', { revision: f.revision(), instance: 'rev-2', op: 'add', definition: 'reviewer', tracker: { bot: 'bot-demo-rev-2', botId: 40 } }); + assert.equal(added.restart, true); + assert.equal(f.reloads.length, 0); + const issue = { agent: 'rev-2', service: 'gitea', token: 'fake_issued_token_0123456789', date: '2099-01-01' }; + assert.equal(code(() => f.ask('credentials.issue', issue)), 'credential-unknown'); + + mkdirSync(join(f.root, 'data-2'), { mode: 0o700 }); + const bus = await startBroker({ dataRoot: join(f.root, 'data-2'), businesses: { demo: busForm(f.root, f.rolesDir) }, organization: { dir: f.root, rolesDir: f.rolesDir, system: systemFor(f.root) } }); + t.after(() => bus.close()); + const reloads = []; + const reloadBusiness = bus.broker.reloadBusiness.bind(bus.broker); + bus.broker.reloadBusiness = (id, next) => { reloads.push(structuredClone(next)); reloadBusiness(id, next); }; + const human = bus.broker.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true }); + const ask = (verb, args) => bus.broker.request(human, { verb, args }); + ask('credentials.issue', issue); + assert.equal(bus.credentialStatus('demo', 'rev-2').find(e => e.service === 'gitea').state, 'valid'); + assert.equal(JSON.parse(readFileSync(f.file, 'utf8')).roles['rev-2'].credentials.gitea.rotateBy, '2099-01-01'); + const changed = ask('instances.set', { revision: ask('instances').revision, instance: 'rev-2', op: 'change', vars: { harness: 'pi', model: 'claude-sonnet-5-5' } }); + assert.equal(changed.restart, false); + assert.equal(reloads.length, 1); + assert.equal(reloads[0].roles['rev-2'].vars.model, 'claude-sonnet-5-5'); +}); + test('T14 a file whose project root differs from the boot copy is not reloaded, because the Credentials store protects the boot roots', async (t) => { const f = await setup(t); const doc = JSON.parse(readFileSync(f.file, 'utf8')); diff --git a/packages/bus/tests/tester-writes.test.mjs b/packages/bus/tests/tester-writes.test.mjs index 687fa0656..e256902d6 100644 --- a/packages/bus/tests/tester-writes.test.mjs +++ b/packages/bus/tests/tester-writes.test.mjs @@ -95,6 +95,8 @@ test('row 175: W2 as the tester refuses credentials, protected definitions, huma const entries = r.log().length; const refused = [ [{ instance: 'reviewer-2', op: 'add', definition: 'reviewer' }, 'organization-credentials-out-of-scope'], + // Row 194 (brief item 7): only the human's add binds credentials. A valid bot doesn't lift it. + [{ instance: 'reviewer-2', op: 'add', definition: 'reviewer', tracker: { bot: 'bot-reviewer-2', botId: 40 } }, 'organization-credentials-out-of-scope'], [{ instance: 'thread-2', op: 'add', definition: 'assistant' }, 'organization-definition-refused'], [{ instance: 'human', op: 'add', definition: 'merge-gate' }, 'invalid-request'], [{ instance: 'tester', op: 'add', definition: 'merge-gate' }, 'invalid-request'], diff --git a/packages/business/src/business.mjs b/packages/business/src/business.mjs index 0754ce779..e07a363e3 100644 --- a/packages/business/src/business.mjs +++ b/packages/business/src/business.mjs @@ -35,7 +35,7 @@ export function businessFilePath(id, dir = configDir()) { return join(dir, "businesses", `${id}.json`); } -function checkBot(tracker, where) { +export function checkBot(tracker, where) { requireObject(tracker, where); rejectUnknownKeys(tracker, ["bot", "botId"], where); if (typeof tracker.bot !== "string" || !BOT_NAME.test(tracker.bot)) refuse(`${where}.bot must be a Vikunja bot username starting with "bot-"`); diff --git a/packages/business/src/credentials.mjs b/packages/business/src/credentials.mjs index f606ad8ff..52f95c085 100644 --- a/packages/business/src/credentials.mjs +++ b/packages/business/src/credentials.mjs @@ -9,7 +9,7 @@ import { credentialKind, isHostKind } from "./vocabulary.mjs"; import { requireObject, rejectUnknownKeys, requireDate } from "./util.mjs"; const ENV_NAME = /^[A-Z][A-Z0-9_]{0,63}$/; -const DATE_KEY = Object.freeze({ gitea: "rotateBy", vikunja: "expires" }); +export const DATE_KEY = Object.freeze({ gitea: "rotateBy", vikunja: "expires" }); const WARN_DAYS = 7; const DAY_MS = 24 * 60 * 60 * 1000; @@ -71,13 +71,15 @@ export function checkCredentialRef(ref, { forbiddenRoots = [], now = new Date(), const problems = []; const warnings = []; const label = `${ref.service} ${ref.file ? `file ${ref.file}` : `env ${ref.env}`}`; + let notIssued = false; if (ref.file) { let stat = null; try { stat = lstatSync(ref.file); } catch (e) { // Row 199 (design D3a): a store reference with no file is an agent not issued yet. - if (ref.store && e.code === "ENOENT") warnings.push(`${label}: not issued`); + notIssued = Boolean(ref.store) && e.code === "ENOENT"; + if (notIssued) warnings.push(`${label}: not issued`); else problems.push(`${label}: not found`); } if (stat) { @@ -106,6 +108,10 @@ export function checkCredentialRef(ref, { forbiddenRoots = [], now = new Date(), } else if (env[ref.env] === undefined || env[ref.env] === "") { warnings.push(`${label}: not set in this environment; the launcher must provide it`); } + // Row 194 (brief item 7, sage-1605 pick a): a human create writes the create day as the date, + // and issue writes the real one. Until then the date describes no token, so a store reference + // with no file skips both date checks. Every other reference keeps them. + if (notIssued) return { problems, warnings }; const days = (dateText) => Math.floor((Date.parse(`${dateText}T00:00:00Z`) - now.getTime()) / DAY_MS); if (ref.expires) { const left = days(ref.expires); diff --git a/packages/business/src/instance-settings.mjs b/packages/business/src/instance-settings.mjs index e3a678302..3a8c6aeae 100644 --- a/packages/business/src/instance-settings.mjs +++ b/packages/business/src/instance-settings.mjs @@ -6,7 +6,8 @@ // logs the actor and the old and new values. import { existsSync, readdirSync } from "node:fs"; import { organizationWriter, OrganizationError } from "./organization.mjs"; -import { validateBusinessDocument, businessFilePath } from "./business.mjs"; +import { validateBusinessDocument, businessFilePath, checkBot } from "./business.mjs"; +import { DATE_KEY } from "./credentials.mjs"; import { checkRoutes, creativeHumanOnly } from "./launch-settings.mjs"; import { loadProject, projectFilePath } from "./project.mjs"; import { resolveInstance } from "./resolve.mjs"; @@ -15,7 +16,7 @@ import { refuse } from "./errors.mjs"; import { isPlainObject, canonicalJson } from "./util.mjs"; import { CREATIVE_DEFINITIONS, END_PROTECTED, ID_PATTERN } from "./vocabulary.mjs"; -const SET_KEYS = ["revision", "instance", "op", "definition", "vars", "launch"]; +const SET_KEYS = ["revision", "instance", "op", "definition", "vars", "launch", "tracker"]; const VETO_KEYS = ["revision", "op", "name"]; const VETO_OPS = ["keep", "unkeep", "nohire", "hire"]; const id = value => typeof value === "string" && ID_PATTERN.test(value); @@ -39,9 +40,12 @@ export function deleteRefusal(document, rolesDir, instance) { if (document.launch?.keep?.includes(instance)) { return { code: "organization-instance-kept", message: `${instance} is kept; run veto unkeep first` }; } - const definition = loadRole(rolesDir, entry.definition); - if (definition.credentials.length > 0 || entry.tracker !== undefined || entry.credentials !== undefined) { - return { code: "organization-credentials-out-of-scope", message: `${instance} holds credentials or a tracker bot; deleting it is a hand edit` }; + // Row 194 (brief item 8): delete revokes the agent's store credentials before the write, so an + // instance whose every reference is `store` can go, its tracker bot included (sage-1610 b). A + // file or env reference stays a hand edit. + const refs = Object.values(entry.credentials ?? {}); + if (refs.some(ref => ref?.store !== true)) { + return { code: "organization-credentials-out-of-scope", message: `${instance} holds a file or env credential; deleting it is a hand edit` }; } return null; } @@ -72,20 +76,62 @@ export function deletedDocument(document, instance) { // adds and changes one, so it isn't closed here. The caller runs creativeHumanOnly first. const closed = name => END_PROTECTED.includes(name) && !CREATIVE_DEFINITIONS.includes(name); -function definitionFor(rolesDir, name) { +// Row 194 (brief item 7): the human's add passes credentials true and lifts it. The tester's add, +// change and hire keep it. +function definitionFor(rolesDir, name, { credentials = false } = {}) { if (closed(name)) throw new OrganizationError("organization-definition-refused"); const definition = loadRole(rolesDir, name); if (definition.roleVersion !== 2) throw new OrganizationError("invalid-request", `role definition ${name} is version 1`); - if (definition.credentials.length > 0) { + if (!credentials && definition.credentials.length > 0) { throw new OrganizationError("organization-credentials-out-of-scope", `${name} declares ${definition.credentials.map(c => c.service).join(" and ")} credentials; binding them is a hand edit`); } return definition; } +// Row 194 (brief item 7, sage-1605, sage-1610 a): the human's add of a credentialed definition. +// Each declared service gets a store reference dated the create day (UTC), and no file: the agent +// needs a bus restart, then row 199's issue. A vikunja definition needs args.tracker, an existing +// Vikunja bot the human names. The add makes no Vikunja account. Any other definition refuses it. +function createdCredentials(old, instance, definition, args) { + const services = definition.credentials.map(c => c.service); + const out = {}; + if (services.includes("vikunja")) { + if (!Object.hasOwn(args, "tracker")) { + throw new OrganizationError("organization-tracker-required", `${definition.name} uses vikunja; add needs tracker {bot, botId}, an existing Vikunja bot`); + } + let tracker; + try { + tracker = checkBot(args.tracker, "tracker"); + } catch (e) { + if (e.name === "BusinessError") throw new OrganizationError("invalid-request", e.message); + throw e; + } + // business.mjs checks the same after the write: no two instances and not the sync bot. + const taken = Object.entries(old.roles).filter(([name, entry]) => name !== instance && entry.tracker).map(([name, entry]) => [name, entry.tracker]); + if (old.tracker?.sync) taken.push(["tracker.sync", old.tracker.sync]); + for (const [name, other] of taken) { + if (other.bot === tracker.bot || other.botId === tracker.botId) { + throw new OrganizationError("organization-tracker-bot-taken", `${name} already uses bot ${other.bot} (botId ${other.botId})`); + } + } + out.tracker = tracker; + } else if (Object.hasOwn(args, "tracker")) { + throw new OrganizationError("invalid-request", `${definition.name} uses no vikunja credential, so it takes no tracker`); + } + if (services.length > 0) { + const today = new Date().toISOString().slice(0, 10); + out.credentials = Object.fromEntries(services.map(service => [service, { store: true, [DATE_KEY[service]]: today }])); + } + return out; +} + // levels(name): the thinking levels harness module `name` applies, or null (launch-settings.mjs -// checkRoutes, row 65). -export function instanceSettings({ dir, rolesDir, system, levels = () => null }) { +// checkRoutes, row 65). Row 194 (brief item 8, row 199 D13): revoke(business, instance, how, +// services) revokes the instance's credentials for a fire or a delete and throws +// credential-revoke-failed when it can't. Null in a writer with no bus (the CLI's), which revokes +// nothing. +export function instanceSettings({ dir, rolesDir, system, levels = () => null, revoke = null }) { const writer = organizationWriter({ dir, rolesDir }); // The definitions in rolesDir and whether add and set accept each one. @@ -151,7 +197,13 @@ export function instanceSettings({ dir, rolesDir, system, levels = () => null }) const old = writer.read(business).document; if (op === "delete") { if (Object.keys(args).some(key => !["revision", "instance", "op"].includes(key))) throw new OrganizationError("invalid-request"); - return commit(business, old, planDelete(old, instance), { revision: args.revision, actor }); + const services = Object.keys(old.roles[instance]?.credentials ?? {}); + const beforeWrite = revoke ? () => revoke(business, instance, "delete", services) : null; + const result = commit(business, old, planDelete(old, instance), { revision: args.revision, actor, beforeWrite }); + // sage-1610 (b): the bot user and any token it holds live in Vikunja, which this write + // can't reach (row 199 A5). + const bot = old.roles[instance]?.tracker?.bot; + return bot ? { ...result, tracker: { bot, removeByHand: `remove the Vikunja bot user ${bot} and any token it holds by hand in Vikunja` } } : result; } const next = structuredClone(old); const exists = Object.hasOwn(next.roles, instance); @@ -160,9 +212,13 @@ export function instanceSettings({ dir, rolesDir, system, levels = () => null }) if (exists) throw new OrganizationError("organization-instance-exists"); creativeHumanOnly(old, actor, instance, args.definition); if ((old.retired ?? []).includes(instance)) throw new OrganizationError("organization-instance-retired"); - definitionFor(rolesDir, args.definition); + // Only the human's add binds credentials. The tester keeps the refusal (row 175 W2): the bus + // names the tester's actor "tester", which no human or role may be called. + const definition = definitionFor(rolesDir, args.definition, { credentials: actor !== "tester" }); next.roles[instance] = { definition: args.definition, ...(Object.hasOwn(args, "vars") ? { vars: structuredClone(args.vars) } : {}) }; + Object.assign(next.roles[instance], createdCredentials(old, instance, definition, args)); } else { + if (Object.hasOwn(args, "tracker")) throw new OrganizationError("invalid-request", "tracker is set only by add"); if (!["definition", "vars", "launch"].some(key => Object.hasOwn(args, key))) throw new OrganizationError("invalid-request"); if (!exists) throw new OrganizationError("organization-unknown-instance"); const entry = next.roles[instance]; @@ -273,11 +329,17 @@ export function instanceSettings({ dir, rolesDir, system, levels = () => null }) } const next = structuredClone(old); next.launch.instances = old.launch.instances.filter(entry => entry !== name); - return { ...commit(business, old, next, { revision, actor, context }), delisted: true }; + // Item 8: fire revokes each service of the entry and keeps the store directory (sage-1593). + const services = Object.keys(old.roles[name].credentials ?? {}); + let revoked = null; + const beforeWrite = revoke ? () => { revoked = revoke(business, name, "fire", services); } : null; + const result = commit(business, old, next, { revision, actor, context, beforeWrite }); + return { ...result, delisted: true, ...(revoked ? { credentials: revoked } : {}) }; } - // The checks every write runs, then the write. - function commit(business, old, next, { revision, actor, context }) { + // The checks every write runs, then beforeWrite (a fire's or a delete's revoke), then the write. A + // check that refuses revokes nothing, and a revoke that throws writes nothing. + function commit(business, old, next, { revision, actor, context, beforeWrite = null }) { if (canonicalJson(next) === canonicalJson(old)) throw new OrganizationError("organization-no-change"); // The checks mosaic business validate runs, before the writer publishes anything, then the @@ -305,6 +367,7 @@ export function instanceSettings({ dir, rolesDir, system, levels = () => null }) } } } + if (beforeWrite) beforeWrite(); const receipt = writer.write(business, next, { revision, actor, context }); return { ...read(business), transaction: receipt.transaction, restart: false }; } diff --git a/packages/business/tests/cli.test.mjs b/packages/business/tests/cli.test.mjs index 9c5de8fab..3aa1d52ee 100644 --- a/packages/business/tests/cli.test.mjs +++ b/packages/business/tests/cli.test.mjs @@ -117,6 +117,29 @@ test("validate: credential reference problems exit 2 and name each one", () => { assert.match(r.err, /3 credential reference problem/); }); +// Row 194 (brief item 7, sage-1605 pick a): a human create writes store references dated the +// create day. Until issue writes a file, the date describes no token, so validate skips it. An +// issued store reference keeps the date check. +test("validate: a not-issued store agent dated today passes, and an issued one with a past expiry fails", () => { + const today = new Date().toISOString().slice(0, 10); + const s = setup((doc) => { + doc.roles.coder.credentials = { gitea: { store: true, rotateBy: today }, vikunja: { store: true, expires: today } }; + }); + const r = run(s, "validate", "acme"); + assert.equal(r.code, 0, r.err); + assert.match(r.err, /gitea file .*secrets\/agents\/acme\/coder\/gitea: not issued/); + assert.match(r.err, /vikunja file .*secrets\/agents\/acme\/coder\/vikunja: not issued/); + assert.doesNotMatch(r.err, /expire|rotation/); + + const issued = setup((doc) => { + doc.roles.coder.credentials = { gitea: { store: true, rotateBy: today }, vikunja: { store: true, expires: "2026-01-01" } }; + }); + tokenFile(join(issued.root, "config", "secrets", "agents", "acme", "coder"), "vikunja"); + const e = run(issued, "validate", "acme"); + assert.equal(e.code, 2); + assert.match(e.err, /vikunja file .*coder\/vikunja: expired on 2026-01-01/); +}); + test("validate: a token file inside the repository is refused", () => { const s = setup((doc) => { doc.roles.pm.credentials.gitea.file = join(REPO, "roles", "pm.md"); }); const r = run(s, "validate", "acme"); diff --git a/packages/business/tests/instance-settings.test.mjs b/packages/business/tests/instance-settings.test.mjs index e61739426..cc0271b5c 100644 --- a/packages/business/tests/instance-settings.test.mjs +++ b/packages/business/tests/instance-settings.test.mjs @@ -147,11 +147,37 @@ test("row 165 refuses each validation failure and leaves the file's bytes alone" }); // mos-0823: no instance is written without its credential binding, and nothing binds one here. -test("row 165 refuses an added instance whose definition declares credentials, and says why", () => { +// Row 194 (brief item 7, sage-1605, sage-1610 a): the human's add of a credentialed definition +// writes store references dated today and no file. A vikunja definition takes an existing bot, +// checked on the add path before the file's own validation: its shape, and no other instance or +// the sync bot using its name or id. A definition without vikunja takes none. +test("T19 add of a credentialed definition writes store references dated today, names its bot, and validate exits 0", () => { const f = fixture(); - refuses(f, { instance: "reviewer-2", op: "add", definition: "reviewer" }, "organization-credentials-out-of-scope"); - assert.throws(() => f.settings.set("acme", { revision: f.settings.read("acme").revision, instance: "reviewer-2", op: "add", definition: "reviewer" }, "jason"), - /reviewer declares gitea and vikunja credentials/); + const add = (instance, definition, extra = {}) => ({ instance, op: "add", definition, ...extra }); + refuses(f, add("reviewer-2", "reviewer"), "organization-tracker-required"); + refuses(f, add("reviewer-2", "reviewer", { tracker: { bot: "reviewer-bot", botId: 40 } }), "invalid-request"); + refuses(f, add("reviewer-2", "reviewer", { tracker: { bot: "bot-acme-reviewer-2", botId: 0 } }), "invalid-request"); + refuses(f, add("reviewer-2", "reviewer", { tracker: { bot: "bot-acme-reviewer", botId: 40 } }), "organization-tracker-bot-taken"); + refuses(f, add("reviewer-2", "reviewer", { tracker: { bot: "bot-acme-reviewer-2", botId: f.doc.roles.pm.tracker.botId } }), "organization-tracker-bot-taken"); + refuses(f, add("reviewer-2", "reviewer", { tracker: { bot: "bot-acme-sync", botId: 40 } }), "organization-tracker-bot-taken"); + refuses(f, add("sec-1", "security-reviewer", { tracker: { bot: "bot-acme-sec-1", botId: 40 } }), "invalid-request"); + refuses(f, { instance: "coder", op: "change", vars: {}, tracker: { bot: "bot-acme-coder-2", botId: 40 } }, "invalid-request"); + assert.throws(() => f.settings.hire("acme", { name: "reviewer-3", definition: "reviewer" }, { actor: "chief", context: {} }), + e => e.code === "organization-credentials-out-of-scope"); + + const today = new Date().toISOString().slice(0, 10); + const done = f.settings.set("acme", { revision: f.settings.read("acme").revision, ...add("reviewer-2", "reviewer", { tracker: { bot: "bot-acme-reviewer-2", botId: 40 } }) }, "jason"); + assert.equal(done.restart, false); + assert.deepEqual(JSON.parse(readFileSync(f.file, "utf8")).roles["reviewer-2"], { + definition: "reviewer", + tracker: { bot: "bot-acme-reviewer-2", botId: 40 }, + credentials: { gitea: { store: true, rotateBy: today }, vikunja: { store: true, expires: today } }, + }); + const validated = f.validate(); + assert.equal(validated.status, 0, validated.stderr); + assert.match(validated.stderr, /reviewer-2\/vikunja: not issued/); + // The Console's create form keeps listing it as not accepted. + assert.equal(f.settings.read("acme").definitions.reviewer.accepted, false); }); test("row 165 refuses a definition change to or from one that declares credentials", () => { diff --git a/packages/cli/src/instances.mjs b/packages/cli/src/instances.mjs index bd5470e5b..cd698aef9 100644 --- a/packages/cli/src/instances.mjs +++ b/packages/cli/src/instances.mjs @@ -10,7 +10,7 @@ import { readFileSync } from "node:fs"; import { CliError } from "./errors.mjs"; export const INSTANCES_USAGE = "mosaic business instances BUSINESS [--json] [--tester] | " + - "business instance add BUSINESS INSTANCE --definition DEF [--vars FILE] [--launch] --revision REV [--tester] | " + + "business instance add BUSINESS INSTANCE --definition DEF [--vars FILE] [--launch] [--bot BOT --bot-id N] --revision REV [--tester] | " + "business instance set BUSINESS INSTANCE [--definition DEF] [--vars FILE] [--launch | --no-launch] --revision REV [--tester] | " + "business instance launch|regenerate BUSINESS INSTANCE [--wait SECONDS] [--tester] | " + "business instance terminate BUSINESS INSTANCE [--reason TEXT] [--tester] | " + @@ -19,8 +19,12 @@ export const INSTANCES_USAGE = "mosaic business instances BUSINESS [--json] [--t // The bus answers a refusal with its code alone, so the reason a human reads is here. export const REASONS = { - "organization-credentials-out-of-scope": "this command binds no credentials, so it refuses a definition that declares them " + - "and a definition change on an instance that holds them; that stays a hand edit of the business file", + "organization-credentials-out-of-scope": "only add binds credentials, as store references; set refuses a definition that " + + "declares them and a definition change on an instance that holds them, and delete refuses a file or env reference; " + + "those stay a hand edit of the business file", + // Row 194 (brief item 7, sage-1610 a): add names an existing Vikunja bot; it makes no account. + "organization-tracker-required": "the definition uses vikunja; add needs --bot BOT --bot-id N, an existing Vikunja bot", + "organization-tracker-bot-taken": "another instance already uses that Vikunja bot name or id", "organization-instance-exists": "the business already has that instance; change it with `mosaic business instance set`", "organization-unknown-instance": "the business has no such instance; add it with `mosaic business instance add`", "organization-definition-refused": "this command neither adds nor changes an assistant, and moves no instance to the assistant " + @@ -66,7 +70,7 @@ function parse(args) { if (["--json", "--launch", "--no-launch", "--tester"].includes(arg)) { if (out.flags.has(arg)) throw new CliError(INSTANCES_USAGE, 4); out.flags.add(arg); - } else if (["--definition", "--vars", "--revision", "--wait", "--reason"].includes(arg)) { + } else if (["--definition", "--vars", "--revision", "--wait", "--reason", "--bot", "--bot-id"].includes(arg)) { if (!args[i + 1] || Object.hasOwn(out.values, arg)) throw new CliError(INSTANCES_USAGE, 4); out.values[arg] = args[++i]; } else if (arg.startsWith("--")) throw new CliError(INSTANCES_USAGE, 4); @@ -80,6 +84,10 @@ function setArgs(parsed) { const [, op, , instance] = parsed.positional; const { values, flags } = parsed; if (values["--wait"] !== undefined || values["--reason"] !== undefined) throw new CliError(INSTANCES_USAGE, 4); + const bot = values["--bot"] !== undefined || values["--bot-id"] !== undefined; + if (bot && (op !== "add" || values["--bot"] === undefined || !/^[0-9]{1,15}$/.test(values["--bot-id"] ?? ""))) { + throw new CliError(INSTANCES_USAGE, 4); + } const launch = flags.has("--launch") ? true : flags.has("--no-launch") ? false : undefined; if (parsed.positional.length !== 4 || !["add", "set"].includes(op) || !values["--revision"] || flags.has("--json") || (flags.has("--launch") && flags.has("--no-launch")) || (op === "add" && (!values["--definition"] || launch === false)) || @@ -96,6 +104,7 @@ function setArgs(parsed) { } } if (launch !== undefined) args.launch = launch; + if (bot) args.tracker = { bot: values["--bot"], botId: Number(values["--bot-id"]) }; return args; } @@ -165,7 +174,10 @@ function refusal(code, why) { } function lifecycleLine(business, op, instance, r) { - if (op === "delete") return `business ${business}: deleted ${instance}, now retired\ntransaction ${r.done.transaction}\n`; + if (op === "delete") { + const bot = r.done.bot ? `tracker bot ${r.done.bot}: remove the Vikunja bot user and any token it holds by hand in Vikunja\n` : ""; + return `business ${business}: deleted ${instance}, now retired\ntransaction ${r.done.transaction}\n${bot}`; + } return `business ${business}: ${op === "launch" ? "launched" : "regenerated"} ${instance}, run ${r.done.run} (request ${r.request})\n`; } @@ -189,7 +201,7 @@ export function formatInstances(view) { const accepted = definitions.filter(([, d]) => d.accepted).map(([name]) => name); const bound = definitions.filter(([, d]) => d.services.length).map(([name, d]) => `${name} (${d.services.join(", ")})`); lines.push(`definitions add and set accept: ${accepted.join(", ") || "none"}`); - if (bound.length) lines.push(`definitions that declare credentials, a hand edit: ${bound.join(", ")}`); + if (bound.length) lines.push(`definitions that declare credentials, added with store references and a restart: ${bound.join(", ")}`); if (view.retired?.length) lines.push(`retired: ${view.retired.join(", ")}`); if (view.noHire?.length) lines.push(`the chief may not hire: ${view.noHire.join(", ")}`); return `${lines.join("\n")}\n`; diff --git a/packages/cli/src/launcher.mjs b/packages/cli/src/launcher.mjs index 0c9f133cf..8599e0026 100644 --- a/packages/cli/src/launcher.mjs +++ b/packages/cli/src/launcher.mjs @@ -793,8 +793,9 @@ export function createLauncher({ } const transaction = out?.transaction ?? null; if (transaction === null) return { refusal: "workspace-rename-failed" }; + const bot = out.bot ? { bot: out.bot } : {}; const from = workspaceDir(dataRoot, b.id, r.instance); - if (!existsSync(from)) return { transaction }; + if (!existsSync(from)) return { transaction, ...bot }; const to = join(dirname(from), ".retired", `${r.instance}-${transaction}`); try { mkdirSync(dirname(to), { recursive: true, mode: 0o700 }); @@ -804,10 +805,10 @@ export function createLauncher({ chmodSync(to, 0o700); } catch (e) { log(`request ${r.request} (${r.instance}): workspace rename failed: ${e.message}; left at ${from}`); - return { transaction, refusal: "workspace-rename-failed", why: `${e.message}; left at ${from}` }; + return { transaction, ...bot, refusal: "workspace-rename-failed", why: `${e.message}; left at ${from}` }; } record({ event: "workspace-retired", instance: r.instance, request: r.request, transaction, path: to }); - return { transaction }; + return { transaction, ...bot }; } // endLaunch's answer ({ released, limit? }), or null when it refused. diff --git a/packages/cli/tests/instances.test.mjs b/packages/cli/tests/instances.test.mjs index a866e41cd..2798661be 100644 --- a/packages/cli/tests/instances.test.mjs +++ b/packages/cli/tests/instances.test.mjs @@ -75,7 +75,7 @@ test("row 165 CLI: instance add puts an instance in the file, validate exits 0, // Row 65: the cli fixture gives every instance its route vars, so the view lists them. assert.match(view.out, /^ {2}chief: chief-of-staff \(launcher\) vars \{"harness":"pi","model":"glm-5\.3-flash","thinking":"high"\}$/m); assert.match(view.out, /^definitions add and set accept: .*\bmerge-gate\b.*\bsecurity-reviewer\b/m); - assert.match(view.out, /^definitions that declare credentials, a hand edit: .*\breviewer \(gitea, vikunja\)/m); + assert.match(view.out, /^definitions that declare credentials, added with store references and a restart: .*\breviewer \(gitea, vikunja\)/m); const added = await s.mosaic(["instance", "add", "acme", "sec-1", "--definition", "security-reviewer", "--launch", "--revision", await s.revision()]); assert.equal(added.code, 0, added.err); const entry = s.log().at(-1); @@ -123,7 +123,9 @@ test("row 165 CLI: a refusal names its code and why, exits 2 and keeps the bytes const rev = await s.revision(); const before = readFileSync(s.file, "utf8"); const cases = [ - [["instance", "add", "acme", "reviewer-2", "--definition", "reviewer", "--revision", rev], /^mosaic: organization-credentials-out-of-scope: this command binds no credentials/], + // Row 194 (brief item 7, sage-1610 a): a vikunja definition needs --bot and --bot-id. + [["instance", "add", "acme", "reviewer-2", "--definition", "reviewer", "--revision", rev], /^mosaic: organization-tracker-required: the definition uses vikunja; add needs --bot BOT --bot-id N/], + [["instance", "add", "acme", "reviewer-2", "--definition", "reviewer", "--bot", "bot-acme-reviewer", "--bot-id", "40", "--revision", rev], /^mosaic: organization-tracker-bot-taken: /], [["instance", "set", "acme", "coder", "--definition", "security-reviewer", "--revision", rev], /^mosaic: organization-credentials-out-of-scope: /], [["instance", "add", "acme", "coder", "--definition", "merge-gate", "--revision", rev], /^mosaic: organization-instance-exists: /], [["instance", "set", "acme", "ghost", "--launch", "--revision", rev], /^mosaic: organization-unknown-instance: /], diff --git a/packages/cli/tests/lifecycle.test.mjs b/packages/cli/tests/lifecycle.test.mjs index 41bf27efa..4944b660b 100644 --- a/packages/cli/tests/lifecycle.test.mjs +++ b/packages/cli/tests/lifecycle.test.mjs @@ -412,6 +412,26 @@ test("row 194 D1.1 item 5: the CLI's launch, regenerate, terminate and delete en assert.match((await s.cli(["instances", "acme"])).out, /^retired: sec-1$/m); }); +// Row 194 (brief item 8, sage-1610 b): an instance whose every credential is a store reference +// deletes with its tracker bot. The launcher carries the bot to the close, and the CLI names it for +// removal in Vikunja, since the bus makes and removes no Vikunja account. +test("row 194 T20: a store-only delete with a tracker bot closes naming the bot, and the CLI says to remove it in Vikunja", { skip, timeout: 60000 }, async (t) => { + const p = prepare(t, (doc) => { + doc.roles["rev-2"] = { definition: "reviewer", vars: { harness: "pi", model: "claude-sonnet-5-5", thinking: "high" }, tracker: { bot: "bot-acme-rev-2", botId: 40 }, + credentials: { gitea: { store: true, rotateBy: "2099-01-01" }, vikunja: { store: true, expires: "2099-01-01" } } }; + return doc; + }); + // The agents' store root beside the business files, private as the boot check needs it. + mkdirSync(join(p.root, "config", "secrets", "agents"), { recursive: true, mode: 0o700 }); + const s = await start(t, p); + const revision = JSON.parse((await s.cli(["instances", "acme", "--json"])).out).revision; + const del = await s.cli(["instance", "delete", "acme", "rev-2", "--revision", revision]); + assert.equal(del.code, 0, del.err); + assert.match(del.out, /^business acme: deleted rev-2, now retired\ntransaction [^\n]+\ntracker bot bot-acme-rev-2: remove the Vikunja bot user and any token it holds by hand in Vikunja\n$/); + // The line reads done.bot, which only the launcher's close writes. + assert.equal(Object.hasOwn(JSON.parse((await s.cli(["instances", "acme", "--json"])).out).instances, "rev-2"), false); +}); + test("row 194 T2a: a launch.revoke between the request and the pass closes it launch-revoked with no process; a done that fails once leaves the request taken and the next pass starts nothing", { skip, timeout: 60000 }, async (t) => { const p = prepare(t); const s = await start(t, p); diff --git a/packages/webui/src/bus.mjs b/packages/webui/src/bus.mjs index 902ffdc6b..c46a6ef50 100644 --- a/packages/webui/src/bus.mjs +++ b/packages/webui/src/bus.mjs @@ -101,6 +101,8 @@ const STATUS = { // Row 165 (#1662): role instances. An id already taken is the user's to resolve by reading again. 'organization-instance-exists': 409, 'organization-unknown-instance': 400, 'organization-credentials-out-of-scope': 400, 'organization-launch-not-configured': 400, + // Row 194 (brief item 7, sage-1610 a): only the CLI names a Vikunja bot on add. + 'organization-tracker-required': 400, 'organization-tracker-bot-taken': 409, 'organization-no-change': 400, 'organization-project-mismatch': 400, 'organization-unresolvable-instance': 400, // Row 254 (#1759): library sync. A sync already running, a held divergence and a stale accept are // the user's to resolve by reading library.status again; a missing credential or a failed fetch diff --git a/packages/webui/src/public/agents.js b/packages/webui/src/public/agents.js index 09da683c8..8f3f794a0 100644 --- a/packages/webui/src/public/agents.js +++ b/packages/webui/src/public/agents.js @@ -10,6 +10,9 @@ const REQUEST_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; const POLL_MS = 2000, POLL_LIMIT = 90; const UNKNOWN = 'Outcome unknown. Read the agents again before trying; nothing was retried.'; + // The same text bus.js shows for an instances.set answer (bus.js RESTART_TEXT, NO_RESTART_TEXT). + const RESTART_TEXT = 'Restart needed: the running bus keeps the roles it loaded at start. The Console does not restart it.'; + const NO_RESTART_TEXT = 'No restart: the launcher reads the change at its next launch check.'; const DONE = { launch: 'Launched', regenerate: 'Regenerated', end: 'Terminated', delete: 'Deleted' }; let ctx = null, view = null, busy = false, receipt = '', confirming = null, pending = null, generation = 0; let create = { instance: '', definition: '' }; @@ -107,7 +110,9 @@ if (r.state !== 'closed') continue; const { action, instance } = pending; pending = null; - receipt = r.reason ? `${instance}: ${r.reason}.` : `${DONE[action] ?? 'Done'} ${instance}${r.done?.run ? ` (run ${r.done.run})` : ''}.`; + // sage-1610 (b): a deleted agent's Vikunja bot stays in Vikunja until the human removes it. + const bot = /^bot-[a-z0-9][a-z0-9._-]{0,60}$/.test(r.done?.bot ?? '') ? ` Remove the Vikunja bot user ${r.done.bot} and any token it holds by hand in Vikunja.` : ''; + receipt = r.reason ? `${instance}: ${r.reason}.` : `${DONE[action] ?? 'Done'} ${instance}${r.done?.run ? ` (run ${r.done.run})` : ''}.${bot}`; reread(); return; } @@ -122,7 +127,7 @@ try { answer = await post('/api/instances', { revision: view.revision, instance, op: 'add', definition }); } catch { answer = { ok: false, result: { sent: 'unknown' } }; } busy = false; if (answer === null) return; - if (answer.ok && /^[a-f0-9]{64}$/.test(answer.result?.revision ?? '')) { create = { instance: '', definition: '' }; receipt = `Created ${instance}.`; reread(); } + if (answer.ok && /^[a-f0-9]{64}$/.test(answer.result?.revision ?? '')) { create = { instance: '', definition: '' }; receipt = `Created ${instance}. ${answer.result.restart ? RESTART_TEXT : NO_RESTART_TEXT}`; reread(); } else { receipt = answer.ok ? UNKNOWN : `${refused(answer.result)} Draft kept.`; redraw(); } } diff --git a/packages/webui/src/serve.mjs b/packages/webui/src/serve.mjs index 2c9653c2a..00c0a85f3 100644 --- a/packages/webui/src/serve.mjs +++ b/packages/webui/src/serve.mjs @@ -323,12 +323,16 @@ async function seatSend(req, res, { route, write, preview, log }) { // Row 165 (#1662, Q171): the human adds a role instance or changes one's definition, vars and // launch membership. The Settings boundary (header user, exact Origin, same-origin Fetch Metadata, // JSON within 16 KiB, strict keys) and one bus call, `instances.set`, through the human transport. -// The writer refuses a definition that declares credentials. The answer's `restart` says whether +// The writer refuses a change to a definition that declares credentials. Row 194 (brief item 7): +// an add of one gets store references, and a vikunja one needs a bot, which this route doesn't +// take (sage-1610 a), so it refuses organization-tracker-required. The answer's `restart` says whether // the running bus must restart before the change counts; the Console never restarts it. const INSTANCE_KEYS = ['revision', 'instance', 'op', 'definition', 'vars', 'launch']; // The bus answers a refusal with its code alone, so the reason the page shows is here. const INSTANCE_REASONS = { 'organization-credentials-out-of-scope': 'that definition declares credentials, or the instance holds them. The Console binds no credentials, so that stays a hand edit of the business file', + 'organization-tracker-required': 'that definition uses vikunja and needs a Vikunja bot. The Console names no bot; use mosaic business instance add with --bot and --bot-id', + 'organization-tracker-bot-taken': 'another instance already uses that Vikunja bot', 'organization-instance-exists': 'the business already has that instance; change it instead', 'organization-unknown-instance': 'the business has no such instance; add it instead', 'organization-definition-refused': 'this form neither adds nor changes an assistant, and moves no instance to the assistant definition; an assistant changes only in the Assistant section', diff --git a/packages/webui/tests/agents-browser.test.mjs b/packages/webui/tests/agents-browser.test.mjs index 4ca0ff270..9416ce57c 100644 --- a/packages/webui/tests/agents-browser.test.mjs +++ b/packages/webui/tests/agents-browser.test.mjs @@ -69,6 +69,27 @@ test('row 194 T16 Settings Agents: unavailable read-only, launch follows its req await click('[data-agent-confirmed]'); await wait('document.querySelector("#agents-receipt")?.textContent==="Deleted coder."'); assert.deepEqual(await b.evaluate('posts.at(-1)'),['/api/instances',{revision:REV,instance:'coder',op:'delete'}]); + // sage-1610 (b): a delete that closes with a tracker bot names it for removal in Vikunja; a bot + // name outside the pattern is not shown. + for (const [bot,text] of [['bot-acme-coder','Deleted coder. Remove the Vikunja bot user bot-acme-coder and any token it holds by hand in Vikunja.'],[hostile,'Deleted coder.']]) { + await b.evaluate(`replies.push([200,{request:'${ID}',at:'x'}]);polls.push([200,{request:'${ID}',action:'delete',instance:'coder',state:'closed',done:{run:null,transaction:'t-9',refusal:null,bot:${JSON.stringify(bot)}},cancelled:null}]);true`); + await click('[data-agent-action="delete"][data-agent-name="coder"]'); + await wait('!!document.querySelector("[data-agent-confirmed]")'); + await click('[data-agent-confirmed]'); + await wait(`document.querySelector("#agents-receipt")?.textContent===${JSON.stringify(text)}`); + } + assert.equal(await b.evaluate('window.injected===true'),false); + + // Create names whether the bus must restart, in the words bus.js uses for the same answer (M63). + const typeCreate=(field,value)=>b.evaluate(`(()=>{const e=document.querySelector('[data-agent-create="${field}"]');e.value=${JSON.stringify(value)};e.dispatchEvent(new Event('change',{bubbles:true}));return true;})()`); + for (const [restart,text] of [[true,'Created rev-2. Restart needed: the running bus keeps the roles it loaded at start. The Console does not restart it.'],[false,'Created rev-2. No restart: the launcher reads the change at its next launch check.']]) { + await typeCreate('instance','rev-2'); + await typeCreate('definition','reviewer'); + await b.evaluate(`replies.push([200,{...${JSON.stringify(view)},transaction:'t-3',restart:${restart}}]);true`); + await b.evaluate('document.querySelector("#agent-create-form").requestSubmit();true'); + await wait(`document.querySelector("#agents-receipt")?.textContent===${JSON.stringify(text)}`); + assert.deepEqual(await b.evaluate('posts.at(-1)'),['/api/instances',{revision:REV,instance:'rev-2',op:'add',definition:'reviewer'}]); + } // Terminate carries the typed reason; a closed refusal shows its reason. await b.evaluate(`(()=>{const e=document.querySelector('[data-agent-reason="coder"]');e.value='done for today';e.dispatchEvent(new Event('input',{bubbles:true}));return true;})()`); diff --git a/packages/webui/tests/instances.test.mjs b/packages/webui/tests/instances.test.mjs index 4482a5aef..e450b16ce 100644 --- a/packages/webui/tests/instances.test.mjs +++ b/packages/webui/tests/instances.test.mjs @@ -78,11 +78,11 @@ test('row 165 Console: the signed-in human adds an instance through a real broke }); assert.equal(checked.status, 0, checked.stderr); - // A definition that declares credentials, a definition change on an instance holding them and a + // A vikunja definition, which needs a bot the Console doesn't take (sage-1610 a), a definition change on an instance holding them and a // stale revision: each refused with its code and why, nothing written, nothing logged. const before = readFileSync(file, 'utf8'), entries = log().length; for (const [args, status, code, why] of [ - [{ revision: added.body.revision, instance: 'reviewer-2', op: 'add', definition: 'reviewer' }, 400, 'organization-credentials-out-of-scope', /declares credentials, or the instance holds them\. The Console binds no credentials/], + [{ revision: added.body.revision, instance: 'reviewer-2', op: 'add', definition: 'reviewer' }, 400, 'organization-tracker-required', /uses vikunja and needs a Vikunja bot\. The Console names no bot; use mosaic business instance add with --bot and --bot-id/], [{ revision: added.body.revision, instance: 'coder', op: 'change', definition: 'security-reviewer' }, 400, 'organization-credentials-out-of-scope', /hand edit of the business file/], [{ revision: current.revision, instance: 'gate-1', op: 'add', definition: 'merge-gate' }, 409, 'revision-conflict', /changed since you read it/], [{ revision: added.body.revision, instance: 'asst-2', op: 'add', definition: 'assistant' }, 400, 'organization-definition-refused', /^organization-definition-refused: this form neither adds nor changes an assistant, and moves no instance to the assistant definition;/],