Compare commits
127
Commits
sp8
..
pickup-launch
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
196505e6ef | ||
|
|
f7c0e4f46c | ||
|
|
5c975faddd | ||
|
|
462215b4bd | ||
|
|
d0293d6602 | ||
|
|
912138ff61 | ||
|
|
4a8d310cd5 | ||
|
|
c28ca57af6 | ||
|
|
255c1575bb | ||
|
|
0ba50111f6 | ||
|
|
dab07f0ff5 | ||
|
|
561ff77e48 | ||
|
|
e1642be760 | ||
|
|
b23ccdfc12 | ||
|
|
57af33630d | ||
|
|
17b972b92d | ||
|
|
d531d7181d | ||
|
|
67e1ff193d | ||
|
|
9a3004cba4 | ||
|
|
4b833d23e9 | ||
|
|
05be6c62bd | ||
|
|
c9fad00d25 | ||
|
|
4c8527fcd3 | ||
|
|
2d44750b96 | ||
|
|
9343baffff | ||
|
|
38ea639d70 | ||
|
|
fc558df31a | ||
|
|
56cc7b59dd | ||
|
|
c641dbfbc9 | ||
|
|
eb1146ebad | ||
|
|
4b5d027361 | ||
|
|
80ce06851d | ||
|
|
b39d5e2ff3 | ||
|
|
c85c768a4a | ||
|
|
b7649ecd73 | ||
|
|
0354452971 | ||
|
|
bbbefb3f28 | ||
|
|
2f91ff5bea | ||
|
|
1ca3a38f86 | ||
|
|
cb80b2b8a8 | ||
|
|
fd300b4fe3 | ||
|
|
a88302d6eb | ||
|
|
820f45e474 | ||
|
|
2e9a2068bd | ||
|
|
fe6c22e0f2 | ||
|
|
9eed814d3c | ||
|
|
7ee606cda2 | ||
|
|
b2d52b57c1 | ||
|
|
cbf1836bd7 | ||
|
|
6fe3625fae | ||
|
|
24551c9eea | ||
|
|
cad9cd057f | ||
|
|
4f24501801 | ||
|
|
02e053866a | ||
|
|
ff096afa27 | ||
|
|
70af20e29d | ||
|
|
d92cdefc1d | ||
|
|
9994f89790 | ||
|
|
4a9c7a931c | ||
|
|
5c7194e05b | ||
|
|
f0bf85befe | ||
|
|
c26879637a | ||
|
|
2fc97a3edb | ||
|
|
68df55130e | ||
|
|
6ad1d33dd1 | ||
|
|
5fba4726dc | ||
|
|
69ce460f91 | ||
|
|
307f88be3e | ||
|
|
bfd3ed6811 | ||
|
|
5b6b39f080 | ||
|
|
2d7d7be5ca | ||
|
|
f73c761ad3 | ||
|
|
8b4a26dd2b | ||
|
|
11d2b43b3a | ||
|
|
8aefc0f7a9 | ||
|
|
9cff3255e6 | ||
|
|
d50d79cddd | ||
|
|
fb3bd16052 | ||
|
|
13615e12b9 | ||
|
|
bd29e756a5 | ||
|
|
6bd9be78ac | ||
|
|
3a84f46b6e | ||
|
|
208439814a | ||
|
|
7c6571768f | ||
|
|
3597e0daf6 | ||
|
|
3116f43e65 | ||
|
|
c66f1ec00c | ||
|
|
9400e0d94d | ||
|
|
a9912983e6 | ||
|
|
626321608f | ||
|
|
5f965cdb30 | ||
|
|
8296d33100 | ||
|
|
69ac78b97e | ||
|
|
a2a7df73df | ||
|
|
789e2bcdd4 | ||
|
|
02df2a3a25 | ||
|
|
b982404963 | ||
|
|
5dd940165d | ||
|
|
ed4f45ed23 | ||
|
|
79df01f1de | ||
|
|
d7b98b4698 | ||
|
|
0f29fe0d92 | ||
|
|
32be3a01bc | ||
|
|
f97e0d3aeb | ||
|
|
eebdb2f0ce | ||
|
|
5373b110ac | ||
|
|
3885f4628b | ||
|
|
ba9933309b | ||
|
|
0785af8129 | ||
|
|
d1b01329bc | ||
|
|
c7aecbffa9 | ||
|
|
bb2f79f3d9 | ||
|
|
e24e7e93a2 | ||
|
|
387f73a7a4 | ||
|
|
61371adb10 | ||
|
|
b913f0f4c8 | ||
|
|
bfd2cc5e79 | ||
|
|
3e53af3941 | ||
|
|
359b3299b4 | ||
|
|
65f7288cea | ||
|
|
211b32ef1a | ||
|
|
163972e08e | ||
|
|
23e504f331 | ||
|
|
23b5e24ebc | ||
|
|
266f3a45ff | ||
|
|
0c35eeed9d | ||
|
|
e6ab8bc1fd |
No files matched your search
@@ -6347,3 +6347,9 @@ R5 quote fallback room (#797 D3, 2026-11-06, MVP3 lead): r4 review P2 found that
|
||||
2026-11-09 UTC, PRD 1.20 and defect l (#1873, #1886; PRs #1887 03fe321b1 and #1888 7a97cfc4f). PRD 1.20: Jason approved draft 2 at 22:57Z ("The file looks fine other than that"; the Montage module name stays deferred). The PRD now has 118 requirements, with REQ-WS-1..8, REQ-AGENT-1..3, REQ-SYS-1..2, REQ-ACCT-1..2 and REQ-SETUP-1..2 added and REQ-ASSIST-1, REQ-USER-1, REQ-TASK-1 and REQ-WEB-3 amended. Builder Codex Terra xhigh declined to commit because stack-copy failed 20/1 (node-gyp missing from the test Node's npm); that failure is pre-existing on 483eccb3d, so the lead committed. Sol review APPROVE 0 (word-for-word diff against draft 2, catalog order, both requirements tests). Defect l: before, an agent that declared a store credential made the next bus start refuse, because Credentials refuses a missing store root and only issue() created it. After: start creates the root 0700 when any reference names the store; a root that exists with loose modes or as a symlink still refuses. Two new credential-verbs tests fail on the parent. Bus suite 171 files one at a time, 1713/0 (Node 26.12.1, env -i). Sol review APPROVE 0. uiorg redeployed at 7a97cfc4f, 23:15Z. Follow-up: the stack-copy node-gyp test environment. Reports: /mnt/storage/scratch/mosaic-lead/reports/{prd120-land,prd120-review,defectl-review}.md.
|
||||
|
||||
2026-11-10 UTC, unified workspace U1 and SYS1 (#1873; PRs #1889 d35447005 and #1890 2c6556ab1). U1, before: each org page read only its own bus and nothing read every org at once. After: /api/workspace returns projects, sessions, inbox, tasks and metrics from every org the owner holds, each row tagged with its org and each org with a state (ok, starting, down, timeout, invalid); `mosaic console restart` and `mosaic org reload <org>` send the F3 routes. Sol review CHANGES 0/2 on 2109458b3: malformed data from one org turned the whole read into a 503, and the per-org deadline left sockets and transport children running. Terra fix 0672d5fe8 validates each org's result inside its boundary and carries an absolute deadline and AbortSignal through the status check and transport; the new workspace-failures test is 0/10 on the parent and 10/0 on the fix. The lead re-pinned the webui bus.mjs hash in bus channel-proof (the deliberate signal/deadline change; nonces, argv and limits unchanged) and amended as d35447005. SYS1, before: no system-type kind. After: a system-type plug-in kind with five modules (business-management, coding, creative-writing, marketing, montage), an org enable list under plugins.system-type, owner-only project selection with an append-only project_system_types table (migration 3t-3u) and CLI verbs; the modules grant no tools yet (REQ-SYS-2 deferred). Sol review CHANGES 1/2 on a9629f332: the restore guard did not count project_system_types, the CLI channel did not admit the two project verbs, and the #811 migration-reader pin still expected 18 steps. Lead fix 2c6556ab1 (rebased on d35447005) adds the table to COUNTED and LISTED with refusal and in-run recount tests, admits both verbs with a run()-level channel test (red on the unfixed channel), and moves the pin to 19 steps ending 3t-3u; fix files 323/0 and rebase overlap files 63/0 (Node 26.12.1, one file at a time, env -i). Full gate on a9629f332 4040/5: the two stack-release pins above, and tester-reads 3/3, which also fails on 1616d1dd6 (project.mjs:95 refuses an org --tester init; follow-up). Correction to the uiorg deploy at 00:50Z: the deploy script switched the tree without the offline schema migration, so all five buses refused to start (normal startup refuses an older schema by design). The lead ran migrate-schema.mjs for the five org stores (3t to 3u, all ready), restarted the buses (201 each) and added the migration to the deploy script with stop-on-refusal. test3 refused writer-locked and stays down, as before. Reports: /mnt/storage/scratch/mosaic-lead/reports/{u1-review,u1-fix,org-sys1-build,sys1-review}.md.
|
||||
|
||||
2026-11-13 UTC, starter packs replace system types (#1873; PRs #1949 c0a60ed3a, #1950 1e65ff3f8, #1951 755ba3fa8, #1952 1ced0e392, #1953 dfef78834, #1955 9a649abf8, #1956 991eb8c33, #1957 34dd33101, #1959 0251acdad and #1960 e6ab8bc1f; final e6ab8bc1f). Backfilled 2026-11-16 by lane docs-1116 from uidev/LEAD-1110.md and git; the Lead wrote no entry at the time. Before: SYS1 (PR #1890, 2c6556ab1) made system types a plug-in kind with five modules, an org enable list under plugins.system-type and an append-only project_system_types table (migration 3t-3u); the modules granted no tools. After: the design docs/plans/2026-11-12_starter-packs-design.md landed as PR #1949 (doc only) after three fix rounds; Jason's FULL SEND at 21:06Z on 11-12 answered Q1 to Q3: system-type removed outright with no legacy, SP10 dropped, SP9 deletes the kind and drops project_system_types. Slices in landing order: SP3 the org keys packs, board and workflows and the applyPack writer op; SP1 the starter-pack plug-in kind and its checker; SP7 workflow guidance in the harness prompt; SP2 the five shipped packs; SP4 pack, board and workflow verbs, routes and CLI words; SP6 board labels, pack picker and workflow editor on the WebUI organization page; SP5 the chief applies a pack's non-definition half and raises hires from its proposals; SP8 the owner saves an organization's shape as a template; SP9 system types removed outright and bus schema 3v-3w dropping project_system_types. Test counts, Lead check then lane gate: SP3 98 files 1294/0, 1828/1; SP1 51 files 708/0, 2854/1; SP7 1281/0, 2537/1; SP2 150/0, 1556/1 at 18add86cb before its rebase onto SP7; SP4 4848/2, 6049/1; SP6 371 files 4233/1, 8262/23; SP5 229 files 2721/0, 8061/2; SP8 415 files 4650/1, 8125/2; SP9 497 files 5542/1, 8655/28. Each single Lead check red is CHAT-01 (host Python lacks jsonschema), red on base too; SP4's second red was the fixture federation-host.mjs wrongly in the run list, and Lead check lists are filtered to *.test.mjs since. The lane gate reds the log names are base or environment reds: CHAT-01, 19 agents/*/work probes, budget-supervisor 3v, ui-browser SSO, six v1 .woodpecker files and one claude-session timing test. Every slice was deployed to uiorg 7350 and verified; at e6ab8bc1f (03:46Z on 11-13) the offline 3v-3w migration ran on all five live stores, 5 stop 200, 5 bus schema 3w ready, 5 setup 201, the system-types route and its js returned 404, and no org file named system-type, so no wipe was needed. Corrections: the Lead's 21:38Z carry that SP2 pack steps must drop id was reversed at 21:46Z: pack steps keep id (SP1 checker) and SP4 drops id when it copies a step into the org file. The Lead's SP7 brief misstated the workflow shape; the lane built to the SP3 loader, which was correct. SP5's last commit before landing changed the broker canonical string builder after its re-check with no suite test; the Lead compared it with organization canonicalJson (7/7 same) and accepted it, and the integer-key pin test is deferred. SP9's first gate, before its rebase, ran packages/cli/live/ui-browser.test.mjs, which binds its own fixture on 17443, a lane rule breach; nothing was listening before or after, and the file was left out of later gates. The 'bus recover' deploy step refuses rc=3 in the agent shell on every deploy since D1; it is harmless while bus stop succeeds. Reports: /mnt/storage/scratch/mosaic-lead/reports/{starter-pack-design-build,starter-pack-design-recheck2,sp1-build-1112-starter-packs,sp2-build-1112-starter-packs,sp3-build-1112-starter-packs,sp4-build,sp5-build,sp6-build,sp7-build,sp8-build,sp9-build,sp9-rebase-recheck}.md.
|
||||
|
||||
2026-11-15 UTC, applying a starter pack is the hire decision, with the route fallback (#1873; PR #1963, b913f0f4c; commits 359b3299b and 3e53af394 lane pd, bfd2cc5e7 and b913f0f4c lane pr2). Backfilled 2026-11-16 by lane docs-1116 from uidev/LEAD-1110.md and git. Before: section 3 of the starter packs design said apply never hires; a person's apply left the pack's hires as proposals for the chief to raise or for a person with org.hire to start. On 7350 at 65f7288ce Jason applied packs and saw no agents. His ruling at 20:48Z on 11-14, verbatim: "Damnit. If I choose a starter pack and apply it, that is a decision!" After, lane pd: a person's apply (pack.apply.console from the WebUI, pack.apply from the CLI) raises one hire decision per proposal after the pack's commit and resolves it, with the evidence an inbox approval leaves. The owner's apply approves flagged and credential lines; a member with org.hire hires only proposals with neither, and the rest wait for the owner as awaiting-owner. An agent apply hires nothing. Hires are written with no credential material, so services show unbound until someone binds them. The design's section 3 carries a 2026-11-14 change note. Route fallback: at 22:03Z the Lead found every 7350 chief had model null, so pack hires would refuse pack-hire-route-missing on Jason's orgs. Ruling at 22:13Z: the hire route is the chief's, else the org assistant's harness and model, else refuse; lane pr2 stacked on pd. Tests: pd gate 3957/0 at its first commit, review changes 6 (2 P2) fixed or deferred, re-check APPROVE; Lead check of pd with pr2 333 files 3813/1, the red a control-board scan.test mtime-tie flake in a file neither lane touched, 70/0 three times alone. Lead ruling on the re-check's P2 1: a member pack hire surface is a follow-up row, because a new transport for a member hire cap is a security boundary and the owner path covers apply; Jason said "proceed". Deployed b913f0f4c at 01:03Z on 11-15: stop 5, schema 3w 5, setup 5. The Lead ran pack hire on faceless (montage ideas-1 and research-1, coding pm-1, coder-1 and reviewer-1, all on fixture-deterministic) and acme (business-management pm-1 and research-1 on opus), each with routeFrom assistant. Related fix the same night: Jason reported "adapter exited 127" in Messages. Lane r127 found the Lead's deploy-uiorg.sh (a scratch script, not in the repository) started the Console without MOSAIC_CLAUDE_BIN, so claude-code sessions ran the /usr/bin/claude wrapper whose target under /opt the sandbox does not bind. The Lead patched the script and landed PR #1964 387f73a7a, which makes exit 127 name the missing program; Lead check 16 files 285/0. Both assistant kinds replied on 7350 at 387f73a7a by 03:33Z. Reports: /mnt/storage/scratch/mosaic-lead/reports/{pd-build,pd-review,pd-recheck,pr2-build,pr2-review,r127-build,r127-review,r127-recheck}.md.
|
||||
|
||||
2026-11-15 UTC, single pane slices sp1 to sp14 (#1873; PRs #1965 to #1978; final c26879637). Backfilled 2026-11-16 by lane docs-1116 from uidev/LEAD-1110.md and git. Before: a Side by side page sat in the sidebar beside the organization pages, and Jason's walkthrough on 65f7288ce (20:48Z on 11-14) found agents from an applied pack not visible. His direction: #/dashboard system-wide, no organization URL base, side-by-side Assistant threads in place of Side by side, and the 3-click rule. The Lead ruled at 03:33Z on 11-15 that #/orgs/<id>/... stays the address of an org page but is a route inside one global shell, with no reload and no mode switch. After, slice by slice (PR, tip, Lead check, lane gate): sp1 shell, #/dashboard system page, org drill-in without reload, a down org says so (#1965, c7aecbffa, 128/0, 1031/0, two reviews, nine findings fixed); sp2 dashboard polish, bare org route, theme, one down banner (#1966, d1b01329b, 132/0); sp3 system Inbox (#1967, 3885f4628, 111/0, 892/0; a theme fix and a render-order fix were read by the Lead, not a reviewer); sp5 system Agents, landed before sp4 (#1968, f97e0d3ae, 89/0 plus unified-workspace 18/0, 745/0); sp4 system Tasks, which the Lead rebased onto f97e0d3ae with three one-line union conflicts (#1969, ed4f45ed2, 131/0, 937/0 before the rebase); sp6 system Assistant with up to three threads from any org side by side, the open set in the hash, Side by side removed from the sidebar and #/side-by-side landing on Assistant (#1970, 789e2bcdd, 95/0, 1472/0, four review rounds); sp7 seven small fixes (#1971, a9912983e, 141/0, 1483/0, three review rounds); sp8 KPI tiles from real reads only and the 3-clicks table (#1972, c66f1ec00, 119/0 plus org-live-edit-browser 4/0 alone, 1490/2 with two load flakes that each passed alone twice, three small fixes not re-reviewed); sp9 read-only workflow list and graph per org (#1973, 7c6571768, 143/0, 1504/0); sp10 workflow edit in the graph (#1974, bd29e756a, 146/0, 1515/0); sp11 eight fixes including agent counts that disagreed and Done this week (#1975, 5b6b39f08, 164/0, 1527/0, three review rounds); sp12 agent drawer from #/agents and org session rows (#1976, 69ce460f9, 196/0, 191 files 1538/0); sp13 organization page fits its width, #/orgs/<id>?query parses, drawer state pending until the instances read answers (#1977, 68df55130, 205/0, 192 files 1547/0); sp14 Queue card off the organization page, running not read where an answer carries no runs, kept Assistant pane messages keyed by an opaque viewer, drawer repaint without new page reads (#1978, commits 2fc97a3ed and c26879637, 218/0, 192 files 1549/0, review changes 1 with the P2 fixed, re-check approve). sp14 adds `viewer` to /api/config (32 hex of sha256 over provider, iss and sub; `local` without sign-in) and adds no route. The Lead ruled at landing of sp13 that the Queue card leaves the organization page; #/queue stays. State at c26879637: system pages #/dashboard, #/inbox, #/agents, #/tasks and #/assistant; org pages at #/orgs/<id>/... inside the same shell. Each slice was deployed to uiorg 7350 with five buses up (deploy log per tip under reports/deploy-<sha>.log); sp1 and sp8 to sp14 record 5 stop, 5 schema 3w and 5 setup. An acme assistant reply was checked live after sp1 and sp6 to sp14; after sp4, #/agents showed the acme assistant running mid-reply; the log records no reply check for sp2, sp3 and sp5. Corrections: sp15 was launched at 19:23Z on a wrong premise. The Lead had told Jason, from reading code only, that the broker's async instances path was the real cause of the sp12 drawer saying not running. The lane stopped at BASE with no diff: the shipped runtime answers instances synchronously (runtime.mjs:1263), and a probe on a real startBroker showed the running and alive arrays present. The sp12 live shot had a 9000 ms screenshot budget that caught the paint before the read; the sp13 shot at 30000 ms shows State running. sp15 closed at 19:26Z with no change and no bus row; sp14's running not read item now only guards a failed or odd read. The Lead's lesson: prove a fault live before naming it a cause. The sp14 live shots read 0 running because they were taken right after the bus restart, before any session started. Follow-ups after sp14: empty space under Active agent sessions at 1440, a drawer pending gap, viewer read once per tab with an unsalted hash, the open pane set kept per browser, and the Dashboard org table scrolling sideways at 390. Reports: /mnt/storage/scratch/mosaic-lead/reports/{sp1-build,sp2-build,sp3-build,sp4tasks-build,sp5agents-build,sp6threads-build,sp7polish-build,sp8kpis-build,sp9workflows-build,sp10workflowedit-build,sp11fixes-build,sp12agentdrawer-build,sp13orgpagefit-build,sp14orgpagetruth-build,sp15businstancesruns-build}.md.
|
||||
@@ -2124,3 +2124,9 @@ are never rewritten or removed; corrections are new entries.
|
||||
2026-11-09 UTC | Mos (lead, Claude Opus 5.5) | Organizations F3 fix round and landing (#1873) | PR #1884 merged a8f9f0957; review P3 fixed, P1 README corrected with follow-up #1883; 195/0 focused suite; uiorg redeployed 22:45Z.
|
||||
2026-11-09 UTC | Mos (lead, Claude Opus 5.5) | PRD 1.20 landing and defect l (#1873, #1886) | PR #1887 merged 03fe321b1, PR #1888 merged 7a97cfc4f; both Sol reviews APPROVE 0; bus suite 1713/0; uiorg redeployed 23:15Z; U1, U2 and U4a builds dispatched.
|
||||
2026-11-10 UTC | Mos (lead, Claude Opus 5.5) | U1 and SYS1 landings (#1873) | PR #1889 merged d35447005, PR #1890 merged 2c6556ab1; both Sol reviews CHANGES, fixed (U1 by Terra, SYS1 by the lead); uiorg at 2c6556ab1 after the missed 3t-3u store migration was run; deploy script now migrates.
|
||||
2026-11-10 UTC | Sage (Lead) | redact3 landing (#1873) | PR #1912 merged 96c900d21 at 23:56Z, gate 268 files 3412/0, Opus review changes 2 fixed; uiorg deploy started. Backfilled 2026-11-16 by lane docs-1116 from uidev/LEAD-1110.md and git.
|
||||
2026-11-11 UTC | Sage (Lead) | Organizations, redaction, accounts, dev readiness and credential binding landings (#1873) | PRs #1913 to #1944 merged, a4eed1e21 to 6d0e9f89b: A2, golden1, TI, redact4, A3, M3 with M3-recon, acct-anchor, org-names, polish2, run sheet doc, cred-bind design, PL1, base-reds, redact5, T1, timing2, cleanup-time, A4, supcost, defscan, redact6, AU, D4, D3, harness-scan, D2, D1, CB01, bus-stop, agent-guard, proxy-ui, CB2. Jason approved CB0 to CB5 at 17:55Z. Per-landing check counts are in uidev/LEAD-1110.md. Backfilled 2026-11-16 by lane docs-1116.
|
||||
2026-11-12 UTC | Sage (Lead) | E1, E2, CB3, E3, CB4 and starter packs design, SP3, SP1, SP7, SP2, SP4 landings (#1873) | PRs #1945 8827905ba (E1), #1946 666f4d686 (E2), #1947 0b8fe202b (CB3), #1948 2ad4b30eb (E3), #1949 c0a60ed3a (design), #1950 1e65ff3f8 (SP3), #1951 755ba3fa8 (SP1), #1952 1ced0e392 (SP7), #1953 dfef78834 (SP2), #1954 95c2ce143 (CB4), #1955 9a649abf8 (SP4). Jason's FULL SEND on starter packs at 21:06Z: system types removed outright, SP10 dropped. The log first dated the E1 landing 11-11; its own correction and git put it at 02:48Z on 11-12. Backfilled 2026-11-16 by lane docs-1116.
|
||||
2026-11-13 UTC | Sage (Lead) | Starter packs SP6, SP5, SP8, SP9 and CB5 landings; E2E round 6 started (#1873) | PRs #1956 991eb8c33 (SP6), #1957 34dd33101 (SP5), #1958 a9d72b3cd (CB5, credential binding CB0 to CB5 complete), #1959 0251acdad (SP8), #1960 e6ab8bc1f (SP9). uiorg 7350 at e6ab8bc1f: bus schema 3w on all five stores, system-types route 404. E2E R6 CLI and WebUI lanes started 23:59Z. Backfilled 2026-11-16 by lane docs-1116.
|
||||
2026-11-14 UTC | Sage (Lead) | E2E round 6 fixes and the pack apply ruling (#1873) | E2E R6 CLI 0/0/7, WebUI 0/3/15. PR #1961 23b5e24eb (f6w) and PR #1962 65f7288ce (f6c) merged; uiorg verified at 65f7288ce 02:40Z. Jason's walkthrough at 20:48Z: applying a starter pack is a decision, plus the single pane direction. Route fallback ruled 22:13Z. Backfilled 2026-11-16 by lane docs-1116.
|
||||
2026-11-15 UTC | Sage (Lead) | Pack decision, exit 127 fix and single pane slices sp1 to sp14 (#1873) | PR #1963 b913f0f4c (pd with pr2), PR #1964 387f73a7a (r127), PRs #1965 to #1978 (sp1 to sp14), final c26879637 at 20:19Z; each deployed to uiorg 7350. sp15 launched 19:23Z on a wrong premise (a bus instances fault that did not exist) and closed 19:26Z with no change. Backfilled 2026-11-16 by lane docs-1116.
|
||||
@@ -346,8 +346,12 @@ For local development on a named instance only, `mosaic bus start BUSINESS --dev
|
||||
|
||||
The hire form and the autonomy panel from a terminal (E2, #1873, P1-3). `mosaic org role-templates|hire|fire|change ORG` and `mosaic org autonomy ORG [set|review]` send the page's own request to the running Console's org route (`/api/orgs/ORG/decisions/hire/templates|start`, `/api/orgs/ORG/autonomy[/review]`), as `org reload` does, so the Console applies the same owner, `--send`, origin, body and live-session checks and the same bus verbs run (`hire.templates.console`, `hire.start.console`, `autonomy.get.console`, `autonomy.set.console`, `autonomy.review.console`). `hire` and `change` read the templates first and send the chosen template's name and sha256, as the form does. `autonomy set` needs the 64-hex `--revision` from `mosaic org autonomy ORG` and sends every setting the panel sends, with only the named ones changed; a stale revision is refused `revision-conflict`; an empty `--authority-resolver ""` clears the resolver, as emptying the panel's field does. These verbs need a named instance (`MOSAIC_CONFIG` set to `~/.config/mosaic-NAME/config.json`) whose Console runs with `--dev-local-owner`; the default instance is refused with exit 3. A Console refusal exits 3 with the Console's code and message; `outcome-unknown` exits 1; an unknown template exits 2. Every one of these verbs, reads included, refuses inside an agent run. `mosaic tasks create|edit|archive` are the task board's three writes: the arguments pass the board's own check (`workspace-tasks.mjs parseTaskWrite`) and go to the bus as the person (`tasks.create|edit|archive`, human transport), so the bus runs its human, field, digest and archive checks. A stale `--expect` is refused `task-conflict`; read the digest with `mosaic tasks --json`.
|
||||
|
||||
Starter packs (#1873): `mosaic org pack list`, `mosaic org pack preview ID PACK [--project P]`, `mosaic org pack apply ID PACK --digest D [--project P]` and `mosaic org pack hire ID PACK [--project P]` call the bus as the organization's human (`packs`, `pack.preview`, `pack.apply`, `pack.hire`). Ruling 2026-11-14 ("If I choose a starter pack and apply it, that is a decision!"): a person's apply is the hire decision. After the pack commits, the same act hires each proposed agent through the hire-decisions path and the receipt's `hires` lists `{name, state, decision | code}` per proposal (`hired`, `exists`, `open`, `awaiting-owner`, `refused`); a `hired` or `awaiting-owner` line adds `routeFrom: 'chief' | 'assistant'`. The owner's apply approves the flagged and credential lines; a credential line is approved but not bound, so the agent's launch refuses `credential-unbound` until its services are bound. The bus verb `pack.hire.console` also takes a member's console cap with `org.hire`: it hires only the proposals with no flagged or credential line, and the rest wait for the owner in the inbox. No member surface calls it yet: the WebUI packs routes and the CLI `pack` words are the owner's. An owner's pack hire also replaces and approves a hire this pack's own member hire left in the inbox; the old decision is withdrawn only after the new hire applies. Two pack hires on one organization at once: the second refuses `organization-busy`; an apply whose hire loop did not run still answers the apply's receipt with `hireError` and no hires. An agent's apply hires nothing. `pack hire` reruns the loop on a pack already applied and hires none twice; it refuses `pack-not-applied` when the pack has no packs entry, and a hire runs as the chief of staff's harness and model, else the organization assistant's (the instance whose definition is `assistant`), and a proposal refuses `pack-hire-route-missing` only when neither has both. All pack words refuse inside an agent run (exit 3). The WebUI pack card's "Hire the N proposed agents" is `POST /api/orgs/<id>/packs/hire`. Details: `packages/cli/README.md`, `packages/bus/README.md` and `packages/webui/README.md`, "Starter pack hires"; design: `docs/plans/2026-11-12_starter-packs-design.md` section 3.
|
||||
|
||||
The bus and Console lifecycle verbs refuse inside an agent run (agent-guard, #1873): `mosaic bus start`, `bus stop`, `bus restart` and `bus recover`, and `mosaic console start`, `console stop` and `console restart`, and `mosaic org archive` and `org delete`, which stop the organization's bus, and `mosaic org restore`, which starts it (`org restore --no-bus` starts nothing and is not refused), and `mosaic org role-templates`, `hire`, `fire`, `change` and `autonomy` (E2). Each exits 3 with `refused: this runs only from a human shell, outside any agent run (found MARKER in the environment)` before it reads anything. It checks the environment it is given and its own process environment, so a sanitized environment does not hide a marker. A usage error (a missing or extra argument, `--pm` with `--no-launch`, or a bad `--dev-insecure-bind`/`--dev-allow-host`) still comes first (exit 4). `mosaic bus status` and `mosaic console status` stay open to agents. The Console's Restart bus and Restart Console controls keep working: the Console starts its bus host with its own environment, which carries no marker, and Restart Console relaunches the Console under its supervisor without going through the CLI. The markers are the ones `packages/cli/src/transport.mjs` lists. The check is cooperative: a process that drops the markers from its environment is not stopped by it.
|
||||
|
||||
Refusal lines (E2E6, #1873). A refusal that has a next step prints it on a second line, `mosaic: next: ...`, after the unchanged message, so callers that match the message keep working. `mosaic bus status`, `start`, `stop` and `restart` on a stale bus host lock exit 3 with `mosaic: stale bus host lock ...` and `mosaic: next: if the bus host died, clear it with mosaic bus recover ORG; recover refuses while the host still runs`. A human-transport verb whose bus is not running (no socket, or the connect refused before anything was sent) exits 3 with `bus-not-running: the bus for ORG is not running, so the request was not sent` and a next line naming `mosaic bus start ORG` and `mosaic bus recover ORG`; `outcome-unknown` (exit 1) stays for a request that left and got no answer. `mosaic org definitions` with an unknown organization, an unknown or malformed name, or a bad id prints one refusal line (exit 3; `unknown-organization` only when the organization file itself is missing, `definitions-unreadable` when `templates` cannot read the roles directory) or, for a bad id, the usage (exit 4), with no stack trace and no host path. Pack, board and workflow refusals carry their next step as `template save` does. `mosaic console start` and `console stop` clear a `console/start.lock` whose named supervisor (pid and start time) is gone, once, with a `cleared a console start lock left by process PID, which is gone` warning; a lock whose holder still runs, or that names no holder, refuses and stays. A start or stop releasing its lock marks it released through its own descriptor and removes the path only while it is still that file, so a lock put back after its release is cleared the same way, with a `cleared a console start lock its holder had released` warning. An `autonomy-precondition` refusal from the bus carries the check that failed (owner notices off, no tested reverse, a resolver without the right, no `review.verdict` holder, no enforced budget, out of the loop only from near the loop, the trail review or near-loop decision missing); the human-transport child writes only the code, so a terminal `org autonomy set` shows the Console's message. `mosaic org template save` writes free text verbatim: it never rewrites prose, and the preview lists every field that mentions the organization id, a project id, an agent name or the owner's account, with the names it mentions, for the owner to edit before sharing. Saving under a name already saved for the account refuses `template-exists` (exit 2, nothing written) with a next line to save under another name or list the saved ones with `mosaic org template list ORG`.
|
||||
|
||||
The instance processing switch is separate from per-business launches off/on.
|
||||
`mosaic halt` durably stops managed processing across every business in the
|
||||
selected configuration's data root. The bus stays up for reads and human
|
||||
|
||||
@@ -374,6 +374,48 @@ exactly as if a person had made them by hand. The steps:
|
||||
`projects.<p>.agents`; those entries refuse instance credential material
|
||||
(`BOUND_KEYS`, `agent-levels.mjs:21`).
|
||||
|
||||
**2026-11-14 change (#1873, lane pd).** Jason's ruling: "Damnit. If I
|
||||
choose a starter pack and apply it, that is a decision!" This replaces
|
||||
"Apply never hires" above for a person's apply. The `packs` entry and the
|
||||
proposals stay as written; what changes is who acts on them:
|
||||
- A person's apply (`pack.apply.console` from the WebUI, `pack.apply` from
|
||||
the CLI) is the hire decision. In the same act, after the pack's commit,
|
||||
the broker raises one hire decision per proposal through the
|
||||
hire-decisions path and resolves it, leaving the evidence an inbox
|
||||
approval leaves: the decision row, its resolved event, `human.input`,
|
||||
`hire.consume`, the `hire.apply` event and `action.allowed pack.hire`.
|
||||
The hired entry carries `hireDecision`.
|
||||
- Invariant 7 still decides each line. The owner's apply approves the
|
||||
flagged and credential lines. A member with `org.hire` hires only the
|
||||
proposals with neither a flagged nor a credential line; each of the
|
||||
others is raised as an open decision that waits for the owner in the
|
||||
inbox (`awaiting-owner`). The owner's later pack hire withdraws such a
|
||||
decision and hires the agent itself. An
|
||||
agent apply hires nothing: the hire stays a proposal for the chief, and
|
||||
a hire verb from an agent is refused `human-required`.
|
||||
- Credentials take the smallest rule. The hire writes the entry with no
|
||||
credential material, so its services show `unbound` and a launch is
|
||||
refused `credential-unbound` until someone binds them. The owner's
|
||||
approval covers the credential lines; it binds nothing and reads no
|
||||
secret.
|
||||
- The route is the chief of staff's resolved harness and model. With
|
||||
none, that proposal is refused `pack-hire-route-missing` and stays open.
|
||||
Note 2026-11-14 (lead ruling, lane pr2): the route is the chief's, else
|
||||
the organization assistant's (the instance whose definition is
|
||||
`assistant`; the one named `assistant` when there are several, else the
|
||||
first in key order), and the refusal applies only when neither resolves
|
||||
a harness and a model. Hire lines carry `routeFrom`.
|
||||
- `pack.hire` / `pack.hire.console` (`mosaic org pack hire ID PACK
|
||||
[--project P]`, `POST /api/orgs/<id>/packs/hire`) runs the same loop on
|
||||
a pack already applied, refused `pack-not-applied` otherwise. A proposal
|
||||
whose instance exists is `exists`, and one with an open decision is
|
||||
`open` or `awaiting-owner`, so neither a re-apply nor `pack hire` ever
|
||||
hires twice. A project pack hires into `projects.<p>.agents`.
|
||||
- Each hire line in the receipt is `{name, state, decision | code}` with
|
||||
state `hired`, `exists`, `open`, `awaiting-owner` or `refused`. The
|
||||
packs read adds `hired` and `open` (with each proposal's reason) to each
|
||||
applied entry, and the instances read names the pack an agent came from.
|
||||
|
||||
### The surface
|
||||
|
||||
| Layer | Name |
|
||||
|
||||
@@ -586,3 +586,4 @@ git history + Gitea issues.
|
||||
|
||||
- 2026-09-26 (sage, lead): Jason's ruling: Sage leads the project, Darkwing is a collaborating seat, more seats to follow, development stays in T3 for now. The fleet Sage seat that took Invoice Ninja coordination outside Jason's instructions is being decommissioned; moving work onto the new stack is the fix. Suites all green. Rows 24 and 25 pushed (1685deb4..43d7574d). Open: about 11 days of uncommitted agent work in the tree (row 16 launch files, row 22, #1512, WUI evidence), 23 untracked aws-* skill directories in skills/ from 2026-09-21, and Jason's target for the next phase.
|
||||
- 2026-10-13 (sage, lead): Jason's PM re-test on 664199f7 is finished (Mos; PM run rcc0f72be8b17; Vikunja #228). Paging, the Board's held roles, the Messages page and the #229 loop (coder push 010d30cb, review, approve, PM close) all worked; #230 and #231 are done, #232 stays open for the secrets-path probe. Two faults checked and dropped: the reviewer did run the tests before its verdict, and the PM's clone did hold the row 95 Board code. Two filed: row 104 (#1598) seat git identity, row 105 (#1599) a review request says whether a reviewer is running. Rows 96, 101-105 briefed; row 85 released to build. Row 85's live steps, any bus restart and row 102's public/ change each need Mos's go. Row 100 waits on Jason (Vikunja #257). Formatting, Jason's direction: no formatting row now. Chat output will be formatted in the TUI and WebUI the way chat interfaces usually do it, made our own; T3 Code's chat is his example. Carry it into the TUI and WebUI chat work.
|
||||
- 2026-11-15 (sage, lead; written 2026-11-16 by lane docs-1116 from uidev/LEAD-1110.md and git): single pane state at c26879637 (#1873, PRs #1965 to #1978). One WebUI shell. System pages #/dashboard, #/inbox, #/agents, #/tasks and #/assistant cover every organization; #/queue stays its own page. Organization pages are #/orgs/<id>/... routes inside the same shell, with no reload and no mode switch (Lead ruling 03:33Z 11-15). Side by side is gone from the sidebar; the Assistant page holds up to three threads from any organization side by side, and #/side-by-side lands there. The organization page has KPI tiles from real reads, a workflow list and graph with edit, an agent drawer (?agent=<org>:<name>), and no Queue card. Where an instances answer carries no runs the page says running was not read, never 0. /api/config names an opaque `viewer` that keys kept Assistant pane messages. Applying a starter pack is the hire decision (PR #1963 b913f0f4c). Follow-ups: empty space under Active agent sessions at 1440, a drawer pending gap, viewer read once per tab with an unsalted hash, the open pane set kept per browser, the Dashboard org table scrolling sideways at 390. Detail: BUILD-LOG.md 2026-11-15 entries.
|
||||
@@ -1240,16 +1240,22 @@ Added in version 1.3 (Q155).
|
||||
changes it, not in one rewrite (Q155). Until it converts, Technical
|
||||
considerations lists where it is hard-coded.
|
||||
|
||||
### System types
|
||||
### Starter packs
|
||||
|
||||
Added in version 1.20.
|
||||
|
||||
- **REQ-SYS-1.** System types are a plug-in kind. Its modules include
|
||||
coding, creative writing, marketing, Mosaic Montage (the OpenMontage
|
||||
fork) and business management. An organization enables a list of them.
|
||||
- **REQ-SYS-2.** A project may use any system type its organization
|
||||
enables, and none is required. An agent working in a project gets the
|
||||
toolsets of the system types that project uses.
|
||||
- **REQ-SYS-1.** Starter packs are a plug-in kind. Mosaic Stack ships five:
|
||||
coding, creative writing, marketing, Mosaic Montage and business
|
||||
management. A pack is a starting configuration of role definitions,
|
||||
proposed hires, a board style and workflow templates. An organization or
|
||||
project copies a pack in once and then owns and changes what it copied. A
|
||||
user can save an organization or project as their own template and apply it
|
||||
the same way.
|
||||
- **REQ-SYS-2.** Applying a pack grants nothing by itself. Every agent it
|
||||
proposes is hired through the hire decision (REQ-AGENT-3), bounded by the
|
||||
chief's own role, with any line above it approved by the owner. A pack never
|
||||
sets credentials, rights, the autonomy setting or plug-in choices. Removing
|
||||
a pack removes nothing it copied.
|
||||
|
||||
### Meta-harness
|
||||
|
||||
|
||||
@@ -1135,3 +1135,40 @@ Each write records `human.input`. A task read returns a `digest` that can be sup
|
||||
`task-conflict`. Existing assignees may remain after a role is removed, but new assignees
|
||||
must be current roles. Automatic tail placement and an explicitly occupied position refuse
|
||||
`task-position-full` when there is no room; no task row is written.
|
||||
|
||||
## Starter pack hires (ruling 2026-11-14, #1873)
|
||||
|
||||
"If I choose a starter pack and apply it, that is a decision!" A person's
|
||||
`pack.apply` (the organization's human, outside any run) or `pack.apply.console`
|
||||
hires the proposals of the packs entry it wrote, once the apply has committed.
|
||||
An agent's `pack.apply` hires nothing. `pack.hire` (the owner's human session)
|
||||
and `pack.hire.console` (the owner's or a member's console cap, needing
|
||||
`org.hire`) run the same loop on a pack already applied; with no packs entry they
|
||||
refuse `pack-not-applied`.
|
||||
|
||||
Each proposal goes through `#raiseHire` and `hire.resolve.console`, the path an
|
||||
inbox approval takes: the decision row, its resolved event, `human.input`,
|
||||
`hire.consume`, the hire's commit and `hire.apply` event, plus
|
||||
`action.allowed {operation: 'pack.hire', pack, version, origin, project, hire,
|
||||
decision}`. The route is the chief of staff's resolved harness and model (the
|
||||
`launch.by` instance), else the organization assistant's: the instance whose
|
||||
definition is `assistant`, the one named `assistant` when there are several,
|
||||
else the first in key order. Thinking is carried when set. With neither the
|
||||
proposal refuses `pack-hire-route-missing`. A `hired` or `awaiting-owner` line
|
||||
carries `routeFrom: 'chief' | 'assistant'`. The entry is written with
|
||||
no credential material, so a credential line leaves its services `unbound`.
|
||||
A proposal whose instance exists is `exists`; one an open hire decision names is
|
||||
`open`, so nothing is hired twice. The owner approves every line, and replaces
|
||||
an open decision an earlier hire of the same pack left for the owner: the new
|
||||
hire is raised and applied first, and the old decision is withdrawn only once it
|
||||
has applied, so a replacement that refuses leaves the old one in the inbox. A member's flagged or credentialed hires are raised after
|
||||
the others, left open for the owner's inbox (`awaiting-owner`). A hire that
|
||||
refuses records `action.allowed {operation: 'pack.hire.refused', code}` and the
|
||||
loop goes on. The `packs` read adds `hired` and `open` to each applied entry,
|
||||
and the `instances` read adds `pack: {id, origin, project}` to each instance a
|
||||
pack hire created. An `awaiting-owner` line this pack's own hire raised carries
|
||||
`fromPack: true` (the owner's pack hire would replace it). One pack hire loop
|
||||
runs per business at a time; a second refuses `organization-busy`. An apply
|
||||
whose hire loop throws after the apply committed still answers the apply's
|
||||
receipt, with no hires and the loop's code as `hireError`. No member surface
|
||||
calls `pack.hire.console` yet; the Console's packs routes are the owner's.
|
||||
@@ -639,22 +639,6 @@ CREATE TRIGGER request_snapshot_events_no_replace BEFORE INSERT ON request_snaps
|
||||
CREATE TRIGGER request_project_events_no_update BEFORE UPDATE ON request_project_events BEGIN SELECT RAISE(ABORT, 'request_project_events is append-only'); END;
|
||||
CREATE TRIGGER request_project_events_no_delete BEFORE DELETE ON request_project_events BEGIN SELECT RAISE(ABORT, 'request_project_events is append-only'); END;
|
||||
CREATE TRIGGER request_project_events_no_replace BEFORE INSERT ON request_project_events WHEN EXISTS (SELECT 1 FROM request_project_events WHERE seq=NEW.seq OR (business=NEW.business AND project=NEW.project AND revision=NEW.revision)) BEGIN SELECT RAISE(ABORT, 'request_project_events is append-only'); END;
|
||||
-- Per-project selections are a human-authored append-only settings trail.
|
||||
CREATE TABLE project_system_types (
|
||||
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
at TEXT NOT NULL,
|
||||
business TEXT NOT NULL,
|
||||
project TEXT NOT NULL REFERENCES projects(id),
|
||||
types TEXT NOT NULL,
|
||||
by TEXT NOT NULL
|
||||
) STRICT;
|
||||
CREATE INDEX project_system_types_project ON project_system_types (business, project, seq);
|
||||
CREATE TRIGGER project_system_types_no_update BEFORE UPDATE ON project_system_types BEGIN SELECT RAISE(ABORT, 'project_system_types is append-only'); END;
|
||||
CREATE TRIGGER project_system_types_no_delete BEFORE DELETE ON project_system_types BEGIN SELECT RAISE(ABORT, 'project_system_types is append-only'); END;
|
||||
CREATE TRIGGER project_system_types_no_replace BEFORE INSERT ON project_system_types WHEN EXISTS (SELECT 1 FROM project_system_types WHERE seq = NEW.seq) BEGIN SELECT RAISE(ABORT, 'project_system_types is append-only'); END;
|
||||
CREATE TRIGGER project_system_types_business BEFORE INSERT ON project_system_types
|
||||
WHEN (SELECT business FROM projects WHERE id = NEW.project) IS NOT NEW.business
|
||||
BEGIN SELECT RAISE(ABORT, 'a system types row belongs to its project business'); END;
|
||||
-- U4a (#1873): the task store built into each organization, the default task-tracker module
|
||||
-- (REQ-TASK-1). Each row is the whole task after one write, so a task's state is its latest row
|
||||
-- and the rows are its history: who wrote it (a role and run, or the person), when, under which
|
||||
|
||||
+254
-99
@@ -11,7 +11,7 @@ import { initializeControl, processingStatus } from '../../processing-control/sr
|
||||
import { NAME as HARNESS_NAME } from '../../plugins/src/kinds.mjs';
|
||||
import { loadRequirements } from '../../tasks/src/requirements.mjs';
|
||||
import { MERGE, LandingRefusal, readLanding } from './landing.mjs';
|
||||
import { pluginName, ID_PATTERN, THREAD_DEFINITIONS, END_PROTECTED, forkProblem, forkUrl, credentialKind, validArgv, commandAllowed, HOST_ID, CREATIVE_DEFINITIONS, giteaName, parseGiteaUrl, covers, grantScopeOf, grantInScope } from '../../organization/src/vocabulary.mjs';
|
||||
import { pluginName, ID_PATTERN, THREAD_DEFINITIONS, END_PROTECTED, forkProblem, forkUrl, credentialKind, validArgv, commandAllowed, HOST_ID, CREATIVE_DEFINITIONS, giteaName, parseGiteaUrl, covers, grantScopeOf, grantInScope, SYSTEM_ONLY_REFUSAL, systemOnly } from '../../organization/src/vocabulary.mjs';
|
||||
|
||||
// Kept closed while S1 lands; its vocabulary is the integration authority.
|
||||
export const ACTIONS = Object.freeze([
|
||||
@@ -178,7 +178,7 @@ export const USER_VERBS = Object.freeze(['project.list', 'thread.create', 'threa
|
||||
'thread.share', 'thread.unshare', 'thread.shares']);
|
||||
// Row 252 (#1753, design sections 2-3): the only verbs a Console owner cap reaches. Every other verb
|
||||
// refuses it human-required before its own checks, and these refuse every other cap.
|
||||
export const CONSOLE_VERBS = Object.freeze(['system-types.console', 'project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
|
||||
export const CONSOLE_VERBS = Object.freeze(['project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'pack.hire.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
|
||||
// Task 3 (#1839): and the owner's intake controls. The reads and writes are the same lifecycle methods the PM's
|
||||
// unsuffixed verbs reach, with the owner's verified (provider, iss, sub) as the only caller; the PM-only
|
||||
// request.question and the PM's own reads keep their unsuffixed names and refuse a console cap.
|
||||
@@ -233,7 +233,7 @@ const TEMPLATE_KEYS = Object.freeze({
|
||||
export const TEMPLATE_BUS_KEYS = Object.freeze(Object.fromEntries(Object.entries(TEMPLATE_KEYS).flatMap(([verb, k]) => [[verb, k], [`${verb}.console`, k]])));
|
||||
// The codes a template refusal keeps, each with its reason: a field path or a checked name, never a
|
||||
// value from the organization file and never a host path.
|
||||
const TEMPLATE_CODES = Object.freeze(['template-secret-suspected', 'invalid-request', 'human-required', 'not-configured', 'pack-plan-stale', 'starter-pack-invalid', 'starter-pack-template-changed']);
|
||||
const TEMPLATE_CODES = Object.freeze(['template-secret-suspected', 'template-exists', 'invalid-request', 'human-required', 'not-configured', 'pack-plan-stale', 'starter-pack-invalid', 'starter-pack-template-changed']);
|
||||
// Row 175: the organization verbs a tester may call. Its writes run every check the human's do
|
||||
// and log actor `tester`; row 176 adds routes reads; limits.set, organization.set and organization.revision refuse it.
|
||||
export const TESTER_ORGANIZATION_VERBS = Object.freeze(['limits', 'plugins', 'instances', 'plugins.set', 'instances.set', 'routes.set', 'routes']);
|
||||
@@ -280,6 +280,11 @@ 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;
|
||||
// proxy-pickup (#1873): the one plain line a bus without a proxy client gives for not-configured.
|
||||
// The runtime writes it from static text and a refusal code; only that line passes, and never
|
||||
// into refusal evidence.
|
||||
const proxyCause = error => error instanceof BusError && error.code === 'not-configured' && typeof error.reason === 'string' && error.reason.length <= 300 ? error.reason : undefined;
|
||||
|
||||
export class BusError extends Error {
|
||||
// Guidance is static policy text; never quote arguments or file bytes here.
|
||||
constructor(code, reason) {
|
||||
@@ -289,9 +294,12 @@ export class BusError extends Error {
|
||||
if (reason !== undefined) this.reason = reason;
|
||||
}
|
||||
}
|
||||
const fail = (code) => {
|
||||
throw new BusError(code);
|
||||
// E2E6 fix 7: a refusal may carry a reason, static text that names which check failed; it never
|
||||
// quotes an argument or file bytes.
|
||||
const fail = (code, reason) => {
|
||||
throw new BusError(code, reason);
|
||||
};
|
||||
const BUDGET_UNCOVERED = 'no enforced budget covers new agents; authority away from the loop needs one';
|
||||
const object = (x) => x !== null && typeof x === 'object' && !Array.isArray(x);
|
||||
// #1873 CB5: a copy binding proposal leaves the bus only as its copy and its change. The copy id,
|
||||
// incarnation, definition pin, services, grant ids and slots stay in the raise event, which the
|
||||
@@ -636,6 +644,9 @@ export class Broker {
|
||||
#builtinBinding;
|
||||
#organization;
|
||||
#hires;
|
||||
// Businesses with a pack hire loop running: a second loop on the same business refuses
|
||||
// organization-busy rather than raising a second decision for the same agent.
|
||||
#packHiring = new Set();
|
||||
#autonomyHost;
|
||||
#pluginService;
|
||||
#credentialVerbs;
|
||||
@@ -6083,7 +6094,7 @@ export class Broker {
|
||||
const args = request.args ?? {};
|
||||
if (!object(args)) fail('invalid-request');
|
||||
return Promise.resolve().then(() => this.#proxyPage(request.verb, args, { business: s.business, human: s.human }))
|
||||
.catch(error => { throw this.#refused(s, new BusError(PROXY_PAGE_CODES.includes(error.code) ? error.code : 'proxy-down'), { verb: request.verb }); });
|
||||
.catch(error => { throw this.#refused(s, new BusError(PROXY_PAGE_CODES.includes(error.code) ? error.code : 'proxy-down', proxyCause(error)), { verb: request.verb }); });
|
||||
}
|
||||
// #1873: the fence clear takes restart evidence, which the runtime re-proves on the host
|
||||
// before the lock clears. Owner only, before every other gate, like the proxy page verbs.
|
||||
@@ -6177,28 +6188,6 @@ export class Broker {
|
||||
return result;
|
||||
}).catch(e => { throw this.#refused(s, e instanceof BusError ? e : new BusError(e.code ?? 'request-failed'), request); });
|
||||
}
|
||||
if (request.verb === 'system-types.console') {
|
||||
if (!s.console || s.human !== this.#business(s.business).human) fail('human-required');
|
||||
keys(args, ['project']);
|
||||
if (!this.#organization) fail('not-configured');
|
||||
const enabled = this.#organization(s.business, 'system-types.current', {}, s.human);
|
||||
if (!Array.isArray(enabled)) fail('not-configured');
|
||||
let project = null;
|
||||
if (args.project !== undefined) {
|
||||
const id = identifier(args.project);
|
||||
if (!this.#store.get('SELECT 1 FROM projects WHERE id=? AND business=?', id, s.business)) fail('project-not-found');
|
||||
const row = this.#store.get('SELECT types FROM project_system_types WHERE business=? AND project=? ORDER BY seq DESC LIMIT 1', s.business, id);
|
||||
const selected = row ? JSON.parse(row.types) : [];
|
||||
project = { project: id, selected, active: selected.filter(x => enabled.includes(x)), inactive: selected.filter(x => !enabled.includes(x)) };
|
||||
}
|
||||
return Promise.resolve(this.#organization(s.business, 'system-types.installed', {}, s.human))
|
||||
.then(installed => {
|
||||
if (!Array.isArray(installed)) fail('not-configured');
|
||||
const result = { installed, enabled, project };
|
||||
this.#secretCheck(result);
|
||||
return result;
|
||||
});
|
||||
}
|
||||
if (request.verb === 'project.remote.get.console' || request.verb === 'project.remote.set.console') {
|
||||
if (!s.console || s.human !== this.#business(s.business).human) fail('human-required');
|
||||
if (!this.#organization) fail('not-configured');
|
||||
@@ -6284,16 +6273,16 @@ export class Broker {
|
||||
if (CREDENTIAL_VERBS.includes(request.verb)) return this.#requestCredential(s, request.verb, structuredClone(args));
|
||||
if(['autonomy.get.console','autonomy.set.console','autonomy.review.console','decision.reverse.console'].includes(request.verb)) {
|
||||
this.#autonomyOwner(s);
|
||||
return this.#autonomyConsole(s,request.verb,structuredClone(args)).catch(e=>{throw this.#refused(s,e instanceof BusError?e:new BusError(e.code??'outcome-unknown'),request);});
|
||||
return this.#autonomyConsole(s,request.verb,structuredClone(args)).catch(e=>{throw this.#refused(s,e instanceof BusError?e:new BusError(e.code??'outcome-unknown',e instanceof BusError?e.reason:undefined),request);});
|
||||
}
|
||||
if (s.hireMembership && !['hire.preview.console','hire.resolve.console','hire.start.console','hire.templates.console'].includes(request.verb)) fail('human-required');
|
||||
if (s.hireMembership && !['hire.preview.console','hire.resolve.console','hire.start.console','hire.templates.console','pack.hire.console'].includes(request.verb)) fail('human-required');
|
||||
if(request.verb==='decision.resolve' && !s.human) {
|
||||
if(s.tester)fail('tester-refused');
|
||||
keys(args,['id','choice','note'],['id','choice']);identifier(args.id);
|
||||
}
|
||||
if(request.verb==='decision.resolve' && !s.human && ['role.hire','role.fire','role.change'].includes(this.#decision(s,args.id).action)) {
|
||||
const d=this.#decision(s,args.id);
|
||||
if(d.route_to!=='human')return this.#resolveAuthority(s,args).catch(e=>{throw this.#refused(s,e instanceof BusError?e:new BusError(e.code??'outcome-unknown'),request);});
|
||||
if(d.route_to!=='human')return this.#resolveAuthority(s,args).catch(e=>{throw this.#refused(s,e instanceof BusError?e:new BusError(e.code??'outcome-unknown',e instanceof BusError?e.reason:undefined),request);});
|
||||
}
|
||||
if(request.verb==='hire.templates.console') {
|
||||
keys(args,[]);const caller=this.#hireCaller(s);
|
||||
@@ -6307,14 +6296,32 @@ export class Broker {
|
||||
const input=request.verb==='decision.raise' ? (()=>{ keys(args,['action','hire'],['action','hire']); if(args.action!==`role.${args.hire?.op}`)fail('invalid-request'); return args.hire; })() : args;
|
||||
// #1873 SP5: a raise from a pack's recorded proposal; the pin, not the caller, names the role.
|
||||
if(request.verb==='hire.raise' && object(args) && Object.hasOwn(args,'proposal'))
|
||||
return Promise.resolve().then(()=>this.#raiseHire(s,this.#proposalHire(s,args),false)).catch(e=>{throw this.#refused(s,new BusError(e.code??'invalid-request'),request);});
|
||||
return this.#raiseHire(s,input,request.verb==='hire.start.console').catch(e=>{throw this.#refused(s,new BusError(e.code??'invalid-request'),request);});
|
||||
return Promise.resolve().then(()=>{const r=this.#proposalHire(s,args);return this.#raiseHire(s,r.input,false,{pack:r.pack});}).catch(e=>{throw this.#refused(s,new BusError(e.code??'invalid-request',e instanceof BusError?e.reason:undefined),request);});
|
||||
return this.#raiseHire(s,input,request.verb==='hire.start.console').catch(e=>{throw this.#refused(s,new BusError(e.code??'invalid-request',e instanceof BusError?e.reason:undefined),request);});
|
||||
}
|
||||
if(request.verb==='decision.preview.console' && ['role.hire','role.fire','role.change'].includes(this.#decision(s,args.id).action))return this.#hireConsole(s,'hire.preview.console',args).catch(e=>{throw this.#refused(s,new BusError(e.code??'outcome-unknown'),request);});
|
||||
if(request.verb==='decision.preview.console' && ['role.hire','role.fire','role.change'].includes(this.#decision(s,args.id).action))return this.#hireConsole(s,'hire.preview.console',args).catch(e=>{throw this.#refused(s,new BusError(e.code??'outcome-unknown',e instanceof BusError?e.reason:undefined),request);});
|
||||
if (['hire.preview.console','hire.resolve.console'].includes(request.verb))
|
||||
return this.#hireConsole(s,request.verb,args).catch(e=>{throw this.#refused(s,new BusError(e.code??'outcome-unknown'),request);});
|
||||
return this.#hireConsole(s,request.verb,args).catch(e=>{throw this.#refused(s,new BusError(e.code??'outcome-unknown',e instanceof BusError?e.reason:undefined),request);});
|
||||
if (request.verb === 'grants.scope' || request.verb === 'grants.scope.set')
|
||||
return this.#grantScopeVerb(s, request.verb, structuredClone(args));
|
||||
// Ruling 2026-11-14: hire a pack's proposed agents after the apply that recorded them, through
|
||||
// the same loop a person's apply runs. pack.hire is the owner's CLI human cap; pack.hire.console
|
||||
// the owner's or a member's console cap. An agent and the tester never get here.
|
||||
if (request.verb === 'pack.hire' || request.verb === 'pack.hire.console') {
|
||||
if (s.tester) fail('tester-refused');
|
||||
if ((request.verb === 'pack.hire.console') !== !!s.console) fail('human-required');
|
||||
keys(args, ['pack', 'project'], ['pack']);
|
||||
if (typeof args.pack !== 'string' || !/^(saved:)?[a-z0-9][a-z0-9._-]{0,63}$/.test(args.pack)) fail('invalid-request');
|
||||
if (Object.hasOwn(args, 'project') && (typeof args.project !== 'string' || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(args.project))) fail('invalid-request');
|
||||
const callerOf = () => this.#packHireCaller(s);
|
||||
if (!callerOf().rights.includes('org.hire')) fail('right-required');
|
||||
return Promise.resolve().then(async () => {
|
||||
const state = this.#organization ? this.#organization(s.business, 'pack.state', { pack: args.pack, project: args.project ?? null }, s.human, {}) : null;
|
||||
if (!state?.entry) fail('pack-not-applied');
|
||||
const out = await this.#packHires(s, callerOf, { pack: args.pack, project: args.project ?? null });
|
||||
this.#secretCheck(out); return { pack: state.entry.id, ...out };
|
||||
}).catch(e => { if (e instanceof BusError) throw this.#refused(s, e, request); this.#packFail(e); });
|
||||
}
|
||||
// #1873 SP4: the owner's starter packs, board and workflows. Only the organization's owner calls
|
||||
// them: the human cap from the CLI, or the owner's console cap (a hire member's cap is refused
|
||||
// above). The tester is refused before any argument check. A preview and an apply raise no
|
||||
@@ -6359,6 +6366,20 @@ export class Broker {
|
||||
if (spends && wrote) this.#store.transaction(() => this.#consumeAuthority(s, 'organization.change'));
|
||||
this.#secretCheck(value); return value;
|
||||
};
|
||||
// Ruling 2026-11-14: a person's apply is the hire decision. Once the apply has committed, the
|
||||
// same call hires the proposals (#packHires); an agent's apply never hires.
|
||||
// The apply has committed by then, so a hire loop that throws (organization-busy, a store error)
|
||||
// still returns the apply's receipt, with no hires and the loop's code as hireError.
|
||||
if (verb === 'pack.apply' && !agent) {
|
||||
const hired = async (value) => {
|
||||
let out;
|
||||
try { out = await this.#packHires(s, () => this.#packHireCaller(s), { pack: args.pack, project: args.project ?? null }); }
|
||||
catch (e) { out = { hires: [], hireError: e instanceof BusError && typeof e.code === 'string' ? e.code : 'outcome-unknown' }; }
|
||||
return done({ ...value, ...out });
|
||||
};
|
||||
return Promise.resolve(result).then(value => value, packFail).then(hired);
|
||||
}
|
||||
if (verb === 'packs') return Promise.resolve(result).then(value => done(this.#packsEnrich(s.business, value)), packFail);
|
||||
return result?.then ? result.then(done, packFail) : done(result);
|
||||
}
|
||||
// #1873 SP8: saving a template. Only the organization's owner: the human cap from the CLI or the
|
||||
@@ -6394,7 +6415,7 @@ export class Broker {
|
||||
if (["limits", "plugins", "instances", "routes", "organization.revision"].includes(request.verb)) keys(args, []);
|
||||
else if (request.verb === "plugins.set") {
|
||||
keys(args, ["revision", "plugins", "usage"], ["revision", "plugins"]);
|
||||
if (s.tester && object(args.plugins) && (Object.hasOwn(args.plugins, 'model-provider') || Object.hasOwn(args.plugins, 'system-type'))) fail('human-required');
|
||||
if (s.tester && object(args.plugins) && Object.hasOwn(args.plugins, 'model-provider')) fail('human-required');
|
||||
}
|
||||
// Row 165 (#1662): instances.set is human-only and outside ORGANIZATION_KEYS, so
|
||||
// organization.set and the chief of staff's tool never reach it (sage-0918).
|
||||
@@ -6480,6 +6501,12 @@ export class Broker {
|
||||
entry.running = this.#running(s.business, name);
|
||||
entry.alive = this.#aliveAfterFire(s.business, name);
|
||||
}
|
||||
// Ruling 2026-11-14: each instance a pack hire created names the pack, from its pack.hire event.
|
||||
if (request.verb === "instances" && result?.instances && typeof result.instances === "object") {
|
||||
const from = this.#packHireOrigins(s.business);
|
||||
for (const entry of Object.values(result.instances))
|
||||
if (typeof entry.hireDecision === 'string' && from.has(entry.hireDecision)) entry.pack = from.get(entry.hireDecision);
|
||||
}
|
||||
// #1873 A3: the copies this bus booted with, and each one's running runs. The file's own
|
||||
// instances above carry no copy; a copy carries its state, missing service names or reason.
|
||||
if (request.verb === "instances" && result?.instances && typeof result.instances === "object" && this.#business(s.business).copies)
|
||||
@@ -6650,7 +6677,7 @@ export class Broker {
|
||||
if(!this.#autonomyHost?.get || !this.#autonomyHost?.set)fail('not-configured');
|
||||
const old=await this.#autonomyHost.get(s.business),b=this.#business(s.business);
|
||||
if(a.revision!==old.revision)fail('revision-conflict');
|
||||
if(AUTONOMY_CLASSES.some(cls=>decisionAutonomy(cls,a.autonomy)==='near the loop') && a.autonomy.notices!==true)fail('autonomy-precondition');
|
||||
if(AUTONOMY_CLASSES.some(cls=>decisionAutonomy(cls,a.autonomy)==='near the loop') && a.autonomy.notices!==true)fail('autonomy-precondition','owner notices are off; a class near the loop needs them on');
|
||||
for(const cls of AUTONOMY_CLASSES) {
|
||||
const before=decisionAutonomy(cls,old.autonomy),after=decisionAutonomy(cls,a.autonomy);
|
||||
// Pulling back is unconditional. Only a move away from the loop has prerequisites.
|
||||
@@ -6659,22 +6686,24 @@ export class Broker {
|
||||
if(cls==='policy')continue;
|
||||
if(cls==='authority' && after==='out of the loop' && before!==after)fail('authority-limits-unavailable');
|
||||
if(['in the loop','near the loop','out of the loop'].indexOf(after)<=['in the loop','near the loop','out of the loop'].indexOf(before))continue;
|
||||
if(a.autonomy.notices!==true || !this.#autonomyHost.reversible?.(cls,b))fail('autonomy-precondition');
|
||||
if(a.autonomy.notices!==true)fail('autonomy-precondition',`owner notices are off; moving ${cls} away from the loop needs them on`);
|
||||
if(!this.#autonomyHost.reversible?.(cls,b))fail('autonomy-precondition',`${cls} has no tested reverse in this organization, so it stays in the loop`);
|
||||
const resolvers=cls==='authority'?[a.autonomy.authorityResolver]:cls==='merge'?[b.arbiters.technical]:cls==='policy'?[b.arbiters.delivery]:Object.values(b.arbiters);
|
||||
for(const name of resolvers) {
|
||||
const role=b.roles[name],right=cls==='authority'?'decision.resolve.authority':`decision.resolve.${cls==='merge'?'technical':cls==='policy'?'delivery':name===b.arbiters.technical?'technical':'delivery'}`;
|
||||
if(!role?.authority?.withinRole.includes(right) || (cls==='authority' && name===b.launch?.by))fail('autonomy-precondition');
|
||||
if(!role?.authority?.withinRole.includes(right))fail('autonomy-precondition',cls==='authority'?'the authority resolver is not a role with decision.resolve.authority':`the ${cls} resolver is not a role with ${right}`);
|
||||
if(cls==='authority' && name===b.launch?.by)fail('autonomy-precondition','the authority resolver is the role that launches agents; name a separate resolver');
|
||||
}
|
||||
if(['merge','policy'].includes(cls) && !Object.values(b.roles).some(r=>r.authority?.withinRole.includes('review.verdict')))fail('autonomy-precondition');
|
||||
if(cls==='authority' && !this.#budgetCovered(b))fail('autonomy-precondition');
|
||||
if(['merge','policy'].includes(cls) && !Object.values(b.roles).some(r=>r.authority?.withinRole.includes('review.verdict')))fail('autonomy-precondition',`no role holds review.verdict, which ${cls} away from the loop needs`);
|
||||
if(cls==='authority' && !this.#budgetCovered(b))fail('autonomy-precondition',BUDGET_UNCOVERED);
|
||||
if(after==='out of the loop') {
|
||||
if(before!=='near the loop')fail('autonomy-precondition');
|
||||
if(before!=='near the loop')fail('autonomy-precondition',`${cls} moves out of the loop only from near the loop`);
|
||||
const review=this.#store.get("SELECT seq,body FROM events WHERE business=? AND kind='action.allowed' AND json_extract(body,'$.operation')='autonomy.review' AND json_extract(body,'$.decisionClass')=? ORDER BY seq DESC LIMIT 1",s.business,cls);
|
||||
const latest=this.#store.get("SELECT seq FROM events WHERE business=? AND kind='action.allowed' AND json_extract(body,'$.operation')='autonomy.set' ORDER BY seq DESC LIMIT 1",s.business);
|
||||
if(!review || JSON.parse(review.body).settingSeq!==latest?.seq)fail('autonomy-precondition');
|
||||
if(!review || JSON.parse(review.body).settingSeq!==latest?.seq)fail('autonomy-precondition',`${cls} needs your review of its trail since the last autonomy change`);
|
||||
const notice=this.#store.get("SELECT seq FROM events WHERE business=? AND kind='action.allowed' AND json_extract(body,'$.operation')='autonomy.notice' AND json_extract(body,'$.decisionClass')=? AND seq>? ORDER BY seq DESC LIMIT 1",s.business,cls,latest?.seq??0);
|
||||
const reversal=this.#store.get("SELECT max(e.seq) seq FROM events e WHERE e.business=? AND e.kind='action.allowed' AND json_extract(e.body,'$.operation') LIKE 'autonomy.reverse%' AND EXISTS(SELECT 1 FROM events n WHERE n.business=e.business AND n.kind='action.allowed' AND json_extract(n.body,'$.operation')='autonomy.notice' AND json_extract(n.body,'$.decisionClass')=? AND json_extract(n.body,'$.decision')=json_extract(e.body,'$.decision'))",s.business,cls);
|
||||
if(!notice || review.seq<=Math.max(notice.seq,reversal?.seq??0))fail('autonomy-precondition');
|
||||
if(!notice || review.seq<=Math.max(notice.seq,reversal?.seq??0))fail('autonomy-precondition',`${cls} needs a near-loop decision since the last autonomy change, and your trail review after it`);
|
||||
}
|
||||
}
|
||||
this.#store.transaction(()=>this.#event(s,'action.allowed',{operation:'autonomy.set.requested',autonomy:a.autonomy,subject:s.console},null));
|
||||
@@ -6758,28 +6787,162 @@ export class Broker {
|
||||
.at(-1);
|
||||
if (!entry) fail('invalid-request');
|
||||
const hire = entry.proposedHires.find(h => h.name === proposal.hire);
|
||||
const pin = hire.pin;
|
||||
if (!object(pin)) fail('invalid-request');
|
||||
let role;
|
||||
if (Object.hasOwn(pin, 'inline')) {
|
||||
if (!object(hire.entry) || typeof pin.sha256 !== 'string') fail('invalid-request');
|
||||
// The broker's sandbox import closure is fixed, so the digest and the composition are local
|
||||
// copies: canonical is organization util.mjs canonicalJson, built as a string so integer-like
|
||||
// keys keep the sorted order (an object would put them first), and the composition is
|
||||
// definitions.mjs compositionOf.
|
||||
const canonical = v => Array.isArray(v) ? `[${v.map(canonical).join(',')}]` : object(v)
|
||||
? `{${Object.keys(v).sort().map(k => `${JSON.stringify(k)}:${canonical(v[k])}`).join(',')}}` : JSON.stringify(v);
|
||||
if (sha256(canonical(hire.entry)) !== pin.sha256) fail('starter-pack-proposal-stale');
|
||||
const from = hire.entry.from?.template;
|
||||
if (from !== undefined && (b.launch?.noHire ?? []).includes(from)) fail('definition-not-hireable');
|
||||
if (!object(hire.entry.role) || typeof hire.entry.instructions !== 'string') fail('invalid-request');
|
||||
role = { inline: { ...hire.entry.role, instructions: hire.entry.instructions, ...(hire.entry.personality !== undefined ? { personality: hire.entry.personality } : {}) } };
|
||||
} else role = structuredClone(pin);
|
||||
const role = this.#pinRole(b.launch?.noHire ?? [], hire);
|
||||
const reason = Object.hasOwn(args, 'reason') ? args.reason : hire.reason;
|
||||
return { op: 'hire', level: project === null ? 'org' : 'project', ...(project === null ? {} : { project }), name: hire.name, role, route: structuredClone(args.route), reason };
|
||||
return { input: { op: 'hire', level: project === null ? 'org' : 'project', ...(project === null ? {} : { project }), name: hire.name, role, route: structuredClone(args.route), reason },
|
||||
pack: { pack: entry.id, version: entry.version ?? null, origin: entry.origin ?? null, project } };
|
||||
}
|
||||
async #raiseHire(s, input, immediate) {
|
||||
// A recorded proposal's pin as a hire request's role (SP5's chief raise and a person's pack hire).
|
||||
#pinRole(noHire, hire) {
|
||||
const pin = hire?.pin;
|
||||
if (!object(pin)) fail('invalid-request');
|
||||
// #1873 triage-fence: a recorded pin never hires a system-only template, by reference or as the
|
||||
// inline copy of one (the inline composition below drops from).
|
||||
if (systemOnly(pin.template) || systemOnly(hire.entry?.from?.template)) fail(SYSTEM_ONLY_REFUSAL);
|
||||
if (!Object.hasOwn(pin, 'inline')) return structuredClone(pin);
|
||||
if (!object(hire.entry) || typeof pin.sha256 !== 'string') fail('invalid-request');
|
||||
// The broker's sandbox import closure is fixed, so the digest and the composition are local
|
||||
// copies: canonical is organization util.mjs canonicalJson, built as a string so integer-like
|
||||
// keys keep the sorted order (an object would put them first), and the composition is
|
||||
// definitions.mjs compositionOf.
|
||||
const canonical = v => Array.isArray(v) ? `[${v.map(canonical).join(',')}]` : object(v)
|
||||
? `{${Object.keys(v).sort().map(k => `${JSON.stringify(k)}:${canonical(v[k])}`).join(',')}}` : JSON.stringify(v);
|
||||
if (sha256(canonical(hire.entry)) !== pin.sha256) fail('starter-pack-proposal-stale');
|
||||
const from = hire.entry.from?.template;
|
||||
if (from !== undefined && noHire.includes(from)) fail('definition-not-hireable');
|
||||
if (!object(hire.entry.role) || typeof hire.entry.instructions !== 'string') fail('invalid-request');
|
||||
return { inline: { ...hire.entry.role, instructions: hire.entry.instructions, ...(hire.entry.personality !== undefined ? { personality: hire.entry.personality } : {}) } };
|
||||
}
|
||||
// Ruling 2026-11-14: a person's pack apply is the hire decision. The person who may hire from a
|
||||
// pack: the owner's console cap, the owner's CLI human cap (outside any run), or a member's console
|
||||
// cap with org.hire. Anyone else is refused human-required; the tester tester-refused.
|
||||
#packHireCaller(s) {
|
||||
if (s.tester) fail('tester-refused');
|
||||
if (s.console) return this.#hireCaller(s);
|
||||
this.#human(s);
|
||||
if (s.human !== this.#business(s.business).human) fail('human-required');
|
||||
return { actor: s.human, agent: false, rights: ['org.hire'], owner: true, instanceOwner: false, subject: null, via: 'cli' };
|
||||
}
|
||||
#openHireDecisions(business) {
|
||||
return this.#store.all(`SELECT d.id FROM decisions d WHERE d.business=? AND d.action='role.hire' AND NOT EXISTS(SELECT 1 FROM decision_events x WHERE x.decision=d.id AND x.op IN ${CLOSED}) ORDER BY d.at, d.id`, business)
|
||||
.map(({ id }) => ({ id, hire: this.#raised(business, id)?.hire })).filter(x => object(x.hire));
|
||||
}
|
||||
// decision id -> {id, origin, project} of the pack whose hire raised it.
|
||||
#packHireOrigins(business) {
|
||||
return new Map(this.#packHireEvents(business).filter(e => e.operation === 'pack.hire' && typeof e.decision === 'string')
|
||||
.map(e => [e.decision, { id: e.pack, origin: e.origin ?? null, project: e.project ?? null }]));
|
||||
}
|
||||
// Ruling 2026-11-14: the packs read gains, per applied entry, the agents its hires created
|
||||
// (launched, for the organization level) and each proposal still open: awaiting-owner with its
|
||||
// decision, refused with the last refusal code, or proposed. Each carries the pack's reason.
|
||||
#packsEnrich(business, value) {
|
||||
if (!Array.isArray(value?.applied)) return value;
|
||||
const events = this.#packHireEvents(business), agents = value.agents ?? { org: {}, projects: {} };
|
||||
const open = new Map(this.#openHireDecisions(business).map(x => [JSON.stringify([x.hire.name, x.hire.project ?? null]), x.id]));
|
||||
const raisedBy = new Map(events.filter(e => e.operation === 'pack.hire').map(e => [e.decision, e]));
|
||||
for (const a of value.applied) {
|
||||
const level = a.project === null ? agents.org ?? {} : agents.projects?.[a.project] ?? {};
|
||||
const mine = e => e.pack === a.id && (e.origin ?? null) === (a.origin ?? null) && (e.project ?? null) === (a.project ?? null);
|
||||
// Hired: every live instance at the entry's level a hire of this pack created, whichever entry
|
||||
// proposed it (a re-apply records an entry that proposes nothing new).
|
||||
a.hired = Object.entries(level).filter(([, inst]) => inst.launched && inst.hireDecision && raisedBy.has(inst.hireDecision) && mine(raisedBy.get(inst.hireDecision))).map(([name]) => name);
|
||||
a.open = [];
|
||||
for (const h of a.proposedHires) {
|
||||
if (Object.hasOwn(level, h.name)) continue;
|
||||
const decision = open.get(JSON.stringify([h.name, a.project ?? null]));
|
||||
// fromPack: this pack's own hire raised it, so the owner's pack hire replaces and approves it.
|
||||
if (decision) { a.open.push({ name: h.name, reason: h.reason, state: 'awaiting-owner', decision, ...(raisedBy.has(decision) && mine(raisedBy.get(decision)) ? { fromPack: true } : {}) }); continue; }
|
||||
const last = events.filter(e => mine(e) && e.hire === h.name).at(-1);
|
||||
if (last?.operation === 'pack.hire.refused') a.open.push({ name: h.name, reason: h.reason, state: 'refused', code: last.code });
|
||||
else a.open.push({ name: h.name, reason: h.reason, state: 'proposed' });
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
#packHireEvents(business) {
|
||||
return this.#store.all(`SELECT body FROM events WHERE business=? AND kind='action.allowed' AND json_extract(body,'$.operation') IN ('pack.hire','pack.hire.refused') ORDER BY seq`, business)
|
||||
.map(r => JSON.parse(r.body));
|
||||
}
|
||||
// One pass over the latest packs entry of `pack` (and project): each proposed hire is raised and
|
||||
// approved in the same act through #raiseHire and #hireConsole, the path an inbox approval takes, so
|
||||
// each agent leaves the same decision record. A hire whose instance exists, or that an open hire
|
||||
// decision already names, is skipped, so a re-apply hires nothing twice. The owner approves every
|
||||
// line. A member approves only the unflagged hires; each flagged or credentialed one is recorded
|
||||
// after them, pinned to the final revision, as an open decision for the owner's inbox. A hire that
|
||||
// refuses records action.allowed pack.hire.refused with its code, and the loop goes on.
|
||||
async #packHires(s, callerOf, { pack, project = null }) {
|
||||
if (!this.#organization || !this.#hires) fail('not-configured');
|
||||
if (this.#packHiring.has(s.business)) fail('organization-busy');
|
||||
this.#packHiring.add(s.business);
|
||||
try { return await this.#packHireLoop(s, callerOf, { pack, project }); }
|
||||
finally { this.#packHiring.delete(s.business); }
|
||||
}
|
||||
async #packHireLoop(s, callerOf, { pack, project }) {
|
||||
const caller = callerOf();
|
||||
const read = () => this.#organization(s.business, 'pack.state', { pack, project }, caller.actor, {});
|
||||
const state = read();
|
||||
if (!state?.entry) return { hires: [] };
|
||||
const entry = state.entry, provenance = { pack: entry.id, version: entry.version ?? null, origin: entry.origin ?? null, project };
|
||||
const out = [], deferred = [];
|
||||
const refused = (name, e) => {
|
||||
const code = e?.code ?? 'outcome-unknown';
|
||||
this.#store.transaction(() => this.#event(s, 'action.allowed', { operation: 'pack.hire.refused', pack: entry.id, origin: entry.origin ?? null, project, hire: name, code }, null));
|
||||
out.push({ name, state: 'refused', code });
|
||||
};
|
||||
const open = new Map(this.#openHireDecisions(s.business).map(x => [JSON.stringify([x.hire.name, x.hire.project ?? null]), x.id]));
|
||||
const raisedBy = new Map(this.#packHireEvents(s.business).filter(e => e.operation === 'pack.hire').map(e => [e.decision, e]));
|
||||
for (const hire of (Array.isArray(entry.proposedHires) ? entry.proposedHires : []).filter(object)) {
|
||||
const name = hire.name;
|
||||
if (state.names.includes(name)) { out.push({ name, state: 'exists' }); continue; }
|
||||
const openId = open.get(JSON.stringify([name, project]));
|
||||
// The owner's pack hire approves every line, so an open decision an earlier pack hire of this
|
||||
// same pack left for the owner is replaced by one approved now (its pin may be stale after the
|
||||
// hires approved since). The old one is withdrawn only once the new hire has applied: a
|
||||
// replacement that refuses leaves it open in the owner's inbox. Any other open decision is left alone.
|
||||
let supersedes = null;
|
||||
if (openId) {
|
||||
const by = raisedBy.get(openId);
|
||||
if (caller.owner !== true || !by || by.pack !== entry.id || (by.origin ?? null) !== (entry.origin ?? null) || (by.project ?? null) !== project) { out.push({ name, state: 'open', decision: openId }); continue; }
|
||||
supersedes = openId;
|
||||
}
|
||||
let input;
|
||||
try {
|
||||
if (!state.route) fail('pack-hire-route-missing');
|
||||
input = { op: 'hire', level: project === null ? 'org' : 'project', ...(project === null ? {} : { project }), name, role: this.#pinRole(state.noHire, hire), route: structuredClone(state.route),
|
||||
reason: typeof hire.reason === 'string' && hire.reason.trim() ? hire.reason : `Proposed by starter pack ${entry.id}.` };
|
||||
} catch (e) { refused(name, e); continue; }
|
||||
let r;
|
||||
try {
|
||||
r = await this.#raiseHire(s, input, true, { caller: callerOf, pack: provenance, defer: caller.owner !== true });
|
||||
} catch (e) { refused(name, e); continue; }
|
||||
if (r?.deferred) { deferred.push(input); continue; }
|
||||
if (supersedes) this.#store.transaction(() => {
|
||||
if (this.#closed(supersedes)) return;
|
||||
const seq = Number(this.#store.run('INSERT INTO decision_events(decision,at,op,by,choice,note,via) VALUES(?,?,?,?,?,?,?)',
|
||||
supersedes, this.#now(), 'withdrawn', caller.actor, null, null, caller.via ?? 'console').lastInsertRowid);
|
||||
this.#event(s, 'human.input', { kind: 'answer', decision: supersedes, op: 'withdrawn', choice: null, via: caller.via ?? 'console', subject: caller.via === 'cli' ? null : s.console, decisionSeq: seq }, supersedes);
|
||||
});
|
||||
out.push({ name, state: 'hired', decision: r.id, routeFrom: state.routeFrom, ...(supersedes ? { supersedes } : {}) });
|
||||
}
|
||||
for (const input of deferred) {
|
||||
try {
|
||||
const r = await this.#raiseHire(s, input, false, { caller: callerOf, pack: provenance, record: true });
|
||||
out.push({ name: input.name, state: 'awaiting-owner', decision: r.id, routeFrom: state.routeFrom });
|
||||
} catch (e) { refused(input.name, e); }
|
||||
}
|
||||
return { hires: out };
|
||||
}
|
||||
|
||||
// opts (ruling 2026-11-14, a person's pack apply is the hire decision):
|
||||
// caller: () => the person's hire caller, read again after prepare. Default #hireCaller(s).
|
||||
// pack: {pack, version, origin, project}; the raise also records action.allowed pack.hire.
|
||||
// defer: a flagged or credentialed hire a non-owner may not approve returns {deferred: true}
|
||||
// instead of refusing hire-owner-required, and records nothing.
|
||||
// record: the person's raise is left open for the owner's inbox (route human, not resolved).
|
||||
async #raiseHire(s, input, immediate, opts = {}) {
|
||||
const b=this.#business(s.business);
|
||||
const human=immediate || opts.record===true;
|
||||
const callerOf=()=>opts.caller ? opts.caller() : this.#hireCaller(s);
|
||||
// Change is a replacement composition and uses the existing role.hire grant.
|
||||
const chiefAllowed=()=>{
|
||||
this.#agent(s);
|
||||
@@ -6789,36 +6952,44 @@ export class Broker {
|
||||
};
|
||||
// #1873 CB1: a copy credential binding is owner-only. A person raising one in one step must be
|
||||
// the organization's owner; a member with org.hire is not.
|
||||
if(immediate) { const c=this.#hireCaller(s); if(!c.rights.includes('org.hire'))fail('right-required'); if(input?.binding!==undefined && c.owner!==true)fail('human-required'); }
|
||||
if(human) { const c=callerOf(); if(!c.rights.includes('org.hire'))fail('right-required'); if(input?.binding!==undefined && c.owner!==true)fail('human-required'); }
|
||||
else chiefAllowed();
|
||||
if(!this.#hires)fail('not-configured');
|
||||
const did=randomUUID(), at=this.#now(), expiresAt=new Date(Date.parse(at)+7*86400000).toISOString();
|
||||
const p=await this.#hires.prepare(s.business,structuredClone(input),{id:did,expiresAt});
|
||||
// Recheck the chief after asynchronous preparation; a released run cannot raise.
|
||||
if(!immediate)chiefAllowed();
|
||||
let caller=null;
|
||||
if(!human)chiefAllowed();
|
||||
else {
|
||||
const caller=this.#hireCaller(s);
|
||||
caller=callerOf();
|
||||
if(p.binding && caller.owner!==true)fail('human-required');
|
||||
if(!p.binding && (((p.flagged.length || p.credentialLines.length) && !caller.owner) || (p.level==='root' && !caller.instanceOwner)))fail('hire-owner-required');
|
||||
const ownerOnly=!p.binding && (((p.flagged.length || p.credentialLines.length) && !caller.owner) || (p.level==='root' && !caller.instanceOwner));
|
||||
if(ownerOnly && opts.defer===true)return {deferred:true,name:p.name,flagged:p.flagged,credentialLines:p.credentialLines};
|
||||
if(ownerOnly && opts.record!==true)fail('hire-owner-required');
|
||||
}
|
||||
const action=`role.${p.op}`;
|
||||
const level=decisionAutonomy('authority',b.autonomy);
|
||||
let route='human';
|
||||
// A binding always goes to the owner; no autonomy level moves it (design section 4).
|
||||
if(!immediate && !p.binding && level!=='in the loop' && p.level!=='root' && !p.flagged.length && !p.credentialLines.length) {
|
||||
if(!human && !p.binding && level!=='in the loop' && p.level!=='root' && !p.flagged.length && !p.credentialLines.length) {
|
||||
if(level==='out of the loop')fail('authority-limits-unavailable');
|
||||
if(!this.#budgetCovered(this.#business(s.business)))fail('autonomy-precondition');
|
||||
if(!this.#budgetCovered(this.#business(s.business)))fail('autonomy-precondition',BUDGET_UNCOVERED);
|
||||
route=b.autonomy?.authorityResolver;
|
||||
if(!b.roles[route]?.authority?.withinRole.includes('decision.resolve.authority'))fail('autonomy-precondition');
|
||||
if(!b.roles[route]?.authority?.withinRole.includes('decision.resolve.authority'))fail('autonomy-precondition','the authority resolver is not a role with decision.resolve.authority');
|
||||
if(route===s.role || resolverSubject(b,route,p.name))route='human';
|
||||
}
|
||||
this.#store.transaction(()=>{
|
||||
const raiser=immediate?'human':s.role;
|
||||
const raiser=human?'human':s.role;
|
||||
const run=human?(caller?.via==='cli'?'human-cli':'human-console'):s.run;
|
||||
this.#store.run('INSERT INTO decisions(id,at,business,project,raised_by_role,raised_by_run,class,action,route_to,question,options,recommendation,blocking) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)',
|
||||
did,at,s.business,p.project??null,raiser,immediate?'human-console':s.run,'gated',action,route,p.binding?`${p.binding.after===null?'unbind':'bind'} credentials for copy ${p.binding.instance}?`:`${p.op} ${p.name} at ${p.level} level?`,JSON.stringify([{key:'yes',text:'Approve'},{key:'no',text:'Deny'}]),'no',0);
|
||||
did,at,s.business,p.project??null,raiser,run,'gated',action,route,p.binding?`${p.binding.after===null?'unbind':'bind'} credentials for copy ${p.binding.instance}?`:`${p.op} ${p.name} at ${p.level} level?`,JSON.stringify([{key:'yes',text:'Approve'},{key:'no',text:'Deny'}]),'no',0);
|
||||
this.#event(s,'action.allowed',{operation:'decision.raise',decision:did,action,approvalChoice:'yes',target:p.name,hire:p,autonomyLevel:level},did);
|
||||
// The pack this hire came from, for the Agents page and the pack card. No target key: the
|
||||
// decision.raise above is the record the decision readers key on.
|
||||
if(opts.pack)this.#event(s,'action.allowed',{operation:'pack.hire',pack:opts.pack.pack,version:opts.pack.version??null,origin:opts.pack.origin??null,project:opts.pack.project??null,hire:p.name,decision:did},did);
|
||||
});
|
||||
if(immediate) return this.#hireConsole(s,'hire.resolve.console',{id:did,choice:'yes',digest:p.digest});
|
||||
if(immediate) return this.#hireConsole(s,'hire.resolve.console',{id:did,choice:'yes',digest:p.digest},opts.caller ?? null);
|
||||
if(human) return {id:did,op:'raised',name:p.name,flagged:p.flagged,credentialLines:p.credentialLines};
|
||||
return {...this.#decisionView(this.#decision(s,did)),hire:bindingSummary(p)};
|
||||
}
|
||||
// The harness fact comes from the host's loaded modules; no host, no account coverage.
|
||||
@@ -6840,7 +7011,7 @@ export class Broker {
|
||||
if(this.#expireHire(s,d,p))fail('decision-expired');
|
||||
if(this.#autonomyLevel(d)==='in the loop')fail('hire-resolution-required');
|
||||
if(this.#autonomyLevel(d)==='out of the loop')fail('authority-limits-unavailable');
|
||||
if(!this.#budgetCovered(this.#business(s.business)))fail('autonomy-precondition');
|
||||
if(!this.#budgetCovered(this.#business(s.business)))fail('autonomy-precondition',BUDGET_UNCOVERED);
|
||||
if(!this.#business(s.business).roles[s.role]?.authority?.withinRole.includes('decision.resolve.authority'))fail('not-resolver');
|
||||
};
|
||||
validate();
|
||||
@@ -6860,7 +7031,7 @@ export class Broker {
|
||||
const recheck=()=>{
|
||||
this.#agent(s);
|
||||
if(this.#autonomyLevel(d)==='out of the loop')fail('authority-limits-unavailable');
|
||||
if(!this.#budgetCovered(this.#business(s.business)))fail('autonomy-precondition');
|
||||
if(!this.#budgetCovered(this.#business(s.business)))fail('autonomy-precondition',BUDGET_UNCOVERED);
|
||||
if(this.#autonomyLevel(d)==='in the loop' || !this.#business(s.business).roles[s.role]?.authority?.withinRole.includes('decision.resolve.authority') || resolverSubject(this.#business(s.business),s.role,p.name))fail('not-resolver');
|
||||
};
|
||||
recheck();
|
||||
@@ -6875,8 +7046,8 @@ export class Broker {
|
||||
this.#store.transaction(()=>this.#event(s,'action.allowed',{operation:'hire.failed',decision:d.id,code:error.code??'outcome-unknown'},d.id));throw error;
|
||||
}
|
||||
}
|
||||
async #hireConsole(s,verb,a) {
|
||||
const caller={...this.#hireCaller(s),now:()=>Math.max(Date.now(),this.#clock)};
|
||||
async #hireConsole(s,verb,a,callerOf=null) {
|
||||
const caller={...(callerOf ? callerOf() : this.#hireCaller(s)),now:()=>Math.max(Date.now(),this.#clock)};
|
||||
keys(a,verb==='hire.preview.console'?['id','adjust']:['id','choice','digest','adjust'],verb==='hire.preview.console'?['id']:['id','choice','digest']);
|
||||
identifier(a.id);
|
||||
const d=this.#decision(s,a.id), raise=this.#raised(s.business,d.id);
|
||||
@@ -6899,8 +7070,9 @@ export class Broker {
|
||||
// A durable close/consume precedes the external file effect. A crash never replays an approval.
|
||||
this.#store.transaction(()=>{
|
||||
if(this.#closed(d.id))fail('decision-closed');
|
||||
this.#store.run('INSERT INTO decision_events(decision,at,op,by,choice,via) VALUES(?,?,?,?,?,?)',d.id,this.#now(),'resolved',caller.actor,a.choice,'console');
|
||||
this.#event(s,'human.input',{kind:'answer',decision:d.id,op:'resolved',choice:a.choice,via:'console',subject:s.console},d.id);
|
||||
const via=caller.via ?? 'console';
|
||||
this.#store.run('INSERT INTO decision_events(decision,at,op,by,choice,via) VALUES(?,?,?,?,?,?)',d.id,this.#now(),'resolved',caller.actor,a.choice,via);
|
||||
this.#event(s,'human.input',{kind:'answer',decision:d.id,op:'resolved',choice:a.choice,via,subject:callerOf ? caller.subject ?? null : s.console},d.id);
|
||||
if(a.choice==='yes')this.#event(s,'action.allowed',{operation:'hire.consume',decision:d.id,digest:p.digest,hire:p},d.id);
|
||||
});
|
||||
if(a.choice==='no')return {id:d.id,op:'resolved',choice:a.choice};
|
||||
@@ -7038,7 +7210,7 @@ export class Broker {
|
||||
// name; a file check (BusinessError) is invalid-request, anything else outcome-unknown.
|
||||
#packFail(e) {
|
||||
const code = e?.code ?? '';
|
||||
if (['credential-leak', 'pack-plan-stale', 'revision-conflict', 'invalid-request', 'human-required', 'not-configured'].includes(code)
|
||||
if (['credential-leak', 'pack-plan-stale', 'revision-conflict', 'invalid-request', 'human-required', 'not-configured', SYSTEM_ONLY_REFUSAL].includes(code)
|
||||
|| /^(starter-pack|definition|organization)-[a-z-]+$/.test(code)) fail(code);
|
||||
if (e?.name === 'BusinessError') fail('invalid-request');
|
||||
throw new BusError('outcome-unknown');
|
||||
@@ -7070,6 +7242,8 @@ export class Broker {
|
||||
if ((verb === "instance.hire" || verb === "instance.fire") && e.code === "definition-not-hireable") fail(e.code);
|
||||
// Row 194 (B7, webby-0094 N3): the limits writer's keep check, against the file, as well.
|
||||
if (e.code === "instance-kept") fail(e.code);
|
||||
// #1873 triage-fence: a system-only template refuses by its one code on every write.
|
||||
if (e.code === SYSTEM_ONLY_REFUSAL) fail(e.code);
|
||||
// #1873 T1: the definition writer's refusals pass by code; a composition refusal stays invalid-request.
|
||||
if (Object.hasOwn(DEFINITION_BUS_KEYS, verb) && /^definition-[a-z-]+$/.test(e.code ?? "")) fail(e.code);
|
||||
// Row 194 (brief item 8): a fire's or a delete's revoke failed, and nothing was written.
|
||||
@@ -8715,25 +8889,6 @@ export class Broker {
|
||||
.filter((p) => !s.user || this.#granted(s, 'project.list', p.id, null))
|
||||
.map((p) => (p.state === 'archive' ? { id: p.id, at: p.at, name: p.name, repo: p.repo, archived: true } : { id: p.id, at: p.at, name: p.name, repo: p.repo }));
|
||||
}
|
||||
case 'project.system-types':
|
||||
case 'project.system-types.set': {
|
||||
this.#human(s);
|
||||
const write = verb === 'project.system-types.set';
|
||||
keys(a, write ? ['project', 'systemTypes'] : ['project'], write ? ['project', 'systemTypes'] : ['project']);
|
||||
const project = identifier(a.project);
|
||||
if (!this.#store.get('SELECT 1 FROM projects WHERE id=? AND business=?', project, s.business)) fail('project-not-found');
|
||||
// When configured, read the trusted file each time; a stale bus snapshot must not reactivate a disabled type.
|
||||
const enabled = this.#organization ? this.#organization(s.business, 'system-types.current', {}, s.human) : (b.plugins?.['system-type'] ?? []);
|
||||
if (!Array.isArray(enabled)) fail('not-configured');
|
||||
if (write) {
|
||||
if (!Array.isArray(a.systemTypes) || a.systemTypes.some(x => typeof x !== 'string') || new Set(a.systemTypes).size !== a.systemTypes.length) fail('invalid-request');
|
||||
if (a.systemTypes.some(x => !enabled.includes(x))) fail('system-type-not-enabled');
|
||||
this.#store.run('INSERT INTO project_system_types(at,business,project,types,by) VALUES(?,?,?,?,?)', this.#now(), s.business, project, JSON.stringify(a.systemTypes), this.#owner(s));
|
||||
}
|
||||
const row = this.#store.get('SELECT types FROM project_system_types WHERE business=? AND project=? ORDER BY seq DESC LIMIT 1', s.business, project);
|
||||
const selected = row ? JSON.parse(row.types) : [];
|
||||
return { project, selected, active: selected.filter(x => enabled.includes(x)), inactive: selected.filter(x => !enabled.includes(x)) };
|
||||
}
|
||||
// #797 MVP3 (owner report 2026-11-06): the owner's reversible retirement of a project. The
|
||||
// human gate is project.create's minus the tester carve-out: tester, user and agent sessions
|
||||
// are refused here. Each verb appends one project_archives row (the audit trail) and deletes
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { connect } from 'node:net';
|
||||
import { BusError, PROJECT_SAVE_VERB, PROJECT_SAVE_REQUEST_MAX } from './broker.mjs';
|
||||
// E2E6 fix 6: a connect that fails with one of these never sent the request. The code stays
|
||||
// outcome-unknown for every caller that reads it (the harness, the Console), and the error is marked
|
||||
// notSent so the human and tester shims can exit with NOT_SENT_EXIT and `mosaic` can say the bus is
|
||||
// not running.
|
||||
const NOT_SENT = new Set(['ENOENT', 'ECONNREFUSED', 'ENOTDIR', 'ENOTSOCK']);
|
||||
export const NOT_SENT_EXIT = 5;
|
||||
export class Client {
|
||||
constructor({ path, cap, human, tester, user, console: owner, timeout = 5000 }) {
|
||||
this.path = path;
|
||||
@@ -22,7 +28,8 @@ export class Client {
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = connect(this.path);
|
||||
let input = Buffer.alloc(0),
|
||||
settled = false;
|
||||
settled = false,
|
||||
connected = false;
|
||||
const end = (error, value) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
@@ -30,8 +37,12 @@ export class Client {
|
||||
error ? reject(error) : resolve(value);
|
||||
};
|
||||
socket.setTimeout(['processing.halt', 'processing.resume'].includes(verb) ? Math.max(this.timeout, 20000) : this.timeout, () => end(new BusError('outcome-unknown')));
|
||||
socket.on('connect', () => socket.write(request));
|
||||
socket.on('error', () => end(new BusError('outcome-unknown')));
|
||||
socket.on('connect', () => { connected = true; socket.write(request); });
|
||||
socket.on('error', (error) => {
|
||||
const unknown = new BusError('outcome-unknown');
|
||||
if (!connected && NOT_SENT.has(error?.code)) unknown.notSent = true;
|
||||
end(unknown);
|
||||
});
|
||||
socket.on('end', () => end(new BusError('outcome-unknown')));
|
||||
socket.on('data', (b) => {
|
||||
input = Buffer.concat([input, b]);
|
||||
|
||||
@@ -3,7 +3,7 @@ import { randomBytes } from 'node:crypto';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { Client } from './client.mjs';
|
||||
import { Client, NOT_SENT_EXIT } from './client.mjs';
|
||||
import { readProcess } from './human.mjs';
|
||||
const file = fileURLToPath(import.meta.url);
|
||||
if (!process.env.MOSAIC_BUS_CLI_NONCE) {
|
||||
@@ -39,5 +39,7 @@ try {
|
||||
process.stdout.write(JSON.stringify(result) + '\n');
|
||||
} catch (e) {
|
||||
process.stderr.write((/^[a-z-]{1,64}$/.test(e.code ?? '') ? e.code : 'invalid-request') + '\n');
|
||||
process.exitCode = 2;
|
||||
// E2E6 fix 6: a request that never left (no socket, or the connect refused) keeps its code and
|
||||
// exits NOT_SENT_EXIT, so `mosaic` can say the bus is not running. Every other failure exits 2.
|
||||
process.exitCode = e?.notSent === true ? NOT_SENT_EXIT : 2;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
-- #1873 SP9: the system-type kind is removed outright (Jason, 2026-11-12: "The only deployed
|
||||
-- system is the dev environment on dragon-lin. It can be wiped and reconfigured. No reason to hold
|
||||
-- on to legacy for this change."). This step drops what 3t-3u created: the four guards, the index
|
||||
-- and the table, with its rows. It is the one deletion of append-only rows in that go, and the
|
||||
-- ruling is its authority. SQLite removes the table's sqlite_sequence row with the table.
|
||||
DROP TRIGGER project_system_types_no_update;
|
||||
DROP TRIGGER project_system_types_no_delete;
|
||||
DROP TRIGGER project_system_types_no_replace;
|
||||
DROP TRIGGER project_system_types_business;
|
||||
DROP INDEX project_system_types_project;
|
||||
DROP TABLE project_system_types;
|
||||
@@ -6,6 +6,8 @@ import { isDeepStrictEqual } from 'node:util';
|
||||
import { BusError } from './broker.mjs';
|
||||
export const REVOKE_TIMEOUT_MS = 5000;
|
||||
export const REVOKE_POLL_MS = 25;
|
||||
export const ISSUE_PROBE_TIMEOUT_MS = 2000;
|
||||
export const ISSUE_REPROBE_MIN_MS = 250;
|
||||
export const MODEL_STOP_TIMEOUT_MS = 5000;
|
||||
const keyId = key => createHash('sha256').update(key).digest('hex').slice(0, 12);
|
||||
const fail = code => { throw new BusError(code); };
|
||||
@@ -223,9 +225,21 @@ export class ModelKeys {
|
||||
this.#sentinel(keys);
|
||||
return this.#issue(instance, false, keys);
|
||||
});
|
||||
let status;
|
||||
try { status = await this.#client.probeKey(proxy.key); }
|
||||
catch { fail('proxy-down'); }
|
||||
// Every v8 CLIProxyAPI applies a key-list PUT by an async reload after it answers, so a
|
||||
// just-issued key can answer 401 for a moment. On 8.0.79 that moment outlasts the confirming
|
||||
// GET (measured, #1873). Only 401 is probed again, until a short deadline; a re-probe waits
|
||||
// about the time left, at least ISSUE_REPROBE_MIN_MS. Any other non-2xx refuses on the first
|
||||
// answer, as before.
|
||||
const deadline = performance.now() + ISSUE_PROBE_TIMEOUT_MS;
|
||||
let status, first = true;
|
||||
for (;;) {
|
||||
const options = first ? undefined : { timeout: Math.max(ISSUE_REPROBE_MIN_MS, Math.ceil(deadline - performance.now())) };
|
||||
first = false;
|
||||
try { status = await this.#client.probeKey(proxy.key, options); }
|
||||
catch { fail('proxy-down'); }
|
||||
if (status !== 401 || performance.now() >= deadline) break;
|
||||
await new Promise(resolve => setTimeout(resolve, REVOKE_POLL_MS));
|
||||
}
|
||||
if (status < 200 || status >= 300) fail('proxy-key-refused');
|
||||
return proxy;
|
||||
}
|
||||
|
||||
@@ -183,7 +183,7 @@ group(
|
||||
"Read my_rails and use the applicable decision path; ask the owner to inspect grants if no supported path exists."
|
||||
);
|
||||
group(
|
||||
"not-configured project-already-archived project-archived project-exists project-not-archived project-not-configured project-not-found project-record-invalid project-remote-configured project-remote-invalid project-remote-library project-remote-protected project-remote-unknown project-spec-human-only system-type-not-enabled tracker-not-store usage-not-configured",
|
||||
"not-configured project-already-archived project-archived project-exists project-not-archived project-not-configured project-not-found project-record-invalid project-remote-configured project-remote-invalid project-remote-library project-remote-protected project-remote-unknown project-spec-human-only tracker-not-store usage-not-configured",
|
||||
"R3/role scope: configured project and service state",
|
||||
"Read the supported project/service status and ask its owner to repair missing configuration or state before retrying."
|
||||
);
|
||||
@@ -199,6 +199,13 @@ group(
|
||||
"R10: only the caller's own saved templates",
|
||||
"List your saved templates and use one of those names. A saved template is visible only to the owner who saved it."
|
||||
);
|
||||
// #1873 triage-fence: a template on the system-only list (organization vocabulary.mjs SYSTEM_ONLY)
|
||||
// joins no organization by any path.
|
||||
group(
|
||||
"template-system-only",
|
||||
"R8/R10: a system-only role template joins no organization",
|
||||
"This role template serves the system outside every organization. Pick another template or definition; no hire, change, pack, import or instance write gives an organization one."
|
||||
);
|
||||
group(
|
||||
"starter-pack-template-changed",
|
||||
"R8: a pack's hash pin must match the current template",
|
||||
@@ -218,6 +225,19 @@ group(
|
||||
"R8: a hire raised from a pack proposal matches its recorded pin",
|
||||
"The role entry stored with this proposal no longer matches the hash it was recorded with. Preview and apply the pack again for a fresh proposal, then raise the hire from that one."
|
||||
);
|
||||
// Ruling 2026-11-14: a person's pack apply is the hire decision. The hire action works from the packs
|
||||
// entry an apply recorded, and each hire runs as the chief's harness and model, else the org
|
||||
// assistant's (lane pr2).
|
||||
group(
|
||||
"pack-not-applied",
|
||||
"R8: a pack hire works from the packs entry an apply recorded",
|
||||
"Preview and apply the pack first; its proposed hires come from the packs entry that apply records."
|
||||
);
|
||||
group(
|
||||
"pack-hire-route-missing",
|
||||
"R3/R8: a hire runs as a harness and model the organization names",
|
||||
"Neither the chief of staff nor the organization's assistant resolves a harness and a model. Give the chief of staff or the assistant both in its vars, or set them at the organization or system level, then use the pack's hire action again."
|
||||
);
|
||||
// #1873 SP8: a saved template carries no credential the bus holds. Save checks every kept string and
|
||||
// key against the credential store; a hit names the field, never the text.
|
||||
group(
|
||||
@@ -225,6 +245,12 @@ group(
|
||||
"R1/R10: a saved template carries no credential value the bus holds",
|
||||
"A field the template would keep holds a credential value. Remove it from the named definition, board or workflow text, then preview and save again."
|
||||
);
|
||||
// E2E6 fix 8: save never replaces a template already saved under the name.
|
||||
group(
|
||||
"template-exists",
|
||||
"R10: a saved template is never replaced",
|
||||
"A template of this name is already saved for your account. Save under another name, or list your saved templates to pick a free one."
|
||||
);
|
||||
group(
|
||||
"not-resolver",
|
||||
"Role resolve right and decision route",
|
||||
|
||||
+150
-16
@@ -27,13 +27,12 @@ import { readSessions, sessionsFile, stopSession } from '../../seat/src/session.
|
||||
import { compactionCount, storeDir } from '../../seat/src/compactions.mjs';
|
||||
import { publishRemote, workingRepo, WorkingError } from '../../seat/src/working.mjs';
|
||||
import { createLoader, hasModule } from '../../plugins/src/loader.mjs';
|
||||
import { installedSystemTypes } from '../../plugins/src/system-types.mjs';
|
||||
import { pluginSettings } from '../../organization/src/plugin-settings.mjs';
|
||||
import { loadManagementClient } from '../../model-proxy/src/client.mjs';
|
||||
import { ProxyPage } from './proxy-page.mjs';
|
||||
import { createModelCatalogue } from './model-catalogue.mjs';
|
||||
import { sha256 } from '../../model-proxy/src/common.mjs';
|
||||
import { initializeProxy } from '../../model-proxy/src/settings.mjs';
|
||||
import { initializeProxy, loadProxy } from '../../model-proxy/src/settings.mjs';
|
||||
import { createProxyLock } from './proxy-lock.mjs';
|
||||
import { verifyRestart } from '../../model-proxy/src/admin.mjs';
|
||||
import { ModelKeys, modelOrganization, stopModelRuns, MODEL_STOP_TIMEOUT_MS } from './model-keys.mjs';
|
||||
@@ -41,6 +40,7 @@ import { instanceSettings } from '../../organization/src/instance-settings.mjs';
|
||||
import { organizationWriter, OrganizationError, setReplyLimits } from '../../organization/src/organization.mjs';
|
||||
import { definitionVerbs, DEFINITION_BUS_VERBS } from '../../organization/src/definition-verbs.mjs';
|
||||
import { ORG_PREFIX, orgDefinitionName, compositionOf, readTemplate, entryFromTemplate, lineDiff, PRIMITIVES } from '../../organization/src/definitions.mjs';
|
||||
import { SYSTEM_ONLY_REFUSAL, systemOnly } from '../../organization/src/vocabulary.mjs';
|
||||
import { installedStarterPacks, readSavedTemplate } from '../../plugins/src/starter-pack.mjs';
|
||||
import { TemplateError, templateList, templatePreview, templateSave } from '../../organization/src/template-save.mjs';
|
||||
import { checkComposition } from '../../organization/src/composition.mjs';
|
||||
@@ -301,7 +301,7 @@ const COPY_SWEEP_MS = 60000;
|
||||
const PACK_AS = /^(definitions|workflows)\.([a-z0-9][a-z0-9._-]{0,63})=([a-z0-9][a-z0-9._-]{0,63})$/;
|
||||
const SAVED_PREFIX = 'saved:';
|
||||
// Each op, and whether it writes.
|
||||
const PACK_OPS = Object.freeze({ packs: false, 'pack.preview': false, 'pack.apply': true, 'board.set': true, 'workflow.set': true });
|
||||
const PACK_OPS = Object.freeze({ packs: false, 'pack.preview': false, 'pack.state': false, 'pack.apply': true, 'board.set': true, 'workflow.set': true });
|
||||
const EMPTY_CHIEF = Object.freeze({ tools: [], network: 'none', authority: { withinRole: [], crossRole: [] }, credentials: [] });
|
||||
function packOps({ writer, rolesDir, dataRoot, system, registryFor, assertClean, configDir }) {
|
||||
const bad = () => { throw new BusError('invalid-request'); };
|
||||
@@ -314,7 +314,10 @@ function packOps({ writer, rolesDir, dataRoot, system, registryFor, assertClean,
|
||||
async function loadPack(name, actor) {
|
||||
if (typeof name !== 'string' || name.length > 128) bad();
|
||||
if (name.startsWith(SAVED_PREFIX)) return readSavedTemplate({ configDir, account: actor, name: name.slice(SAVED_PREFIX.length), rolesDir });
|
||||
const found = (await installed()).find(p => p.id === name);
|
||||
const { packs, refused } = await installedStarterPacks({ dataRoot, rolesDir });
|
||||
const found = packs.find(p => p.id === name);
|
||||
// #1873 triage-fence: an installed pack refused for naming a system-only template says so.
|
||||
if (!found && refused.some(r => r.name === name && r.code === SYSTEM_ONLY_REFUSAL)) throw new BusError(SYSTEM_ONLY_REFUSAL);
|
||||
if (!found) throw new BusError('starter-pack-not-found');
|
||||
return found;
|
||||
}
|
||||
@@ -333,6 +336,9 @@ function packOps({ writer, rolesDir, dataRoot, system, registryFor, assertClean,
|
||||
// The entry a pack definition writes: a template reference becomes the template's own entry, pinned
|
||||
// by its hash (a moved hash refuses), and a full entry is copied as it is. Neither carries rev.
|
||||
function entryOf(value) {
|
||||
// #1873 triage-fence: preview and apply both refuse a pack naming a system-only template, as a
|
||||
// reference or as the from of a full entry.
|
||||
if (systemOnly(value?.template) || systemOnly(value?.from?.template)) throw new BusError(SYSTEM_ONLY_REFUSAL);
|
||||
if (Object.hasOwn(value, 'template') && Object.hasOwn(value, 'sha256') && Object.keys(value).length === 2) {
|
||||
const template = readTemplate(rolesDir, value.template);
|
||||
if (template.sha256 !== value.sha256) throw new BusError('starter-pack-template-changed');
|
||||
@@ -502,9 +508,67 @@ function packOps({ writer, rolesDir, dataRoot, system, registryFor, assertClean,
|
||||
return `projects.${args.project}.${key}`;
|
||||
};
|
||||
const revisionOf = args => { if (typeof args.revision !== 'string' || !/^[0-9a-f]{64}$/.test(args.revision)) bad(); return args.revision; };
|
||||
// Ruling 2026-11-14 ("If I choose a starter pack and apply it, that is a decision!"): the
|
||||
// organization facts the broker's pack hire loop and the packs read need, as the file stands.
|
||||
// `pack` names a packs entry the way apply names the pack: saved:NAME is the owner's saved
|
||||
// template, any other name the latest shipped or installed entry of that id. The route is a
|
||||
// resolved harness, model and thinking (system, organization and agent vars): the chief's (the
|
||||
// launch.by instance), else the org assistant's (lane pr2, lead ruling 2026-11-14), else null.
|
||||
// routeFrom names which one gave it.
|
||||
const latestEntries = doc => {
|
||||
const latest = new Map();
|
||||
for (const e of doc.packs ?? []) if (isObject(e) && typeof e.id === 'string') latest.set(canonicalJson([e.id, e.origin ?? null, e.project ?? null]), e);
|
||||
return [...latest.values()];
|
||||
};
|
||||
const agentsOf = doc => {
|
||||
const launched = doc.launch?.instances ?? [];
|
||||
const one = (entry, isLaunched) => ({ hireDecision: typeof entry?.hireDecision === 'string' ? entry.hireDecision : null, launched: isLaunched });
|
||||
return {
|
||||
org: Object.fromEntries(Object.entries(doc.roles ?? {}).map(([name, e]) => [name, one(e, launched.includes(name))])),
|
||||
projects: Object.fromEntries(Object.entries(doc.projects ?? {}).filter(([, p]) => isObject(p) && p.kind !== 'library')
|
||||
.map(([project, p]) => [project, Object.fromEntries(Object.entries(p.agents ?? {}).map(([name, e]) => [name, one(e, true)]))])),
|
||||
};
|
||||
};
|
||||
// The org assistant is the instance whose definition is `assistant` (broker.mjs continuationEffect);
|
||||
// with several, the one named `assistant`, else the first in key order.
|
||||
const packRoute = (doc, id) => {
|
||||
const roles = doc.roles ?? {};
|
||||
let loaded = null;
|
||||
const routeOf = instance => {
|
||||
loaded ??= validateBusinessDocument(doc, `${id}.json`, { rolesDir, dataRoot });
|
||||
const { vars } = resolveInstance({ system, business: loaded, instance });
|
||||
const pick = k => (typeof vars?.[k] === 'string' && vars[k] ? vars[k] : null);
|
||||
if (!pick('harness') || !pick('model')) return null;
|
||||
return { harness: pick('harness'), model: pick('model'), ...(pick('thinking') ? { thinking: pick('thinking') } : {}) };
|
||||
};
|
||||
const by = doc.launch?.by;
|
||||
const chief = typeof by === 'string' && Object.hasOwn(roles, by) ? routeOf(by) : null;
|
||||
if (chief) return { route: chief, routeFrom: 'chief' };
|
||||
const assistants = Object.keys(roles).filter(name => isObject(roles[name]) && roles[name].definition === 'assistant');
|
||||
const assistant = assistants.includes('assistant') ? 'assistant' : assistants[0];
|
||||
const route = assistant === undefined ? null : routeOf(assistant);
|
||||
return route ? { route, routeFrom: 'assistant' } : { route: null, routeFrom: null };
|
||||
};
|
||||
const applied = doc => latestEntries(doc).map(e => ({ id: e.id, origin: e.origin ?? null, project: e.project ?? null, version: e.version ?? null,
|
||||
proposedHires: (Array.isArray(e.proposedHires) ? e.proposedHires : []).filter(isObject).map(h => ({ name: h.name, reason: h.reason ?? null })) }));
|
||||
return {
|
||||
// Shipped and installed packs only: a saved template is its owner's, read by name.
|
||||
packs: async () => ({ packs: (await installed()).map(({ id, origin, pack }) => ({ id, origin, pack })) }),
|
||||
// Shipped and installed packs only: a saved template is its owner's, read by name. `applied` is
|
||||
// the latest packs entry of each id, origin and project, and `agents` each instance's hire record.
|
||||
packs: async (id) => {
|
||||
const doc = writer.read(id).document;
|
||||
return { packs: (await installed()).map(({ id: pid, origin, pack }) => ({ id: pid, origin, pack })), applied: applied(doc), agents: agentsOf(doc) };
|
||||
},
|
||||
'pack.state': (id, args) => {
|
||||
if (typeof args.pack !== 'string' || !args.pack) bad();
|
||||
const project = args.project ?? null;
|
||||
if (project !== null && (typeof project !== 'string' || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(project))) bad();
|
||||
const { document: doc, revision } = writer.read(id);
|
||||
const saved = args.pack.startsWith(SAVED_PREFIX);
|
||||
const packId = saved ? args.pack.slice(SAVED_PREFIX.length) : args.pack;
|
||||
const entry = (doc.packs ?? []).filter(e => isObject(e) && e.id === packId && (e.project ?? null) === project && (saved ? e.origin === 'saved' : e.origin !== 'saved')).at(-1) ?? null;
|
||||
const scope = project === null ? doc.roles ?? {} : doc.projects?.[project]?.agents ?? {};
|
||||
return { revision, entry: entry ? structuredClone(entry) : null, ...packRoute(doc, id), names: Object.keys(scope), noHire: [...(doc.launch?.noHire ?? [])] };
|
||||
},
|
||||
'pack.preview': (id, args, actor, context) => build(id, args, actor, context),
|
||||
'pack.apply': async (id, args, actor, context) => {
|
||||
if (typeof args.digest !== 'string') bad();
|
||||
@@ -567,6 +631,7 @@ export async function startBroker({
|
||||
builtinBinding = null,
|
||||
modelCatalogue = null, // in-process fixture seam; boot JSON cannot supply a service
|
||||
makeProviderLoader = createLoader, // in-process fixture seam; boot JSON cannot supply a function
|
||||
initProxy = initializeProxy, // in-process fixture seam (a test install pin); boot JSON cannot supply a function
|
||||
// #1873 A3: the boot's root and project agent copies (cli config.mjs copiesAtBoot), plain data. Every
|
||||
// reload of the organization file below re-applies this snapshot, never the root file.
|
||||
copies = null,
|
||||
@@ -574,6 +639,7 @@ export async function startBroker({
|
||||
// In-process only, like librarySync; production passes none.
|
||||
copyTransport = null,
|
||||
}) {
|
||||
if (typeof initProxy !== 'function') throw new BusError('invalid-host-request');
|
||||
if (copies !== null && (typeof copies !== 'object' || Array.isArray(copies) || typeof copies.org !== 'string'
|
||||
|| !Object.hasOwn(businesses ?? {}, copies.org) || copies.copies === null || typeof copies.copies !== 'object' || Array.isArray(copies.copies)))
|
||||
throw new BusError('invalid-host-request');
|
||||
@@ -771,7 +837,72 @@ export async function startBroker({
|
||||
// records. A daily key quota moved within one agent's lineage keeps its since and its count.
|
||||
const keyLineage=(business,keyId)=>modelKeyLineage(credentials.status(),business,keyId);
|
||||
const settings=organization?launchSettings({...organization,sessions:()=>readSessions(dataRoot),levels,keyLineage}):null;
|
||||
modelCatalogues = modelCatalogue ?? (settings ? createModelCatalogue({ pluginDataRoot:instanceRoot ?? dataRoot, client: () => modelProxyClient, settings: id => settings.current(id).plugins ?? {}, proxyLock }) : null);
|
||||
// #1873 proxy-pickup: a bus started before the instance had a shared proxy picks it up at the
|
||||
// first request that needs one, through the start path's checks, loader and lock. A client got
|
||||
// that way (or by this bus's own proxy.init) is checked again at every such request and dropped
|
||||
// when the start path would now refuse it. A bus started with a proxy keeps its boot client:
|
||||
// its ModelKeys holds that client. `proxyCause` is the one plain line the owner sees while there
|
||||
// is no client: static text and a refusal code, never a path or a key.
|
||||
let lateProxy = false, proxyCause = null, proxySync = Promise.resolve();
|
||||
const dropLateProxy = cause => {
|
||||
if (lateProxy) { modelProxyClient = null; proxyPage = null; proxyPort = null; proxyLock = null; lateProxy = false; modelCatalogues?.invalidate?.(); }
|
||||
proxyCause = cause;
|
||||
};
|
||||
// The host refuses fixture-proxy-configured at boot when a dev fixture is recorded for the
|
||||
// instance and the organization routes a launch to the fixture (cli dev-fixture.mjs
|
||||
// fixtureLauncherOptions). Anything but a plain absence of the record counts as recorded.
|
||||
const fixtureRecorded = () => { try { lstatSync(join(instanceRoot ?? dataRoot, 'dev-fixture', 'fixture.json')); return true; } catch (error) { return error.code !== 'ENOENT'; } };
|
||||
const usesFixture = id => {
|
||||
try {
|
||||
const doc = settings.current(id), providers = doc.plugins?.['model-provider'];
|
||||
return (Array.isArray(providers) && providers.includes('fixture')) || Object.values(doc.launch?.models ?? {}).some(m => m?.module === 'fixture');
|
||||
} catch { return true; }
|
||||
};
|
||||
async function pickProxy() {
|
||||
if (proxy || !organization || !settings) return;
|
||||
if (org !== null && (!org || typeof org.id !== 'string' || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(org.id) || typeof instanceDataRoot !== 'string' || typeof instanceConfigDir !== 'string'))
|
||||
return dropLateProxy('This bus has no valid organization binding for the shared proxy (invalid-host-request). Restart it from the host.');
|
||||
const configDir = org ? instanceConfigDir : organization.dir;
|
||||
let found;
|
||||
try { found = loadProxy(configDir, instanceRoot ?? dataRoot); }
|
||||
catch (error) { return dropLateProxy(`The model proxy settings do not load (${/^proxy-[a-z-]+$/.test(error?.code ?? '') ? error.code : 'proxy-config-invalid'}). This organization reads no accounts or catalogue until they do.`); }
|
||||
if (found === undefined) return dropLateProxy('The model proxy has not been set up for this instance yet. Set it up on the Model proxy page.');
|
||||
if (modelProxyClient && found.port !== proxyPort) dropLateProxy(null);
|
||||
if (fixtureRecorded() && Object.keys(businesses).some(usesFixture))
|
||||
return dropLateProxy('This organization routes launches to the dev fixture, which the host refuses next to a model proxy (fixture-proxy-configured). Remove the fixture or stop using it here.');
|
||||
let client;
|
||||
try { client = await loadManagementClient({ configDir, proxy: found, receipt: proxyReceipt }); }
|
||||
catch { return dropLateProxy('The model proxy management key does not load (proxy-management-key-invalid). This bus cannot reach the proxy until the key file is fixed.'); }
|
||||
let lock = null;
|
||||
if (org) {
|
||||
try { lock = createProxyLock({ stateDir: join(instanceDataRoot, 'proxy'), identity: `${instanceConfigDir}:${found.port}` }); }
|
||||
catch { return dropLateProxy('The shared proxy lock does not load (proxy-lock-invalid). Check the proxy state for this instance, then restart this bus.'); }
|
||||
}
|
||||
proxyCause = null;
|
||||
// Same port, key and lock still load: keep the client and its page, which holds login states.
|
||||
if (modelProxyClient) return;
|
||||
modelProxyClient = client; proxyPort = found.port; proxyLock = lock; lateProxy = true;
|
||||
configureProxyPage(); modelCatalogues?.invalidate?.();
|
||||
}
|
||||
// One check at a time; an unexpected failure drops a late client, never keeps it.
|
||||
const syncProxy = () => (proxySync = proxySync.then(pickProxy).catch(() => dropLateProxy('The model proxy could not be checked (proxy-down). Try again shortly.')));
|
||||
// Unavailable with no client: the catalogue names the cause instead of a bare unavailable.
|
||||
// pickup-launch: a late client serves accounts and the catalogue, but a launch on it needs what
|
||||
// only the start path builds (ModelKeys here, the proxy in the host launcher's boot system), so
|
||||
// while this bus holds one a ready catalogue says plainly that a restart is needed. Not on an
|
||||
// unavailable one: a fence, a collision or a down proxy still refuses after a restart.
|
||||
const RESTART_TO_LAUNCH = 'Restart this organization to start agents on these models.';
|
||||
const explainCatalogue = value => {
|
||||
if (value?.status === 'unavailable' && value.reason === undefined && !modelProxyClient && proxyCause)
|
||||
return { ...value, reason: 'proxy-not-configured', notices: [proxyCause] };
|
||||
if (lateProxy && value?.status === 'ready')
|
||||
return { ...value, notices: [...(value?.notices ?? []), RESTART_TO_LAUNCH] };
|
||||
return value;
|
||||
};
|
||||
const baseCatalogue = settings ? createModelCatalogue({ pluginDataRoot:instanceRoot ?? dataRoot, client: () => modelProxyClient, settings: id => settings.current(id).plugins ?? {},
|
||||
// A view, so a lock taken by a later pickup or init counts as it does for the start path's.
|
||||
proxyLock: { assertCertain: () => proxyLock?.assertCertain(), generation: () => proxyLock?.generation() } }) : null;
|
||||
modelCatalogues = modelCatalogue ?? (baseCatalogue ? { ...baseCatalogue, read: async (id, options) => { await syncProxy(); return explainCatalogue(await baseCatalogue.read(id, options)); } } : null);
|
||||
// Resolve legacy table entries with the enabled modules' declarations. A
|
||||
// missing or ambiguous mapping never becomes an available route.
|
||||
async function catalogueFor(id, options = {}) {
|
||||
@@ -1200,8 +1331,6 @@ export async function startBroker({
|
||||
if (preview === undefined && typeof digest === 'string') return templateSave({ ...base, document, name, project, digest, assertClean });
|
||||
throw new TemplateError('invalid-request', 'template.save takes preview: true or the preview digest');
|
||||
}
|
||||
if (verb === 'system-types.installed') return installedSystemTypes({dataRoot:instanceRoot ?? dataRoot});
|
||||
if (verb === 'system-types.current') return settings.current(id).plugins?.['system-type'] ?? [];
|
||||
if(verb==='limits')return withTokens(id,settings.read(id));
|
||||
if(verb==='plugins')return {...plugins.read(id), available:{harness:levels.names ?? []}};
|
||||
// Row 256 (#1761): the actor is the reader, so endProtected is the delete check for that reader.
|
||||
@@ -1278,22 +1407,27 @@ export async function startBroker({
|
||||
// Row 199 (#1697, design section 6): issue, rotate, revoke and delete, live with no restart; each
|
||||
// rewrites or records through the organization writer, so changes.jsonl holds the receipt.
|
||||
proxyPage: async (verb, args, scope) => {
|
||||
if (!proxyPage) throw new BusError('not-configured');
|
||||
await syncProxy();
|
||||
if (!proxyPage) throw new BusError('not-configured', proxyCause ?? undefined);
|
||||
return proxyPage.request(verb, args, scope);
|
||||
},
|
||||
proxyInit: organization ? async args => {
|
||||
const settings = await initializeProxy({ configDir: organization.dir, dataRoot: instanceRoot ?? dataRoot, ...args });
|
||||
modelProxyClient = await loadManagementClient({ configDir: organization.dir, proxy: settings, receipt: proxyReceipt });
|
||||
proxyPort = settings.port;
|
||||
const settings = await initProxy({ configDir: organization.dir, dataRoot: instanceRoot ?? dataRoot, ...args });
|
||||
const client = await loadManagementClient({ configDir: organization.dir, proxy: settings, receipt: proxyReceipt });
|
||||
// #1873: an org bus that initializes the shared proxy also holds its write lock from now on.
|
||||
if (org && !proxyLock) proxyLock = createProxyLock({ stateDir: join(instanceDataRoot, 'proxy'), identity: `${instanceConfigDir}:${settings.port}` });
|
||||
configureProxyPage();
|
||||
// proxy-pickup: the lock comes first, so a lock that refuses leaves no client behind.
|
||||
const lock = org && !proxyLock ? createProxyLock({ stateDir: join(instanceDataRoot, 'proxy'), identity: `${instanceConfigDir}:${settings.port}` }) : proxyLock;
|
||||
// proxy-pickup: a client this bus did not boot with is checked again like a picked-up one.
|
||||
if (!proxy) { lateProxy = true; proxyCause = null; }
|
||||
modelProxyClient = client; proxyPort = settings.port; proxyLock = lock;
|
||||
configureProxyPage(); modelCatalogues?.invalidate?.();
|
||||
return settings;
|
||||
} : null,
|
||||
// #1873: clear the uncertain-write fence only on restart evidence this host re-proves: the
|
||||
// process on the proxy port is new, alive and started after the fence was set.
|
||||
proxyFenceClear: organization ? async ({ evidence }) => {
|
||||
if (!proxyLock || !modelProxyClient) throw new BusError('not-configured');
|
||||
await syncProxy();
|
||||
if (!proxyLock || !modelProxyClient) throw new BusError('not-configured', proxyCause ?? undefined);
|
||||
return proxyLock.clear({ restarted: true, read: () => modelProxyClient.getKeys(), verify: previous => verifyRestart(evidence, { fence: previous, port: proxyPort }) });
|
||||
} : null,
|
||||
credentialVerbs: organization
|
||||
|
||||
@@ -13,8 +13,8 @@ import { join, isAbsolute } from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
const ddl = readFileSync(new URL('../schema.sql', import.meta.url), 'utf8');
|
||||
export const SCHEMA_SHA256 = 'e5868996851ee60a3c6d2798a17b9da446ba666c859d84d1b575ca5104ae61f8';
|
||||
export const SCHEMA_VERSION = '3v';
|
||||
export const SCHEMA_SHA256 = '1c305d842619360c14c8388cd43cb9de81afbe46ff0662fd5de9851be9ff3ea0';
|
||||
export const SCHEMA_VERSION = '3w';
|
||||
// Ordered, named offline steps. New schema changes append a step and keep prior DDL pinned.
|
||||
const legacyDDL = readFileSync(new URL('./migrations/3b.sql', import.meta.url), 'utf8');
|
||||
const LEGACY_SHA256 = '179ffe356d4ff19a49b5ebad39b6c6bfd7771deb8e1b7c55b5e746f039d69e65';
|
||||
@@ -120,6 +120,11 @@ const migrations = [{
|
||||
// Only a new append-only table, its index and its guards; no existing row changes.
|
||||
from: '3u', to: '3v',
|
||||
sql: readFileSync(new URL('./migrations/3u-3v.sql', import.meta.url), 'utf8'),
|
||||
}, {
|
||||
// SP9 (#1873, Jason's ruling 2026-11-12): drops the table 3t-3u created, its index and its four
|
||||
// guards, with its rows.
|
||||
from: '3v', to: '3w',
|
||||
sql: readFileSync(new URL('./migrations/3v-3w.sql', import.meta.url), 'utf8'),
|
||||
}];
|
||||
const timedTables = [
|
||||
'events',
|
||||
@@ -146,7 +151,6 @@ const timedTables = [
|
||||
'request_snapshot_events',
|
||||
'request_project_events',
|
||||
'project_archives',
|
||||
'project_system_types',
|
||||
'store_tasks',
|
||||
];
|
||||
const hex = (value) => createHash('sha256').update(value).digest('hex');
|
||||
|
||||
@@ -15,7 +15,7 @@ if (!process.env.MOSAIC_BUS_TESTER_NONCE) {
|
||||
// P19 #876: only the re-executed child, whose initial environment holds the nonce, talks to the
|
||||
// bus. Loading the client (and the broker module graph behind it) here instead of at the top
|
||||
// keeps the re-exec parent to a bare node start.
|
||||
const { Client } = await import('./client.mjs');
|
||||
const { Client, NOT_SENT_EXIT } = await import('./client.mjs');
|
||||
const { readProcess } = await import('./human.mjs');
|
||||
try {
|
||||
const request = JSON.parse(readFileSync(0, 'utf8'));
|
||||
@@ -39,5 +39,6 @@ try {
|
||||
process.stdout.write(JSON.stringify(result) + '\n');
|
||||
} catch (e) {
|
||||
process.stderr.write((/^[a-z-]{1,64}$/.test(e.code ?? '') ? e.code : 'invalid-request') + '\n');
|
||||
process.exitCode = 2;
|
||||
// E2E6 fix 6: as human-cli.mjs, a request that never left exits NOT_SENT_EXIT.
|
||||
process.exitCode = e?.notSent === true ? NOT_SENT_EXIT : 2;
|
||||
}
|
||||
@@ -19,7 +19,7 @@ const here = (p) => new URL(p, import.meta.url);
|
||||
const SESSIONS_3L = ['sessions', 'session_defaults', 'thread_claims', 'message_threads', 'thread_opens'];
|
||||
// Row 206 (#1704): and the 3l→3m step's thread_shares. thread-shares.test.mjs tests it.
|
||||
// Row 271 (#1776): and the 3m→3n step's session_ops and message_cancels. session-clear.test.mjs tests them.
|
||||
const later3l = (r) => [...SESSIONS_3L, 'thread_shares', 'session_ops', 'message_cancels', 'project_archives', 'project_system_types', 'store_tasks', 'request_events', 'request_effects', 'request_snapshots', 'request_snapshot_events', 'request_project_events'].includes(r.tbl_name) || ['delivery_same_thread', 'delivery_same_session', 'threads_id_not_session'].includes(r.name);
|
||||
const later3l = (r) => [...SESSIONS_3L, 'thread_shares', 'session_ops', 'message_cancels', 'project_archives', 'store_tasks', 'request_events', 'request_effects', 'request_snapshots', 'request_snapshot_events', 'request_project_events'].includes(r.tbl_name) || ['delivery_same_thread', 'delivery_same_session', 'threads_id_not_session'].includes(r.name);
|
||||
function source3h(t) {
|
||||
const root = mkdtempSync(join(tmpdir(), 'account-migrate-'));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
@@ -96,6 +96,7 @@ async function engine(root, name, { store, schema, step = (s) => s }) {
|
||||
copyFileSync(here('../src/migrations/3s-3t.sql'), join(moduleRoot, 'src/migrations/3s-3t.sql'));
|
||||
copyFileSync(here('../src/migrations/3t-3u.sql'), join(moduleRoot, 'src/migrations/3t-3u.sql'));
|
||||
copyFileSync(here('../src/migrations/3u-3v.sql'), join(moduleRoot, 'src/migrations/3u-3v.sql'));
|
||||
copyFileSync(here('../src/migrations/3v-3w.sql'), join(moduleRoot, 'src/migrations/3v-3w.sql'));
|
||||
return (await import(pathToFileURL(join(moduleRoot, 'src/store.mjs')))).Store;
|
||||
}
|
||||
|
||||
@@ -103,7 +104,7 @@ test('REQ-LIMIT-4 3h copy migrates to 3i: every row keeps its seq, the sequence
|
||||
const { root, path } = source3h(t), before = snapshot(path), was = master(path);
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
new Store(root, { migrateSchema: true }).close();
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
// Every table's rows as they were, usage_records with its seq values and sqlite_sequence with 50.
|
||||
assert.deepEqual(migrated3l(snapshot(path, before.columns).rows), before.rows);
|
||||
assert.deepEqual(before.rows.usage_records.map(r => r.seq), [1, 2, 3]);
|
||||
@@ -153,7 +154,7 @@ test('REQ-LIMIT-4 a 3h→3i step that fails partway leaves the store at 3h with
|
||||
assert.deepEqual(snapshot(path, before.columns).rows, before.rows);
|
||||
// Still a whole 3h store: the real step migrates it.
|
||||
new Store(root, { migrateSchema: true }).close();
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.deepEqual(migrated3l(snapshot(path, before.columns).rows), before.rows);
|
||||
});
|
||||
|
||||
@@ -165,14 +166,14 @@ test('REQ-LIMIT-4 the 3h engine refuses a migrated store, migrating or not, and
|
||||
schema: ddl3h,
|
||||
store: (source) => source
|
||||
.replace(/export const SCHEMA_SHA256 = '[a-f0-9]+';/, `export const SCHEMA_SHA256 = '${createHash('sha256').update(ddl3h).digest('hex')}';`)
|
||||
.replace("export const SCHEMA_VERSION = '3v';", "export const SCHEMA_VERSION = '3h';")
|
||||
.replace("export const SCHEMA_VERSION = '3w';", "export const SCHEMA_VERSION = '3h';")
|
||||
.replace(/\}, \{\n {2}\/\/ Row 126 \(#1620\)[\s\S]*?\}\];\nconst timedTables/, '}];\nconst timedTables'),
|
||||
});
|
||||
const pinned = readFileSync(join(root, 'engine-3h/src/store.mjs'), 'utf8');
|
||||
assert.ok(pinned.includes("export const SCHEMA_VERSION = '3h';") && !pinned.includes('3h-3i'), 'the 3h engine has no 3h→3i step');
|
||||
assert.throws(() => new Store3h(root), /schema-mismatch/);
|
||||
assert.throws(() => new Store3h(root, { migrateSchema: true }), /schema-mismatch/);
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.deepEqual(master(path), was);
|
||||
assert.deepEqual(snapshot(path, after.columns).rows, after.rows);
|
||||
});
|
||||
@@ -64,7 +64,7 @@ test('AU authority reverse crossing deadline in prepared IO never publishes',asy
|
||||
});
|
||||
test('AU authority resolver rechecks budget removal after a proposal was raised',async t=>{
|
||||
const f=world(t),d=await f.raise(),b=structuredClone(f.loaded());b.plugins['limit-check']=[];f.broker.reloadBusiness('demo',b);
|
||||
const before=f.writer.read('demo').revision;await assert.rejects(f.call('judge','decision.resolve',{id:d.id,choice:'yes'}),{code:'autonomy-precondition'});
|
||||
const before=f.writer.read('demo').revision;await assert.rejects(f.call('judge','decision.resolve',{id:d.id,choice:'yes'}),{code:'autonomy-precondition',reason:'no enforced budget covers new agents; authority away from the loop needs one'});
|
||||
assert.equal(f.writer.read('demo').revision,before);assert.equal(f.store.get('SELECT count(*) n FROM decision_events WHERE decision=?',d.id).n,0);
|
||||
});
|
||||
|
||||
@@ -113,7 +113,7 @@ test('AU an account-quota authority raise routes to the resolver only when the h
|
||||
const covered=world(t,{account:true,countsAccount:name=>name==='pi'}),d=await covered.raise();assert.equal(d.route_to,'judge');
|
||||
for(const countsAccount of [undefined,()=>false,()=>null]){
|
||||
const f=world(t,{account:true,countsAccount});
|
||||
await assert.rejects(f.raise(),{code:'autonomy-precondition'});
|
||||
await assert.rejects(f.raise(),{code:'autonomy-precondition',reason:'no enforced budget covers new agents; authority away from the loop needs one'});
|
||||
assert.equal(f.store.get("SELECT count(*) n FROM decisions").n,0);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -137,11 +137,11 @@ test('AU authority near requires an enforced organization budget covering every
|
||||
const f=await settingsFixture(t);
|
||||
for(const tokens of [{},{instances:{coder:tokenCap}},{providers:{unrelated:tokenCap}}]){
|
||||
f.business.launch.limits.tokens=tokens;f.broker.reloadBusiness('demo',f.business);
|
||||
await assert.rejects(f.set(authorityNear),{code:'autonomy-precondition'});
|
||||
await assert.rejects(f.set(authorityNear),{code:'autonomy-precondition',reason:'no enforced budget covers new agents; authority away from the loop needs one'});
|
||||
}
|
||||
f.business.launch.limits.tokens={providers:{anthropic:{...tokenCap,limit:0}}};
|
||||
f.business.plugins={'limit-check':[]};f.broker.reloadBusiness('demo',f.business);
|
||||
await assert.rejects(f.set(authorityNear),{code:'autonomy-precondition'});
|
||||
await assert.rejects(f.set(authorityNear),{code:'autonomy-precondition',reason:'no enforced budget covers new agents; authority away from the loop needs one'});
|
||||
f.business.plugins={'limit-check':['token-limit']};f.broker.reloadBusiness('demo',f.business);
|
||||
await f.set(authorityNear);assert.equal(f.writes(),1);
|
||||
});
|
||||
@@ -153,12 +153,20 @@ test('AU authority out refuses until per-definition agent limits exist, even wit
|
||||
await assert.rejects(f.set({...authorityNear,authority:'out of the loop'}),e=>e.code==='authority-limits-unavailable' && /near the loop/.test(e.nextStep));
|
||||
assert.equal(f.writes(),1);
|
||||
});
|
||||
test('AU a class moves out of the loop only from near the loop, and the refusal says so (E2E6 fix 7)',async t=>{
|
||||
const f=await settingsFixture(t);await f.set({'cross-role':'in the loop'});
|
||||
await assert.rejects(f.set({'cross-role':'out of the loop',notices:true}),{code:'autonomy-precondition',reason:'cross-role moves out of the loop only from near the loop'});
|
||||
assert.equal(f.writes(),1);
|
||||
});
|
||||
test('AU moving out requires an actual near resolution and a later owner review',async t=>{
|
||||
const f=await settingsFixture(t);await f.set({merge:'in the loop'});await f.set({merge:'near the loop',notices:true});
|
||||
// E2E6 fix 7: each refusal names the check that failed.
|
||||
await assert.rejects(f.set({merge:'near the loop'}),{code:'autonomy-precondition',reason:'owner notices are off; a class near the loop needs them on'});
|
||||
await assert.rejects(f.set({merge:'out of the loop',notices:true}),{code:'autonomy-precondition',reason:'merge needs your review of its trail since the last autonomy change'});
|
||||
f.call(f.owner,'autonomy.review.console',{decisionClass:'merge'});
|
||||
await assert.rejects(f.set({merge:'out of the loop',notices:true}),{code:'autonomy-precondition'});
|
||||
await assert.rejects(f.set({merge:'out of the loop',notices:true}),{code:'autonomy-precondition',reason:'merge needs a near-loop decision since the last autonomy change, and your trail review after it'});
|
||||
const d=f.raise({action:'git.merge.protected'});f.call(f.chief,'decision.resolve',{id:d.id,choice:'yes'});
|
||||
await assert.rejects(f.set({merge:'out of the loop',notices:true}),{code:'autonomy-precondition'});
|
||||
await assert.rejects(f.set({merge:'out of the loop',notices:true}),{code:'autonomy-precondition',reason:'merge needs a near-loop decision since the last autonomy change, and your trail review after it'});
|
||||
f.call(f.owner,'autonomy.review.console',{decisionClass:'merge'});
|
||||
await f.set({merge:'out of the loop',notices:true});
|
||||
});
|
||||
@@ -11,6 +11,8 @@
|
||||
// which shares humanCall's spawn as transport(). The human proof and its spawn are unchanged.
|
||||
// Row 225 (C2-10b) re-pins webui bus.mjs for one STATUS entry, library-revert-not-agent: 409; no proof
|
||||
// or transport change.
|
||||
// E2E6 fix 6 re-pins human-cli.mjs, which exits 5 when its connect failed before the request was
|
||||
// written, and cli transport.mjs, which reads that exit as bus-not-running. The proof is unchanged.
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { createHash } from "node:crypto";
|
||||
@@ -21,9 +23,10 @@ import { Client } from "../src/client.mjs";
|
||||
|
||||
const baselines = {
|
||||
"packages/bus/src/human.mjs": "bb13c146717cdc46d75d157177e400edac4d3e10f14fe511027a25fd44cec885",
|
||||
"packages/bus/src/human-cli.mjs": "271b9781d73cf31cc562a56180e3ebcd725b5fde148a83347a201fdef2fc28af",
|
||||
"packages/bus/src/human-cli.mjs": "410892787cc70440b0ba4c45d6f24861d12ee5e70cba678cfeb1ed86b796c149",
|
||||
// Row 239 (#1745): EXIT outcome-unknown-revoked 1; no proof or transport change.
|
||||
"packages/cli/src/transport.mjs": "662642a8ce739fcb6c188ad07125a94e008c8a305eced127c8041d472c56e55b",
|
||||
// E2E6 fix 6: shim exit 5 with outcome-unknown becomes bus-not-running (exit 3, start and recover next).
|
||||
"packages/cli/src/transport.mjs": "101870f7ffb47a9cbd54ebd8c1901734cc9f442d6770cb2a0d059afd4d14b160",
|
||||
// Row 165 (#1662): seven STATUS entries for the role instance routes (organization-instance-exists,
|
||||
// organization-unknown-instance, organization-credentials-out-of-scope, organization-launch-not-configured,
|
||||
// organization-no-change, organization-project-mismatch, organization-unresolvable-instance), no proof or
|
||||
@@ -39,7 +42,8 @@ const baselines = {
|
||||
// deadline; userCall shares transport(). Nonces, argv and limits are unchanged.
|
||||
// #1873 A3: STATUS maps credential-unbound, copy-refused, project-refused and project-agent-elsewhere
|
||||
// to 409; no proof or transport change.
|
||||
"packages/webui/src/bus.mjs": "d8f3e0eb5299fdb192e98a1238ca693aae7c36af9a21de72d5f5d39610589377",
|
||||
// #1873 triage-fence: STATUS maps template-system-only to 400; no proof or transport change.
|
||||
"packages/webui/src/bus.mjs": "cd08e1beb49e9e881bb1b308f2ab3343a480b47dd9b17ccbd16e120d341d7511",
|
||||
};
|
||||
const repoFile = path => new URL("../../../" + path, import.meta.url);
|
||||
|
||||
|
||||
@@ -615,7 +615,7 @@ async function database3c(t) {
|
||||
let source = readFileSync(here('../src/store.mjs'), 'utf8');
|
||||
const pinned = source
|
||||
.replace(/export const SCHEMA_SHA256 = '[a-f0-9]+';/, `export const SCHEMA_SHA256 = '${createHash('sha256').update(ddl3c).digest('hex')}';`)
|
||||
.replace("export const SCHEMA_VERSION = '3v';", "export const SCHEMA_VERSION = '3c';")
|
||||
.replace("export const SCHEMA_VERSION = '3w';", "export const SCHEMA_VERSION = '3c';")
|
||||
.replace(/\}, \{\n {2}from: '3c',[\s\S]*?\}\];\nconst timedTables/, '}];\nconst timedTables');
|
||||
assert.notEqual(pinned, source);
|
||||
assert.ok(!pinned.includes('3c-3d'), 'the 3c engine has no 3c→3d step');
|
||||
@@ -639,7 +639,7 @@ test('REQ-ROLE-2, REQ-COS-1: the 3c→3d migration lets the chief of staff end a
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
const store = new Store(root, { migrateSchema: true });
|
||||
t.after(() => store.close());
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3v');
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3w');
|
||||
assert.equal(store.get("SELECT body FROM events WHERE id='preserved'").body, '{"fixture":true}');
|
||||
assert.equal(store.get("SELECT holder_run FROM role_claims WHERE role='coder'").holder_run, 'coder-run');
|
||||
const b = new Broker({ store, businesses: demo(), organization: null });
|
||||
|
||||
@@ -33,7 +33,7 @@ test('explicit 3b copy migration preserves evidence and opens as 3g; normal star
|
||||
const original = readFileSync(source);
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
const store = new Store(root, { migrateSchema: true });
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3v');
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3w');
|
||||
assert.equal(store.get("SELECT body FROM events WHERE id='preserved'").body, '{"fixture":true}');
|
||||
assert.equal(store.get('SELECT count(*) n FROM task_comment_cursors').n, 0);
|
||||
const epoch = store.get("SELECT value FROM meta WHERE key='comment_cursor_epoch'").value;
|
||||
@@ -75,15 +75,15 @@ test('named migration registry chains 3b through 3g to a fixture-only future ver
|
||||
const sha = createHash('sha256').update(futureDDL).digest('hex');
|
||||
let source = readFileSync(new URL('../src/store.mjs', import.meta.url), 'utf8');
|
||||
source = source.replace(/export const SCHEMA_SHA256 = '[a-f0-9]+';/, `export const SCHEMA_SHA256 = '${sha}';`)
|
||||
.replace("export const SCHEMA_VERSION = '3v';", "export const SCHEMA_VERSION = '3w';")
|
||||
.replace('}];\nconst timedTables', `}, { from: '3v', to: '3w', sql: ${JSON.stringify(futureSQL)} }];\nconst timedTables`);
|
||||
.replace("export const SCHEMA_VERSION = '3w';", "export const SCHEMA_VERSION = '3x';")
|
||||
.replace('}];\nconst timedTables', `}, { from: '3w', to: '3x', sql: ${JSON.stringify(futureSQL)} }];\nconst timedTables`);
|
||||
writeFileSync(join(moduleRoot, 'src/store.mjs'), source);
|
||||
writeFileSync(join(moduleRoot, 'schema.sql'), futureDDL);
|
||||
for (const name of ['3b.sql', '3b-3c.sql', '3c-3d.sql', '3d-3e.sql', '3e-3f.sql', '3f-3g.sql', '3g-3h.sql', '3h-3i.sql', '3i-3j.sql', '3j-3k.sql', '3k-3l.sql', '3l-3m.sql', '3m-3n.sql', '3n-3o.sql', '3o-3p.sql', '3p-3q.sql', '3q-3r.sql', '3r-3s.sql', '3s-3t.sql', '3t-3u.sql', '3u-3v.sql'])
|
||||
for (const name of ['3b.sql', '3b-3c.sql', '3c-3d.sql', '3d-3e.sql', '3e-3f.sql', '3f-3g.sql', '3g-3h.sql', '3h-3i.sql', '3i-3j.sql', '3j-3k.sql', '3k-3l.sql', '3l-3m.sql', '3m-3n.sql', '3n-3o.sql', '3o-3p.sql', '3p-3q.sql', '3q-3r.sql', '3r-3s.sql', '3s-3t.sql', '3t-3u.sql', '3u-3v.sql', '3v-3w.sql'])
|
||||
copyFileSync(new URL('../src/migrations/' + name, import.meta.url), join(moduleRoot, 'src/migrations', name));
|
||||
const { Store: FutureStore } = await import(pathToFileURL(join(moduleRoot, 'src/store.mjs')));
|
||||
const future = new FutureStore(root, { migrateSchema: true });
|
||||
assert.equal(future.get("SELECT value FROM meta WHERE key='schema_version'").value, '3w');
|
||||
assert.equal(future.get("SELECT value FROM meta WHERE key='schema_version'").value, '3x');
|
||||
assert.equal(future.get("SELECT name FROM sqlite_master WHERE name='future_fixture'").name, 'future_fixture');
|
||||
assert.equal(future.get("SELECT count(*) n FROM task_comment_cursors").n, 0);
|
||||
assert.equal(future.get("SELECT id FROM events").id, 'preserved');
|
||||
@@ -109,7 +109,7 @@ test('offline command migrates only the supplied fixture root and reports usage
|
||||
const command = new URL('../src/migrate-schema.mjs', import.meta.url).pathname;
|
||||
const migrated = spawnSync(process.execPath, [command, root], { encoding: 'utf8' });
|
||||
assert.equal(migrated.status, 0, migrated.stderr);
|
||||
assert.match(migrated.stdout, /bus schema 3v ready/);
|
||||
assert.match(migrated.stdout, /bus schema 3w ready/);
|
||||
new Store(root).close();
|
||||
const usage = spawnSync(process.execPath, [command], { encoding: 'utf8' });
|
||||
assert.equal(usage.status, 2);
|
||||
|
||||
@@ -89,7 +89,7 @@ function setup(t) {
|
||||
// #797 / #1839 adds the owner-only artifact read to the existing decision and request controls;
|
||||
// no unsuffixed verb is ever a console verb.
|
||||
test('N4: owner Console verbs have an explicit immutable whitelist and exclude decision.resolve', () => {
|
||||
assert.deepEqual([...CONSOLE_VERBS], ['system-types.console', 'project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
|
||||
assert.deepEqual([...CONSOLE_VERBS], ['project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'pack.hire.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
|
||||
'request.get.console', 'request.projects.console', 'request.answer.console', 'request.attach.console', 'request.cancel.console',
|
||||
// Starter packs SP4 (#1873): the owner's pack list and preview, and the three pack writes.
|
||||
'packs.console', 'pack.preview.console', 'pack.apply.console', 'board.set.console', 'workflow.set.console',
|
||||
|
||||
@@ -36,11 +36,11 @@ function source3j(t) {
|
||||
const SESSIONS_3L = ['sessions', 'session_defaults', 'thread_claims', 'message_threads', 'thread_opens'];
|
||||
// Row 206 (#1704): and the 3l→3m step's thread_shares. thread-shares.test.mjs tests it.
|
||||
// Row 271 (#1776): and the 3m→3n step's session_ops and message_cancels. session-clear.test.mjs tests them.
|
||||
const later3l = (r) => [...SESSIONS_3L, 'thread_shares', 'session_ops', 'message_cancels', 'project_archives', 'project_system_types', 'store_tasks', 'request_events', 'request_effects', 'request_snapshots', 'request_snapshot_events', 'request_project_events'].includes(r.tbl_name) || ['delivery_same_thread', 'delivery_same_session', 'threads_id_not_session'].includes(r.name);
|
||||
const later3l = (r) => [...SESSIONS_3L, 'thread_shares', 'session_ops', 'message_cancels', 'project_archives', 'store_tasks', 'request_events', 'request_effects', 'request_snapshots', 'request_snapshot_events', 'request_project_events'].includes(r.tbl_name) || ['delivery_same_thread', 'delivery_same_session', 'threads_id_not_session'].includes(r.name);
|
||||
function rows(path) {
|
||||
const db = new DatabaseSync(path, { readOnly: true });
|
||||
try {
|
||||
return Object.fromEntries(db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT IN ('gitea_users','gitea_grants','sessions','session_defaults','thread_shares','session_ops','message_cancels','request_events','request_effects','request_snapshots','request_snapshot_events','request_project_events','project_archives','project_system_types','store_tasks')").all()
|
||||
return Object.fromEntries(db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT IN ('gitea_users','gitea_grants','sessions','session_defaults','thread_shares','session_ops','message_cancels','request_events','request_effects','request_snapshots','request_snapshot_events','request_project_events','project_archives','store_tasks')").all()
|
||||
.map(({ name }) => [name, db.prepare(`SELECT * FROM ${name} ORDER BY rowid`).all()
|
||||
.filter(r => name !== 'meta' || !['schema_version', 'schema_digest'].includes(r.key)).map(r => ({ ...r }))]));
|
||||
} finally { db.close(); }
|
||||
@@ -86,6 +86,7 @@ async function engine(root, name, { store, schema, step = (s) => s }) {
|
||||
copyFileSync(here('../src/migrations/3s-3t.sql'), join(moduleRoot, 'src/migrations/3s-3t.sql'));
|
||||
copyFileSync(here('../src/migrations/3t-3u.sql'), join(moduleRoot, 'src/migrations/3t-3u.sql'));
|
||||
copyFileSync(here('../src/migrations/3u-3v.sql'), join(moduleRoot, 'src/migrations/3u-3v.sql'));
|
||||
copyFileSync(here('../src/migrations/3v-3w.sql'), join(moduleRoot, 'src/migrations/3v-3w.sql'));
|
||||
return (await import(pathToFileURL(join(moduleRoot, 'src/store.mjs')))).Store;
|
||||
}
|
||||
function fresh(t) {
|
||||
@@ -107,7 +108,7 @@ test('3j copy migrates to 3k: every row kept, and sqlite_master gains only the t
|
||||
const { root, path } = source3j(t), before = rows(path), was = master(path);
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
new Store(root, { migrateSchema: true }).close();
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.deepEqual(migrated3l(rows(path)), before);
|
||||
const now = master(path);
|
||||
assert.deepEqual(now.filter(r => !NEW.includes(r.name) && !later3l(r)), was.filter(r => !later3l(r)));
|
||||
@@ -133,7 +134,7 @@ test('a 3j→3k step that fails partway leaves the store at 3j with every row an
|
||||
assert.deepEqual(master(path), was);
|
||||
assert.deepEqual(rows(path), before);
|
||||
new Store(root, { migrateSchema: true }).close();
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
});
|
||||
|
||||
test('the 3j engine refuses a migrated store, migrating or not, and leaves it as it was', async t => {
|
||||
@@ -144,14 +145,14 @@ test('the 3j engine refuses a migrated store, migrating or not, and leaves it as
|
||||
schema: ddl3j,
|
||||
store: (source) => source
|
||||
.replace(/export const SCHEMA_SHA256 = '[a-f0-9]+';/, `export const SCHEMA_SHA256 = '${createHash('sha256').update(ddl3j).digest('hex')}';`)
|
||||
.replace("export const SCHEMA_VERSION = '3v';", "export const SCHEMA_VERSION = '3j';")
|
||||
.replace("export const SCHEMA_VERSION = '3w';", "export const SCHEMA_VERSION = '3j';")
|
||||
.replace(/\}, \{\n {2}\/\/ Row 236 \(#1742[\s\S]*?\}\];\nconst timedTables/, '}];\nconst timedTables'),
|
||||
});
|
||||
const pinned = readFileSync(join(root, 'engine-3j/src/store.mjs'), 'utf8');
|
||||
assert.ok(pinned.includes("export const SCHEMA_VERSION = '3j';") && !pinned.includes('3j-3k'), 'the 3j engine has no 3j→3k step');
|
||||
assert.throws(() => new Store3j(root), /schema-mismatch/);
|
||||
assert.throws(() => new Store3j(root, { migrateSchema: true }), /schema-mismatch/);
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.deepEqual(master(path), was);
|
||||
assert.deepEqual(rows(path), after);
|
||||
});
|
||||
|
||||
@@ -22,7 +22,7 @@ const LATER = ['gitea_users', 'gitea_grants', 'sqlite_autoindex_gitea_users_1',
|
||||
const SESSIONS_3L = ['sessions', 'session_defaults', 'thread_claims', 'message_threads', 'thread_opens'];
|
||||
// Row 206 (#1704): and the 3l→3m step's thread_shares. thread-shares.test.mjs tests it.
|
||||
// Row 271 (#1776): and the 3m→3n step's session_ops and message_cancels. session-clear.test.mjs tests them.
|
||||
const later3l = (r) => [...SESSIONS_3L, 'thread_shares', 'session_ops', 'message_cancels', 'project_archives', 'project_system_types', 'store_tasks', 'request_events', 'request_effects', 'request_snapshots', 'request_snapshot_events', 'request_project_events'].includes(r.tbl_name) || ['delivery_same_thread', 'delivery_same_session', 'threads_id_not_session'].includes(r.name);
|
||||
const later3l = (r) => [...SESSIONS_3L, 'thread_shares', 'session_ops', 'message_cancels', 'project_archives', 'store_tasks', 'request_events', 'request_effects', 'request_snapshots', 'request_snapshot_events', 'request_project_events'].includes(r.tbl_name) || ['delivery_same_thread', 'delivery_same_session', 'threads_id_not_session'].includes(r.name);
|
||||
function source3i(t) {
|
||||
const root = mkdtempSync(join(tmpdir(), 'grant-migrate-'));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
@@ -42,7 +42,7 @@ function source3i(t) {
|
||||
function rows(path) {
|
||||
const db = new DatabaseSync(path, { readOnly: true });
|
||||
try {
|
||||
return Object.fromEntries(db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT IN ('hosts','host_grants','gitea_users','gitea_grants','sessions','session_defaults','thread_shares','session_ops','message_cancels','request_events','request_effects','request_snapshots','request_snapshot_events','request_project_events','project_archives','project_system_types','store_tasks')").all()
|
||||
return Object.fromEntries(db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT IN ('hosts','host_grants','gitea_users','gitea_grants','sessions','session_defaults','thread_shares','session_ops','message_cancels','request_events','request_effects','request_snapshots','request_snapshot_events','request_project_events','project_archives','store_tasks')").all()
|
||||
.map(({ name }) => [name, db.prepare(`SELECT * FROM ${name} ORDER BY rowid`).all()
|
||||
.filter(r => name !== 'meta' || !['schema_version', 'schema_digest'].includes(r.key)).map(r => ({ ...r }))]));
|
||||
} finally { db.close(); }
|
||||
@@ -89,6 +89,7 @@ async function engine(root, name, { store, schema, step = (s) => s }) {
|
||||
copyFileSync(here('../src/migrations/3s-3t.sql'), join(moduleRoot, 'src/migrations/3s-3t.sql'));
|
||||
copyFileSync(here('../src/migrations/3t-3u.sql'), join(moduleRoot, 'src/migrations/3t-3u.sql'));
|
||||
copyFileSync(here('../src/migrations/3u-3v.sql'), join(moduleRoot, 'src/migrations/3u-3v.sql'));
|
||||
copyFileSync(here('../src/migrations/3v-3w.sql'), join(moduleRoot, 'src/migrations/3v-3w.sql'));
|
||||
return (await import(pathToFileURL(join(moduleRoot, 'src/store.mjs')))).Store;
|
||||
}
|
||||
function fresh(t) {
|
||||
@@ -112,7 +113,7 @@ test('3i copy migrates to 3j: every row kept, and sqlite_master gains only the t
|
||||
const { root, path } = source3i(t), before = rows(path), was = master(path);
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
new Store(root, { migrateSchema: true }).close();
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.deepEqual(migrated3l(rows(path)), before);
|
||||
const now = master(path).filter(r => !LATER.includes(r.name));
|
||||
assert.deepEqual(now.filter(r => !NEW.includes(r.name) && !later3l(r)), was.filter(r => !later3l(r)));
|
||||
@@ -137,7 +138,7 @@ test('a 3i→3j step that fails partway leaves the store at 3i with every row an
|
||||
assert.deepEqual(master(path), was);
|
||||
assert.deepEqual(rows(path), before);
|
||||
new Store(root, { migrateSchema: true }).close();
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
});
|
||||
|
||||
test('the 3i engine refuses a migrated store, migrating or not, and leaves it as it was', async t => {
|
||||
@@ -148,14 +149,14 @@ test('the 3i engine refuses a migrated store, migrating or not, and leaves it as
|
||||
schema: ddl3i,
|
||||
store: (source) => source
|
||||
.replace(/export const SCHEMA_SHA256 = '[a-f0-9]+';/, `export const SCHEMA_SHA256 = '${createHash('sha256').update(ddl3i).digest('hex')}';`)
|
||||
.replace("export const SCHEMA_VERSION = '3v';", "export const SCHEMA_VERSION = '3i';")
|
||||
.replace("export const SCHEMA_VERSION = '3w';", "export const SCHEMA_VERSION = '3i';")
|
||||
.replace(/\}, \{\n {2}\/\/ Row 234 \(#1740\)[\s\S]*?\}\];\nconst timedTables/, '}];\nconst timedTables'),
|
||||
});
|
||||
const pinned = readFileSync(join(root, 'engine-3i/src/store.mjs'), 'utf8');
|
||||
assert.ok(pinned.includes("export const SCHEMA_VERSION = '3i';") && !pinned.includes('3i-3j'), 'the 3i engine has no 3i→3j step');
|
||||
assert.throws(() => new Store3i(root), /schema-mismatch/);
|
||||
assert.throws(() => new Store3i(root, { migrateSchema: true }), /schema-mismatch/);
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.deepEqual(master(path), was);
|
||||
assert.deepEqual(rows(path), after);
|
||||
});
|
||||
|
||||
@@ -11,7 +11,7 @@ import { tmpdir } from 'node:os';
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { Credentials } from '../src/credentials.mjs';
|
||||
import { ManagementClient } from '../../model-proxy/src/client.mjs';
|
||||
import { ModelKeys, REVOKE_TIMEOUT_MS, REVOKE_POLL_MS } from '../src/model-keys.mjs';
|
||||
import { ModelKeys, REVOKE_TIMEOUT_MS, REVOKE_POLL_MS, ISSUE_PROBE_TIMEOUT_MS, ISSUE_REPROBE_MIN_MS } from '../src/model-keys.mjs';
|
||||
import { startBroker } from '../src/runtime.mjs';
|
||||
import { busOrganization } from '../src/organization-context.mjs';
|
||||
import { Registry } from '../../seat/src/session.mjs';
|
||||
@@ -42,6 +42,7 @@ async function fixture(t, { delayed = 0 } = {}) {
|
||||
const key = req.headers.authorization?.slice(7);
|
||||
const accepted = state.keys.includes(key) || (state.removed.has(key) && performance.now() - state.removed.get(key) < state.delay);
|
||||
state.onProbe?.(state.status ?? (accepted ? 200 : 401));
|
||||
if (state.stallProbe?.()) return;
|
||||
res.writeHead(state.status ?? (accepted ? 200 : 401)); res.end('{}');
|
||||
});
|
||||
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
||||
@@ -123,10 +124,33 @@ test('proxy-revoke-revision-conflict keeps local revoking record and ids-only re
|
||||
assert.equal(JSON.stringify(f.receipts).includes(key), false);
|
||||
await f.create().reconcile(); assert.equal(f.credentials.modelRecord('demo/coder') === null, true);
|
||||
});
|
||||
for (const status of [401, 503, 302]) test(`proxy-key-refused: preflight rejects HTTP ${status} with exactly one probe`, async t => {
|
||||
for (const status of [503, 302]) test(`proxy-key-refused: preflight rejects HTTP ${status} with exactly one probe`, async t => {
|
||||
const f = await fixture(t); await f.manager.reconcile(); await f.manager.ensure('demo/coder'); f.state.status = status;
|
||||
await assert.rejects(f.manager.preflight('demo/coder'), failCode('proxy-key-refused')); assert.equal(f.state.probes, 1);
|
||||
});
|
||||
test('proxy-key-refused: a key that keeps answering 401 refuses once the short probe deadline passes', async t => {
|
||||
const f = await fixture(t); await f.manager.reconcile(); await f.manager.ensure('demo/coder'); f.state.status = 401;
|
||||
const started = performance.now();
|
||||
await assert.rejects(f.manager.preflight('demo/coder'), failCode('proxy-key-refused'));
|
||||
const took = performance.now() - started;
|
||||
assert.ok(f.state.probes > 1, 'a 401 is probed again'); assert.ok(took >= ISSUE_PROBE_TIMEOUT_MS && took < ISSUE_PROBE_TIMEOUT_MS + 2000, `bounded: ${took}`);
|
||||
});
|
||||
test('proxy-down: a re-probe that stalls ends near the probe deadline, not the client default', async t => {
|
||||
const f = await fixture(t); await f.manager.reconcile(); await f.manager.ensure('demo/coder'); f.state.status = 401;
|
||||
f.state.stallProbe = () => f.state.probes >= 2;
|
||||
const started = performance.now();
|
||||
await assert.rejects(f.manager.preflight('demo/coder'), failCode('proxy-down'));
|
||||
const took = performance.now() - started;
|
||||
assert.equal(f.state.probes, 2); assert.ok(took < ISSUE_PROBE_TIMEOUT_MS + ISSUE_REPROBE_MIN_MS + 1000, `bounded: ${took}`);
|
||||
});
|
||||
// Every v8 CLIProxyAPI applies the PUT by an async reload; on 8.0.79 a just-issued key answers 401
|
||||
// past the confirming GET (#1873).
|
||||
test('first launch passes when the proxy applies the new key a moment after the PUT answers', async t => {
|
||||
const f = await fixture(t); await f.manager.reconcile(); f.state.status = 401;
|
||||
f.state.onProbe = () => { if (f.state.probes === 3) f.state.status = null; };
|
||||
const answer = await f.manager.preflight('demo/coder');
|
||||
assert.equal(f.state.probes, 3); assert.equal(f.state.keys.includes(answer.key), true);
|
||||
});
|
||||
test('rotate keeps old key while its run lives, new launches use new, exit removes old', async t => {
|
||||
const f = await fixture(t); await f.manager.reconcile(); const first = await f.manager.ensure('demo/coder');
|
||||
f.runs.push({ instance: 'demo/coder', run: 'old', keyId: hash(first.key) });
|
||||
|
||||
@@ -65,7 +65,7 @@ test('3f copy migrates to 3g preserving every old column/row, with an empty inst
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
const store = new Store(root, { migrateSchema: true });
|
||||
try {
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3v');
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3w');
|
||||
assert.deepEqual({ ...store.get('SELECT to_name FROM messages') }, { to_name: null });
|
||||
assert.equal(store.get('SELECT count(*) AS n FROM instance_names').n, 0);
|
||||
assert.deepEqual({ ...store.get('SELECT spec_path,spec_commit FROM decisions') }, { spec_path: 'docs/spec.md', spec_commit: 'c'.repeat(40) });
|
||||
|
||||
@@ -0,0 +1,367 @@
|
||||
// Ruling 2026-11-14 ("If I choose a starter pack and apply it, that is a decision!"): a person's
|
||||
// apply records one hire decision per proposed hire in the same act and applies it, so the agents
|
||||
// exist when the call returns. The owner approves every line; a member with org.hire gets the
|
||||
// unflagged hires and the rest wait in the owner's inbox; an agent's apply never hires.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { chmodSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { pluginHash } from '../../plugins/src/pinned.mjs';
|
||||
import { installPlugin } from '../../plugins/src/install.mjs';
|
||||
import { starterPack as codingPack } from '../../plugins/starter-pack/coding/index.mjs';
|
||||
import { templateHash } from '../../organization/src/definitions.mjs';
|
||||
|
||||
const SUBJECT = { provider: 'test', iss: 'test', sub: 'owner' };
|
||||
const ROUTE = { harness: 'pi', model: 'claude-opus-5-5' };
|
||||
const ASSISTANT_ROUTE = { harness: 'pi', model: 'glm-5.3-flash', thinking: 'low' };
|
||||
|
||||
// assistant: false, no assistant instance; {} an assistant with no vars; any other object the
|
||||
// assistant's vars. Lane pr2: a pack hire falls back to the org assistant's route.
|
||||
async function harness(t, { route = true, assistant = false, mutate = () => {} } = {}) {
|
||||
const { startBroker } = await import('../src/runtime.mjs');
|
||||
const { businessDoc, rolesCopy, systemFor, writeJson } = await import('../../organization/tests/helpers.mjs');
|
||||
const root = mkdtempSync(join(tmpdir(), 'packhire-'));
|
||||
const rolesDir = rolesCopy(root);
|
||||
const doc = businessDoc(root, 'demo');
|
||||
doc.plugins = { harness: ['pi'] };
|
||||
if (route) doc.roles.chief.vars = { ...ROUTE };
|
||||
if (assistant) doc.roles.assistant = { definition: 'assistant', ...(Object.keys(assistant).length ? { vars: { ...assistant } } : {}) };
|
||||
mutate(doc);
|
||||
writeJson(join(root, 'businesses/demo.json'), doc);
|
||||
const data = join(root, 'data');
|
||||
mkdirSync(data, { mode: 0o700 });
|
||||
const roles = { chief: { definition: 'chief-of-staff', authority: { withinRole: ['decision.resolve.technical', 'decision.resolve.delivery', 'organization.change'], crossRole: [] } },
|
||||
coder: { definition: 'coder', authority: { withinRole: ['message.send'], crossRole: [] } } };
|
||||
const businesses = { demo: { id: 'demo', human: 'jason', arbiters: { technical: 'chief', delivery: 'chief' }, roles } };
|
||||
const bus = await startBroker({ dataRoot: data, businesses, organization: { dir: root, rolesDir, system: systemFor(root) } });
|
||||
const thaw = (p) => { const st = lstatSync(p); if (st.isSymbolicLink()) return; if (st.isDirectory()) { chmodSync(p, 0o700); for (const e of readdirSync(p)) thaw(join(p, e)); } };
|
||||
t.after(async () => { await bus.close(); thaw(root); rmSync(root, { recursive: true, force: true }); });
|
||||
const b = bus.broker;
|
||||
const consoleOwner = b.bindConsole({ business: 'demo', human: 'jason', subject: SUBJECT });
|
||||
const human = b.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true });
|
||||
const member = b.bindHireConsole({ business: 'demo', actor: 'alice', subject: { provider: 'test', iss: 'test', sub: 'alice' }, rights: ['org.hire', 'board.read'] });
|
||||
const call = async (verb, args = {}, cap = consoleOwner) => b.request(cap, { verb, args });
|
||||
const path = join(root, 'businesses/demo.json');
|
||||
const file = () => JSON.parse(readFileSync(path, 'utf8'));
|
||||
const decisions = list => b.request(human, { verb: 'decisions', args: { list } });
|
||||
// The broker's own database, read-only.
|
||||
const db = (sql, ...a) => { const d = new DatabaseSync(join(data, 'bus/bus.sqlite'), { readOnly: true }); try { return d.prepare(sql).all(...a); } finally { d.close(); } };
|
||||
const store = { all: db, get: (sql, ...a) => db(sql, ...a)[0] };
|
||||
const events = () => store.all("SELECT kind, body FROM events WHERE business='demo' ORDER BY seq").map(r => ({ kind: r.kind, body: JSON.parse(r.body) }));
|
||||
let n = 0;
|
||||
const install = (pack) => {
|
||||
const src = join(root, `src-${n++}`);
|
||||
mkdirSync(join(src, 'starter-pack'), { recursive: true });
|
||||
writeFileSync(join(src, 'starter-pack', 'index.mjs'), `export const interfaceVersion = 1;\nexport function starterPack() { return ${JSON.stringify(pack)}; }\n`);
|
||||
const manifest = { name: pack.id, version: '1.0.0', kinds: ['starter-pack'], interfaceVersions: { 'starter-pack': 1 }, sha256: '0'.repeat(64),
|
||||
source: { path: 'fixture', version: '1.0.0' }, signature: null, tools: [], actions: [], services: [], roleTemplates: [] };
|
||||
writeFileSync(join(src, 'plugin.json'), JSON.stringify(manifest));
|
||||
manifest.sha256 = pluginHash(src);
|
||||
writeFileSync(join(src, 'plugin.json'), JSON.stringify(manifest));
|
||||
installPlugin({ dataRoot: data, source: src, expectedHash: manifest.sha256 });
|
||||
};
|
||||
const op = (name) => events().filter(e => e.kind === 'action.allowed' && e.body.operation === name).map(e => e.body);
|
||||
return { bus, b, root, rolesDir, path, consoleOwner, human, member, call, file, decisions, events, op, store, install };
|
||||
}
|
||||
|
||||
const apply = async (call, args = { pack: 'coding' }, cap) => {
|
||||
const preview = await call('pack.preview.console', args, cap);
|
||||
return { preview, out: await call('pack.apply.console', { ...args, digest: preview.digest }, cap) };
|
||||
};
|
||||
|
||||
// The evidence an inbox-approved hire leaves: a decision.raise naming the hire, a console
|
||||
// resolution yes, a hire.consume and a hire.apply, and the instance's hireDecision.
|
||||
function assertHireRecord(h, name, decision) {
|
||||
const raise = h.op('decision.raise').find(r => r.decision === decision);
|
||||
assert.ok(raise, `decision.raise for ${name}`);
|
||||
assert.equal(raise.hire.name, name);
|
||||
assert.equal(raise.action, 'role.hire');
|
||||
assert.ok(h.op('hire.consume').some(r => r.decision === decision), `hire.consume for ${name}`);
|
||||
assert.ok(h.op('hire.apply').some(r => r.decision === decision), `hire.apply for ${name}`);
|
||||
const resolved = h.store.all('SELECT op, choice, via, by FROM decision_events WHERE decision=?', decision);
|
||||
assert.deepEqual(resolved.map(r => [r.op, r.choice]), [['resolved', 'yes']]);
|
||||
assert.equal(h.file().roles[name].hireDecision, decision);
|
||||
}
|
||||
|
||||
test('PD the owner applies a pack with flagged hires on a fresh org; the agents exist on return, each with its decision record', async t => {
|
||||
const h = await harness(t);
|
||||
const { preview, out } = await apply(h.call);
|
||||
// The preview lists the flagged and credential lines the owner's apply approves.
|
||||
assert.ok(preview.hires.some(x => x.flagged.length || x.credentialLines.length), JSON.stringify(preview.hires));
|
||||
assert.deepEqual(out.hires.map(x => [x.name, x.state]), [['pm-1', 'hired'], ['coder-1', 'hired'], ['reviewer-1', 'hired']]);
|
||||
const doc = h.file();
|
||||
for (const x of out.hires) {
|
||||
assert.ok(Object.hasOwn(doc.roles, x.name), `${x.name} exists`);
|
||||
assert.ok(doc.launch.instances.includes(x.name), `${x.name} is launched`);
|
||||
assertHireRecord(h, x.name, x.decision);
|
||||
}
|
||||
// The coder's credential lines are approved, not bound: the instance is written with no credential.
|
||||
assert.equal(doc.roles['coder-1'].credentials, undefined);
|
||||
// Each hire names its pack.
|
||||
assert.deepEqual(h.op('pack.hire').map(e => [e.hire, e.pack, e.origin, e.project]), out.hires.map(x => [x.name, 'coding', 'shipped', null]));
|
||||
// The instances read carries the pack each agent came from.
|
||||
const inst = await h.call('instances', {}, h.human);
|
||||
assert.deepEqual(inst.instances['coder-1'].pack, { id: 'coding', origin: 'shipped', project: null });
|
||||
assert.equal(inst.instances.pm.pack, undefined);
|
||||
// The packs read counts the hires and lists nothing open.
|
||||
const packs = await h.call('packs.console');
|
||||
const applied = packs.applied.find(a => a.id === 'coding');
|
||||
assert.deepEqual(applied.hired.sort(), ['coder-1', 'pm-1', 'reviewer-1']);
|
||||
assert.deepEqual(applied.open, []);
|
||||
});
|
||||
|
||||
test('PD a re-apply hires nothing twice', async t => {
|
||||
const h = await harness(t);
|
||||
await apply(h.call);
|
||||
const raised = h.op('decision.raise').length;
|
||||
const again = await apply(h.call);
|
||||
// The second apply proposes nothing: each proposal's instance exists.
|
||||
assert.deepEqual(again.out.hires, []);
|
||||
assert.deepEqual((await h.call('packs.console')).applied.find(a => a.id === 'coding').hired.sort(), ['coder-1', 'pm-1', 'reviewer-1']);
|
||||
// The pack action on the same entry skips each instance that exists.
|
||||
const hired = await h.call('pack.hire.console', { pack: 'coding' });
|
||||
assert.equal(h.op('decision.raise').length, raised);
|
||||
assert.ok(hired.hires.every(x => x.state === 'exists'), JSON.stringify(hired));
|
||||
});
|
||||
|
||||
test('PD the owner CLI apply hires through the same path, resolved via cli', async t => {
|
||||
const h = await harness(t);
|
||||
const preview = await h.call('pack.preview', { pack: 'coding' }, h.human);
|
||||
const out = await h.call('pack.apply', { pack: 'coding', digest: preview.digest }, h.human);
|
||||
assert.deepEqual(out.hires.map(x => x.state), ['hired', 'hired', 'hired']);
|
||||
for (const x of out.hires) {
|
||||
assertHireRecord(h, x.name, x.decision);
|
||||
assert.equal(h.store.get('SELECT via FROM decision_events WHERE decision=?', x.decision).via, 'cli');
|
||||
assert.equal(h.store.get('SELECT raised_by_run FROM decisions WHERE id=?', x.decision).raised_by_run, 'human-cli');
|
||||
}
|
||||
});
|
||||
|
||||
test('PD with no chief route the apply records the pack, hires nothing and says why; the hire action on the existing record hires once a route exists', async t => {
|
||||
const h = await harness(t, { route: false });
|
||||
const { out } = await apply(h.call);
|
||||
assert.deepEqual(out.hires.map(x => [x.name, x.state, x.code]), [['pm-1', 'refused', 'pack-hire-route-missing'], ['coder-1', 'refused', 'pack-hire-route-missing'], ['reviewer-1', 'refused', 'pack-hire-route-missing']]);
|
||||
assert.equal(h.op('decision.raise').length, 0);
|
||||
const packs = await h.call('packs.console');
|
||||
assert.deepEqual(packs.applied.find(a => a.id === 'coding').open.map(o => [o.name, o.state, o.code, typeof o.reason]),
|
||||
[['pm-1', 'refused', 'pack-hire-route-missing', 'string'], ['coder-1', 'refused', 'pack-hire-route-missing', 'string'], ['reviewer-1', 'refused', 'pack-hire-route-missing', 'string']]);
|
||||
// The owner gives the chief a route; the pack action hires from the packs entry already recorded.
|
||||
const doc = h.file();
|
||||
doc.roles.chief.vars = { ...ROUTE };
|
||||
writeFileSync(h.path, JSON.stringify(doc, null, 2) + '\n');
|
||||
const hired = await h.call('pack.hire.console', { pack: 'coding' });
|
||||
assert.deepEqual(hired.hires.map(x => [x.name, x.state]), [['pm-1', 'hired'], ['coder-1', 'hired'], ['reviewer-1', 'hired']]);
|
||||
for (const x of hired.hires) assertHireRecord(h, x.name, x.decision);
|
||||
assert.deepEqual((await h.call('packs.console')).applied.find(a => a.id === 'coding').open, []);
|
||||
// The CLI's pack hire is the same action; nothing is left to hire.
|
||||
const cli = await h.call('pack.hire', { pack: 'coding' }, h.human);
|
||||
assert.ok(cli.hires.every(x => x.state === 'exists'));
|
||||
await assert.rejects(h.call('pack.hire.console', { pack: 'nosuch' }), /pack-not-applied/);
|
||||
});
|
||||
|
||||
// A pack with one hire inside the chief's own grants and two above them.
|
||||
// An installed pack's own definition narrows a template; the scout keeps only read.
|
||||
const mixkit = (rolesDir) => {
|
||||
const SCOUT = { from: { template: 'coder', sha256: templateHash(rolesDir, 'coder') }, role: { tools: ['read'], network: 'none', authority: { withinRole: [], crossRole: [] }, credentials: [] }, instructions: 'Read and report.' };
|
||||
const p = structuredClone(codingPack());
|
||||
p.id = 'mixkit';
|
||||
p.definitions = { scout: SCOUT, coder: p.definitions.coder, reviewer: p.definitions.reviewer };
|
||||
p.hires = [{ name: 'scout-1', definition: 'scout', reason: 'reads and reports' }, { name: 'coder-1', definition: 'coder', reason: 'implements each change' }, { name: 'reviewer-1', definition: 'reviewer', reason: 'reviews each change' }];
|
||||
p.workflows = { change: { description: 'One change.', steps: [{ id: 'build', title: 'Build it', roles: ['coder'], state: 'in-progress' }, { id: 'review', title: 'Review it', roles: ['reviewer'], state: 'in-review' }] } };
|
||||
return p;
|
||||
};
|
||||
|
||||
test('PD a member with org.hire gets the unflagged hires; the flagged ones become open decisions in the owner inbox', async t => {
|
||||
const h = await harness(t, { route: false });
|
||||
h.install(mixkit(h.rolesDir));
|
||||
await apply(h.call, { pack: 'mixkit' });
|
||||
const doc = h.file();
|
||||
doc.roles.chief.vars = { ...ROUTE };
|
||||
writeFileSync(h.path, JSON.stringify(doc, null, 2) + '\n');
|
||||
const out = await h.call('pack.hire.console', { pack: 'mixkit' }, h.member);
|
||||
assert.deepEqual(out.hires.map(x => [x.name, x.state]), [['scout-1', 'hired'], ['coder-1', 'awaiting-owner'], ['reviewer-1', 'awaiting-owner']]);
|
||||
const after = h.file();
|
||||
assert.ok(after.launch.instances.includes('scout-1'));
|
||||
assert.equal(Object.hasOwn(after.roles, 'coder-1'), false);
|
||||
assert.equal(Object.hasOwn(after.roles, 'reviewer-1'), false);
|
||||
assertHireRecord(h, 'scout-1', out.hires[0].decision);
|
||||
assert.equal(h.store.get('SELECT via FROM decision_events WHERE decision=?', out.hires[0].decision).via, 'console');
|
||||
// Each flagged hire is an open decision routed to the human, raised by the member's act.
|
||||
const waiting = out.hires.filter(x => x.state === 'awaiting-owner');
|
||||
for (const x of waiting) {
|
||||
const d = h.store.get('SELECT route_to, raised_by_role, action FROM decisions WHERE id=?', x.decision);
|
||||
assert.deepEqual([d.route_to, d.raised_by_role, d.action], ['human', 'human', 'role.hire']);
|
||||
assert.equal(h.store.all('SELECT 1 FROM decision_events WHERE decision=?', x.decision).length, 0);
|
||||
}
|
||||
// The packs read lists both as open, awaiting the owner, each with the pack's reason.
|
||||
const applied = (await h.call('packs.console')).applied.find(a => a.id === 'mixkit');
|
||||
assert.deepEqual(applied.hired, ['scout-1']);
|
||||
assert.deepEqual(applied.open.map(o => [o.name, o.state, o.reason, o.decision]), [['coder-1', 'awaiting-owner', 'implements each change', waiting[0].decision], ['reviewer-1', 'awaiting-owner', 'reviews each change', waiting[1].decision]]);
|
||||
// The member's pack action never re-raises a hire an open decision names.
|
||||
const again = await h.call('pack.hire.console', { pack: 'mixkit' }, h.member);
|
||||
assert.deepEqual(again.hires.map(x => [x.name, x.state, x.decision ?? null]), [['scout-1', 'exists', null], ['coder-1', 'open', waiting[0].decision], ['reviewer-1', 'open', waiting[1].decision]]);
|
||||
// The member cannot approve a flagged hire; the owner can, from the inbox, and the agent exists.
|
||||
const view = await h.call('hire.preview.console', { id: waiting[0].decision });
|
||||
await assert.rejects(h.call('hire.resolve.console', { id: waiting[0].decision, choice: 'yes', digest: view.digest }, h.member), /hire-owner-required|human-required/);
|
||||
await h.call('hire.resolve.console', { id: waiting[0].decision, choice: 'yes', digest: view.digest });
|
||||
assert.ok(h.file().launch.instances.includes('coder-1'));
|
||||
// The owner's pack action approves the rest: the open pack decision is withdrawn by the owner and
|
||||
// replaced by one approved in the same act.
|
||||
const owner = await h.call('pack.hire.console', { pack: 'mixkit' });
|
||||
assert.deepEqual(owner.hires.map(x => [x.name, x.state, x.supersedes ?? null]), [['scout-1', 'exists', null], ['coder-1', 'exists', null], ['reviewer-1', 'hired', waiting[1].decision]]);
|
||||
assert.deepEqual(h.store.all('SELECT op, by FROM decision_events WHERE decision=?', waiting[1].decision).map(r => [r.op, r.by]), [['withdrawn', 'jason']]);
|
||||
assertHireRecord(h, 'reviewer-1', owner.hires[2].decision);
|
||||
const done = (await h.call('packs.console')).applied.find(a => a.id === 'mixkit');
|
||||
assert.deepEqual(done.hired.sort(), ['coder-1', 'reviewer-1', 'scout-1']);
|
||||
assert.deepEqual(done.open, []);
|
||||
});
|
||||
|
||||
test('PD an agent apply still refuses human-required and hires nothing; the tester and a cli cap on the console name refuse', async t => {
|
||||
const h = await harness(t);
|
||||
const agent = h.b.bindLaunch({ business: 'demo', role: 'coder', run: 'coder-run', harness: 'pi', address: 'coder-run' });
|
||||
h.b.request(agent, { verb: 'role.claim' });
|
||||
assert.throws(() => h.b.request(agent, { verb: 'pack.apply.console', args: { pack: 'coding', digest: 'a'.repeat(64) } }), /human-required/);
|
||||
await assert.rejects(Promise.resolve().then(() => h.b.request(agent, { verb: 'pack.hire', args: { pack: 'coding' } })), /human-required/);
|
||||
await assert.rejects(Promise.resolve().then(() => h.b.request(agent, { verb: 'pack.hire.console', args: { pack: 'coding' } })), /human-required/);
|
||||
await assert.rejects(Promise.resolve().then(() => h.b.request(h.human, { verb: 'pack.hire.console', args: { pack: 'coding' } })), /human-required/);
|
||||
await assert.rejects(h.call('pack.hire', { pack: 'coding' }), /human-required/);
|
||||
for (const args of [{}, { pack: 7 }, { pack: 'coding', extra: 1 }, { pack: 'coding', project: 'Bad Name' }])
|
||||
await assert.rejects(h.call('pack.hire.console', args), /invalid-request/);
|
||||
assert.equal(h.op('decision.raise').length, 0);
|
||||
});
|
||||
|
||||
test('PD a project pack hires into projects.<p>.agents', async t => {
|
||||
const h = await harness(t);
|
||||
const pack = structuredClone(codingPack());
|
||||
pack.id = 'projkit'; pack.scope = 'project';
|
||||
h.install(pack);
|
||||
const { out } = await apply(h.call, { pack: 'projkit', project: 'stack' });
|
||||
assert.deepEqual(out.hires.map(x => x.state), ['hired', 'hired', 'hired']);
|
||||
const agents = h.file().projects.stack.agents;
|
||||
for (const x of out.hires) { assert.equal(agents[x.name].hireDecision, x.decision); assert.equal(agents[x.name].credentials, undefined); }
|
||||
assert.equal(Object.hasOwn(h.file().roles, 'coder-1'), false);
|
||||
assert.deepEqual(h.op('pack.hire').map(e => e.project), ['stack', 'stack', 'stack']);
|
||||
const applied = (await h.call('packs.console')).applied.find(a => a.id === 'projkit');
|
||||
assert.deepEqual(applied.hired.sort(), ['coder-1', 'pm-1', 'reviewer-1']);
|
||||
const again = await h.call('pack.hire.console', { pack: 'projkit', project: 'stack' });
|
||||
assert.ok(again.hires.every(x => x.state === 'exists'));
|
||||
});
|
||||
|
||||
test('PD the new codes are in the refusal table with a rail and a next step that names no path', async () => {
|
||||
const { REFUSALS } = await import('../src/refusals.mjs');
|
||||
for (const c of ['pack-not-applied', 'pack-hire-route-missing', 'hire-owner-required', 'no-chief-of-staff']) {
|
||||
assert.ok(Object.hasOwn(REFUSALS, c), c);
|
||||
assert.ok(REFUSALS[c].rail?.length > 5);
|
||||
assert.ok(REFUSALS[c].nextStep?.length > 20);
|
||||
assert.ok(!/(^|[\s("'`])(\/|~\/)/.test(REFUSALS[c].nextStep));
|
||||
}
|
||||
});
|
||||
|
||||
test('PD the owner supersede withdraws an inbox decision only after its replacement hires; a refused replacement leaves it open', async t => {
|
||||
const h = await harness(t, { route: false });
|
||||
h.install(mixkit(h.rolesDir));
|
||||
await apply(h.call, { pack: 'mixkit' });
|
||||
const setRoute = (vars) => { const doc = h.file(); if (vars) doc.roles.chief.vars = { ...vars }; else delete doc.roles.chief.vars; writeFileSync(h.path, JSON.stringify(doc, null, 2) + '\n'); };
|
||||
setRoute(ROUTE);
|
||||
const out = await h.call('pack.hire.console', { pack: 'mixkit' }, h.member);
|
||||
const waiting = out.hires.filter(x => x.state === 'awaiting-owner');
|
||||
assert.equal(waiting.length, 2);
|
||||
// The packs read marks each member-raised line as raised by a pack hire.
|
||||
const open = (await h.call('packs.console')).applied.find(a => a.id === 'mixkit').open;
|
||||
assert.deepEqual(open.map(o => [o.name, o.state, o.fromPack]), [['coder-1', 'awaiting-owner', true], ['reviewer-1', 'awaiting-owner', true]]);
|
||||
// The chief loses its route; the owner's pack hire cannot build a replacement.
|
||||
setRoute(null);
|
||||
const owner = await h.call('pack.hire.console', { pack: 'mixkit' });
|
||||
assert.deepEqual(owner.hires.map(x => [x.name, x.state, x.code ?? null]), [['scout-1', 'exists', null], ['coder-1', 'refused', 'pack-hire-route-missing'], ['reviewer-1', 'refused', 'pack-hire-route-missing']]);
|
||||
// Both inbox decisions are still open: nothing withdrew them.
|
||||
for (const x of waiting) assert.deepEqual(h.store.all('SELECT op FROM decision_events WHERE decision=?', x.decision), []);
|
||||
// With the route back, the owner's pack hire replaces them, withdrawing each only once its replacement applied.
|
||||
setRoute(ROUTE);
|
||||
const done = await h.call('pack.hire.console', { pack: 'mixkit' });
|
||||
assert.deepEqual(done.hires.map(x => [x.name, x.state, x.supersedes ?? null]), [['scout-1', 'exists', null], ['coder-1', 'hired', waiting[0].decision], ['reviewer-1', 'hired', waiting[1].decision]]);
|
||||
for (const x of waiting) assert.deepEqual(h.store.all('SELECT op, by FROM decision_events WHERE decision=?', x.decision).map(r => [r.op, r.by]), [['withdrawn', 'jason']]);
|
||||
});
|
||||
|
||||
test('PD a second pack hire on the same organization while one runs refuses organization-busy and raises nothing', async t => {
|
||||
const h = await harness(t, { route: false });
|
||||
await apply(h.call);
|
||||
const doc = h.file();
|
||||
doc.roles.chief.vars = { ...ROUTE };
|
||||
writeFileSync(h.path, JSON.stringify(doc, null, 2) + '\n');
|
||||
const first = h.call('pack.hire.console', { pack: 'coding' });
|
||||
const second = h.call('pack.hire.console', { pack: 'coding' });
|
||||
await assert.rejects(second, /organization-busy/);
|
||||
const hired = await first;
|
||||
assert.deepEqual(hired.hires.map(x => [x.name, x.state]), [['pm-1', 'hired'], ['coder-1', 'hired'], ['reviewer-1', 'hired']]);
|
||||
// One decision per hire: the refused call raised nothing.
|
||||
assert.equal(h.op('decision.raise').length, 3);
|
||||
// Once the loop ends the latch is free again: the next pack hire runs and finds nothing to hire.
|
||||
const later = await h.call('pack.hire.console', { pack: 'coding' });
|
||||
assert.ok(later.hires.every(x => x.state === 'exists'), JSON.stringify(later));
|
||||
});
|
||||
|
||||
// Lane pr2 (lead ruling 2026-11-14): a pack hire takes the chief of staff's harness and model, else
|
||||
// the org assistant's, else refuses pack-hire-route-missing.
|
||||
test('PR2 with no chief route the apply hires every proposal with the org assistant harness and model', async t => {
|
||||
const h = await harness(t, { route: false, assistant: ASSISTANT_ROUTE });
|
||||
const { out } = await apply(h.call);
|
||||
assert.deepEqual(out.hires.map(x => [x.name, x.state, x.routeFrom]), [['pm-1', 'hired', 'assistant'], ['coder-1', 'hired', 'assistant'], ['reviewer-1', 'hired', 'assistant']]);
|
||||
const doc = h.file();
|
||||
for (const x of out.hires) {
|
||||
assertHireRecord(h, x.name, x.decision);
|
||||
assert.deepEqual(doc.roles[x.name].vars, ASSISTANT_ROUTE);
|
||||
assert.deepEqual(h.op('decision.raise').find(r => r.decision === x.decision).hire.route, ASSISTANT_ROUTE);
|
||||
}
|
||||
});
|
||||
|
||||
test('PR2 a chief route wins over a different assistant route', async t => {
|
||||
const h = await harness(t, { assistant: ASSISTANT_ROUTE });
|
||||
const { out } = await apply(h.call);
|
||||
assert.deepEqual(out.hires.map(x => [x.name, x.state, x.routeFrom]), [['pm-1', 'hired', 'chief'], ['coder-1', 'hired', 'chief'], ['reviewer-1', 'hired', 'chief']]);
|
||||
for (const x of out.hires) assert.deepEqual(h.file().roles[x.name].vars, ROUTE);
|
||||
});
|
||||
|
||||
test('PR2 an assistant with no harness and model gives no route: the apply refuses as before', async t => {
|
||||
for (const assistant of [{}, { harness: 'pi' }]) {
|
||||
const h = await harness(t, { route: false, assistant });
|
||||
const { out } = await apply(h.call);
|
||||
assert.deepEqual(out.hires.map(x => [x.name, x.state, x.code]), [['pm-1', 'refused', 'pack-hire-route-missing'], ['coder-1', 'refused', 'pack-hire-route-missing'], ['reviewer-1', 'refused', 'pack-hire-route-missing']]);
|
||||
assert.equal(h.op('decision.raise').length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test('PR2 with several assistants the one named assistant gives the route, else the first in key order', async t => {
|
||||
const OTHER = { harness: 'pi', model: 'claude-sonnet-5-5' };
|
||||
const named = await harness(t, { route: false, assistant: ASSISTANT_ROUTE, mutate: doc => { doc.roles = { aide: { definition: 'assistant', vars: { ...OTHER } }, ...doc.roles }; } });
|
||||
const a = await apply(named.call);
|
||||
for (const x of a.out.hires) assert.deepEqual(named.file().roles[x.name].vars, ASSISTANT_ROUTE);
|
||||
const first = await harness(t, { route: false, mutate: doc => { doc.roles.aide = { definition: 'assistant', vars: { ...OTHER } }; doc.roles.zed = { definition: 'assistant', vars: { ...ASSISTANT_ROUTE } }; } });
|
||||
const b = await apply(first.call);
|
||||
assert.deepEqual(b.out.hires.map(x => [x.state, x.routeFrom]), [['hired', 'assistant'], ['hired', 'assistant'], ['hired', 'assistant']]);
|
||||
for (const x of b.out.hires) assert.deepEqual(first.file().roles[x.name].vars, OTHER);
|
||||
});
|
||||
|
||||
test('PR2 a member pack hire on the assistant route marks hired and awaiting-owner lines routeFrom assistant', async t => {
|
||||
const h = await harness(t, { route: false, assistant: ASSISTANT_ROUTE });
|
||||
h.install(mixkit(h.rolesDir));
|
||||
// The member's apply would not run; the owner's apply would hire everything. Record the pack first
|
||||
// with the assistant route absent, then give it back and let the member hire.
|
||||
const doc0 = h.file(); delete doc0.roles.assistant.vars; writeFileSync(h.path, JSON.stringify(doc0, null, 2) + '\n');
|
||||
await apply(h.call, { pack: 'mixkit' });
|
||||
const doc = h.file(); doc.roles.assistant.vars = { ...ASSISTANT_ROUTE }; writeFileSync(h.path, JSON.stringify(doc, null, 2) + '\n');
|
||||
const out = await h.call('pack.hire.console', { pack: 'mixkit' }, h.member);
|
||||
assert.deepEqual(out.hires.map(x => [x.name, x.state, x.routeFrom]), [['scout-1', 'hired', 'assistant'], ['coder-1', 'awaiting-owner', 'assistant'], ['reviewer-1', 'awaiting-owner', 'assistant']]);
|
||||
assert.deepEqual(h.file().roles['scout-1'].vars, ASSISTANT_ROUTE);
|
||||
});
|
||||
|
||||
test('PR2 a project pack with no chief route hires into the project on the assistant route', async t => {
|
||||
const h = await harness(t, { route: false, assistant: ASSISTANT_ROUTE });
|
||||
const pack = structuredClone(codingPack());
|
||||
pack.id = 'projkit'; pack.scope = 'project';
|
||||
h.install(pack);
|
||||
const { out } = await apply(h.call, { pack: 'projkit', project: 'stack' });
|
||||
assert.deepEqual(out.hires.map(x => [x.state, x.routeFrom]), [['hired', 'assistant'], ['hired', 'assistant'], ['hired', 'assistant']]);
|
||||
const agents = h.file().projects.stack.agents;
|
||||
for (const x of out.hires) { assert.equal(agents[x.name].hireDecision, x.decision); assert.deepEqual(h.op('decision.raise').find(r => r.decision === x.decision).hire.route, ASSISTANT_ROUTE); }
|
||||
});
|
||||
@@ -0,0 +1,299 @@
|
||||
// #1873 pickup-launch: a bus that picked up the shared proxy late serves accounts and a ready
|
||||
// catalogue, but a launch on a proxy model still needs a restart (no ModelKeys on the bus, no proxy
|
||||
// in the host launcher's boot system). While it holds such a client, its catalogue answer says so
|
||||
// in one plain notice, and a launch refuses exactly as before. A refused or dropped client shows
|
||||
// its cause instead. Real buses, a real launcher whose model ops go to the bus, a fake loopback
|
||||
// management server; no live config.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { startBroker } from '../src/runtime.mjs';
|
||||
import { busOrganization } from '../src/organization-context.mjs';
|
||||
import { createProxyLock } from '../src/proxy-lock.mjs';
|
||||
import { Registry, launchLogFile } from '../../seat/src/session.mjs';
|
||||
import { loadBusiness } from '../../organization/src/organization-config.mjs';
|
||||
import { resolveInstance } from '../../organization/src/resolve.mjs';
|
||||
import { businessDoc, rolesCopy, systemFor, writeJson } from '../../organization/tests/helpers.mjs';
|
||||
import { PIN } from '../../model-proxy/src/common.mjs';
|
||||
import { initializeProxy, installPaths, loadProxy } from '../../model-proxy/src/settings.mjs';
|
||||
import { createLauncher } from '../../cli/src/launcher.mjs';
|
||||
import { initializeControl } from '../../processing-control/src/state.mjs';
|
||||
import { ZAI_URL } from '../../plugins/model-provider/cliproxy/index.mjs';
|
||||
import { fakeHarnesses, humanEnv, withoutHostCredentials } from '../../cli/tests/helpers.mjs';
|
||||
import { REPO_SKILLS } from '../../harness/tests/helpers.mjs';
|
||||
|
||||
const RESTART = 'Restart this organization to start agents on these models.';
|
||||
const MODEL = 'claude-claude-opus-5-5';
|
||||
const sha = value => createHash('sha256').update(value).digest('hex');
|
||||
|
||||
// A loopback stand-in for the proxy's management API: one ready Claude account with one model,
|
||||
// and an access key list that keeps what a PUT sends, so a boot ModelKeys reconciles against it.
|
||||
async function fakeProxy(t, key, port = 0, { groups = [] } = {}) {
|
||||
const seen = { calls: 0, wrongKey: 0 };
|
||||
let accessKeys = [];
|
||||
const server = http.createServer((req, res) => {
|
||||
seen.calls++;
|
||||
if (req.headers.authorization !== `Bearer ${key}`) { seen.wrongKey++; res.writeHead(401); res.end('{}'); return; }
|
||||
const url = new URL(req.url, 'http://127.0.0.1');
|
||||
if (url.pathname === '/v8/management/config/access/api-keys' && req.method === 'PUT') {
|
||||
const chunks = [];
|
||||
req.on('data', c => chunks.push(c));
|
||||
req.on('end', () => { accessKeys = JSON.parse(Buffer.concat(chunks)); res.end(JSON.stringify({ status: 'ok' })); });
|
||||
return;
|
||||
}
|
||||
const answer = url.pathname === '/v8/management/credentials' ? { files: [{ id: 'acct-1', name: 'acct-1', provider: 'claude', status: 'ready', priority: 1 }] }
|
||||
: url.pathname === '/v8/management/credentials/models' ? { models: [{ id: 'claude-opus-5-5' }] }
|
||||
: url.pathname === '/v8/management/config/api-keys/claude' ? groups
|
||||
: url.pathname === '/v8/management/config/access/api-keys' ? accessKeys
|
||||
: null;
|
||||
if (answer === null) { res.writeHead(404); res.end('{}'); return; }
|
||||
res.end(JSON.stringify(answer));
|
||||
});
|
||||
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolve); });
|
||||
t.after(async () => { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); });
|
||||
return { port: server.address().port, seen, server };
|
||||
}
|
||||
|
||||
// One instance (config dir + data root) and a fake proxy install whose bytes a test pin names.
|
||||
function instance(t) {
|
||||
const root = fs.mkdtempSync(join(tmpdir(), 'pl-'));
|
||||
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
|
||||
const configDir = join(root, 'config'), dataRoot = join(root, 'instance');
|
||||
fs.mkdirSync(join(configDir, 'secrets', 'agents'), { recursive: true, mode: 0o700 });
|
||||
fs.chmodSync(join(configDir, 'secrets'), 0o700);
|
||||
fs.mkdirSync(dataRoot, { mode: 0o700 });
|
||||
const paths = installPaths(dataRoot);
|
||||
fs.mkdirSync(join(paths.dir, 'static'), { recursive: true, mode: 0o700 });
|
||||
fs.writeFileSync(paths.binary, 'fixture proxy binary\n', { mode: 0o700 });
|
||||
fs.writeFileSync(paths.panel, '<!doctype html>\n', { mode: 0o600 });
|
||||
const pin = { ...PIN, binary: { ...PIN.binary, sha256: sha('fixture proxy binary\n') }, panel: { ...PIN.panel, sha256: sha('<!doctype html>\n') } };
|
||||
const rolesDir = rolesCopy(root), system = systemFor(root);
|
||||
const key = `pl1873-${randomBytes(24).toString('hex')}`;
|
||||
return { root, configDir, dataRoot, paths, pin, rolesDir, system, key };
|
||||
}
|
||||
|
||||
// A real organization bus on the instance, started with no proxy unless `binding.proxy` gives one.
|
||||
async function orgBus(t, f, id, { providers = ['cliproxy'], binding = {} } = {}) {
|
||||
const doc = businessDoc(f.root, id);
|
||||
doc.plugins = { harness: ['pi'], 'model-provider': providers };
|
||||
writeJson(join(f.configDir, 'businesses', `${id}.json`), doc);
|
||||
const business = loadBusiness(id, { dir: f.configDir, rolesDir: f.rolesDir }), resolved = {};
|
||||
for (const name of Object.keys(business.roles)) resolved[name] = resolveInstance({ system: f.system, business, instance: name });
|
||||
const dataRoot = join(f.root, `${id}-bus`); fs.mkdirSync(dataRoot, { mode: 0o700 }); new Registry(dataRoot);
|
||||
const bus = await startBroker({ dataRoot, businesses: { [id]: busOrganization(business, resolved) },
|
||||
organization: { dir: f.configDir, rolesDir: f.rolesDir, system: f.system },
|
||||
instanceRoot: f.dataRoot, org: { id }, instanceDataRoot: f.dataRoot, instanceConfigDir: f.configDir,
|
||||
initProxy: args => initializeProxy({ ...args, pin: f.pin }), ...binding });
|
||||
t.after(() => bus.close().catch(() => {}));
|
||||
const human = bus.broker.bindHuman({ business: id, human: 'jason', via: 'cli', outsideAgent: true });
|
||||
const ask = (verb, args) => Promise.resolve().then(() => bus.broker.request(human, { verb, args }));
|
||||
return { id, bus, ask, dataRoot };
|
||||
}
|
||||
|
||||
// Every stderr line written while `run` is in flight.
|
||||
async function capture(run) {
|
||||
const write = process.stderr.write, lines = [];
|
||||
process.stderr.write = (chunk, ...rest) => { lines.push(String(chunk)); return write.call(process.stderr, chunk, ...rest); };
|
||||
try { return { value: await run(), lines }; } finally { process.stderr.write = write; }
|
||||
}
|
||||
|
||||
async function initThroughA(t, f, a, options) {
|
||||
const settings = await a.ask('proxy.init', { key: f.key });
|
||||
const proxy = await fakeProxy(t, f.key, settings.port, options);
|
||||
return { settings, proxy };
|
||||
}
|
||||
|
||||
// The owner picks the catalogue's proxy model for the coder on the Routing page, through the bus.
|
||||
async function pickModel(o) {
|
||||
const view = await o.ask('routes');
|
||||
assert.equal(view.catalogue.status, 'ready');
|
||||
assert.ok(view.catalogue.models.some(m => m.key === MODEL));
|
||||
await o.ask('routes.set', { revision: view.revision, routes: { coder: { harness: 'pi', model: MODEL, thinking: 'low', fallback: null } } });
|
||||
}
|
||||
|
||||
// The host launcher as cli.mjs builds it for a bus that booted with no proxy.json: its system has
|
||||
// no proxy. The model ops go to the bus itself; the rest are the launch-routes stub, and
|
||||
// authorizeLaunch stops a launch that passed every check before it.
|
||||
async function hostLauncher(t, f, o, { system = {} } = {}) {
|
||||
initializeControl(o.dataRoot);
|
||||
// A launch whose role names a skill that is not enabled refuses before the model gate.
|
||||
if (!fs.existsSync(join(f.dataRoot, 'skills-enabled'))) fs.cpSync(REPO_SKILLS, join(f.dataRoot, 'skills-enabled'), { recursive: true });
|
||||
const env = withoutHostCredentials(humanEnv({ MOSAIC_CONFIG: join(f.configDir, 'config.json'), MOSAIC_ROLES_DIR: f.rolesDir }), { piKey: true });
|
||||
const answers = [], ops = [];
|
||||
const host = { business: o.id, beforeClose: () => {}, op: async m => {
|
||||
ops.push(m.op);
|
||||
if (m.op === 'identity') return { business: o.id, role: 'pm' };
|
||||
if (m.op === 'mayLaunch') return { allow: true };
|
||||
if (m.op === 'modelAdmission' || m.op === 'modelPreflight') { const answer = await o.bus[m.op](m); answers.push({ op: m.op, answer }); return answer; }
|
||||
if (m.op === 'authorizeLaunch') throw Object.assign(Error('fixture authorization stop'), { code: 'fixture-policy' });
|
||||
return {};
|
||||
} };
|
||||
const cliproxy = JSON.stringify(pathToFileURL(new URL('../../plugins/model-provider/cliproxy/index.mjs', import.meta.url).pathname).href);
|
||||
const makeLoader = await fakeHarnesses(t, { pi: null }, write => write('model-provider', 'cliproxy', `export * from ${cliproxy};\n`));
|
||||
// The validated system config shape (mosaic-config.mjs), as cli.mjs passes it with the org root.
|
||||
const config = { configVersion: 1, environment: 'development', dataRoot: o.dataRoot, instanceRoot: f.dataRoot,
|
||||
execution: { backend: 'docker', provider: 'zai', model: 'glm-5.3-flash', adapter: 'mock' }, ...system };
|
||||
const launcher = createLauncher({ host, system: config, env, makeLoader, bwrap: '/usr/bin/true', log: () => {} });
|
||||
t.after(() => launcher.close?.().catch?.(() => {}));
|
||||
const events = () => { try { return fs.readFileSync(launchLogFile(o.dataRoot, o.id), 'utf8').trim().split('\n').filter(Boolean).map(l => JSON.parse(l)); } catch { return []; } };
|
||||
return { launch: () => launcher.fromSession('fixture-cap', 'coder'), answers, ops, events };
|
||||
}
|
||||
|
||||
const restartNotices = view => view.catalogue.notices.filter(n => n === RESTART).length;
|
||||
|
||||
test('a bus that picked up the proxy says on its ready catalogue that a restart starts agents on these models, and the launch refuses as before', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
const before = await b.ask('routes');
|
||||
assert.equal(before.catalogue.status, 'unavailable');
|
||||
assert.equal(restartNotices(before), 0, 'no client yet: the not-set-up cause, not the restart notice');
|
||||
await initThroughA(t, f, a);
|
||||
await pickModel(b);
|
||||
const view = await b.ask('routes');
|
||||
assert.equal(view.catalogue.status, 'ready');
|
||||
assert.equal(restartNotices(view), 1);
|
||||
assert.equal(restartNotices(await b.ask('routes')), 1, 'one notice at every read');
|
||||
// The bus that ran init holds a client it did not boot with too.
|
||||
const own = await a.ask('routes');
|
||||
assert.equal(own.catalogue.status, 'ready');
|
||||
assert.equal(restartNotices(own), 1);
|
||||
// The launch refuses as before, with the existing code and line, before any key or run: the
|
||||
// launcher booted with no proxy sends no proxy transport, and the bus's admission refuses that.
|
||||
const host = await hostLauncher(t, f, b);
|
||||
assert.deepEqual(await host.launch(), { ok: false, error: 'model-provider-unavailable' });
|
||||
assert.deepEqual(host.answers, [{ op: 'modelAdmission', answer: { allow: false, code: 'model-provider-unavailable' } }]);
|
||||
assert.equal(host.ops.includes('authorizeLaunch'), false);
|
||||
assert.equal(host.ops.includes('modelPreflight'), false);
|
||||
const refused = host.events().filter(e => e.event === 'refused');
|
||||
assert.equal(refused.length, 1);
|
||||
assert.equal(refused[0].code, 'model-provider-unavailable');
|
||||
assert.equal(refused[0].why, 'model cliproxy/claude/claude-opus-5-5 unavailable (model-provider-unavailable)');
|
||||
// The bus side has no ModelKeys: a preflight issues no key.
|
||||
assert.equal(await b.bus.modelPreflight({ business: 'beta', role: 'coder' }), null);
|
||||
});
|
||||
|
||||
test('the restart notice is added after the notices the catalogue already carries', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
// A z.ai upstream group with no models: the cliproxy catalogue's own notice.
|
||||
await initThroughA(t, f, a, { groups: [{ 'base-url': ZAI_URL, keys: [{ name: 'group-1' }] }] });
|
||||
const view = await b.ask('routes');
|
||||
assert.equal(view.catalogue.status, 'ready');
|
||||
assert.deepEqual(view.catalogue.notices, ['z.ai account has no models configured. Add them on Model proxy.', RESTART]);
|
||||
});
|
||||
|
||||
test('a bus started with the proxy shows no restart notice', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha');
|
||||
await initThroughA(t, f, a);
|
||||
const c = await orgBus(t, f, 'gamma', { binding: { proxy: loadProxy(f.configDir, f.dataRoot) } });
|
||||
const view = await c.ask('routes');
|
||||
assert.equal(view.catalogue.status, 'ready', JSON.stringify(view.catalogue));
|
||||
assert.deepEqual(view.catalogue.notices, []);
|
||||
});
|
||||
|
||||
test('an organization with no model provider shows a disabled catalogue with no restart notice (the routes verb answers disabled itself)', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta', { providers: [] });
|
||||
await initThroughA(t, f, a);
|
||||
await b.ask('proxy.accounts', {});
|
||||
assert.ok(b.bus.modelProxy, 'the client is held');
|
||||
const view = await b.ask('routes');
|
||||
assert.equal(view.catalogue.status, 'disabled');
|
||||
assert.deepEqual(view.catalogue.notices, []);
|
||||
});
|
||||
|
||||
test('a fenced catalogue on a picked-up client reads unavailable with no restart notice, since a restart would not help', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
const { proxy } = await initThroughA(t, f, a);
|
||||
assert.equal(restartNotices(await b.ask('routes')), 1);
|
||||
createProxyLock({ stateDir: join(f.dataRoot, 'proxy'), identity: `${f.configDir}:${proxy.port}` }).fence({ org: 'alpha' });
|
||||
const view = await b.ask('routes');
|
||||
assert.equal(view.catalogue.status, 'unavailable');
|
||||
assert.ok(b.bus.modelProxy);
|
||||
assert.equal(restartNotices(view), 0);
|
||||
// A bus that booted with the proxy on the same fenced instance, which is what a restart gives,
|
||||
// reads the same unavailable catalogue: the restart notice would have sent the owner nowhere.
|
||||
const c = await orgBus(t, f, 'gamma', { binding: { proxy: loadProxy(f.configDir, f.dataRoot) } });
|
||||
assert.equal((await c.ask('routes')).catalogue.status, 'unavailable');
|
||||
// Once the fence is gone, the ready catalogue says again that a restart is needed.
|
||||
fs.rmSync(join(f.dataRoot, 'proxy', 'mosaic-keys.uncertain'));
|
||||
const after = await b.ask('routes');
|
||||
assert.equal(after.catalogue.status, 'ready', JSON.stringify(after.catalogue));
|
||||
assert.equal(restartNotices(after), 1);
|
||||
});
|
||||
|
||||
test('refused settings still refuse the launch and name their cause, not the restart notice', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
await initThroughA(t, f, a);
|
||||
await pickModel(b);
|
||||
// The management key file stops being private: the start path refuses it.
|
||||
fs.chmodSync(join(f.configDir, 'secrets', 'proxy-management.key'), 0o644);
|
||||
const view = await b.ask('routes');
|
||||
assert.equal(view.catalogue.status, 'unavailable');
|
||||
assert.equal(view.catalogue.reason, 'proxy-not-configured');
|
||||
assert.equal(view.catalogue.notices.length, 1);
|
||||
assert.match(view.catalogue.notices[0], /management key does not load/);
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
const host = await hostLauncher(t, f, b);
|
||||
// The bus itself refuses now: the catalogue keeps the model it saw, marked unavailable.
|
||||
assert.deepEqual(await host.launch(), { ok: false, error: 'model-provider-unavailable' });
|
||||
assert.deepEqual(host.answers, [{ op: 'modelAdmission', answer: { allow: false, code: 'model-provider-unavailable' } }]);
|
||||
assert.match(host.events().at(-1).why, /^model cliproxy\/claude\/claude-opus-5-5 unavailable \(model-provider-unavailable\)$/);
|
||||
});
|
||||
|
||||
test('a dropped client refuses the next launch, and the catalogue names the cause instead of the restart notice', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
await initThroughA(t, f, a);
|
||||
await pickModel(b);
|
||||
const host = await hostLauncher(t, f, b);
|
||||
assert.deepEqual(await host.launch(), { ok: false, error: 'model-provider-unavailable' });
|
||||
assert.equal(restartNotices(await b.ask('routes')), 1);
|
||||
fs.rmSync(join(f.configDir, 'proxy.json'));
|
||||
// The next launch refuses with the same code and line.
|
||||
assert.deepEqual(await host.launch(), { ok: false, error: 'model-provider-unavailable' });
|
||||
assert.deepEqual(host.answers.map(a => a.answer), [{ allow: false, code: 'model-provider-unavailable' }, { allow: false, code: 'model-provider-unavailable' }]);
|
||||
assert.equal(host.events().filter(e => e.event === 'refused').length, 2);
|
||||
// The page's next read drops the client and names the cause.
|
||||
const view = await b.ask('routes');
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
assert.equal(view.catalogue.status, 'unavailable');
|
||||
assert.equal(view.catalogue.reason, 'proxy-not-configured');
|
||||
assert.deepEqual(view.catalogue.notices.length, 1);
|
||||
assert.match(view.catalogue.notices[0], /not been set up/);
|
||||
});
|
||||
|
||||
test('the management key is in no stderr line, response, refusal, launch log or file the launch path writes', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
await initThroughA(t, f, a);
|
||||
await pickModel(b);
|
||||
const host = await hostLauncher(t, f, b);
|
||||
const outputs = [];
|
||||
const { lines } = await capture(async () => {
|
||||
outputs.push(await b.ask('routes'));
|
||||
outputs.push(await host.launch());
|
||||
outputs.push(await b.bus.modelPreflight({ business: 'beta', role: 'coder' }));
|
||||
fs.chmodSync(join(f.configDir, 'secrets', 'proxy-management.key'), 0o644);
|
||||
outputs.push(await b.ask('routes'));
|
||||
outputs.push(await host.launch());
|
||||
fs.chmodSync(join(f.configDir, 'secrets', 'proxy-management.key'), 0o600);
|
||||
outputs.push(await b.ask('routes'));
|
||||
outputs.push(await host.launch());
|
||||
});
|
||||
outputs.push(host.answers, host.events());
|
||||
assert.equal(lines.join('').includes(f.key), false, 'stderr');
|
||||
assert.equal(JSON.stringify(outputs).includes(f.key), false, 'responses, answers and launch log');
|
||||
const walk = dir => fs.readdirSync(dir, { withFileTypes: true }).flatMap(e => e.isDirectory() ? walk(join(dir, e.name)) : e.isFile() ? [join(dir, e.name)] : []);
|
||||
const files = [...walk(b.dataRoot), ...walk(join(f.dataRoot, 'proxy')).filter(p => !p.endsWith('/config.yaml'))];
|
||||
assert.ok(files.some(p => p === launchLogFile(b.dataRoot, 'beta')), 'the launch log is scanned');
|
||||
for (const file of files) assert.equal(fs.readFileSync(file).includes(f.key), false, file);
|
||||
});
|
||||
@@ -198,8 +198,7 @@ test('3p through 3s migration preserves existing request rows and the append-onl
|
||||
const path = join(root, 'bus/bus.sqlite'), ddl = readFileSync(new URL('../schema.sql', import.meta.url), 'utf8')
|
||||
// 3s-3t (#797) adds project_archives; the 3p fixture predates it and the replayed chain recreates it.
|
||||
.replace(readFileSync(new URL('../src/migrations/3s-3t.sql', import.meta.url), 'utf8'), '')
|
||||
.replace(readFileSync(new URL('../src/migrations/3t-3u.sql', import.meta.url), 'utf8'), '')
|
||||
// 3u-3v (#1873, U4a) adds store_tasks after project_system_types; the same holds for it.
|
||||
// 3u-3v (#1873, U4a) adds store_tasks; the same holds for it.
|
||||
.replace(readFileSync(new URL('../src/migrations/3u-3v.sql', import.meta.url), 'utf8'), '')
|
||||
.replace(",'prd.submitted','prd.activated','prd.invalidated','question.asked','question.answered','attach.selected','mode.changed','advanced'", '');
|
||||
const db = new DatabaseSync(path); db.exec(ddl);
|
||||
@@ -216,7 +215,7 @@ test('3p through 3s migration preserves existing request rows and the append-onl
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
const store = new Store(root, { migrateSchema: true }); t.after(() => store.close());
|
||||
assert.deepEqual(store.all('SELECT * FROM request_events'), before);
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3v');
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3w');
|
||||
store.run("INSERT INTO request_events(business,request,revision,kind,at,body) VALUES('demo','r',2,'prd.submitted',?,'{}')", at);
|
||||
assert.throws(() => store.run('DELETE FROM request_events'), /append-only/);
|
||||
assert.throws(() => store.run("UPDATE request_events SET body='{}'"), /append-only/);
|
||||
|
||||
@@ -143,8 +143,8 @@ const here = (p) => new URL(p, import.meta.url);
|
||||
const migrationSQL = readFileSync(here('../src/migrations/3s-3t.sql'), 'utf8');
|
||||
const currentDDL = readFileSync(here('../schema.sql'), 'utf8');
|
||||
assert.equal(currentDDL.split(migrationSQL).length, 2, 'schema.sql holds the 3s→3t step exactly once');
|
||||
// 3u-3v (#1873, U4a) adds store_tasks after them; a 3s store has neither.
|
||||
const ddl3s = currentDDL.replace(migrationSQL, '').replace(readFileSync(here('../src/migrations/3t-3u.sql'), 'utf8'), '').replace(readFileSync(here('../src/migrations/3u-3v.sql'), 'utf8'), '');
|
||||
// 3u-3v (#1873, U4a) adds store_tasks after it; a 3s store has neither table.
|
||||
const ddl3s = currentDDL.replace(migrationSQL, '').replace(readFileSync(here('../src/migrations/3u-3v.sql'), 'utf8'), '');
|
||||
|
||||
function source3s(t) {
|
||||
const root = mkdtempSync(join(tmpdir(), 'project-archive-3s-'));
|
||||
@@ -179,7 +179,7 @@ test('a 3s store migrates to 3t: project_archives is new and empty, every row st
|
||||
assert.deepEqual(master(path), was, 'the refused open changed nothing');
|
||||
const store = new Store(root, { migrateSchema: true });
|
||||
t.after(() => store.close());
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.equal(store.get("SELECT id FROM events").id, 'preserved');
|
||||
assert.equal(store.get("SELECT name FROM projects").name, 'kept');
|
||||
assert.deepEqual(store.all('SELECT seq,at,business,project,op,by FROM project_archives'), []);
|
||||
@@ -212,7 +212,7 @@ test('the 3s engine refuses a 3t store, migrating or not, and leaves it as it wa
|
||||
const source = readFileSync(here('../src/store.mjs'), 'utf8');
|
||||
const edited = source
|
||||
.replace(/export const SCHEMA_SHA256 = '[a-f0-9]+';/, `export const SCHEMA_SHA256 = '${createHash('sha256').update(ddl3s).digest('hex')}';`)
|
||||
.replace("export const SCHEMA_VERSION = '3v';", "export const SCHEMA_VERSION = '3s';")
|
||||
.replace("export const SCHEMA_VERSION = '3w';", "export const SCHEMA_VERSION = '3s';")
|
||||
.replace(/\}, \{\n {2}\/\/ #797 MVP3[\s\S]*?\}\];\nconst timedTables/, '}];\nconst timedTables');
|
||||
assert.ok(edited.includes("export const SCHEMA_VERSION = '3s';") && edited.includes('3r-3s') && !edited.includes('3s-3t'), 'the 3s engine has no 3s→3t step');
|
||||
writeFileSync(join(moduleRoot, 'src/store.mjs'), edited);
|
||||
@@ -222,7 +222,7 @@ test('the 3s engine refuses a 3t store, migrating or not, and leaves it as it wa
|
||||
const Store3s = (await import(pathToFileURL(join(moduleRoot, 'src/store.mjs')))).Store;
|
||||
assert.throws(() => new Store3s(root), /schema-mismatch/);
|
||||
assert.throws(() => new Store3s(root, { migrateSchema: true }), /schema-mismatch/);
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.deepEqual(master(path), was);
|
||||
// The same engine opens a fresh 3s store, so the refusal is the version's and not a broken copy.
|
||||
const { root: old } = source3s(t);
|
||||
|
||||
@@ -43,7 +43,8 @@ test('Broker keeps the sandbox client import closure: only the listed imports, n
|
||||
// Row 236 (#1742, #436b) reads giteaName and parseGiteaUrl for the Gitea grant path.
|
||||
// FED R3 r5 (row 274, #414) reads covers, a user's grant check, from it.
|
||||
// Row 219 reads THREAD_DEFINITIONS from the same vocabulary for creative thread admission.
|
||||
"import { pluginName, ID_PATTERN, THREAD_DEFINITIONS, END_PROTECTED, forkProblem, forkUrl, credentialKind, validArgv, commandAllowed, HOST_ID, CREATIVE_DEFINITIONS, giteaName, parseGiteaUrl, covers, grantScopeOf, grantInScope } from '../../organization/src/vocabulary.mjs';",
|
||||
// #1873 triage-fence reads SYSTEM_ONLY_REFUSAL and systemOnly from the same vocabulary.
|
||||
"import { pluginName, ID_PATTERN, THREAD_DEFINITIONS, END_PROTECTED, forkProblem, forkUrl, credentialKind, validArgv, commandAllowed, HOST_ID, CREATIVE_DEFINITIONS, giteaName, parseGiteaUrl, covers, grantScopeOf, grantInScope, SYSTEM_ONLY_REFUSAL, systemOnly } from '../../organization/src/vocabulary.mjs';",
|
||||
]);
|
||||
assert.doesNotMatch(source, /\bimport\s*\(/);
|
||||
assert.doesNotMatch(readFileSync(new URL('../src/proxy-page-vocabulary.mjs', import.meta.url), 'utf8'), /\bimport\b/);
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
// #1873 proxy-pickup: a running organization bus picks up the shared model proxy that another
|
||||
// organization's bus initialized, with no restart, through the start path's loader and lock. A
|
||||
// bus whose proxy settings the start path would refuse still refuses, and names the cause in one
|
||||
// plain line. Real buses and a fake loopback management server; no live config.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { startBroker } from '../src/runtime.mjs';
|
||||
import { busOrganization } from '../src/organization-context.mjs';
|
||||
import { createProxyLock } from '../src/proxy-lock.mjs';
|
||||
import { Registry } from '../../seat/src/session.mjs';
|
||||
import { loadBusiness } from '../../organization/src/organization-config.mjs';
|
||||
import { resolveInstance } from '../../organization/src/resolve.mjs';
|
||||
import { businessDoc, rolesCopy, systemFor, writeJson } from '../../organization/tests/helpers.mjs';
|
||||
import { PIN } from '../../model-proxy/src/common.mjs';
|
||||
import { initializeProxy, installPaths } from '../../model-proxy/src/settings.mjs';
|
||||
import { FIXTURE_ENTRY, FIXTURE_KEY_NAME } from '../../plugins/model-provider/fixture/index.mjs';
|
||||
|
||||
const sha = value => createHash('sha256').update(value).digest('hex');
|
||||
|
||||
// A loopback stand-in for the proxy's management API: one ready Claude account with one model.
|
||||
async function fakeProxy(t, key, port = 0) {
|
||||
const seen = { calls: 0, wrongKey: 0 };
|
||||
const server = http.createServer((req, res) => {
|
||||
seen.calls++;
|
||||
if (req.headers.authorization !== `Bearer ${key}`) { seen.wrongKey++; res.writeHead(401); res.end('{}'); return; }
|
||||
const url = new URL(req.url, 'http://127.0.0.1');
|
||||
const answer = url.pathname === '/v8/management/credentials' ? { files: [{ id: 'acct-1', name: 'acct-1', provider: 'claude', status: 'ready', priority: 1 }] }
|
||||
: url.pathname === '/v8/management/credentials/models' ? { models: [{ id: 'claude-opus-5-5' }] }
|
||||
: url.pathname === '/v8/management/config/api-keys/claude' ? []
|
||||
: url.pathname === '/v8/management/config/access/api-keys' ? []
|
||||
: null;
|
||||
if (answer === null) { res.writeHead(404); res.end('{}'); return; }
|
||||
res.end(JSON.stringify(answer));
|
||||
});
|
||||
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolve); });
|
||||
t.after(async () => { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); });
|
||||
return { port: server.address().port, seen, server };
|
||||
}
|
||||
|
||||
// One instance (config dir + data root) and a fake proxy install whose bytes a test pin names.
|
||||
// The pin keeps the shipped version, so the pinned binary path is the one loadProxy accepts.
|
||||
function instance(t) {
|
||||
const root = fs.mkdtempSync(join(tmpdir(), 'pk-'));
|
||||
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
|
||||
const configDir = join(root, 'config'), dataRoot = join(root, 'instance');
|
||||
fs.mkdirSync(join(configDir, 'secrets', 'agents'), { recursive: true, mode: 0o700 });
|
||||
fs.chmodSync(join(configDir, 'secrets'), 0o700);
|
||||
fs.mkdirSync(dataRoot, { mode: 0o700 });
|
||||
const paths = installPaths(dataRoot);
|
||||
fs.mkdirSync(join(paths.dir, 'static'), { recursive: true, mode: 0o700 });
|
||||
fs.writeFileSync(paths.binary, 'fixture proxy binary\n', { mode: 0o700 });
|
||||
fs.writeFileSync(paths.panel, '<!doctype html>\n', { mode: 0o600 });
|
||||
const pin = { ...PIN, binary: { ...PIN.binary, sha256: sha('fixture proxy binary\n') }, panel: { ...PIN.panel, sha256: sha('<!doctype html>\n') } };
|
||||
const rolesDir = rolesCopy(root), system = systemFor(root);
|
||||
const key = `pk1873-${randomBytes(24).toString('hex')}`;
|
||||
return { root, configDir, dataRoot, paths, pin, rolesDir, system, key, closers: [] };
|
||||
}
|
||||
|
||||
// A real organization bus on the instance, started with no proxy (as cli bootConfig does when the
|
||||
// instance has no proxy.json at boot).
|
||||
async function orgBus(t, f, id, { providers = ['cliproxy'], edit = () => {}, org = { id }, binding = {} } = {}) {
|
||||
const doc = businessDoc(f.root, id);
|
||||
doc.plugins = { harness: ['pi'], 'model-provider': providers };
|
||||
edit(doc);
|
||||
writeJson(join(f.configDir, 'businesses', `${id}.json`), doc);
|
||||
const business = loadBusiness(id, { dir: f.configDir, rolesDir: f.rolesDir }), resolved = {};
|
||||
for (const name of Object.keys(business.roles)) resolved[name] = resolveInstance({ system: f.system, business, instance: name });
|
||||
const dataRoot = join(f.root, `${id}-bus`); fs.mkdirSync(dataRoot, { mode: 0o700 }); new Registry(dataRoot);
|
||||
const bus = await startBroker({ dataRoot, businesses: { [id]: busOrganization(business, resolved) },
|
||||
organization: { dir: f.configDir, rolesDir: f.rolesDir, system: f.system },
|
||||
instanceRoot: f.dataRoot, org, instanceDataRoot: f.dataRoot, instanceConfigDir: f.configDir,
|
||||
initProxy: args => initializeProxy({ ...args, pin: f.pin }), ...binding });
|
||||
t.after(() => bus.close().catch(() => {}));
|
||||
const human = bus.broker.bindHuman({ business: id, human: 'jason', via: 'cli', outsideAgent: true });
|
||||
const ask = (verb, args) => Promise.resolve().then(() => bus.broker.request(human, { verb, args }));
|
||||
return { bus, ask, dataRoot };
|
||||
}
|
||||
|
||||
// Every stderr line written while `run` is in flight.
|
||||
async function capture(run) {
|
||||
const write = process.stderr.write, lines = [];
|
||||
process.stderr.write = (chunk, ...rest) => { lines.push(String(chunk)); return write.call(process.stderr, chunk, ...rest); };
|
||||
try { return { value: await run(), lines }; } finally { process.stderr.write = write; }
|
||||
}
|
||||
|
||||
// The proxy init through bus A writes proxy.json and the key, then the proxy starts on that port.
|
||||
async function initThroughA(t, f, a) {
|
||||
const settings = await a.ask('proxy.init', { key: f.key });
|
||||
const proxy = await fakeProxy(t, f.key, settings.port);
|
||||
return { settings, proxy };
|
||||
}
|
||||
|
||||
const notConfigured = (pattern) => e => e.code === 'not-configured' && typeof e.reason === 'string' && pattern.test(e.reason) && e.reason.length <= 300;
|
||||
|
||||
test('a running organization bus answers accounts and a cliproxy catalogue once another bus initialized the shared proxy, with no restart', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
// Before init: bus B has nothing to pick up, and says so.
|
||||
await assert.rejects(b.ask('proxy.accounts', {}), notConfigured(/not been set up/));
|
||||
const before = await b.ask('routes');
|
||||
assert.equal(before.catalogue.status, 'unavailable');
|
||||
assert.equal(before.catalogue.reason, 'proxy-not-configured');
|
||||
assert.equal(before.catalogue.notices.length, 1);
|
||||
const { proxy } = await initThroughA(t, f, a);
|
||||
// Bus A holds the client from its own init; bus B picks it up at its next read.
|
||||
assert.deepEqual((await a.ask('proxy.accounts', {})).accounts.map(r => r.provider), ['claude']);
|
||||
const accounts = await b.ask('proxy.accounts', {});
|
||||
assert.deepEqual(accounts.accounts.map(r => [r.provider, r.status]), [['claude', 'ready']]);
|
||||
const after = await b.ask('routes');
|
||||
assert.equal(after.catalogue.status, 'ready');
|
||||
assert.deepEqual(after.catalogue.models.map(m => m.key), ['claude-claude-opus-5-5']);
|
||||
assert.equal(after.catalogue.reason, undefined);
|
||||
assert.equal(proxy.seen.wrongKey, 0);
|
||||
// Bus B reached the proxy through the same lock identity the start path uses.
|
||||
assert.ok(createProxyLock({ stateDir: join(f.dataRoot, 'proxy'), identity: `${f.configDir}:${proxy.port}` }));
|
||||
});
|
||||
|
||||
test('a bus started before the proxy existed and asked only for a catalogue picks the proxy up', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
assert.equal((await b.ask('routes')).catalogue.status, 'unavailable');
|
||||
await initThroughA(t, f, a);
|
||||
assert.equal((await b.ask('routes')).catalogue.status, 'ready');
|
||||
});
|
||||
|
||||
// Each case writes the shared proxy's files by hand into a state the start path refuses.
|
||||
const refusedStates = [
|
||||
['proxy.json names an unpinned binary', /settings do not load/, f => writeJson(join(f.configDir, 'proxy.json'), { port: 40999, binary: '/elsewhere/cli-proxy-api' })],
|
||||
['proxy.json is not JSON', /settings do not load/, f => fs.writeFileSync(join(f.configDir, 'proxy.json'), '{', { mode: 0o600 })],
|
||||
['the management key file is readable by others', /management key does not load/, f => {
|
||||
writeJson(join(f.configDir, 'proxy.json'), { port: 40999, binary: f.paths.binary });
|
||||
fs.writeFileSync(join(f.configDir, 'secrets', 'proxy-management.key'), f.key, { mode: 0o644 });
|
||||
fs.chmodSync(join(f.configDir, 'secrets', 'proxy-management.key'), 0o644);
|
||||
}],
|
||||
['the management key file is missing', /management key does not load/, f => writeJson(join(f.configDir, 'proxy.json'), { port: 40999, binary: f.paths.binary })],
|
||||
['the proxy state names another port', /proxy lock/, f => {
|
||||
writeJson(join(f.configDir, 'proxy.json'), { port: 40999, binary: f.paths.binary });
|
||||
fs.writeFileSync(join(f.configDir, 'secrets', 'proxy-management.key'), f.key, { mode: 0o600 });
|
||||
fs.mkdirSync(join(f.dataRoot, 'proxy'), { mode: 0o700 });
|
||||
createProxyLock({ stateDir: join(f.dataRoot, 'proxy'), identity: `${f.configDir}:40998` });
|
||||
}],
|
||||
['the proxy state directory is open to others', /proxy lock/, f => {
|
||||
writeJson(join(f.configDir, 'proxy.json'), { port: 40999, binary: f.paths.binary });
|
||||
fs.writeFileSync(join(f.configDir, 'secrets', 'proxy-management.key'), f.key, { mode: 0o600 });
|
||||
fs.mkdirSync(join(f.dataRoot, 'proxy'), { mode: 0o755 }); fs.chmodSync(join(f.dataRoot, 'proxy'), 0o755);
|
||||
}],
|
||||
];
|
||||
for (const [name, cause, arrange] of refusedStates) test(`no pickup when ${name}: accounts and catalogue refuse with the cause`, async t => {
|
||||
const f = instance(t);
|
||||
const b = await orgBus(t, f, 'beta');
|
||||
arrange(f);
|
||||
await assert.rejects(b.ask('proxy.accounts', {}), notConfigured(cause));
|
||||
const view = await b.ask('routes');
|
||||
assert.equal(view.catalogue.status, 'unavailable');
|
||||
assert.equal(view.catalogue.reason, 'proxy-not-configured');
|
||||
assert.match(view.catalogue.notices[0], cause);
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
});
|
||||
|
||||
// The host refuses fixture-proxy-configured only when a dev fixture is recorded for the instance.
|
||||
const recordFixture = f => {
|
||||
fs.mkdirSync(join(f.dataRoot, 'dev-fixture'), { mode: 0o700 });
|
||||
fs.writeFileSync(join(f.dataRoot, 'dev-fixture', 'fixture.json'), '{}\n', { mode: 0o600 });
|
||||
};
|
||||
|
||||
test('no pickup for an organization on the fixture model provider, which the host refuses with a proxy', async t => {
|
||||
const f = instance(t);
|
||||
recordFixture(f);
|
||||
const a = await orgBus(t, f, 'alpha');
|
||||
const b = await orgBus(t, f, 'beta', { providers: ['fixture', 'cliproxy'], edit: doc => { doc.launch.models[FIXTURE_KEY_NAME] = { ...FIXTURE_ENTRY }; } });
|
||||
await initThroughA(t, f, a);
|
||||
await assert.rejects(b.ask('proxy.accounts', {}), notConfigured(/fixture-proxy-configured/));
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
const view = await b.ask('routes');
|
||||
assert.equal(view.catalogue.reason, 'proxy-not-configured');
|
||||
assert.match(view.catalogue.notices[0], /fixture/);
|
||||
});
|
||||
|
||||
test('no pickup for an organization whose launch table names the fixture module only', async t => {
|
||||
const f = instance(t);
|
||||
recordFixture(f);
|
||||
const a = await orgBus(t, f, 'alpha');
|
||||
const b = await orgBus(t, f, 'beta', { edit: doc => { doc.launch.models[FIXTURE_KEY_NAME] = { ...FIXTURE_ENTRY }; } });
|
||||
await initThroughA(t, f, a);
|
||||
await assert.rejects(b.ask('proxy.accounts', {}), notConfigured(/fixture-proxy-configured/));
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
});
|
||||
|
||||
test('an organization that lists the fixture still picks the proxy up when no fixture is recorded, as the host would start it', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha');
|
||||
const b = await orgBus(t, f, 'beta', { providers: ['fixture', 'cliproxy'] });
|
||||
await initThroughA(t, f, a);
|
||||
await b.ask('proxy.accounts', {});
|
||||
assert.ok(b.bus.modelProxy);
|
||||
// A fixture recorded later drops the client at the next request.
|
||||
recordFixture(f);
|
||||
await assert.rejects(b.ask('proxy.accounts', {}), notConfigured(/fixture-proxy-configured/));
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
});
|
||||
|
||||
test('a picked-up client is dropped when proxy.json goes away, its port changes, or the key stops loading', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
const { settings } = await initThroughA(t, f, a);
|
||||
await b.ask('proxy.accounts', {});
|
||||
assert.ok(b.bus.modelProxy);
|
||||
const file = join(f.configDir, 'proxy.json'), keyFile = join(f.configDir, 'secrets', 'proxy-management.key');
|
||||
const saved = fs.readFileSync(file);
|
||||
// Port change: the lock identity is bound to the port, so the bus refuses until a restart.
|
||||
writeJson(file, { ...settings, port: settings.port + 1 === 8317 ? settings.port + 2 : settings.port + 1 });
|
||||
await assert.rejects(b.ask('proxy.accounts', {}), notConfigured(/proxy lock/));
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
assert.equal((await b.ask('routes')).catalogue.status, 'unavailable');
|
||||
// Back to the original port, the bus picks it up again.
|
||||
fs.writeFileSync(file, saved);
|
||||
await b.ask('proxy.accounts', {});
|
||||
assert.ok(b.bus.modelProxy);
|
||||
// Key file no longer 0600.
|
||||
fs.chmodSync(keyFile, 0o640);
|
||||
await assert.rejects(b.ask('proxy.accounts', {}), notConfigured(/management key does not load/));
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
fs.chmodSync(keyFile, 0o600);
|
||||
await b.ask('proxy.accounts', {});
|
||||
// proxy.json removed.
|
||||
fs.rmSync(file);
|
||||
await assert.rejects(b.ask('proxy.accounts', {}), notConfigured(/not been set up/));
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
const view = await b.ask('routes');
|
||||
assert.equal(view.catalogue.status, 'unavailable');
|
||||
assert.equal(view.catalogue.reason, 'proxy-not-configured');
|
||||
});
|
||||
|
||||
test('a default-instance bus (no organization binding, no lock) follows a port change to the new client, never the old one', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), d = await orgBus(t, f, 'delta', { org: null });
|
||||
const { settings, proxy } = await initThroughA(t, f, a);
|
||||
assert.deepEqual((await d.ask('proxy.accounts', {})).accounts.map(r => r.provider), ['claude']);
|
||||
const old = d.bus.modelProxy;
|
||||
// A listener on the new port that answers nothing to the right key: reaching it proves the move.
|
||||
const moved = await fakeProxy(t, `other-${f.key.slice(0, 6)}`);
|
||||
writeJson(join(f.configDir, 'proxy.json'), { ...settings, port: moved.port });
|
||||
const before = proxy.seen.calls;
|
||||
await assert.rejects(d.ask('proxy.accounts', {}));
|
||||
assert.ok(d.bus.modelProxy && d.bus.modelProxy !== old);
|
||||
assert.ok(moved.seen.calls > 0);
|
||||
assert.equal(proxy.seen.calls, before);
|
||||
});
|
||||
|
||||
test('a picked-up bus reads its catalogue through the shared lock: a fence makes it unavailable', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
const { proxy } = await initThroughA(t, f, a);
|
||||
assert.equal((await b.ask('routes')).catalogue.status, 'ready');
|
||||
createProxyLock({ stateDir: join(f.dataRoot, 'proxy'), identity: `${f.configDir}:${proxy.port}` }).fence({ org: 'alpha' });
|
||||
const view = await b.ask('routes');
|
||||
assert.equal(view.catalogue.status, 'unavailable');
|
||||
assert.ok(b.bus.modelProxy, 'the client stays; the fence alone holds the catalogue');
|
||||
});
|
||||
|
||||
test('a fixture record path in any state but absent counts as recorded', async t => {
|
||||
const f = instance(t);
|
||||
fs.writeFileSync(join(f.dataRoot, 'dev-fixture'), 'not a directory\n', { mode: 0o600 });
|
||||
const a = await orgBus(t, f, 'alpha');
|
||||
const b = await orgBus(t, f, 'beta', { providers: ['fixture', 'cliproxy'] });
|
||||
await initThroughA(t, f, a);
|
||||
await assert.rejects(b.ask('proxy.accounts', {}), notConfigured(/fixture-proxy-configured/));
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
});
|
||||
|
||||
test('with a fixture recorded, an organization document that no longer validates counts as using it', async t => {
|
||||
const f = instance(t);
|
||||
recordFixture(f);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
await initThroughA(t, f, a);
|
||||
fs.writeFileSync(join(f.configDir, 'businesses', 'beta.json'), '{', { mode: 0o600 });
|
||||
await assert.rejects(b.ask('proxy.accounts', {}), notConfigured(/fixture-proxy-configured/));
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
});
|
||||
|
||||
test('the bus that ran init also drops its client when the key stops loading', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha');
|
||||
await initThroughA(t, f, a);
|
||||
await a.ask('proxy.accounts', {});
|
||||
fs.rmSync(join(f.configDir, 'secrets', 'proxy-management.key'));
|
||||
await assert.rejects(a.ask('proxy.accounts', {}), notConfigured(/management key does not load/));
|
||||
assert.equal(a.bus.modelProxy, null);
|
||||
});
|
||||
|
||||
test('an init whose lock refuses leaves the init bus holding no client: no ready catalogue without the lock', async t => {
|
||||
const f = instance(t);
|
||||
// The real init, then the proxy state dir is left readable by the group, which the lock refuses.
|
||||
const initProxy = async args => { const settings = await initializeProxy({ ...args, pin: f.pin });
|
||||
fs.mkdirSync(join(f.dataRoot, 'proxy'), { recursive: true }); fs.chmodSync(join(f.dataRoot, 'proxy'), 0o750); return settings; };
|
||||
const a = await orgBus(t, f, 'alpha', { binding: { initProxy } });
|
||||
await assert.rejects(a.ask('proxy.init', { key: f.key }));
|
||||
await fakeProxy(t, f.key, JSON.parse(fs.readFileSync(join(f.configDir, 'proxy.json'), 'utf8')).port);
|
||||
assert.equal(a.bus.modelProxy, null);
|
||||
const view = await a.ask('routes');
|
||||
assert.equal(view.catalogue.status, 'unavailable');
|
||||
assert.match(view.catalogue.notices[0], /proxy-lock-invalid/);
|
||||
assert.equal(a.bus.modelProxy, null);
|
||||
});
|
||||
|
||||
test('a default-instance bus (no lock generation) refreshes its catalogue at once on pickup and on drop', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), d = await orgBus(t, f, 'delta', { org: null });
|
||||
// An unavailable catalogue read before init must not be served after the pickup.
|
||||
assert.equal((await d.ask('routes')).catalogue.status, 'unavailable');
|
||||
await initThroughA(t, f, a);
|
||||
assert.equal((await d.ask('routes')).catalogue.status, 'ready');
|
||||
// A ready catalogue read through the picked-up client must not be served after the drop.
|
||||
fs.rmSync(join(f.configDir, 'proxy.json'));
|
||||
const gone = await d.ask('routes');
|
||||
assert.equal(gone.catalogue.status, 'unavailable');
|
||||
assert.equal(gone.catalogue.reason, 'proxy-not-configured');
|
||||
assert.equal(d.bus.modelProxy, null);
|
||||
});
|
||||
|
||||
test('a picked-up bus clears a proxy fence through the same client and lock', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
await initThroughA(t, f, a);
|
||||
// proxy.fence.clear on a bus that has not read anything yet still picks the proxy up first; the
|
||||
// restart evidence check is the existing one and refuses this empty evidence.
|
||||
await assert.rejects(b.ask('proxy.fence.clear', { evidence: {} }));
|
||||
assert.ok(b.bus.modelProxy);
|
||||
});
|
||||
|
||||
test('a bus serving an invalid organization id never picks up a proxy', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha');
|
||||
await initThroughA(t, f, a);
|
||||
let b;
|
||||
try { b = await orgBus(t, f, 'beta', { binding: { instanceConfigDir: 42 } }); }
|
||||
catch (error) { assert.equal(error.code, 'invalid-host-request'); return; }
|
||||
await assert.rejects(b.ask('proxy.accounts', {}), notConfigured(/organization binding/));
|
||||
assert.equal(b.bus.modelProxy, null);
|
||||
});
|
||||
|
||||
test('the management key is in no stderr line, response, refusal, event or file the pickup path writes', async t => {
|
||||
const f = instance(t);
|
||||
const a = await orgBus(t, f, 'alpha'), b = await orgBus(t, f, 'beta');
|
||||
await initThroughA(t, f, a);
|
||||
const outputs = [];
|
||||
const { lines } = await capture(async () => {
|
||||
outputs.push(await b.ask('proxy.accounts', {}));
|
||||
outputs.push(await b.ask('routes'));
|
||||
// A refusal after the key stops loading, and the pickup after it loads again.
|
||||
fs.chmodSync(join(f.configDir, 'secrets', 'proxy-management.key'), 0o644);
|
||||
await b.ask('proxy.accounts', {}).catch(error => outputs.push({ code: error.code, reason: error.reason, message: error.message, next: error.next }));
|
||||
outputs.push(await b.ask('routes'));
|
||||
fs.chmodSync(join(f.configDir, 'secrets', 'proxy-management.key'), 0o600);
|
||||
outputs.push(await b.ask('proxy.accounts', {}));
|
||||
});
|
||||
assert.ok(lines.some(line => line.startsWith('model-proxy: ')), 'the pickup client writes its usual receipts');
|
||||
assert.equal(lines.join('').includes(f.key), false, 'stderr');
|
||||
assert.equal(JSON.stringify(outputs).includes(f.key), false, 'responses');
|
||||
// Every file under bus B's data root (store, WAL, sessions) and the proxy state directory,
|
||||
// except the proxy's own config.yaml that init writes for the proxy process.
|
||||
const walk = dir => fs.readdirSync(dir, { withFileTypes: true }).flatMap(e => e.isDirectory() ? walk(join(dir, e.name)) : e.isFile() ? [join(dir, e.name)] : []);
|
||||
const files = [...walk(b.dataRoot), ...walk(join(f.dataRoot, 'proxy')).filter(p => !p.endsWith('/config.yaml'))];
|
||||
assert.ok(files.length > 0);
|
||||
for (const file of files) assert.equal(fs.readFileSync(file).includes(f.key), false, file);
|
||||
});
|
||||
@@ -90,7 +90,7 @@ const ask = (x, state, extra = {}) => x.call('pm', 'request.question', { request
|
||||
options: [{ key: 'web', text: 'Web' }, { key: 'cli', text: 'CLI' }], ...extra });
|
||||
|
||||
test('the console verb list includes the artifact read and existing owner controls', () => {
|
||||
assert.deepEqual([...CONSOLE_VERBS], ['system-types.console', 'project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
|
||||
assert.deepEqual([...CONSOLE_VERBS], ['project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'pack.hire.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
|
||||
'request.get.console', 'request.projects.console', 'request.answer.console', 'request.attach.console', 'request.cancel.console',
|
||||
// Starter packs SP4 (#1873): the owner's pack list and preview, and the three pack writes.
|
||||
'packs.console', 'pack.preview.console', 'pack.apply.console', 'board.set.console', 'workflow.set.console',
|
||||
@@ -306,7 +306,7 @@ test('a cancel is refused when the owner-to-PM edge closed, with no withdrawn de
|
||||
});
|
||||
|
||||
test('3q through 3s widens the kind list to the union, keeps every 3q kind, row, seq and guard, and the chain matches the fresh digest', t => {
|
||||
assert.equal(SCHEMA_VERSION, '3v');
|
||||
assert.equal(SCHEMA_VERSION, '3w');
|
||||
const root = mkdtempSync(join(tmpdir(), 'request-migration-3r-'));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true })); mkdirSync(join(root, 'bus'), { mode: 0o700 });
|
||||
const path = join(root, 'bus/bus.sqlite'), AT = '2026-11-03T00:00:00.000Z';
|
||||
@@ -314,11 +314,10 @@ test('3q through 3s widens the kind list to the union, keeps every 3q kind, row,
|
||||
// 3s-3t (#797) adds project_archives, outside request_events; the 3q fixture predates it and
|
||||
// the replayed chain recreates it, so the step's text is removed here like the kinds are.
|
||||
const step3t = readFileSync(new URL('../src/migrations/3s-3t.sql', import.meta.url), 'utf8');
|
||||
// 3t-3u (#1873, SYS1) adds project_system_types the same way, and 3u-3v (U4a) adds store_tasks.
|
||||
const step3u = readFileSync(new URL('../src/migrations/3t-3u.sql', import.meta.url), 'utf8');
|
||||
// 3u-3v (#1873, U4a) adds store_tasks the same way.
|
||||
const step3v = readFileSync(new URL('../src/migrations/3u-3v.sql', import.meta.url), 'utf8');
|
||||
// 3p-3q shipped the PRD kinds and mode.changed; 3q-3r adds the three Task 3 kinds after them.
|
||||
const ddl3q = current.replace(step3t, '').replace(step3u, '').replace(step3v, '').replace(",'advanced'", '').replace("'prd.invalidated','question.asked','question.answered','attach.selected','mode.changed','cancelled'", "'prd.invalidated','mode.changed','cancelled'");
|
||||
const ddl3q = current.replace(step3t, '').replace(step3v, '').replace(",'advanced'", '').replace("'prd.invalidated','question.asked','question.answered','attach.selected','mode.changed','cancelled'", "'prd.invalidated','mode.changed','cancelled'");
|
||||
assert.notEqual(ddl3q, current, 'the fixture is the narrower schema');
|
||||
const migration = readFileSync(new URL('../src/migrations/3q-3r.sql', import.meta.url), 'utf8');
|
||||
assert.ok(migration.includes("'prd.submitted','prd.activated','prd.invalidated','question.asked','question.answered','attach.selected','mode.changed','cancelled'"), 'the step carries every 3q kind plus its own');
|
||||
@@ -335,7 +334,7 @@ test('3q through 3s widens the kind list to the union, keeps every 3q kind, row,
|
||||
db.close(); chmodSync(path, 0o600);
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
const cli = spawnSync(process.execPath, [new URL('../src/migrate-schema.mjs', import.meta.url).pathname, root], { encoding: 'utf8' });
|
||||
assert.equal(cli.status, 0, cli.stderr); assert.equal(cli.stdout, 'bus schema 3v ready\n');
|
||||
assert.equal(cli.status, 0, cli.stderr); assert.equal(cli.stdout, 'bus schema 3w ready\n');
|
||||
const store = new Store(root);
|
||||
assert.deepEqual(store.all('SELECT * FROM request_events ORDER BY seq'), before, 'every row keeps its seq and bytes, including the 3q kinds');
|
||||
const fresh = new DatabaseSync(':memory:'); fresh.exec(current);
|
||||
|
||||
@@ -230,8 +230,7 @@ test('3r to 3s migration preserves journal and sequence and admits only the new
|
||||
// 3s-3t (#797) adds project_archives; the 3r fixture predates it and the replayed chain recreates it.
|
||||
db.exec(readFileSync(new URL('../schema.sql', import.meta.url), 'utf8')
|
||||
.replace(readFileSync(new URL('../src/migrations/3s-3t.sql', import.meta.url), 'utf8'), '')
|
||||
.replace(readFileSync(new URL('../src/migrations/3t-3u.sql', import.meta.url), 'utf8'), '')
|
||||
// 3u-3v (#1873, U4a) adds store_tasks after project_system_types; the same holds for it.
|
||||
// 3u-3v (#1873, U4a) adds store_tasks; the same holds for it.
|
||||
.replace(readFileSync(new URL('../src/migrations/3u-3v.sql', import.meta.url), 'utf8'), '')
|
||||
.replace(",'advanced'", ''));
|
||||
db.prepare('INSERT INTO meta VALUES(?,?)').run('schema_version', '3r');
|
||||
@@ -253,7 +252,7 @@ test('3r to 3s migration preserves journal and sequence and admits only the new
|
||||
assert.deepEqual(store.all('SELECT * FROM request_events ORDER BY seq'), before);
|
||||
assert.deepEqual(store.all("SELECT name,sql FROM sqlite_master WHERE type='trigger' AND tbl_name IN ('request_events','request_effects') ORDER BY name"), guards);
|
||||
assert.equal(store.get("SELECT name FROM sqlite_master WHERE type='index' AND name='request_events_request'").name, 'request_events_request');
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3v');
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3w');
|
||||
store.run("INSERT INTO request_events(business,request,revision,kind,at,body) VALUES('demo','r',16,'advanced',?,'{}')", at);
|
||||
assert.equal(store.get("SELECT max(seq) n FROM request_events").n, 42);
|
||||
assert.throws(() => store.run("UPDATE request_events SET kind='opened'"), /append-only/);
|
||||
|
||||
@@ -278,8 +278,7 @@ test('3n_to_3o_is_explicit_offline_preserves_rows_and_old_engine_refuses_new_sch
|
||||
// 3s-3t (#797) adds project_archives after the request tables; the pre-3t fixtures below
|
||||
// predate it and the replayed chain recreates it, so the step's text comes out here too.
|
||||
.replace(readFileSync(new URL('../src/migrations/3s-3t.sql', import.meta.url), 'utf8'), '')
|
||||
.replace(readFileSync(new URL('../src/migrations/3t-3u.sql', import.meta.url), 'utf8'), '')
|
||||
// 3u-3v (#1873, U4a) adds store_tasks after project_system_types; the same holds for it.
|
||||
// 3u-3v (#1873, U4a) adds store_tasks; the same holds for it.
|
||||
.replace(readFileSync(new URL('../src/migrations/3u-3v.sql', import.meta.url), 'utf8'), '')
|
||||
.replace("'setup.wait','bootstrap.stale','bootstrap.completed','prd.submitted','prd.activated','prd.invalidated','question.asked','question.answered','attach.selected','mode.changed','advanced','cancelled'", "'setup.wait','cancelled'");
|
||||
const newDDL = readFileSync(new URL('../src/migrations/3n-3o.sql', import.meta.url), 'utf8');
|
||||
@@ -293,7 +292,7 @@ test('3n_to_3o_is_explicit_offline_preserves_rows_and_old_engine_refuses_new_sch
|
||||
db.close(); chmodSync(path, 0o600); const before = readFileSync(path);
|
||||
assert.throws(() => new Store(root), /schema-mismatch/); assert.deepEqual(readFileSync(path), before);
|
||||
const cli = spawnSync(process.execPath, [new URL('../src/migrate-schema.mjs', import.meta.url).pathname, root], { encoding: 'utf8' });
|
||||
assert.equal(cli.status, 0, cli.stderr); assert.equal(cli.stdout, 'bus schema 3v ready\n'); assert.equal(SCHEMA_VERSION, '3v');
|
||||
assert.equal(cli.status, 0, cli.stderr); assert.equal(cli.stdout, 'bus schema 3w ready\n'); assert.equal(SCHEMA_VERSION, '3w');
|
||||
const store = new Store(root); assert.equal(store.get("SELECT id FROM events").id, 'preserved');
|
||||
for (const table of ['request_events','request_effects','request_snapshots','request_snapshot_events','request_project_events']) assert.equal(store.get(`SELECT count(*) n FROM ${table}`).n, 0);
|
||||
store.close(); assert.equal(spawnSync(process.execPath, [new URL('../src/migrate-schema.mjs', import.meta.url).pathname, root]).status, 0);
|
||||
@@ -316,8 +315,7 @@ test('3o_to_3p_widens_only_the_event_kinds_and_keeps_rows_seq_and_guards', t =>
|
||||
// The 3o schema is the current one with the narrower kind list.
|
||||
const ddl3o = readFileSync(new URL('../schema.sql', import.meta.url), 'utf8')
|
||||
.replace(readFileSync(new URL('../src/migrations/3s-3t.sql', import.meta.url), 'utf8'), '')
|
||||
.replace(readFileSync(new URL('../src/migrations/3t-3u.sql', import.meta.url), 'utf8'), '')
|
||||
// 3u-3v (#1873, U4a) adds store_tasks after project_system_types; the same holds for it.
|
||||
// 3u-3v (#1873, U4a) adds store_tasks; the same holds for it.
|
||||
.replace(readFileSync(new URL('../src/migrations/3u-3v.sql', import.meta.url), 'utf8'), '')
|
||||
.replace("'setup.wait','bootstrap.stale','bootstrap.completed','prd.submitted','prd.activated','prd.invalidated','question.asked','question.answered','attach.selected','mode.changed','advanced','cancelled'", "'setup.wait','cancelled'");
|
||||
const { schemaDigest } = awaitImportStore, AT = '2026-11-03T00:00:00.000Z';
|
||||
@@ -335,7 +333,7 @@ test('3o_to_3p_widens_only_the_event_kinds_and_keeps_rows_seq_and_guards', t =>
|
||||
db.close(); chmodSync(path, 0o600);
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
const cli = spawnSync(process.execPath, [new URL('../src/migrate-schema.mjs', import.meta.url).pathname, root], { encoding: 'utf8' });
|
||||
assert.equal(cli.status, 0, cli.stderr); assert.equal(cli.stdout, 'bus schema 3v ready\n');
|
||||
assert.equal(cli.status, 0, cli.stderr); assert.equal(cli.stdout, 'bus schema 3w ready\n');
|
||||
const store = new Store(root);
|
||||
assert.deepEqual(store.all('SELECT * FROM request_events ORDER BY seq'), before, 'every row keeps its seq and bytes');
|
||||
assert.deepEqual(store.all('SELECT * FROM request_effects ORDER BY seq'), effects);
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { SCHEMA_VERSION, Store, schemaDigest } from '../src/store.mjs';
|
||||
|
||||
// #1873 SP9: bus schema step 3v-3w drops project_system_types with its index, its four triggers and
|
||||
// its rows (Jason's 2026-11-12 ruling removes the system-type kind outright).
|
||||
const TABLE = 'project_system_types';
|
||||
const ddl = readFileSync(new URL('../schema.sql', import.meta.url), 'utf8');
|
||||
const createdBy3u = readFileSync(new URL('../src/migrations/3t-3u.sql', import.meta.url), 'utf8');
|
||||
const named = (path) => {
|
||||
const db = new DatabaseSync(path, { readOnly: true });
|
||||
try {
|
||||
return {
|
||||
master: db.prepare('SELECT type,name FROM sqlite_master WHERE name LIKE ? OR tbl_name=? ORDER BY type,name').all(`${TABLE}%`, TABLE).map((r) => ({ ...r })),
|
||||
sequence: db.prepare('SELECT name FROM sqlite_sequence WHERE name=?').all(TABLE).map((r) => r.name),
|
||||
digest: schemaDigest(db),
|
||||
version: db.prepare("SELECT value FROM meta WHERE key='schema_version'").get().value,
|
||||
};
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
};
|
||||
|
||||
test('SP9 a store opened at schema 3w has no project_system_types table', (t) => {
|
||||
assert.equal(SCHEMA_VERSION, '3w');
|
||||
assert.equal(ddl.includes(TABLE), false, 'schema.sql no longer creates the table');
|
||||
const root = mkdtempSync(join(tmpdir(), 'sp9-fresh-'));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
new Store(root).close();
|
||||
const fresh = named(join(root, 'bus/bus.sqlite'));
|
||||
assert.equal(fresh.version, '3w');
|
||||
assert.deepEqual(fresh.master, []);
|
||||
});
|
||||
|
||||
test('SP9 a 3v store holding project_system_types rows migrates to 3w with nothing of the table left', (t) => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'sp9-3v-'));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
mkdirSync(join(root, 'bus'), { mode: 0o700 });
|
||||
const path = join(root, 'bus/bus.sqlite');
|
||||
const db = new DatabaseSync(path);
|
||||
// The 3v schema is today's schema.sql plus what 3t-3u created; the store's step check refuses any
|
||||
// other shape, so a migration that succeeds proves the fixture is a real 3v store.
|
||||
db.exec(ddl + createdBy3u);
|
||||
db.prepare('INSERT INTO meta VALUES (?,?)').run('schema_version', '3v');
|
||||
db.prepare('INSERT INTO meta VALUES (?,?)').run('schema_digest', schemaDigest(db));
|
||||
db.prepare('INSERT INTO meta VALUES (?,?)').run('comment_cursor_epoch', '2026-11-12T00:00:00.000Z');
|
||||
db.prepare('INSERT INTO projects(id,at,business,name,repo,created_by) VALUES(?,?,?,?,?,?)').run('p1', '2026-11-12T00:00:00.000Z', 'acme', 'example', null, 'jason');
|
||||
const select = db.prepare(`INSERT INTO ${TABLE}(at,business,project,types,by) VALUES(?,?,?,?,?)`);
|
||||
select.run('2026-11-12T00:00:01.000Z', 'acme', 'p1', '["coding"]', 'jason');
|
||||
select.run('2026-11-12T00:00:02.000Z', 'acme', 'p1', '["coding","montage"]', 'jason');
|
||||
db.close();
|
||||
chmodSync(path, 0o600);
|
||||
const before = named(path);
|
||||
assert.deepEqual(before.master.map((r) => r.name).sort(), [TABLE, `${TABLE}_business`, `${TABLE}_no_delete`, `${TABLE}_no_replace`, `${TABLE}_no_update`, `${TABLE}_project`]);
|
||||
assert.deepEqual(before.sequence, [TABLE]);
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
assert.deepEqual(named(path), before, 'the refused open changed nothing');
|
||||
const store = new Store(root, { migrateSchema: true });
|
||||
t.after(() => store.close());
|
||||
assert.equal(store.get('SELECT name FROM projects WHERE id=?', 'p1').name, 'example', 'other rows stay');
|
||||
const after = named(path);
|
||||
assert.equal(after.version, '3w');
|
||||
assert.deepEqual(after.master, [], 'no table, index or trigger of that name is left');
|
||||
assert.deepEqual(after.sequence, [], 'no sqlite_sequence row of that name is left');
|
||||
const freshRoot = mkdtempSync(join(tmpdir(), 'sp9-ref-'));
|
||||
t.after(() => rmSync(freshRoot, { recursive: true, force: true }));
|
||||
new Store(freshRoot).close();
|
||||
assert.equal(after.digest, named(join(freshRoot, 'bus/bus.sqlite')).digest, 'the migrated schema is the fresh one');
|
||||
});
|
||||
@@ -528,7 +528,8 @@ test('v3b prototype refusals, views and append-only mutations', (t) => {
|
||||
// Task 4 (3p to 3q), Task 3 (3q to 3r) and Task 6b (3r to 3s) widen request_events.kind in place.
|
||||
// #797 MVP3 (3s to 3t) adds project_archives and its five guards; project-archive.test.mjs tests them.
|
||||
// 3t to 3u adds project_system_types and four guards; U4a #1873 (3u to 3v) adds store_tasks and its seven guards.
|
||||
assert.equal(count('table') - 1, 33);
|
||||
assert.equal(count('trigger'), 130);
|
||||
// SP9 #1873 (3v to 3w) drops project_system_types and its four guards.
|
||||
assert.equal(count('table') - 1, 32);
|
||||
assert.equal(count('trigger'), 126);
|
||||
assert.equal(count('view'), 5);
|
||||
});
|
||||
@@ -530,9 +530,9 @@ test('T4 schema: a 3m store migrates to 3n, session_ops and message_cancels are
|
||||
const before = tables(path);
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
new Store(root, { migrateSchema: true }).close();
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
const after = tables(path);
|
||||
for (const name of ['session_ops', 'message_cancels', 'request_events', 'request_effects', 'request_snapshots', 'request_snapshot_events', 'request_project_events', 'project_archives', 'project_system_types', 'store_tasks']) {
|
||||
for (const name of ['session_ops', 'message_cancels', 'request_events', 'request_effects', 'request_snapshots', 'request_snapshot_events', 'request_project_events', 'project_archives', 'store_tasks']) {
|
||||
assert.deepEqual(after[name], [], name);
|
||||
delete after[name];
|
||||
}
|
||||
@@ -571,7 +571,7 @@ async function engine3m(root) {
|
||||
const source = readFileSync(here('../src/store.mjs'), 'utf8');
|
||||
const edited = source
|
||||
.replace(/export const SCHEMA_SHA256 = '[a-f0-9]+';/, `export const SCHEMA_SHA256 = '${createHash('sha256').update(ddl3m).digest('hex')}';`)
|
||||
.replace("export const SCHEMA_VERSION = '3v';", "export const SCHEMA_VERSION = '3m';")
|
||||
.replace("export const SCHEMA_VERSION = '3w';", "export const SCHEMA_VERSION = '3m';")
|
||||
.replace(/\}, \{\n {2}\/\/ Row 271 \(#1776\)[\s\S]*?\}\];\nconst timedTables/, '}];\nconst timedTables');
|
||||
assert.ok(edited.includes("export const SCHEMA_VERSION = '3m';") && edited.includes('3l-3m') && !edited.includes('3m-3n'), 'the 3m engine has no 3m→3n step');
|
||||
writeFileSync(join(moduleRoot, 'src/store.mjs'), edited);
|
||||
@@ -588,7 +588,7 @@ test('T4 schema: the 3m engine refuses a 3n store, migrating or not, and leaves
|
||||
const Store3m = await engine3m(root);
|
||||
assert.throws(() => new Store3m(root), /schema-mismatch/);
|
||||
assert.throws(() => new Store3m(root, { migrateSchema: true }), /schema-mismatch/);
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.deepEqual(master(path), was);
|
||||
assert.deepEqual(tables(path), before);
|
||||
// The same engine opens a fresh 3m store, so the refusal is the version's and not a broken copy.
|
||||
|
||||
@@ -374,7 +374,7 @@ test('T7: a 3k store migrates to 3l, each thread\'s default session has the thre
|
||||
const { root, path } = source3k(t);
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
new Store(root, { migrateSchema: true }).close();
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
// The migrated schema is the fresh one, object for object.
|
||||
const freshRoot = mkdtempSync(join(tmpdir(), 'sessions-fresh-'));
|
||||
t.after(() => rmSync(freshRoot, { recursive: true, force: true }));
|
||||
@@ -430,7 +430,7 @@ async function engine3k(root) {
|
||||
const source = readFileSync(here('../src/store.mjs'), 'utf8');
|
||||
const edited = source
|
||||
.replace(/export const SCHEMA_SHA256 = '[a-f0-9]+';/, `export const SCHEMA_SHA256 = '${createHash('sha256').update(ddl3k).digest('hex')}';`)
|
||||
.replace("export const SCHEMA_VERSION = '3v';", "export const SCHEMA_VERSION = '3k';")
|
||||
.replace("export const SCHEMA_VERSION = '3w';", "export const SCHEMA_VERSION = '3k';")
|
||||
.replace(/\}, \{\n {2}\/\/ Row 264a \(#1769\)[\s\S]*?\}\];\nconst timedTables/, '}];\nconst timedTables');
|
||||
assert.ok(edited.includes("export const SCHEMA_VERSION = '3k';") && edited.includes('3j-3k') && !edited.includes('3k-3l'), 'the 3k engine has no 3k→3l step');
|
||||
writeFileSync(join(moduleRoot, 'src/store.mjs'), edited);
|
||||
@@ -447,7 +447,7 @@ test('T7 D9: the 3k engine refuses a 3l store, migrating or not, and leaves it a
|
||||
const Store3k = await engine3k(root);
|
||||
assert.throws(() => new Store3k(root), /schema-mismatch/);
|
||||
assert.throws(() => new Store3k(root, { migrateSchema: true }), /schema-mismatch/);
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.deepEqual(master(path), was);
|
||||
assert.deepEqual(rows(path), before);
|
||||
// The same engine opens a fresh 3k store, so the refusal is the version's and not a broken copy.
|
||||
|
||||
@@ -63,7 +63,7 @@ test('3e copy migrates through 3f to 3g preserving every old column/row and addi
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
const store = new Store(root, { migrateSchema: true });
|
||||
try {
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3v');
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3w');
|
||||
assert.deepEqual({ ...store.get('SELECT spec_path,spec_commit FROM decisions') }, { spec_path: null, spec_commit: null });
|
||||
assert.equal(store.get('PRAGMA quick_check').quick_check, 'ok');
|
||||
assert.deepEqual(store.all('PRAGMA foreign_key_check'), []);
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
// #1873 lane triage-fence: through the broker, no organization gains the system-only Triage
|
||||
// template. Pack preview and apply, the Console hire start, the chief's hire.raise and
|
||||
// decision.raise, and instances.set add as the human and the tester each refuse with
|
||||
// template-system-only; the Console's hire template list omits triage. The coding pack still
|
||||
// previews as before. Fixtures live in a temp directory.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { chmodSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { Broker } from '../src/broker.mjs';
|
||||
import { Store } from '../src/store.mjs';
|
||||
import { pluginHash } from '../../plugins/src/pinned.mjs';
|
||||
import { installPlugin } from '../../plugins/src/install.mjs';
|
||||
import { starterPack as codingPack } from '../../plugins/starter-pack/coding/index.mjs';
|
||||
import { templateHash } from '../../organization/src/definitions.mjs';
|
||||
import { hireDecisions } from '../../organization/src/hire-decisions.mjs';
|
||||
import { organizationWriter } from '../../organization/src/organization.mjs';
|
||||
import { loadBusiness } from '../../organization/src/organization-config.mjs';
|
||||
import { businessDoc, rolesCopy, systemFor, writeJson } from '../../organization/tests/helpers.mjs';
|
||||
|
||||
const CODE = 'template-system-only';
|
||||
const SUBJECT = { provider: 'test', iss: 'https://issuer.test', sub: 'owner' };
|
||||
const ROUTE = { harness: 'pi', model: 'claude-opus-5-5' };
|
||||
|
||||
// The broker started as the runtime starts it, with the organization writer and installed packs.
|
||||
async function runtime(t) {
|
||||
const { startBroker } = await import('../src/runtime.mjs');
|
||||
const root = mkdtempSync(join(tmpdir(), 'sobus-'));
|
||||
const rolesDir = rolesCopy(root);
|
||||
const doc = businessDoc(root, 'demo');
|
||||
doc.plugins = { harness: ['pi'] };
|
||||
doc.roles.chief.vars = { ...ROUTE };
|
||||
writeJson(join(root, 'businesses/demo.json'), doc);
|
||||
const data = join(root, 'data');
|
||||
mkdirSync(data, { mode: 0o700 });
|
||||
const roles = { chief: { definition: 'chief-of-staff', authority: { withinRole: ['decision.resolve.technical', 'decision.resolve.delivery', 'organization.change'], crossRole: [] } } };
|
||||
const businesses = { demo: { id: 'demo', human: 'jason', arbiters: { technical: 'chief', delivery: 'chief' }, roles, vars: { 'bus.tester': true } } };
|
||||
const bus = await startBroker({ dataRoot: data, businesses, organization: { dir: root, rolesDir, system: systemFor(root) } });
|
||||
const thaw = (p) => { const st = lstatSync(p); if (st.isSymbolicLink()) return; if (st.isDirectory()) { chmodSync(p, 0o700); for (const e of readdirSync(p)) thaw(join(p, e)); } };
|
||||
t.after(async () => { await bus.close(); thaw(root); rmSync(root, { recursive: true, force: true }); });
|
||||
const b = bus.broker;
|
||||
const owner = b.bindConsole({ business: 'demo', human: 'jason', subject: SUBJECT });
|
||||
const human = b.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true });
|
||||
const tester = b.bindTester({ business: 'demo' });
|
||||
const call = async (verb, args = {}, cap = owner) => b.request(cap, { verb, args });
|
||||
const file = () => readFileSync(join(root, 'businesses/demo.json'), 'utf8');
|
||||
let n = 0;
|
||||
const install = (pack) => {
|
||||
const src = join(root, `src-${n++}`);
|
||||
mkdirSync(join(src, 'starter-pack'), { recursive: true });
|
||||
writeFileSync(join(src, 'starter-pack', 'index.mjs'), `export const interfaceVersion = 1;\nexport function starterPack() { return ${JSON.stringify(pack)}; }\n`);
|
||||
const manifest = { name: pack.id, version: '1.0.0', kinds: ['starter-pack'], interfaceVersions: { 'starter-pack': 1 }, sha256: '0'.repeat(64),
|
||||
source: { path: 'fixture', version: '1.0.0' }, signature: null, tools: [], actions: [], services: [], roleTemplates: [] };
|
||||
writeFileSync(join(src, 'plugin.json'), JSON.stringify(manifest));
|
||||
manifest.sha256 = pluginHash(src);
|
||||
writeFileSync(join(src, 'plugin.json'), JSON.stringify(manifest));
|
||||
installPlugin({ dataRoot: data, source: src, expectedHash: manifest.sha256 });
|
||||
};
|
||||
return { b, root, rolesDir, owner, human, tester, call, file, install };
|
||||
}
|
||||
|
||||
// The A4 broker with the real hire service, so the chief's raise and the Console start reach it.
|
||||
function hires(t) {
|
||||
const root = mkdtempSync(join(tmpdir(), 'sohire-')), rolesDir = rolesCopy(root);
|
||||
writeJson(join(root, 'businesses/demo.json'), { ...businessDoc(root, 'demo'), plugins: { harness: ['pi'] } });
|
||||
const storeRoot = join(root, 'data'); mkdirSync(storeRoot, { mode: 0o700 });
|
||||
const writer = organizationWriter({ dir: root, rolesDir }), store = new Store(storeRoot);
|
||||
const service = hireDecisions({ writer, rolesDir, dataRoot: storeRoot, configDir: root, assertClean: () => {} });
|
||||
const loaded = () => { const doc = loadBusiness('demo', { dir: root, rolesDir }); return { ...doc, roles: Object.fromEntries(Object.entries(doc.roles).map(([k, e]) => [k, { ...doc.definitions[e.definition], ...e }])) }; };
|
||||
const b = new Broker({ store, businesses: { demo: loaded() }, hires: service });
|
||||
t.after(() => { store.close(); rmSync(root, { recursive: true, force: true }); });
|
||||
const owner = b.bindConsole({ business: 'demo', human: 'jason', subject: SUBJECT });
|
||||
const chief = b.bindLaunch({ business: 'demo', role: 'chief', run: 'chief-run', harness: 'pi' });
|
||||
b.request(chief, { verb: 'role.claim' });
|
||||
const call = (cap, verb, args = {}) => b.request(cap, { verb, args });
|
||||
const triage = { template: 'triage', sha256: templateHash(rolesDir, 'triage') };
|
||||
const hire = (extra = {}) => ({ op: 'hire', level: 'org', name: 'sorter', role: triage, route: ROUTE, reason: 'Sort the inbox', ...extra });
|
||||
const decisions = () => store.get('SELECT count(*) n FROM decisions').n;
|
||||
return { owner, chief, call, hire, decisions };
|
||||
}
|
||||
|
||||
const refuses = async (promise) => assert.rejects(Promise.resolve().then(() => promise), (e) => e?.code === CODE);
|
||||
|
||||
test('pack preview refuses an installed pack that defines triage', async (t) => {
|
||||
const h = await runtime(t);
|
||||
const pack = { ...codingPack(), id: 'sorting', label: 'Sorting' };
|
||||
pack.definitions = { ...pack.definitions, triage: { template: 'triage', sha256: templateHash(h.rolesDir, 'triage') } };
|
||||
h.install(pack);
|
||||
const before = h.file();
|
||||
await refuses(h.call('pack.preview.console', { pack: 'sorting' }));
|
||||
assert.equal(h.file(), before);
|
||||
});
|
||||
|
||||
test('pack apply refuses an installed pack that defines triage', async (t) => {
|
||||
const h = await runtime(t);
|
||||
const pack = { ...codingPack(), id: 'sorting', label: 'Sorting' };
|
||||
pack.definitions = { ...pack.definitions, triage: { template: 'triage', sha256: templateHash(h.rolesDir, 'triage') } };
|
||||
h.install(pack);
|
||||
const before = h.file();
|
||||
await refuses(h.call('pack.apply.console', { pack: 'sorting', digest: 'a'.repeat(64) }));
|
||||
assert.equal(h.file(), before);
|
||||
});
|
||||
|
||||
test('instances.set add refuses triage for the human', async (t) => {
|
||||
const h = await runtime(t);
|
||||
const { revision } = await h.call('instances', {}, h.human);
|
||||
const before = h.file();
|
||||
await refuses(h.call('instances.set', { revision, instance: 'sorter', op: 'add', definition: 'triage' }, h.human));
|
||||
assert.equal(h.file(), before);
|
||||
});
|
||||
|
||||
test('instances.set add refuses triage for the tester', async (t) => {
|
||||
const h = await runtime(t);
|
||||
const { revision } = await h.call('instances', {}, h.human);
|
||||
const before = h.file();
|
||||
await refuses(h.call('instances.set', { revision, instance: 'sorter', op: 'add', definition: 'triage' }, h.tester));
|
||||
assert.equal(h.file(), before);
|
||||
});
|
||||
|
||||
test('the instances read offers no triage add', async (t) => {
|
||||
const h = await runtime(t);
|
||||
const view = await h.call('instances', {}, h.human);
|
||||
assert.equal(Object.hasOwn(view.definitions, 'triage'), false);
|
||||
});
|
||||
|
||||
test('the Console hire start refuses a triage template', async (t) => {
|
||||
const f = hires(t);
|
||||
await refuses(f.call(f.owner, 'hire.start.console', f.hire()));
|
||||
assert.equal(f.decisions(), 0);
|
||||
});
|
||||
|
||||
test('the chief hire.raise refuses a triage template at org, project and root level', async (t) => {
|
||||
const f = hires(t);
|
||||
await refuses(f.call(f.chief, 'hire.raise', f.hire()));
|
||||
await refuses(f.call(f.chief, 'hire.raise', f.hire({ level: 'project', project: 'stack' })));
|
||||
await refuses(f.call(f.chief, 'hire.raise', f.hire({ level: 'root' })));
|
||||
assert.equal(f.decisions(), 0);
|
||||
});
|
||||
|
||||
test('the chief decision.raise naming role.hire or role.change refuses a triage template', async (t) => {
|
||||
const f = hires(t);
|
||||
await refuses(f.call(f.chief, 'decision.raise', { action: 'role.hire', hire: f.hire() }));
|
||||
await refuses(f.call(f.chief, 'decision.raise', { action: 'role.change', hire: f.hire({ op: 'change', name: 'coder' }) }));
|
||||
assert.equal(f.decisions(), 0);
|
||||
});
|
||||
|
||||
test('the Console hire template list omits triage and keeps the rest', async (t) => {
|
||||
const f = hires(t);
|
||||
const names = (await f.call(f.owner, 'hire.templates.console')).templates.map((x) => x.name);
|
||||
assert.ok(!names.includes('triage'));
|
||||
assert.ok(names.includes('coder') && names.includes('reviewer'));
|
||||
});
|
||||
|
||||
// The guard: a shipped pack previews and applies as before, and an installed pack with no triage loads.
|
||||
test('the shipped coding pack and an installed pack without triage preview as before', async (t) => {
|
||||
const h = await runtime(t);
|
||||
const preview = await h.call('pack.preview.console', { pack: 'coding' });
|
||||
assert.match(preview.digest, /^[a-f0-9]{64}$/);
|
||||
h.install({ ...codingPack(), id: 'plain', label: 'Plain' });
|
||||
const plain = await h.call('pack.preview.console', { pack: 'plain' });
|
||||
assert.match(plain.digest, /^[a-f0-9]{64}$/);
|
||||
const out = await h.call('pack.apply.console', { pack: 'coding', digest: preview.digest });
|
||||
assert.deepEqual(out.hires.map((x) => [x.name, x.state]), [['pm-1', 'hired'], ['coder-1', 'hired'], ['reviewer-1', 'hired']]);
|
||||
});
|
||||
@@ -1,109 +0,0 @@
|
||||
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 { installedSystemTypes } from '../../plugins/src/system-types.mjs';
|
||||
|
||||
test('project selections require enabled types, retain inactive selections, and only the owner writes', t => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'sys-'));
|
||||
const store = new Store(root); t.after(() => { store.close(); rmSync(root, { recursive: true, force: true }); });
|
||||
const business = { id: 'demo', human: 'jason', arbiters: { technical: 'chief', delivery: 'chief' }, roles: { chief: { definition: 'chief-of-staff', authority: { withinRole: [], crossRole: [] } } }, projects: {}, plugins: { 'system-type': ['coding'] }, vars: { 'bus.tester': true } };
|
||||
const broker = new Broker({ store, businesses: { demo: business } });
|
||||
const owner = broker.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true });
|
||||
const tester = broker.bindTester({ business: 'demo' });
|
||||
const agent = broker.bindLaunch({ business: 'demo', role: 'chief', run: 'chief-run', harness: 'pi' });
|
||||
const call = (verb, args = {}, cap = owner) => broker.request(cap, { verb, args });
|
||||
const project = call('project.create', { name: 'example' }).id;
|
||||
assert.deepEqual(call('project.system-types', { project }), { project, selected: [], active: [], inactive: [] });
|
||||
assert.throws(() => call('project.system-types.set', { project, systemTypes: ['montage'] }), /system-type-not-enabled/);
|
||||
assert.throws(() => call('project.system-types.set', { project, systemTypes: ['coding'] }, tester), /tester-refused/);
|
||||
assert.throws(() => call('project.system-types.set', { project, systemTypes: ['coding'] }, agent), /human-required/);
|
||||
assert.throws(() => call('project.system-types.set', { project, systemTypes: ['coding', 'coding'] }), /invalid-request/);
|
||||
call('project.system-types.set', { project, systemTypes: ['coding'] });
|
||||
assert.deepEqual(call('project.system-types', { project }).active, ['coding']);
|
||||
broker.reloadBusiness('demo', { ...business, plugins: { 'system-type': [] } });
|
||||
assert.deepEqual(call('project.system-types', { project }), { project, selected: ['coding'], active: [], inactive: ['coding'] });
|
||||
assert.deepEqual(store.all('SELECT by FROM project_system_types').map(r => r.by), ['jason']);
|
||||
assert.throws(() => store.run("UPDATE project_system_types SET types='[]'"), /append-only/);
|
||||
assert.throws(() => store.run('DELETE FROM project_system_types'), /append-only/);
|
||||
assert.throws(() => store.run("INSERT INTO project_system_types(at,business,project,types,by) VALUES(?,?,?,?,?)", new Date().toISOString(), 'other', project, '[]', 'jason'), /belongs to its project/);
|
||||
});
|
||||
|
||||
test('console owner can read system types but cannot write project selections', async t => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'sys-'));
|
||||
const store = new Store(root); t.after(() => { store.close(); rmSync(root, { recursive: true, force: true }); });
|
||||
const business = { id: 'demo', human: 'jason', arbiters: { technical: 'chief', delivery: 'chief' }, roles: { chief: { definition: 'chief-of-staff', authority: { withinRole: [], crossRole: [] } } }, projects: {}, plugins: { 'system-type': ['coding'] }, vars: { 'bus.tester': true } };
|
||||
let discoveries = 0, enabled = ['coding'];
|
||||
const broker = new Broker({ store, businesses: { demo: business }, organization: (_id, verb) => { if (verb === 'system-types.current') return enabled; if (verb === 'system-types.installed') { discoveries++; return installedSystemTypes(); } } });
|
||||
const owner = broker.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true });
|
||||
const consoleOwner = broker.bindConsole({ business: 'demo', human: 'jason', subject: { provider: 'test', iss: 'test', sub: 'owner' } });
|
||||
const tester = broker.bindTester({ business: 'demo' });
|
||||
assert.throws(() => broker.request(tester, { verb: 'plugins.set', args: { revision: 'a'.repeat(64), plugins: { 'system-type': ['coding'] } } }), /human-required/);
|
||||
const project = broker.request(owner, { verb: 'project.create', args: { name: 'example' } }).id;
|
||||
const result = await broker.request(consoleOwner, { verb: 'system-types.console', args: { project } });
|
||||
assert.deepEqual(result.enabled, ['coding']);
|
||||
assert.equal(result.installed.length, 5);
|
||||
assert.equal(discoveries, 1);
|
||||
broker.request(owner, { verb: 'project.system-types.set', args: { project, systemTypes: ['coding'] } });
|
||||
enabled = [];
|
||||
assert.deepEqual(broker.request(owner, { verb: 'project.system-types', args: { project } }).inactive, ['coding']);
|
||||
assert.throws(() => broker.request(owner, { verb: 'project.system-types.set', args: { project, systemTypes: ['coding'] } }), /system-type-not-enabled/);
|
||||
assert.deepEqual(result.project, { project, selected: [], active: [], inactive: [] });
|
||||
assert.throws(() => broker.request(consoleOwner, { verb: 'project.system-types.set', args: { project, systemTypes: ['coding'] } }), /human-required/);
|
||||
});
|
||||
|
||||
test('3t store migrates offline without altering existing project rows', async t => {
|
||||
const { DatabaseSync } = await import('node:sqlite');
|
||||
const { readFileSync, mkdirSync, chmodSync } = await import('node:fs');
|
||||
const { schemaDigest } = await import('../src/store.mjs');
|
||||
const root = mkdtempSync(join(tmpdir(), 'sys-migration-'));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
mkdirSync(join(root, 'bus'), { mode: 0o700 });
|
||||
const dbpath = join(root, 'bus/bus.sqlite');
|
||||
const db = new DatabaseSync(dbpath);
|
||||
const ddl = readFileSync(new URL('../schema.sql', import.meta.url), 'utf8');
|
||||
const step = readFileSync(new URL('../src/migrations/3t-3u.sql', import.meta.url), 'utf8');
|
||||
assert.equal(ddl.split(step).length, 2);
|
||||
// 3u-3v (U4a) adds store_tasks after this step; a 3t store has neither.
|
||||
const later = readFileSync(new URL('../src/migrations/3u-3v.sql', import.meta.url), 'utf8');
|
||||
db.exec(ddl.replace(step, '').replace(later, ''));
|
||||
db.prepare('INSERT INTO meta VALUES(?,?)').run('schema_version', '3t');
|
||||
db.prepare('INSERT INTO meta VALUES(?,?)').run('schema_digest', schemaDigest(db));
|
||||
db.prepare('INSERT INTO meta VALUES(?,?)').run('comment_cursor_epoch', '2026-01-01T00:00:00.000Z');
|
||||
db.prepare('INSERT INTO projects(id,at,business,name,repo,created_by) VALUES(?,?,?,?,?,?)').run('old', '2026-01-01T00:00:00.000Z', 'demo', 'old', null, 'jason');
|
||||
db.close(); chmodSync(dbpath, 0o600);
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
const migrated = new Store(root, { migrateSchema: true }); t.after(() => migrated.close());
|
||||
assert.equal(migrated.get('SELECT name FROM projects WHERE id=?', 'old').name, 'old');
|
||||
assert.equal(migrated.get('SELECT count(*) AS n FROM project_system_types').n, 0);
|
||||
assert.equal(migrated.get("SELECT value FROM meta WHERE key='schema_version'").value, '3v');
|
||||
});
|
||||
|
||||
test('runtime reads the current organization file for project selections and console discovery', async t => {
|
||||
const { mkdirSync } = await import('node:fs');
|
||||
const { startBroker } = await import('../src/runtime.mjs');
|
||||
const { businessDoc, rolesCopy, systemFor, writeJson } = await import('../../organization/tests/helpers.mjs');
|
||||
const root = mkdtempSync(join(tmpdir(), 'sys-runtime-'));
|
||||
const rolesDir = rolesCopy(root), doc = businessDoc(root, 'demo');
|
||||
doc.plugins = { 'system-type': ['coding'] };
|
||||
writeJson(join(root, 'businesses/demo.json'), doc);
|
||||
mkdirSync(join(root, 'data'), { mode: 0o700 });
|
||||
const business = { id: 'demo', human: 'jason', arbiters: { technical: 'chief', delivery: 'chief' }, roles: {chief: { definition: 'chief-of-staff', authority: { withinRole: ['decision.resolve.technical', 'decision.resolve.delivery'], crossRole: [] } }, coder: { authority: { withinRole: [], crossRole: [] } } } };
|
||||
const bus = await startBroker({ dataRoot: join(root, 'data'), businesses: { demo: business }, organization: { dir: root, rolesDir, system: systemFor(root) } });
|
||||
t.after(async () => { await bus.close(); rmSync(root, { recursive: true, force: true }); });
|
||||
const human = bus.broker.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true });
|
||||
const consoleOwner = bus.broker.bindConsole({ business: 'demo', human: 'jason', subject: { provider: 'test', iss: 'test', sub: 'owner' } });
|
||||
const call = (verb, args = {}, cap = human) => bus.broker.request(cap, { verb, args });
|
||||
const project = call('project.create', { name: 'example' }).id;
|
||||
call('project.system-types.set', { project, systemTypes: ['coding'] });
|
||||
const view = await call('system-types.console', { project }, consoleOwner);
|
||||
assert.deepEqual(view.enabled, ['coding']);
|
||||
assert.deepEqual(view.project.active, ['coding']);
|
||||
assert.equal(view.installed.length, 5);
|
||||
const plugins = call('plugins');
|
||||
call('plugins.set', { revision: plugins.revision, plugins: { 'system-type': [] } });
|
||||
assert.deepEqual(call('project.system-types', { project }).inactive, ['coding']);
|
||||
});
|
||||
@@ -402,7 +402,8 @@ test('REQ-TASK-1 a 3u store migrates to 3v: store_tasks is new and empty, every
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
mkdirSync(join(root, 'bus'), { mode: 0o700 });
|
||||
const path = join(root, 'bus/bus.sqlite'), db = new DatabaseSync(path);
|
||||
db.exec(currentDDL.replace(stepSQL, ''));
|
||||
// SP9 (#1873): a 3u store still has what 3t-3u created; 3v-3w drops it on the way to the fresh schema.
|
||||
db.exec(currentDDL.replace(stepSQL, '') + readFileSync(here('../src/migrations/3t-3u.sql'), 'utf8'));
|
||||
db.prepare('INSERT INTO meta VALUES (?,?)').run('schema_version', '3u');
|
||||
db.prepare('INSERT INTO meta VALUES (?,?)').run('schema_digest', schemaDigest(db));
|
||||
db.prepare('INSERT INTO meta VALUES (?,?)').run('comment_cursor_epoch', '2026-11-09T00:00:00.000Z');
|
||||
@@ -414,7 +415,7 @@ test('REQ-TASK-1 a 3u store migrates to 3v: store_tasks is new and empty, every
|
||||
assert.deepEqual(master(path), was, 'the refused open changed nothing');
|
||||
const store = new Store(root, { migrateSchema: true });
|
||||
t.after(() => store.close());
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.equal(store.get('SELECT id FROM events').id, 'preserved');
|
||||
assert.deepEqual(store.all('SELECT * FROM store_tasks'), []);
|
||||
const freshRoot = mkdtempSync(join(tmpdir(), 'ts-fresh-'));
|
||||
|
||||
@@ -154,7 +154,7 @@ test('SP8 argument checks: a second save, a .. name, an unknown key, preview wit
|
||||
const { call, saved } = await harness(t);
|
||||
const { preview } = await save(call, 'demo-shape');
|
||||
const first = readFileSync(saved('demo-shape'));
|
||||
await assert.rejects(call('template.save.console', { name: 'demo-shape', digest: preview.digest }), (e) => e.code === 'invalid-request' && e.reason === 'a template of this name is already saved');
|
||||
await assert.rejects(call('template.save.console', { name: 'demo-shape', digest: preview.digest }), (e) => e.code === 'template-exists' && e.reason === 'a template of this name is already saved; save under another name');
|
||||
assert.deepEqual(readFileSync(saved('demo-shape')), first);
|
||||
for (const name of ['..', '../x', 'a/b']) await assert.rejects(call('template.save.console', { name, preview: true }), { code: 'invalid-request' });
|
||||
for (const args of [{ name: 'x', preview: true, account: 'alex' }, { name: 'x', preview: true, digest: preview.digest }, { name: 'x' }, { preview: true }, { name: 'x', preview: false }])
|
||||
|
||||
@@ -49,7 +49,7 @@ async function database3d(t) {
|
||||
const source = readFileSync(here('../src/store.mjs'), 'utf8');
|
||||
const pinned = source
|
||||
.replace(/export const SCHEMA_SHA256 = '[a-f0-9]+';/, `export const SCHEMA_SHA256 = '${createHash('sha256').update(ddl3d).digest('hex')}';`)
|
||||
.replace("export const SCHEMA_VERSION = '3v';", "export const SCHEMA_VERSION = '3d';")
|
||||
.replace("export const SCHEMA_VERSION = '3w';", "export const SCHEMA_VERSION = '3d';")
|
||||
.replace(/\}, \{\n {2}from: '3d',[\s\S]*?\}\];\nconst timedTables/, '}];\nconst timedTables');
|
||||
assert.ok(!pinned.includes('3d-3e'), 'the 3d engine has no 3d→3e step');
|
||||
writeFileSync(join(moduleRoot, 'src/store.mjs'), pinned);
|
||||
@@ -101,7 +101,7 @@ test('REQ-THREAD-1 REQ-ORG-2: the 3d→3e migration adds the thread tables and l
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
const store = new Store(root, { migrateSchema: true });
|
||||
t.after(() => store.close());
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3v');
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3w');
|
||||
for (const table of ['projects', 'threads', 'thread_claims', 'message_threads', 'thread_opens'])
|
||||
assert.equal(store.get(`SELECT count(*) n FROM ${table}`).n, 0, table);
|
||||
// Parked: the undelivered ones are counted per business and role, and none is changed or given a thread.
|
||||
@@ -161,5 +161,5 @@ test('REQ-THREAD-1: the offline command prints the kept-message counts before th
|
||||
const command = new URL('../src/migrate-schema.mjs', import.meta.url).pathname;
|
||||
const migrated = spawnSync(process.execPath, [command, root], { encoding: 'utf8' });
|
||||
assert.equal(migrated.status, 0, migrated.stderr);
|
||||
assert.equal(migrated.stdout, [...REPORT, 'bus schema 3v ready', ''].join('\n'));
|
||||
assert.equal(migrated.stdout, [...REPORT, 'bus schema 3w ready', ''].join('\n'));
|
||||
});
|
||||
@@ -403,12 +403,12 @@ test('a 3l store migrates to 3m: thread_shares is new and empty, and every other
|
||||
const before = tables(path);
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
new Store(root, { migrateSchema: true }).close();
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
const after = tables(path);
|
||||
assert.deepEqual(after.thread_shares, []);
|
||||
delete after.thread_shares;
|
||||
// Row 271 (#1776): the 3m→3n step's session_ops and message_cancels, new and empty too.
|
||||
for (const name of ['session_ops', 'message_cancels', 'request_events', 'request_effects', 'request_snapshots', 'request_snapshot_events', 'request_project_events', 'project_archives', 'project_system_types', 'store_tasks']) {
|
||||
for (const name of ['session_ops', 'message_cancels', 'request_events', 'request_effects', 'request_snapshots', 'request_snapshot_events', 'request_project_events', 'project_archives', 'store_tasks']) {
|
||||
assert.deepEqual(after[name], [], name);
|
||||
delete after[name];
|
||||
}
|
||||
@@ -439,7 +439,7 @@ async function engine3l(root) {
|
||||
const source = readFileSync(here('../src/store.mjs'), 'utf8');
|
||||
const edited = source
|
||||
.replace(/export const SCHEMA_SHA256 = '[a-f0-9]+';/, `export const SCHEMA_SHA256 = '${createHash('sha256').update(ddl3l).digest('hex')}';`)
|
||||
.replace("export const SCHEMA_VERSION = '3v';", "export const SCHEMA_VERSION = '3l';")
|
||||
.replace("export const SCHEMA_VERSION = '3w';", "export const SCHEMA_VERSION = '3l';")
|
||||
.replace(/\}, \{\n {2}\/\/ Row 206 \(193b2[\s\S]*?\}\];\nconst timedTables/, '}];\nconst timedTables');
|
||||
assert.ok(edited.includes("export const SCHEMA_VERSION = '3l';") && edited.includes('3k-3l') && !edited.includes('3l-3m'), 'the 3l engine has no 3l→3m step');
|
||||
writeFileSync(join(moduleRoot, 'src/store.mjs'), edited);
|
||||
@@ -456,7 +456,7 @@ test('the 3l engine refuses a 3m store, migrating or not, and leaves it as it wa
|
||||
const Store3l = await engine3l(root);
|
||||
assert.throws(() => new Store3l(root), /schema-mismatch/);
|
||||
assert.throws(() => new Store3l(root, { migrateSchema: true }), /schema-mismatch/);
|
||||
assert.equal(version(path), '3v');
|
||||
assert.equal(version(path), '3w');
|
||||
assert.deepEqual(master(path), was);
|
||||
assert.deepEqual(tables(path), before);
|
||||
// The same engine opens a fresh 3l store, so the refusal is the version's and not a broken copy.
|
||||
|
||||
@@ -121,3 +121,24 @@ test('committed mutation followed by dropped reply reports unknown and is never
|
||||
assert.equal(calls, 1);
|
||||
assert.equal(store.get('SELECT count(*) n FROM messages').n, 1);
|
||||
});
|
||||
|
||||
// E2E6 fix 6: a connect that fails before the request is written is marked notSent; the code stays
|
||||
// outcome-unknown for every caller. A request that left and got no answer is not marked.
|
||||
test('E2E6 a failed connect is outcome-unknown marked notSent; a dropped answer is not marked', async (t) => {
|
||||
const { createServer } = await import('node:net');
|
||||
const { writeFileSync } = await import('node:fs');
|
||||
const { NOT_SENT_EXIT } = await import('../src/client.mjs');
|
||||
assert.equal(NOT_SENT_EXIT, 5);
|
||||
const dir = mkdtempSync(join(tmpdir(), 'e2e6-'));
|
||||
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
||||
const plain = join(dir, 'plain');
|
||||
writeFileSync(plain, '');
|
||||
for (const path of [join(dir, 'missing.sock'), plain, join(plain, 'below')]) {
|
||||
await assert.rejects(new Client({ path, cap: 'x' }).call('inbox', {}), (e) => e.code === 'outcome-unknown' && e.notSent === true, path);
|
||||
}
|
||||
const sock = join(dir, 'drop.sock');
|
||||
const server = createServer((c) => c.once('data', () => c.destroy()));
|
||||
await new Promise((r) => server.listen(sock, r));
|
||||
t.after(() => server.close());
|
||||
await assert.rejects(new Client({ path: sock, cap: 'x' }).call('inbox', {}), (e) => e.code === 'outcome-unknown' && e.notSent === undefined);
|
||||
});
|
||||
@@ -68,7 +68,7 @@ test('REQ-LIMIT-4 3g copy migrates through 3h, 3i, 3j and 3k to 3l preserving ev
|
||||
assert.throws(() => new Store(root), /schema-mismatch/);
|
||||
const store = new Store(root, { migrateSchema: true });
|
||||
try {
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3v');
|
||||
assert.equal(store.get("SELECT value FROM meta WHERE key='schema_version'").value, '3w');
|
||||
assert.deepEqual({ ...store.get('SELECT to_name FROM messages') }, { to_name: null });
|
||||
assert.equal(store.get('SELECT count(*) AS n FROM usage_records').n, 0);
|
||||
assert.equal(store.get('SELECT name FROM instance_names').name, 'Builder');
|
||||
|
||||
+114
-9
@@ -1363,6 +1363,23 @@ message, an answer that never came exits 1, an unknown template exits 2. All of
|
||||
these verbs, reads included, refuse inside an agent run (exit 3) after their
|
||||
usage checks (exit 4) and before any config is read.
|
||||
|
||||
Starter pack hires (ruling 2026-11-14, #1873): `mosaic org pack apply ID PACK
|
||||
--digest D [--project P]` is the owner's hire decision. After the pack commits,
|
||||
the same command hires each proposed agent through the bus's hire-decisions
|
||||
path (`pack.apply` as the organization's human) and the receipt adds `hires`,
|
||||
one `{name, state, decision | code}` per proposal: `hired`, `exists` (an
|
||||
instance by that name is there), `open` (a hire decision already names it),
|
||||
`awaiting-owner` or `refused` with the hire's code. The owner's apply approves
|
||||
the flagged and credential lines; a credential line is approved, not bound, so
|
||||
the agent's launch is refused `credential-unbound` until its services are
|
||||
bound. `mosaic org pack hire ID PACK [--project P]` (`pack.hire`) runs the same
|
||||
loop on a pack already applied, for the proposals an earlier apply left open,
|
||||
and hires none twice; a pack with no packs entry is refused `pack-not-applied`
|
||||
with the hint to preview and apply it first. A proposal is refused
|
||||
`pack-hire-route-missing` when neither the chief of staff nor the
|
||||
organization's assistant has a harness and model to give it; the chief's route
|
||||
wins when both have one. Like the other pack words, both refuse inside an agent run (exit 3).
|
||||
|
||||
`mosaic tasks create|edit|archive` are the task board's three writes. The
|
||||
arguments pass the board's own check, then go to the bus as the person
|
||||
(`tasks.create`, `tasks.edit`, `tasks.archive`), so the bus runs its human,
|
||||
@@ -1370,15 +1387,6 @@ field, digest and archive checks. Edit and archive need the task's digest from
|
||||
`mosaic tasks --json` as `--expect`; a stale one is refused `task-conflict`
|
||||
(exit 2) and nothing is written. They refuse inside an agent run.
|
||||
|
||||
System types are installed plug-ins. `mosaic org system-types installed` prints
|
||||
module metadata; `mosaic org system-types enabled ID` prints an organization's enabled
|
||||
ids. The owner changes the enabled list through the existing organization file
|
||||
update or `mosaic plugins set`. `mosaic project system-types PROJECT --org ID`
|
||||
shows selected, active and inactive ids. The owner replaces the selection with
|
||||
`mosaic project system-types-set PROJECT --types coding,montage --org ID`; an
|
||||
empty `--types ''` clears it. Disabled selections stay recorded but become
|
||||
inactive. Project settings changes are append-only and require human proof.
|
||||
|
||||
## Accounts
|
||||
|
||||
`mosaic accounts` administers the instance-level accounts store locally, as the
|
||||
@@ -1417,3 +1425,100 @@ installer writes `<dataRoot>/.deployed` as mode 0444 naming the instance.
|
||||
`webui-service.sh` refuses accounts and deployed instances because its user
|
||||
manager runs under a human or development seat uid. The receipt uid identifies
|
||||
the invoking process; it does not attribute a human or resist tampering by that uid.
|
||||
|
||||
## Triage route (#1873, held for Jason's ruling)
|
||||
|
||||
`mosaic triage route show` prints the Triage route the instance owner set, or
|
||||
`triage route: not set` (exit 0). `mosaic triage route set --model KEY
|
||||
--harness NAME --cap TOKENS --time-zone ZONE [--revision N]` writes it. Both
|
||||
refuse inside an agent run before anything is read (exit 3).
|
||||
|
||||
The file is `<dataRoot>/triage/route.json`
|
||||
(packages/webui/src/triage-route-store.mjs): a catalogue model key, a harness
|
||||
name and a daily cap leaf `{limit, since, reset, timeZone}`. It holds no env
|
||||
value and no key. The day resets at 00:00 in the zone given, which has no
|
||||
default; an unknown zone refuses. The first cap counts from the time it is
|
||||
set; a later change keeps that `since`, as an organization's token limits do,
|
||||
so lowering the cap never drops tokens already spent. The directory is 0700 and the file 0600,
|
||||
owned by the running user; a link, a non-file, a wrong mode or owner, or an
|
||||
unknown field refuses (exit 3). A write is compare-and-set on `revision`
|
||||
(`--revision 0`: only when nothing is set), atomic, and appends one line with
|
||||
the old and new values to `route-receipts.jsonl`. A write that died leaves
|
||||
`route.lock`; the next write refuses and names it, and you remove it by hand.
|
||||
If the route changed but its receipt line could not be written, the write
|
||||
refuses with `triage-route-unrecorded` (exit 3) and names the new revision.
|
||||
`set` checks the harness against packages/plugins/harness/; it does not check
|
||||
the model key against a catalogue yet.
|
||||
|
||||
The Console does not read this file: the Triage host keeps `route: null` until
|
||||
the wiring slice.
|
||||
|
||||
## Triage key (#1873)
|
||||
|
||||
`mosaic triage key issue|rotate|retire|status` manage Triage's own model
|
||||
proxy client key. Every verb refuses inside an agent run before anything is
|
||||
read (exit 3), and takes no options.
|
||||
|
||||
The key is `mst-<tag>-triage-<43 base64url>`, where `<tag>` is the first 12
|
||||
hex of sha256 of the config directory, the tag on the instance's own `msk-`
|
||||
sentinel. An org bus reconciles only its `mso-<tag>-<org>-key-` names and a
|
||||
no-org bus only its `msk-<tag>-` names, so neither removes it. The file is
|
||||
`<configDir>/secrets/triage/model`: `{version, key, keyId, issuedAt,
|
||||
rotateBy, retiring}`. The directory is 0700 and the file 0600, owned by the
|
||||
running user. A link, a non-file, a second hard link, a wrong mode or owner, a
|
||||
file over 64 KiB, or a record that does not match the shape refuses every verb
|
||||
with `triage-key-unreadable` (exit 3).
|
||||
|
||||
- `issue` adds one key and writes the file. It refuses `triage-key-issued`
|
||||
when a key is already issued; that is `rotate`.
|
||||
- `rotate` adds a new key and moves the old one to `retiring`, with a retire
|
||||
time of now plus `rotateGraceMinutes` from proxy.json, where the bus reads
|
||||
it (default 120). `rotateBy` is 30 days on, as for an org key. An old key
|
||||
the proxy no longer holds is dropped at once.
|
||||
- `retire` removes retiring keys whose grace has passed or that the proxy no
|
||||
longer holds. It changes nothing before then.
|
||||
|
||||
Nothing runs on a timer. The retire time is the earliest a retiring key may
|
||||
go; the key stays live in the proxy until someone runs `retire` (or a later
|
||||
`rotate` or `issue`) after it. `rotateBy` works the same way: `status` marks
|
||||
it due, and only `rotate` replaces the key.
|
||||
- `status` prints whether a key is issued, its key id, its age, its rotate-by
|
||||
day, each retiring key, what the proxy list holds, a set fence, any key in
|
||||
the Triage namespace the file does not hold, and the next command. It takes
|
||||
no lock and writes nothing.
|
||||
|
||||
`issue`, `rotate` and `retire` hold the instance proxy lock that org buses
|
||||
take (`<dataRoot>/proxy`). Each reads the list, refuses without this
|
||||
instance's sentinel (`triage-key-proxy-open`), reads it again and refuses if
|
||||
it moved (`triage-key-raced`), sets the fence, writes, reads back and clears
|
||||
the fence. The proxy changes first and the file second. Each run that
|
||||
changes something appends one line of key ids, never keys, to
|
||||
`<dataRoot>/proxy/mosaic-keys.receipts.jsonl`. That file is checked under the
|
||||
lock before anything changes; an unsafe one refuses
|
||||
`triage-key-receipts-unsafe`. A receipt line that still fails after the change
|
||||
refuses `triage-key-unrecorded`. No output, error or receipt holds a key.
|
||||
|
||||
The file is written to a 0600 temp file in the same directory, synced, renamed
|
||||
into place, and the directory is synced. A failed directory sync after the
|
||||
rename refuses `triage-key-unsynced`: the file is in place but may not survive
|
||||
a power loss. `proxy-lock-busy` means another proxy writer holds the lock; if
|
||||
none is running, `mosaic proxy fence status` shows the lock state.
|
||||
|
||||
After a crash:
|
||||
|
||||
- Killed after the proxy write and before the read-back: the fence stays set
|
||||
and every proxy writer on the instance refuses `proxy-uncertain`. `status`
|
||||
shows the fence. Restart the proxy, run `mosaic proxy fence clear
|
||||
--proxy-restarted`, then run the verb again.
|
||||
- Killed after the read-back and before the file write: the proxy holds a key
|
||||
the file does not. `status` names it; the next `issue`, `rotate` or `retire`
|
||||
removes it. A file that could not be written refuses
|
||||
`triage-key-unwritten` and says to run the verb again.
|
||||
- Killed after the temp file is written and before its rename: a
|
||||
`.model.<pid>.<hex>.tmp` file that may hold a key stays in the triage
|
||||
directory. `status` counts it; the next `issue`, `rotate` or `retire`
|
||||
removes it under the lock.
|
||||
- A `retire` killed after the proxy write leaves a retiring key the proxy no
|
||||
longer holds. `status` marks it; the next `retire` drops it from the file.
|
||||
|
||||
Nothing gives the key to the Triage host yet; that is the wiring slice.
|
||||
@@ -75,7 +75,8 @@ export function readAccounting({ dataRoot,business,start,end }) {
|
||||
try {
|
||||
db.exec('BEGIN');
|
||||
// U4a (#1873) 3u-3v adds only store_tasks, which accounting never reads, so 3v joins the closed list.
|
||||
if (!['3s','3t','3u','3v'].includes(db.prepare("SELECT value FROM meta WHERE key='schema_version'").get()?.value)) fail('test-store-schema-refused');
|
||||
// SP9 (#1873) 3v-3w drops only the table 3t-3u added, which accounting never reads, so 3w joins too.
|
||||
if (!['3s','3t','3u','3v','3w'].includes(db.prepare("SELECT value FROM meta WHERE key='schema_version'").get()?.value)) fail('test-store-schema-refused');
|
||||
const store = { all:(sql,...args) => db.prepare(sql).all(...args) };
|
||||
const records = turnRecords(store,business);
|
||||
const raw = store.all("SELECT * FROM usage_records WHERE business=? AND source<>'@proxy/cliproxy-queue' ORDER BY seq",business);
|
||||
|
||||
@@ -79,7 +79,7 @@ test('accounting reads a real store at the current bus schema version',t=>{
|
||||
const records=readAccounting({dataRoot:f.dataRoot,business:f.c.business,start:f.c.start,end:f.c.end});
|
||||
assert.equal(records.length,1);assert.equal(records[0].input,1);
|
||||
});
|
||||
for(const version of ['3s','3r','3v',null]) test(`accounting ${version==='3s'?'accepts':'refuses'} schema ${version??'missing'}`,t=>{
|
||||
for(const version of ['3s','3r','3x',null]) test(`accounting ${version==='3s'?'accepts':'refuses'} schema ${version??'missing'}`,t=>{
|
||||
const f=setup(t,100);
|
||||
// Only this disposable fixture is altered; the production meta table is append-only.
|
||||
f.store.run('DROP TRIGGER meta_no_update');f.store.run('DROP TRIGGER meta_no_delete');
|
||||
|
||||
@@ -56,6 +56,7 @@ import { ORG_CONFIG, runConfigCommand } from "../../organization/src/config-comm
|
||||
import { devCommand, DEV_USAGE, fixtureLaunchEnv, fixtureLauncherOptions } from "./dev-fixture.mjs";
|
||||
import { runCommand, RUN_USAGE } from "./run-evidence.mjs";
|
||||
import { tasksWriteCommand, TASKS_WRITE_OPS, TASKS_WRITE_USAGE } from "./tasks-write.mjs";
|
||||
import { triageCommand, TRIAGE_USAGE } from "./triage.mjs";
|
||||
|
||||
export const USAGE = `usage:
|
||||
${ACCOUNTS_USAGE}
|
||||
@@ -103,6 +104,7 @@ export const USAGE = `usage:
|
||||
mosaic console start [--dev-local-owner [--dev-insecure-bind ADDR --dev-allow-host NAME[,NAME...]]] [--detach] [--port auto|N]
|
||||
mosaic console stop|status
|
||||
mosaic console restart
|
||||
${TRIAGE_USAGE}
|
||||
${DEV_USAGE}
|
||||
${RUN_USAGE}`;
|
||||
|
||||
@@ -778,7 +780,7 @@ export async function main(argv, io = { env: process.env, stdin: process.stdin,
|
||||
if (["inbox", "decide", "tasks", "agents", "trail"].includes(verb)) return human(verb, rest, io, deps);
|
||||
if (verb === "project" && rest[0] === "north-star") return northStarCommand(rest.slice(1), io, (p) => callFor(p, io, deps));
|
||||
if (verb === "project" && rest[0] === "interview") return interviewCommand(rest.slice(1), io);
|
||||
if (verb === "project") return ["create", "list", "archive", "unarchive", "system-types", "system-types-set"].includes(rest[0]) ? projectBusCommand(rest, io, (p) => channelCallFor(p, io, deps)) : projectCommand(rest, io, deps, (p) => callFor(p, io, deps));
|
||||
if (verb === "project") return ["create", "list", "archive", "unarchive"].includes(rest[0]) ? projectBusCommand(rest, io, (p) => channelCallFor(p, io, deps)) : projectCommand(rest, io, deps, (p) => callFor(p, io, deps));
|
||||
if (verb === "threads") return threadsCommand(rest, io, (p) => channelCallFor(p, io, deps));
|
||||
if (verb === "session") return sessionCommand(rest, io, (p) => channelCallFor(p, io, deps));
|
||||
if (verb === "thread") return threadCommand(rest, io, (p) => channelCallFor(p, io, deps), formatMessage);
|
||||
@@ -818,6 +820,8 @@ export async function main(argv, io = { env: process.env, stdin: process.stdin,
|
||||
if (verb === "launches") return launches(rest, io, deps);
|
||||
if (verb === "bus") return bus(rest, io, deps);
|
||||
if (verb === "console") return consoleCommand(rest, io, deps);
|
||||
// triage-route-store (#1873): the owner's Triage route file, read and written as the person.
|
||||
if (verb === "triage") return triageCommand(rest, io, deps);
|
||||
if (verb === "dev") return devCommand(rest, io, { system: deps.system });
|
||||
if (verb === "run") return runCommand(rest, io, { system: deps.system, callFor: (p) => channelCallFor(p, io, deps) });
|
||||
if (verb === "-h" || verb === "--help") return io.stdout.write(`${USAGE}\n`);
|
||||
@@ -845,6 +849,7 @@ export async function run(argv, io = { env: process.env, stdin: process.stdin, s
|
||||
if (!(error instanceof CliError)) throw error;
|
||||
io.stderr.write(`mosaic: ${error.message}\n`);
|
||||
if (OTHER_TREE_CODES.has(error.code)) io.stderr.write(`mosaic: ${OTHER_TREE}\n`);
|
||||
if (typeof error.next === "string" && error.next !== "") io.stderr.write(`mosaic: next: ${error.next}\n`);
|
||||
return error.exitCode;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,11 +3,15 @@
|
||||
// input, a decision or option that doesn't exist); 3 refused (system or
|
||||
// business config problem, the broker or notifier refused, the human proof
|
||||
// refused, a host already running); 4 usage.
|
||||
//
|
||||
// E2E6: `next` is an optional next-step line. run() prints it after the message as
|
||||
// `mosaic: next: ...`; the message itself stays as callers (the Console among them) match it.
|
||||
export class CliError extends Error {
|
||||
constructor(message, exitCode = 2) {
|
||||
constructor(message, exitCode = 2, { next } = {}) {
|
||||
super(message);
|
||||
this.name = "CliError";
|
||||
this.exitCode = exitCode;
|
||||
if (typeof next === "string" && next !== "") this.next = next;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -76,6 +76,11 @@ const same = (a, b) => a?.pid === b?.pid && a?.startTime === b?.startTime && a?.
|
||||
// tried again, like one that goes before the check. `found` runs once the
|
||||
// lock is found and before it is read, `between` after the stale lock is
|
||||
// read; both are for the tests. Exported for the tests.
|
||||
// E2E6 fix 1: every stale-lock refusal names the verb that clears a host that died.
|
||||
export const recoverNext = (business) =>
|
||||
typeof business === "string" && /^[a-z0-9][a-z0-9._-]{0,63}$/.test(business)
|
||||
? `if the bus host died, clear it with mosaic bus recover ${business}; recover refuses while the host still runs`
|
||||
: "if the bus host died, clear it with mosaic bus recover <org>; recover refuses while the host still runs";
|
||||
export function claimHostLock(dataRoot, state, { found = () => {}, between = () => {}, refuseStale = false } = {}) {
|
||||
mkdirSync(hostDir(dataRoot), { recursive: true, mode: 0o700 });
|
||||
const file = hostLock(dataRoot);
|
||||
@@ -94,7 +99,8 @@ export function claimHostLock(dataRoot, state, { found = () => {}, between = ()
|
||||
const prior = readState(file, found);
|
||||
if (!prior) continue;
|
||||
if (prior.live) throw new CliError(`a bus host already runs for ${prior.business} (pid ${prior.pid})`, 3);
|
||||
if (refuseStale) throw new CliError("stale bus host lock", 3);
|
||||
// E2E6 fix 1: the message stays (the Console matches it); the next line names the clearing verb.
|
||||
if (refuseStale) throw new CliError("stale bus host lock", 3, { next: recoverNext(prior.business) });
|
||||
between();
|
||||
try {
|
||||
renameSync(file, aside);
|
||||
|
||||
@@ -8,7 +8,7 @@ import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { resolveOrg, withOrgLifecycle } from '../../organization/src/org-registry.mjs';
|
||||
import { orgPaths } from './config.mjs';
|
||||
import { cmdlineOf, hostFile, hostLock, hostStatus, readHostState, startTimeOf, stopHost } from './host.mjs';
|
||||
import { cmdlineOf, hostFile, hostLock, hostStatus, readHostState, recoverNext, startTimeOf, stopHost } from './host.mjs';
|
||||
import { CliError } from './errors.mjs';
|
||||
import { readBootStatus } from './boot-status.mjs';
|
||||
|
||||
@@ -27,20 +27,22 @@ async function target(ctx, id, allowDeleting = false) {
|
||||
return { ...org, paths: orgPaths(org.root) };
|
||||
}
|
||||
function checkedState(org) {
|
||||
// E2E6 fix 1: each refusal keeps its message and adds the recover line as its next step.
|
||||
const stale = message => { throw new CliError(message, 3, { next: recoverNext(org.id) }); };
|
||||
const s = hostStatus(org.root);
|
||||
let lock = null;
|
||||
try { lock = JSON.parse(readFileSync(hostLock(org.root), 'utf8')); }
|
||||
catch (e) { if (e.code !== 'ENOENT') fail('bus host lock is unreadable'); }
|
||||
if (lock && (!Number.isSafeInteger(lock.pid) || typeof lock.startTime !== 'string' || startTimeOf(lock.pid) !== lock.startTime)) fail('stale bus host lock');
|
||||
if (s.host && (!s.host.live || s.host.business !== org.id)) fail('stale or mismatched bus host state');
|
||||
catch (e) { if (e.code !== 'ENOENT') stale('bus host lock is unreadable'); }
|
||||
if (lock && (!Number.isSafeInteger(lock.pid) || typeof lock.startTime !== 'string' || startTimeOf(lock.pid) !== lock.startTime)) stale('stale bus host lock');
|
||||
if (s.host && (!s.host.live || s.host.business !== org.id)) stale('stale or mismatched bus host state');
|
||||
if (s.host) {
|
||||
const args = cmdlineOf(s.host.pid) ?? [], i = args.indexOf(CLI);
|
||||
if (i < 0 || args[i + 1] !== 'bus' || args[i + 2] !== 'start' || args[i + 3] !== org.id) fail('bus host identity mismatch');
|
||||
if (i < 0 || args[i + 1] !== 'bus' || args[i + 2] !== 'start' || args[i + 3] !== org.id) stale('bus host identity mismatch');
|
||||
}
|
||||
if (lock && (!s.host || lock.pid !== s.host.pid || lock.business !== org.id)) fail('bus host lock does not match host state');
|
||||
if (s.writerLock && !s.writerLock.live) fail('stale bus writer lock');
|
||||
if (!s.host && s.writerLock) fail('bus writer lock has no matching host');
|
||||
if (s.host && !lock) fail('bus host lock is missing');
|
||||
if (lock && (!s.host || lock.pid !== s.host.pid || lock.business !== org.id)) stale('bus host lock does not match host state');
|
||||
if (s.writerLock && !s.writerLock.live) stale('stale bus writer lock');
|
||||
if (!s.host && s.writerLock) stale('bus writer lock has no matching host');
|
||||
if (s.host && !lock) stale('bus host lock is missing');
|
||||
return s;
|
||||
}
|
||||
export function probeBusSocket(path, { signal, deadline } = {}) {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { randomBytes } from 'node:crypto';
|
||||
import { processState } from '../../seat/src/process-state.mjs';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { request as httpRequest } from 'node:http';
|
||||
import { constants, closeSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, rmSync, renameSync, writeFileSync, writeSync } from 'node:fs';
|
||||
import { constants, closeSync, fstatSync, ftruncateSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, rmSync, renameSync, writeFileSync, writeSync } from 'node:fs';
|
||||
import { basename, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { listOrgs, resolveOrg } from '../../organization/src/org-registry.mjs';
|
||||
@@ -60,14 +60,79 @@ function removeStale(ctx, s, warn) {
|
||||
warn(`mosaic: stale console state moved to ${aside}\n`);
|
||||
return true;
|
||||
}
|
||||
function takeLock(ctx) {
|
||||
// E2E6 fix 4: what a start.lock that already exists names. Null when it names no holder: unreadable,
|
||||
// empty (a holder between its open and its write), not a regular file of this user, or a bad pid or
|
||||
// start time. Such a lock is never cleared. A lock its holder marked released ({"released":true},
|
||||
// written through the holder's own descriptor) names no live holder and is cleared (f6c review P3-1).
|
||||
function lockHolder(path) {
|
||||
let fd;
|
||||
try { fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); }
|
||||
catch { return null; }
|
||||
try {
|
||||
const st = fstatSync(fd);
|
||||
if (!st.isFile() || st.uid !== process.getuid() || st.nlink !== 1 || st.size > 4096) return null;
|
||||
const data = JSON.parse(readFileSync(fd, 'utf8'));
|
||||
if (data?.released === true && Object.keys(data).length === 1) return { released: true, dev: st.dev, ino: st.ino };
|
||||
if (!Number.isSafeInteger(data?.pid) || data.pid <= 0 || typeof data.startTime !== 'string' || !/^\d+$/.test(data.startTime)) return null;
|
||||
return { pid: data.pid, startTime: data.startTime, dev: st.dev, ino: st.ino };
|
||||
} catch { return null; } finally { closeSync(fd); }
|
||||
}
|
||||
// True when the process the lock names (pid and start time) is gone. A /proc read that cannot settle
|
||||
// it counts as live, so an uncertain holder is never cleared.
|
||||
function holderGone(holder) {
|
||||
if (holder.released) return true;
|
||||
let p;
|
||||
try { p = processState(holder.pid); } catch { return false; }
|
||||
return !p.alive || p.startTime !== holder.startTime;
|
||||
}
|
||||
// Moves aside and removes the lock the holder check read, and only that file: a lock another start
|
||||
// took in between is put back and the clear refuses.
|
||||
function clearLock(path, holder) {
|
||||
const aside = `${path}.dead-${randomBytes(4).toString('hex')}`;
|
||||
try { renameSync(path, aside); } catch { fail('console start lock changed while it was being cleared; run the command again'); }
|
||||
const st = lstatSync(aside);
|
||||
if (st.dev !== holder.dev || st.ino !== holder.ino) {
|
||||
// Put back without replacing: if a third start took the path meanwhile, the aside stays for a human.
|
||||
let restored = false;
|
||||
try { linkSync(aside, path); restored = true; } catch { /* left aside */ }
|
||||
if (restored) rmSync(aside, { force: true });
|
||||
fail('console start lock changed while it was being cleared; run the command again');
|
||||
}
|
||||
rmSync(aside, { force: true });
|
||||
}
|
||||
function takeLock(ctx, warn = () => {}) {
|
||||
checkDir(ctx);
|
||||
const path = join(directory(ctx), 'start.lock');
|
||||
let fd; try { fd = openSync(path, 'wx', 0o600); } catch { fail('console start lock exists'); }
|
||||
let fd;
|
||||
for (let cleared = false; fd === undefined;) {
|
||||
try { fd = openSync(path, 'wx', 0o600); }
|
||||
catch (e) {
|
||||
if (e?.code !== 'EEXIST' || cleared) fail('console start lock exists');
|
||||
// E2E6 fix 4: a lock whose named holder (pid and start time) is gone is cleared once, and the
|
||||
// take tried again. A live holder, or a lock that names none, refuses and stays.
|
||||
const holder = lockHolder(path);
|
||||
if (!holder) fail('console start lock exists and names no holder; remove console/start.lock under the data root once no console start or stop runs');
|
||||
if (!holderGone(holder)) fail(`console start lock is held by process ${holder.pid}, which still runs; wait for its start or stop to finish`);
|
||||
clearLock(path, holder);
|
||||
warn(holder.released ? 'mosaic: cleared a console start lock its holder had released\n' : `mosaic: cleared a console start lock left by process ${holder.pid}, which is gone\n`);
|
||||
cleared = true;
|
||||
}
|
||||
}
|
||||
// D1: the lock names its holder, so a detached start that timed out can clear the lock of the
|
||||
// supervisor it killed (clearDeadLock) and no other.
|
||||
// supervisor it killed (clearDeadLock), and a later start or stop can clear it once that holder is gone.
|
||||
try { writeSync(fd, JSON.stringify({ pid: process.pid, startTime: startTimeOf(process.pid) })); } catch { /* an unnamed lock is only never cleared */ }
|
||||
return () => { closeSync(fd); rmSync(path, { force: true }); };
|
||||
// f6c review P3-1: the release marks its own file released, through its own descriptor, and removes
|
||||
// the path only while the path is still that file. A clear that moved the lock aside and puts it back
|
||||
// after this release puts back a released lock, which the next start or stop clears; and the release
|
||||
// never removes a lock another start took meanwhile.
|
||||
// A failed marker write (disk full) still removes the path: an empty lock would refuse forever.
|
||||
return () => {
|
||||
try {
|
||||
try { ftruncateSync(fd, 0); writeSync(fd, JSON.stringify({ released: true }), 0); } catch { /* the matched unlink below still runs */ }
|
||||
const own = fstatSync(fd), now = lstatSync(path);
|
||||
if (own.dev === now.dev && own.ino === now.ino) rmSync(path, { force: true });
|
||||
} catch { /* gone already, or moved aside by a clear */ } finally { closeSync(fd); }
|
||||
};
|
||||
}
|
||||
// Removes start.lock only when it names this exact process (pid and start time) and that process
|
||||
// is gone. A lock that is unreadable, unnamed or another holder's stays.
|
||||
@@ -242,7 +307,7 @@ export async function consoleStart(ctx, { devLocalOwner = false, detach = false,
|
||||
// re-check P1). A Restart Console relaunch goes through relaunch(), not here.
|
||||
refuseInsideAgent(process.env); if (ctx.env) refuseInsideAgent(ctx.env);
|
||||
if (detach && devLocalOwner) return detachedSupervisor(ctx, { port, bind, allowHosts, warn });
|
||||
const release = takeLock(ctx);
|
||||
const release = takeLock(ctx, warn);
|
||||
let run, args;
|
||||
try {
|
||||
const prior = state(ctx);
|
||||
@@ -266,7 +331,7 @@ export async function consoleStart(ctx, { devLocalOwner = false, detach = false,
|
||||
return result;
|
||||
}
|
||||
export async function consoleStop(ctx, { warn = s => process.stderr.write(s) } = {}) {
|
||||
const release = takeLock(ctx);
|
||||
const release = takeLock(ctx, warn);
|
||||
try {
|
||||
const s = state(ctx);
|
||||
if (!s || removeStale(ctx, s, warn)) return { stopped: false };
|
||||
|
||||
@@ -4,10 +4,12 @@
|
||||
// credential store, whose held-secret check every definition write needs (R1), and no other process
|
||||
// holds the tokens it looks for. Each write prints its receipt.
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { basename } from 'node:path';
|
||||
import { configDir } from '../../organization/src/organization-config.mjs';
|
||||
import { organizationWriter } from '../../organization/src/organization.mjs';
|
||||
import { definitionVerbs } from '../../organization/src/definition-verbs.mjs';
|
||||
import { checkDefinition } from '../../organization/src/definitions.mjs';
|
||||
import { ID_PATTERN } from '../../organization/src/vocabulary.mjs';
|
||||
import { rolesDir } from './config.mjs';
|
||||
import { CliError } from './errors.mjs';
|
||||
import { busExit, refuseInsideAgent } from './transport.mjs';
|
||||
@@ -59,6 +61,33 @@ function refusal(code, verb, name, rev, read) {
|
||||
return error;
|
||||
}
|
||||
|
||||
// E2E6 fix 2: a read or a write's file check that fails says so in one line: an unknown
|
||||
// organization, a missing definition or a bad file, by code. No stack trace, and no host path: a raw
|
||||
// filesystem error is named by its operation and code, and any absolute path left in a message is cut.
|
||||
const NAME_SHOWN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
||||
function missing(id, name) { return `${NAME_SHOWN.test(name ?? '') ? `definitions declares no ${name}` : 'definitions declares no definition by that name'}; list them with mosaic org definitions ${id} list`; }
|
||||
// f6c review P3-3: a path after ':' or a backtick is cut too.
|
||||
function pathFree(message) { return String(message).replace(/(^|[\s'"(=:`])\/[^\s'"),`]*/g, '$1<path>'); }
|
||||
export function definitionsFailure(e, id, name) {
|
||||
if (e instanceof CliError) return e;
|
||||
const coded = (code, text, exit = 3) => Object.assign(new CliError(`${code}: ${text}`, exit), { code });
|
||||
if (typeof e?.syscall === 'string' && typeof e.code === 'string' && /^E[A-Z0-9]+$/.test(e.code)) {
|
||||
// f6c review P3-2: only a missing organization file means no organization; another missing file
|
||||
// (the roles directory for `templates`, a role template) says which operation failed.
|
||||
if (e.code === 'ENOENT' && (typeof e.path !== 'string' || basename(e.path) === `${id}.json`)) return coded('unknown-organization', `this instance has no organization ${id}; list them with mosaic org list`);
|
||||
if (id === 'templates' || id === undefined) return coded('definitions-unreadable', `cannot ${e.syscall} a file the definitions command reads (${e.code})`);
|
||||
return coded('organization-unreadable', `cannot ${e.syscall} the file of organization ${id} (${e.code})`);
|
||||
}
|
||||
const message = typeof e?.message === 'string' ? e.message : '';
|
||||
if (/^definitions declares no /.test(message)) return coded('definition-missing', missing(id, name));
|
||||
if (typeof e?.code === 'string' && /^[a-z][a-z-]{0,63}$/.test(e.code)) {
|
||||
const text = e.code === 'definition-missing' ? missing(id, name) : pathFree(message);
|
||||
return coded(e.code, text);
|
||||
}
|
||||
if (e?.name === 'OrganizationConfigError' || e?.name === 'BusinessError') return coded('organization-invalid', pathFree(message));
|
||||
return coded('definitions-failed', 'the definitions command failed', 1);
|
||||
}
|
||||
|
||||
// deps.callFor(parsed) returns the human's call(verb, args) for the organization parsed names (cli.mjs
|
||||
// passes its callFor). Without one, a write refuses: it never runs without the bus's secret check.
|
||||
export async function definitionsCommand(args, io, deps = {}) {
|
||||
@@ -68,6 +97,10 @@ export async function definitionsCommand(args, io, deps = {}) {
|
||||
const ifRev = () => { const r = need('--if-rev'); if (!/^[1-9][0-9]*$/.test(r)) throw new CliError('invalid --if-rev', 4); return Number(r); };
|
||||
const [id, verb, name] = pos;
|
||||
if (WRITES.includes(verb)) refuseInsideAgent(io.env);
|
||||
if (id !== 'templates' && id !== undefined && !ID_PATTERN.test(id)) throw new CliError(`invalid organization id: an id is 1 to 64 of a-z, 0-9, '.', '_' and '-', starting with a letter or digit\n${DEFINITIONS_USAGE}`, 4);
|
||||
try { await run(); }
|
||||
catch (e) { throw definitionsFailure(e, id, name); }
|
||||
async function run() {
|
||||
const writer = deps.writer ?? organizationWriter({ dir: configDir(io.env), rolesDir: rolesDir(io.env) });
|
||||
const verbs = definitionVerbs({ writer, rolesDir: rolesDir(io.env) });
|
||||
let result;
|
||||
@@ -93,4 +126,5 @@ export async function definitionsCommand(args, io, deps = {}) {
|
||||
}
|
||||
} else throw new CliError(DEFINITIONS_USAGE, 4);
|
||||
io.stdout.write(JSON.stringify(result, null, 2) + '\n');
|
||||
}
|
||||
}
|
||||
@@ -100,6 +100,15 @@ export function autonomyDocument(current, changes) {
|
||||
return out;
|
||||
}
|
||||
|
||||
// E2E6 fix 7: the autonomy-precondition check the CLI can see from the read and the document it sent:
|
||||
// owner notices off while a class sits near the loop, or moves away from the loop.
|
||||
const ORDER = ['in the loop', 'near the loop', 'out of the loop'];
|
||||
export function preconditionSeen(current, doc) {
|
||||
if (doc?.notices === true) return undefined;
|
||||
const moved = CLASSES.filter(c => ORDER.indexOf(doc?.[c]) > ORDER.indexOf(current?.levels?.[c] ?? 'in the loop'));
|
||||
if (CLASSES.some(c => doc?.[c] === 'near the loop') || moved.length) return 'owner notices are off; a class near the loop, or one moving away from it, needs them on (--notices on)';
|
||||
return undefined;
|
||||
}
|
||||
// Autonomy codes carry no message from the route; these are the panel's own words (autonomy.js).
|
||||
const AUTONOMY_GUIDANCE = {
|
||||
'revision-conflict': 'the organization changed; read it again with mosaic org autonomy ID',
|
||||
@@ -117,6 +126,10 @@ function refused(answer, what, unknown, guidance = {}) {
|
||||
const code = typeof raw === 'string' && /^[a-z-]{1,64}$/.test(raw) ? raw : `http ${answer.status}`;
|
||||
if (code === 'outcome-unknown' || (answer.status >= 500 && !raw)) return new CliError(`outcome unknown: ${unknown}`, 1);
|
||||
const said = typeof answer.body?.message === 'string' ? answer.body.message.slice(0, 500) : guidance[code];
|
||||
// E2E6 fix 7: a route that forwards the bus's reason (which check failed) has it said first; the
|
||||
// general guidance becomes the next line. A reason is one printable line, never a control byte.
|
||||
const reason = typeof answer.body?.reason === 'string' && /^[\x20-\x7e]{1,300}$/.test(answer.body.reason) ? answer.body.reason : undefined;
|
||||
if (reason) return new CliError(`${what} refused (${code}): ${reason}`, 3, { next: said });
|
||||
return new CliError(`${what} refused (${code})${said ? `: ${said}` : ''}`, 3);
|
||||
}
|
||||
|
||||
@@ -173,8 +186,14 @@ export async function orgOwnerCommand(args, io, deps = {}) {
|
||||
const read = await consoleOrgRequest(ctx, id, { path: 'autonomy' });
|
||||
if (!ok(read)) throw refused(read, 'autonomy set', 'the autonomy read did not finish; nothing was changed', AUTONOMY_GUIDANCE);
|
||||
const unknown = `the setting may have been saved; check mosaic org autonomy ${id} before trying again`;
|
||||
const answer = await consoleOrgRequest(ctx, id, { method: 'POST', path: 'autonomy', body: { revision, autonomy: autonomyDocument(read.body, changes) }, unknown });
|
||||
if (!ok(answer)) throw refused(answer, 'autonomy set', unknown, AUTONOMY_GUIDANCE);
|
||||
const doc = autonomyDocument(read.body, changes);
|
||||
const answer = await consoleOrgRequest(ctx, id, { method: 'POST', path: 'autonomy', body: { revision, autonomy: doc }, unknown });
|
||||
if (!ok(answer)) {
|
||||
// E2E6 fix 7: a route that forwards no reason still gets the one check this side can see.
|
||||
const local = answer.body?.error === 'autonomy-precondition' && answer.body?.reason === undefined ? preconditionSeen(read.body, doc) : undefined;
|
||||
if (local) throw new CliError(`autonomy set refused (autonomy-precondition): ${local}`, 3, { next: AUTONOMY_GUIDANCE['autonomy-precondition'] });
|
||||
throw refused(answer, 'autonomy set', unknown, AUTONOMY_GUIDANCE);
|
||||
}
|
||||
return { value: answer.body, text: b => `saved autonomy for ${id}: revision ${b.revision ?? 'unknown'}${b.transaction ? `, receipt ${b.transaction}` : ''}\n` };
|
||||
};
|
||||
} else if (step === 'review') {
|
||||
|
||||
+33
-22
@@ -4,7 +4,6 @@ import { basename } from 'node:path';
|
||||
import { listOrgs, orgLock, resolveOrg } from '../../organization/src/org-registry.mjs';
|
||||
import { organizationWriter } from '../../organization/src/organization.mjs';
|
||||
import { templateRender, validateOrg, createOrg, showOrg, updateOrg, queueInit, queueShow, projectRepoInit, projectRepoShow, projectRepoSet, deleteOrg, archiveOrg, restoreOrg } from '../../organization/src/org-service.mjs';
|
||||
import { installedSystemTypes } from '../../plugins/src/system-types.mjs';
|
||||
import { installedStarterPacks } from '../../plugins/src/starter-pack.mjs';
|
||||
import { DEV_OWNER, devOwnerInstance } from './dev-local-owner.mjs';
|
||||
import { loadSystem, orgPaths, rolesDir } from './config.mjs';
|
||||
@@ -16,10 +15,10 @@ import { busExit, humanTransport, refuseInsideAgent } from './transport.mjs';
|
||||
import { definitionsCommand, DEFINITIONS_USAGE } from './org-definitions.mjs';
|
||||
import { orgOwnerCommand, ORG_OWNER_USAGE, ORG_OWNER_VERBS } from './org-owner.mjs';
|
||||
// Starter packs SP4 (design section 8): the owner's pack, board and workflow words.
|
||||
export const PACKS_USAGE = 'mosaic org pack list | pack preview ID PACK [--project P] [--as KIND.NAME=NEW]... | pack apply ID PACK --digest D [--project P] [--as KIND.NAME=NEW]... | board set ID FILE [--project P] | workflow set ID NAME FILE [--project P] | workflow remove ID NAME [--project P]';
|
||||
export const PACKS_USAGE = 'mosaic org pack list | pack preview ID PACK [--project P] [--as KIND.NAME=NEW]... | pack apply ID PACK --digest D [--project P] [--as KIND.NAME=NEW]... | pack hire ID PACK [--project P] | board set ID FILE [--project P] | workflow set ID NAME FILE [--project P] | workflow remove ID NAME [--project P]';
|
||||
// #1873 SP8: saving the organization, or one project, as a template; the owner's alone.
|
||||
export const TEMPLATE_USAGE = 'mosaic org template save ID NAME [--project P] (--preview | --digest D) | template list ID';
|
||||
export const ORG_USAGE = 'mosaic org system-types installed | system-types enabled ID | lock show|clear ID | reload ID | archive ID --if-revision N [--json] | restore ID --if-revision N [--no-bus] [--json] | delete ID --confirm ID [--if-revision N] [--json] | template render ID [--fixture local] --output FILE | validate FILE | create ID --from FILE | show ID [--json] | list [--json] | update ID --from FILE --if-revision N | queue init ID (--local-only --accept-local-loss-risk | --remote URL) | queue show ID [--json] | project repo init ID PROJECT (--local-only --accept-local-loss-risk | --remote URL) | project repo show ID PROJECT [--json] | project repo set ID PROJECT (--local-only --accept-local-loss-risk | --remote URL) --if-revision N [--json] | ' + DEFINITIONS_USAGE.slice('mosaic org '.length) + ' | ' + ORG_OWNER_USAGE.slice('mosaic org '.length) + ' | ' + PACKS_USAGE.slice('mosaic org '.length) + ' | ' + TEMPLATE_USAGE.slice('mosaic org '.length) + ' | config validate ID | config resolve ID INSTANCE [--project ID]';
|
||||
export const ORG_USAGE = 'mosaic org lock show|clear ID | reload ID | archive ID --if-revision N [--json] | restore ID --if-revision N [--no-bus] [--json] | delete ID --confirm ID [--if-revision N] [--json] | template render ID [--fixture local] --output FILE | validate FILE | create ID --from FILE | show ID [--json] | list [--json] | update ID --from FILE --if-revision N | queue init ID (--local-only --accept-local-loss-risk | --remote URL) | queue show ID [--json] | project repo init ID PROJECT (--local-only --accept-local-loss-risk | --remote URL) | project repo show ID PROJECT [--json] | project repo set ID PROJECT (--local-only --accept-local-loss-risk | --remote URL) --if-revision N [--json] | ' + DEFINITIONS_USAGE.slice('mosaic org '.length) + ' | ' + ORG_OWNER_USAGE.slice('mosaic org '.length) + ' | ' + PACKS_USAGE.slice('mosaic org '.length) + ' | ' + TEMPLATE_USAGE.slice('mosaic org '.length) + ' | config validate ID | config resolve ID INSTANCE [--project ID]';
|
||||
function parse(args) { const pos = [], values = {}, flags = new Set(); for (let i = 0; i < args.length; i++) { const a = args[i]; if (['--json', '--local-only', '--accept-local-loss-risk', '--no-bus'].includes(a)) { if (flags.has(a)) throw new CliError(`duplicate ${a}`, 4); flags.add(a); } else if (['--fixture', '--output', '--from', '--if-revision', '--remote', '--confirm'].includes(a)) { if (values[a] !== undefined || !args[i+1] || args[i+1].startsWith('--')) throw new CliError(`${a} needs one value`, 4); values[a] = args[++i]; } else if (a.startsWith('--')) throw new CliError(`unknown option ${a}`, 4); else pos.push(a); } return { pos, values, flags }; }
|
||||
// A refusal names the document by label and the error by its code, never by host path or bytes (PR #1916).
|
||||
const errorCode = e => typeof e?.code === 'string' && /^E[A-Z0-9]+$/.test(e.code) ? e.code : 'unreadable';
|
||||
@@ -64,7 +63,27 @@ const PACK_REFUSALS = {
|
||||
'invalid-request': 'the bus refused the request: a bad argument, a project that is not a code project, or a pack that fails the composition check',
|
||||
'human-required': 'only the organization\'s owner, from a human shell, may do this',
|
||||
'starter-pack-not-found': 'no installed, shipped or saved pack has that name',
|
||||
'starter-pack-invalid': 'the pack fails its own checks or the composition check; nothing was written',
|
||||
'starter-pack-template-changed': 'a template the pack names changed since it was loaded; preview again',
|
||||
'not-configured': 'this organization\'s bus has no organization writer configured',
|
||||
// Ruling 2026-11-14: apply and pack hire hire the pack's proposals. These come back as a hire's code.
|
||||
'pack-not-applied': 'that pack has no packs entry in this organization or project; preview and apply it first',
|
||||
'pack-hire-route-missing': 'neither the chief of staff nor the assistant has a harness and model to give a hire; set both in either one\'s vars, then run pack hire',
|
||||
'no-chief-of-staff': 'the organization has no chief of staff to raise its hires',
|
||||
'right-required': 'hiring needs the org.hire right',
|
||||
};
|
||||
// E2E6 fix 3: humanTransport throws a CliError whose message and .code are the bus code alone. A code
|
||||
// a table knows gains its hint, as template save's do; a next line it carried is kept. Any other
|
||||
// CliError (bus-not-running with its own next line, a usage error) passes unchanged, and a bare coded
|
||||
// error (a test's call) becomes a CliError named by its code.
|
||||
function hinted(e, ...tables) {
|
||||
const code = typeof e?.code === 'string' ? e.code : '';
|
||||
const table = tables.find(t => Object.hasOwn(t, code));
|
||||
if (!table && (code === '' || e instanceof CliError)) return e;
|
||||
const error = new CliError(table ? `${code}: ${table[code]}` : code, busExit(code), { next: e.next });
|
||||
error.code = code;
|
||||
return error;
|
||||
}
|
||||
async function packsCommand(args, io, deps) {
|
||||
const pos = [], values = {}, as = [];
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
@@ -87,13 +106,15 @@ async function packsCommand(args, io, deps) {
|
||||
if (sub === 'apply' && !values['--digest']) throw new CliError('--digest is required: apply the digest a preview printed', 4);
|
||||
verb = `pack.${sub}`;
|
||||
request = { pack: name, ...project, ...(as.length ? { as } : {}), ...(sub === 'apply' ? { digest: values['--digest'] } : {}) };
|
||||
} else if (word === 'pack' && sub === 'hire' && pos.length === 4) {
|
||||
// Ruling 2026-11-14: hire the proposals of a pack already applied, the same loop apply runs.
|
||||
allowed('--project'); verb = 'pack.hire'; request = { pack: name, ...project };
|
||||
} else if (word === 'board' && sub === 'set' && pos.length === 4) { allowed('--project'); verb = 'board.set'; revised = true; request = { board: await packFile(name), ...project }; }
|
||||
else if (word === 'workflow' && sub === 'set' && pos.length === 5) { allowed('--project'); verb = 'workflow.set'; revised = true; request = { name, workflow: await packFile(file), ...project }; }
|
||||
else if (word === 'workflow' && sub === 'remove' && pos.length === 4) { allowed('--project'); verb = 'workflow.set'; revised = true; request = { name, workflow: null, ...project }; }
|
||||
else throw new CliError(PACKS_USAGE, 4);
|
||||
// pack list names no organization, so it reads what the bus's `packs` verb reads (the shipped and
|
||||
// installed packs, never a saved template) from this instance's data root, as `system-types
|
||||
// installed` does.
|
||||
// installed packs, never a saved template) from this instance's data root.
|
||||
if (verb === 'packs') {
|
||||
const system = deps.system ?? loadSystem({ env: io.env, instance: devOwnerInstance(io.env) });
|
||||
const { packs } = await installedStarterPacks({ dataRoot: system.dataRoot, rolesDir: rolesDir(io.env) });
|
||||
@@ -107,13 +128,7 @@ async function packsCommand(args, io, deps) {
|
||||
}
|
||||
let result;
|
||||
try { result = await call(verb, request); }
|
||||
catch (e) {
|
||||
if (typeof e?.code !== 'string' || e.code === '' || e instanceof CliError) throw e;
|
||||
const why = PACK_REFUSALS[e.code];
|
||||
const error = new CliError(why ? `${e.code}: ${why}` : e.code, busExit(e.code));
|
||||
error.code = e.code;
|
||||
throw error;
|
||||
}
|
||||
catch (e) { throw hinted(e, PACK_REFUSALS); }
|
||||
io.stdout.write(JSON.stringify(result, null, 2) + '\n');
|
||||
}
|
||||
// #1873 SP8: template save previews (--preview) or writes the previewed JSON (--digest); template
|
||||
@@ -122,7 +137,8 @@ async function packsCommand(args, io, deps) {
|
||||
const TEMPLATE_REFUSALS = {
|
||||
'template-secret-suspected': 'a field the template would keep holds a credential the organization\'s bus holds; remove it and preview again (nothing was written)',
|
||||
'pack-plan-stale': 'the organization or a template changed since the preview; preview again and save its digest',
|
||||
'invalid-request': 'the bus refused the request: a bad name, a name already saved, an unknown project, or an organization the template cannot hold',
|
||||
'template-exists': 'a template of this name is already saved for your account; nothing was written',
|
||||
'invalid-request': 'the bus refused the request: a bad name, an unknown project, or an organization the template cannot hold',
|
||||
'human-required': 'only the organization\'s owner, from a human shell, may do this',
|
||||
'not-configured': 'the templates directory is missing or not private to this instance\'s user',
|
||||
'starter-pack-invalid': 'the template would not be a valid pack: more than 8 hires, or a definition wider than its template',
|
||||
@@ -149,12 +165,9 @@ async function templateCommand(args, io, deps) {
|
||||
let result;
|
||||
try { result = await packCall(id, io, deps)(verb, request); }
|
||||
catch (e) {
|
||||
// humanTransport throws a CliError named by the bus code alone: a known code gains its hint.
|
||||
const why = typeof e?.code !== 'string' ? undefined
|
||||
: Object.hasOwn(TEMPLATE_REFUSALS, e.code) ? TEMPLATE_REFUSALS[e.code] : Object.hasOwn(PACK_REFUSALS, e.code) ? PACK_REFUSALS[e.code] : undefined;
|
||||
if (!why) throw e;
|
||||
const error = new CliError(`${e.code}: ${why}`, busExit(e.code));
|
||||
error.code = e.code;
|
||||
const error = hinted(e, TEMPLATE_REFUSALS, PACK_REFUSALS);
|
||||
// E2E6 fix 8: a taken name says what to do next.
|
||||
if (error.code === 'template-exists' && error.next === undefined) error.next = `preview and save under another name, or see the saved names with mosaic org template list ${id}`;
|
||||
throw error;
|
||||
}
|
||||
io.stdout.write(JSON.stringify(result, null, 2) + '\n');
|
||||
@@ -179,10 +192,8 @@ export async function orgCommand(args, io, deps = {}) {
|
||||
let lifecycle = null;
|
||||
if (['archive', 'restore'].includes(words[0]) && words.length === 2) { allowed(['--json', ...(words[0] === 'restore' ? ['--no-bus'] : [])], ['--if-revision']); lifecycle = { ifRevision: revision(p.values['--if-revision'], true) }; if (words[0] === 'archive' || !p.flags.has('--no-bus')) refuseAgentRun(io); }
|
||||
else if (words[0] === 'delete' && words.length === 2) { allowed(['--json'], ['--confirm', '--if-revision']); const ifRevision = revision(p.values['--if-revision'], false); lifecycle = { confirm: need('--confirm'), ifRevision }; refuseAgentRun(io); }
|
||||
if (words[0] === 'system-types' && words[1] === 'installed' && words.length === 2) { allowed(['--json'], []); io.stdout.write(JSON.stringify(await installedSystemTypes(), null, 2) + '\n'); return; }
|
||||
const instance = devOwnerInstance(io.env); const system = deps.system ?? loadSystem({ env: io.env, instance }); const ctx = { configDir: configDir(io.env), dataRoot: system.dataRoot, instance, principal: DEV_OWNER };
|
||||
if (words[0] === 'system-types' && words[1] === 'enabled' && words.length === 3) { allowed(['--json'], []); const org = await showOrg(ctx, words[2]); result = { organization: words[2], enabled: org.doc.plugins?.['system-type'] ?? [] }; }
|
||||
else if (words[0] === 'lock' && ['show', 'clear'].includes(words[1]) && words.length === 3) { allowed([], []); result = await orgLock(ctx, words[2], { clear: words[1] === 'clear' }); }
|
||||
if (words[0] === 'lock' && ['show', 'clear'].includes(words[1]) && words.length === 3) { allowed([], []); result = await orgLock(ctx, words[2], { clear: words[1] === 'clear' }); }
|
||||
else if (words[0] === 'create' && words.length === 2) { allowed([], ['--from']); result = await createOrg(ctx, words[1], await document(need('--from'))); }
|
||||
else if (words[0] === 'update' && words.length === 2) { allowed([], ['--from', '--if-revision']); const r = need('--if-revision'); if (!/^[1-9][0-9]*$/.test(r)) throw new CliError('invalid revision', 4); result = await updateOrg(ctx, words[1], await document(need('--from')), { ifRevision: Number(r) }); }
|
||||
else if (words[0] === 'archive' && words.length === 2) result = await archiveOrg(ctx, words[1], { ...lifecycle, busStop: busStopForDelete, copyRemote: await (deps.copyRemoteFor ?? copyRemoteFor)(ctx) });
|
||||
|
||||
@@ -14,8 +14,6 @@ export const PROJECT_USAGE = 'mosaic project init <business> <project> [--tester
|
||||
// and check above work on the repository on disk and never contact the bus, except that
|
||||
// init --tester (row 175, #1673) binds the tester once before it writes.
|
||||
export const PROJECT_BUS_USAGE = [
|
||||
'mosaic project system-types <name-or-id> [--business <id>] [--json]',
|
||||
'mosaic project system-types-set <name-or-id> --types <comma-separated-ids> [--business <id>]',
|
||||
'mosaic project create <name> [--repo <repo>] [--business <id>] [--tester]',
|
||||
'mosaic project list [--archived] [--business <id>] [--json] [--tester]',
|
||||
'mosaic project archive <name-or-id> [--business <id>]',
|
||||
@@ -30,8 +28,8 @@ export async function projectBusCommand(args, io, callFor) {
|
||||
? { flags: ['--tester'], values: ['--repo', '--business'] }
|
||||
: sub === 'list'
|
||||
? { flags: ['--json', '--tester', '--archived'], values: ['--business'] }
|
||||
: { flags: sub === 'system-types' ? ['--json'] : [], values: sub === 'system-types-set' ? ['--business', '--types'] : ['--business'] });
|
||||
const one = ['create', 'archive', 'unarchive', 'system-types', 'system-types-set'].includes(sub);
|
||||
: { flags: [], values: ['--business'] });
|
||||
const one = ['create', 'archive', 'unarchive'].includes(sub);
|
||||
if (parsed.positional.length !== (one ? 1 : 0))
|
||||
throw new CliError(`project ${sub} takes ${one ? (sub === 'create' ? 'one name' : 'one name or id') : 'no arguments'}\n${PROJECT_BUS_USAGE}`, 4);
|
||||
const call = callFor(parsed);
|
||||
@@ -47,17 +45,6 @@ export async function projectBusCommand(args, io, callFor) {
|
||||
}
|
||||
return io.stdout.write(`created project ${name} id ${made.id}\n`);
|
||||
}
|
||||
if (sub === 'system-types' || sub === 'system-types-set') {
|
||||
const projects = await call('project.list', { includeArchived: true });
|
||||
const ref = parsed.positional[0];
|
||||
const hit = projects.find(p => p.id === ref) ?? projects.find(p => p.name === ref);
|
||||
if (!hit) throw new CliError(`no project is named or numbered ${JSON.stringify(ref)}`, 2);
|
||||
const write = sub === 'system-types-set';
|
||||
if (write && parsed.values['--types'] === undefined) throw new CliError('--types is required (an empty string clears the list)', 4);
|
||||
const systemTypes = parsed.values['--types'] ? parsed.values['--types'].split(',') : [];
|
||||
const result = await call(write ? 'project.system-types.set' : 'project.system-types', { project: hit.id, ...(write ? { systemTypes } : {}) });
|
||||
return io.stdout.write(JSON.stringify(result, null, 2) + '\n');
|
||||
}
|
||||
// #797 MVP3: the owner's reversible archive. Resolution reads the full list, archived included,
|
||||
// so an archived project can be named for unarchive.
|
||||
if (sub === 'archive' || sub === 'unarchive') {
|
||||
|
||||
@@ -41,6 +41,7 @@ const EXIT = {
|
||||
"tester-required": 3,
|
||||
"tester-off": 3,
|
||||
"tester-refused": 3,
|
||||
"bus-not-running": 3,
|
||||
"outcome-unknown": 1,
|
||||
"outcome-unknown-revoked": 1,
|
||||
"response-too-large": 1,
|
||||
@@ -51,6 +52,17 @@ export function busExit(code) {
|
||||
return EXIT[code] ?? 2;
|
||||
}
|
||||
|
||||
// E2E6 fix 6: the shim exits 5 (packages/bus/src/client.mjs NOT_SENT_EXIT) when its connect failed
|
||||
// before the request was written: no socket, or the connect refused. That is a stopped bus, and
|
||||
// nothing happened; outcome-unknown stays for a request that left and got no answer.
|
||||
const NOT_SENT_EXIT = 5;
|
||||
export function busNotRunning(business) {
|
||||
const error = new CliError(`bus-not-running: the bus for ${business} is not running, so the request was not sent`, 3);
|
||||
error.code = "bus-not-running";
|
||||
error.next = `start it with mosaic bus start ${business}, or clear a host that died with mosaic bus recover ${business}`;
|
||||
return error;
|
||||
}
|
||||
|
||||
// Returns a call(verb, args) for one business. `cli` and `spawn` exist for
|
||||
// the tests; the command line never sets them.
|
||||
export function humanTransport({ socket, business, env = process.env, cli = HUMAN_CLI, spawn = spawnSync, timeoutMs = 30000 }) {
|
||||
@@ -65,6 +77,7 @@ export function humanTransport({ socket, business, env = process.env, cli = HUMA
|
||||
if (proc.error || proc.status === null) throw new CliError("outcome-unknown: the bus transport did not finish", 1);
|
||||
if (proc.status !== 0) {
|
||||
const code = String(proc.stderr ?? "").trim().split("\n").reverse().find((l) => /^[a-z-]{1,64}$/.test(l)) ?? "invalid-response";
|
||||
if (proc.status === NOT_SENT_EXIT && code === "outcome-unknown") throw busNotRunning(business);
|
||||
const error = new CliError(code, busExit(code));
|
||||
error.code = code;
|
||||
throw error;
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
// #1873 triage-wiring: the Triage key file's reader, moved out of triage-key.mjs so the Console can
|
||||
// read the key at each Triage spawn without loading the proxy management client or the proxy lock.
|
||||
// It imports node built-ins only; packages/webui/tests/triage-wiring.test.mjs fails if the Console's
|
||||
// Triage modules load model-proxy/src/client.mjs. triage-key.mjs (the owner's key verbs) imports
|
||||
// these and re-exports what it exported before, so its callers are unchanged.
|
||||
//
|
||||
// <configDir>/secrets/triage/model (directory 0700, file 0600, the running user's)
|
||||
// { version, key, keyId, issuedAt, rotateBy, retiring: [{ key, keyId, issuedAt, retireAt }] }
|
||||
//
|
||||
// Messages name files, never values.
|
||||
import { closeSync, constants, fchmodSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync } from "node:fs";
|
||||
import { createHash } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
|
||||
export const KEY_VERSION = 1;
|
||||
const FIELDS = Object.freeze(["version", "key", "keyId", "issuedAt", "rotateBy", "retiring"]);
|
||||
const RETIRING_FIELDS = Object.freeze(["key", "keyId", "issuedAt", "retireAt"]);
|
||||
const MAX_BYTES = 64 * 1024;
|
||||
export const MAX_RETIRING = 16;
|
||||
export const SECRET = /^[A-Za-z0-9_-]{43}$/;
|
||||
const ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
|
||||
const DAY = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
export class TriageKeyError extends Error {
|
||||
constructor(code, message, exitCode = 3) {
|
||||
super(message);
|
||||
this.name = "TriageKeyError";
|
||||
this.code = code;
|
||||
this.exitCode = exitCode;
|
||||
}
|
||||
}
|
||||
export const unreadable = (why) => new TriageKeyError("triage-key-unreadable", `the Triage key store is unreadable: ${why}`);
|
||||
|
||||
export const keyIdOf = (key) => createHash("sha256").update(key).digest("hex").slice(0, 12);
|
||||
export const instanceTag = (configDir) => createHash("sha256").update(configDir).digest("hex").slice(0, 12);
|
||||
export const keyPrefix = (configDir) => `mst-${instanceTag(configDir)}-triage-`;
|
||||
const ownKey = (configDir) => (k) => typeof k === "string" && k.startsWith(keyPrefix(configDir)) && SECRET.test(k.slice(keyPrefix(configDir).length));
|
||||
|
||||
export function keyPaths(configDir) {
|
||||
const secrets = join(configDir, "secrets");
|
||||
const dir = join(secrets, "triage");
|
||||
return { secrets, dir, file: join(dir, "model") };
|
||||
}
|
||||
|
||||
const plain = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype;
|
||||
const exactKeys = (v, keys) => plain(v) && Object.keys(v).length === keys.length && keys.every((k) => Object.hasOwn(v, k));
|
||||
const canonicalTime = (s) => typeof s === "string" && ISO.test(s) && !Number.isNaN(Date.parse(s)) && new Date(s).toISOString() === s;
|
||||
const canonicalDay = (s) => typeof s === "string" && DAY.test(s) && !Number.isNaN(Date.parse(`${s}T00:00:00Z`)) && new Date(`${s}T00:00:00Z`).toISOString().slice(0, 10) === s;
|
||||
|
||||
export function validRecord(doc, configDir) {
|
||||
const own = ownKey(configDir);
|
||||
return exactKeys(doc, FIELDS)
|
||||
&& doc.version === KEY_VERSION
|
||||
&& own(doc.key) && doc.keyId === keyIdOf(doc.key)
|
||||
&& canonicalTime(doc.issuedAt) && canonicalDay(doc.rotateBy)
|
||||
&& Array.isArray(doc.retiring) && doc.retiring.length <= MAX_RETIRING
|
||||
&& doc.retiring.every((r) => exactKeys(r, RETIRING_FIELDS) && own(r.key) && r.key !== doc.key && r.keyId === keyIdOf(r.key)
|
||||
&& canonicalTime(r.issuedAt) && canonicalTime(r.retireAt))
|
||||
&& new Set(doc.retiring.map((r) => r.key)).size === doc.retiring.length;
|
||||
}
|
||||
|
||||
const uidOf = (opts) => opts.uid ?? process.getuid();
|
||||
|
||||
// A real directory, the running user's, mode 0700. Missing: false, or made when `create` is on.
|
||||
export function checkDir(dir, uid, what, { create }) {
|
||||
let st;
|
||||
try { st = lstatSync(dir); }
|
||||
catch (e) {
|
||||
if (e.code !== "ENOENT") throw unreadable(`${what} cannot be read`);
|
||||
if (!create) return false;
|
||||
try { mkdirSync(dir, { mode: 0o700 }); } catch { throw unreadable(`${what} cannot be made`); }
|
||||
try {
|
||||
const fd = openSync(dir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
|
||||
try { fchmodSync(fd, 0o700); } finally { closeSync(fd); }
|
||||
} catch { throw unreadable(`${what} cannot be made`); }
|
||||
st = lstatSync(dir);
|
||||
}
|
||||
if (st.isSymbolicLink()) throw unreadable(`${what} is a link`);
|
||||
if (!st.isDirectory()) throw unreadable(`${what} is not a directory`);
|
||||
if (st.uid !== uid) throw unreadable(`${what} is not owned by this user`);
|
||||
if ((st.mode & 0o777) !== 0o700) throw unreadable(`${what} mode is not 0700`);
|
||||
return true;
|
||||
}
|
||||
|
||||
export function checkFile(fd, uid, what, fail = unreadable) {
|
||||
const st = fstatSync(fd);
|
||||
if (!st.isFile()) throw fail(`${what} is not a regular file`);
|
||||
if (st.nlink !== 1) throw fail(`${what} has more than one link`);
|
||||
if (st.uid !== uid) throw fail(`${what} is not owned by this user`);
|
||||
if ((st.mode & 0o777) !== 0o600) throw fail(`${what} mode is not 0600`);
|
||||
return st;
|
||||
}
|
||||
|
||||
// The stored record, or null when no key is issued. Throws triage-key-unreadable on anything unsafe.
|
||||
// opts.uid (both directories and the file) and opts.fileUid (the file only) are test seams for the
|
||||
// owner checks.
|
||||
export function readKey(configDir, opts = {}) {
|
||||
const { secrets, dir, file } = keyPaths(configDir);
|
||||
const uid = uidOf(opts);
|
||||
if (!checkDir(secrets, uid, "the secrets directory", { create: false })) return null;
|
||||
if (!checkDir(dir, uid, "the triage secrets directory", { create: false })) return null;
|
||||
let fd;
|
||||
try { fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); }
|
||||
catch (e) {
|
||||
if (e.code === "ENOENT") return null;
|
||||
if (e.code === "ELOOP") throw unreadable("the key file is a link");
|
||||
throw unreadable("the key file cannot be opened");
|
||||
}
|
||||
try {
|
||||
const st = checkFile(fd, opts.fileUid ?? uid, "the key file");
|
||||
if (st.size > MAX_BYTES) throw unreadable("the key file is too large");
|
||||
let doc;
|
||||
try { doc = JSON.parse(readFileSync(fd, "utf8")); } catch { throw unreadable("the key file is not JSON"); }
|
||||
if (!validRecord(doc, configDir)) throw unreadable("the key file does not match the key shape");
|
||||
return doc;
|
||||
} finally { closeSync(fd); }
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
// #1873 triage-key: Triage's own model proxy client key, issued from the owner's terminal
|
||||
// (design report reports/triage-route-design.md slice 3, Jason's ruling 2026-11-18).
|
||||
//
|
||||
// <configDir>/secrets/triage/model (directory 0700, file 0600, the running user's)
|
||||
// { version, key, keyId, issuedAt, rotateBy, retiring: [{ key, keyId, issuedAt, retireAt }] }
|
||||
//
|
||||
// The key is `mst-<instance tag>-triage-<43 base64url>`, where the tag is the first 12 hex of
|
||||
// sha256(configDir), the tag the instance's own `msk-` sentinel carries. An org bus reconciles only
|
||||
// its own `mso-<tag>-<org>-key-` names and a no-org bus only `msk-<tag>-`, so neither touches it.
|
||||
//
|
||||
// Every proxy write runs under the instance proxy lock (packages/bus/src/proxy-lock.mjs), the lock
|
||||
// org buses take: read the list, check this instance's sentinel, fence, PUT, read back, confirm.
|
||||
// The proxy changes first and the file second, as the bus does for an agent key. A crash between
|
||||
// leaves a key in the Triage namespace that the file does not hold; the next issue, rotate or retire
|
||||
// removes it, and status names it. A crash after the PUT and before the read-back leaves the lock's
|
||||
// uncertain fence, which every proxy writer on the instance refuses until a human clears it
|
||||
// (`mosaic proxy fence clear --proxy-restarted`).
|
||||
//
|
||||
// Nothing runs on a timer. rotate records when the old key's grace ends; the key stays in the proxy
|
||||
// until a later retire, rotate or issue removes it, and status says when that is due. The same goes
|
||||
// for rotateBy: status marks it due; only rotate replaces the key.
|
||||
//
|
||||
// Nothing here prints, logs or records a key. Receipts and output carry key ids only (the first 12
|
||||
// hex of sha256(key), the id the bus uses). Messages name files and options, never values.
|
||||
// The Console reads the key at each Triage spawn through triage-key-file.mjs, never this module.
|
||||
import { closeSync, constants, fchmodSync, fsyncSync, lstatSync, openSync, readdirSync, renameSync, unlinkSync, writeSync } from "node:fs";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import { createProxyLock } from "../../bus/src/proxy-lock.mjs";
|
||||
import { loadManagementClient } from "../../model-proxy/src/client.mjs";
|
||||
|
||||
// #1873 triage-wiring: the key file's reader lives in triage-key-file.mjs (node built-ins only), so
|
||||
// the Console reads the key without this module's proxy client. Re-exported here unchanged.
|
||||
import { KEY_VERSION, MAX_RETIRING, SECRET, TriageKeyError, checkDir, checkFile, instanceTag, keyIdOf, keyPaths, keyPrefix, readKey, unreadable, validRecord } from "./triage-key-file.mjs";
|
||||
export { KEY_VERSION, TriageKeyError, instanceTag, keyIdOf, keyPaths, keyPrefix, readKey, validRecord };
|
||||
|
||||
// The org key lifetime and the rotate grace default. The bus holds both as literals
|
||||
// (packages/bus/src/model-keys.mjs #issue: 30 days to rotateBy; packages/bus/src/runtime.mjs:
|
||||
// `proxy.rotateGraceMinutes ?? 120`) and exports neither, and this lane may not change the bus.
|
||||
// packages/cli/tests/triage-key.test.mjs drives the bus's own ModelKeys with the same clock and
|
||||
// proves these give the same rotateBy and retireAt, so a change on either side goes red there.
|
||||
// The grace itself is read from proxy.json first, where the bus reads it.
|
||||
export const KEY_LIFETIME_DAYS = 30;
|
||||
export const DEFAULT_ROTATE_GRACE_MINUTES = 120;
|
||||
const sentinelPrefix = (configDir) => `msk-${instanceTag(configDir)}-sentinel-`;
|
||||
// Any name under the prefix is Triage's to remove, well formed or not, as the bus treats its own
|
||||
// `msk-<tag>-` names. Only a well-formed key may be stored in the file.
|
||||
const inNamespace = (configDir) => (k) => typeof k === "string" && k.startsWith(keyPrefix(configDir));
|
||||
|
||||
// Both directories, checked (and the triage one made) before any proxy write, so a store that cannot
|
||||
// be written refuses while the proxy is still untouched.
|
||||
function prepareDirs(configDir, uid) {
|
||||
const { secrets, dir } = keyPaths(configDir);
|
||||
if (!checkDir(secrets, uid, "the secrets directory", { create: false })) throw unreadable("the secrets directory is missing");
|
||||
checkDir(dir, uid, "the triage secrets directory", { create: true });
|
||||
}
|
||||
|
||||
// A temp file writeKey left when it was killed before its rename. It may hold a key.
|
||||
const TEMP = /^\.model\.\d+\.[0-9a-f]{12}\.tmp$/;
|
||||
const tempsIn = (dir) => { try { return readdirSync(dir).filter((n) => TEMP.test(n)); } catch { return []; } };
|
||||
// Under the lock no other Triage writer runs, so every temp file left in the directory is dead.
|
||||
function removeTemps(configDir) {
|
||||
const { dir } = keyPaths(configDir);
|
||||
for (const name of tempsIn(dir)) {
|
||||
try { if (!lstatSync(join(dir, name)).isDirectory()) unlinkSync(join(dir, name)); }
|
||||
catch { throw unreadable("a leftover temp file in the triage secrets directory cannot be removed"); }
|
||||
}
|
||||
}
|
||||
|
||||
// A directory sync that failed after the rename: the file is in place but may not be durable.
|
||||
class NotSynced extends Error {}
|
||||
|
||||
// Atomic: a 0600 temp file in the same directory, fsync, rename, fsync of the directory.
|
||||
function writeKey(configDir, record, uid, hook = () => {}) {
|
||||
const { dir, file } = keyPaths(configDir);
|
||||
prepareDirs(configDir, uid);
|
||||
const temp = join(dir, `.model.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
|
||||
let fd;
|
||||
try { fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); }
|
||||
catch { throw unreadable("the key file cannot be written"); }
|
||||
try {
|
||||
try { fchmodSync(fd, 0o600); writeSync(fd, `${JSON.stringify(record, null, 2)}\n`); fsyncSync(fd); }
|
||||
finally { closeSync(fd); }
|
||||
hook("rename");
|
||||
renameSync(temp, file);
|
||||
} catch { try { unlinkSync(temp); } catch {} throw unreadable("the key file cannot be written"); }
|
||||
try {
|
||||
hook("sync");
|
||||
const dfd = openSync(dir, constants.O_RDONLY | constants.O_DIRECTORY);
|
||||
try { fsyncSync(dfd); } finally { closeSync(dfd); }
|
||||
} catch { throw new NotSynced(); }
|
||||
}
|
||||
|
||||
// One line per write in the proxy lock's receipts file, ids only. `receiptsReady` runs under the
|
||||
// lock before any change, so an unsafe receipts file refuses while nothing has changed yet.
|
||||
const RECEIPTS_FLAGS = constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW | constants.O_NONBLOCK;
|
||||
const receiptsUnsafe = (why) => new TriageKeyError("triage-key-receipts-unsafe", `${why}; nothing was changed`);
|
||||
function receiptsReady(stateDir, uid) {
|
||||
let fd;
|
||||
try { fd = openSync(join(stateDir, "mosaic-keys.receipts.jsonl"), RECEIPTS_FLAGS, 0o600); }
|
||||
catch { throw receiptsUnsafe("the proxy receipts file cannot be opened"); }
|
||||
try { checkFile(fd, uid, "the proxy receipts file", receiptsUnsafe); } finally { closeSync(fd); }
|
||||
}
|
||||
function receipt(stateDir, uid, entry) {
|
||||
const unrecorded = new TriageKeyError("triage-key-unrecorded", "the change was made but its receipt line was not written; run mosaic triage key status");
|
||||
let fd;
|
||||
try { fd = openSync(join(stateDir, "mosaic-keys.receipts.jsonl"), RECEIPTS_FLAGS, 0o600); } catch { throw unrecorded; }
|
||||
try {
|
||||
checkFile(fd, uid, "the proxy receipts file", () => unrecorded);
|
||||
writeSync(fd, `${JSON.stringify(entry)}\n`);
|
||||
fsyncSync(fd);
|
||||
} catch { throw unrecorded; }
|
||||
finally { closeSync(fd); }
|
||||
}
|
||||
|
||||
// The grace the bus uses: proxy.json's rotateGraceMinutes, or the bus default.
|
||||
export const graceMinutes = (proxy) => proxy?.rotateGraceMinutes ?? DEFAULT_ROTATE_GRACE_MINUTES;
|
||||
export const rotateByFor = (nowMs) => new Date(nowMs + KEY_LIFETIME_DAYS * 86400_000).toISOString().slice(0, 10);
|
||||
export const retireAtFor = (nowMs, proxy) => new Date(nowMs + graceMinutes(proxy) * 60_000).toISOString();
|
||||
|
||||
const proxyFailure = (code) => {
|
||||
const words = {
|
||||
"proxy-lock-busy": "another proxy writer holds the instance proxy lock; try again when it ends, and if no writer is running, see mosaic proxy fence status",
|
||||
"proxy-lock-uncertain": "the instance proxy lock is in a state this verb will not guess about; check <dataRoot>/proxy by hand",
|
||||
"proxy-lock-invalid": "the instance proxy lock directory is missing or unsafe, or names another proxy",
|
||||
"proxy-uncertain": "an earlier proxy write has an uncertain outcome; see mosaic proxy fence status",
|
||||
"proxy-management-key-invalid": "the proxy management key file is missing or unsafe",
|
||||
"proxy-client-invalid": "the proxy settings are not usable",
|
||||
"proxy-client-down": "the proxy did not answer",
|
||||
"proxy-client-refused": "the proxy refused the management request",
|
||||
"proxy-client-redirect": "the proxy answered with a redirect",
|
||||
"proxy-client-response": "the proxy gave an answer this verb cannot use",
|
||||
};
|
||||
return new TriageKeyError(code, words[code] ?? "the proxy write failed");
|
||||
};
|
||||
|
||||
// opts.uid, opts.now and opts.hook(stage) are test seams; a stage hook may throw or kill the process.
|
||||
function context({ configDir, system, uid, fileUid, now, hook }) {
|
||||
if (!system?.proxy || !Number.isInteger(system.proxy.port)) throw new TriageKeyError("triage-key-no-proxy", "the instance has no model proxy set up (proxy.json)");
|
||||
return {
|
||||
configDir, dataRoot: system.dataRoot, proxy: system.proxy, stateDir: join(system.dataRoot, "proxy"),
|
||||
uid: uid ?? process.getuid(), fileUid, now: now ?? Date.now, hook: hook ?? (() => {}),
|
||||
};
|
||||
}
|
||||
|
||||
function lockFor(c) {
|
||||
try { return createProxyLock({ stateDir: c.stateDir, identity: `${c.configDir}:${c.proxy.port}` }); }
|
||||
catch (e) { throw proxyFailure(e.code ?? "proxy-lock-invalid"); }
|
||||
}
|
||||
|
||||
async function clientFor(c) {
|
||||
try { return await loadManagementClient({ configDir: c.configDir, proxy: c.proxy }); }
|
||||
catch (e) { throw proxyFailure(e.code ?? "proxy-management-key-invalid"); }
|
||||
}
|
||||
|
||||
function checkSentinel(c, keys) {
|
||||
const prefix = sentinelPrefix(c.configDir);
|
||||
if (!keys.some((k) => k.startsWith(prefix) && SECRET.test(k.slice(prefix.length)))) {
|
||||
throw new TriageKeyError("triage-key-proxy-open", "the proxy's key list has no sentinel for this instance, so it may be another proxy");
|
||||
}
|
||||
}
|
||||
|
||||
// Under the instance proxy lock: read the list, check the sentinel, run `plan`, write the result.
|
||||
// `plan(keys, record)` returns { after, record, removed, added, done }; `record` null leaves the
|
||||
// file alone. The proxy changes first, then the file, then one receipt line.
|
||||
async function change(c, op, plan) {
|
||||
const lock = lockFor(c);
|
||||
const client = await clientFor(c);
|
||||
try {
|
||||
return await lock.run(async () => {
|
||||
const before = await client.getKeys();
|
||||
checkSentinel(c, before);
|
||||
const current = readKey(c.configDir, { uid: c.uid, fileUid: c.fileUid });
|
||||
const result = plan(before, current);
|
||||
if (result.record) prepareDirs(c.configDir, c.uid);
|
||||
removeTemps(c.configDir);
|
||||
receiptsReady(c.stateDir, c.uid);
|
||||
const after = result.after;
|
||||
const removed = before.filter((k) => !after.includes(k));
|
||||
const added = after.filter((k) => !before.includes(k));
|
||||
// A key in another namespace never leaves the list.
|
||||
if (removed.some((k) => !inNamespace(c.configDir)(k))) throw new TriageKeyError("triage-key-failed", "the change would remove a key outside the Triage namespace");
|
||||
if (added.length || removed.length) {
|
||||
// As the bus does: a list that moved since the first read is not overwritten.
|
||||
if (!isDeepStrictEqual(await client.getKeys(), before)) throw new TriageKeyError("triage-key-raced", "the proxy's key list changed while this verb ran; run it again");
|
||||
lock.fence({ org: null, op: `triage.${op}` });
|
||||
await client.putKeys(after);
|
||||
c.hook("put");
|
||||
const confirmed = await client.getKeys();
|
||||
if (!confirmed.some((k) => k.startsWith(sentinelPrefix(c.configDir))) || added.some((k) => !confirmed.includes(k)) || removed.some((k) => confirmed.includes(k))) {
|
||||
throw new TriageKeyError("triage-key-unconfirmed", "the proxy did not confirm the change; the instance proxy fence stays set, see mosaic proxy fence status");
|
||||
}
|
||||
lock.confirm();
|
||||
}
|
||||
c.hook("write");
|
||||
let unsynced = false;
|
||||
if (result.record) {
|
||||
try { writeKey(c.configDir, result.record, c.uid, c.hook); }
|
||||
catch (e) {
|
||||
if (e instanceof NotSynced) unsynced = true;
|
||||
else throw new TriageKeyError("triage-key-unwritten", `the proxy list changed but ${keyPaths(c.configDir).file} was not written (${e.message}); fix the file's directory, then run mosaic triage key ${op} again, which clears what this run left`);
|
||||
}
|
||||
}
|
||||
c.hook("receipt");
|
||||
// A run that changed neither the proxy nor the file leaves no receipt.
|
||||
if (added.length || removed.length || result.record) receipt(c.stateDir, c.uid, { op: `triage.key.${op}`, time: new Date(c.now()).toISOString(), addedKeyIds: added.map(keyIdOf), removedKeyIds: removed.map(keyIdOf) });
|
||||
// The file is in place and the receipt written; only its durability is in doubt.
|
||||
if (unsynced) throw new TriageKeyError("triage-key-unsynced", `${keyPaths(c.configDir).file} was written but its directory could not be synced, so it may not survive a power loss; run mosaic triage key status`);
|
||||
return { ...result.done, addedKeyIds: added.map(keyIdOf), removedKeyIds: removed.map(keyIdOf) };
|
||||
});
|
||||
} catch (e) {
|
||||
if (e instanceof TriageKeyError) throw e;
|
||||
throw proxyFailure(typeof e?.code === "string" && /^proxy-[a-z-]+$/.test(e.code) ? e.code : "triage-key-failed");
|
||||
}
|
||||
}
|
||||
|
||||
const newKey = (configDir) => keyPrefix(configDir) + randomBytes(32).toString("base64url");
|
||||
|
||||
// Keys in the Triage namespace that the file does not hold: left by a crash between the PUT and the
|
||||
// file write, or by a file that was removed by hand.
|
||||
const orphansOf = (configDir, keys, record) => {
|
||||
const held = record ? [record.key, ...record.retiring.map((r) => r.key)] : [];
|
||||
return keys.filter((k) => inNamespace(configDir)(k) && !held.includes(k));
|
||||
};
|
||||
|
||||
export async function issueKey(opts) {
|
||||
const c = context(opts);
|
||||
return change(c, "issue", (before, current) => {
|
||||
if (current) throw new TriageKeyError("triage-key-issued", "a Triage key is already issued; use mosaic triage key rotate");
|
||||
const orphans = orphansOf(c.configDir, before, null);
|
||||
const key = newKey(c.configDir), nowMs = c.now();
|
||||
const record = { version: KEY_VERSION, key, keyId: keyIdOf(key), issuedAt: new Date(nowMs).toISOString(), rotateBy: rotateByFor(nowMs), retiring: [] };
|
||||
return { after: [...before.filter((k) => !orphans.includes(k)), key], record, done: { keyId: record.keyId, rotateBy: record.rotateBy } };
|
||||
});
|
||||
}
|
||||
|
||||
// Retiring keys whose grace has passed, or that the proxy no longer holds.
|
||||
const dueOf = (record, keys, nowMs) => record.retiring.filter((r) => Date.parse(r.retireAt) <= nowMs || !keys.includes(r.key));
|
||||
|
||||
export async function rotateKey(opts) {
|
||||
const c = context(opts);
|
||||
return change(c, "rotate", (before, current) => {
|
||||
if (!current) throw new TriageKeyError("triage-key-not-issued", "no Triage key is issued; use mosaic triage key issue");
|
||||
const nowMs = c.now();
|
||||
const orphans = orphansOf(c.configDir, before, current);
|
||||
const due = dueOf(current, before, nowMs);
|
||||
const keep = before.includes(current.key);
|
||||
const retiring = [...current.retiring.filter((r) => !due.includes(r)),
|
||||
...(keep ? [{ key: current.key, keyId: current.keyId, issuedAt: current.issuedAt, retireAt: retireAtFor(nowMs, c.proxy) }] : [])];
|
||||
if (retiring.length > MAX_RETIRING) throw new TriageKeyError("triage-key-failed", "too many keys are retiring; run mosaic triage key retire once their grace has passed");
|
||||
const key = newKey(c.configDir);
|
||||
const record = { version: KEY_VERSION, key, keyId: keyIdOf(key), issuedAt: new Date(nowMs).toISOString(), rotateBy: rotateByFor(nowMs), retiring };
|
||||
const drop = [...orphans, ...due.map((r) => r.key)];
|
||||
return {
|
||||
after: [...before.filter((k) => !drop.includes(k)), key], record,
|
||||
done: { keyId: record.keyId, rotateBy: record.rotateBy, old: keep ? { keyId: current.keyId, retireAt: retiring.at(-1).retireAt } : { keyId: current.keyId, lost: true } },
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function retireKeys(opts) {
|
||||
const c = context(opts);
|
||||
return change(c, "retire", (before, current) => {
|
||||
const nowMs = c.now();
|
||||
const orphans = orphansOf(c.configDir, before, current);
|
||||
const due = current ? dueOf(current, before, nowMs) : [];
|
||||
const record = current && due.length ? { ...current, retiring: current.retiring.filter((r) => !due.includes(r)) } : null;
|
||||
const drop = [...orphans, ...due.map((r) => r.key)];
|
||||
return { after: before.filter((k) => !drop.includes(k)), record, done: { droppedKeyIds: due.map((r) => r.keyId) } };
|
||||
});
|
||||
}
|
||||
|
||||
// Read only: the file, and when the proxy is set up, what its list holds. No lock, no write.
|
||||
// The fence is checked by name only, so status writes nothing, not even the lock's identity file.
|
||||
export async function keyStatus(opts) {
|
||||
const { configDir, system, uid, fileUid } = opts;
|
||||
const record = readKey(configDir, { uid, fileUid });
|
||||
const proxy = { state: "not-set-up", fence: false, leftoverTemps: tempsIn(keyPaths(configDir).dir).length };
|
||||
if (system?.proxy && Number.isInteger(system.proxy.port)) {
|
||||
try { lstatSync(join(system.dataRoot, "proxy", "mosaic-keys.uncertain")); proxy.fence = true; }
|
||||
catch (e) { if (e.code !== "ENOENT") proxy.fence = true; }
|
||||
try {
|
||||
const client = await loadManagementClient({ configDir, proxy: system.proxy });
|
||||
const keys = await client.getKeys();
|
||||
const prefix = sentinelPrefix(configDir);
|
||||
proxy.state = keys.some((k) => k.startsWith(prefix) && SECRET.test(k.slice(prefix.length))) ? "read" : "no-sentinel";
|
||||
proxy.holdsKey = record ? keys.includes(record.key) : null;
|
||||
proxy.retiringHeld = record ? record.retiring.map((r) => keys.includes(r.key)) : [];
|
||||
proxy.orphanKeyIds = orphansOf(configDir, keys, record).map(keyIdOf);
|
||||
} catch (e) { proxy.state = "unreadable"; proxy.code = typeof e?.code === "string" && /^proxy-[a-z-]+$/.test(e.code) ? e.code : "proxy-client-response"; }
|
||||
}
|
||||
return { record, proxy };
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
// #1873 triage-route-store: the owner's terminal verbs for the Triage route file,
|
||||
// <dataRoot>/triage/route.json (packages/webui/src/triage-route-store.mjs).
|
||||
//
|
||||
// mosaic triage route show
|
||||
// mosaic triage route set --model KEY --harness NAME --cap TOKENS --time-zone ZONE [--revision N]
|
||||
//
|
||||
// Both are human verbs: an agent run is refused before anything is read (exit 3), from this
|
||||
// process's environment and the one the command was given, as the bus and Console lifecycle verbs
|
||||
// refuse it. `show` with no file prints "not set" and exits 0. Without --revision a write
|
||||
// compares with the revision read under the store's lock; pass --revision from `show` to make the
|
||||
// write conditional on what was shown (0: only when no route is set yet).
|
||||
//
|
||||
// Nothing here wires the route into the Triage host: the Console keeps `route: null` until the
|
||||
// wiring slice. `set` checks the harness against the repository's harness modules; it does not
|
||||
// check the model key against a catalogue, since none exists outside an organization's bus yet.
|
||||
//
|
||||
// mosaic triage key issue | rotate | retire | status
|
||||
//
|
||||
// Triage's own model proxy client key (packages/cli/src/triage-key.mjs). Human verbs as well,
|
||||
// refused in an agent run before anything is read. No output names a key, only its id.
|
||||
import { lstatSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { readRoute, RouteStoreError, writeRoute } from "../../webui/src/triage-route-store.mjs";
|
||||
import { loadSystem } from "./config.mjs";
|
||||
import { configDir } from "../../organization/src/organization-config.mjs";
|
||||
import { issueKey, keyPaths, keyStatus, retireKeys, rotateKey, TriageKeyError } from "./triage-key.mjs";
|
||||
import { CliError } from "./errors.mjs";
|
||||
import { refuseInsideAgent } from "./transport.mjs";
|
||||
|
||||
export const TRIAGE_USAGE = "mosaic triage route show | set --model KEY --harness NAME --cap TOKENS --time-zone ZONE [--revision N] | key issue | rotate | retire | status";
|
||||
const KEY_VERBS = ["issue", "rotate", "retire", "status"];
|
||||
const HARNESS_ROOT = fileURLToPath(new URL("../../plugins/harness/", import.meta.url));
|
||||
const VALUES = ["--model", "--harness", "--cap", "--time-zone", "--revision"];
|
||||
const WHOLE = /^(0|[1-9][0-9]*)$/;
|
||||
// The actor every terminal write records: the instance owner, the only person who runs this verb.
|
||||
const ACTOR = "owner";
|
||||
|
||||
const usage = (why) => new CliError(`${why}\nusage: ${TRIAGE_USAGE}`, 4);
|
||||
|
||||
// Option names, never values, in a refusal.
|
||||
function parse(args) {
|
||||
const values = {}, positional = [];
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const a = args[i];
|
||||
if (VALUES.includes(a)) {
|
||||
if (i + 1 >= args.length) throw usage(`${a} needs one value`);
|
||||
if (Object.hasOwn(values, a)) throw usage(`${a} is given twice`);
|
||||
values[a] = args[++i];
|
||||
} else if (a.startsWith("--")) throw usage("unknown option");
|
||||
else positional.push(a);
|
||||
}
|
||||
return { values, positional };
|
||||
}
|
||||
|
||||
function whole(text, name) {
|
||||
if (!WHOLE.test(text)) throw new CliError(`triage-route-invalid: ${name} must be a whole number`, 2);
|
||||
return Number(text);
|
||||
}
|
||||
|
||||
function knownHarness(name) {
|
||||
if (!/^[a-z][a-z0-9-]{0,31}$/.test(name)) return false;
|
||||
try { return lstatSync(join(HARNESS_ROOT, name, "index.mjs")).isFile(); } catch { return false; }
|
||||
}
|
||||
|
||||
function storeError(error) {
|
||||
if (!(error instanceof RouteStoreError)) throw error;
|
||||
return new CliError(`${error.code}: ${error.message}`, error.code === "triage-route-invalid" ? 2 : 3);
|
||||
}
|
||||
|
||||
function show(route) {
|
||||
if (!route) return "triage route: not set\n";
|
||||
const { cap } = route;
|
||||
return [
|
||||
`triage route: revision ${route.revision}`,
|
||||
`model: ${route.model}`,
|
||||
`harness: ${route.harness}`,
|
||||
`cap: ${cap.limit} tokens a day, resets ${cap.reset} ${cap.timeZone}, counted since ${cap.since}`,
|
||||
`updated: ${route.updatedAt} by ${route.updatedBy}`,
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
// A key error prints its code and fixed words. Anything else becomes one fixed line, so no value
|
||||
// that an unexpected error might carry reaches the terminal.
|
||||
function keyError(error) {
|
||||
if (error instanceof CliError) return error;
|
||||
if (error instanceof TriageKeyError) return new CliError(`${error.code}: ${error.message}`, error.exitCode);
|
||||
return new CliError("triage-key-failed: the key verb stopped on an unexpected error; run mosaic triage key status", 3);
|
||||
}
|
||||
|
||||
const age = (ms) => {
|
||||
const m = Math.max(0, Math.floor(ms / 60_000));
|
||||
return `${Math.floor(m / 1440)}d ${Math.floor((m % 1440) / 60)}h ${m % 60}m`;
|
||||
};
|
||||
const ids = (list) => (list.length ? list.join(", ") : "none");
|
||||
|
||||
function statusText({ record, proxy }, nowMs, file) {
|
||||
const lines = [`triage key: ${record ? "issued" : "not issued"}`, `file: ${file}`];
|
||||
const rotateDue = record && Date.parse(`${record.rotateBy}T00:00:00Z`) <= nowMs;
|
||||
const retireDue = record ? record.retiring.filter((r) => Date.parse(r.retireAt) <= nowMs) : [];
|
||||
if (record) {
|
||||
lines.push(`key id: ${record.keyId}`, `issued: ${record.issuedAt} (age ${age(nowMs - Date.parse(record.issuedAt))})`, `rotate by: ${record.rotateBy}${rotateDue ? " (due)" : ""}`);
|
||||
record.retiring.forEach((r, i) => {
|
||||
const held = proxy.retiringHeld?.[i];
|
||||
lines.push(`retiring: ${r.keyId}, live until a retire after ${r.retireAt}${Date.parse(r.retireAt) <= nowMs ? " (due)" : ""}${held === false ? " (not in the proxy list)" : ""}`);
|
||||
});
|
||||
}
|
||||
const state = {
|
||||
"not-set-up": "not set up for this instance (no proxy.json)",
|
||||
"no-sentinel": "its key list has no sentinel for this instance",
|
||||
unreadable: `not read (${proxy.code})`,
|
||||
read: record ? (proxy.holdsKey ? "holds the key" : "does not hold the key") : "read",
|
||||
}[proxy.state];
|
||||
lines.push(`proxy: ${state}`);
|
||||
if (proxy.fence) lines.push("proxy fence: set, an earlier proxy write has an uncertain outcome");
|
||||
if (proxy.leftoverTemps) lines.push(`leftover temp files in the triage secrets directory: ${proxy.leftoverTemps} (the next issue, rotate or retire removes them)`);
|
||||
if (proxy.orphanKeyIds?.length) lines.push(`keys in the Triage namespace the file does not hold: ${ids(proxy.orphanKeyIds)}`);
|
||||
let next;
|
||||
if (proxy.fence) next = "restart the proxy, then mosaic proxy fence clear --proxy-restarted";
|
||||
else if (proxy.state !== "read") next = proxy.state === "not-set-up" ? "set up the model proxy first (mosaic proxy init)" : "check the proxy with mosaic proxy status";
|
||||
else if (!record) next = "mosaic triage key issue";
|
||||
else if (!proxy.holdsKey || rotateDue) next = "mosaic triage key rotate";
|
||||
else if (retireDue.length || proxy.leftoverTemps || proxy.orphanKeyIds?.length || proxy.retiringHeld?.includes(false)) next = "mosaic triage key retire";
|
||||
else next = "nothing";
|
||||
lines.push(`next: ${next}`, "");
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
async function keyCommand(sub, args, io, deps) {
|
||||
if (!KEY_VERBS.includes(sub)) throw usage("unknown triage key command");
|
||||
if (args.length) throw usage(args[0].startsWith("--") ? "unknown option" : "unexpected argument");
|
||||
try {
|
||||
const system = deps.system ?? loadSystem({ env: io.env });
|
||||
const dir = configDir(io.env);
|
||||
const now = deps.now ? () => deps.now().getTime() : Date.now;
|
||||
const opts = { configDir: dir, system, now, uid: deps.triageKeyUid, fileUid: deps.triageKeyFileUid, hook: deps.triageKeyHook };
|
||||
if (sub === "status") {
|
||||
io.stdout.write(statusText(await keyStatus(opts), now(), keyPaths(dir).file));
|
||||
return;
|
||||
}
|
||||
if (sub === "issue") {
|
||||
const r = await issueKey(opts);
|
||||
io.stdout.write(`triage key issued: ${r.keyId}, rotate by ${r.rotateBy}\nfile: ${keyPaths(dir).file}\n`);
|
||||
if (r.removedKeyIds.length) io.stdout.write(`removed keys this file did not hold: ${ids(r.removedKeyIds)}\n`);
|
||||
return;
|
||||
}
|
||||
if (sub === "rotate") {
|
||||
const r = await rotateKey(opts);
|
||||
io.stdout.write(`triage key rotated: ${r.keyId}, rotate by ${r.rotateBy}\n`);
|
||||
io.stdout.write(r.old.lost
|
||||
? `old key ${r.old.keyId} was not in the proxy list; nothing to retire\n`
|
||||
: `old key ${r.old.keyId} stays live until mosaic triage key retire runs at or after ${r.old.retireAt}\n`);
|
||||
if (r.removedKeyIds.length) io.stdout.write(`removed: ${ids(r.removedKeyIds)}\n`);
|
||||
return;
|
||||
}
|
||||
const r = await retireKeys(opts);
|
||||
io.stdout.write(r.removedKeyIds.length ? `triage key retire: removed ${ids(r.removedKeyIds)}\n` : "triage key retire: nothing to remove\n");
|
||||
} catch (e) { throw keyError(e); }
|
||||
}
|
||||
|
||||
export function triageCommand(rest, io, deps = {}) {
|
||||
refuseInsideAgent(process.env);
|
||||
refuseInsideAgent(io.env);
|
||||
const [noun, sub, ...args] = rest;
|
||||
if (noun === "key" && sub !== undefined) return keyCommand(sub, args, io, deps);
|
||||
if (noun !== "route" || !["show", "set"].includes(sub)) throw usage("unknown triage command");
|
||||
const { values, positional } = parse(args);
|
||||
if (positional.length) throw usage("unexpected argument");
|
||||
const dataRoot = () => (deps.system ?? loadSystem({ env: io.env })).dataRoot;
|
||||
if (sub === "show") {
|
||||
if (Object.keys(values).length) throw usage("show takes no options");
|
||||
let route;
|
||||
try { route = readRoute(dataRoot()); } catch (e) { throw storeError(e); }
|
||||
io.stdout.write(show(route));
|
||||
return;
|
||||
}
|
||||
for (const name of ["--model", "--harness", "--cap", "--time-zone"]) if (!Object.hasOwn(values, name)) throw usage(`set needs ${name}`);
|
||||
if (!knownHarness(values["--harness"])) throw new CliError("triage-route-invalid: no harness module has that name", 2);
|
||||
const input = {
|
||||
model: values["--model"], harness: values["--harness"], limit: whole(values["--cap"], "--cap"),
|
||||
timeZone: values["--time-zone"], by: ACTOR,
|
||||
...(Object.hasOwn(values, "--revision") ? { revision: whole(values["--revision"], "--revision") } : {}),
|
||||
};
|
||||
let route;
|
||||
try { route = writeRoute(dataRoot(), input, deps.now ? { now: deps.now } : {}); } catch (e) { throw storeError(e); }
|
||||
io.stdout.write(`triage route set: revision ${route.revision}\n`);
|
||||
}
|
||||
@@ -89,6 +89,8 @@ function organizations({ send = true } = {}) {
|
||||
calls.push({ verb, args, opts });
|
||||
if (verb === 'autonomy.review.console') return { reviewed: args.decisionClass };
|
||||
if (args.revision !== state.revision) throw new BusReadError('revision-conflict');
|
||||
// E2E6 fix 7: the bus refuses policy out of the loop here; the route forwards the code alone.
|
||||
if (args.autonomy.policy === 'out of the loop') throw new BusReadError('autonomy-precondition');
|
||||
const { notices, reverseWindowHours, authorityResolver, ...levels } = args.autonomy;
|
||||
state = { revision: REV(parseInt(state.revision, 16) + 1), levels, autonomy: { notices, reverseWindowHours, ...(authorityResolver ? { authorityResolver } : {}) } };
|
||||
return { revision: state.revision, transaction: `tx-${parseInt(state.revision, 16)}` };
|
||||
@@ -259,6 +261,21 @@ test('autonomy reads, saves with the panel\'s revision check and records a revie
|
||||
assert.equal((await page(c.port, 'GET', '/api/orgs/alpha/autonomy')).body.revision, REV(5));
|
||||
c.calls.splice(0);
|
||||
|
||||
// E2E6 fix 7: an autonomy-precondition the route sends without a reason still names the one check the
|
||||
// terminal can see from its read and the document it sent (notices off while a class moves away),
|
||||
// and the general guidance becomes the next line.
|
||||
r = await mosaic(env, ['org', 'autonomy', 'alpha', 'set', '--revision', REV(5), '--policy', 'out']);
|
||||
assert.equal(r.status, 3, r.stderr);
|
||||
assert.match(r.stderr, /^mosaic: autonomy set refused \(autonomy-precondition\): owner notices are off; a class near the loop, or one moving away from it, needs them on \(--notices on\)$/m);
|
||||
assert.match(r.stderr, /^mosaic: next: this move needs a separate resolver/m);
|
||||
const { preconditionSeen } = await import('../src/org-owner.mjs');
|
||||
const shown = { levels: { ...LOOP, merge: 'near the loop' } };
|
||||
assert.equal(preconditionSeen(shown, { ...LOOP, merge: 'near the loop', notices: true }), undefined);
|
||||
assert.equal(preconditionSeen(shown, { ...LOOP, notices: false }), undefined, 'moving back toward the loop needs no notices');
|
||||
assert.match(preconditionSeen(shown, { ...LOOP, merge: 'near the loop', notices: false }), /^owner notices are off/);
|
||||
assert.match(preconditionSeen({ levels: LOOP }, { ...LOOP, authority: 'out of the loop', notices: false }), /^owner notices are off/);
|
||||
c.calls.splice(0);
|
||||
|
||||
r = await mosaic(env, ['org', 'autonomy', 'alpha', 'review', 'merge']);
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
assert.equal(r.stdout, 'recorded your trail review for merge on alpha\n');
|
||||
|
||||
@@ -67,6 +67,15 @@ test('two organization buses are isolated and refusals never select a sibling',
|
||||
writeFileSync(join(alpha.root, 'bus-host/host.json'), JSON.stringify(staleHost), { mode: 0o600 });
|
||||
writeFileSync(join(alpha.root, 'bus-host/host.lock'), JSON.stringify(staleHost), { mode: 0o600 });
|
||||
writeFileSync(join(alpha.root, 'bus/writer.lock'), JSON.stringify({ pid: 2147483647, at: '2026-01-01T00:00:00Z' }), { mode: 0o600 });
|
||||
// E2E6 fix 1: status, start, stop and restart refuse a dead host's lock with the message unchanged and a
|
||||
// next line naming the verb that clears it.
|
||||
for (const args of [['status', 'alpha', '--json'], ['start', 'alpha', '--no-launch', '--detach'], ['stop', 'alpha'], ['restart', 'alpha']]) {
|
||||
const r = spawnSync(join(REPO, 'scripts/mosaic'), ['bus', ...args], { env, encoding: 'utf8', timeout: 30000 });
|
||||
assert.equal(r.status, 3, `${args[0]}: ${r.stderr}`);
|
||||
assert.match(r.stderr, /^mosaic: stale bus host lock$/m, args[0]);
|
||||
assert.match(r.stderr, /^mosaic: next: if the bus host died, clear it with mosaic bus recover alpha; recover refuses while the host still runs$/m, args[0]);
|
||||
}
|
||||
await assert.rejects(busStatus(ctx, 'alpha'), e => e.message === 'stale bus host lock' && e.exitCode === 3 && /mosaic bus recover alpha/.test(e.next));
|
||||
const recovery = spawnSync(join(REPO, 'scripts/mosaic'), ['bus', 'recover', 'alpha'], { env, encoding: 'utf8' });
|
||||
assert.equal(recovery.status, 0, recovery.stderr);
|
||||
const restarted = await busStart(ctx, 'alpha', { detach: true, noLaunch: true });
|
||||
|
||||
@@ -417,3 +417,60 @@ test('a detached console without the dev owner has no supervisor, so it refuses
|
||||
assert.equal(start.stderr, '');
|
||||
assert.equal((await consoleStop(ctx)).stopped, true);
|
||||
});
|
||||
|
||||
// E2E6 fix 4: console start and stop clear a start.lock whose named supervisor (pid and start time) is
|
||||
// gone, and never one whose holder still runs or that names no holder.
|
||||
test('E2E6 a start.lock whose holder is gone is cleared by stop and by start; a live or unnamed one refuses and stays', { timeout: 60000 }, async t => {
|
||||
const { startTimeOf } = await import('../src/host.mjs');
|
||||
const { ctx } = await instance(t);
|
||||
const dir = join(ctx.dataRoot, 'console'), lock = join(dir, 'start.lock');
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
// A process this test starts and lets end: its pid and start time name a supervisor that is gone.
|
||||
const child = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 30000)'], { stdio: 'ignore' });
|
||||
await new Promise(r => child.once('spawn', r));
|
||||
const deadHolder = { pid: child.pid, startTime: startTimeOf(child.pid) };
|
||||
assert.match(deadHolder.startTime, /^\d+$/);
|
||||
child.kill('SIGKILL');
|
||||
await new Promise(r => child.once('exit', r));
|
||||
|
||||
const warnings = [];
|
||||
writeFileSync(lock, JSON.stringify(deadHolder), { mode: 0o600 });
|
||||
assert.deepEqual(await consoleStop(ctx, { warn: s => warnings.push(s) }), { stopped: false });
|
||||
assert.deepEqual(warnings, [`mosaic: cleared a console start lock left by process ${child.pid}, which is gone\n`]);
|
||||
assert.equal(existsSync(lock), false);
|
||||
assert.deepEqual(readdirSync(dir).filter(x => x.startsWith('start.lock')), []);
|
||||
|
||||
// A live pid with another start time is a reused pid: its holder is gone too.
|
||||
writeFileSync(lock, JSON.stringify({ pid: process.pid, startTime: '1' }), { mode: 0o600 });
|
||||
warnings.length = 0;
|
||||
const result = await consoleStart(ctx, { detach: true, port: 'auto', warn: s => warnings.push(s) });
|
||||
assert.deepEqual(warnings, [`mosaic: cleared a console start lock left by process ${process.pid}, which is gone\n`]);
|
||||
assert.equal(existsSync(lock), false, 'the start released its own lock');
|
||||
assert.equal((await consoleStop(ctx)).stopped, true);
|
||||
assert.ok(Number.isSafeInteger(result.pid));
|
||||
|
||||
// A live holder refuses on start and stop, and the lock stays as it was.
|
||||
const live = JSON.stringify({ pid: process.pid, startTime: startTimeOf(process.pid) });
|
||||
writeFileSync(lock, live, { mode: 0o600 });
|
||||
await assert.rejects(consoleStop(ctx), e => e.message === `console start lock is held by process ${process.pid}, which still runs; wait for its start or stop to finish`);
|
||||
await assert.rejects(consoleStart(ctx, { detach: true, port: 'auto' }), /which still runs/);
|
||||
assert.equal(readFileSync(lock, 'utf8'), live);
|
||||
// A lock that names no holder (empty: a holder between its open and its write; or bad JSON) stays too.
|
||||
for (const body of ['', '{"pid":', JSON.stringify({ pid: 0, startTime: '1' }), JSON.stringify({ pid: child.pid, startTime: 7 })]) {
|
||||
writeFileSync(lock, body, { mode: 0o600 });
|
||||
await assert.rejects(consoleStop(ctx), /console start lock exists and names no holder/);
|
||||
assert.equal(readFileSync(lock, 'utf8'), body);
|
||||
}
|
||||
// f6c review P3-1: a lock its holder marked released (a clear put it back after the release) is
|
||||
// cleared; a released marker with anything else in it names no holder and stays.
|
||||
writeFileSync(lock, JSON.stringify({ released: true }), { mode: 0o600 });
|
||||
warnings.length = 0;
|
||||
assert.deepEqual(await consoleStop(ctx, { warn: s => warnings.push(s) }), { stopped: false });
|
||||
assert.deepEqual(warnings, ['mosaic: cleared a console start lock its holder had released\n']);
|
||||
assert.equal(existsSync(lock), false);
|
||||
const odd = JSON.stringify({ released: true, pid: 1 });
|
||||
writeFileSync(lock, odd, { mode: 0o600 });
|
||||
await assert.rejects(consoleStop(ctx), /console start lock exists and names no holder/);
|
||||
assert.equal(readFileSync(lock, 'utf8'), odd);
|
||||
rmSync(lock);
|
||||
});
|
||||
@@ -136,3 +136,55 @@ test('T1 mosaic org definitions: writes go through the bus and its secret check,
|
||||
await assert.rejects(orgCommand(['definitions', 'acme', 'remove', 'copy', '--if-rev', '1'], x), (e) => e.exitCode === 3 && /organization bus/.test(e.message));
|
||||
assert.deepEqual(readFileSync(file), before);
|
||||
});
|
||||
|
||||
// E2E6 fix 2: an unknown definition, an unknown organization, a bad id and a bad name each end in
|
||||
// one usage or refusal line: no stack trace and no host path.
|
||||
test('E2E6 mosaic org definitions: unknown names, an unknown org and a bad id give one line, no stack and no path', async (t) => {
|
||||
const root = tmp(t);
|
||||
const f = fixture(root, 'acme');
|
||||
const { run } = await import('../src/cli.mjs');
|
||||
const cases = [
|
||||
[['acme', 'show', 'ghost'], 3, 'mosaic: definition-missing: definitions declares no ghost; list them with mosaic org definitions acme list'],
|
||||
[['acme', 'diff', 'ghost'], 3, 'mosaic: definition-missing: definitions declares no ghost; list them with mosaic org definitions acme list'],
|
||||
[['acme', 'show', 'Bad Name'], 3, 'mosaic: definition-missing: definitions declares no definition by that name; list them with mosaic org definitions acme list'],
|
||||
[['nosuch', 'list'], 3, 'mosaic: unknown-organization: this instance has no organization nosuch; list them with mosaic org list'],
|
||||
[['nosuch', 'show', 'x'], 3, 'mosaic: unknown-organization: this instance has no organization nosuch; list them with mosaic org list'],
|
||||
];
|
||||
for (const [args, exit, line] of cases) {
|
||||
const x = io(f.env);
|
||||
assert.equal(await run(['org', 'definitions', ...args], x, {}), exit, args.join(' '));
|
||||
assert.equal(x.err.text, `${line}\n`, args.join(' '));
|
||||
assert.ok(!x.err.text.includes(root) && !/\n\s+at /.test(x.err.text), args.join(' '));
|
||||
}
|
||||
for (const args of [['Bad/Id', 'list'], ['../x', 'show', 'y']]) {
|
||||
const x = io(f.env);
|
||||
assert.equal(await run(['org', 'definitions', ...args], x, {}), 4, args.join(' '));
|
||||
assert.match(x.err.text, /^mosaic: invalid organization id: an id is 1 to 64 of a-z/);
|
||||
assert.match(x.err.text, /\nmosaic org definitions templates \| definitions ID list/);
|
||||
assert.ok(!x.err.text.includes(root) && !/\n\s+at /.test(x.err.text));
|
||||
}
|
||||
});
|
||||
|
||||
test('E2E6 definitionsFailure: a raw filesystem error is named by its operation and code, a message path is cut, an unknown error says only that it failed', async () => {
|
||||
const { definitionsFailure } = await import('../src/org-definitions.mjs');
|
||||
const fsError = (code, syscall) => Object.assign(new Error(`${code}: no such file, open '/home/someone/.config/x/acme.json'`), { code, syscall, path: '/home/someone/.config/x/acme.json' });
|
||||
let e = definitionsFailure(fsError('EACCES', 'open'), 'acme');
|
||||
assert.deepEqual([e.code, e.exitCode, e.message], ['organization-unreadable', 3, 'organization-unreadable: cannot open the file of organization acme (EACCES)']);
|
||||
e = definitionsFailure(Object.assign(new Error("organization file /srv/x/acme.json is not valid"), { code: 'organization-invalid' }), 'acme');
|
||||
assert.equal(e.message, 'organization-invalid: organization file <path> is not valid');
|
||||
e = definitionsFailure(new TypeError('Cannot read properties of undefined'), 'acme');
|
||||
assert.deepEqual([e.code, e.exitCode, e.message], ['definitions-failed', 1, 'definitions-failed: the definitions command failed']);
|
||||
// f6c review P3-2: only the organization file missing means no organization.
|
||||
e = definitionsFailure(fsError('ENOENT', 'open'), 'acme');
|
||||
assert.deepEqual([e.code, e.message], ['unknown-organization', 'unknown-organization: this instance has no organization acme; list them with mosaic org list']);
|
||||
const rolesGone = Object.assign(new Error("ENOENT: no such file or directory, scandir '/home/someone/roles'"), { code: 'ENOENT', syscall: 'scandir', path: '/home/someone/roles' });
|
||||
e = definitionsFailure(rolesGone, 'templates');
|
||||
assert.deepEqual([e.code, e.exitCode, e.message], ['definitions-unreadable', 3, 'definitions-unreadable: cannot scandir a file the definitions command reads (ENOENT)']);
|
||||
e = definitionsFailure(rolesGone, 'acme');
|
||||
assert.equal(e.code, 'organization-unreadable');
|
||||
// f6c review P3-3: a path after ':' or inside backticks is cut.
|
||||
e = definitionsFailure(Object.assign(new Error('organization file:/srv/x/acme.json is not valid'), { code: 'organization-invalid' }), 'acme');
|
||||
assert.equal(e.message, 'organization-invalid: organization file:<path> is not valid');
|
||||
e = definitionsFailure(Object.assign(new Error('bad role at `/srv/roles/x.json`'), { code: 'organization-invalid' }), 'acme');
|
||||
assert.equal(e.message, 'organization-invalid: bad role at `<path>`');
|
||||
});
|
||||
@@ -97,3 +97,55 @@ test('SP4 an agent shell refuses every pack, board and workflow word, pack list
|
||||
assert.deepEqual(s.calls, []);
|
||||
assert.deepEqual(readFileSync(s.file), before);
|
||||
});
|
||||
|
||||
// E2E6 fix 3: the real transport shape. humanTransport throws a CliError whose message and .code are
|
||||
// the bus code alone (packages/cli/src/transport.mjs); pack, board and workflow refusals must still
|
||||
// gain their hint, as template save's do, and a CliError with its own next line passes unchanged.
|
||||
test('E2E6 pack, board and workflow refusals from a CliError-shaped transport print the hint', async (t) => {
|
||||
const { CliError } = await import('../src/errors.mjs');
|
||||
const { busExit, busNotRunning } = await import('../src/transport.mjs');
|
||||
const root = tmp(t);
|
||||
const f = fixture(root, 'acme');
|
||||
const boot = bootConfig({ system: loadSystem({ env: f.env }), businessId: 'acme', env: f.env });
|
||||
const b = await startBroker({ dataRoot: f.dataRoot, businesses: boot.businesses, organization: boot.organization });
|
||||
t.after(() => b.close());
|
||||
const human = b.broker.bindHuman({ business: 'acme', human: f.doc.human, via: 'cli', outsideAgent: true });
|
||||
let down = false;
|
||||
const deps = { system: { dataRoot: f.dataRoot }, transport: () => async (verb, args = {}) => {
|
||||
if (down) throw busNotRunning('acme');
|
||||
try { return structuredClone(await b.broker.request(human, { verb, args })); }
|
||||
catch (e) { if (!(e instanceof BusError)) throw e; throw Object.assign(new CliError(e.code, busExit(e.code)), { code: e.code }); }
|
||||
} };
|
||||
const run = async (args) => { const x = io(f.env); await main(['org', ...args], x, deps); return JSON.parse(x.out.text); };
|
||||
const hinted = (e) => typeof e.code === 'string' && e instanceof CliError && e.message.startsWith(`${e.code}: `) && e.message.length > e.code.length + 10;
|
||||
|
||||
await assert.rejects(run(['pack', 'preview', 'acme', 'no-such-pack']), (e) => e.code === 'starter-pack-not-found' && e.message === 'starter-pack-not-found: no installed, shipped or saved pack has that name');
|
||||
const spec = join(root, 'board.json');
|
||||
writeFileSync(spec, JSON.stringify({ columns: [{ state: 'todo', label: 'Backlog' }], layout: 'kanban' }));
|
||||
await assert.rejects(run(['board', 'set', 'acme', spec]), (e) => hinted(e) && e.exitCode === busExit(e.code));
|
||||
await assert.rejects(run(['workflow', 'remove', 'acme', 'ghost']), (e) => hinted(e) && e.exitCode === busExit(e.code));
|
||||
|
||||
// A stopped bus keeps its own message and next line.
|
||||
down = true;
|
||||
await assert.rejects(run(['pack', 'preview', 'acme', 'no-such-pack']), (e) => e.code === 'bus-not-running' && e.exitCode === 3
|
||||
&& e.message === 'bus-not-running: the bus for acme is not running, so the request was not sent' && /mosaic bus start acme/.test(e.next) && /mosaic bus recover acme/.test(e.next));
|
||||
});
|
||||
|
||||
// Ruling 2026-11-14: "If I choose a starter pack and apply it, that is a decision!" The owner's apply
|
||||
// hires the proposals in the same act; pack hire runs the same loop on the packs entry and hires none twice.
|
||||
test('PD mosaic org pack apply hires the proposals; pack hire on the same record hires nothing twice', async (t) => {
|
||||
const s = await setup(t);
|
||||
assert.ok(PACKS_USAGE.includes('pack hire ID PACK [--project P]'));
|
||||
const preview = await s.run(['pack', 'preview', 'acme', 'coding']);
|
||||
const applied = await s.run(['pack', 'apply', 'acme', 'coding', '--digest', preview.digest]);
|
||||
assert.deepEqual(applied.hires.map((x) => [x.name, x.state]), [['pm-1', 'hired'], ['coder-1', 'hired'], ['reviewer-1', 'hired']]);
|
||||
for (const x of applied.hires) assert.match(String(x.decision), /^[0-9a-f-]{36}$/);
|
||||
const doc = s.doc();
|
||||
for (const x of applied.hires) { assert.equal(doc.roles[x.name].hireDecision, x.decision); assert.ok(doc.launch.instances.includes(x.name), x.name); }
|
||||
|
||||
const again = await s.run(['pack', 'hire', 'acme', 'coding']);
|
||||
assert.deepEqual(again.hires.map((x) => [x.name, x.state]), [['pm-1', 'exists'], ['coder-1', 'exists'], ['reviewer-1', 'exists']]);
|
||||
assert.deepEqual(s.calls.at(-1), ['pack.hire', ['pack']]);
|
||||
await assert.rejects(s.run(['pack', 'hire', 'acme', 'ghost-pack']), (e) => e.code === 'pack-not-applied' && /apply it first/.test(e.message));
|
||||
await assert.rejects(s.run(['pack', 'hire', 'acme']), (e) => e.exitCode === 4 && e.message === PACKS_USAGE);
|
||||
});
|
||||
@@ -37,8 +37,13 @@ test('organization host claim refuses a stale lock without removing it', t => {
|
||||
const stale = { pid: 99999999, startTime: '0', business: 'alpha', startedAt: 'old' };
|
||||
writeFileSync(hostLock(root), JSON.stringify(stale), { mode: 0o600 });
|
||||
const mine = { pid: process.pid, startTime: startTimeOf(process.pid), business: 'alpha', startedAt: 'now' };
|
||||
assert.throws(() => claimHostLock(root, mine, { refuseStale: true }), /stale.*lock/i);
|
||||
// E2E6 fix 1: the message stays; the next line names the verb that clears the dead host.
|
||||
assert.throws(() => claimHostLock(root, mine, { refuseStale: true }), e => e.message === 'stale bus host lock' && e.exitCode === 3
|
||||
&& e.next === 'if the bus host died, clear it with mosaic bus recover alpha; recover refuses while the host still runs');
|
||||
assert.deepEqual(JSON.parse(readFileSync(hostLock(root), 'utf8')), stale);
|
||||
// A lock naming no valid organization id still names the verb, with a placeholder.
|
||||
writeFileSync(hostLock(root), JSON.stringify({ ...stale, business: '../x\nsecret' }), { mode: 0o600 });
|
||||
assert.throws(() => claimHostLock(root, mine, { refuseStale: true }), e => e.next === 'if the bus host died, clear it with mosaic bus recover <org>; recover refuses while the host still runs');
|
||||
});
|
||||
|
||||
import { busStatus } from '../src/org-bus.mjs';
|
||||
|
||||
@@ -40,7 +40,7 @@ test('SP8 mosaic org template save: --preview writes nothing, --digest writes th
|
||||
const before = readFileSync(s.file);
|
||||
const preview = await s.run(['template', 'save', 'acme', 'acme-shape', '--preview']);
|
||||
assert.match(preview.digest, /^[0-9a-f]{64}$/);
|
||||
assert.ok(Array.isArray(preview.freeText) && Array.isArray(preview.replacements));
|
||||
assert.ok(Array.isArray(preview.freeText) && Array.isArray(preview.mentions) && !('replacements' in preview));
|
||||
assert.ok(!existsSync(s.saved('acme-shape')), 'preview writes no file');
|
||||
|
||||
const out = await s.run(['template', 'save', 'acme', 'acme-shape', '--digest', preview.digest]);
|
||||
@@ -49,7 +49,9 @@ test('SP8 mosaic org template save: --preview writes nothing, --digest writes th
|
||||
assert.equal(lstatSync(s.saved('acme-shape')).mode & 0o777, 0o600);
|
||||
assert.deepEqual(readFileSync(s.file), before, 'save writes nothing to the organization file');
|
||||
|
||||
await assert.rejects(s.run(['template', 'save', 'acme', 'acme-shape', '--digest', preview.digest]), (e) => e.code === 'invalid-request' && /already saved/.test(e.message));
|
||||
await assert.rejects(s.run(['template', 'save', 'acme', 'acme-shape', '--digest', preview.digest]), (e) => e.code === 'template-exists' && e.exitCode === 2
|
||||
&& e.message === 'template-exists: a template of this name is already saved for your account; nothing was written'
|
||||
&& /under another name/.test(e.next) && /mosaic org template list acme/.test(e.next));
|
||||
await assert.rejects(s.run(['template', 'save', 'acme', 'other', '--digest', preview.digest]), (e) => e.code === 'pack-plan-stale' && /preview again/.test(e.message));
|
||||
const listed = await s.run(['template', 'list', 'acme']);
|
||||
assert.deepEqual(listed.templates.map((x) => x.name), ['acme-shape']);
|
||||
|
||||
@@ -12,7 +12,6 @@ test('organization CLI renders, validates, creates, updates and initializes git'
|
||||
const file = join(home, 'alpha.json'); const invoke = (...args) => { const r = run(env, ...args); assert.equal(r.status, 0, r.stderr); return r.stdout; };
|
||||
invoke('org', 'template', 'render', 'alpha', '--fixture', 'local', '--output', file);
|
||||
invoke('org', 'validate', file); invoke('org', 'create', 'alpha', '--from', file);
|
||||
assert.deepEqual(JSON.parse(invoke('org', 'system-types', 'enabled', 'alpha')), { organization: 'alpha', enabled: [] });
|
||||
const bootCheck = spawnSync(process.execPath, ['--input-type=module', '-e', `import {loadSystem, bootConfig} from './packages/cli/src/config.mjs'; const system=loadSystem({env:process.env, instance:'orgtest'}); bootConfig({system,businessId:'alpha',env:process.env});`], { cwd: repo, env, encoding: 'utf8' }); assert.equal(bootCheck.status, 0, bootCheck.stderr);
|
||||
let info = JSON.parse(invoke('org', 'show', 'alpha', '--json')); assert.equal(info.id, 'alpha'); assert.equal(JSON.parse(invoke('org', 'list', '--json')).length, 1);
|
||||
invoke('org', 'update', 'alpha', '--from', file, '--if-revision', String(info.revision));
|
||||
|
||||
@@ -306,7 +306,7 @@ test('#811 migration readers follow the engine order and refuse malformed pairs'
|
||||
assert.notEqual(engineSource,source);
|
||||
const engine=await import(`data:text/javascript;base64,${Buffer.from(engineSource).toString('base64')}`);
|
||||
const pairs=engine.migrations.map(({from,to})=>[from,to]);
|
||||
assert.equal(pairs.length,20);assert.deepEqual(pairs.at(-1),['3u','3v']);
|
||||
assert.equal(pairs.length,21);assert.deepEqual(pairs.at(-1),['3v','3w']);
|
||||
const release=readFileSync(join(ROOT,'scripts/stack-release.sh'),'utf8');
|
||||
const fn=(name)=>{const m=release.match(new RegExp(`^${name}\\(\\) \{[\\s\\S]*?^\}`, 'm'));assert.ok(m,name);return m[0]};
|
||||
const functions=['copy_schema','target_schema','plan_steps'].map(fn).join('\n');
|
||||
@@ -885,7 +885,7 @@ const COUNTED=/^COUNTED="([^"]*)"$/m.exec(srText)[1].split(' ');
|
||||
const STORE_JS=/^STORE_JS='([\s\S]*?)'$/m.exec(srText)[1];
|
||||
// sage-1163's list 2, written out so that a table dropped from the script's COUNTED fails T45 as
|
||||
// well as T46.
|
||||
const LISTED=['role_claims','thread_claims','decision_events','messages','deliveries','task_snapshots','projects','project_archives','threads','sessions','session_defaults','thread_opens','thread_shares','instance_names','usage_records','session_ops','message_cancels','request_events','request_effects','request_snapshots','request_snapshot_events','request_project_events','project_system_types'];
|
||||
const LISTED=['role_claims','thread_claims','decision_events','messages','deliveries','task_snapshots','projects','project_archives','threads','sessions','session_defaults','thread_opens','thread_shares','instance_names','usage_records','session_ops','message_cancels','request_events','request_effects','request_snapshots','request_snapshot_events','request_project_events'];
|
||||
const LATE='2999-01-01T00:00:00.000Z';
|
||||
const addRow=(file,table,at=LATE)=>{const db=new DatabaseSync(file);db.exec(`CREATE TABLE IF NOT EXISTS ${table} (seq INTEGER PRIMARY KEY, at TEXT NOT NULL)`);db.prepare(`INSERT INTO ${table} (at) VALUES (?)`).run(at);db.close()};
|
||||
|
||||
@@ -903,7 +903,7 @@ test('T45 row 181 items 2 and 3: the restore guard counts events and every COUNT
|
||||
both(store('3f.sqlite',['events'],['events','instance_names']),'1\t1 event(s)\n');
|
||||
both(store('none.sqlite',[],['instance_names']),'0\t0 event(s)\n');
|
||||
});
|
||||
for(const x of ['instance_names','usage_records','project_system_types'])await t.test(`one ${x} row and no event refuses before any stop; --events 1 restores`,async(t)=>{
|
||||
for(const x of ['instance_names','usage_records','request_project_events'])await t.test(`one ${x} row and no event refuses before any stop; --events 1 restores`,async(t)=>{
|
||||
const e=await mk(t);await seed(e);
|
||||
assert.equal((await run(e,'activate',C,'acme','--migrate')).code,0);const act=pointer(e).activation;
|
||||
addRow(e.store,x);
|
||||
@@ -925,7 +925,7 @@ test('T45 row 181 items 2 and 3: the restore guard counts events and every COUNT
|
||||
assert.equal(r.code,3,r.out+r.err);assert.ok(r.err.endsWith(`stack-release: refusing restore-mismatch: cannot count the rows after ${stamp}\n`),r.err);
|
||||
assert.deepEqual(fp(e),before);assert.deepEqual(startsStops(e,n),[]);assert.equal(logLines(e).at(-1).code,'restore-mismatch');
|
||||
});
|
||||
for(const x of ['thread_opens','project_system_types'])await t.test(`the in-run recount counts the listed tables too (${x})`,async(t)=>{
|
||||
for(const x of ['thread_opens','project_archives'])await t.test(`the in-run recount counts the listed tables too (${x})`,async(t)=>{
|
||||
const e=await mk(t);await seed(e);
|
||||
assert.equal((await run(e,'activate',C,'acme','--migrate')).code,0);const act=pointer(e).activation;
|
||||
fault(e,'stop-writes-row',x);
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { orgCommand } from '../src/org.mjs';
|
||||
import { projectBusCommand } from '../src/project.mjs';
|
||||
|
||||
test('org installed system types and project selection reads print JSON', async () => {
|
||||
let output = '';
|
||||
const io = { stdout: { write: s => { output += s; } }, env: {} };
|
||||
await orgCommand(['system-types', 'installed'], io);
|
||||
assert.deepEqual(JSON.parse(output).map(x => x.id), ['business-management', 'coding', 'creative-writing', 'marketing', 'montage']);
|
||||
output = '';
|
||||
const calls = [];
|
||||
await projectBusCommand(['system-types', 'work', '--business', 'demo', '--json'], io, () => async (verb, args) => {
|
||||
calls.push([verb, args]);
|
||||
return verb === 'project.list' ? [{ id: 'project-id', name: 'work' }] : { project: 'project-id', selected: ['coding'], active: ['coding'], inactive: [] };
|
||||
});
|
||||
assert.deepEqual(calls.map(x => x[0]), ['project.list', 'project.system-types']);
|
||||
assert.deepEqual(JSON.parse(output).active, ['coding']);
|
||||
});
|
||||
|
||||
// sys1-review P2: both commands go through run() and the real CLI channel module, so a verb the
|
||||
// channel does not admit fails here. A disabled channel and an agent run still refuse.
|
||||
test('project system-types and system-types-set pass the CLI channel', async t => {
|
||||
const { run } = await import('../src/cli.mjs');
|
||||
const { fixture, humanEnv, io: mkio, tmp } = await import('./helpers.mjs');
|
||||
const root = tmp(t), f = fixture(root);
|
||||
const P = '10000000-0000-4000-8000-000000000001';
|
||||
const transportFor = channels => {
|
||||
const calls = [];
|
||||
const transport = () => async (verb, args) => {
|
||||
if (verb === 'plugins') return { business: 'acme', revision: 'a'.repeat(64), plugins: { channel: channels } };
|
||||
calls.push([verb, args]);
|
||||
if (verb === 'project.list') return [{ id: P, at: '2026-11-09T00:00:00.000Z', name: 'work', repo: null }];
|
||||
if (verb === 'project.system-types') return { project: P, selected: ['coding'], active: ['coding'], inactive: [] };
|
||||
if (verb === 'project.system-types.set') return { project: P, selected: args.systemTypes, active: args.systemTypes, inactive: [] };
|
||||
throw Object.assign(new Error(verb), { code: 'bus-refused' });
|
||||
};
|
||||
return { calls, transport };
|
||||
};
|
||||
const read = transportFor(['cli']), rx = mkio(humanEnv(f.env));
|
||||
assert.equal(await run(['project', 'system-types', 'work', '--business', 'acme'], rx, { transport: read.transport }), 0, rx.err?.text);
|
||||
assert.deepEqual(read.calls, [['project.list', { includeArchived: true }], ['project.system-types', { project: P }]]);
|
||||
assert.deepEqual(JSON.parse(rx.out.text).active, ['coding']);
|
||||
const write = transportFor(['cli']), wx = mkio(humanEnv(f.env));
|
||||
assert.equal(await run(['project', 'system-types-set', 'work', '--types', 'coding,marketing', '--business', 'acme'], wx, { transport: write.transport }), 0, wx.err?.text);
|
||||
assert.deepEqual(write.calls.at(-1), ['project.system-types.set', { project: P, systemTypes: ['coding', 'marketing'] }]);
|
||||
const off = transportFor(['webui']), ox = mkio(humanEnv(f.env));
|
||||
assert.equal(await run(['project', 'system-types', 'work', '--business', 'acme'], ox, { transport: off.transport }), 3);
|
||||
assert.deepEqual(off.calls, []);
|
||||
const agent = transportFor(['cli']);
|
||||
assert.notEqual(await run(['project', 'system-types-set', 'work', '--types', 'coding', '--business', 'acme'], mkio({ ...humanEnv(f.env), CODEX_THREAD_ID: 'fixture-agent' }), { transport: agent.transport }), 0);
|
||||
assert.deepEqual(agent.calls, []);
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { busExit, humanTransport, refuseInsideAgent } from "../src/transport.mjs";
|
||||
import { busExit, humanTransport, refuseInsideAgent, HUMAN_CLI } from "../src/transport.mjs";
|
||||
import { fakeCli, humanEnv, tmp } from "./helpers.mjs";
|
||||
|
||||
// The fake records argv and stdin, then answers per verb. The real
|
||||
@@ -15,6 +15,8 @@ const { verb } = JSON.parse(input);
|
||||
if (verb === "inbox") process.stdout.write(JSON.stringify([{ id: "d1" }]) + "\\n");
|
||||
else if (verb === "garbage") process.stdout.write("not json");
|
||||
else if (verb === "hang") setTimeout(() => {}, 60000);
|
||||
else if (verb === "not-sent") { process.stderr.write("outcome-unknown\\n"); process.exit(5); }
|
||||
else if (verb === "not-sent-other") { process.stderr.write("human-required\\n"); process.exit(5); }
|
||||
else { process.stderr.write("some noise\\n" + verb + "\\n"); process.exit(2); }
|
||||
`;
|
||||
|
||||
@@ -50,3 +52,28 @@ test("busExit and refuseInsideAgent", () => {
|
||||
assert.doesNotThrow(() => refuseInsideAgent(humanEnv()));
|
||||
assert.throws(() => refuseInsideAgent({ PI_AGENT_DIR: "/x" }), (e) => e.exitCode === 3 && /PI_AGENT_DIR/.test(e.message));
|
||||
});
|
||||
|
||||
// E2E6 fix 6: the shim exits 5 when its connect failed before the request was written. That is a stopped
|
||||
// bus: mosaic says so with the start and recover line. outcome-unknown stays for a request that left.
|
||||
test("E2E6 exit 5 with outcome-unknown is bus-not-running; exit 2 with outcome-unknown is unchanged", async (t) => {
|
||||
const s = setup(t);
|
||||
await assert.rejects(s.call("not-sent"), (e) => e.code === "bus-not-running" && e.exitCode === 3
|
||||
&& e.message === "bus-not-running: the bus for acme is not running, so the request was not sent"
|
||||
&& e.next === "start it with mosaic bus start acme, or clear a host that died with mosaic bus recover acme");
|
||||
await assert.rejects(s.call("outcome-unknown"), (e) => e.code === "outcome-unknown" && e.exitCode === 1 && e.message === "outcome-unknown" && e.next === undefined);
|
||||
// Exit 5 says only that nothing was sent; any other code it carries keeps its own meaning.
|
||||
await assert.rejects(s.call("not-sent-other"), (e) => e.code === "human-required" && e.exitCode === 3);
|
||||
assert.equal(busExit("bus-not-running"), 3);
|
||||
});
|
||||
|
||||
// The real shim, with no bus behind the path: nothing reaches a broker, so no proof runs. A missing socket
|
||||
// and a path that is not a listening socket are both a bus that is not running.
|
||||
test("E2E6 the real human shim against a missing socket or a plain file says the bus is not running", async (t) => {
|
||||
const root = tmp(t);
|
||||
const plain = join(root, "plain.sock");
|
||||
writeFileSync(plain, "");
|
||||
for (const socket of [join(root, "missing.sock"), plain]) {
|
||||
const call = humanTransport({ socket, business: "acme", env: humanEnv(), cli: HUMAN_CLI, timeoutMs: 20000 });
|
||||
await assert.rejects(call("inbox"), (e) => e.code === "bus-not-running" && e.exitCode === 3, socket);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,695 @@
|
||||
// #1873 triage-key: `mosaic triage key issue|rotate|retire|status`, Triage's own model proxy key.
|
||||
// A stand-in management server on loopback and a temporary config directory only; nothing here
|
||||
// reads a real config, proxy or secret. Every stdout, stderr, receipt and file the verbs leave is
|
||||
// scanned for every key the stand-in ever saw, at the end of each test and once more at the end.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { run } from "../src/cli.mjs";
|
||||
import { AGENT_MARKERS } from "../src/transport.mjs";
|
||||
import { DEFAULT_ROTATE_GRACE_MINUTES, keyPaths, retireAtFor, rotateByFor } from "../src/triage-key.mjs";
|
||||
import { ModelKeys } from "../../bus/src/model-keys.mjs";
|
||||
import { ManagementClient } from "../../model-proxy/src/client.mjs";
|
||||
import { startBroker } from "../../bus/src/runtime.mjs";
|
||||
import { busOrganization } from "../../bus/src/organization-context.mjs";
|
||||
import { Registry } from "../../seat/src/session.mjs";
|
||||
import { loadBusiness } from "../../organization/src/organization-config.mjs";
|
||||
import { resolveInstance } from "../../organization/src/resolve.mjs";
|
||||
import { businessDoc, rolesCopy, systemFor, writeJson } from "../../organization/tests/helpers.mjs";
|
||||
import { humanEnv, io } from "./helpers.mjs";
|
||||
|
||||
const REPO = new URL("../../../", import.meta.url).pathname;
|
||||
const NOW = Date.parse("2026-11-18T12:00:00.000Z");
|
||||
const MIN = 60_000, HOUR = 60 * MIN, DAY = 24 * HOUR;
|
||||
const MANAGE = "fx1873-manage";
|
||||
const KEY_PATH = "/v8/management/config/access/api-keys";
|
||||
const sha = (s) => createHash("sha256").update(s).digest("hex");
|
||||
const tag = (dir) => sha(dir).slice(0, 12);
|
||||
const id = (key) => sha(key).slice(0, 12);
|
||||
const b64 = () => randomBytes(32).toString("base64url");
|
||||
const iso = (ms) => new Date(ms).toISOString();
|
||||
|
||||
// Every output any verb produced in this file, and every Triage key the stand-in ever held.
|
||||
const OUTPUTS = [];
|
||||
const SEEN = new Set();
|
||||
const VERBS = ["issue", "rotate", "retire", "status"];
|
||||
|
||||
function leaks(text, keys = SEEN) {
|
||||
for (const key of keys) {
|
||||
const secret = key.slice(-43);
|
||||
if (text.includes(key) || text.includes(secret)) return true;
|
||||
for (let i = 0; i + 8 <= secret.length; i++) if (text.includes(secret.slice(i, i + 8))) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function walk(dir, skip, out = []) {
|
||||
for (const name of fs.readdirSync(dir)) {
|
||||
const p = join(dir, name), st = fs.lstatSync(p);
|
||||
if (st.isDirectory()) walk(p, skip, out);
|
||||
else if (st.isFile() && !skip.includes(p)) out.push(p);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function fixture(t, { sentinel = true } = {}) {
|
||||
const root = fs.realpathSync(fs.mkdtempSync(join(tmpdir(), "tk-")));
|
||||
const configDir = join(root, "config");
|
||||
fs.mkdirSync(join(configDir, "secrets"), { recursive: true, mode: 0o700 });
|
||||
fs.chmodSync(configDir, 0o700); fs.chmodSync(join(configDir, "secrets"), 0o700);
|
||||
fs.writeFileSync(join(configDir, "secrets", "proxy-management.key"), MANAGE, { mode: 0o600 });
|
||||
fs.mkdirSync(join(root, "proxy"), { mode: 0o700 });
|
||||
const prefix = `mst-${tag(configDir)}-triage-`;
|
||||
const state = {
|
||||
keys: [...(sentinel ? [`msk-${tag(configDir)}-sentinel-${b64()}`] : []), "foreign-client-key", `mso-${tag(configDir)}-demo-key-${b64()}`],
|
||||
gets: 0, puts: [], ignorePut: false, dropSentinelOnPut: false, onGet: null,
|
||||
};
|
||||
const server = http.createServer(async (req, res) => {
|
||||
if (req.url !== KEY_PATH) {
|
||||
const key = req.headers.authorization?.slice(7);
|
||||
res.writeHead(state.keys.includes(key) ? 200 : 401); res.end("{}"); return;
|
||||
}
|
||||
if (req.headers.authorization !== `Bearer ${MANAGE}`) { res.writeHead(401); res.end("{}"); return; }
|
||||
if (req.method === "GET") { state.gets++; const body = JSON.stringify(state.keys); state.onGet?.(state.gets); res.end(body); return; }
|
||||
const chunks = []; for await (const c of req) chunks.push(c);
|
||||
const next = JSON.parse(Buffer.concat(chunks));
|
||||
for (const k of next) if (/^mst-.*-[A-Za-z0-9_-]{43}$/.test(k)) SEEN.add(k);
|
||||
state.puts.push(next);
|
||||
if (state.dropSentinelOnPut) state.keys = next.filter((k) => !k.startsWith("msk-") || !k.includes("-sentinel-"));
|
||||
else if (!state.ignorePut) state.keys = next;
|
||||
res.end('{"status":"ok"}');
|
||||
});
|
||||
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const port = server.address().port;
|
||||
const closers = [];
|
||||
t.after(async () => {
|
||||
for (const close of closers) await close();
|
||||
server.closeAllConnections(); await new Promise((resolve) => server.close(resolve));
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
const f = {
|
||||
root, configDir, prefix, state, server, port, closers, now: NOW,
|
||||
system: { dataRoot: root, proxy: { port, binary: "/fixture-unused" } },
|
||||
file: keyPaths(configDir).file, dir: keyPaths(configDir).dir,
|
||||
env: (extra = {}) => humanEnv({ MOSAIC_CONFIG: join(configDir, "config.json"), ...extra }),
|
||||
async cli(argv, { env, deps = {}, system = f.system } = {}) {
|
||||
const s = io(env ?? f.env());
|
||||
const code = await run(argv, s, { system, now: () => new Date(f.now), ...deps });
|
||||
const out = { code, stdout: s.out.text, stderr: s.err.text };
|
||||
OUTPUTS.push(out.stdout, out.stderr);
|
||||
return out;
|
||||
},
|
||||
// The same verb in a child process that SIGKILLs itself at `stage`.
|
||||
crash(argv, stage) {
|
||||
const script = `
|
||||
import { run } from ${JSON.stringify(new URL("../src/cli.mjs", import.meta.url).href)};
|
||||
import { io } from ${JSON.stringify(new URL("./helpers.mjs", import.meta.url).href)};
|
||||
const p = JSON.parse(process.env.TK_CRASH);
|
||||
const s = io(process.env);
|
||||
const code = await run(p.argv, s, { system: p.system, now: () => new Date(p.now),
|
||||
triageKeyHook: (stage) => { if (stage === p.stage) process.kill(process.pid, "SIGKILL"); } });
|
||||
process.stdout.write(s.out.text); process.stderr.write(s.err.text); process.exitCode = code;`;
|
||||
const env = f.env({ TK_CRASH: JSON.stringify({ argv, stage, system: f.system, now: f.now }) });
|
||||
return new Promise((resolve) => {
|
||||
const child = spawn(process.execPath, ["--input-type=module", "-e", script], { env, stdio: ["ignore", "pipe", "pipe"] });
|
||||
let stdout = "", stderr = "";
|
||||
child.stdout.on("data", (d) => { stdout += d; });
|
||||
child.stderr.on("data", (d) => { stderr += d; });
|
||||
child.on("exit", (code, signal) => { OUTPUTS.push(stdout, stderr); resolve({ code, signal, stdout, stderr }); });
|
||||
});
|
||||
},
|
||||
record: () => JSON.parse(fs.readFileSync(f.file, "utf8")),
|
||||
triageKeys: () => state.keys.filter((k) => k.startsWith(prefix)),
|
||||
receipts: () => {
|
||||
const file = join(root, "proxy", "mosaic-keys.receipts.jsonl");
|
||||
return fs.existsSync(file) ? fs.readFileSync(file, "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l)) : [];
|
||||
},
|
||||
fenced: () => fs.existsSync(join(root, "proxy", "mosaic-keys.uncertain")),
|
||||
// No file under the fixture but the key file itself holds a key; neither does any output.
|
||||
scan(alsoKeyFiles = []) {
|
||||
for (const k of state.keys) if (/^mst-.*-[A-Za-z0-9_-]{43}$/.test(k)) SEEN.add(k);
|
||||
for (const p of walk(root, [f.file, join(configDir, "secrets", "proxy-management.key"), ...alsoKeyFiles])) {
|
||||
assert.equal(leaks(fs.readFileSync(p, "latin1")), false, `a key is in ${p}`);
|
||||
}
|
||||
for (const text of OUTPUTS) assert.equal(leaks(text), false, "a key is in an output");
|
||||
},
|
||||
};
|
||||
return f;
|
||||
}
|
||||
|
||||
const ok = (r) => assert.equal(r.code, 0, r.stderr);
|
||||
const refusal = (r, code, words) => {
|
||||
assert.equal(r.code, 3, r.stderr);
|
||||
assert.equal(r.stdout, "");
|
||||
assert.match(r.stderr, new RegExp(`^mosaic: ${code}: ${words ?? ""}`));
|
||||
};
|
||||
|
||||
test("issue adds one key under the lock, writes the 0600 file, and records ids only", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const before = [...f.state.keys];
|
||||
const r = await f.cli(["triage", "key", "issue"]);
|
||||
ok(r);
|
||||
const rec = f.record();
|
||||
assert.deepEqual(Object.keys(rec), ["version", "key", "keyId", "issuedAt", "rotateBy", "retiring"]);
|
||||
assert.match(rec.key, new RegExp(`^${f.prefix}[A-Za-z0-9_-]{43}$`));
|
||||
assert.equal(rec.keyId, id(rec.key));
|
||||
assert.equal(rec.issuedAt, iso(NOW));
|
||||
assert.equal(rec.rotateBy, "2026-12-18");
|
||||
assert.deepEqual(rec.retiring, []);
|
||||
assert.equal(r.stdout, `triage key issued: ${rec.keyId}, rotate by 2026-12-18\nfile: ${f.file}\n`);
|
||||
assert.deepEqual(f.state.keys, [...before, rec.key]);
|
||||
assert.equal(f.state.puts.length, 1);
|
||||
const file = fs.lstatSync(f.file), dir = fs.lstatSync(f.dir);
|
||||
assert.equal(file.mode & 0o777, 0o600); assert.equal(dir.mode & 0o777, 0o700);
|
||||
assert.equal(file.uid, process.getuid()); assert.equal(dir.uid, process.getuid());
|
||||
assert.deepEqual(f.receipts(), [{ op: "triage.key.issue", time: iso(NOW), addedKeyIds: [rec.keyId], removedKeyIds: [] }]);
|
||||
assert.equal(f.fenced(), false);
|
||||
assert.equal(fs.readFileSync(join(f.root, "proxy", "keys.generation"), "utf8"), "1\n");
|
||||
// A second issue refuses and changes nothing; rotate is the verb for that.
|
||||
const again = await f.cli(["triage", "key", "issue"]);
|
||||
refusal(again, "triage-key-issued", "a Triage key is already issued; use mosaic triage key rotate\n$");
|
||||
assert.equal(f.state.puts.length, 1);
|
||||
assert.deepEqual(f.record(), rec);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("status reads the file and the list and writes nothing", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const none = await f.cli(["triage", "key", "status"]);
|
||||
ok(none);
|
||||
assert.equal(none.stdout, `triage key: not issued\nfile: ${f.file}\nproxy: read\nnext: mosaic triage key issue\n`);
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
const rec = f.record(), puts = f.state.puts.length, receipts = f.receipts().length;
|
||||
f.now = NOW + 3 * DAY + 4 * HOUR + 5 * MIN;
|
||||
const shown = await f.cli(["triage", "key", "status"]);
|
||||
ok(shown);
|
||||
assert.equal(shown.stdout, [
|
||||
"triage key: issued", `file: ${f.file}`, `key id: ${rec.keyId}`, `issued: ${iso(NOW)} (age 3d 4h 5m)`,
|
||||
"rotate by: 2026-12-18", "proxy: holds the key", "next: nothing", "",
|
||||
].join("\n"));
|
||||
f.now = Date.parse("2026-12-18T00:00:00.000Z");
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, /rotate by: 2026-12-18 \(due\)\n[^]*next: mosaic triage key rotate\n$/);
|
||||
f.now = NOW + HOUR;
|
||||
f.state.keys = f.state.keys.filter((k) => k !== rec.key);
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, /proxy: does not hold the key\nnext: mosaic triage key rotate\n$/);
|
||||
assert.equal(f.state.puts.length, puts);
|
||||
assert.equal(f.receipts().length, receipts);
|
||||
assert.equal(fs.readdirSync(join(f.root, "proxy")).includes("mosaic-keys.lock"), false);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("rotate adds a new key and keeps the old one for the bus grace; retire removes it once due", async (t) => {
|
||||
const f = await fixture(t);
|
||||
refusal(await f.cli(["triage", "key", "rotate"]), "triage-key-not-issued", "no Triage key is issued; use mosaic triage key issue\n$");
|
||||
assert.equal(f.state.puts.length, 0);
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
const first = f.record();
|
||||
f.now = NOW + HOUR;
|
||||
const r = await f.cli(["triage", "key", "rotate"]);
|
||||
ok(r);
|
||||
const second = f.record();
|
||||
const retireAt = iso(NOW + HOUR + 120 * MIN);
|
||||
assert.notEqual(second.key, first.key);
|
||||
assert.equal(second.issuedAt, iso(NOW + HOUR));
|
||||
assert.deepEqual(second.retiring, [{ key: first.key, keyId: first.keyId, issuedAt: first.issuedAt, retireAt }]);
|
||||
assert.equal(r.stdout, `triage key rotated: ${second.keyId}, rotate by 2026-12-18\nold key ${first.keyId} stays live until mosaic triage key retire runs at or after ${retireAt}\n`);
|
||||
assert.deepEqual(f.triageKeys(), [first.key, second.key]);
|
||||
f.now = NOW + HOUR + 119 * MIN;
|
||||
const early = await f.cli(["triage", "key", "retire"]);
|
||||
ok(early);
|
||||
assert.equal(early.stdout, "triage key retire: nothing to remove\n");
|
||||
assert.equal(f.state.puts.length, 2);
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, new RegExp(`retiring: ${first.keyId}, live until a retire after ${retireAt}\\n[^]*next: nothing\\n$`));
|
||||
f.now = NOW + HOUR + 120 * MIN;
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, new RegExp(`retiring: ${first.keyId}, live until a retire after ${retireAt} \\(due\\)\\n[^]*next: mosaic triage key retire\\n$`));
|
||||
const done = await f.cli(["triage", "key", "retire"]);
|
||||
ok(done);
|
||||
assert.equal(done.stdout, `triage key retire: removed ${first.keyId}\n`);
|
||||
assert.deepEqual(f.triageKeys(), [second.key]);
|
||||
assert.deepEqual(f.record(), { ...second, retiring: [] });
|
||||
assert.deepEqual(f.receipts().map((e) => e.op), ["triage.key.issue", "triage.key.rotate", "triage.key.retire"]);
|
||||
assert.deepEqual(f.receipts()[2].removedKeyIds, [first.keyId]);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("rotate takes the grace from proxy.json, where the bus reads it, and drops an old key the proxy lost", async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.system = { ...f.system, proxy: { ...f.system.proxy, rotateGraceMinutes: 30 } };
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
const first = f.record();
|
||||
ok(await f.cli(["triage", "key", "rotate"]));
|
||||
const second = f.record();
|
||||
assert.equal(second.retiring[0].retireAt, iso(NOW + 30 * MIN));
|
||||
// The proxy lost the current key: rotate drops it at once, as the bus does for an agent key.
|
||||
f.state.keys = f.state.keys.filter((k) => k !== second.key);
|
||||
const r = await f.cli(["triage", "key", "rotate"]);
|
||||
ok(r);
|
||||
assert.match(r.stdout, new RegExp(`old key ${second.keyId} was not in the proxy list; nothing to retire\\n$`));
|
||||
assert.deepEqual(f.record().retiring.map((e) => e.keyId), [first.keyId]);
|
||||
// A retiring key past its time, or no longer in the list, leaves on the next rotate.
|
||||
f.now = NOW + 31 * MIN;
|
||||
ok(await f.cli(["triage", "key", "rotate"]));
|
||||
const last = f.record();
|
||||
assert.deepEqual(last.retiring.map((e) => e.keyId), [id(f.triageKeys()[0])]);
|
||||
assert.equal(f.triageKeys().includes(first.key), false);
|
||||
assert.equal(f.triageKeys().length, 2);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("lifetime and grace match the bus's own ModelKeys for the same clock and proxy settings", async (t) => {
|
||||
const runtime = fs.readFileSync(join(REPO, "packages/bus/src/runtime.mjs"), "utf8");
|
||||
const literal = runtime.match(/rotateGraceMinutes: proxy\.rotateGraceMinutes \?\? (\d+)/);
|
||||
assert.ok(literal, "the bus no longer reads rotateGraceMinutes as this test expects");
|
||||
assert.equal(Number(literal[1]), DEFAULT_ROTATE_GRACE_MINUTES);
|
||||
for (const grace of [undefined, 45]) {
|
||||
const f = await fixture(t);
|
||||
if (grace !== undefined) f.system = { ...f.system, proxy: { ...f.system.proxy, rotateGraceMinutes: grace } };
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
f.now = NOW + 3 * HOUR;
|
||||
ok(await f.cli(["triage", "key", "rotate"]));
|
||||
const ours = f.record();
|
||||
// The bus, driven the way runtime.mjs drives it, on its own in-memory list.
|
||||
let keys = [`msk-${tag(f.configDir)}-sentinel-${b64()}`], record = null, now = NOW;
|
||||
const credentials = { registerModel() {}, modelRecord: () => record, writeModel: (_, r) => { record = r; }, status: () => [] };
|
||||
const client = { getKeys: async () => [...keys], putKeys: async (k) => { keys = [...k]; return { ok: true }; } };
|
||||
const bus = new ModelKeys({ credentials, client, configDir: f.configDir, baseUrl: "http://127.0.0.1:1", now: () => now,
|
||||
...(grace === undefined ? {} : { rotateGraceMinutes: f.system.proxy.rotateGraceMinutes ?? Number(literal[1]) }) });
|
||||
await bus.reconcile();
|
||||
await bus.ensure("demo/x");
|
||||
assert.equal(record.rotateBy, rotateByFor(NOW));
|
||||
now = NOW + 3 * HOUR;
|
||||
await bus.rotate("demo/x");
|
||||
assert.equal(ours.rotateBy, record.rotateBy);
|
||||
assert.equal(ours.retiring[0].retireAt, record.retiring[0].retireAt);
|
||||
assert.equal(ours.retiring[0].retireAt, retireAtFor(now, f.system.proxy));
|
||||
f.scan();
|
||||
}
|
||||
});
|
||||
|
||||
test("an agent caller is refused before anything is read, for every key verb", async (t) => {
|
||||
const f = await fixture(t);
|
||||
for (const marker of AGENT_MARKERS) {
|
||||
for (const verb of VERBS) {
|
||||
const r = await f.cli(["triage", "key", verb], { env: { ...f.env(), [marker]: "1" } });
|
||||
assert.equal(r.code, 3, marker);
|
||||
assert.equal(r.stderr, `mosaic: refused: this runs only from a human shell, outside any agent run (found ${marker} in the environment)\n`);
|
||||
}
|
||||
const saved = process.env[marker];
|
||||
process.env[marker] = "1";
|
||||
try {
|
||||
for (const verb of VERBS) {
|
||||
const r = await f.cli(["triage", "key", verb]);
|
||||
assert.equal(r.code, 3, marker);
|
||||
assert.match(r.stderr, new RegExp(`found ${marker} in the environment`));
|
||||
}
|
||||
} finally { if (saved === undefined) delete process.env[marker]; else process.env[marker] = saved; }
|
||||
}
|
||||
assert.equal(f.state.gets, 0);
|
||||
assert.equal(f.state.puts.length, 0);
|
||||
assert.equal(fs.existsSync(f.dir), false);
|
||||
assert.deepEqual(fs.readdirSync(join(f.root, "proxy")), []);
|
||||
});
|
||||
|
||||
test("usage: unknown key verbs, options and arguments exit 4 and echo no value", async (t) => {
|
||||
const f = await fixture(t);
|
||||
for (const argv of [["triage", "key"], ["triage", "key", "nope"], ["triage", "key", "issue", "extra"], ["triage", "key", "status", "--json"]]) {
|
||||
const r = await f.cli(argv);
|
||||
assert.equal(r.code, 4, argv.join(" "));
|
||||
assert.equal(r.stdout, "");
|
||||
assert.match(r.stderr, /\nusage: mosaic triage route show [^\n]*\| key issue \| rotate \| retire \| status\n$/);
|
||||
}
|
||||
const r = await f.cli(["triage", "key", "rotate", "--key", "secret-value"]);
|
||||
assert.equal(r.code, 4);
|
||||
assert.match(r.stderr, /^mosaic: unknown option\n/);
|
||||
assert.doesNotMatch(r.stderr, /secret-value/);
|
||||
assert.equal(f.state.gets, 0);
|
||||
});
|
||||
|
||||
test("an unsafe key store refuses every verb before any proxy write", async (t) => {
|
||||
const uid = process.getuid();
|
||||
const cases = [
|
||||
["file mode", (f) => fs.chmodSync(f.file, 0o644), {}, "the key file mode is not 0600"],
|
||||
["file owner", () => {}, { triageKeyFileUid: uid + 1 }, "the key file is not owned by this user"],
|
||||
["file link", (f) => { fs.renameSync(f.file, join(f.dir, "real")); fs.symlinkSync(join(f.dir, "real"), f.file); }, {}, "the key file is a link"],
|
||||
["file is a directory", (f) => { fs.rmSync(f.file); fs.mkdirSync(f.file, { mode: 0o700 }); }, {}, "the key file is not a regular file"],
|
||||
["file is a FIFO", (f) => { fs.rmSync(f.file); assert.equal(spawnSync("mkfifo", ["-m", "600", f.file]).status, 0); }, {}, "the key file is not a regular file"],
|
||||
["hard link", (f) => fs.linkSync(f.file, join(f.dir, "second")), {}, "the key file has more than one link"],
|
||||
["not JSON", (f) => fs.writeFileSync(f.file, "{"), {}, "the key file is not JSON"],
|
||||
["extra field", (f) => fs.writeFileSync(f.file, JSON.stringify({ ...f.record(), extra: 1 })), {}, "the key file does not match the key shape"],
|
||||
["another instance's key", (f) => { const r = f.record(); const key = `mst-${tag("/elsewhere")}-triage-${b64()}`; fs.writeFileSync(f.file, JSON.stringify({ ...r, key, keyId: id(key) })); }, {}, "the key file does not match the key shape"],
|
||||
["wrong key id", (f) => fs.writeFileSync(f.file, JSON.stringify({ ...f.record(), keyId: "000000000000" })), {}, "the key file does not match the key shape"],
|
||||
["too large", (f) => fs.writeFileSync(f.file, " ".repeat(64 * 1024 + 1)), {}, "the key file is too large"],
|
||||
["triage directory mode", (f) => fs.chmodSync(f.dir, 0o755), {}, "the triage secrets directory mode is not 0700"],
|
||||
["triage directory link", (f) => { fs.renameSync(f.dir, join(f.configDir, "secrets", "moved")); fs.symlinkSync(join(f.configDir, "secrets", "moved"), f.dir); }, {}, "the triage secrets directory is a link"],
|
||||
["triage directory is a file", (f) => { fs.rmSync(f.dir, { recursive: true }); fs.writeFileSync(f.dir, "", { mode: 0o600 }); }, {}, "the triage secrets directory is not a directory"],
|
||||
["secrets mode", (f) => fs.chmodSync(join(f.configDir, "secrets"), 0o750), {}, "the secrets directory mode is not 0700"],
|
||||
["owner", () => {}, { triageKeyUid: uid + 1 }, "the secrets directory is not owned by this user"],
|
||||
];
|
||||
for (const [name, spoil, deps, words] of cases) {
|
||||
const f = await fixture(t);
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
spoil(f);
|
||||
const keys = [...f.state.keys], puts = f.state.puts.length;
|
||||
for (const verb of VERBS) {
|
||||
const r = await f.cli(["triage", "key", verb], { deps });
|
||||
refusal(r, "triage-key-unreadable", `the Triage key store is unreadable: ${words.replace(/[.()]/g, "\\$&")}\n$`);
|
||||
assert.equal(f.state.puts.length, puts, `${name}: ${verb}`);
|
||||
}
|
||||
assert.deepEqual(f.state.keys, keys);
|
||||
// The spoils above move or link the key file itself; those copies are the key file.
|
||||
f.scan([join(f.dir, "real"), join(f.dir, "second"), join(f.configDir, "secrets", "moved", "model")]);
|
||||
}
|
||||
// No secrets directory at all: status says not issued; issue refuses before the proxy changes.
|
||||
const f = await fixture(t);
|
||||
fs.rmSync(join(f.configDir, "secrets"), { recursive: true });
|
||||
fs.mkdirSync(join(f.configDir, "secrets"), { mode: 0o700 });
|
||||
fs.writeFileSync(join(f.configDir, "secrets", "proxy-management.key"), MANAGE, { mode: 0o600 });
|
||||
fs.chmodSync(join(f.configDir, "secrets"), 0o755);
|
||||
refusal(await f.cli(["triage", "key", "issue"]), "triage-key-unreadable", "the Triage key store is unreadable: the secrets directory mode is not 0700\n$");
|
||||
assert.equal(f.state.puts.length, 0);
|
||||
});
|
||||
|
||||
test("the instance proxy lock, the fence, the sentinel and the proxy itself each refuse plainly", async (t) => {
|
||||
// Lock held by a live process: busy after the lock's wait, and nothing changes.
|
||||
const f = await fixture(t);
|
||||
const lockFile = join(f.root, "proxy", "mosaic-keys.lock");
|
||||
ok(await f.cli(["triage", "key", "status"]));
|
||||
fs.writeFileSync(lockFile, `${JSON.stringify({ pid: process.pid, token: "a".repeat(32) })}\n`, { mode: 0o600 });
|
||||
const busy = await f.cli(["triage", "key", "issue"]);
|
||||
refusal(busy, "proxy-lock-busy", "another proxy writer holds the instance proxy lock; try again when it ends, and if no writer is running, see mosaic proxy fence status\n$");
|
||||
assert.equal(f.state.gets, 1);
|
||||
// A lock left by a process that is gone is reaped, and the verb goes ahead.
|
||||
const dead = spawnSync(process.execPath, ["-e", ""]).pid;
|
||||
fs.writeFileSync(lockFile, `${JSON.stringify({ pid: dead, token: "b".repeat(32) })}\n`, { mode: 0o600 });
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
assert.equal(fs.existsSync(lockFile), false);
|
||||
assert.equal(f.triageKeys().length, 1);
|
||||
fs.rmSync(f.file);
|
||||
f.state.keys = f.state.keys.filter((k) => !k.startsWith(f.prefix));
|
||||
// A set fence: every write refuses, status names it and the way out.
|
||||
const putsBefore = f.state.puts.length;
|
||||
fs.writeFileSync(join(f.root, "proxy", "mosaic-keys.uncertain"), "{}\n", { mode: 0o600 });
|
||||
for (const verb of ["issue", "rotate", "retire"]) refusal(await f.cli(["triage", "key", verb]), "proxy-uncertain");
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, /proxy fence: set, an earlier proxy write has an uncertain outcome\nnext: restart the proxy, then mosaic proxy fence clear --proxy-restarted\n$/);
|
||||
assert.equal(f.state.puts.length, putsBefore);
|
||||
// No sentinel for this instance (another instance's does not count).
|
||||
const g = await fixture(t, { sentinel: false });
|
||||
g.state.keys.push(`msk-${tag("/elsewhere")}-sentinel-${b64()}`);
|
||||
refusal(await g.cli(["triage", "key", "issue"]), "triage-key-proxy-open");
|
||||
assert.match((await g.cli(["triage", "key", "status"])).stdout, /proxy: its key list has no sentinel for this instance\nnext: check the proxy with mosaic proxy status\n$/);
|
||||
assert.equal(g.state.puts.length, 0);
|
||||
// No proxy set up, no management key, proxy down.
|
||||
const h = await fixture(t);
|
||||
const bare = { dataRoot: h.root };
|
||||
refusal(await h.cli(["triage", "key", "issue"], { system: bare }), "triage-key-no-proxy");
|
||||
assert.equal((await h.cli(["triage", "key", "status"], { system: bare })).stdout,
|
||||
`triage key: not issued\nfile: ${h.file}\nproxy: not set up for this instance (no proxy.json)\nnext: set up the model proxy first (mosaic proxy init)\n`);
|
||||
fs.chmodSync(join(h.configDir, "secrets", "proxy-management.key"), 0o644);
|
||||
refusal(await h.cli(["triage", "key", "issue"]), "proxy-management-key-invalid");
|
||||
fs.chmodSync(join(h.configDir, "secrets", "proxy-management.key"), 0o600);
|
||||
h.server.closeAllConnections(); await new Promise((resolve) => h.server.close(resolve));
|
||||
h.server.close = (cb) => cb();
|
||||
refusal(await h.cli(["triage", "key", "issue"]), "proxy-client-down");
|
||||
assert.match((await h.cli(["triage", "key", "status"])).stdout, /proxy: not read \(proxy-client-down\)\n/);
|
||||
assert.equal(fs.existsSync(h.file), false);
|
||||
f.scan(); g.scan(); h.scan();
|
||||
});
|
||||
|
||||
test("a write the proxy does not confirm keeps the fence; a list that moves mid-verb is not overwritten", async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.state.ignorePut = true;
|
||||
refusal(await f.cli(["triage", "key", "issue"]), "triage-key-unconfirmed");
|
||||
assert.equal(f.fenced(), true);
|
||||
assert.equal(fs.existsSync(f.file), false);
|
||||
// The store's directory was made and checked before the proxy changed, not after.
|
||||
assert.equal(fs.lstatSync(f.dir).mode & 0o777, 0o700);
|
||||
assert.deepEqual(f.receipts(), []);
|
||||
// A PUT the proxy takes but whose read-back has lost this instance's sentinel is not confirmed.
|
||||
const s = await fixture(t);
|
||||
s.state.dropSentinelOnPut = true;
|
||||
refusal(await s.cli(["triage", "key", "issue"]), "triage-key-unconfirmed");
|
||||
assert.equal(s.fenced(), true);
|
||||
assert.equal(fs.existsSync(s.file), false);
|
||||
s.scan();
|
||||
const g = await fixture(t);
|
||||
g.state.onGet = (n) => { if (n === 1) g.state.keys = [...g.state.keys, "late-foreign-key"]; };
|
||||
refusal(await g.cli(["triage", "key", "issue"]), "triage-key-raced");
|
||||
assert.equal(g.state.puts.length, 0);
|
||||
assert.equal(g.fenced(), false);
|
||||
f.scan(); g.scan();
|
||||
});
|
||||
|
||||
test("keys outside the Triage namespace are never touched; Triage keys the file does not hold are removed", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const agent = `msk-${tag(f.configDir)}-${b64()}`, other = `mst-${tag("/elsewhere")}-triage-${b64()}`;
|
||||
const orphan = `${f.prefix}${b64()}`, odd = `${f.prefix}short`;
|
||||
f.state.keys.push(agent, other, orphan, odd);
|
||||
const foreign = f.state.keys.filter((k) => k !== orphan && k !== odd);
|
||||
const r = await f.cli(["triage", "key", "issue"]);
|
||||
ok(r);
|
||||
// A malformed name under the Triage prefix is still Triage's, as the bus treats its own prefix.
|
||||
assert.match(r.stdout, new RegExp(`removed keys this file did not hold: ${id(orphan)}, ${id(odd)}\\n$`));
|
||||
for (const verb of ["rotate", "retire"]) { f.now += 3 * HOUR; ok(await f.cli(["triage", "key", verb])); }
|
||||
for (const k of foreign) assert.ok(f.state.keys.includes(k), "a key outside the namespace left the list");
|
||||
assert.equal(f.state.keys.includes(orphan), false);
|
||||
assert.equal(f.state.keys.includes(odd), false);
|
||||
assert.deepEqual(f.triageKeys(), [f.record().key]);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("crash after the PUT, before the read-back: the fence holds; status says so; clear, then issue recovers", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const crashed = await f.crash(["triage", "key", "issue"], "put");
|
||||
assert.equal(crashed.signal, "SIGKILL");
|
||||
assert.equal(f.fenced(), true);
|
||||
assert.equal(f.triageKeys().length, 1);
|
||||
assert.equal(fs.existsSync(f.file), false);
|
||||
const status = await f.cli(["triage", "key", "status"]);
|
||||
ok(status);
|
||||
assert.match(status.stdout, new RegExp(`proxy fence: set[^\\n]*\\nkeys in the Triage namespace the file does not hold: ${id(f.triageKeys()[0])}\\nnext: restart the proxy, then mosaic proxy fence clear --proxy-restarted\\n$`));
|
||||
refusal(await f.cli(["triage", "key", "issue"]), "proxy-uncertain");
|
||||
ok(await f.cli(["proxy", "fence", "clear", "--proxy-restarted"]));
|
||||
assert.equal(f.fenced(), false);
|
||||
const stray = f.triageKeys()[0];
|
||||
const r = await f.cli(["triage", "key", "issue"]);
|
||||
ok(r);
|
||||
assert.match(r.stdout, new RegExp(`removed keys this file did not hold: ${id(stray)}\\n$`));
|
||||
assert.deepEqual(f.triageKeys(), [f.record().key]);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("crash after the read-back, before the file write: no fence; status names the stray key; issue removes it", async (t) => {
|
||||
const f = await fixture(t);
|
||||
assert.equal((await f.crash(["triage", "key", "issue"], "write")).signal, "SIGKILL");
|
||||
assert.equal(f.fenced(), false);
|
||||
assert.equal(fs.existsSync(f.file), false);
|
||||
const [stray] = f.triageKeys();
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout,
|
||||
new RegExp(`^triage key: not issued\\n[^]*keys in the Triage namespace the file does not hold: ${id(stray)}\\nnext: mosaic triage key issue\\n$`));
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
assert.deepEqual(f.triageKeys(), [f.record().key]);
|
||||
// The same crash in rotate: the file keeps the old key, the stray new one is named, retire removes it.
|
||||
const held = f.record();
|
||||
assert.equal((await f.crash(["triage", "key", "rotate"], "write")).signal, "SIGKILL");
|
||||
assert.deepEqual(f.record(), held);
|
||||
const strayNew = f.triageKeys().find((k) => k !== held.key);
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout,
|
||||
new RegExp(`proxy: holds the key\\nkeys in the Triage namespace the file does not hold: ${id(strayNew)}\\nnext: mosaic triage key retire\\n$`));
|
||||
const retired = await f.cli(["triage", "key", "retire"]);
|
||||
ok(retired);
|
||||
assert.equal(retired.stdout, `triage key retire: removed ${id(strayNew)}\n`);
|
||||
assert.deepEqual(f.triageKeys(), [held.key]);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("file written but the old key not yet retired: status shows it due; a crash inside retire recovers on the next retire", async (t) => {
|
||||
const f = await fixture(t);
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
const first = f.record();
|
||||
ok(await f.cli(["triage", "key", "rotate"]));
|
||||
f.now = NOW + 121 * MIN;
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, new RegExp(`retiring: ${first.keyId}, live until a retire after [^\\n]* \\(due\\)\\n[^]*next: mosaic triage key retire\\n$`));
|
||||
// retire dies after the proxy dropped the key but before the file was rewritten.
|
||||
assert.equal((await f.crash(["triage", "key", "retire"], "write")).signal, "SIGKILL");
|
||||
assert.equal(f.state.keys.includes(first.key), false);
|
||||
assert.equal(f.record().retiring.length, 1);
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, /\(due\) \(not in the proxy list\)\n[^]*next: mosaic triage key retire\n$/);
|
||||
const puts = f.state.puts.length;
|
||||
const r = await f.cli(["triage", "key", "retire"]);
|
||||
ok(r);
|
||||
assert.equal(f.state.puts.length, puts);
|
||||
assert.deepEqual(f.record().retiring, []);
|
||||
// And a retire killed after its PUT leaves the fence, like any other write.
|
||||
ok(await f.cli(["triage", "key", "rotate"]));
|
||||
f.now += 121 * MIN;
|
||||
assert.equal((await f.crash(["triage", "key", "retire"], "put")).signal, "SIGKILL");
|
||||
assert.equal(f.fenced(), true);
|
||||
refusal(await f.cli(["triage", "key", "retire"]), "proxy-uncertain");
|
||||
ok(await f.cli(["proxy", "fence", "clear", "--proxy-restarted"]));
|
||||
ok(await f.cli(["triage", "key", "retire"]));
|
||||
assert.deepEqual(f.record().retiring, []);
|
||||
assert.deepEqual(f.triageKeys(), [f.record().key]);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("a file that cannot be written after the proxy changed is reported with its recovery", async (t) => {
|
||||
const f = await fixture(t);
|
||||
ok(await f.cli(["triage", "key", "status"]));
|
||||
fs.mkdirSync(f.dir, { mode: 0o700 });
|
||||
const r = await f.cli(["triage", "key", "issue"], { deps: { triageKeyHook: (stage) => { if (stage === "write") fs.chmodSync(f.dir, 0o755); } } });
|
||||
refusal(r, "triage-key-unwritten", "the proxy list changed but ");
|
||||
assert.match(r.stderr, /run mosaic triage key issue again, which clears what this run left\n$/);
|
||||
assert.equal(f.triageKeys().length, 1);
|
||||
fs.chmodSync(f.dir, 0o700);
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
assert.deepEqual(f.triageKeys(), [f.record().key]);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("crash after the temp file, before its rename: status counts it; the next verb removes it", async (t) => {
|
||||
const f = await fixture(t);
|
||||
assert.equal((await f.crash(["triage", "key", "issue"], "rename")).signal, "SIGKILL");
|
||||
assert.equal(fs.existsSync(f.file), false);
|
||||
const temps = fs.readdirSync(f.dir).filter((n) => n.endsWith(".tmp"));
|
||||
assert.equal(temps.length, 1);
|
||||
assert.match(temps[0], /^\.model\.\d+\.[0-9a-f]{12}\.tmp$/);
|
||||
// The temp file holds the key the proxy now has; that is why it must go.
|
||||
const [stray] = f.triageKeys();
|
||||
assert.ok(fs.readFileSync(join(f.dir, temps[0]), "utf8").includes(stray));
|
||||
const status = await f.cli(["triage", "key", "status"]);
|
||||
ok(status);
|
||||
assert.match(status.stdout, new RegExp(`leftover temp files in the triage secrets directory: 1 \\(the next issue, rotate or retire removes them\\)\\nkeys in the Triage namespace the file does not hold: ${id(stray)}\\nnext: mosaic triage key issue\\n$`));
|
||||
// Something else in the directory is not a leftover and stays.
|
||||
fs.writeFileSync(join(f.dir, "notes.tmp"), "", { mode: 0o600 });
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
assert.deepEqual(fs.readdirSync(f.dir).sort(), ["model", "notes.tmp"]);
|
||||
assert.deepEqual(f.triageKeys(), [f.record().key]);
|
||||
// Retire, with nothing else to do, still removes a leftover.
|
||||
assert.equal((await f.crash(["triage", "key", "rotate"], "rename")).signal, "SIGKILL");
|
||||
ok(await f.cli(["triage", "key", "retire"]));
|
||||
assert.deepEqual(fs.readdirSync(f.dir).sort(), ["model", "notes.tmp"]);
|
||||
assert.doesNotMatch((await f.cli(["triage", "key", "status"])).stdout, /leftover/);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("the receipts file is checked before the proxy changes; a receipt that fails after is named", async (t) => {
|
||||
const receipts = (f) => join(f.root, "proxy", "mosaic-keys.receipts.jsonl");
|
||||
const spoils = [
|
||||
["mode", (f) => { fs.writeFileSync(receipts(f), "", { mode: 0o644 }); fs.chmodSync(receipts(f), 0o644); }, "the proxy receipts file mode is not 0600"],
|
||||
["link", (f) => { fs.writeFileSync(join(f.root, "elsewhere"), "", { mode: 0o600 }); fs.symlinkSync(join(f.root, "elsewhere"), receipts(f)); }, "the proxy receipts file cannot be opened"],
|
||||
["FIFO", (f) => assert.equal(spawnSync("mkfifo", ["-m", "600", receipts(f)]).status, 0), "the proxy receipts file cannot be opened"],
|
||||
];
|
||||
for (const [name, spoil, words] of spoils) {
|
||||
const f = await fixture(t);
|
||||
spoil(f);
|
||||
refusal(await f.cli(["triage", "key", "issue"]), "triage-key-receipts-unsafe", `${words}; nothing was changed\n$`);
|
||||
assert.equal(f.state.puts.length, 0, name);
|
||||
assert.equal(f.fenced(), false, name);
|
||||
assert.equal(fs.existsSync(f.file), false, name);
|
||||
f.scan();
|
||||
}
|
||||
// Safe before the change, unsafe at the receipt: the change stands and the refusal says so.
|
||||
const f = await fixture(t);
|
||||
const r = await f.cli(["triage", "key", "issue"], { deps: { triageKeyHook: (stage) => { if (stage === "receipt") fs.chmodSync(receipts(f), 0o644); } } });
|
||||
refusal(r, "triage-key-unrecorded", "the change was made but its receipt line was not written; run mosaic triage key status\n$");
|
||||
assert.deepEqual(f.triageKeys(), [f.record().key]);
|
||||
assert.equal(f.fenced(), false);
|
||||
assert.equal(fs.readFileSync(receipts(f), "utf8"), "");
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("a directory sync that fails after the rename is named, and the receipt is still written", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const r = await f.cli(["triage", "key", "issue"], { deps: { triageKeyHook: (stage) => { if (stage === "sync") throw new Error("EIO"); } } });
|
||||
refusal(r, "triage-key-unsynced", `${f.file.replace(/[.]/g, "\\.")} was written but its directory could not be synced, so it may not survive a power loss; run mosaic triage key status\n$`);
|
||||
const rec = f.record();
|
||||
assert.deepEqual(f.triageKeys(), [rec.key]);
|
||||
assert.deepEqual(f.receipts().map((e) => e.addedKeyIds), [[rec.keyId]]);
|
||||
assert.equal(f.fenced(), false);
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, /proxy: holds the key\nnext: nothing\n$/);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("an unexpected error prints fixed words, never the error's own text", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const secret = `mst-${tag(f.configDir)}-triage-${b64()}`;
|
||||
SEEN.add(secret);
|
||||
// Outside the proxy write: the verb's own fallback line.
|
||||
const broken = { dataRoot: f.root, get proxy() { throw new Error(`boom ${secret}`); } };
|
||||
for (const verb of VERBS) {
|
||||
const r = await f.cli(["triage", "key", verb], { system: broken });
|
||||
assert.equal(r.code, 3, verb);
|
||||
assert.equal(r.stderr, "mosaic: triage-key-failed: the key verb stopped on an unexpected error; run mosaic triage key status\n");
|
||||
}
|
||||
// Inside the proxy write: the write's own fixed line, and the fence stays for a human.
|
||||
const r = await f.cli(["triage", "key", "issue"], { deps: { triageKeyHook: (stage) => { if (stage === "put") throw new Error(`boom ${secret}`); } } });
|
||||
refusal(r, "triage-key-failed", "the proxy write failed\n$");
|
||||
assert.equal(f.fenced(), true);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
// The org bus reconciles its own `mso-` namespace at start and a no-org bus its `msk-` one; a
|
||||
// Triage key sits in neither, so both leave it. Stray keys in each namespace show the reconcile ran.
|
||||
test("an org bus that starts and reconciles, and a no-org reconcile, both leave the Triage key alone", async (t) => {
|
||||
const f = await fixture(t);
|
||||
ok(await f.cli(["triage", "key", "issue"]));
|
||||
const triage = f.record().key;
|
||||
const strayOrg = `mso-${tag(f.configDir)}-demo-key-${b64()}`;
|
||||
f.state.keys.push(strayOrg);
|
||||
const rolesDir = rolesCopy(f.root), system = systemFor(f.root), doc = businessDoc(f.root, "demo");
|
||||
doc.plugins = { ...doc.plugins, harness: ["pi"] };
|
||||
const file = writeJson(join(f.configDir, "businesses", "demo.json"), doc);
|
||||
assert.ok(file);
|
||||
const business = loadBusiness("demo", { dir: f.configDir, rolesDir }), resolved = {};
|
||||
for (const instance of Object.keys(business.roles)) resolved[instance] = resolveInstance({ system, business, instance });
|
||||
fs.mkdirSync(join(f.root, "data"), { mode: 0o700 });
|
||||
new Registry(join(f.root, "data"));
|
||||
const bus = await startBroker({ dataRoot: join(f.root, "data"), businesses: { demo: busOrganization(business, resolved) },
|
||||
organization: { dir: f.configDir, rolesDir, system }, proxy: { port: f.port, binary: "/fixture-unused" },
|
||||
org: { id: "demo" }, instanceDataRoot: f.root, instanceConfigDir: f.configDir });
|
||||
f.closers.push(() => bus.close());
|
||||
const orgKey = (await bus.modelPreflight({ business: "demo", role: "chief" })).key;
|
||||
assert.ok(orgKey.startsWith(`mso-${tag(f.configDir)}-demo-key-`));
|
||||
assert.equal(f.state.keys.includes(strayOrg), false, "the org reconcile did not run");
|
||||
assert.ok(f.state.keys.includes(triage), "the org bus removed the Triage key");
|
||||
// A no-org reconcile on the same instance.
|
||||
const strayAgent = `msk-${tag(f.configDir)}-${b64()}`;
|
||||
f.state.keys.push(strayAgent);
|
||||
const client = new ManagementClient({ baseUrl: `http://127.0.0.1:${f.port}`, key: MANAGE });
|
||||
const keys = new ModelKeys({ credentials: { status: () => [], modelRecord: () => null }, client, configDir: f.configDir, baseUrl: `http://127.0.0.1:${f.port}` });
|
||||
await keys.reconcile();
|
||||
assert.equal(f.state.keys.includes(strayAgent), false, "the no-org reconcile did not run");
|
||||
assert.ok(f.state.keys.includes(triage), "the no-org reconcile removed the Triage key");
|
||||
// Triage still works under the shared lock while the org bus runs, and leaves the org key.
|
||||
f.now += HOUR;
|
||||
ok(await f.cli(["triage", "key", "rotate"]));
|
||||
assert.ok(f.state.keys.includes(orgKey));
|
||||
assert.match((await f.cli(["triage", "key", "status"])).stdout, /proxy: holds the key\n/);
|
||||
f.scan();
|
||||
});
|
||||
|
||||
test("scripts/mosaic routes triage key status with the instance's own config directory", (t) => {
|
||||
const home = fs.mkdtempSync(join(tmpdir(), "tkm-"));
|
||||
t.after(() => fs.rmSync(home, { recursive: true, force: true }));
|
||||
const env = humanEnv({ HOME: home, MOSAIC_CONFIG: join(home, ".config/mosaic-tktest/config.json") });
|
||||
const setup = spawnSync(join(REPO, "scripts/bootstrap.sh"), ["--instance", "tktest"], { env, encoding: "utf8" });
|
||||
assert.equal(setup.status, 0, setup.stderr);
|
||||
const r = spawnSync(join(REPO, "scripts/mosaic"), ["triage", "key", "status"], { env, encoding: "utf8", timeout: 60000 });
|
||||
OUTPUTS.push(r.stdout, r.stderr);
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
assert.equal(r.stdout, `triage key: not issued\nfile: ${join(home, ".config/mosaic-tktest/secrets/triage/model")}\nproxy: not set up for this instance (no proxy.json)\nnext: set up the model proxy first (mosaic proxy init)\n`);
|
||||
const refused = spawnSync(join(REPO, "scripts/mosaic"), ["triage", "key", "issue"], { env: { ...env, CLAUDECODE: "1" }, encoding: "utf8", timeout: 60000 });
|
||||
assert.equal(refused.status, 3);
|
||||
assert.match(refused.stderr, /found CLAUDECODE in the environment/);
|
||||
});
|
||||
|
||||
test("no output of any verb in this file holds any key the stand-in saw", () => {
|
||||
assert.ok(SEEN.size >= 20, `only ${SEEN.size} keys were seen`);
|
||||
assert.ok(OUTPUTS.length >= 100);
|
||||
for (const text of OUTPUTS) assert.equal(leaks(text), false);
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
// #1873 triage-route-store: `mosaic triage route show|set`, the owner's terminal verbs for the
|
||||
// Triage route file (packages/webui/src/triage-route-store.mjs). Human verbs: an agent run is
|
||||
// refused before anything is read (exit 3), as the other human verbs refuse it. `show` with no
|
||||
// file says the route is not set and exits 0.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { run } from "../src/cli.mjs";
|
||||
import { AGENT_MARKERS } from "../src/transport.mjs";
|
||||
import { routePaths } from "../../webui/src/triage-route-store.mjs";
|
||||
import { humanEnv, io } from "./helpers.mjs";
|
||||
|
||||
const REPO = new URL("../../../", import.meta.url).pathname;
|
||||
const MOSAIC = join(REPO, "scripts/mosaic");
|
||||
const NOW = new Date("2026-11-18T12:00:00.000Z");
|
||||
const SET = ["triage", "route", "set", "--model", "glm-5", "--harness", "claude-code", "--cap", "200000", "--time-zone", "America/Chicago"];
|
||||
|
||||
function dataRoot(t) {
|
||||
const d = mkdtempSync(join(tmpdir(), "tr-"));
|
||||
t.after(() => rmSync(d, { recursive: true, force: true }));
|
||||
return d;
|
||||
}
|
||||
async function cli(argv, d, env = humanEnv()) {
|
||||
const s = io(env);
|
||||
const code = await run(argv, s, { system: { dataRoot: d }, now: () => NOW });
|
||||
return { code, stdout: s.out.text, stderr: s.err.text };
|
||||
}
|
||||
|
||||
test("show with no route says it is not set and exits 0", async (t) => {
|
||||
const d = dataRoot(t);
|
||||
assert.deepEqual(await cli(["triage", "route", "show"], d), { code: 0, stdout: "triage route: not set\n", stderr: "" });
|
||||
assert.equal(existsSync(routePaths(d).dir), false);
|
||||
});
|
||||
|
||||
test("set writes the route; show reads it back", async (t) => {
|
||||
const d = dataRoot(t);
|
||||
const set = await cli(SET, d);
|
||||
assert.equal(set.code, 0, set.stderr);
|
||||
assert.equal(set.stdout, "triage route set: revision 1\n");
|
||||
const shown = await cli(["triage", "route", "show"], d);
|
||||
assert.equal(shown.code, 0);
|
||||
assert.equal(shown.stdout, [
|
||||
"triage route: revision 1",
|
||||
"model: glm-5",
|
||||
"harness: claude-code",
|
||||
"cap: 200000 tokens a day, resets 00:00 America/Chicago, counted since 2026-11-18T12:00:00.000Z",
|
||||
"updated: 2026-11-18T12:00:00.000Z by owner",
|
||||
"",
|
||||
].join("\n"));
|
||||
const doc = JSON.parse(readFileSync(routePaths(d).file, "utf8"));
|
||||
assert.equal(doc.updatedBy, "owner");
|
||||
// --revision makes the write conditional on what show printed.
|
||||
const five = ["triage", "route", "set", "--model", "glm-5", "--harness", "claude-code", "--cap", "5", "--time-zone", "America/Chicago", "--revision", "1"];
|
||||
assert.equal((await cli(five, d)).code, 0);
|
||||
assert.equal(JSON.parse(readFileSync(routePaths(d).file, "utf8")).cap.limit, 5);
|
||||
const stale = await cli([...SET, "--revision", "1"], d);
|
||||
assert.equal(stale.code, 3);
|
||||
assert.match(stale.stderr, /^mosaic: triage-route-stale: /);
|
||||
});
|
||||
|
||||
test("refused input exits 2 or 4 and writes nothing", async (t) => {
|
||||
const d = dataRoot(t);
|
||||
const without = (flag) => { const a = [...SET]; const i = a.indexOf(flag); a.splice(i, 2); return a; };
|
||||
const swap = (flag, value) => { const a = [...SET]; a[a.indexOf(flag) + 1] = value; return a; };
|
||||
const cases = [
|
||||
[without("--model"), 4], [without("--harness"), 4], [without("--cap"), 4], [without("--time-zone"), 4],
|
||||
[swap("--cap", "-1"), 2], [swap("--cap", "1e3"), 2], [swap("--cap", "01"), 2], [swap("--cap", "9007199254740993"), 2],
|
||||
[swap("--time-zone", "Atlantis/Lost"), 2], [swap("--model", "Has Space"), 2],
|
||||
[swap("--harness", "nonesuch"), 2], [swap("--harness", "../pi"), 2],
|
||||
[[...SET, "--revision", "x"], 2], [[...SET, "--revision", "-1"], 2],
|
||||
[[...SET, "--cap", "5"], 4], [[...SET, "--unknown", "1"], 4], [[...SET, "extra"], 4],
|
||||
[["triage", "route", "show", "--model", "x"], 4], [["triage", "route", "show", "extra"], 4],
|
||||
[["triage", "route"], 4], [["triage", "route", "remove"], 4], [["triage"], 4], [["triage", "key"], 4],
|
||||
];
|
||||
for (const [argv, want] of cases) {
|
||||
const r = await cli(argv, d);
|
||||
assert.equal(r.code, want, `${argv.join(" ")}: ${r.stderr}`);
|
||||
assert.equal(r.stdout, "");
|
||||
}
|
||||
// An unknown option is named as one, and its value never reaches the message.
|
||||
const unknown = await cli([...SET, "--unknown", "secret-value"], d);
|
||||
assert.equal(unknown.code, 4);
|
||||
assert.match(unknown.stderr, /^mosaic: unknown option\n/);
|
||||
assert.doesNotMatch(unknown.stderr, /secret-value/);
|
||||
assert.equal(existsSync(routePaths(d).file), false);
|
||||
});
|
||||
|
||||
test("an unreadable store exits 3 on show and on set", async (t) => {
|
||||
const d = dataRoot(t);
|
||||
assert.equal((await cli(SET, d)).code, 0);
|
||||
chmodSync(routePaths(d).file, 0o644);
|
||||
for (const argv of [["triage", "route", "show"], [...SET, "--revision", "1"]]) {
|
||||
const r = await cli(argv, d);
|
||||
assert.equal(r.code, 3);
|
||||
assert.match(r.stderr, /^mosaic: triage-route-unreadable: the Triage route store is unreadable: route\.json mode is not 0600\n$/);
|
||||
}
|
||||
});
|
||||
|
||||
test("an agent caller is refused before anything is read, for show and set", async (t) => {
|
||||
const d = dataRoot(t);
|
||||
for (const marker of AGENT_MARKERS) {
|
||||
for (const argv of [["triage", "route", "show"], SET]) {
|
||||
const r = await cli(argv, d, { ...humanEnv(), [marker]: "1" });
|
||||
assert.equal(r.code, 3, marker);
|
||||
assert.equal(r.stderr, `mosaic: refused: this runs only from a human shell, outside any agent run (found ${marker} in the environment)\n`);
|
||||
}
|
||||
}
|
||||
assert.equal(existsSync(routePaths(d).dir), false);
|
||||
});
|
||||
|
||||
test("scripts/mosaic routes triage to the verb; a marker in the process env refuses", (t) => {
|
||||
const home = mkdtempSync(join(tmpdir(), "trm-"));
|
||||
t.after(() => rmSync(home, { recursive: true, force: true }));
|
||||
const env = humanEnv({ HOME: home, MOSAIC_CONFIG: join(home, ".config/mosaic-trtest/config.json") });
|
||||
const setup = spawnSync(join(REPO, "scripts/bootstrap.sh"), ["--instance", "trtest"], { env, encoding: "utf8" });
|
||||
assert.equal(setup.status, 0, setup.stderr);
|
||||
const mosaic = (args, extra = {}) => spawnSync(MOSAIC, args, { env: { ...env, ...extra }, encoding: "utf8", timeout: 60000 });
|
||||
const shown = mosaic(["triage", "route", "show"]);
|
||||
assert.equal(shown.status, 0, shown.stderr);
|
||||
assert.equal(shown.stdout, "triage route: not set\n");
|
||||
const set = mosaic(SET.slice(0));
|
||||
assert.equal(set.status, 0, set.stderr);
|
||||
assert.equal(set.stdout, "triage route set: revision 1\n");
|
||||
const dataDir = join(home, ".mosaic-trtest");
|
||||
assert.equal(JSON.parse(readFileSync(routePaths(dataDir).file, "utf8")).model, "glm-5");
|
||||
const refused = mosaic(["triage", "route", "show"], { CLAUDECODE: "1" });
|
||||
assert.equal(refused.status, 3);
|
||||
assert.match(refused.stderr, /found CLAUDECODE in the environment/);
|
||||
assert.equal(refused.stdout, "");
|
||||
});
|
||||
|
||||
test("a marker in this process's own environment refuses even when the command's env is clean", async (t) => {
|
||||
const d = dataRoot(t);
|
||||
for (const marker of AGENT_MARKERS) {
|
||||
const saved = process.env[marker];
|
||||
process.env[marker] = "1";
|
||||
try {
|
||||
for (const argv of [["triage", "route", "show"], SET]) {
|
||||
const r = await cli(argv, d, humanEnv());
|
||||
assert.equal(r.code, 3, marker);
|
||||
assert.match(r.stderr, new RegExp(`found ${marker} in the environment`));
|
||||
}
|
||||
} finally { if (saved === undefined) delete process.env[marker]; else process.env[marker] = saved; }
|
||||
}
|
||||
assert.equal(existsSync(routePaths(d).dir), false);
|
||||
});
|
||||
@@ -36,9 +36,9 @@
|
||||
import { refusalGuidance } from "../../bus/src/refusals.mjs";
|
||||
import { spawn } from "node:child_process";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
import { chmodSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, closeSync } from "node:fs";
|
||||
import { chmodSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, rmSync, closeSync } from "node:fs";
|
||||
import { createServer, connect } from "node:net";
|
||||
import { join } from "node:path";
|
||||
import { basename, join } from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { Client } from "../../bus/src/client.mjs";
|
||||
import { LENGTH_FAILURE_NOTICE_PREFIX } from "./failure-notice.mjs";
|
||||
@@ -384,13 +384,56 @@ export function toolServer({ path, tools, client, local }) {
|
||||
});
|
||||
}
|
||||
|
||||
// #1873 r127: exit 127 is the shell's "command not found". The turn's stderr then holds the
|
||||
// shell's own line for it, the last one nearest the exit:
|
||||
// bash X: line N: [exec: ]CMD: No such file or directory | [command ]not found
|
||||
// dash X: N: [exec: ]CMD: not found
|
||||
// env [/usr/bin/]env: 'CMD': No such file or directory
|
||||
// Only those shapes count, so another program's missing file (cat: F: No such file…) doesn't.
|
||||
// The answer is CMD's basename, which the person reads in the failure; never its host path, and
|
||||
// nothing that isn't a plain program name. A run of 16 letters and digits looks like a key, not a
|
||||
// program, so it stays in the run's private stderr.
|
||||
const NOT_FOUND = [
|
||||
/(?:^|: )line \d+: (?:exec: )?([^\s:]+): (?:(?:command )?not found|No such file or directory)$/,
|
||||
/: \d+: (?:exec: )?([^\s:]+): not found$/,
|
||||
/^(?:\S*\/)?env: ['\u2018]([^\s:'\u2019]+)['\u2019]: No such file or directory$/,
|
||||
];
|
||||
export function missingCommand(text) {
|
||||
let name = null;
|
||||
for (const line of String(text).split(/\r?\n/)) {
|
||||
const m = NOT_FOUND.map((re) => re.exec(line)).find(Boolean);
|
||||
if (m) name = basename(m[1]);
|
||||
}
|
||||
return name && /^[A-Za-z0-9._+-]{1,64}$/.test(name) && !/[A-Za-z0-9]{16}/.test(name) ? name : null;
|
||||
}
|
||||
|
||||
// The last 16 KiB of a turn's stderr file from a line start, or "" when it can't be read.
|
||||
const TAIL = 16384;
|
||||
function stderrTail(path) {
|
||||
let fd;
|
||||
try {
|
||||
fd = openSync(path, "r");
|
||||
const size = fstatSync(fd).size, length = Math.min(size, TAIL);
|
||||
const buf = Buffer.alloc(length);
|
||||
readSync(fd, buf, 0, length, size - length);
|
||||
const text = buf.toString("utf8");
|
||||
// A window that starts mid-file starts mid-line; that partial line is dropped.
|
||||
return size > TAIL ? text.slice(text.indexOf("\n") + 1) : text;
|
||||
} catch {
|
||||
return "";
|
||||
} finally {
|
||||
if (fd !== undefined) closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
// Run one turn. Resolves { ok, text, reason }.
|
||||
function runTurn({ session, request, n, env, onChild }) {
|
||||
const marker = session.turnMarker;
|
||||
rmSync(marker, { force: true });
|
||||
const turns = join(session.runDir, "turns");
|
||||
mkdirSync(turns, { recursive: true, mode: 0o700 });
|
||||
const errFd = openSync(join(turns, `${String(n).padStart(4, "0")}.stderr`), "wx", 0o600);
|
||||
const errPath = join(turns, `${String(n).padStart(4, "0")}.stderr`);
|
||||
const errFd = openSync(errPath, "wx", 0o600);
|
||||
// Adapters are 0644 in the repository (the image sets the mode), so the
|
||||
// host runs them through sh.
|
||||
const child = spawn("/bin/sh", [session.adapter], {
|
||||
@@ -461,6 +504,10 @@ function runTurn({ session, request, n, env, onChild }) {
|
||||
if (status?.stopReason === "length" && status.hasText === false && status.hasToolCall === false)
|
||||
return resolve({ ok: false, emptyLength: true, reason: "output limit reached while thinking before any answer or tool call" });
|
||||
}
|
||||
if (code === 127) {
|
||||
const missing = missingCommand(stderrTail(errPath));
|
||||
return resolve({ ok: false, reason: `adapter exited 127${missing ? ` (command not found: ${missing})` : ""}` });
|
||||
}
|
||||
if (code !== 0) return resolve({ ok: false, reason: signal ? `adapter killed by ${signal}` : `adapter exited ${code}` });
|
||||
// A "marker" harness (row 65: the module's turnEnd()) writes the marker when its turn ends.
|
||||
if (session.turnEnd === "marker" && !existsSync(marker)) return resolve({ ok: false, reason: `${session.harness} exited before the turn ended (no turn marker)` });
|
||||
|
||||
@@ -13,7 +13,7 @@ import { join } from "node:path";
|
||||
import { Store } from "../../bus/src/store.mjs";
|
||||
import { Broker, BusError } from "../../bus/src/broker.mjs";
|
||||
import { serve } from "../../bus/src/server.mjs";
|
||||
import { EXIT, founderCheck, landingRequest, stateBlock, turnRequest, unslopCounts, unslopLog, unslopNotes } from "../src/runner.mjs";
|
||||
import { EXIT, founderCheck, landingRequest, missingCommand, stateBlock, turnRequest, unslopCounts, unslopLog, unslopNotes } from "../src/runner.mjs";
|
||||
import { typedTools } from "../src/tools.mjs";
|
||||
import { resolvedFor, scratch } from "./helpers.mjs";
|
||||
|
||||
@@ -298,6 +298,88 @@ test("SIGKILL of the model child keeps base failure receipts through the real ad
|
||||
assert.equal(records[1].body, records[0].body);
|
||||
});
|
||||
|
||||
// #1873 r127: on the dev instance /usr/bin/claude is a wrapper that execs a binary outside /usr.
|
||||
// The sandbox binds /usr only, so the wrapper starts and its target is missing: the shell exits
|
||||
// 127 and the person read only "adapter exited 127". The reason now names the missing program.
|
||||
test("r127 an adapter exit 127 names the program that wasn't found, through the real claude adapter", async t => {
|
||||
const ctx = await setup(t, {session:{harness:"claude-code", turnEnd:"exit", adapter:new URL("../../../adapters/claude/adapter.sh", import.meta.url).pathname}});
|
||||
const sessionFile = join(ctx.runDir, "session.json");
|
||||
const session = JSON.parse(readFileSync(sessionFile, "utf8"));
|
||||
const wrapper = join(ctx.dir, "bin", "claude");
|
||||
mkdirSync(join(ctx.dir, "bin"));
|
||||
writeFileSync(wrapper, `#!/bin/sh\nexport DISABLE_UPDATES=1\nexec ${join(ctx.dir, "not-mounted", "claude-code", "bin", "claude")} "$@"\n`, {mode:0o755});
|
||||
session.harnessEnv = {MOSAIC_CLAUDE_BIN:wrapper, MOSAIC_THINKING:"low", MOSAIC_CLAUDE_SETTINGS:session.bundle.policy, MOSAIC_CLAUDE_MCP_CONFIG:session.bundle.tools};
|
||||
writeFileSync(sessionFile, JSON.stringify(session));
|
||||
ctx.inbox = [];
|
||||
const r = startRunner(ctx.runDir, ctx.cap);
|
||||
t.after(() => r.child.kill("SIGKILL"));
|
||||
const sent = ctx.call(ctx.pm, "message.send", {to:"coder", body:"hello", class:"REQUEST"});
|
||||
const [reply] = await until(replies(ctx));
|
||||
await until(() => ctx.store.get("SELECT 1 FROM deliveries WHERE message=? AND op='read'", sent.id));
|
||||
assert.equal(reply.body, "The turn failed: adapter exited 127 (command not found: claude)");
|
||||
assert.doesNotMatch(reply.body, /not-mounted|\/bin\//, "the reason names the program, never its host path");
|
||||
assert.match(r.stderr(), /failed: adapter exited 127 \(command not found: claude\)/);
|
||||
r.child.kill("SIGTERM"); await r.exited;
|
||||
});
|
||||
|
||||
test("r127 an adapter whose own command is missing names it; a 127 with no such line keeps the bare reason", async t => {
|
||||
const ctx = await setup(t);
|
||||
const adapter = join(ctx.dir, "adapter.sh");
|
||||
writeFileSync(adapter, `case "$MOSAIC_REQUEST" in *QUIET*) echo "nothing useful" >&2; exit 127 ;; esac\nexec mosaic-r127-no-such-harness -p "$MOSAIC_REQUEST"\n`);
|
||||
ctx.inbox = [];
|
||||
const r = startRunner(ctx.runDir, ctx.cap);
|
||||
t.after(() => r.child.kill("SIGKILL"));
|
||||
ctx.call(ctx.pm, "message.send", {to:"coder", body:"one"});
|
||||
ctx.call(ctx.pm, "message.send", {to:"coder", body:"QUIET"});
|
||||
await until(() => replies(ctx)() && ctx.inbox.length >= 2);
|
||||
assert.deepEqual(ctx.inbox.map(m => m.body), [
|
||||
"The turn failed: adapter exited 127 (command not found: mosaic-r127-no-such-harness)",
|
||||
"The turn failed: adapter exited 127",
|
||||
]);
|
||||
r.child.kill("SIGTERM"); await r.exited;
|
||||
});
|
||||
|
||||
test("r127 missingCommand reads the shells' not-found lines and gives a safe basename only", () => {
|
||||
assert.equal(missingCommand("/usr/bin/claude: line 4: /opt/claude-code/bin/claude: No such file or directory\nclaude adapter: invalid or incomplete model stream\n"), "claude");
|
||||
assert.equal(missingCommand("/usr/bin/claude: 4: exec: /opt/claude-code/bin/claude: not found\n"), "claude");
|
||||
assert.equal(missingCommand("/x/adapters/pi/adapter.sh: 140: exec: pi: not found\n"), "pi");
|
||||
assert.equal(missingCommand("/x/adapter.sh: line 9: exec: pi: not found\n"), "pi");
|
||||
assert.equal(missingCommand("sh: line 1: pi: command not found\n"), "pi");
|
||||
assert.equal(missingCommand("/usr/bin/env: 'node': No such file or directory\n"), "node");
|
||||
assert.equal(missingCommand("/usr/bin/env: ‘node’: No such file or directory\n"), "node");
|
||||
// The last such line is the one nearest the exit.
|
||||
assert.equal(missingCommand("a: 1: exec: first: not found\nb: 2: exec: second: not found\n"), "second");
|
||||
assert.equal(missingCommand(""), null);
|
||||
assert.equal(missingCommand("error: model refused\n"), null);
|
||||
// A name that isn't a plain program name is left out, never echoed.
|
||||
assert.equal(missingCommand("a: 1: exec: $(rm -rf x): not found\n"), null);
|
||||
assert.equal(missingCommand(`a: 1: exec: ${"x".repeat(80)}: not found\n`), null);
|
||||
// Review r127 P3-5: tokens without spaces reach the name check, and it refuses them.
|
||||
assert.equal(missingCommand("a: 1: exec: $(id): not found\n"), null);
|
||||
assert.equal(missingCommand("a: line 2: x;id: command not found\n"), null);
|
||||
assert.equal(missingCommand("a: line 2: `id`: command not found\n"), null);
|
||||
// P3-2: a long run of letters and digits looks like a key, not a program; it stays in stderr.
|
||||
assert.equal(missingCommand("adapter.sh: line 3: sk-proj-abcDEF1234567890xyz: command not found\n"), null);
|
||||
assert.equal(missingCommand("adapter.sh: line 3: 0123456789abcdef0123: command not found\n"), null);
|
||||
// P3-1: only a shell's or env's own line counts; other programs' missing files don't.
|
||||
assert.equal(missingCommand("cat: /nope/file: No such file or directory\n"), null);
|
||||
assert.equal(missingCommand("w.sh: line 1: /opt/x/claude: No such file or directory\ncat: /run/state.json: No such file or directory\n"), "claude");
|
||||
// P3-4: CRLF lines read the same.
|
||||
assert.equal(missingCommand("sh: line 1: pi: command not found\r\n"), "pi");
|
||||
});
|
||||
|
||||
test("r127 a not-found line cut by the 16 KiB stderr window is not read as a name", async t => {
|
||||
const ctx = await setup(t, { session: { harness: 'pi', turnEnd: 'exit' } });
|
||||
ctx.inbox = [];
|
||||
// 52 + 16351 + 1 bytes: the 16 KiB window starts inside "claude", at "aude: No such file…".
|
||||
writeFileSync(join(ctx.dir, 'adapter.sh'),
|
||||
`printf 'x: line 1: /opt/x/claude: No such file or directory\\n' >&2\nhead -c 16351 /dev/zero | tr '\\0' 'z' >&2\nprintf '\\n' >&2\nexit 127\n`);
|
||||
const r = startRunner(ctx.runDir, ctx.cap);
|
||||
t.after(async () => { r.child.kill('SIGTERM'); await r.exited; });
|
||||
const reply = await ask(ctx);
|
||||
assert.equal(reply.body, "The turn failed: adapter exited 127");
|
||||
});
|
||||
|
||||
// Claude's private stream reader owns model activity; final result stdout alone
|
||||
// (even a synthetic success) must not cancel the model watchdog. Other adapters
|
||||
// still need the stdout fallback when no streaming producer is installed.
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"version": "8.0.42",
|
||||
"version": "8.0.79",
|
||||
"archive": {
|
||||
"asset": "CLIProxyAPI_8.0.42_linux_amd64.tar.gz",
|
||||
"url": "https://github.com/router-for-me/CLIProxyAPI/releases/download/v8.0.42/CLIProxyAPI_8.0.42_linux_amd64.tar.gz",
|
||||
"sha256": "1e10566fe0042ed5a9b80306cf296bf86a83de590cd967a8b177988b896c8d31"
|
||||
"asset": "CLIProxyAPI_8.0.79_linux_amd64.tar.gz",
|
||||
"url": "https://github.com/router-for-me/CLIProxyAPI/releases/download/v8.0.79/CLIProxyAPI_8.0.79_linux_amd64.tar.gz",
|
||||
"sha256": "7cbb9709ed939ff3684e10592a45cc538ee82d5da759daa7e18c7e1dc3b32acd"
|
||||
},
|
||||
"binary": {
|
||||
"sha256": "74661f8cf949977870231359e8bf4344e07946766a673c08fa25a3e5f72fc95e"
|
||||
"sha256": "4968bd27b04f813849add020b95a26dc7abf3e30810b97d291c0d88f495fe601"
|
||||
},
|
||||
"panel": {
|
||||
"version": "1.26.7",
|
||||
|
||||
@@ -56,8 +56,28 @@ uses a new temp root and private network namespace, with made-up credentials,
|
||||
and calls the page's bus verbs. If the page cannot pass against the new PIN,
|
||||
the upgrade stops; Sage takes Q46's fallback to Jason through Mos.
|
||||
|
||||
A running instance takes a new PIN in three steps, in this order. First run
|
||||
the new code: update the checkout or pinned copy the bus, Console and proxy
|
||||
unit start from. The proxy unit runs `run.mjs` and reads `PIN` from the tree
|
||||
it was installed from (`systemctl --user cat <unit>` shows it). If the new
|
||||
code is in that same tree, a restart picks it up. If it is in another tree,
|
||||
the unit keeps the old PIN until it is installed again from the new tree:
|
||||
stop it, remove its unit file, then `mosaic proxy unit install` from the new
|
||||
tree, because install never replaces a unit. Then run `mosaic proxy fetch` (or Fetch on the Console's
|
||||
Model proxy settings), which installs the new release beside the old one
|
||||
under `<dataRoot>/opt/cliproxyapi/<version>/`. Then restart the proxy with
|
||||
`mosaic proxy unit restart`. Before the fetch, the proxy fails to start with
|
||||
`proxy-install-missing`, and keeps failing until the fetch is done. Restart the bus and
|
||||
Console as well so their status and Fetch use the new PIN. `proxy.json` keeps
|
||||
the path from the PIN it was created under. That path stays valid, and the
|
||||
proxy always runs the hash-verified install for the current PIN. Signed-in
|
||||
accounts in `<dataRoot>/proxy/auth/` carry over. From 8.0.55 the proxy also
|
||||
keeps a `kv.db` file in that directory, and 8.0.79 adds a `.codex-refresh/`
|
||||
directory there once a Codex account renews. The old release directory can be
|
||||
removed once the new one runs.
|
||||
|
||||
The native `/proxy` page uses human-only bus verbs; only the bus holds the
|
||||
management client. On PIN 8.0.42, OAuth credentials are listed under
|
||||
management client. On PIN 8.0.79, OAuth credentials are listed under
|
||||
`/v8/management/credentials` and priority is patched as `{name, priority}`.
|
||||
API-key groups are absent from that list: z.ai keys use the Claude-compatible
|
||||
provider configuration at `/v8/management/config/api-keys/claude`, whose keys
|
||||
|
||||
@@ -7,12 +7,23 @@ export function installPaths(dataRoot, pin = PIN) {
|
||||
const dir = path.join(dataRoot, 'opt', 'cliproxyapi', pin.version);
|
||||
return { dir, binary: path.join(dir, 'cli-proxy-api'), panel: path.join(dir, 'static', 'management.html') };
|
||||
}
|
||||
// proxy.json records the install path from the PIN it was created under, and nothing
|
||||
// rewrites it. After a PIN bump an earlier release's path under this data root stays valid
|
||||
// and reads as the current pinned path. The runner executes only the hash-verified pinned
|
||||
// install, never the recorded path, so an old value selects nothing.
|
||||
const releasePath = (dataRoot, binary) => {
|
||||
const base = path.join(dataRoot, 'opt', 'cliproxyapi') + path.sep;
|
||||
if (typeof binary !== 'string' || !binary.startsWith(base)) return false;
|
||||
const [version, file, ...rest] = binary.slice(base.length).split(path.sep);
|
||||
return rest.length === 0 && file === 'cli-proxy-api' && /^\d{1,4}\.\d{1,4}\.\d{1,6}$/.test(version);
|
||||
};
|
||||
export function validateProxy(value, dataRoot, pin = PIN) {
|
||||
const pinned = installPaths(dataRoot, pin).binary;
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)
|
||||
|| Object.keys(value).some(k => !['binary', 'port', 'rotateGraceMinutes', 'firstOutputSeconds'].includes(k))
|
||||
|| !Number.isInteger(value.port) || value.port < 1024 || value.port > 65535 || value.port === 8317
|
||||
|| value.binary !== installPaths(dataRoot, pin).binary) refuse('proxy-config-invalid');
|
||||
return { port: value.port, binary: value.binary, ...proxyTiming(value) };
|
||||
|| (value.binary !== pinned && !releasePath(dataRoot, value.binary))) refuse('proxy-config-invalid');
|
||||
return { port: value.port, binary: pinned, ...proxyTiming(value) };
|
||||
}
|
||||
export function loadProxy(configDir, dataRoot) {
|
||||
const file = path.join(configDir, 'proxy.json');
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// P4 pinned8.0.42 regression: absent Claude provider config is HTTP404.
|
||||
// P4 regression since PIN 8.0.42 (still so on 8.0.79): absent Claude provider config is HTTP 404.
|
||||
// Normalize only that fixed GET; all other methods/endpoints/statuses refuse.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
@@ -13,3 +13,13 @@ for (const [field, maximum, code] of [['rotateGraceMinutes', 1440, 'proxy-rotate
|
||||
assert.throws(() => validateProxy({ ...base, [field]: value }, dataRoot), e => e.code === code);
|
||||
});
|
||||
}
|
||||
// #1873 PIN bump: a sidecar written under an earlier PIN keeps the instance config valid.
|
||||
test('a proxy.json written under an earlier PIN reads as the current pinned path', () => {
|
||||
const old = { ...base, binary: '/fixture-data/opt/cliproxyapi/8.0.42/cli-proxy-api' };
|
||||
assert.deepEqual(validateProxy(old, dataRoot), base);
|
||||
assert.deepEqual(validateProxy({ ...old, rotateGraceMinutes: 60 }, dataRoot), { ...base, rotateGraceMinutes: 60 });
|
||||
});
|
||||
for (const binary of ['/bad', '/fixture-data/opt/cliproxyapi/8.0.42/other', '/fixture-data/opt/cliproxyapi/latest/cli-proxy-api',
|
||||
'/fixture-data/opt/cliproxyapi/8.0.42/x/cli-proxy-api', '/fixture-data/opt/cliproxyapi/../cliproxyapi/8.0.42/cli-proxy-api',
|
||||
'/other-data/opt/cliproxyapi/8.0.42/cli-proxy-api', '/fixture-data/opt/cliproxyapi/8.0/cli-proxy-api', 7])
|
||||
test(`proxy-config-invalid: binary ${JSON.stringify(binary)}`, () => assert.throws(() => validateProxy({ ...base, binary }, dataRoot), e => e.code === 'proxy-config-invalid'));
|
||||
@@ -1,4 +1,4 @@
|
||||
// P4 client contract; endpoint/payload cases are probe-pending on PIN8.0.42.
|
||||
// P4 client contract; endpoint/payload cases were probe-pending on PIN 8.0.42.
|
||||
// Catches management key/body/query values leaking into receipts, redirects/retries.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
@@ -615,11 +615,6 @@ selection on this release's throwaway development instances. Receipt subjects
|
||||
name that principal, not Jason. The dev-purpose bootstrap fence is a separate
|
||||
follow-up before person-used deployment.
|
||||
|
||||
The optional `plugins.system-type` list enables installed system-type modules for
|
||||
an organization. Missing means none. Unknown ids refuse validation. Changes
|
||||
are owner-only; project selections are separate bus settings and a selection
|
||||
whose type is disabled remains recorded as inactive.
|
||||
|
||||
## Instance accounts (Phase M2)
|
||||
|
||||
`src/accounts.mjs` validates `<configDir>/accounts.json` without a dependency or
|
||||
@@ -689,3 +684,11 @@ After the pinned window, use an ordinary new decision.
|
||||
Policy has no effect executor. Per the Lead ruling, its in and existing out
|
||||
levels work, while near refuses `policy-reverse-unavailable` and directs the
|
||||
owner to choose in or out. Policy near and its reverse wait for that executor.
|
||||
|
||||
### Pack hires and rights (ruling 2026-11-14, #1873)
|
||||
|
||||
`src/org-rights.mjs` maps `pack.hire.console` to `org.hire`: hiring a starter
|
||||
pack's proposed agents is a hire, so a member with that right hires the
|
||||
unflagged proposals and the rest wait for the owner (invariant 7). The read
|
||||
`instanceSettings` returns each instance's `hireDecision`, which the bus's
|
||||
`instances` read uses to name the pack an agent came from.
|
||||
@@ -9,6 +9,7 @@ import { join } from "node:path";
|
||||
import { refuse } from "./errors.mjs";
|
||||
import { checkDefinitions } from "./definitions.mjs";
|
||||
import { loadRole } from "./role.mjs";
|
||||
import { SYSTEM_ONLY_REFUSAL, systemOnly } from "./vocabulary.mjs";
|
||||
import { checkVars, mergeVars, REGISTRY } from "./vars.mjs";
|
||||
import { deepFreeze, isPlainObject, readJsonFile, rejectUnknownKeys, requireDistinctList, requireId, requireObject } from "./util.mjs";
|
||||
|
||||
@@ -27,6 +28,8 @@ export function rootAgentsPath(configDir) {
|
||||
function definitionOf(name, at, rolesDir, cache, definitions = {}) {
|
||||
if (typeof name === "string" && name.startsWith("org:") && Object.hasOwn(definitions,name)) return definitions[name];
|
||||
requireId(name, `${at}.definition`);
|
||||
// #1873 triage-fence: no root or project agent, and so no copy of one, names a system-only template.
|
||||
if (systemOnly(name)) refuse(`${SYSTEM_ONLY_REFUSAL}: ${at}.definition names ${name}, a template no organization may hold`);
|
||||
if (!cache.has(name)) {
|
||||
// A role refusal names host paths; this message travels to the Console, so it names none.
|
||||
try { cache.set(name, loadRole(rolesDir, name)); }
|
||||
|
||||
@@ -15,6 +15,7 @@ import { OrganizationError } from "./organization.mjs";
|
||||
import {
|
||||
diffDefinition, entryFromTemplate, instancesNaming, readTemplate, templateHashes, checkDefinitionName, ORG_PREFIX,
|
||||
} from "./definitions.mjs";
|
||||
import { SYSTEM_ONLY_REFUSAL, systemOnly } from "./vocabulary.mjs";
|
||||
|
||||
// The verb names the policy table maps, following R1's hire.resolve.console.
|
||||
export const DEFINITION_VERBS = Object.freeze({
|
||||
@@ -64,6 +65,8 @@ export function definitionVerbs({ writer, rolesDir, assertClean }) {
|
||||
// Copies a template into definitions with from set to its name and current hash.
|
||||
function importTemplate(id, { revision, template, as = template }, caller) {
|
||||
authorize(caller, "import");
|
||||
// #1873 triage-fence: no organization imports a system-only template.
|
||||
if (systemOnly(template)) fail(SYSTEM_ONLY_REFUSAL);
|
||||
checkDefinitionName(as, "definition name");
|
||||
const source = readTemplate(rolesDir, template);
|
||||
const result = writer.setDefinition(id, as, (current) => {
|
||||
@@ -125,5 +128,5 @@ export function definitionVerbs({ writer, rolesDir, assertClean }) {
|
||||
return { organization: id, revision, ...diffDefinition(document, name, rolesDir) };
|
||||
}
|
||||
|
||||
return { import: importTemplate, edit, invent, remove, list, show, diff, templates: () => templateHashes(rolesDir) };
|
||||
return { import: importTemplate, edit, invent, remove, list, show, diff, templates: () => templateHashes(rolesDir).filter(({ template }) => !systemOnly(template)) };
|
||||
}
|
||||
@@ -23,7 +23,7 @@ import { createHash } from "node:crypto";
|
||||
import { refuse } from "./errors.mjs";
|
||||
import { buildRegistry, checkComposition } from "./composition.mjs";
|
||||
import { validateRoleDocument } from "./role.mjs";
|
||||
import { ID_PATTERN } from "./vocabulary.mjs";
|
||||
import { ID_PATTERN, SYSTEM_ONLY_REFUSAL, systemOnly } from "./vocabulary.mjs";
|
||||
import { canonicalJson, deepFreeze } from "./util.mjs";
|
||||
|
||||
export const ORG_PREFIX = "org:";
|
||||
@@ -88,6 +88,8 @@ export function checkDefinition(name, entry, { assertClean = NO_STORE, where = "
|
||||
keysOnly(entry.from, FROM_KEYS, `${at}.from`);
|
||||
if (typeof entry.from.template !== "string" || !ID_PATTERN.test(entry.from.template)) refuse(`${at}.from.template must be a template name matching ${ID_PATTERN}`);
|
||||
if (typeof entry.from.sha256 !== "string" || !HEX64.test(entry.from.sha256)) refuse(`${at}.from.sha256 must be 64 lowercase hex characters`);
|
||||
// #1873 triage-fence: no organization definition copies a system-only template.
|
||||
if (systemOnly(entry.from.template)) refuse(`${SYSTEM_ONLY_REFUSAL}: ${at}.from.template names ${entry.from.template}, a template no organization may hold`);
|
||||
}
|
||||
if (!plain(entry.role)) refuse(`${at}.role must be a JSON object`);
|
||||
keysOnly(entry.role, ROLE_KEYS, `${at}.role`);
|
||||
|
||||
@@ -8,7 +8,7 @@ import { compositionOf, entryFromTemplate, readTemplate, templateHashes } from '
|
||||
import { readRootAgentsFile, changeRootAgent } from './agent-levels-write.mjs';
|
||||
import { validateBusinessDocument } from './organization-config.mjs';
|
||||
import { canonicalJson, isPlainObject, readJsonFile } from './util.mjs';
|
||||
import { ID_PATTERN, NETWORKS } from './vocabulary.mjs';
|
||||
import { ID_PATTERN, NETWORKS, SYSTEM_ONLY_REFUSAL, systemOnly } from './vocabulary.mjs';
|
||||
import { OrganizationError } from './organization.mjs';
|
||||
import { resolveInstance } from './resolve.mjs';
|
||||
import { checkRoutes } from './launch-settings.mjs';
|
||||
@@ -204,6 +204,8 @@ export function hireDecisions({ writer, rolesDir, configDir, dataRoot, assertCle
|
||||
if ('template' in input.role) { id(input.role.template); if (!/^[a-f0-9]{64}$/.test(input.role.sha256??'') || Object.keys(input.role).length!==2) fail('invalid-request'); }
|
||||
if ('definition' in input.role) { id(input.role.definition); if (!Number.isSafeInteger(input.role.rev) || Object.keys(input.role).length!==2) fail('invalid-request'); }
|
||||
if ('inline' in input.role && Object.keys(input.role).length!==1) fail('invalid-request');
|
||||
// #1873 triage-fence: no hire or change at any level copies a system-only template.
|
||||
if (systemOnly(input.role.template)) fail(SYSTEM_ONLY_REFUSAL);
|
||||
} else if (['role','route','credentials','personality'].some(k=>k in input)) fail('invalid-request');
|
||||
const {document:doc,revision} = writer.read(business);
|
||||
const loaded = validateBusinessDocument(doc,`${business}.json`,{rolesDir,dataRoot});
|
||||
@@ -226,6 +228,7 @@ export function hireDecisions({ writer, rolesDir, configDir, dataRoot, assertCle
|
||||
if ('template' in ref) { const template=readTemplate(rolesDir,ref.template); if(template.sha256!==ref.sha256) fail('decision-stale'); entry=entryFromTemplate(template); }
|
||||
else if ('definition' in ref) { entry=doc.definitions?.[ref.definition]; if(!entry || entry.rev!==ref.rev) fail('definition-rev-conflict'); entry=structuredClone(entry); }
|
||||
else entry={rev:1,role:{},instructions:''};
|
||||
if (systemOnly(entry.from?.template)) fail(SYSTEM_ONLY_REFUSAL);
|
||||
let c='inline' in ref ? structuredClone(ref.inline) : compositionOf(entry);
|
||||
if ('credentials' in input) c.credentials=structuredClone(input.credentials);
|
||||
if ('personality' in input) c.personality=structuredClone(input.personality);
|
||||
@@ -387,5 +390,5 @@ export function hireDecisions({ writer, rolesDir, configDir, dataRoot, assertCle
|
||||
const result=writer.reverseHireDecision(business,p,{...caller,beforeWrite:guard,beforePublish:publicationGuard});
|
||||
return {...result,...(r.op==='change' && stopped?.running?{relaunch:publicOf(p)}:{})};
|
||||
}
|
||||
return {prepare,reverse,templates:()=>({templates:templateHashes(rolesDir).map(({template,sha256})=>({name:template,sha256}))}),preview:async(business,decision,caller)=>{const p=await adjusted(business,decision,caller.adjust);if(Date.parse(p.expiresAt)<=(caller.now??Date.now)())fail('decision-expired');authorizeHire(publicOf(p),caller);return publicOf(p);},rootRefusal,rootActive:name=>rootRefusal(name)===null,check:async(...args)=>{await check(...args);},apply,read: decision => publicOf(read(decision))};
|
||||
return {prepare,reverse,templates:()=>({templates:templateHashes(rolesDir).filter(({template})=>!systemOnly(template)).map(({template,sha256})=>({name:template,sha256}))}),preview:async(business,decision,caller)=>{const p=await adjusted(business,decision,caller.adjust);if(Date.parse(p.expiresAt)<=(caller.now??Date.now)())fail('decision-expired');authorizeHire(publicOf(p),caller);return publicOf(p);},rootRefusal,rootActive:name=>rootRefusal(name)===null,check:async(...args)=>{await check(...args);},apply,read: decision => publicOf(read(decision))};
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import { resolveInstance } from "./resolve.mjs";
|
||||
import { loadRole } from "./role.mjs";
|
||||
import { refuse } from "./errors.mjs";
|
||||
import { isPlainObject, canonicalJson } from "./util.mjs";
|
||||
import { CREATIVE_DEFINITIONS, CREATIVE_SERVICE, END_PROTECTED, HOST_SERVICE, ID_PATTERN, checkGrantScope, grantScopeOf } from "./vocabulary.mjs";
|
||||
import { CREATIVE_DEFINITIONS, CREATIVE_SERVICE, END_PROTECTED, HOST_SERVICE, ID_PATTERN, SYSTEM_ONLY_REFUSAL, checkGrantScope, grantScopeOf, systemOnly } from "./vocabulary.mjs";
|
||||
|
||||
const SET_KEYS = ["revision", "instance", "op", "definition", "vars", "launch", "tracker"];
|
||||
const VETO_KEYS = ["revision", "op", "name"];
|
||||
@@ -93,6 +93,8 @@ const sameCredentialServices = (before, after) => credentialServices(before).joi
|
||||
// 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 } = {}) {
|
||||
// #1873 triage-fence: no add or change of definition gives an instance a system-only template.
|
||||
if (systemOnly(name)) throw new OrganizationError(SYSTEM_ONLY_REFUSAL);
|
||||
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`);
|
||||
@@ -153,6 +155,8 @@ export function instanceSettings({ dir, rolesDir, system, levels = () => null, r
|
||||
const out = {};
|
||||
for (const file of readdirSync(rolesDir).filter(f => f.endsWith(".json")).sort()) {
|
||||
const name = file.slice(0, -5);
|
||||
// #1873 triage-fence: the add list never offers a system-only template.
|
||||
if (systemOnly(name)) continue;
|
||||
let definition;
|
||||
try {
|
||||
definition = loadRole(rolesDir, name);
|
||||
@@ -183,6 +187,8 @@ export function instanceSettings({ dir, rolesDir, system, levels = () => null, r
|
||||
protected: closed(entry.definition),
|
||||
kept: (launch?.keep ?? []).includes(name),
|
||||
endProtected: protectedRefusal(document, name, actor) !== null,
|
||||
// Ruling 2026-11-14: a hired instance names its hire decision; the bus adds the pack it came from.
|
||||
...(typeof entry.hireDecision === 'string' ? { hireDecision: entry.hireDecision } : {}),
|
||||
}]));
|
||||
// Row 194 (D1): the human's forbid lists and the retired names. The bus adds running runs.
|
||||
return {
|
||||
|
||||
@@ -87,7 +87,6 @@ export const VERB_RIGHTS = record({
|
||||
'request.draft.console': 'request.write',
|
||||
'prd.revoke.console': 'request.write',
|
||||
'plugins.set': 'org.setup',
|
||||
'system-types.console': 'org.setup',
|
||||
'project.remote.get.console': 'org.setup',
|
||||
'project.remote.set.console': 'org.setup',
|
||||
// #1873 SP4: starter packs, the board and workflows. The list is a board read; every write is
|
||||
@@ -95,6 +94,9 @@ export const VERB_RIGHTS = record({
|
||||
'packs.console': 'board.read',
|
||||
'pack.preview.console': null,
|
||||
'pack.apply.console': null,
|
||||
// Ruling 2026-11-14: hiring a pack's proposed agents is a hire; a member with org.hire gets the
|
||||
// unflagged ones and the rest wait for the owner (invariant 7).
|
||||
'pack.hire.console': 'org.hire',
|
||||
'board.set.console': null,
|
||||
'workflow.set.console': null,
|
||||
// #1873 SP8: saving a template, and listing the saved ones, are the owner's alone: a template is a
|
||||
|
||||
@@ -12,10 +12,8 @@ import { checkVars } from "./vars.mjs";
|
||||
import { parseCredentialRef } from "./credentials.mjs";
|
||||
import { loadRole } from "./role.mjs";
|
||||
import { checkDefinition, checkDefinitions, checkDefinitionName, orgDefinitionName, ORG_PREFIX } from "./definitions.mjs";
|
||||
import { END_PROTECTED, parseRepoRemote } from "./vocabulary.mjs";
|
||||
import { END_PROTECTED, parseRepoRemote, SYSTEM_ONLY_REFUSAL, systemOnly } from "./vocabulary.mjs";
|
||||
import { checkPlugins, checkUsageSettings, NAME as KIND_NAME } from "../../plugins/src/kinds.mjs";
|
||||
import { hasModule } from "../../plugins/src/loader.mjs";
|
||||
import { readPluginLock } from "../../plugins/src/pinned.mjs";
|
||||
import { checkMapping } from "../../library/src/mapping.mjs";
|
||||
import { forkProblem, giteaName, parseGiteaUrl, HOST_SERVICE, CREATIVE_DEFINITIONS } from "./vocabulary.mjs";
|
||||
import { checkAppearance } from "./appearance.mjs";
|
||||
@@ -115,6 +113,8 @@ function checkPin(pin, where) {
|
||||
if (!shape) refuse(`${where} must be {template, sha256}, {definition, rev} or {inline}`);
|
||||
if (shape[0] === "template") {
|
||||
requireId(pin.template, `${where}.template`);
|
||||
// #1873 triage-fence: no pack proposal pins a system-only template.
|
||||
if (systemOnly(pin.template)) refuse(`${SYSTEM_ONLY_REFUSAL}: ${where}.template names ${pin.template}, a template no organization may hold`);
|
||||
if (typeof pin.sha256 !== "string" || !HEX64.test(pin.sha256)) refuse(`${where}.sha256 must be 64 lowercase hex characters`);
|
||||
} else if (shape[0] === "definition") {
|
||||
checkDefinitionName(pin.definition, `${where}.definition`);
|
||||
@@ -287,8 +287,11 @@ function checkRoles(roles, file, rolesDir, business, hasLibrary, orgDefinitions)
|
||||
rejectUnknownKeys(entry, ["definition", "holder", "vars", "tracker", "credentials", "identity", "publish", "hosts", "hireDecision"], at);
|
||||
// #1873 T1: "org:<name>" names one of this file's definitions; anything else is a template.
|
||||
const orgName = orgDefinitionName(entry.definition);
|
||||
if (orgName === null) requireId(entry.definition, `${at}.definition`);
|
||||
else if (!Object.hasOwn(orgDefinitions, ORG_PREFIX + checkDefinitionName(orgName, `${at}.definition after org:`))) {
|
||||
if (orgName === null) {
|
||||
requireId(entry.definition, `${at}.definition`);
|
||||
// #1873 triage-fence: no instance names a system-only template.
|
||||
if (systemOnly(entry.definition)) refuse(`${SYSTEM_ONLY_REFUSAL}: ${at}.definition names ${entry.definition}, a template no organization may hold`);
|
||||
} else if (!Object.hasOwn(orgDefinitions, ORG_PREFIX + checkDefinitionName(orgName, `${at}.definition after org:`))) {
|
||||
refuse(`definition-missing: ${at}.definition names ${ORG_PREFIX}${orgName}, which definitions doesn't declare`);
|
||||
}
|
||||
const definition = Object.hasOwn(definitions, entry.definition) ? definitions[entry.definition]
|
||||
@@ -505,14 +508,6 @@ export function validateOrganizationDocument(document, file, { rolesDir, dataRoo
|
||||
// here; whether each module loads is the loader's check, at load time.
|
||||
const plugins = document.plugins === undefined ? {}
|
||||
: structuredClone(checkPlugins(document.plugins, `${file} plugins`, { fail: (_code, message) => refuse(message) }));
|
||||
let installedNames = new Set();
|
||||
if (dataRoot !== null && plugins["system-type"]?.some(id=>!hasModule("system-type",id))) {
|
||||
try { installedNames = new Set(Object.keys(readPluginLock(dataRoot).plugins)); }
|
||||
catch { installedNames = null; } // the loader reports an unreadable lock; core still loads
|
||||
}
|
||||
for (const id of plugins["system-type"] ?? []) {
|
||||
if (!hasModule("system-type", id) && installedNames !== null && !installedNames.has(id)) refuse(`${file} plugins.system-type names unknown module ${id}`);
|
||||
}
|
||||
const usage = document.usage === undefined ? undefined : checkUsageSettings(document.usage);
|
||||
const autonomy = checkAutonomy(document.autonomy);
|
||||
if(autonomy?.authorityResolver) {
|
||||
|
||||
@@ -126,13 +126,6 @@ function autonomyFence(old, document, actor) {
|
||||
if(actor!==old.human || actor==='tester' || agents.includes(actor))fail('human-required');
|
||||
}
|
||||
|
||||
function systemTypesFence(old, document, actor) {
|
||||
if (canonicalJson(old.plugins?.['system-type'] ?? []) === canonicalJson(document?.plugins?.['system-type'] ?? [])) return;
|
||||
const agents = Object.entries(old.roles ?? {}).flatMap(([name, role]) => [name, `${role?.definition}.${name}`]);
|
||||
if (actor === old.human && actor !== 'tester' && !agents.includes(actor)) return;
|
||||
fail('organization-system-types-human-only');
|
||||
}
|
||||
|
||||
// C2-06 M11: replyLimits is the human's alone. Any setter that changes it refuses unless the actor is
|
||||
// the business's human as the file stood before the write, and no agent or the tester under that
|
||||
// name. Compared as M9 compares projects, on the document and again on what lands on disk.
|
||||
@@ -320,7 +313,6 @@ export function organizationWriter({ dir, rolesDir, dataRoot = null, barrier = (
|
||||
replyLimitsFence(old, document, actor);
|
||||
modelQuotaFence(old, document, actor);
|
||||
usageFence(old, document, actor);
|
||||
systemTypesFence(old, document, actor);
|
||||
autonomyFence(old, document, actor);
|
||||
validateBusinessDocument(document, file, { rolesDir, dataRoot });
|
||||
const bytes = JSON.stringify(document, null, 2) + "\n";
|
||||
@@ -332,7 +324,6 @@ export function organizationWriter({ dir, rolesDir, dataRoot = null, barrier = (
|
||||
replyLimitsFence(old, written, actor);
|
||||
modelQuotaFence(old, written, actor);
|
||||
usageFence(old, written, actor);
|
||||
systemTypesFence(old, written, actor);
|
||||
autonomyFence(old, written, actor);
|
||||
validateBusinessDocument(written, file, { rolesDir, dataRoot });
|
||||
if (beforeWrite) {
|
||||
|
||||
@@ -10,10 +10,13 @@
|
||||
// (instance credentials, copyBindings, copyId, orgIncarnation, generation), launch, plugins, vars,
|
||||
// project roots and git state, definition revs and hire decisions, and everything on the bus.
|
||||
//
|
||||
// Free text is kept, with the organization id, its project ids, its agent names, the owner's
|
||||
// account and the project roots replaced by {org}, {project}, {agent}, {owner} and {root}. The
|
||||
// preview lists each replacement and every kept free-text field by path, and the exact JSON save
|
||||
// writes; save takes that JSON's digest. Every string and key is passed to the credential store's
|
||||
// Free text is kept verbatim: save never rewrites prose (E2E6 fix 5, Lead ruling). A placeholder
|
||||
// could stand only where a field's whole value is an organization identifier, and a pack carries no
|
||||
// such field (hire names are <role>-<n>, step roles name definitions or templates), so save writes
|
||||
// none and apply has none to resolve. The preview lists every kept free-text field by path, each
|
||||
// one that mentions the organization id, a project id, an agent name, the owner's account or a
|
||||
// project root (so the owner can edit it before saving), and the exact JSON save writes; save takes
|
||||
// that JSON's digest. Every string and key is passed to the credential store's
|
||||
// assertClean; a hit refuses template-secret-suspected naming the path, never the text.
|
||||
//
|
||||
// A refusal is a TemplateError: a bus code and a reason that names a path or a checked name only,
|
||||
@@ -49,8 +52,8 @@ export const DEFAULT_BOARD = Object.freeze({
|
||||
layout: "kanban",
|
||||
});
|
||||
const HIRE_REASON = "The organization this template was saved from ran this agent.";
|
||||
// A word boundary for placeholder replacement: an identifier character on either side means the
|
||||
// literal is part of a longer name, which stays as it is.
|
||||
// A word boundary for a mention: an identifier character on either side means the literal is part of
|
||||
// a longer name, which is not a mention.
|
||||
const WORD = "A-Za-z0-9_-";
|
||||
|
||||
export class TemplateError extends Error {
|
||||
@@ -100,63 +103,63 @@ function templateOrNull(rolesDir, name, cache) {
|
||||
return cache.get(name);
|
||||
}
|
||||
|
||||
// ---- Placeholders ----
|
||||
// ---- Mentions ----
|
||||
|
||||
// The literals section 5 replaces, longest first so a root path is replaced before the ids inside
|
||||
// it. A name that is also a template or a definition name is a role's name, not a person's or a
|
||||
// client's, and stays: replacing "coder" would rewrite every role text that says coder.
|
||||
function literals(document, { rolesDir, cache }) {
|
||||
// The organization-specific names the preview looks for in kept text, longest first so a root path
|
||||
// is found before the ids inside it. A name that is also a template or a definition name is a role's
|
||||
// name, not a person's or a client's, and is not a mention: role text says "coder" on purpose. A
|
||||
// mention is labelled by kind and name; a project root is labelled by kind alone, so the preview
|
||||
// names no host path beyond the text it already shows.
|
||||
function orgNames(document, { rolesDir, cache }) {
|
||||
const out = [];
|
||||
const add = (text, placeholder) => {
|
||||
if (typeof text === "string" && text.length > 0 && !out.some((l) => l.text === text)) out.push({ text, placeholder });
|
||||
const add = (text, label) => {
|
||||
if (typeof text === "string" && text.length > 0 && !out.some((l) => l.text === text)) out.push({ text, label });
|
||||
};
|
||||
for (const project of Object.values(document.projects ?? {})) {
|
||||
add(project?.root, "{root}");
|
||||
add(project?.repo, "{root}");
|
||||
add(project?.root, "project root");
|
||||
add(project?.repo, "project root");
|
||||
}
|
||||
add(document.id, "{org}");
|
||||
for (const id of Object.keys(document.projects ?? {})) add(id, "{project}");
|
||||
add(document.human, "{owner}");
|
||||
if (typeof document.id === "string") add(document.id, `organization ${document.id}`);
|
||||
for (const id of Object.keys(document.projects ?? {})) add(id, `project ${id}`);
|
||||
if (typeof document.human === "string") add(document.human, `owner ${document.human}`);
|
||||
const role = (name) => Object.hasOwn(document.definitions ?? {}, name) || templateOrNull(rolesDir, name, cache) !== null;
|
||||
const agents = new Set([...Object.keys(document.roles ?? {}), ...(Array.isArray(document.retired) ? document.retired : [])]);
|
||||
for (const project of Object.values(document.projects ?? {})) for (const name of Object.keys(project?.agents ?? {})) agents.add(name);
|
||||
for (const name of agents) if (!role(name)) add(name, "{agent}");
|
||||
for (const name of agents) if (!role(name)) add(name, `agent ${name}`);
|
||||
out.sort((a, b) => b.text.length - a.text.length);
|
||||
return out;
|
||||
}
|
||||
|
||||
// Returns the text with every literal replaced, and counts each placeholder used. One pass over the
|
||||
// text with one alternation, longest literal first: a placeholder written in never matches a later
|
||||
// literal, so an instance named "root" or "agent" cannot rewrite {root} or {agent}.
|
||||
// The labels of every name the text mentions, in first-mention order, each once. One pass with one
|
||||
// alternation, longest name first, so a root path is one mention and not the ids inside it.
|
||||
const combined = new WeakMap();
|
||||
function replace(text, list, counts) {
|
||||
if (list.length === 0) return text;
|
||||
function mentions(text, list) {
|
||||
if (list.length === 0) return [];
|
||||
let entry = combined.get(list);
|
||||
if (!entry) {
|
||||
const by = new Map(list.map((l) => [l.text, l.placeholder]));
|
||||
const by = new Map(list.map((l) => [l.text, l.label]));
|
||||
entry = { by, pattern: new RegExp(`(?<![${WORD}])(?:${list.map((l) => escape(l.text)).join("|")})(?![${WORD}])`, "g") };
|
||||
combined.set(list, entry);
|
||||
}
|
||||
return text.replace(entry.pattern, (match) => {
|
||||
const placeholder = entry.by.get(match);
|
||||
counts[placeholder] = (counts[placeholder] ?? 0) + 1;
|
||||
return placeholder;
|
||||
});
|
||||
const found = [];
|
||||
for (const match of text.matchAll(entry.pattern)) {
|
||||
const label = entry.by.get(match[0]);
|
||||
if (!found.includes(label)) found.push(label);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
// ---- Capture ----
|
||||
|
||||
// Builds the template document. With list null, free text is kept as it is (the scan's second
|
||||
// copy); otherwise each replacement and each kept free-text field is recorded by path.
|
||||
// Builds the template document. Free text is copied verbatim; each kept free-text field, and each
|
||||
// one that mentions an organization-specific name, is recorded by path.
|
||||
function capture(document, { name, project, rolesDir, list, record }) {
|
||||
const cache = new Map();
|
||||
const text = (value, path) => {
|
||||
if (list === null) return value;
|
||||
const counts = {};
|
||||
const out = replace(value, list, counts);
|
||||
for (const [placeholder, count] of Object.entries(counts)) record.replacements.push({ path, placeholder, count });
|
||||
record.freeText.push({ path, text: out });
|
||||
return out;
|
||||
record.freeText.push({ path, text: value });
|
||||
const names = mentions(value, list);
|
||||
if (names.length > 0) record.mentions.push({ path, names });
|
||||
return value;
|
||||
};
|
||||
const orgDefinitions = plain(document.definitions) ? document.definitions : {};
|
||||
const scope = project === undefined ? "org" : "project";
|
||||
@@ -233,7 +236,7 @@ function capture(document, { name, project, rolesDir, list, record }) {
|
||||
if (!template) refuse("starter-pack-invalid", `${at}.from names a template that is not a version 2 role`);
|
||||
// A template that changed since the definition copied it: the saved from names its current
|
||||
// hash, and the role must still narrow the current template. The preview lists the re-pin.
|
||||
if (template.sha256 !== entry.from.sha256 && list !== null) record.repinned.push(`${at}.from`);
|
||||
if (template.sha256 !== entry.from.sha256) record.repinned.push(`${at}.from`);
|
||||
out.from = { template: template.name, sha256: template.sha256 };
|
||||
let composition;
|
||||
try {
|
||||
@@ -323,11 +326,12 @@ function capture(document, { name, project, rolesDir, list, record }) {
|
||||
seen.add(k);
|
||||
packs.push({ id: entry.id, version: entry.version });
|
||||
}
|
||||
if (list !== null) record.packsDropped = Math.max(0, packs.length - PACK_BOUNDS.packs);
|
||||
record.packsDropped = Math.max(0, packs.length - PACK_BOUNDS.packs);
|
||||
const keptPacks = packs.slice(Math.max(0, packs.length - PACK_BOUNDS.packs));
|
||||
|
||||
const label = name.slice(0, PACK_BOUNDS.label);
|
||||
const descriptionText = scope === "org" ? "Saved from {org}." : "Saved from {project} in {org}.";
|
||||
// No placeholder: apply copies the description as it stands, so a "{org}" here would stay literal.
|
||||
const descriptionText = scope === "org" ? "Saved from an organization." : "Saved from one project of an organization.";
|
||||
return {
|
||||
packVersion: PACK_VERSION, id: name, version: "1.0.0", label, description: descriptionText, scope,
|
||||
definitions, hires, board, workflows, skills, packs: keptPacks,
|
||||
@@ -356,20 +360,16 @@ function scan(value, path, assertClean) {
|
||||
}
|
||||
}
|
||||
|
||||
// The preview: the exact JSON save writes, its digest, each replacement and each kept free-text
|
||||
// field by path. Refuses before returning when any string or key holds a held credential value.
|
||||
// The preview: the exact JSON save writes, its digest, each kept free-text field by path, each such
|
||||
// field that mentions an organization-specific name, with the names it mentions, and each re-pin.
|
||||
// Refuses before returning when any string or key holds a held credential value.
|
||||
export function templatePreview({ document, name, project, rolesDir, assertClean }) {
|
||||
checkTemplateName(name);
|
||||
if (project !== undefined && (typeof project !== "string" || !ID_PATTERN.test(project))) refuse("invalid-request", "the project id is invalid");
|
||||
if (typeof assertClean !== "function") throw new TypeError("templatePreview needs the credential store's assertClean");
|
||||
if (!plain(document)) refuse("invalid-request", "the organization file is not readable");
|
||||
const scope = { name, project, rolesDir };
|
||||
// The scan reads both copies: the kept text before replacement (a held value a placeholder would
|
||||
// break up still refuses) and the document save writes.
|
||||
const raw = capture(document, { ...scope, list: null, record: null });
|
||||
scan(raw, "", assertClean);
|
||||
const record = { replacements: [], freeText: [], repinned: [], packsDropped: 0 };
|
||||
const template = capture(document, { ...scope, list: literals(document, { rolesDir, cache: new Map() }), record });
|
||||
const record = { freeText: [], mentions: [], repinned: [], packsDropped: 0 };
|
||||
const template = capture(document, { name, project, rolesDir, list: orgNames(document, { rolesDir, cache: new Map() }), record });
|
||||
scan(template, "", assertClean);
|
||||
let checked;
|
||||
try {
|
||||
@@ -386,13 +386,27 @@ export function templatePreview({ document, name, project, rolesDir, assertClean
|
||||
return {
|
||||
name, scope: checked.scope, ...(project === undefined ? {} : { project }),
|
||||
template: checked, json, digest: sha256(json),
|
||||
replacements: record.replacements.sort(byPath), freeText: record.freeText.sort(byPath),
|
||||
freeText: record.freeText.sort(byPath), mentions: record.mentions.sort(byPath),
|
||||
repinned: record.repinned.sort(), packsDropped: record.packsDropped,
|
||||
};
|
||||
}
|
||||
|
||||
// ---- The file ----
|
||||
|
||||
const TEMPLATE_EXISTS = "a template of this name is already saved; save under another name";
|
||||
// Whether a file (or anything, a symlink included) already holds the name. It looks only through a
|
||||
// templates and an account directory that are real directories, so a link is never followed to say
|
||||
// what lies elsewhere; any other case is left to the directory checks and the exclusive create.
|
||||
function taken(templates, home, file) {
|
||||
try {
|
||||
if (!lstatSync(templates).isDirectory() || !lstatSync(home).isDirectory()) return false;
|
||||
lstatSync(file);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// A directory save writes under: real, the uid's own, writable by nobody else. The account's own
|
||||
// directory is private (0700 or narrower), as readSavedTemplate requires.
|
||||
function directory(path, uid, { private: closed }) {
|
||||
@@ -413,23 +427,25 @@ function directory(path, uid, { private: closed }) {
|
||||
}
|
||||
|
||||
// Save: the preview again, its digest compared, then the file created exclusively (wx, 0600). A
|
||||
// name already saved refuses; nothing is replaced.
|
||||
// name already saved refuses template-exists; nothing is replaced. The name is checked before the
|
||||
// digest, so a save under a taken name says so even when the preview is stale.
|
||||
export function templateSave({ document, name, project, digest, rolesDir, assertClean, configDir, account, uid = process.getuid() }) {
|
||||
checkAccount(account);
|
||||
checkTemplateName(name);
|
||||
if (typeof digest !== "string" || !/^[0-9a-f]{64}$/.test(digest)) refuse("invalid-request", "save takes the preview's digest");
|
||||
const preview = templatePreview({ document, name, project, rolesDir, assertClean });
|
||||
if (preview.digest !== digest) refuse("pack-plan-stale", "the organization or a template changed since the preview");
|
||||
const templates = join(configDir, "templates");
|
||||
const home = join(templates, account);
|
||||
const file = join(home, `${name}.json`);
|
||||
if (taken(templates, home, file)) refuse("template-exists", TEMPLATE_EXISTS);
|
||||
const preview = templatePreview({ document, name, project, rolesDir, assertClean });
|
||||
if (preview.digest !== digest) refuse("pack-plan-stale", "the organization or a template changed since the preview");
|
||||
directory(templates, uid, { private: false });
|
||||
directory(home, uid, { private: true });
|
||||
const file = join(home, `${name}.json`);
|
||||
let fd;
|
||||
try {
|
||||
fd = openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
||||
} catch (error) {
|
||||
if (error?.code === "EEXIST") refuse("invalid-request", "a template of this name is already saved");
|
||||
if (error?.code === "EEXIST") refuse("template-exists", TEMPLATE_EXISTS);
|
||||
refuse("not-configured", "the template file cannot be created");
|
||||
}
|
||||
try {
|
||||
|
||||
@@ -209,6 +209,15 @@ export const THREAD_DEFINITIONS = Object.freeze([THREAD_DEFINITION, ...CREATIVE_
|
||||
// organization write may give an instance one of them, except the human's instances.set for a
|
||||
// creative definition (row 213).
|
||||
export const END_PROTECTED = THREAD_DEFINITIONS;
|
||||
// #1873 lane triage-fence: the shipped templates no organization may hold. Jason approved the
|
||||
// Triage template on 2026-11-16; its use outside an organization waits for his ruling. Every path
|
||||
// by which an organization could gain a role reads this list and refuses with SYSTEM_ONLY_REFUSAL:
|
||||
// a hire or change at org, project or root level, a pack preview or apply, instances.set, the
|
||||
// organization file's own validation, and every template list a page offers. The template itself
|
||||
// still loads and validates as a template.
|
||||
export const SYSTEM_ONLY = Object.freeze(["triage"]);
|
||||
export const SYSTEM_ONLY_REFUSAL = "template-system-only";
|
||||
export const systemOnly = name => typeof name === "string" && SYSTEM_ONLY.includes(name);
|
||||
|
||||
// Row 199 (#1697, design D9c): the Gitea URL parse. It lives here because the broker reads it and
|
||||
// this file imports nothing. Gitea's name rule for users and repositories: letters, digits, "_", "."
|
||||
|
||||
@@ -79,7 +79,6 @@ const VERBS = {
|
||||
'request.draft.console': 'request.write',
|
||||
'prd.revoke.console': 'request.write',
|
||||
'plugins.set': 'org.setup',
|
||||
'system-types.console': 'org.setup',
|
||||
'project.remote.get.console': 'org.setup',
|
||||
'project.remote.set.console': 'org.setup',
|
||||
// #1873 SP4: starter packs, the board and workflows. The list is a board read; every write is
|
||||
@@ -87,6 +86,7 @@ const VERBS = {
|
||||
'packs.console': 'board.read',
|
||||
'pack.preview.console': null,
|
||||
'pack.apply.console': null,
|
||||
'pack.hire.console': 'org.hire',
|
||||
'board.set.console': null,
|
||||
'workflow.set.console': null,
|
||||
// Starter packs SP8 (#1873): saving a template and listing the saved ones are the owner's alone.
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
// #1873 lane triage-fence: the Triage template is system-only. Jason approved the template on
|
||||
// 2026-11-16; no organization may hold it until he rules on its use outside one. Every place an
|
||||
// organization could gain it refuses with one code, template-system-only, and the template itself
|
||||
// still loads and validates as a template. Fixtures live in a temp directory.
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
// A namespace import, so a run against the commit before the fence fails test by test, not at load.
|
||||
import * as vocabulary from "../src/vocabulary.mjs";
|
||||
import { checkDefinition, entryFromTemplate, readTemplate, templateHash, templateHashes } from "../src/definitions.mjs";
|
||||
import { loadRole } from "../src/role.mjs";
|
||||
import { validateBusinessDocument } from "../src/organization-config.mjs";
|
||||
import { checkProjectAgents, checkRootAgents } from "../src/agent-levels.mjs";
|
||||
import { hireDecisions } from "../src/hire-decisions.mjs";
|
||||
import { instanceSettings } from "../src/instance-settings.mjs";
|
||||
import { definitionVerbs } from "../src/definition-verbs.mjs";
|
||||
import { organizationWriter } from "../src/organization.mjs";
|
||||
import { ROLE_RIGHTS } from "../src/org-rights.mjs";
|
||||
import { checkPack, installedStarterPacks } from "../../plugins/src/starter-pack.mjs";
|
||||
import { businessDoc, rolesCopy, systemFor, tmp, writeJson } from "./helpers.mjs";
|
||||
|
||||
const CODE = "template-system-only";
|
||||
const coded = (e) => e?.code === CODE;
|
||||
const prefixed = (e) => e?.name === "BusinessError" && e.message.startsWith(`${CODE}: `);
|
||||
const OWNER = { actor: "jason", agent: false, rights: ["org.hire"], owner: true, instanceOwner: true, subject: { provider: "test", iss: "https://test", sub: "owner" } };
|
||||
const DEF_OWNER = { actor: "jason", rights: [...ROLE_RIGHTS.owner], agent: false };
|
||||
const ROUTE = { harness: "pi", model: "claude-opus-5-5" };
|
||||
|
||||
function rootDir(t) {
|
||||
const root = tmp();
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
return root;
|
||||
}
|
||||
|
||||
function hireSetup(t) {
|
||||
const root = mkdtempSync(join(tmpdir(), "so-"));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
const rolesDir = rolesCopy(root);
|
||||
writeJson(join(root, "businesses/demo.json"), { ...businessDoc(root, "demo"), plugins: { harness: ["pi"] } });
|
||||
const writer = organizationWriter({ dir: root, rolesDir });
|
||||
const dataRoot = join(root, "data");
|
||||
mkdirSync(dataRoot, { mode: 0o700 });
|
||||
const service = hireDecisions({ writer, rolesDir, configDir: root, dataRoot, assertClean: () => {} });
|
||||
const triage = { template: "triage", sha256: templateHash(rolesDir, "triage") };
|
||||
let n = 0;
|
||||
const prepare = (extra) => service.prepare("demo", { op: "hire", level: "org", name: "sorter", role: triage, route: ROUTE, reason: "Sort the inbox", ...extra },
|
||||
{ id: `1111111${n++}-1111-4111-8111-111111111111`, expiresAt: "2099-01-01T00:00:00.000Z" });
|
||||
return { root, rolesDir, writer, service, prepare, triage };
|
||||
}
|
||||
|
||||
function settingsSetup(t) {
|
||||
const root = rootDir(t);
|
||||
const rolesDir = rolesCopy(root);
|
||||
const dir = join(root, "config");
|
||||
const doc = businessDoc(root, "acme");
|
||||
doc.plugins = { harness: ["pi", "claude-code"] };
|
||||
writeJson(join(dir, "businesses", "acme.json"), doc);
|
||||
return { rolesDir, settings: instanceSettings({ dir, rolesDir, system: systemFor(root) }) };
|
||||
}
|
||||
|
||||
function verbsSetup(t) {
|
||||
const root = rootDir(t);
|
||||
const dir = join(root, "config");
|
||||
const rolesDir = rolesCopy(root);
|
||||
writeJson(join(dir, "businesses/acme.json"), businessDoc(root));
|
||||
const writer = organizationWriter({ dir, rolesDir });
|
||||
return { root, dir, rolesDir, writer, verbs: definitionVerbs({ writer, rolesDir, assertClean: () => {} }) };
|
||||
}
|
||||
|
||||
test("the list is one name, triage, and its refusal code is template-system-only", () => {
|
||||
assert.deepEqual([...(vocabulary.SYSTEM_ONLY ?? [])], ["triage"]);
|
||||
assert.equal(vocabulary.SYSTEM_ONLY_REFUSAL, CODE);
|
||||
assert.equal(vocabulary.systemOnly?.("triage"), true);
|
||||
assert.equal(vocabulary.systemOnly?.("coder"), false);
|
||||
assert.equal(vocabulary.systemOnly?.(undefined), false);
|
||||
});
|
||||
|
||||
test("triage still loads and validates as a template", (t) => {
|
||||
const rolesDir = rolesCopy(rootDir(t));
|
||||
const role = loadRole(rolesDir, "triage");
|
||||
assert.equal(role.roleVersion, 2);
|
||||
const source = readTemplate(rolesDir, "triage");
|
||||
assert.match(source.sha256, /^[a-f0-9]{64}$/);
|
||||
assert.ok(templateHashes(rolesDir).some(({ template }) => template === "triage"));
|
||||
});
|
||||
|
||||
test("hire refuses a triage template at org level", async (t) => {
|
||||
const f = hireSetup(t);
|
||||
await assert.rejects(f.prepare(), coded);
|
||||
});
|
||||
|
||||
test("hire refuses a triage template at project level", async (t) => {
|
||||
const f = hireSetup(t);
|
||||
await assert.rejects(f.prepare({ level: "project", project: "stack" }), coded);
|
||||
});
|
||||
|
||||
test("hire refuses a triage template at root level", async (t) => {
|
||||
const f = hireSetup(t);
|
||||
await assert.rejects(f.prepare({ level: "root" }), coded);
|
||||
});
|
||||
|
||||
test("a change refuses to move an org instance onto triage", async (t) => {
|
||||
const f = hireSetup(t);
|
||||
await assert.rejects(f.prepare({ op: "change", name: "coder" }), coded);
|
||||
});
|
||||
|
||||
test("the hire template list a page offers omits triage and keeps every other template", (t) => {
|
||||
const f = hireSetup(t);
|
||||
const offered = f.service.templates().templates.map(({ name }) => name);
|
||||
assert.ok(!offered.includes("triage"));
|
||||
assert.deepEqual(offered, templateHashes(f.rolesDir).map(({ template }) => template).filter((n) => n !== "triage"));
|
||||
});
|
||||
|
||||
test("instances add refuses triage for the human and the tester", (t) => {
|
||||
const f = settingsSetup(t);
|
||||
for (const actor of ["jason", "tester"]) {
|
||||
const revision = f.settings.read("acme").revision;
|
||||
assert.throws(() => f.settings.set("acme", { revision, instance: "sorter", op: "add", definition: "triage" }, actor), coded, actor);
|
||||
}
|
||||
});
|
||||
|
||||
test("instances change of definition refuses triage", (t) => {
|
||||
const f = settingsSetup(t);
|
||||
const revision = f.settings.read("acme").revision;
|
||||
assert.throws(() => f.settings.set("acme", { revision, instance: "coder", op: "change", definition: "triage" }, "jason"), coded);
|
||||
});
|
||||
|
||||
test("the instances add list omits triage", (t) => {
|
||||
const f = settingsSetup(t);
|
||||
assert.equal(Object.hasOwn(f.settings.read("acme").definitions, "triage"), false);
|
||||
});
|
||||
|
||||
test("an organization file whose roles name triage is refused", (t) => {
|
||||
const root = rootDir(t);
|
||||
const rolesDir = rolesCopy(root);
|
||||
const doc = businessDoc(root);
|
||||
doc.roles.sorter = { definition: "triage" };
|
||||
assert.throws(() => validateBusinessDocument(doc, join(root, "acme.json"), { rolesDir }), prefixed);
|
||||
});
|
||||
|
||||
test("an organization definition copied from triage is refused", (t) => {
|
||||
const rolesDir = rolesCopy(rootDir(t));
|
||||
const entry = entryFromTemplate(readTemplate(rolesDir, "triage"));
|
||||
assert.throws(() => checkDefinition("sorter", entry), prefixed);
|
||||
});
|
||||
|
||||
test("a root agent naming triage is refused", (t) => {
|
||||
const rolesDir = rolesCopy(rootDir(t));
|
||||
assert.throws(() => checkRootAgents({ agentsVersion: 1, agents: { sorter: { definition: "triage" } } }, { rolesDir }), prefixed);
|
||||
});
|
||||
|
||||
test("a project agent naming triage is refused", (t) => {
|
||||
const rolesDir = rolesCopy(rootDir(t));
|
||||
assert.throws(() => checkProjectAgents({ sorter: { definition: "triage" } }, { rolesDir, where: "projects.stack.agents" }), prefixed);
|
||||
});
|
||||
|
||||
test("a pack record proposing a triage hire is refused", (t) => {
|
||||
const root = rootDir(t);
|
||||
const rolesDir = rolesCopy(root);
|
||||
const doc = businessDoc(root);
|
||||
doc.packs = [{ id: "coding", version: "1.0.0", sha256: "a".repeat(64), origin: "shipped", scope: "org", project: null,
|
||||
at: "2026-11-12T20:00:00.000Z", by: "jason", added: [], proposedHires: [{ name: "sorter-1", pin: { template: "triage", sha256: "a".repeat(64) } }] }];
|
||||
assert.throws(() => validateBusinessDocument(doc, join(root, "acme.json"), { rolesDir }), prefixed);
|
||||
});
|
||||
|
||||
test("import refuses triage and the definitions template list omits it", (t) => {
|
||||
const f = verbsSetup(t);
|
||||
const revision = f.writer.read("acme").revision;
|
||||
assert.throws(() => f.verbs.import("acme", { revision, template: "triage" }, DEF_OWNER), coded);
|
||||
const listed = f.verbs.templates().map(({ template }) => template);
|
||||
assert.deepEqual(listed, templateHashes(f.rolesDir).map(({ template }) => template).filter((n) => n !== "triage"));
|
||||
});
|
||||
|
||||
test("a starter pack naming triage is refused when checked", async (t) => {
|
||||
const rolesDir = rolesCopy(rootDir(t));
|
||||
const { starterPack } = await import("../../plugins/starter-pack/coding/index.mjs");
|
||||
const doc = starterPack();
|
||||
doc.definitions = { ...doc.definitions, triage: { template: "triage", sha256: templateHash(rolesDir, "triage") } };
|
||||
assert.throws(() => checkPack(doc, { origin: "installed", rolesDir, name: doc.id }), coded);
|
||||
});
|
||||
|
||||
// The guard: the fence changes nothing for any other template or any shipped pack.
|
||||
test("every other shipped template imports as before and every shipped pack loads unchanged", async (t) => {
|
||||
const f = verbsSetup(t);
|
||||
const all = templateHashes(f.rolesDir).map(({ template }) => template);
|
||||
const others = all.filter((n) => n !== "triage");
|
||||
assert.equal(others.length, all.length - 1);
|
||||
// Each template's import outcome, measured on 5c7194e05 before the fence: chief-of-staff carries
|
||||
// role.hire, which a hired agent may not hold, so its import refused before and still does.
|
||||
const refusedBefore = ["chief-of-staff"];
|
||||
const outcome = {};
|
||||
for (const template of others) {
|
||||
try {
|
||||
f.verbs.import("acme", { revision: f.writer.read("acme").revision, template }, DEF_OWNER);
|
||||
outcome[template] = "imported";
|
||||
} catch (e) {
|
||||
assert.ok(!String(e.message).includes(CODE) && e.code !== CODE, template);
|
||||
outcome[template] = "refused";
|
||||
}
|
||||
}
|
||||
assert.deepEqual(Object.keys(outcome).filter((n) => outcome[n] === "refused"), refusedBefore.filter((n) => others.includes(n)));
|
||||
const defs = f.writer.read("acme").document.definitions;
|
||||
assert.deepEqual(Object.keys(defs).sort(), others.filter((n) => outcome[n] === "imported").sort());
|
||||
const { packs, refused } = await installedStarterPacks({ dataRoot: null });
|
||||
assert.deepEqual(refused, []);
|
||||
assert.deepEqual(packs.map((p) => p.id).sort(), ["business-management", "coding", "creative-writing", "marketing", "montage"]);
|
||||
});
|
||||
Loaded 100 of 231 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user