Compare commits

..
Author SHA1 Message Date
jason.woltje 9aae73ade2 docs(row321): wait for loopback health before precheck (#1817, F11) 2026-10-23 17:45:43 -05:00
jason.woltje d9400f0d36 docs(row321): remove whitespace from the embedded diff receipt (#1817) 2026-10-23 17:40:52 -05:00
jason.woltje b5d4d79031 docs(row321): set wrapper environment and explain first adoption (#1817) 2026-10-23 17:40:28 -05:00
jason.woltje 833ec1cc8d queue: revs 3718-3732: row 239 note, in-review and failed request (honker 3718-3720), request (sage 3721-3722), approve record (duckworth 3723), note and done (sage 3724-3725); rows 321 (#1817, F7 and F10, Gladstone, Boyd) and 322 (#1818, F8/F9, Goldie, Morgana) add, brief re-pin, piece and briefed (sage 3726-3732) 2026-10-23 17:38:11 -05:00
jason.woltje a147042103 docs: add F10 to the F7 brief (#1817): the run sheet's adopt step after a first install, and --no-rehearsal on the first upgrade after adopt (ops-0274, mos-1548); doc only 2026-10-23 17:31:54 -05:00
jason.woltje 062599252a docs: briefs for F7 (#1817, host run sheet wrapper step PATH and umask under sudo) and F8/F9 (#1818, case2-install.sh persona import from the copy and a refusal that keeps the error line); register the Codex builder seat Goldie for F8/F9 (mos-1542, mos-1544, mos-1546); doc only 2026-10-23 17:29:12 -05:00
jason.woltje aabaf97b60 duckworth: row 239 round 1 approve on r4 e0cb1db2c, replay exact, 16 paths equal r3, BUILD.md-only delta, pins match (duckworth-0295) (replayed onto e0cb1db2c by Sage) 2026-10-23 17:28:23 -05:00
jason.woltje e0cb1db2c8 row 239 (#1745) r4: BUILD.md: the replay onto 546366f4a and the sage-3773 slot run on 0cae2dad5: touched files whole 65/65, 9/9 mutants killed on their named tests, restores matched; no full gate (Sage at landing); doc only 2026-10-23 17:02:21 -05:00
jason.woltje 0cae2dad55 row 239 (#1745) r3: rebased onto refactor 93694c518; channel-proof keeps row 301's and row 239's comments and pins the merged webui bus.mjs at e3f52172; BUILD.md records the drift, the exact-once mutant check and sage-3730's run order; doc only beyond the rebase, untested 2026-10-23 17:00:42 -05:00
jason.woltje 4764bc9eb3 row 239 (#1745) r2: rebased onto refactor 94c33a43c after rows 253 and 275; BUILD.md records duckworth-0168, the N1 choice, the broker-only drift and the exact-once mutant check; doc only (sage-2906) 2026-10-23 17:00:42 -05:00
jason.woltje 712a084124 row 239 (#1745) b1: the fire's and the delete's revoke runs inside writer.write under the lock, after the revision check and the validations; an error after it carries revoked and the bus names it revision-conflict-revoked or outcome-unknown-revoked, with CLI, Console (OPEN, duckworth-0165 C1) and fire-notice texts; the mark sits in a catch around withLock (C2); tests T1-T6, channel-proof re-pins transport.mjs and webui bus.mjs; BUILD.md with mutants M1-M3g and the gate plan; untested, waits for a CLEAR (sage-2792) 2026-10-23 17:00:42 -05:00
jason.woltje cb3a456989 row 239 (#1745): design draft 1. beforeWrite runs inside writer.write under the lock after the revision and validation checks; a refusal after the revoke is marked and the bus names it revision-conflict-revoked or outcome-unknown-revoked, with CLI, Console and fire-notice texts; injected-writer fire test T1, T2-T6, mutants M1-M3e; Q1-Q3 for Duckworth; doc only (sage-2792) 2026-10-23 17:00:42 -05:00
jason.woltje 546366f4af docs: SESSIONS line for Sage's rows 220, 216 and 320 landings and queue-commit 604523b20 2026-10-23 16:58:38 -05:00
jason.woltje 604523b200 queue: revs 3678-3717: row 283 in-progress, in-review and failed request (honker 3678-3680), request (sage 3681-3682), approve record (webby 3683), note and done (sage 3684, 3686); rows 220 and 216 r5 moves and failed requests (researcher 3685, 3687-3691), requests (sage 3692-3695), approve records (filbert 3696-3697), notes and done (sage 3698-3701); row 320 (#1816) add and brief (sage 3702-3703), moves and failed requests (gladstone 3704-3706, 3710-3712), requests (sage 3707-3708, 3713-3714), CHANGES and APPROVE records (morgana 3709, 3715), note and done (sage 3716-3717)
Row 320 landed 094124b4e; rows 220 and 216 landed fbe57a05b; row 283 landed 93694c518.
2026-10-23 16:58:20 -05:00
jason.woltje 094124b4e8 docs: append the candidate's BUILD-LOG.md and SESSIONS.md lines at the current file ends (replay of faf55618e; those logs were excluded from the per-commit replay because their tails moved on refactor) 2026-10-23 16:37:24 -05:00
jason.woltje 5f4e578cf4 test(row320): reproduce an unsearchable inherited cwd and restore cleanup (#1816). Untested 2026-10-23 16:37:24 -05:00
jason.woltje fe2752954a docs(row 320, #1816): move Gladstone build receipt to queue path 2026-10-23 16:37:24 -05:00
jason.woltje 84530f6c5e docs(build): correct the citation receipt line count (#1816) 2026-10-23 16:37:24 -05:00
jason.woltje 86d8dbc035 docs(installer): cite the wrapper live-step gate (#1816, sage-3747) 2026-10-23 16:37:24 -05:00
jason.woltje ae3acc3bda docs(installer): add gated wrapper creation and private notify parent (#1816, Vikunja 614). Untested 2026-10-23 16:37:24 -05:00
jason.woltje 40501ab3e1 test(installer): add approved explicit notifier fixtures (#1816, mos-1537). Untested 2026-10-23 16:37:24 -05:00
jason.woltje ea4eaf388f fix(precheck): require the explicit notifier decision before host start (#1816, Vikunja 614). Untested 2026-10-23 16:37:24 -05:00
jason.woltje f9202a7701 fix(installer): allow scoped Claude paths and leave unreadable cwd (#1816, Vikunja 614). Untested 2026-10-23 16:37:24 -05:00
jason.woltje 689a0a3c91 fix(hostcheck): accept dpkg octal mode and verify bundles in scratch repos (#1816, Vikunja 614). Untested 2026-10-23 16:37:24 -05:00
jason.woltje 45e3ca7bdb docs: #1816 brief (Case 1/2 host fixes F1-F6 for the 433 P1 rerun, mos-1532/1534/1536/1537) and agents/gladstone/README.md registering the Codex builder seat; docs only 2026-10-23 16:13:48 -05:00
jason.woltje 582b86935a docs: SESSIONS line for Filbert's rows 220 and 216 round 2 verdicts (Filbert ddf73fe03, replayed onto the 220+216 landing tip) 2026-10-23 16:09:04 -05:00
jason.woltje fbe57a05b1 researcher: row 216 r5, index-build test makes Book One/Places before the write and query test lists the hybrid paths in sorted order (mos-1528, sage-3702); tests only, BUILD.md round 4 2026-10-23 15:40:52 -05:00
jason.woltje b64e681edf row 216 (C2-05a, #1717) r4: BUILD.md records the rebase onto 45dca69f6 (range-diff =), the drift check against 48e450ce8..45dca69f6 and the hash-pin grep with a positive control; doc only (sage-3576) 2026-10-23 15:40:52 -05:00
jason.woltje 2cc076fec5 row 216 (C2-05a, #1717): library index cache and lookup queries find, get, search, manuscript, universeInfo; get pages links, manuscript takes no chapter, search marks a too-long line, PRD 1.14 levels (rulings da9555ca2); unrun 2026-10-23 15:40:52 -05:00
jason.woltje 8e2885d265 researcher: row 220 r5, new library-seats test where lstat fails with ENOTDIR (a config directory under a regular file) kills M8-e; BUILD.md corrects the M8-e kill claim (sage-3715); test only 2026-10-23 15:40:52 -05:00
jason.woltje 63b9c64431 researcher: row 220 r5 R2 (mos-1528, option A), the F16 catalogue spy returns a listing and a new route test pins the refusal status of a refusing listing; test only, BUILD.md round 5 2026-10-23 15:40:52 -05:00
jason.woltje 6b8743c857 researcher: row 220 r5 R1, the library-seats unreadable-file test restores the file mode without failing when the fixture already removed it (mos-1528, sage-3712); test only 2026-10-23 15:40:52 -05:00
jason.woltje fc858800bf row 220 (C2-10a, #1721) r4: BUILD.md records the rebase onto 45dca69f6 (range-diff all =), the drift check against 48e450ce8..45dca69f6 and the discord helpers gate addition; doc only (sage-3576) 2026-10-23 15:40:52 -05:00
jason.woltje 303216ae25 row 220 (C2-10a, #1721) r2e: BUILD.md corrects the heading times of rounds 2b-2d from the commit clock; doc only 2026-10-23 15:40:52 -05:00
jason.woltje ccfb8308bc row 220 (C2-10a, #1721) r2d: BUILD.md closes the listRoots Refusal question with file:line (rootsFromSpecs, loadRegistrations, readRegistration, samePath, toTime throw no Refusal), so /api/conversations has no status change beyond the business refusal; doc only (sage-2730) 2026-10-23 15:40:52 -05:00
jason.woltje 04f3dc4f5f row 220 (C2-10a, #1721) r2c: BUILD.md corrects the refusalResponse statement from the serve.mjs and reader.mjs diffs against aca16404c (catalogue is now wrapped in refuse(), listRoots Refusal throws unchecked) and names the controller.mjs:176 follow-up; doc only (sage-2729) 2026-10-23 15:40:52 -05:00
jason.woltje 4310555874 row 220 (C2-10a, #1721) r2b: M8 run refusal tests, default-reader M7 test, configDirectory fixture scope; BUILD.md round 2b lists mutants M7-w, M7-c, M7-o, M8-p, M8-e and states no existing route's status or body changes with refusalResponse; unrun (sage-2719, filbert-220-early) 2026-10-23 15:40:52 -05:00
jason.woltje 45788f92c1 row 220 (C2-10a, #1721): M7 hides a creative seat's sessions from the conversation reader, M8 refuses a raw engine on a library seat in discord check and run; library-seats helper in packages/business (rulings da9555ca2); unrun 2026-10-23 15:40:52 -05:00
jason.woltje 93694c5185 deferred: row 283 Webby N1, SURVEY-RUN.md:96 shows the scopes line without supporting; bound to the next docs commit on that file (webby-0267, #1788); docs only 2026-10-23 15:38:05 -05:00
jason.woltje 8d2856ee3c row 283 (#1788): BUILD.md: G1 per sage-3713: mos-1528 OKs the mapping.test.mjs:52 draft deepEqual gaining supporting: [] (old :48 at 45dca69f6, new :52), recorded as an append that completes BUILD.md:42; doc only 2026-10-23 15:17:26 -05:00
jason.woltje 252b29bd8c row 283 (#1788): BUILD.md: T2 receipts on c18ad3e12 (sage-3695): base 16+6+6+7 library and 21 business green, 14/14 mutants killed on their named tests, library 98/98 and business 231/231; the mos-1272 first-run red and its test-helper fix; doc only 2026-10-23 15:17:26 -05:00
jason.woltje 54d9e07bb7 row 283 (#1788): mos-1272 first-run red: supporting.test's refuses() labelled each assertion with JSON.stringify(path), which throws on the 1n case added for E3; it now uses util.inspect. Test helper only 2026-10-23 15:17:25 -05:00
jason.woltje de6419f30f row 283 (#1788): sage-2925/sage-3649: optional editor.user (her Gitea login for library-human, read by row 288), checked with USER as the entry user is, kept in the output only when given; T3 accepted and refused cases; README; mutants M6e/M6f; BUILD.md records the departure from DESIGN.md section 1. Untested 2026-10-23 15:17:25 -05:00
jason.woltje 9ed0f3374a row 283 (#1788): webby-0236 E5: the git round-trip test drops GIT_DIR, GIT_WORK_TREE, GIT_COMMON_DIR and GIT_INDEX_FILE and reads no global or system config (repo convention); BUILD.md records E5. Untested 2026-10-23 15:17:25 -05:00
jason.woltje efcd3f0fc4 row 283 (#1788): E4 per sage-3606: editor values starting or ending with git's crud() set (bytes <= 0x20 and , : ; < > " \ ') refuse library-mapping-invalid; T3 cases per character and key, inner chars pinned, git round-trip test; mutants M6c/M6d; BUILD.md cites crud() and records the claim (rev 3642). Untested 2026-10-23 15:17:25 -05:00
jason.woltje b358427677 row 283 (#1788): E2 per sage-3601: editor values with surrounding whitespace refuse library-mapping-invalid (git trims idents at commit); T3 padded cases per key, mutant M6c; BUILD.md records the departure from DESIGN.md section 1 and the fixture grep (none). Untested 2026-10-23 15:17:25 -05:00
jason.woltje 675813594f row 283 (#1788): webby-0227 E3: supportingPath checks the type before stringifying, so a non-string path refuses library-write-story-path; string case covers 7, null, undefined, 1n and an array; BUILD.md records E1-E3, E2 to Sage. Untested 2026-10-23 15:17:25 -05:00
jason.woltje 3f1aa76b03 row 283 (#1788): BUILD.md: drift check, N3 grep, mos-1330 :73 old and new text, Q2 tradeoff, Q4 handoff to row 288 via #1793 c30738, mutants M1-M8 exact strings, gate plan; doc only 2026-10-23 15:17:25 -05:00
jason.woltje bcd1f34c2d row 283 (#1788): survey.test:73 re-pin under mos-1330 item 4. The scopes line gains only supporting 0; old 'scopes canon 5, playground 1, unmapped 3; indexed 6', new 'scopes canon 5, playground 1, supporting 0, unmapped 3; indexed 6' 2026-10-23 15:17:25 -05:00
jason.woltje c87ddc6041 row 283 (#1788): C2-01d supporting folders. supporting lists on every universe kind with the playground's prefix rules, library-supporting-other-universe and the cross-list rules; optional editor {name, email} refusing controls, < and >; classify checks supporting before playground; supportingPath with the eight checks over the listTree array, exported; survey counts supporting (sage-2923); README; tests T1-T8. Untested: runs wait for Sage's CLEAR 2026-10-23 15:17:25 -05:00
jason.woltje ce4040542f row 283 (#1788): design draft 2 folds webby-0169 R1 (editor refuses < and >, T3, M6b) and N1 (check 8 compares NFC and case, NFD case in T6, M4b); Q2-Q4 accepted, Q4 handoff to C2-02 in BUILD.md; doc only 2026-10-23 15:17:25 -05:00
jason.woltje f2f76fd2c3 row 283 (#1788): design draft 1. supporting lists with the playground's prefix rules and library-supporting-other-universe, cross-list rules, the optional editor, supporting first in classify, supportingPath over the listTree array; survey.mjs departure Q1 for Sage, Q2-Q5 for Webby; doc only (sage-2906) 2026-10-23 15:17:25 -05:00
jason.woltje 59226f878f queue: revs 3637-3677: row 226 in-review and failed request (gosalyn 3637-3638), request (sage 3639-3640), approve record (webby 3641), landing note and done (sage 3665-3666); row 283 in-progress (honker 3642), E1 note, in-review and failed request (honker 3671-3673), request (sage 3674-3675, comment 31337), approve record (webby 3677); owner assigns 217 225 298 296 297 288 227 (sage 3643-3649); 225 and 217 after sets, 288 note (sage 3650-3652); row 227 in-progress (gizmoduck 3653); rows 220 and 216 in-progress, in-review and failed requests (researcher 3654-3659), requests (sage 3661-3664, comments 31321 31322); row 298 in-progress (boyd 3660), in-review and failed request (boyd 3667-3668), request (sage 3669-3670, comment 31336); row 319 GitHub consumer added (sage 3676, mos-1525) 2026-10-23 15:16:03 -05:00
jason.woltje f67e5c15c5 docs: brief for the GitHub consumer of row 297's protected githubWithToken callback, honoring expiry and cancellation, post-10-27 (mos-1525, #1803); docs only 2026-10-23 15:10:34 -05:00
jason.woltje e2b8733904 deferred: row 226 Webby N1-N4 (install id regex, first-run refusal leftovers, clone sha on the run sheet, library-status lock wait), webby-0225, #1727 2026-10-23 14:42:22 -05:00
jason.woltje fd3d2a99fe docs: host run sheet section 2 verifies Node's SHASUMS256.txt with the detached SHASUMS256.txt.sig, not the clearsigned .asc (Vikunja 611, ops-0243, mos-1514, mos-1515); docs only 2026-10-23 14:41:39 -05:00
jason.woltje 661890e909 gosalyn: row 226 C2-13b build, case2-install.sh writes the business file and personas through a plan step before any write, case2-precheck.sh adds the D6a mode, persona and Discord checks and --library-status with lastError first and the wider escape, case2-install.test.mjs, run sheet lines; candidate before the gate (webby-0087 N2 N3, sage-2195, sage-2205, #1727) 2026-10-23 14:41:39 -05:00
jason.woltje 3046fd60a3 gosalyn: row 226 C2-13b design d2, release package and activate dropped, precheck split into pre-start checks and --library-status after the bus is up, Webby's N1-N6 taken in, design 10 text change listed (webby-0085, webby-0086, sage-2189, #1727) 2026-10-23 14:41:39 -05:00
jason.woltje b97f9df1ee gosalyn: row 226 C2-13b design d1, the business file as an input, install steps, persona staging before 2b, re-run rules, precheck library checks and tests, Q1-Q3 for review (#1727) 2026-10-23 14:41:39 -05:00
jason.woltje 8352da88c5 agents: register Beakley, Fethry, Boyd, Lena, Violet and Bubba as seats so the queue can name them as row owners (Q245, mos-1506) 2026-10-23 14:18:27 -05:00
128 changed files with 7304 additions and 4023 deletions

No files matched your search

+10 -2
View File
@@ -5412,6 +5412,14 @@ Row 299 (573, #1806, Gander, Filbert): before, the P10 band test timed a fault r
2026-10-23T17:32:37Z | Gyro sage-3544 fenton-0016 N1/N2 delta | Before: W7 Gate/final real-conversion list omit the W8 build-order cross-reference and W8 human-view filtering cites agent settings. After: both locations explicitly put W8 landing before human opening as mos-1470 build order, not acceptance; comment/tracked-deletion links are not current story links and never appear in the human Connections view regardless of agent settings. New commit atop approved 5af060fb5, no amend. Static diff and append-only checks pass. Docs only, no repo Node/tests/live action. Fenton checks only this delta.
## 2026-10-23 — Row 288 C2-02 build starts (Bubba, #1793)
2026-10-23 | Gladstone | Gitea #1816 / Vikunja 614 hostcheck item 5 and bundle verification | Before: dpkg's correct 750 form falsely fails item 5, and two run-sheet bundle verifies require a missing repository. Draft after: exact root/mosaic/path with octal 0750 equivalence; stat/output unchanged; both verifies use cleaned-up bare scratch repos. Three additive-only test blocks, two planned mutants. Untested under Sage-3738; Sage-3740 authorizes untested branch push for static review. Queue row pending; Sage owns gate and landing.
Before: agents can read the library; supporting-path and push-credential dependencies are separate unlanded heads. After intended: per-seat supporting writes/deletes with exact notices, human revert and one commit per Console save. Work is on bubba/row288, chained on original 283/285/286 commits; 284 tool base still pending. Plan and acceptance evidence: agents/bubba/work/queue-288/BUILD.md. Untested; no Node/test/build/gate run before Sage CLEAR. Landing waits for every dependency's own gate.
2026-10-23 | Gladstone | #1816 / Vikunja 614 scope amendment mos-1534, sage-3741 | F1 narrowed to exact 750/0750 and single spaces; F3 allows @ in absolute unit paths with unsafe-character refusals retained; F4 moves copy_tree to / after path resolution. AS_USER audit found git -C and stack-release's existing checkout cd cover the other steps. Added new unit and unreadable-cwd copy tests only. Untested under Sage's no-Node hold; no live action.
2026-10-23 | Gladstone | #1816 / Vikunja 614 F5 draft (mos-1536) | Before: the run sheet omits the explicit notify decision and precheck misses a bus-start refusal. After: section 9a creates a private null-binding decision as mosaic; precheck directly reuses readNotifyConfig and private_dir, and new tests cover accepted and refused decisions. Existing fixture setup additions await Mos approval through Sage; installer unchanged. Untested under no-Node hold.
2026-10-23 | Gladstone | #1816 / Vikunja 614 fixture ruling mos-1537 | Added only three setup lines each to host(t)/world(t) for the explicit null notifier decision. Existing assertions/fakes/lines intact. New install test checks decision bytes/mode preserved and missing decision remains absent. F5 missing-file fault removes the setup file. Untested under Sage's hold; separate follow-up atop 33950cf9b.
2026-10-23 | Gladstone | #1816 / Vikunja 614 F6 and notify parent (mos-1537) | Before: the run sheet's copy check lacks its required CLI wrapper; mkdir -p -m does not guarantee the notify parent mode. After: a separately Mos-gated wrapper --create step follows install and precedes check, as mosaic from cwd /; section 9a explicitly creates both notify directories at 0700. Docs only, no live action; Node/tests still held.
2026-10-23 | Gladstone | Row320 / #1816 first review CHANGES (morgana-0217) | Reviewer run: hostcheck19/19, unit47/47, install24/24, copy17/18; seven of eight mutants killed, M4 survived because both base/mutant failed only cleanup. Fixed this row's F4 test to enter cwd then chmod000, assert no read/search, pass an absolute outside bundle, and restore0700 in finally. Existing tests/setup and production scripts unchanged. Correction untested locally pending Morgana's focused rerun; no acceptance claim.
+8
View File
@@ -0,0 +1,8 @@
# Beakley
Builder seat, Codex gpt-6.1-sol, started by Mos under Q245 (mos-1506). Owns row 217 (C2-06, handed over from Launchpad).
No launcher in this directory. The seat runs as a T3 thread (thread 88b97f65) and works in its own worktree. It has no
credentials of its own; it pushes only its own `beakley/*` branches through the repository credential helper (mos-0981),
never `refactor`, `main` or another seat's branch. Claude seats orchestrate and review (Q245). Registered by Sage on
2026-10-23 so the queue can name the seat as row owner (store.mjs isSeatDir).
+8
View File
@@ -0,0 +1,8 @@
# Boyd
Builder seat, Codex gpt-6.1-sol, started by Mos under Q245 (mos-1506). Owns row 298 (the chief-of-staff grant scope, handed over from Megavolt).
No launcher in this directory. The seat runs as a T3 thread (thread 48a3ae38) and works in its own worktree. It has no
credentials of its own; it pushes only its own `boyd/*` branches through the repository credential helper (mos-0981),
never `refactor`, `main` or another seat's branch. Claude seats orchestrate and review (Q245). Registered by Sage on
2026-10-23 so the queue can name the seat as row owner (store.mjs isSeatDir).
+8
View File
@@ -0,0 +1,8 @@
# Bubba
Builder seat, Codex gpt-6.1-sol, started by Mos under Q245 (mos-1506). Owns row 288 (agent write notices and library revert, handed over from Honker).
No launcher in this directory. The seat runs as a T3 thread (thread 3d6672b5) and works in its own worktree. It has no
credentials of its own; it pushes only its own `bubba/*` branches through the repository credential helper (mos-0981),
never `refactor`, `main` or another seat's branch. Claude seats orchestrate and review (Q245). Registered by Sage on
2026-10-23 so the queue can name the seat as row owner (store.mjs isSeatDir).
-304
View File
@@ -1,304 +0,0 @@
# Row 288 (#1793): C2-02 agent writes, notices, revert and Console saves
Owner: Bubba, Codex gpt-6.1-sol, thread 3d6672b5-5544-4b95-9e09-e79574f1aa14.
Reviewer: Webby. Gate and landing: Sage. Append-only build record.
## 2026-10-23 start and implementation plan
Base 45dca69f6 on bubba/row288. Direct mandate mos-1499 (Q245), confirmed sage-3613.
The canonical `scripts/mosaic queue next bubba` returned `nothing`; Sage owns the owner transition.
The initial worktree invocation refused linked-worktree use; retried in canonical checkout.
Spec: docs/plans/2026-10-20_case2-rows.md, C2-02; agents/gosalyn/work/case2/DESIGN.md ruling after r11.
Handoffs: Honker queue-283 BUILD.md Q4 (missing/non-100644 delete refuses); Morgana
queue-225 BUILD.md A2 at 66f7becf2 (strict revert arguments/result), confirmed by Fethry fethry-0005.
`project` is the business.projects key, never a chat UUID.
Dependencies merged with their commits intact, no amend or force-push:
- 283 origin/honker/row283-build 88ec5e8e4 (new E4 head to follow).
- 285 origin/scrooge/row285-r2 53db6b7ca.
- 286 origin/ludwig/row286-r2 573fa0be0.
- 284: no named remote branch yet. Tool changes come last.
All merge commits are marked Untested. Nothing has run under Node. Sage's latest instruction
sage-3613 reserves **all Node and test runs** for CLEAR; this supersedes the initial targeted-test
permission. Build untested now as instructed, then run RED/GREEN checks/mutants on CLEAR.
Architecture: one host-only plumbing writer under the existing library lock; broker authorizes and
selects credentials, then inserts the fixed notice directly. Human save/revert use editor +
library-human independently of seat lifecycle. No worktree, deferred push, role expansion or UI.
### Tasks and acceptance
- [ ] Plumbing: new library/src/write.mjs, mirror state publication and package exports; new
library/tests/write.test.mjs. One-parent write/delete, byte-exact content, seat identity/trailer,
stale-base, nonregular/missing deletes, retry once on an unrelated remote change, push failure
without local ref movement, human editor and revert reachability/single-path checks.
- [ ] Broker + runtime: library.doc.write/delete, library.file.save, library.revert; strict keys,
creative + library.write + live unheld project grant; direct exact notice; human-only save/revert.
New bus/tests/library-write.test.mjs covers authorization, unchanged refs, A2 contract and socket.
- [ ] Transport: only human library.file.save joins the existing large-save exception. New tests
prove >64 KiB save accepted, agent writes retain 64 KiB bound, malformed/oversize saves refuse.
- [ ] Tools after 284: library_doc_write/delete in harness tools; exact eight/ten-name snapshots
in a new harness test; cli dispatch wiring.
- [ ] Verify on CLEAR: new tests, library/bus/harness suites and all scripts/test-*.sh on Sage's
assigned slot. Mutants remove supporting guard and force push; both must fail. Fixture-token
search over captured output. No gate, landing or queue move claimed before Sage's acceptance.
Pre-flight interfaces: broker consumes library writer {project,path,commit}; revert adds reverted;
writer consumes C2-03b push {pushed} or {raced,tip} and supportingPath(mapping,universe,path,tree).
State publication must add optional lastPush while preserving old state readability. Refusals must
restore fetched remote-tracking refs as well as preserve served. Runtime must bind credential file
references itself; no file, identity, message or credential is supplied by the agent.
Necessary file-scope additions: packages/bus/src/runtime.mjs (actual adapter injection),
packages/library/src/index.mjs (exports), and CLI's existing console adapter if saves require it.
Reported to Sage in bubba-0002. Existing tests will not be edited without Mos's OK via Sage.
Review focus: remote tip races, nonregular entries and folded paths, unsafe human credential before
git, revert after revoked/fired writer, and large-request exception never extending agent writes.
### Existing-test changes
None authored by Bubba yet. Dependency test changes remain their owners' original commits.
## 2026-10-23 first static build (not a gate result)
283 E4 merged intact at 76d651dba. Honker next reports e67c27b32 (test environment only), to merge
before push. Della reports row 284 has not been built/pushed; row224's 23816cf28 is not a 284 head.
No speculative 284 pin. Typed tools and served-blob lookup integration remain pending 284.
Implemented (unrun): bare plumbing writer, one-parent commit and fixed trailer, exact-content blobs,
base comparison, supporting path guard and delete regular-blob check, one remote-race retry,
ref restoration on refusal, immediate served publication/lastPush; human save and reachable one-path
business-trailer revert; broker grants/identity/notice path; runtime adapter wiring; large-save socket
exception. New tests: library/tests/write.test.mjs and bus/tests/library-write.test.mjs. No old test edits.
### Approved scope additions, sage-3628
Every hunk outside the brief's owned list:
- `packages/bus/src/runtime.mjs`: `humanWriteOptions` checks editor before choosing the human slot;
three library adapter entries bind dataRoot, command and the host-only seat store reference. These
are needed to make actual bus calls reach the new writer without accepting agent-supplied files.
- `packages/library/src/index.mjs`: export writeLibraryDoc/saveLibraryFile/revertLibraryCommit so
runtime's existing library module adapter can call them.
- `packages/library/src/sync.mjs`: shared write guard with opaque token compared by identity;
push's race fetch recognizes only that owner and does not clear its guard; ordinary sync and a
forged token still refuse library-sync-busy. Narrow publishLibraryWrite validates ids, reads the
locked state, rebuilds the index via readLibrary, moves served/tracking and writes lastPush. The
raw writeState remains private and is not exported through index.mjs.
Ludwig ludwig-0064 reviewed the intended interface and requested the opaque token (implemented),
narrow publication (implemented), whole library + bus library-credential checks and a token mutant
(planned). His 573fa0be0 remains current and unrun. 288's additions are separate commits, not folded
into 286. Tracking restores only if the whole write refuses, not between the first race and retry.
Known tradeoff, accepted by Sage sage-3628 for MVP: the brief holds the flock through network Git;
readers can hit the existing 5-second library-sync-busy while it runs. Structural supportingPath
preflight is pure and precedes Git; served/fetched listTree checks repeat it with the real tree before
any remote write. A tree-dependent check necessarily reads the tree first (Honker honker-0184 item2).
### Mutants for CLEAR
- Remove the `pathOf` calls for agent operations: the M12 broker/bare-ref tests must fail on a
story/unsupported path while checking remote, tracking and served refs.
- Prefix the push refspec in syncCommand with `+`: write.test moved-target race must fail, because
its command seam preserves production syncCommand's refspec (only remote URL/protocol are fixture).
- Replace `writers.get(mirror) === writeToken` with `true`: write.test forged-token case must fail.
No Node, test, build or mutant has run. `git diff --check` is clean. Counts are not claimed.
### Console dispatch integration
The existing cli delegates its transport wiring to console-bus.mjs, so the save dispatch needs that
file too: one null `librarySave` option and one `--send` assignment to library.file.save. cli.mjs
threads that option into startServer; row C2-11b owns the actual route/page that consumes it. New
webui/tests/library-write-options.test.mjs covers --send and the user transport boundary. 225 owns
libraryRevert dispatch; 288 adds only librarySave to avoid overlapping that ownership. Additional
scope reported to Sage and Fethry. No changes to an existing test.
## 2026-10-23 second static pass and dependency review
First push: c867cada9 on origin/bubba/row288, reported bubba-0005 to Sage/Webby/Mos and
bubba-0006 to Fethry/Ludwig. No PR created and no review/gate requested as complete.
Ludwig ludwig-0065 checked the exact sync diff against 286 without running anything. Token identity,
ordinary-sync exclusion, 286 R1 preservation, guard key and end-of-write tracking restoration fit.
F1: state publication could fail after served moved, leaving old state/new served. Root cause is
publication order without rollback, compared against sync's existing rollback. Added an unrun
filesystem rename-failure regression, then changed the narrow helper: on failure it validates the
state under the same lock, CAS-restoring served if state has not published the new commit. If rename
succeeded but directory fsync failed and the state validates against new served, it keeps that pair.
All failure cases answer outcome-unknown; tracking remains the commit already pushed remotely.
Verification is pending CLEAR, so this is a proposed fix, not a tested resolution.
Added the actual broker-to-bare tests for each M12 path refusal (both agent verbs), unchanged remote
and all mirror refs, exact write/delete notices, and human revert after fixture grant removal/hold.
The bare fixture moved to new library/tests/write-fixture.mjs so broker tests reuse real plumbing.
Added the raw socket proof-nested-save-name case to pin the parsed-verb large-request check.
Missing editor/slot tests now make the mirror metadata invalid first: reaching Git would change the
refusal, so the tests check the pre-Git gate rather than merely count remote commands.
Additional required doc hunk: packages/library/README.md appends the four verb contracts,
lastPush shape, exact notice, lock tradeoff and publication failure behavior. No existing test from
the dependency/base has changed. All new/modified tests in this pass were authored by this row.
`git diff --check` remains clean. No Node/tests/build/mutants run; 284 and CLEAR remain pending.
## 2026-10-23 early review follow-up (Webby E1-E6; Ludwig F2)
Sage sage-3652 approves console-bus.mjs wiring (null option + --send dispatch), confirms editor.user
as the sole human login source and reserves CLEAR for T3/T4 after T2. Ordinary sync()'s separate
post-rename fsync gap stays out of 288 per that ruling; no change to sync()'s existing rollback.
Honker 283 head 46bad7ea3 merged intact: mapping editor.user is optional, and if present uses the
existing plain Gitea-user pattern. The omission at mapping level is valid; human writes refuse it.
- Ludwig F2 / Webby E6: confirmed the previous runtime used the fetch bot's mapping.user wrongly.
Runtime now passes mapping.editor.user to humanCredential, never mapping.user. Missing user gives
library-human-missing before Git. New real-runtime cases pin both save and revert with a separate
fetch-bot login, positive pushes under her-gitea-login, and no command for an absent editor login.
The broker's credential.agent is s.role, not args: added an exact assertion and strict-key refusal
cases for caller-supplied agent and credential.
- E1: replaced the business-id RegExp interpolation with a literal startsWith(business.id + '/')
check and ID_PATTERN on only the instance suffix. New acme.co vs acme-co trailer test.
- E2: new broker→bare case holds the seat in the fetch command. beforePush must refuse
library-write-no-grant with all local refs and the remote unchanged and no notice. New mutant:
remove `options.beforePush?.();` in write.mjs; the E2 test must fail.
- E3: new broker cases for expired rotate_by, fire.stopped without fire.done, missing role.publish
project, grant/identity Gitea-user mismatch, and missing identity name/email, for both agent verbs.
- E4: the exceptional publication failure currently returns outcome-unknown before the broker has
a successful result to put in a notice, so a remote agent commit can exist without a Console
notice. There is no durable notice outbox/retry in this row. The trailer commit remains human
revertible by id after sync; this is an explicit known failure-mode gap for the manifest, not
a claim that every failed publication emits a notice. A new real-push test breaks state decoding
after push admission, pins outcome-unknown, old served and no notice. It also found a local error
propagation gap: errors before publishLibraryWrite's internal try now normalize to outcome-unknown
in the writer once push has succeeded, so the caller is never told an ordinary refused-write code.
- E5: 284 still has no build. Tools/8-or-10 snapshot and served-blob integration remain pending.
librarySave is intentionally only an adapter option until C2-11b supplies its route/page.
All tests above are newly authored by row288 and remain unrun; no changes to baseline/dependency
tests. RED/GREEN and mutants await CLEAR. Proposed fixes are not claimed verified. The new host-only
library write module imports the existing pure ID_PATTERN to match the broker's accepted instance ids.
## 2026-10-23 mos-1520 ruling: post-push notice is required
Correction to the E4 interpretation above: Mos rejected the known-gap treatment. The requirement
stays: a pushed agent commit has the exact notice even if local publication then fails. This is not
an outbox or retry. The writer now calls the broker's trusted synchronous onPushed callback as soon
as push returns pushed:true, before publication. The callback records the exact library-write notice
and action.allowed in the normal Console-store transaction. Publication failure still answers
outcome-unknown. The notice's Revert can refuse library-revert-not-agent until sync makes that commit
reachable from served; README now says that explicitly and removes the rejected gap description.
The row's own real-push corruption test now pins the exact notice body with the pushed id, old
served and outcome-unknown; after restoring readable state it pins Revert's refusal before sync and
success after sync. The successful-write adapter fixture calls onPushed too, matching runtime's
writer contract. No existing baseline/dependency test changed (mos-1520 explicitly authorizes this
row's test correction without mos-1272).
Residual Console-store failure: if notice insertion/routing/its event transaction fails, the broker
calls a separate host log sink with {event:library-notice-store-failed,code:outcome-unknown,business,
instance,op,commit}. It logs no args, path content, credential, raw SQL or exception output. Runtime's
new library.log adapter writes this metadata to stderr. The caller gets outcome-unknown even if
recording action.refused in that same broken store fails. A new real-push test uses temporary SQLite
abort triggers on notice insertion and refusal evidence, checks remote advanced/served unchanged,
no message, the exact external log and outcome-unknown. It does not claim a notice can be stored in
a failed Console store. If the host log sink itself also fails, no durable log can be promised; the
caller still receives outcome-unknown. The runtime log hunk is the required residual-failure wiring.
Mutant added: move `options.onPushed?.({ project: context.project, path: change.path, commit });`
from before `await publishLibraryWrite(...)` to immediately after that await inside the same try.
Successful operations keep their notice, but the outcome-unknown publication path drops it. The
C2-02 E4 real-push corruption test must fail on its exact notice assertion. Run on CLEAR and restore.
No Node/tests/build/mutants run. Static git diff --check clean. Della's first284 head0ed4fbab9 is
explicitly incomplete and not a finished dependency; waiting for her complete-head pin before tools.
Webby webby-0253 (static, cef503cb9) closes E4 per mos-1520; no tests ran. N1: a failed notice insert throws from onPushed before publication, so served stays at the prior commit until sync; the store-failure test pins this safe direction. Only E5 (284 tools/snapshot integration) remains open in this early review.
## 2026-10-23 complete284 merge and final tool integration (unrun)
Della della-0037 supplied complete untested head47db04eba85ac3ceb7e81385603f97bb6f8c1a38,
replacing the incomplete head. Merged intact as c0ca3894c. Its22423816cf28 and2164f3fbc25a
lineage is retained. Three conflicts were in overlapping production wiring only:
- broker.mjs: keep Della's LIBRARY_LOOKUPS object and #requestLibraryLookup byte-for-byte, and
keep288 writer/notice methods; LIBRARY_VERBS contains both sets and request dispatch calls lookup.
- runtime.mjs: keep lookup adapter plus288's metadata log and write adapters.
- library/index.mjs: keep index/query exports,286's push/humanCredential exports and288's writer exports.
No dependency test body was changed in the merge. These are overlapping consumer integrations,
not rewrites of dependency commits. Every prerequisite still needs its own gate (mos-1351).
Added library_doc_write/library_doc_delete after the five lookups, only for a creative definition
with a within-role library.write grant and library enabled. Closed schemas carry exactly
{universe,path,base,content} and {universe,path,base}; base is string-or-null with 40-lowercase-hex
pattern. No project, business, author, credential, commit or message. tools.action is library.write.
New harness/tests/library-write-tools.test.mjs pins per-role eight/ten names, both schema invariants,
no repo/commit/business/accept, exact required/verb/action, nullable base, and missing library/grant
or noncreative exclusion. This satisfies sage-3678 and mos-1523's replacement coverage condition.
Publication's narrow helper now calls indexFor for the new served commit instead of only readLibrary,
so the284 lookup index is rebuilt before publication. New broker integration uses library.get's
served blob as write/delete base, independently checks served:path, reads the new text/blob immediately,
preserves default-canon null, then sees null after delete. No change to284's query behavior.
### Authorized baseline-test migration, own commit (mos-1523 via sage-3677)
File: packages/harness/tests/library-tools.test.mjs. Numstat: +4/-4, exactly.
The noncreative LOOKUPS assertion at :33 is unchanged. Every existing lookup schema assertion stays.
The four old/new lines are:
```diff
- ? ['web_search', 'web_fetch'] : []), ...LOOKUPS];
+ ? ['web_search', 'web_fetch'] : []), ...LOOKUPS, 'library_doc_write', 'library_doc_delete'];
-test('M3: per-role snapshots contain six names, or eight with the C2-08 web grant', t => {
+test('M3: per-role snapshots contain eight names, or ten with the C2-08 web grant', t => {
- for (const [i, tool] of tools.filter(t => t.name.startsWith('library_')).entries()) {
+ for (const [i, tool] of tools.filter(t => LOOKUPS.includes(t.name)).entries()) {
- assert.deepEqual(tools.map(t => t.name), ['send_message', ...LOOKUPS]);
+ assert.deepEqual(tools.map(t => t.name), ['send_message', ...LOOKUPS, 'library_doc_write', 'library_doc_delete']);
```
Additional schema mutant (mos-1523): add `commit: str("caller commit")` to writeBase in tools.mjs,
thereby adding it to either/both write schemas. The new-file schema test must fail both its exact
property set and forbidden-property assertions. Run on CLEAR and restore. No further assertion
change in library-tools.test.mjs is authorized or made.
All code/tests/mutants remain unrun. No Node, build or syntax check before Sage's named CLEAR.
Static diff --check is clean. Scope additions stay listed above, now including indexFor import and
call in the previously approved narrow publication helper. E5 implementation is present; review and
acceptance are pending evidence, not claimed complete.
## 2026-10-23 testing and landing boundary (sage-3682)
Latest complete dependency2845d587a552 (test/docs only over47db04eba) merged intact as f8f79ea2f.
Own tool implementation cd2f50dae and separate mos-1523 migration29455c0c5 are pushed; Webby reads
E5 and Dewey checks the migration. Static manifest-r1 covered21 own paths at f8f79ea2f.
Sage reserves first focused runs/RED-GREEN/mutants for T7, provisionally about22:25Z, unless he
explicitly frees an earlier lane. No Node before his CLEAR. This is a schedule, not CLEAR. Full
library/bus/harness and shell gates still need their own authorized slot; no gate result is claimed.
Before the gate, incorporate landed refactor after283/224/284 land while preserving every
prerequisite. Under the standing add-commits/no-force-push rule, update this published branch by merge
rather than rewriting its pushed history. 288 lands last in the chain; no landing is authorized here.
## 2026-10-23 E5 static closure and N2 wording
Dewey dewey-0948: the mos-1523 migration at29455c0c5 is static CLEAN, exactly+4/-4, with the
noncreative assertion unchanged and new-file schema coverage meeting every condition. Webby
webby-0263: E5 closed on29455c0c5/cd2f50dae (f8f79ea2f;98ca25ab1 only BUILD.md), nothing blocking.
Both ran nothing; Webby did not read the scratch manifest, so no manifest verification is implied.
Webby N2: delete inherited the write base description "or null to create". Delete now overrides only
that description: "The existing file's blob from library_get; a missing file cannot be deleted".
The reviewed nullable-base schema/required keys/verbs remain unchanged. The row's new schema test
pins create wording only on write and existing-file wording without create on delete. No further
assertion change in the baseline library-tools.test.mjs. No Node/tests run; still await Sage CLEAR.
## 2026-10-23 dependency283 follow-up (honker-0195)
Merged origin/honker/row283-build b2a1f4092 intact, fast-forward lineage from46bad7ea3. It changes
supporting.test's helper and Honker's BUILD receipts only; no production source changed. Honker
reports library98/98, business231/231 and14/14 mutants killed on that dependency head. Those are
his dependency receipts, not verification of288's combined branch. No288 Node/tests run; Sage's
CLEAR is still required. The dependency's own gate/landing remains Sage's responsibility.
-170
View File
@@ -1,170 +0,0 @@
# Row 224 — C2-05b broker lookups and typed tools (#1725)
Owner: Della; reviewer: Dewey. Assignment sage-2795; scope extension sage-2804.
Base: `4f3fbc25a` (Researcher C2-05a). Branch: `della/row224`.
Brief: C2-05b in `docs/plans/2026-10-20_case2-rows.md` at `aca16404c`
and `51cc0445c`; design section 3, 5.3 M3 and 7.2; C2-05a BUILD rulings.
## Execution boundary and progress
Code/docs and local Git only while row 253 holds the gate. No Node (including
syntax checks), HTTPS Git, queue claim, test or push until Sage's CLEAR.
Tests are written first; their RED/GREEN runs are deferred, not claimed.
Queue next is deferred too: its executable uses Node. Sage assigned this row
explicitly. After 253 and 216 land, rebase under a new branch name.
- Pre-flight: query.mjs consumes `{repo,commit,mapping}`; broker cannot import
Git/filesystem library code because it is in the sandbox import closure.
Runtime injects the host lookup adapter; existing human file/status/sync stay.
- Pre-flight: resolved has no project list and a library is never a checkout.
Bundle needs an explicit library flag from launcher business configuration.
- M3 reading: exact creative base is five lookups plus send_message; retain
explicitly granted broker web_search/web_fetch for research/companion under
landed C2-08 and sage-2804. No generic spec, task, evidence or decision tools. Residual (mos-1308): those
reads lack broker action checks; their typed-tool absence is the only fence
for creative roles. M1/M2 deny bash; broker-side refusal is outside this row.
Mos confirmed this interpretation in mos-1308; design wording fix belongs to Gosalyn. Other definitions retain their current tools.
- Multi-library businesses use an optional project ID; omit it only with one
configured library. Universe is required for all five tools, including get.
- Missing library uses the brief's `library-not-configured`; argument errors
reuse `invalid-request` and C2-05a query codes. No new action or authority.
## Manifest (draft code, unrun)
- bus/src/broker.mjs: five lookup verbs, strict args, holder/business rechecks.
- bus/src/runtime.mjs: host lookup adapter, stale-before-read sync, served pin.
- harness/src/tools.mjs: five schemas; creative exact-set filtering.
- harness/src/bundle.mjs: library flag forwarded to typedTools.
- cli/src/launcher.mjs: one flag derived from trusted business projects.
- bus/tests/library-lookups.test.mjs: real query/broker/socket/runtime cases.
- harness/tests/library-tools.test.mjs: schemas, role snapshots, bundle parity.
- cli/tests/thread-launch.test.mjs: flag reaches a real launched bundle with no library checkout.
- agents/della/work/queue-224/BUILD.md: manifest, rulings and deferred verification ledger.
## Verification ledger
No test or syntax-check run yet. Acceptance requires full bus/cli/harness suites
and every scripts/test-*.sh on Sage's gate; focused files and affected CLI/
seat import-closure tests precede that only in an authorized CLEAR.
## Coordination
Huey272 reports no runtime/bundle/launcher overlap. Rocko219 changes launcher
THREAD_DEFINITIONS checks only, separate from our buildBundle flag argument.
The launcher argument is required: bundle cannot derive library presence from
checkout IDs (a library has no agent clone). No role, authority or config schema
changes; library project entries are already validated and protected by M9.
## Mount and pin impact (inspection only)
No new imports in broker.mjs or tools.mjs; no RUNNER_FILES or sandbox mount
addition. runtime.mjs is host-only and already imports library index.mjs.
Bundle forwards only a boolean, never a root/mapping/slot/credential. The
existing import-closure tests are bus/tests/project-runtime.test.mjs and
seat/tests/sandbox.test.mjs. Grep found no literal sha256 pin for runtime.mjs
or bundle.mjs; bundle tests derive current source digests through SOURCES.
Library sources remain in the existing whole-directory release copy.
## Runs to schedule only after CLEAR
Set TMPDIR=/mnt/storage/scratch/tmp. Focused new bus/harness files first,
then existing library.test.mjs, library-sync.test.mjs, project-runtime.test.mjs,
harness creative/tools/spec-tools/bundle files and affected CLI launch tests.
Follow with the required whole bus/cli/harness suites and Sage's full shell gate.
No timing claim yet: use the repository/Sage per-file limits and record every
command, outcome, elapsed time and timeout before acceptance. No focused skip
or pattern run substitutes for whole-file gate evidence.
## Read-through findings and residuals
- Library get requires universe although the older design table omitted it;
section 3 isolation rule and C2-05a's accepted API are binding.
- Query type enum matches mapping.TYPES (five values); manuscript is a distinct
lookup and not a find type. Unknown host-path/commit/business/accept fields
are refused; explicit project is restricted to this business's library list.
- Async reads recheck the live holder and current project revision. A stale
read attempts sync, then takes the new served snapshot; a returned fetch
failure/divergence keeps serving the old pin. Busy sync uses the current pin.
Unreadable state, no served commit or unsafe configuration refuse. Query
and sync never hold a SQLite transaction over await.
- Processing halt refuses new agent lookup work and rechecks before returning
async results. Existing human library file/status/sync behavior is unchanged.
- Timer sync and reads still use C2-03a's 60-second contract. No timer tuning or
resource-limit schema is introduced by this row. Q222 creative reply settings
are in C2-06; no reply guard or writing capability is implemented here.
- The generic tool socket's existing 60-second client timeout can precede the
server's 120-second Git timeout. This row does not change the generic timeout;
a timed-out lookup is read-only and retryable, never a write/outcome claim.
- All tests are authored but unrun. No RED, GREEN, syntax, runtime performance,
sandbox, broker/harness suite, shell gate, claim or push evidence exists yet.
## Candidate review checklist (read-through only)
- [x] Five verbs mapped to real C2-05a methods, all require universe.
- [x] Default sole library or explicit owned project; no caller repo/commit.
- [x] Human-only file/status/sync gates kept; lookup holder rechecked.
- [x] Async socket dispatch includes lookup verbs through LIBRARY_VERBS.
- [x] Stale/unknown fetch syncs first; results use current immutable served pin.
- [x] Six/eight creative names per mos-1308; other roles retain their tools.
- [x] Launcher -> bundle -> typedTools passes presence without a library clone.
- [x] No imports added to sandbox source closure; no mount change.
- [ ] Execute new tests, RED characterization, full files/suites after CLEAR.
- [ ] Rebase after rows 253/216 land, under a new branch name.
- [ ] Claim/push only in Sage-authorized gap; Dewey review and Sage gate.
Candidate preservation commits are explicitly unrun under sage-2795; they are
not completion, green-suite or landing claims. No dependencies installed.
Correction: the first committed-range diff --check found a blank line at EOF
in the new library-tools test, missed while it was untracked. Removed in a
follow-up local commit; the complete range must be checked again. No tests ran.
## Shared-log receipts for Sage (sage-2815)
The shared logs are unchanged from the base in this row. Sage appends these
receipts in the landing sweep; they are preserved here, not in the manifest.
For `BUILD-LOG.md`:
```text
2026-10-22T16:36:30Z | Della row224 C2-05b #1725 preparation | Before: C2-05a queries exist at 4f3fbc25a but no broker lookup verbs or typed tools. Scope: broker/tools plus Sage-authorized runtime/bundle integration, tests and docs. Existing human-only library reads retained; five agent queries require a live holder and trusted configured source. Code/docs only under row253 gate; no Node/test/push/claim. Runtime ownership coordinated with Rocko219/Huey272.
```
For `docs/SESSIONS.md`:
```text
2026-10-22T16:36:30Z | Della (sage-2795 / sage-2804, Q220) | Row 224 C2-05b #1725, della/row224 base 4f3fbc25a | Read both pinned briefs and C2-05a source; preparing broker/typed tools and authorized host runtime/bundle seams. No queue command, Node, HTTPS Git, claim, test or push during Gander gate. Dewey reviewer; Rocko/Huey runtime coordination sent. Tests and integration verification deferred to CLEAR.
```
Local-only draft pins 19c0a7adf/7cf39c390 are superseded by the
log-free candidate. Saved as local branch della/row224-draft-with-logs before
rebuilding the unpublished candidate commit; no remote history changed.
## Dewey dewey-0852 and Sage sage-2819 — focused corrections
B1: inline freshness uses max(lastFetch, lastError.at), not lastFetch alone.
An error within 60 seconds counts as a recent attempt, so later lookups serve
the old served pin without another fetch. Keep inline sync: the brief requires
it and businesses without timed libraries have no sync timer. The extended
failed-fetch test makes reads at +1, +59,999 and +60,000 ms (one attempt total),
then +60,001 ms (second attempt). All reads must return the old commit.
Required mutant M-B1: remove lastError.at from recentAttempt. The repeated
reads must fail the attempted-count assertion. This mutant has NOT been run.
Residual (Sage will defer): the first inline fetch in each outage window can
still exceed the tool timeout (60 seconds, or the runner broker client’s
30 seconds). Bounding that fetch is out of scope for 224. Subsequent reads
are paced by persisted lastError.at. No claim of first-read outage latency.
N1: whole bus, cli and harness suites are required, plus the shell gate.
If the new thread-launch integration test skips due to sandboxProblem(),
name the skip; a skip is not launcher integration proof.
N2: cli/tests/thread-launch.test.mjs now depends on library/tests/helpers.mjs
mappingEntry() and library/tests/fixtures/mapping.json. Changes to that fixture
must rerun the CLI launch file.
N3: harness/tests/library-tools.test.mjs compares the type enum to mapping.mjs
TYPES, so adding a mapped type cannot silently leave the typed tool behind.
These edits are local code/docs only. No Node, RED/GREEN run, mutant, claim,
HTTPS Git or push. New local pin goes to Dewey/Mos/Sage for focused review.
-196
View File
@@ -1,196 +0,0 @@
# Row284 C2-05c — supporting scope and served-tree blob (#1789)
Owner Della; reviewer Dewey; gate Sage. Build start sage-3658/3660 (10-23).
Branch della/row284. Original prerequisite base Honker28346bad7ea3;
merge fc05bcbc3 carries22423816cf28 and2164f3fbc25a intact. Only conflict was
CLI thread-launch's added footer tests: retained both full test bodies and
assertions. No prerequisite code copied. Every prerequisite needs its own
review/mutants/landing under mos1351; rebase after283 lands.
## Execution status
UNTESTED. No Node, node--check, test or mutant run before Sage CLEAR. First
own commit is the authorized old-test migration; the implementation follows.
Sage authorizes an immediate untested push. No queue write or shared-log edit.
224 stays first;284 is critical to Bubba288. T4 for224 is not a CLEAR yet.
## Binding readings
Brief C2-05c at94c33a43c:1737-1789, Q226, sage2918 and mos1330 item3.
get defaults canon; explicit playground/supporting opt-in; mismatch null.
Sort full outgoing/incoming lists supporting, playground, canon before paging,
keep cross-scope links and universe filter. Manuscript stays canon/playground.
No all/array scope, write tool, guard, mapping or creative-name-count change.
## mos-1330 old-test migration (separate commit)
All paths below are packages/library/tests/query.test.mjs. Baseline file at
fc05bcbc3 matches216's file. Source assertions retained; negative calls receive
explicit scope too, so universe isolation cannot pass on default-scope denial.
Call/assertion 348 -> 348:
```js
// OLD
const rin = await get(s, { universe: 'idea', path: 'Drafts/New World/Characters/Rin.md' });
// NEW
const rin = await get(s, { universe: 'idea', path: 'Drafts/New World/Characters/Rin.md', scope: 'playground' });
```
Call/assertion 350 -> 350:
```js
// OLD
assert.equal(await get(s, { universe: 'harbor', path: 'Drafts/New World/Characters/Rin.md' }), null);
// NEW
assert.equal(await get(s, { universe: 'harbor', path: 'Drafts/New World/Characters/Rin.md', scope: 'playground' }), null);
```
Call/assertion 366 -> 366:
```js
// OLD
assert.equal(await get(src(ref, mapping(WITH_BLEND)), { universe: 'blend', path }), null);
// NEW
assert.equal(await get(src(ref, mapping(WITH_BLEND)), { universe: 'blend', path, scope: 'playground' }), null);
```
Call/assertion 367 -> 367:
```js
// OLD
const own = await get(src(ref), { universe: 'harbor', path });
// NEW
const own = await get(src(ref), { universe: 'harbor', path, scope: 'playground' });
```
Assertion 349 retained, OLD == NEW:
```js
assert.equal(rin.scope, 'playground');
```
Assertion 368 retained, OLD == NEW:
```js
assert.equal(own.scope, 'playground');
```
The null assertions at350 and366 are the complete OLD/NEW expressions above:
expectation remains null. Added one separate no-scope playground-get -> null
behavior test. It is unrun and expected to expose old get behavior until the
new scope implementation lands. This migration is authorized by mos1330 under
mos1272; no check removed or weakened. Dewey checks this list in manifest review.
## 283 surface and blob choice
Inspected actual46bad7ea3: optional editor.user is present. reader's parsed
file records and index entries still discard tree oid. In owned query.mjs use
the existing bounded listTree(repo, servedCommit) to obtain exact path oid,
not HEAD and not a user-supplied revision expression. No reader/index edit.
Tradeoff: one additional bounded tree listing per get; latency unmeasured.
Recheck after rebasing to283's actual landing.
## Intended owned paths
query.mjs; broker.mjs lookup branch; tools.mjs lookup schemas/descriptions;
library query.test.mjs/query-fixture.mjs; bus library-lookups.test.mjs;
harness library-tools.test.mjs; this BUILD.md. Other files are prerequisites.
## Gate
Dewey manifest approval, whole library/bus/harness suites and every
scripts/test-*.sh on Sage gate. Before review grep all package tests for enum
pins and canon/playground pairs. Keep shared logs out; send receipts to Sage.
No test or mutant evidence claimed. Manifest/digest follows complete code.
## Implementation head (UNTESTED, sage-3658)
- query scope accepts supporting for find/search/get. get defaults canon,
mismatch null. Manuscript passes a separate two-value scope allowlist.
- get returns blob from listTree(source.repo,index.commit) after scope/universe
filtering. The same index.commit supplies the text; source HEAD is irrelevant.
- Full outgoing and incoming link lists are stably sorted by supporting,
playground,canon before combining/paging. All visible cross-scope links stay;
universe/hybrid visibility still applies. Scope metadata isn't added to links.
- Broker only adds optional scope to library.get's strict fields. No new verbs.
- Typed scope expands find/search/get only; manuscript retains its own two-value
enum. Names/M3 counts remain the row224 six/eight, no write tools added.
- New tests: book/universe/draft supporting find/search/get; defaults/mismatch;
absent supporting prefix; source HEAD advances but each scope's blob equals
served:path; 300 outgoing plus300 incoming links ordered across bounded pages,
retaining cross-scope links and dropping other-universe links; hybrid source
stays canon-only; no all/array scope; manuscript rejects supporting; broker
scope/blob forwarding; typed enums and unchanged names. All unrun.
## Additional old assertion pin (brief Gate)
harness/tests/library-tools.test.mjs:49 at23816cf28 (line49, unchanged in this head):
OLD find scope enum ['canon','playground']; NEW ['canon','playground','supporting'].
This is the exact scope-enum pin the brief directs updating. Existing six/eight
name snapshots and TYPES equality assertion are unchanged. The new manuscript
pin intentionally remains ['canon','playground']. No other two-scope test pin
was found by rg over packages/*/tests at this build's prerequisite merge.
## Proposed mutation evidence (reviewer confirms final set)
All unrun. Require assertion failures with whole-file runs and pristine restore:
M1 remove supporting from query SCOPES -> supporting lookup cases.
M2 drop get's requested-scope comparison -> default/mismatch null cases.
M3 use source HEAD for blob lookup -> served-tree/advanced-HEAD equality case.
M4 remove link rank sort -> multi-page outgoing/incoming expected order.
M5 restrict links to requested scope -> cross-scope link counts/order case.
M6 drop sees() from visible/link filtering -> second-universe/hybrid cases.
M7 allow supporting in manuscript validator -> manuscript refusal case.
M8 omit get scope from broker fields -> real broker supporting get case.
M9 widen typed manuscript enum -> typed-scope separation case.
## Inspection and pending gate
No production imports change in broker/tools, so no new sandbox closure file
or mount. query.mjs is host library code and adds existing reader.listTree;
no new package/export/copy-path file. rg found the one old find scope pin plus
the intentional new manuscript two-scope pin. Whole library/bus/harness and
shell gates remain required. CLI integration/merge context is prerequisite224/
219, not this row's source delta; any changed gate expectation goes to Sage.
Node checks, tests, mutants and elapsed-time evidence remain absent pending
CLEAR. The first test-migration commit and this implementation are distinct.
Sage sweep receipt: Della row284 builds on28346bad7ea3 plus intact224 merge;
mos1330 old-test migration separate, supporting scope/blob implementation and
fixtures authored, completely UNTESTED. No shared-log/queue write or live action.
## Current assertion anchors after implementation imports
The separate migration commit0ed4fbab9 retains its complete OLD/NEW text
above. Adding only the fs/path imports in the implementation shifts anchors:
query.test.mjs:130: `const blendCh2 = await get(src(ref, mapping(WITH_BLEND)), { universe: 'blend', path: 'Book One/Chapters/Chapter 02.md' });`
query.test.mjs:350: `const rin = await get(s, { universe: 'idea', path: 'Drafts/New World/Characters/Rin.md', scope: 'playground' });`
query.test.mjs:351: `assert.equal(rin.scope, 'playground');`
query.test.mjs:352: `assert.equal(await get(s, { universe: 'harbor', path: 'Drafts/New World/Characters/Rin.md', scope: 'playground' }), null);`
query.test.mjs:368: `assert.equal(await get(src(ref, mapping(WITH_BLEND)), { universe: 'blend', path, scope: 'playground' }), null);`
query.test.mjs:369: `const own = await get(src(ref), { universe: 'harbor', path, scope: 'playground' });`
query.test.mjs:370: `assert.equal(own.scope, 'playground');`
No result/null assertion changed; scope arguments carry the explicit opt-in.
## Dewey dewey-0941 static review — round2
Static scope fc05bcbc3..47db04eba CLEAN; not a final verdict or test evidence.
M1-M9 accepted as the final set. Optional M10 not added to this gate.
N2 taken: keep the existing canon-path supporting-scope mismatch assertion,
and ADD get(Book One/Support/Notes/Helper.md,scope:supporting) -> null under
the default mapping with no supporting prefix. The supporting-positive test
already returns this same path under withSupporting, so the added probe
pins the missing-prefix case directly. No assertion removed or weakened;
mos1330's separate migration commit and its retained assertions unchanged.
N1 proposed DEFERRED/follow-up for Sage: retain each tree oid in reader/index
entries so get can return blob without cat-file/whole ls-tree -r -l per page.
Current get's result is pinned correctly, but per-page cost grows with the
library. No performance measurement yet. This optimization needs reader/index
ownership and separate acceptance/performance evidence; do not silently expand
284's manifest or change its served-snapshot contract for it.
No Node, tests, mutants or syntax checks run in this round; hold still applies.
@@ -0,0 +1,30 @@
# Row 239 round 1 verdict: honker/row239-r4 e0cb1db2c (duckworth-0295)
Request: honker-0206 (in-review round 1, rev 3719). Candidate: e0cb1db2c on refactor 546366f4a.
Method: git reads of local objects only. No node, no tests, no fetch, no queue reads.
## Verdict: APPROVE
- **The replay is exact.** `git range-diff 93694c518..5b8492b0f 546366f4a..0cae2dad5` gives four `=`
lines. None of the 16 manifest paths changed between 93694c518 and 546366f4a, and
`git diff 5b8492b0f 0cae2dad5` over those 16 paths is empty. My r3 read (REBASE-r3-5b8492b0f.md,
duckworth-0292) applies unchanged, and so do the 0165 design approval and the 0168 code approval with
C1 and C2 met.
- **e0cb1db2c is doc only.** It appends 26 lines to agents/honker/work/queue-239/BUILD.md. No test reads
that file.
- **Pins at e0cb1db2c.** All four 64-hex pins in channel-proof.test.mjs match the files' sha256:
human.mjs, human-cli.mjs, transport.mjs and webui bus.mjs (e3f52172…). Upstream changed library
src/index.mjs and business src/index.mjs, and no test or script pins them. The only hit in my grep
is a basename collision (`cli.mjs` matched `human-cli.mjs`).
- **The run, as Honker reported it (sage-3773 CLEAR, on 0cae2dad5. I didn't rerun it):**
- The six touched test files ran whole: 65/65, 0 skipped, no first-run red.
- Mutants M1-M3g: 9/9 killed as assertion failures in their named tests.
- M3f killed T6, which matches my static trace in 0292.
- Every restore matched by sha256, and the tree was clean afterwards.
Running on the replay rather than r3's base was right, because bus runtime.mjs imports library
src/index.mjs and the cli imports business src/index.mjs, and both changed upstream.
- **What remains is Sage's.** The full gate runs on the replay at landing (sage-3730). Sage's call.
## Notes
- None new. 0168 N1 (endsWith access-revoked) stands as recorded.
+8
View File
@@ -0,0 +1,8 @@
# Fethry
Builder seat, Codex gpt-6.1-sol, started by Mos under Q245 (mos-1506). Owns row 225 (C2-10b, handed over from Morgana).
No launcher in this directory. The seat runs as a T3 thread (thread 14f80e3c) and works in its own worktree. It has no
credentials of its own; it pushes only its own `fethry/*` branches through the repository credential helper (mos-0981),
never `refactor`, `main` or another seat's branch. Claude seats orchestrate and review (Q245). Registered by Sage on
2026-10-23 so the queue can name the seat as row owner (store.mjs isSeatDir).
+9
View File
@@ -0,0 +1,9 @@
# Gladstone
Builder seat, Codex gpt-6.1-sol, started by Mos (mos-1531, mos-1532). Owns the Case 1/2 host fixes for the 433 P1 rerun,
F1 to F6 (#1816, Vikunja 614).
No launcher in this directory. The seat runs as a T3 thread (thread 433058fc) and works in its own worktree. It has no
credentials of its own; it pushes only its own `gladstone/*` branches through the repository credential helper (mos-0981),
never `refactor`, `main` or another seat's branch. Claude seats orchestrate and review (Q245). Registered by Sage on
2026-10-23 so the queue can name the seat as row owner (store.mjs isSeatDir).
+304
View File
@@ -0,0 +1,304 @@
# Hostcheck item 5 and bundle verification (Gitea #1816, Vikunja 614)
Queue row pending from Sage. Owner Gladstone, reviewer Morgana, gate/landing Sage.
Base: fetched origin/refactor 93694c5185d0a7f989d2fe78fb620e44599b744e;
branch gladstone/hostcheck-item5. Scope: mos-1531 / ops-0256, sage-3738 and sage-3740.
## Before and after
Ubuntu 24.04 dpkg 1.22.6ubuntu6.6 prints `root mosaic 750 /usr/bin/bwrap`.
Item 5 compared the literal `0750`, falsely refusing a correctly configured host;
--enforce would unload the profile, close bwrap and record DRIFT.
The candidate accepts exactly four fields, root, mosaic, octal 0750, and $BWRAP.
`0*750` represents all octal spellings numerically equal to 0750 without arithmetic
conversion/overflow. Horizontal whitespace separates fields; extra fields and
embedded newlines refuse. Owner, group and path remain exact. The stat comparison
and existing output strings remain unchanged. Only the item 5 comment also changes.
The two release-transport bundle checks previously ran outside any repository.
Each now creates an empty bare scratch repository, verifies with git -C, and removes
the scratch directory using an EXIT trap. A failure exits the shell before cloning
or fetching. No other run-sheet text changes.
## Tests and mutants
Only packages/cli/tests/case1-hostcheck.test.mjs changes among tests, by appending
three new test() blocks; the existing passing 0750 fake and failing fake are intact.
The pass test exercises 750, 0750 and 000750. The enforce test checks no unload,
chown, chmod, DRIFT or hostcheck log for 750. Refusals independently cover 755,
0755, 4750, 75, 7500, 075, non-octal strings, other owner/group/path, missing path,
extra fields, multiple lines, blank/empty output and a missing fixture file.
| Mutant | Change | Killer | Result |
|---|---|---|---|
| M1 | Restore the old literal root mosaic 0750 comparison (drop 750) | new check pass test | Unrun |
| M2 | Accept any mode while preserving owner/group/path | new refusal test | Unrun |
Mutant procedure: preserve script bytes, assert one replacement, run the named
killer alone, require failure for its intended assertion, restore in finally and
check the original bytes/hash. Run the original targeted file again after restore.
## Verification status
Untested. Sage-3738 prohibits all Node until CLEAR because the joint full gate
runs alone. Sage-3740 explicitly directs pushing this untested build for Morgana's
static review before CLEAR. This supersedes test-first execution for this draft;
no Node, tests, node --check, full suites or live-host operations have run.
Queue next refused linked-worktree execution; Sage owns queue creation/movement.
Push only gladstone/*, with MOSAIC_GITEA_CREDENTIAL_FILE unset; no amend/force.
Static draft receipt: `git diff --check` passed. Test-file numstat against the
base is `46 0 packages/cli/tests/case1-hostcheck.test.mjs` (added/deleted).
## Scope and implementation amendment (mos-1534, sage-3741)
F1 correction: Sage requires precisely `750` or `0750` and exactly single spaces,
so the candidate now uses `0?750` and literal spaces. It refuses 00750/000750,
a doubled space and a tab. This supersedes the initial numeric-equivalence design
above. Only this row's own appended tests change; no base test line changes.
F3: case2-unit.sh plain() adds @. abs_plain is its only caller and requires an
absolute normalized path, so @ cannot become an ExecStart prefix. In sed @ is
ordinary replacement text (the delimiter is |); &, backslash and | still refuse.
Environment=MOSAIC_CLAUDE_BIN carries @ literally; the parser compares the complete
value, with no shell evaluation. @anthropic-ai also cannot match the residual
@[A-Z_]+@ token check. Tests render/reinstall with a regular executable under
@anthropic-ai, checking Environment and the new copy's WorkingDirectory. Since a
nonroot test cannot create root ownership, a stat fake models root:0755 only for
that file and its ancestor chain. The real file type/executable checks, render,
installed-unit parser, and all other stat calls remain active. A separate block
refuses space, %, $, both quote characters, backslash, & and |.
F4: copy_tree changes to / before archive/npm/find, after all its path arguments
are absolute. copy_bundle retains its existing relative-bundle resolution before
calling copy_tree. Checkout copies have absolute REPO and COPIES too. Source-only
use from stack-release.sh changes no cwd because copy_tree is not called there.
Audit of every AS_USER command in stack-upgrade.sh: fetch and merge use git -C;
plan, gate, revert, confirm-rollback, stage (activate/rollback), confirm and rehearse
invoke stack-release.sh, which changes to its checkout at line 34. No other
AS_USER command needs a fix. The new test enters a directory mode 0111, verifies
that ls cannot read it, then runs both a relative-bundle copy and checkout copy,
asserting success, no find restore error, and an immutable completed copy.
Additional mutants (unrun under the same no-Node hold):
| Mutant | Change | Killer | Result |
|---|---|---|---|
| M3 | Drop @ from plain() | new factory scoped Claude-path test | Unrun |
| M4 | Remove copy_tree's cd / | new unreadable-cwd copy test | Unrun |
All four fixes remain untested. Follow-up is an additive commit on the pushed
branch, per sage-3741, with no amend or force. Morgana's static F1/F2 read of
f30c74b12 was CLEAN (morgana-0205); F3/F4 and execution remain open.
Morgana N1: the outer bundle-verification failure now prints
`STOP: bundle verify failed; do not continue` instead of exiting the interactive
root shell. The subshell still returns failure and cleans up. This follows the
sheet's human read-and-stop convention and avoids sending remaining pasted lines
to a parent shell after exiting sudo -i. Inner mktemp failure still exits only the
subshell. This supersedes the initial outer-shell failure behavior noted above.
## File numstat against 93694c518 (added / deleted)
| File | Added | Deleted |
|---|---:|---:|
| `BUILD-LOG.md` | 4 | 0 |
| `agents/gladstone/work/hostcheck-item5/BUILD.md` | 114 | 0 |
| `docs/SESSIONS.md` | 1 | 0 |
| `docs/guides/host-run-sheet.md` | 12 | 2 |
| `packages/cli/tests/case1-hostcheck.test.mjs` | 48 | 0 |
| `packages/cli/tests/case2-unit.test.mjs` | 29 | 0 |
| `packages/cli/tests/stack-copy.test.mjs` | 16 | 0 |
| `scripts/case1-hostcheck.sh` | 2 | 2 |
| `scripts/case2-unit.sh` | 1 | 1 |
| `scripts/stack-copy.sh` | 3 | 0 |
## F5 (mos-1536 / ops-0260): explicit notifier decision
Before: no run-sheet step creates the required notifier decision, and precheck
accepts a host whose bus will refuse missing notify.json. After: section 9a
requires the mosaic user to create its business notify directory at 0700 and an
explicit {"notifyVersion": 1, "binding": null} file at 0600 before section 10.
The shell runs with cwd / and umask 077; noclobber refuses an existing decision.
Named binding is explicitly a later per-host choice requiring Mos's go.
case2-install.sh is unchanged and makes no silent default.
case2-precheck.sh's existing facts helper dynamically imports readNotifyConfig
from cli.mjs and calls it directly. File type, uid, exact 0600 mode, JSON keys,
version and binding-name validation therefore stay identical to the bus. The
shell checks the business notify directory with existing private_dir (same uid,
not a symlink, exactly 0700) and prints the new notifier config line. No notifier
is started and no configuration is written. Tests append pass cases for null and
a valid named binding, and refusal cases for missing file, 0644, 0755 directory,
extra key, malformed JSON, invalid binding/version and a symlinked file.
M5 (unrun): remove the notifier shell check, including its refusal branch; the
new notifier refusal test must fail. Also include Morgana's F3 negative mutant
M3b (allow $ in plain), killed by the new unsafe-character test.
Existing positive precheck tests need an explicit notify fixture. Approval
requested via Sage in gladstone-0006/-0007 for minimal setup-only additions to
case2-unit.test.mjs host(t) and case2-install.test.mjs world(t); assertions remain
unchanged. Those additions are not yet applied. Correction to gladstone-0007:
case1-accept.test.mjs also names case2-precheck.sh, but uses a stand-in; it does
not execute the changed script and needs no fixture amendment.
Execution remains held by Sage: no Node/tests run. Morgana-0207 static F1-F4
verdict on a75532db1 is CLEAN; execution and F5 review are still open.
F5 acceptance from mos-1536 (for review):
1. Before section 10, as mosaic, explicitly create <dataRoot>/notify/<business>
at 0700 and notify.json at 0600 with default binding null; a later named
binding needs Mos's go. Do not make case2-install.sh write it.
2. Precheck must refuse missing file, non-0600 file, directory looser than 0700
and a document outside the CLI's exact shape. Reuse/match cli.mjs validation,
and name the new line in this run-sheet step's Precheck entry.
3. Append-only test blocks cover pass, missing, 0644, 0755 dir, extra key; record
a skip-check mutant, the touched test file and its numstat.
4. F3/F4 precede F5, each follow-up commit stays on gladstone/hostcheck-item5;
send pushes to Sage/Morgana with Mos cc. No Node until Sage CLEAR.
Static F5 draft receipt: git diff --check passed. Existing fixture approvals
remain pending; F5's new pass test creates its own explicit decisions. No claim
that the old positive precheck tests pass without the pending setup changes.
## F5 candidate file numstat against 93694c518 (added / deleted)
| File | Added | Deleted |
|---|---:|---:|
| `BUILD-LOG.md` | 6 | 0 |
| `agents/gladstone/work/hostcheck-item5/BUILD.md` | 179 | 0 |
| `docs/SESSIONS.md` | 1 | 0 |
| `docs/guides/host-run-sheet.md` | 34 | 2 |
| `packages/cli/tests/case1-hostcheck.test.mjs` | 48 | 0 |
| `packages/cli/tests/case2-unit.test.mjs` | 65 | 0 |
| `packages/cli/tests/stack-copy.test.mjs` | 16 | 0 |
| `scripts/case1-hostcheck.sh` | 2 | 2 |
| `scripts/case2-precheck.sh` | 19 | 0 |
| `scripts/case2-unit.sh` | 1 | 1 |
| `scripts/stack-copy.sh` | 3 | 0 |
## Fixture approval and separate follow-up (mos-1537)
Mos approved exactly setup-only additions to case2-unit.test.mjs host(t) and
case2-install.test.mjs world(t): each gets three added lines for a 0700
notify/acme directory and 0600 notify.json with {"notifyVersion":1,"binding":null}.
No existing line, fake or assertion changes or is deleted. F5's missing-file
negative case removes the file after setup, so the new default cannot mask it.
The newly appended install test checks preserved bytes and mode after success,
and separately removes the decision before install and checks it stays absent.
case1-accept.test.mjs is unchanged. This follow-up is committed separately on
33950cf9b as directed, with no amend. No Node/tests run; suite claims remain open.
Morgana-0211 found F5 source/run sheet CLEAN statically; the setup prerequisite B1
is addressed by this approved fixture patch, pending execution.
Additional planned mutants from Morgana-0211 (unrun): M5b drops private_dir,
killed by the directory fault; M5c prints NOTIFY ok unconditionally, killed by
the document faults. Existing test preservation is checked by git diff showing
only additions (numstat below).
Fixture follow-up numstat: case2-unit.test.mjs +3/-0,
case2-install.test.mjs +18/-0. Against the original base: case1-hostcheck.test.mjs
+48/-0, case2-unit.test.mjs +68/-0, stack-copy.test.mjs +16/-0,
case2-install.test.mjs +18/-0. git diff --check passed.
## F6 and notify parent correction (mos-1537 / ops-0261)
Before: install creates a copy but no human CLI wrapper; the sheet's
stack-copy.sh check --units external therefore fails even with correct units.
After: the sheet explicitly places a wrapper step after successful install and
before that check. On Mos's separate live-step go, mosaic changes cwd to /,
creates $HOME/.npm-global/bin if absent, then invokes its clone's stack-copy.sh
wrapper <sha> --create. Existing wrappers refuse and require review; install is
unchanged. This is documentation of a gated host action, not execution of it.
There are no tests pinning these sheet steps to adjust.
Section 9a now explicitly creates/chmods <dataRoot>/notify and then its business
leaf, each 0700. This addresses ops-0261's observation that mkdir -p -m only
controls the leaf. The existing umask 077 remains. All exits are inside the
unprivileged shell, so no failure exits the operator's interactive root shell.
Static receipt: git diff --check passed. No Node, tests or live action. F6 and
this parent-directory documentation correction are a separate commit after the
approved fixture-only 5fd2328b6 follow-up. Reviewer should retain the earlier
F1-F5 source verdicts and inspect this delta. Queue row still pending from Sage.
## F6 candidate file numstat against 93694c518 (added / deleted)
| File | Added | Deleted |
|---|---:|---:|
| `BUILD-LOG.md` | 10 | 0 |
| `agents/gladstone/work/hostcheck-item5/BUILD.md` | 241 | 0 |
| `docs/SESSIONS.md` | 1 | 0 |
| `docs/guides/host-run-sheet.md` | 51 | 2 |
| `packages/cli/tests/case1-hostcheck.test.mjs` | 48 | 0 |
| `packages/cli/tests/case2-install.test.mjs` | 18 | 0 |
| `packages/cli/tests/case2-unit.test.mjs` | 68 | 0 |
| `packages/cli/tests/stack-copy.test.mjs` | 16 | 0 |
| `scripts/case1-hostcheck.sh` | 2 | 2 |
| `scripts/case2-precheck.sh` | 19 | 0 |
| `scripts/case2-unit.sh` | 1 | 1 |
| `scripts/stack-copy.sh` | 3 | 0 |
## F6 gate citation (sage-3747)
Added scripts/stack-copy.sh:3 to the F6 wrapper step's explicit Mos-go requirement.
This is doc-only; commands and tests are unchanged. Sage ruled the delete-after-
setup missing-file negative meets mos-1537, so no fixture change is needed.
Morgana-0213 found the fixture/F6 deltas CLEAN statically. No Node/tests run;
Morgana's eventual run waits for Sage's row and CLEAR after the 220+216 landing.
Numstat for this follow-up: host-run-sheet.md +1/-1; BUILD.md +9/-0.
Static receipt: git diff --check passed.
Correction: 0f3d874d4 added 10 BUILD.md lines, not 9; the git numstat is authoritative.
## First review run and F4 test correction (morgana-0217)
Morgana ran af201b4a9 (6fa47e07d only relocates this file) under her authorized
slot with timeout -k 10 and TMPDIR under /mnt/storage/scratch/tmp. Receipts:
/mnt/storage/scratch/morgana-g320-out/base-summary.txt and mutants-summary.txt.
| Targeted file | Passed | Failed |
|---|---:|---:|
| case1-hostcheck.test.mjs | 19 | 0 |
| case2-unit.test.mjs | 47 | 0 |
| case2-install.test.mjs | 24 | 0 |
| stack-copy.test.mjs | 17 | 1 |
Seven of eight mutants were killed: M1 literal0750, M2 anymode, M3a drop@,
M3b allow$, M5 drop shell block, M5b drop private_dir, M5c always NOTIFY ok.
M4 drop cd / SURVIVED: base and mutant both failed only setup's cleanup hook.
This is a test defect, not a green acceptance result. The 0111 cwd retained
search permission and did not reproduce the inaccessible inherited cwd. It
also blocked setup's chmod -R cleanup because the directory remained unreadable.
B1 correction touches only this row's appended F4 test: the child shell enters
an initially searchable directory, chmods it 000, checks both ! -r and ! -x, then
execs stack-copy. The parent asserts all read/search bits remain cleared. The
bundle now lives outside cwd and is passed absolutely, matching the real flow;
existing row232 coverage still tests relative bundles from an accessible cwd.
Both bundle and checkout paths remain covered.
B2 correction: each child run/assertion sequence has a finally that restores the
cwd to0700 before setup's existing cleanup. No old setup/test lines change.
Production scripts are unchanged; the cd / fix remains correct by static review.
Correction is untested locally: no builder Node/test CLEAR was given. Morgana
will rerun stack-copy whole, M4 and residue cleanup on the pushed correction;
other files need no rerun unless changed. git diff --check passed.
## F4 corrected candidate numstat against 93694c518 (added / deleted)
| File | Added | Deleted |
|---|---:|---:|
| `BUILD-LOG.md` | 12 | 0 |
| `agents/gladstone/work/queue-320/BUILD.md` | 304 | 0 |
| `docs/SESSIONS.md` | 1 | 0 |
| `docs/guides/host-run-sheet.md` | 51 | 2 |
| `packages/cli/tests/case1-hostcheck.test.mjs` | 48 | 0 |
| `packages/cli/tests/case2-install.test.mjs` | 18 | 0 |
| `packages/cli/tests/case2-unit.test.mjs` | 68 | 0 |
| `packages/cli/tests/stack-copy.test.mjs` | 22 | 0 |
| `scripts/case1-hostcheck.sh` | 2 | 2 |
| `scripts/case2-precheck.sh` | 19 | 0 |
| `scripts/case2-unit.sh` | 1 | 1 |
| `scripts/stack-copy.sh` | 3 | 0 |
+171
View File
@@ -0,0 +1,171 @@
# Row 321: F7 wrapper environment and F10 first adoption (#1817)
Owner Gladstone; reviewer Boyd (separate Codex thread); queue/review/landing Sage.
Authorized by sage-3791. Branch gladstone/row321 starts at fetched origin/refactor
833ec1cc8d7c11842efb82e57c1a0b256c8d22d7. The row320 branch is unchanged.
Brief: docs/plans/2026-10-23_host-fixes-1816-brief.md, section
"Brief: F7, the wrapper step's PATH and umask under sudo", including F10;
verified blob 7333f94ba9cfd58f87c5a3580d428b84c65845b6 (requested pin 7333f94ba9cf).
Only the run sheet and this BUILD.md change. No scripts, tests, config, credentials,
queue state, deployment or live host operation changed. No tests or Node commands run.
## Before and after
F7: sudo secure_path omits the pinned Node directory, so wrapper creation reaches
instance.sh's bare node and exits127. An inherited umask can leave the bin dir0775.
The MOSAIC_WRAPPER heredoc now sets umask077 and the sheet's existing pinned Node
PATH before mkdir. One sentence names secure_path and why the step sets both.
The existing Mos go remains explicit. No wrapper command is executed here.
F10: first install omits adoption, so the first activate refuses no-pointer.
The release-transport section now places explicit adoption after both units are
running (section10) and before any activate/upgrade, run as mosaic on Mos's go by
Jason or Mos, citing stack-release.sh:14. It uses the configured dev instance and
external units, with the same pinned Node PATH under sudo.
Adjacent to the upgrade command, the sheet now says only the first upgrade after
adopt takes --no-rehearsal: adopt writes no backup; missing flag refuses no-backup;
later upgrades omit it, because a backup with that flag refuses rehearsal-required.
Source checks: stack-release.sh pointer_for_business refuses no-pointer and directs
adopt; stack-upgrade.sh rehearse handles rc3/no-backup and rc0/rehearsal-required.
This records existing behavior and authority; it adds no requirement or live go.
## Test-reference grep (negative and positive control)
The required negative grep covers both F7 and F10 because neither is read by any
matched test. The positive control locates the precheck path that the unit/install
tests actually execute, showing the pathspecs reach their test files.
Negative grep:
```sh
git grep -n 'host-run-sheet' -- 'packages/*/tests/*' 'scripts/test-*.sh'
# exit 1
# no matches
```
Positive control:
```sh
git grep -n 'case2-precheck.sh' -- 'packages/*/tests/*' 'scripts/test-*.sh'
# exit 0
packages/cli/tests/case1-accept.test.mjs:26:const PRECHECK = `${HOME}/.local/share/mosaic-stack/copies/${COPY}/scripts/case2-precheck.sh`;
packages/cli/tests/case2-install.test.mjs:2:// scripts/case2-precheck.sh's library checks and --library-status mode. Brief:
packages/cli/tests/case2-install.test.mjs:23:const PRECHECK = join(REPO, "scripts", "case2-precheck.sh");
packages/cli/tests/case2-install.test.mjs:271:// ---- case2-precheck.sh, the library profile (D6a) ----
packages/cli/tests/case2-install.test.mjs:334:// ---- case2-precheck.sh --library-status (D6b) ----
packages/cli/tests/case2-unit.test.mjs:2:// and scripts/case2-precheck.sh checks the host before they start. Brief: docs/plans/2026-10-20_case2-rows.md
packages/cli/tests/case2-unit.test.mjs:20:const PRECHECK = join(REPO, "scripts", "case2-precheck.sh");
packages/cli/tests/case2-unit.test.mjs:588:// ---- case2-precheck.sh ----
```
## Run-sheet diff against the pinned base (git diff --unified=0)
```diff
diff --git a/docs/guides/host-run-sheet.md b/docs/guides/host-run-sheet.md
index d2ba28d7c..96fd4f363 100644
--- a/docs/guides/host-run-sheet.md
+++ b/docs/guides/host-run-sheet.md
@@ -209,0 +210,9 @@ sudo -u mosaic -H git clone -q -b refactor /srv/mosaic/incoming/<sha>.bundle /sr
+After a first install, once both units are running (section 10), adopt the installed copy before
+any activate or upgrade. This step runs only on Mos's go, with Jason or Mos running it
+(`scripts/stack-release.sh:14`):
+
+```sh
+sudo -u mosaic -H env PATH=/opt/mosaic-stack/node-<v>/bin:/usr/sbin:/usr/bin:/sbin:/bin \
+ /srv/mosaic/src/mosaic-stack/scripts/stack-release.sh adopt <business> --instance dev --units external
+```
+
@@ -211,0 +221,4 @@ Each upgrade, before `stack-upgrade.sh upgrade`:
+Only the first upgrade after adopt takes `--no-rehearsal`: append it to the upgrade command below.
+Adopt writes no backup, so omitting the flag then refuses `no-backup`. Subsequent upgrades omit it;
+when a backup exists, supplying it refuses `rehearsal-required`.
+
@@ -246,0 +260 @@ step requiring Mos's go (`scripts/stack-copy.sh:3`); the install does not create
+The step runs under sudo's `secure_path`, so it sets its own PATH and umask.
@@ -250,0 +265,2 @@ cd / || exit 1
+umask 077
+PATH=/opt/mosaic-stack/node-<v>/bin:/usr/sbin:/usr/bin:/sbin:/bin; export PATH
```
## Verification
No matching test reads the changed lines, so the stop condition did not apply.
No test run or slot is required under sage-3791. Verification is static: the
required grep and positive control above, exact brief/base pins, scoped diff,
and git diff --check. Reviewer Boyd and Sage own review/landing; no approval
or landing is claimed here.
Receipt correction: the first commit embedded ordinary diff context lines that
contain a single space. git diff --check flagged those as trailing whitespace.
This follow-up uses the exact zero-context diff instead. The run sheet is
unchanged, no tests or Node commands run, and no amend or force-push is used.
## F11 addition (sage-3805, mos-1549, ops-0275)
The brief was extended after F7/F10 drafting and re-pinned at revision3733:
canonical local commit a9bae9af2, same F7 section anchor, full verified blob
0e684ef2103447dcc2013b6bf81b1c4ca5bbc0bd (requested pin0e684ef21034).
Read using git show from the canonical checkout; no fetch, rebase or queue write
is required. This new pin supersedes the earlier brief pin for this follow-up.
Defect: a precheck one second after unit start found no bus.sqlite yet.
Section10 now requires loopback healthz success after a unit start before any
case2-precheck.sh, including section9's --library-status. It uses the same
127.0.0.1:<port>/healthz curl form as scripts/case1-accept.sh:458. The subshell
tries at most30 times, each curl capped at2 seconds, with1 second between failed
attempts (at most89 seconds plus scheduling overhead). Exhaustion prints STOP
and exits only the subshell. The instruction says to stop before precheck/adopt;
it does not exit the interactive operator shell. The section9 library-gitea row
now explicitly requires this bounded wait before --library-status. <port> is the
installed Console unit's --port, not an assumed port or business name.
No host action, test, Node command or credential access occurred.
Required grep repeated for the widened scope:
```sh
git grep -n 'host-run-sheet' -- 'packages/*/tests/*' 'scripts/test-*.sh'
# exit1, no matches
git grep -n 'case2-precheck.sh' -- 'packages/*/tests/*' 'scripts/test-*.sh'
# exit0, positive control; output follows
packages/cli/tests/case1-accept.test.mjs:26:const PRECHECK = `${HOME}/.local/share/mosaic-stack/copies/${COPY}/scripts/case2-precheck.sh`;
packages/cli/tests/case2-install.test.mjs:2:// scripts/case2-precheck.sh's library checks and --library-status mode. Brief:
packages/cli/tests/case2-install.test.mjs:23:const PRECHECK = join(REPO, "scripts", "case2-precheck.sh");
packages/cli/tests/case2-install.test.mjs:271:// ---- case2-precheck.sh, the library profile (D6a) ----
packages/cli/tests/case2-install.test.mjs:334:// ---- case2-precheck.sh --library-status (D6b) ----
packages/cli/tests/case2-unit.test.mjs:2:// and scripts/case2-precheck.sh checks the host before they start. Brief: docs/plans/2026-10-20_case2-rows.md
packages/cli/tests/case2-unit.test.mjs:20:const PRECHECK = join(REPO, "scripts", "case2-precheck.sh");
packages/cli/tests/case2-unit.test.mjs:588:// ---- case2-precheck.sh ----
```
No test reads the changed run-sheet lines; the stop condition does not apply.
No test run is needed under the docs-only brief. Static verification checks both
locations, retry limit/timeout, the loopback URL, unchanged F7/F10 and scoped diff.
F11 delta against d9400f0d3 (git diff --unified=0):
```diff
diff --git a/docs/guides/host-run-sheet.md b/docs/guides/host-run-sheet.md
index 96fd4f363..e9fa87f24 100644
--- a/docs/guides/host-run-sheet.md
+++ b/docs/guides/host-run-sheet.md
@@ -322 +322 @@ file with `stat -c '%U %a %n' PATH`, never `cat`. `<business>` is the host's bus
-| `/srv/mosaic/.config/mosaic-dev/secrets/<business>/` | `library-gitea` | 0600 | mosaic | library | `case2-precheck.sh --business <business> --library-status`, after the bus is up: `library-last-error library-credential-missing` until it's placed, then `library <project> last fetched ...` |
+| `/srv/mosaic/.config/mosaic-dev/secrets/<business>/` | `library-gitea` | 0600 | mosaic | library | After a unit start, wait for loopback `/healthz` with the bounded retry in section 10 before `case2-precheck.sh --business <business> --library-status`: `library-last-error library-credential-missing` until it's placed, then `library <project> last fetched ...` |
@@ -357,0 +358,16 @@ None by hand. I2's `case2-unit.sh` enables both units, starts the bus, then the
+After a unit start, wait for the Console's loopback `/healthz` to succeed before running
+`case2-precheck.sh`, including `--library-status` in section 9. Replace `<port>` with the installed
+Console unit's `--port`. This retry is bounded to 30 attempts, each with a 2-second timeout, with
+1 second between failed attempts. If it prints STOP, stop here; do not run the precheck or adopt.
+
+```sh
+(
+ attempts=0
+ until curl -fsS --max-time 2 -o /dev/null 'http://127.0.0.1:<port>/healthz'; do
+ attempts=$((attempts + 1))
+ [ "$attempts" -lt 30 ] || { echo "STOP: loopback healthz did not become ready; do not continue" >&2; exit 1; }
+ sleep 1
+ done
+)
+```
+
```
+9
View File
@@ -0,0 +1,9 @@
# Goldie
Builder seat, Codex gpt-6.1-sol, started by Sage under mos-1542 and mos-1546. Owns F8 and F9, the library persona
import in `scripts/case2-install.sh` (#1818), for the 433 Run B rerun.
No launcher in this directory. The seat runs as a T3 thread and works in its own worktree. It has no credentials of its
own; it pushes only its own `goldie/*` branches through the repository credential helper (mos-0981), never `refactor`,
`main` or another seat's branch. Claude seats orchestrate and review the install path (mos-1542 rule 4). Registered by
Sage on 2026-10-23 so the queue can name the seat as row owner (store.mjs isSeatDir).
+331
View File
@@ -0,0 +1,331 @@
# Row 226 build notes, C2-13b install script and library precheck (#1727)
Brief: docs/plans/2026-10-20_case2-rows.md "C2-13b install script and library precheck" (:1073-1134 at
d37210288). Design: agents/gosalyn/work/case2/DESIGN.md r11 sections 4 and 10, on gosalyn/case2-design
75fb3e10e. Row 195's needs: agents/darkwing/work/queue-195/DESIGN.md "What row 195 needs from row 226".
This is design round d2. Nothing is built yet. d1 was f46e66883, and Webby's review of it is webby-0085
(CHANGES, B1 and N1-N6) and webby-0086 (the ordering problem). Sage ruled on both in sage-2189. The
changes from d1 are listed at the end.
## Base
Branch gosalyn/c2-13b from refactor d37210288. Rows 215, 221, 222 and 230 are done.
## Facts the design rests on
- No CLI writes a business file. `mosaic business validate <id>` checks one and exits 0 ok, 2 invalid
(packages/business/src/cli.mjs). A business file needs `human`, `arbiters`, `projects`, `tracker`
with a sync bot and a Vikunja credential ref, and `roles`, each role with its tracker bot when its
definition uses Vikunja (business.mjs:23, :84-100, :131-149).
- The library is a project, `projects.<id>.kind === "library"`, checked by `checkMapping`
(packages/library/src/mapping.mjs). There is no top-level `library` key.
- `library.sync` and `library.status` are bus verbs, human only (broker.mjs:92, :2452-2476). The only
client is `packages/bus/src/human-cli.mjs` over the bus socket.
- The bus makes each library mirror at start, `ensureMirror({ business, project, dataRoot })`
(packages/bus/src/runtime.mjs:143-145). Before the bus first starts there is no mirror.
- `sync()` fetches outside `withLibraryLock`. Only a per-process `running` set keeps two syncs apart
(packages/library/src/sync.mjs:97-98), so a second process calling `sync()` would race the bus's
timer.
- `libraryStatus(context)` reads the recorded state under the flock and writes nothing
(mirror.mjs:232-239). A missing or unsafe mirror fails `library-git` (`ownedRoot`, mirror.mjs:43-49).
A mirror that has never synced returns the empty state, `lastFetch: null`, `lastError: null`,
`problems: []` (mirror.mjs:27, :205-210). `lastError` is `{ code, at }` with `code` matching
`^[a-z-]{1,64}$` (mirror.mjs:225).
- The bus builds the library context as `{ business, project, dataRoot }` and the slot as
`<slotDir>/secrets/<business.id>/library-gitea` (runtime.mjs:146-151, :162-164).
- `case2-persona-import.mjs install --staging DIR --config-dir DIR --business ID` writes
`<configDir>/personas/<business>/<instance>.md` at 0600 in 0700 dirs, never overwriting, and prints
`instance bean: persona.name Bean, persona.sha256 <hex>` per persona.
- A Discord binding is `<dataRoot>/discord/<name>.json` (packages/discord/src/binding.mjs:70-83).
- `case2-unit.sh --copy ID` needs `<home>/.local/share/mosaic-stack/copies/<ID>`, which
`stack-copy.sh copy COMMIT --copies DIR` makes. The copy runs `npm ci` from package-lock.json
(stack-copy.sh:70), which installs the pinned pi.
## Design
### D1. The business file is an input
Unchanged from d1. `case2-install.sh` takes `--business-file FILE`, a JSON business document written for
the host from Jason's go. The script doesn't build one from flags, because bots, botIds and credential
refs are host values and the brief says every host value is an input. It checks the input, adds what
only it knows, writes it, and then runs `mosaic business validate`, so business.mjs stays the only
schema.
What the script checks before it writes anything, beyond `validate`:
- `id` equals `--business`.
- `library`: at least one library project, `bus.tester` not true, roles `bean` and `chet` with
definition `companion`, and no `persona.*` var in the input, since D3 adds them.
- `factory`: no library project, and `bus.tester` true. These are the precheck's rules at
case2-precheck.sh:127-135, so the install refuses what the precheck would refuse.
### D2. Install steps, in order
1. Refuse to run as root.
2. `scripts/bootstrap.sh`. It's idempotent and never rewrites an existing config.
3. `scripts/stack-copy.sh copy <--commit> --copies <home>/.local/share/mosaic-stack/copies`. The copy
`case2-unit.sh --copy` names has to exist before root renders the units (row 195 need 3).
4. `library` only: the persona import's `install` step from `--personas DIR` (D3).
5. Write `<configDir>/businesses/<id>.json` at 0600 with O_EXCL (D4).
6. `library` only: make `<configDir>/secrets/<business>/` at 0700, empty. The token is Jason's, design 10
step 4.
7. `mosaic business validate <id>`. If it refuses and step 5 created the file in this run, remove that
file, then refuse. A file that already matched on a re-run (D4) is never removed (N4).
8. Print the copy id and the next steps: root's 2c, Jason's 2d, 3 and 4, then the `--library-status`
check (D6b).
d1's step 3, `release.sh package` and `activate`, is gone (Q4a, webby-0085 B1, sage-2189). Package is a
`docker compose build`, and activate runs a pi Compose health check that mounts `PI_AUTH_FILE`
(compose.yaml:43). Neither fits 2a, which has no Docker and no pi credential, and the hub doesn't run
containers. The pinned harness comes from the copy's `npm ci` (Q3). The `CASE2_RELEASE` seam goes with
it.
It starts no unit, writes no unit file, doesn't write `/etc/mosaic-stack/dev.args` and doesn't run
`adopt`. These are my answers to row 195's needs 4 and 5 (gosalyn-0087), unchanged. Row 195's W8 now
passes `--business-file` and has no release step.
### D3. Personas come from the staging dir
Unchanged from d1. `library` requires `--personas DIR`, the staging dir from `case2-persona-import.mjs
stage`. The install runs `case2-persona-import.mjs install --staging DIR --config-dir <configDir>
--business <id>` and reads its two `instance` lines into `roles.bean.vars` and `roles.chet.vars`. Only
those two lines go into the business file. They hold a name and a digest, never text.
This moves the persona import's stage part of design 10 step 6 ahead of 2b: the read of her Hermes
profiles and Jason's check of the printed pairing. Webby agreed in webby-0085 (Q1).
### D4. Re-runs
Unchanged from d1, plus N4. Each step is safe to run again. bootstrap and the copy are idempotent. An
existing business file that matches the one the script would write passes, and the script remembers it
didn't create it. One that differs refuses `business-file-differs`, and the script doesn't touch it.
The persona import already refuses to overwrite. On a re-run the install compares each existing
persona file's sha256 with the staging manifest, and refuses on a mismatch.
### D5. Inputs and seams
```
case2-install.sh --business ID --business-file FILE --commit SHA [--profile factory|library]
[--personas DIR] [--home DIR]
```
`--home` defaults to `$HOME`, which is `/srv/mosaic` under `sudo -u mosaic -H`. `MOSAIC_CONFIG` is
honoured as bootstrap.sh honours it. One test seam, in case2-unit.sh's `CASE2_*` pattern:
`CASE2_STACK_COPY` is the copy script, and the test uses a stub that makes the copy dir.
Exit codes: 0 ok, 1 refused, 4 usage, as case2-unit.sh uses.
### D6. Precheck library checks, split in two (Q4b, sage-2189)
d1 ran `sync()` from the precheck. Webby's N1 and webby-0086 showed two faults. The precheck runs before
the units start, so there is no mirror yet (runtime.mjs:143-145). And a precheck `sync()` after the bus
is up would race the bus's timer, since `sync()` fetches outside the lock (sync.mjs:97-98). Sage split
the check in sage-2189, and the brief's "runs library.sync" becomes "reads the bus's recorded sync
state".
#### D6a. Before the units start, `--profile library`
These run where the precheck runs today, after 2c's render and before the start. They sync nothing and
read no mirror. Each is a `refuse` line in the script's style.
- The business file is owned by the uid, with no group or other bit (`business-file-mode`).
`businesses/.history/<id>/` is 0700 and its `changes.jsonl` is 0600, when present (`history-mode`).
- The persona dirs are 0700. Each creative role's persona file is regular, owned and 0600
(`persona-mode`), and its sha256 equals the role's `persona.sha256` (`persona-mismatch`). The output
prints names and digests, never text.
- No `<dataRoot>/discord/*.json` exists (`discord-binding`).
#### D6b. `case2-precheck.sh --business ID --library-status`, after the bus is up and after step 4
A new mode, run as `<user>` once the bus is up and Jason has placed the token. It changes nothing. A
node block builds the context the bus builds, `{ business, project, dataRoot }` for each library
project, with `dataRoot` from the config (N3, runtime.mjs:146-151, :162-164). For each one it:
- refuses `library-mirror-missing` when the mirror path doesn't exist. It checks this itself, so the
message says the bus hasn't made it, not `library-git`;
- calls `libraryStatus(context)` only, and refuses with the thrown code when that fails, for example
`library-git` for an unsafe mirror or `library-sync-busy` when the flock wait runs out;
- refuses `library-never-synced` when `lastFetch` is null;
- refuses `library-last-error <code>` when `lastError` is not null. The code is the fixed
`^[a-z-]{1,64}$` string, so it's safe to print. This also covers Webby's N2;
- prints each recorded R-problem as `problem R<n> <path>`, with the path through `JSON.stringify`, then
one `problems <count>` line (N5). Her file names are the only part that prints, never text.
R-problems don't refuse (Q2, agreed by Webby).
The bus syncs each library with a `user` every 60 s, so the first run after step 4 may need a minute,
or Jason's own `library.sync`. The run sheet says so.
### D7. host-run-sheet.md fix
`docs/guides/host-run-sheet.md:240` says "I2's install writes it" about `dev.args`. It becomes: root
writes it at the unit render, from the values the go names, and the install never writes it, because
`<user>` can't write `/etc` and root reads nothing `<user>` wrote. Sage asked in sage-1832 for this fix
to go in this build commit, with its path in the manifest. Section 9's `library-gitea` line (:275) says
"C2-13b's `library.sync` (not landed)". It becomes the `--library-status` check (D6b). The install
section also gets a line that the copy's `npm ci` needs the npm registry from the host (Q3, webby-0085).
### D8. Design 10 text
Sage ruled that design 10 gets the same change when 226 lands, with the line in this row's manifest.
In agents/gosalyn/work/case2/DESIGN.md:
- step 2b drops `release.sh package` and `activate`;
- a new step after step 4 runs `case2-precheck.sh --business <business> --library-status`;
- the precheck's library text says it reads the bus's recorded sync state, not that it runs
`library.sync`.
### D9. Tests, `packages/cli/tests/case2-install.test.mjs`
These follow case2-unit.test.mjs: scratch HOME, MOSAIC_CONFIG, stub bin dir and seams, a local bare repo
cloned `--bare --no-local` as sync.test.mjs does, and the fixture's key never in output.
- Install `library`:
- writes the business file at 0600 with bean's and chet's persona vars;
- writes the persona files at 0600 in 0700 dirs and the empty slot dir at 0700;
- logs the copy call and no release call;
- starts nothing;
- passes on a re-run;
- refuses `business-file-differs` and leaves the file unchanged.
- Install `factory`:
- writes no library mapping, no persona file and no slot dir, which is the brief's case;
- refuses a library project and `bus.tester` off.
- Install refuses: run as root, a business id mismatch, missing `--personas` under library, and a
`validate` refusal, after which no business file is left.
- N4: a re-run where the matching business file is already there and `validate` refuses leaves that
file in place, byte for byte.
- D6a refusals, one case each: a persona file at 0644, a digest mismatch, a business file at 0644, a
`changes.jsonl` at 0644, and a Discord binding. A clean library host passes D6a with no mirror.
- D6b, with the mirror made by `ensureMirror` and the state written by a real `sync()` against the local
bare repo, as the bus would:
- no mirror refuses `library-mirror-missing`;
- a fresh mirror refuses `library-never-synced`;
- a sync against a remote that doesn't resolve refuses `library-last-error` with its code;
- a synced bare repo with one R2 path prints its `problem` line and `problems 1`, and passes.
Every new refusal gets a mutant that removes it. The count goes in the slot request.
### D10. Files
Owned by the brief: `scripts/case2-install.sh` (new), `scripts/case2-precheck.sh` (library checks and
`--library-status` only) and `packages/cli/tests/case2-install.test.mjs` (new). Also
`docs/guides/host-run-sheet.md` (D7, sage-1832), agents/gosalyn/work/case2/DESIGN.md (D8, sage-2189)
and this BUILD.md. Before the slot request I'll grep for outside readers of case2-precheck.sh, since
case2-unit.test.mjs runs it.
## Questions
All three d1 questions are settled:
- Q1, persona stage before 2b: Webby agreed (webby-0085).
- Q2, R-problems don't refuse: Webby agreed.
- Q3, the pinned harness is the copy's `npm ci`: Webby agreed, and asked for the registry note in D7.
- Q4a and Q4b: Sage, sage-2189.
One choice for Webby to check: D6b's `problem` line carries the path through `JSON.stringify`. N5 asked
for a prefix and a count. I kept the path because Jason needs it to tell her which file to fix, and the
names are hers, not text.
## Changes from d1
- B1: release package and activate dropped, with the `CASE2_RELEASE` seam and its test (D2, D5).
- N1 and webby-0086: the sync is gone from the precheck. D6 splits into D6a before the start and D6b,
`--library-status`, after the bus is up and step 4 (sage-2189).
- N2: covered by D6b's `lastError` refusal.
- N3: D6b builds the context and slot as the bus does.
- N4: step 7 removes only a file this run created, with a test.
- N5: `problem` prefix and a `problems` count.
- N6: the run sheet lines are :240 and :275.
- New D8, the design 10 text change, and its path in D10.
## Build
Webby approved d2 in webby-0087 (REVIEW-design-d2.md, webby/reviews 2f488b4ea). Nothing above this
section changed after approval. This section records the build.
### D8 lands on case2-design
Sage ruled in sage-2195, after Webby's N1, that D8 goes on gosalyn/case2-design, because
agents/gosalyn/work/case2/DESIGN.md isn't on refactor. The change is commit 624212842 there, pushed:
step 2b drops `release.sh package` and `activate`, new step 4a runs `--library-status`, and the C2-13b
row text says the precheck reads the bus's recorded sync state. DESIGN.md is not in this row's manifest.
The brief's lines docs/plans/2026-10-20_case2-rows.md:1093-1096 still name release package, activate and
a library.sync fetch. Sage owns the brief and will amend those lines to match D8 in a doc-only commit
after the re-pin window (sage-2205). They are not in this row's manifest.
### Webby's d2 notes
- N2: the `problem` line keeps the path. After `JSON.stringify` the precheck also escapes DEL, the C1
controls U+0080-009F, U+200E and U+200F, U+2028 and U+2029, and the bidi controls U+202A-202E and
U+2066-2069 as `\uXXXX`. Webby named C1 and bidi. I added the rest because `JSON.stringify` leaves
them raw too, and each one can change how a terminal shows the line. The test path holds U+202E and
U+0085, and the test checks that neither prints raw.
- N3: `lastError` is checked before `lastFetch`. A first sync with no token records
`library-credential-missing` and leaves `lastFetch` null, so it refuses `library-last-error`, not
`library-never-synced`. The fresh-mirror test has `lastError` null and refuses `library-never-synced`.
### Choices made in the build
- The config dir. The persona import refuses a config dir with group or other bits, and bootstrap makes
one with the default mode. So the install makes the config dir at 0700 when it's absent, before
bootstrap, and refuses `config-dir-mode` when it exists with a group or other bit. It checks
`secrets/` and `secrets/<id>/` the same way under library (`secrets-mode`, `slot-mode`).
- `--home` must equal `$HOME` (`home-mismatch`). Every path comes from `$HOME` and `MOSAIC_CONFIG`, as
bootstrap's does, so a different `--home` would only name a second home the script doesn't use.
- A plan step runs before anything is written. It reads the input and the staging manifest, computes
the persona vars from the manifest, and compares the result with what's on disk. It refuses every
input rule, `business-file-differs` and `persona-differs` there, so a refused run writes nothing.
After the import the script checks that the import's two `instance` lines carry the manifest's
digests.
- A re-run with both persona files present and matching skips the import, which would refuse to
overwrite them. One matching file and one missing refuses `persona-differs`.
- A diverged library prints one line under `--library-status`, naming the tip `library.sync --accept`
would take. It doesn't refuse. The design doesn't list it as a refusal, and the bus still serves the
old tip.
- The precheck's library checks print `ok` lines for each check they pass, as the rest of the script
does. A business file that's missing prints no extra line, since the existing business-file check
already refuses it.
- The business id must match the persona import's rule, `^[a-z0-9][a-z0-9-]{0,63}$`. That's narrower
than the precheck's, which also takes `.` and `_`, because the persona dir uses the id.
### Outside readers
`git grep` over packages/*/tests/*, packages/*/src/* and scripts/test-*.sh finds case2-precheck.sh read
by case2-unit.test.mjs, which runs it, and case1-accept.test.mjs, which names a copy's path but runs a
fake. No test reads host-run-sheet.md. No test pins a hash of either script. case2-unit.test.mjs's
precheck host has a 0600 business file and no persona vars, so the new D6a checks pass there.
### Mutants
24, in /mnt/storage/scratch/gosalyn-r226/mutate.py. Each replaces one exact string once. Line numbers
are the candidate's. run.sh stops with BASE RED before any mutant unless the base run is rc=0 and
fail 0.
| Mutant | Line | Check removed |
|---|---|---|
| I1 | install :73 | run-as-root |
| I2 | install :74 | home-mismatch |
| I3 | install :81 | config-dir-mode |
| I4 | install :101 | business-id-mismatch |
| I5 | install :107 | profile-library-business |
| I6 | install :108 | bus-tester-off |
| I7 | install :111 | bus-tester-on |
| I8 | install :115 | persona-var-input |
| I9 | install :158 | business-file-differs |
| I10 | install :152 | persona-differs |
| I11 | install :218 | N4, removes the file even when this run didn't write it |
| I12 | install :218 | validate's removal of the file this run wrote |
| P1 | precheck :229 | business-file-mode |
| P2 | precheck :235 | history-mode for changes.jsonl |
| P3 | precheck :246 | persona-mode for a persona file |
| P4 | precheck :251 | persona-mismatch |
| P5 | precheck :241 | persona-mode for a persona dir |
| P6 | precheck :258 | discord-binding |
| P7 | precheck :104 | library-mirror-missing |
| P8 | precheck :107 | library-last-error |
| P9 | precheck :107 | N3, the order swapped |
| P10 | precheck :108 | library-never-synced |
| P11 | precheck :92 | N2, the escape after stringify |
| P12 | precheck :65 | --library-status refuses --profile |
`history-mode` for the history dir itself has no mutant and no test. The brief names only the
`changes.jsonl` case.
### Tests
Not run yet. They wait for a slot.
+177
View File
@@ -0,0 +1,177 @@
# Row 239 (#1745) build notes (append only)
## 2026-10-22 b1 (Honker)
Design d1 5da5f28f6 was approved by Duckworth with C1 and C2 and no blockers (duckworth-0165, note
agents/duckworth/work/row239/REVIEW-design-d1.md). The code is on honker/row239 from aca16404c. No test
has run yet: every run waits for Sage's CLEAR.
### Duckworth's conditions and answers
- C1 (option a): `outcome-unknown-revoked` is in the Console's `OPEN` list (webui bus.mjs), so
`sendOutcome` answers it as `outcome-unknown` with `sent: 'unknown'` and never "Nothing changed". T6
covers it and M3f is its mutant.
- C2: `write()` sets `revoked = true` after `beforeWrite()` returns, and a catch around the whole
`withLock(...)` call marks the error. So a throw from the lock's release in its finally is marked as
well. This is structural and has no test, as Duckworth said.
- Q1: `beforeWrite` runs after both validations. Q2: two codes. Q3: M2 removes the `:188` check (now
organization.mjs:195).
### Notes N1-N5
- N1: `beforeWrite` must not write the same business, because it would find its own lock and refuse
`organization-busy`. This is said in the comments on `write()` and `commit()`. Today's revokes (the
bus's credential revoke) write no business file.
- N2: the lock is held across the revoke. A fire or a delete now keeps other writers of that business
out for as long as the revoke takes. They refuse `organization-busy`, as they do for any held lock.
- N3: a revoke that fails partway (some tokens revoked, then `credential-revoke-failed`) behaves as
today. The error carries no `revoked` mark, because `beforeWrite` didn't return, and nothing is
written. This row doesn't change that.
- N4: a delete closed with `outcome-unknown-revoked` exits 3 in the CLI, as every closed refusal does.
Exit 1 (transport EXIT) applies only to a direct verb answer.
- N5: I grepped for "before the write" and similar comments. The ones left (lifecycle-revoke.test:2,
instance-settings:56, cli instances.mjs:53, serve.mjs:365) are still true and are unchanged. T21 in
bus lifecycle-revoke.test:173 is unchanged.
### Differences from the design
- The business tests are in lifecycle-settings.test.mjs, not instance-settings.test.mjs. The fire tests
and their fixture already live there. The fixture now returns `dir` and `rolesDir` too.
- T3 covers T3b (the delete) in the same test, looping over fire and delete. It also checks that a
revoke throwing `credential-revoke-failed` carries no mark and writes nothing.
- T4b is the plain-code check. The design's "T4b, outcome-unknown-revoked for an fs-style error" is in
T4, which checks EIO with and without the mark for both a fire and a delete.
- The bus test's fake org gets `deleteError`, thrown from its `instances.set` branch, so T4 can drive a
delete.
- transport.test gets one assertion, `busExit("outcome-unknown-revoked") === 1`, for M3g.
- A latent Console text: a direct (not closed-request) `revision-conflict-revoked` answer in the
Console would still get " Nothing changed." appended, because only `OPEN` codes skip it. That sentence
is true there: the file is unchanged. No direct human path gives this code today, since a delete
reaches the Console as a closed request's refusal.
- The Console's STATUS entry for `outcome-unknown-revoked` (503) can't be reached while the code is in
`OPEN`. It stays for symmetry with the CLI and is harmless.
### What changed
- packages/business/src/organization.mjs: `write()` takes `beforeWrite`, runs it under the lock after
the revision check and both validations, and marks any later error `revoked`. The body is reindented
inside the try.
- packages/business/src/instance-settings.mjs: `instanceSettings` takes an optional `writer`. `commit()`
passes `beforeWrite` to `writer.write` instead of calling it. The early check stays, and its comment
is rewritten.
- packages/bus/src/broker.mjs: `#organizationFail` maps a marked error to `revision-conflict-revoked` or
`outcome-unknown-revoked` before the existing mappings. `#fireJob`'s notice adds "Its credential
tokens may already be revoked." for a `-revoked` code.
- packages/bus/src/runtime.mjs: comment only.
- packages/cli/src/instances.mjs: two REASONS entries. packages/cli/src/transport.mjs: EXIT
`outcome-unknown-revoked` 1.
- packages/webui/src/serve.mjs: two AGENT_REASONS entries. packages/webui/src/bus.mjs: `OPEN` entry and
two STATUS entries.
- Tests:
- business lifecycle-settings.test: "row 239 T1", "row 239 T2", "row 239 T3".
- bus fire-revokes-grants.test: "row 239 T4", "row 239 T4b".
- cli instances.test: "row 239 T5 CLI". cli transport.test: one assertion in "busExit and
refuseInsideAgent".
- webui agents.test: "row 239 T6".
- bus channel-proof.test re-pins packages/cli/src/transport.mjs (662642a8...) and
packages/webui/src/bus.mjs (1eba9774...), with a comment on each. Neither changes a proof or the
transport. The design's file list missed this. The pin grep found it before the first run.
### Mutants for the gate (exact-once replacements)
- M1 (instance-settings.mjs, beforeWrite before the lock): replace
` const receipt = writer.write(business, next, { revision, actor, context, beforeWrite });` with
` if (beforeWrite) beforeWrite();\n const receipt = writer.write(business, next, { revision, actor, context });`.
The kill is lifecycle-settings "row 239 T1" (the revoke spy has a call).
- M2 (organization.mjs, the fire refusal dropped): delete the line
` if (revision !== before) fail("revision-conflict", "organization revision changed; read again");`.
The kill is "row 239 T1" (the write lands over the hand edit).
- M3a (organization.mjs, the mark dropped): ` if (revoked && e instanceof Error) e.revoked = true;`
becomes ` void revoked;`. The kills are "row 239 T2" and "row 239 T3" (business). T4 drives the mark
through a fake org, so it doesn't see M3a.
- M3b (broker.mjs): delete the line
` if (e.revoked) fail(e.code === "revision-conflict" ? "revision-conflict-revoked" : "outcome-unknown-revoked");`.
The kill is fire-revokes-grants "row 239 T4".
- M3c (cli instances.mjs): delete the five lines from ` "revision-conflict-revoked": "the business file`
through ` "business file again with \`mosaic business instances\` before trying again",`. The kill is
instances.test "row 239 T5 CLI".
- M3d (webui serve.mjs): delete the two lines starting ` 'revision-conflict-revoked': 'the business file`
and ` 'outcome-unknown-revoked': 'the agent\'s tokens`. The kill is agents.test "row 239 T6".
- M3e (broker.mjs): ` const tokens = code.endsWith('-revoked') ? ' Its credential tokens may already be revoked.' : '';`
becomes ` const tokens = '';`. The kill is "row 239 T4".
- M3f (webui bus.mjs, C1): the `OPEN` line loses `, 'outcome-unknown-revoked'`. The kill is "row 239 T6"
(the launch POST answers 503 outcome-unknown, sent unknown).
- M3g (cli transport.mjs): delete the line ` "outcome-unknown-revoked": 1,`. The kill is transport.test
"busExit and refuseInsideAgent".
A kill counts only as a failed assertion in the named test, not a load error or a different test.
### Gate plan (mos-1275 timeouts)
- My row 256 gate (2026-10-22 10:34Z, same machine) took 590s for the cli package, 57s for webui and
38s for test-foundation, the longest shell script.
- Packages: `timeout -k 10 1800` per package (3x the cli run).
- Each scripts/test-*.sh: `timeout -k 10 300` (more than 3x the 38s longest).
- Single files and mutants: `timeout -k 10 600` per file run (cli instances.test whole is the longest
single file).
- Order on Sage's CLEAR: the touched test files whole (business lifecycle-settings, bus
fire-revokes-grants and channel-proof, cli instances and transport, webui agents), then M1-M3g, then
the full gate.
- Before the in-review move: grep packages/*/tests for the changed comment and error text and for
64-hex pins on the changed files, and drift-check BASE..refactor against them.
## 2026-10-22 r2 rebase (Honker)
- Duckworth approved b1 b0c28366f statically, with no blockers (duckworth-0168). On N1 (`endsWith('-revoked')`
would also match `access-revoked`, which can't reach a fire job today), the check stays as it is, so the
approved candidate doesn't change before the gate (honker-0163).
- Rows 253 (48e450ce8) and 275 landed. b1 is rebased onto refactor 94c33a43c as honker/row239-r2. The
push branch honker/row239 isn't rewritten.
- Drift between aca16404c and 94c33a43c on the 15 paths: only packages/bus/src/broker.mjs, where row 275
changes the viewer verbs. Neither of row 239's two hunks (`#fireJob` and `#organizationFail`) moves in
meaning. The rebase applied with no conflict. The two pinned files (cli transport.mjs, webui bus.mjs)
and channel-proof.test have no upstream change, so the b1 pins stand.
- Each M1-M3g replacement string still matches exactly once.
- The touched test files run whole again on the new base, in the slot (the rebase rule).
## 2026-10-23 r3 rebase (Honker, sage-3730)
- r2 (70c6e3772) is rebased onto refactor 93694c518 as honker/row239-r3. honker/row239-r2 isn't rewritten.
- Between 94c33a43c and 93694c518, five of the 16 paths changed upstream: bus broker.mjs and runtime.mjs,
channel-proof.test, and webui bus.mjs and serve.mjs. Every file merged on its own except channel-proof.test,
where row 301 (59f0e44f4, mos-1449) re-pinned webui bus.mjs for the user transport fold. The merged
pin keeps row 301's comment and row 239's, and takes sha256 e3f52172…1c2a89 of the merged bus.mjs.
The transport.mjs pin (662642a8…6e55b) still matches the file.
- Row 239's hunks in broker.mjs (`#fireJob`, `#organizationFail`), runtime.mjs (the revoke comment),
bus.mjs (OPEN, STATUS) and serve.mjs are unchanged apart from their position. The range-diff shows
only the channel-proof pin and the hunk context moved.
- Each M1-M3g replacement string still matches exactly once. M3f's target is the whole `OPEN` line,
since `, 'outcome-unknown-revoked'` also appears in the STATUS line.
- No 64-hex pin in packages/*/tests or scripts names a changed file except channel-proof.test.
- On the CLEAR (sage-3730): the touched files whole, then M1-M3g, then the counts here. Sage runs the
full gate on the replay at landing.
## 2026-10-23 r4 replay and the slot run (Honker, sage-3773 CLEAR)
- On the CLEAR, refactor was 546366f4a (row 320 landed at 094124b4e). None of the 16 manifest paths changed
between 93694c518 and 546366f4a. Upstream did change library src/index.mjs, which bus runtime.mjs imports,
and business src/index.mjs, which the cli imports, so the run was on a replay onto 546366f4a rather than
on r3's base. That replay is honker/row239-r4 0cae2dad5. The range-diff of r3 against r4 is four `=`
lines with equal patch-ids, so duckworth-0292's read of r3 applies to r4. r3 isn't rewritten.
- The run was on 0cae2dad5 with a clean tree, TMPDIR under /mnt/storage/scratch/tmp, 22:01:27Z-22:01:52Z.
- The touched files, run whole: business lifecycle-settings 12/12, bus fire-revokes-grants 24/24, bus
channel-proof 2/2, cli instances 15/15, cli transport 3/3, webui agents 9/9. That's 65/65 with 0 skipped,
and no first-run red.
- Mutants: 9 of 9 killed. Each was applied exactly once, and each made its named test fail as an assertion:
- M1 lifecycle: 3 fail (T1, T2, T3).
- M2: T1.
- M3a: T2 and T3.
- M3b fire-revokes-grants: T4.
- M3c instances: T5 CLI.
- M3d agents: T6.
- M3e: T4.
- M3f agents: T6.
- M3g transport: "busExit and refuseInsideAgent".
T4b passed under M3b and M3e. Every restore matched the HEAD blob by sha256, and the tree was clean
after the run.
- No full gate (sage-3730): Sage runs it on the replay at landing.
+159
View File
@@ -0,0 +1,159 @@
# Row 239 design: the revoke under the writer's lock, and a fire test
Brief: docs/plans/2026-10-20_agent-lifecycle.md, "Brief: row 194 follow-up, the revoke under the writer's
lock and a fire test" (blob 3b3b3b2b9), from Duckworth's row 194 b3 N1 and mos-1158. Base aca16404c (row
194 landed as fd6dd327c, row 281 as e479521d3). Builder Honker, reviewer Duckworth, gate owner Sage.
Draft 1, 2026-10-22.
## Today
- `instance-settings.mjs` `commit()` runs the checks, then compares the caller's revision with a fresh
`writer.read` (row 194 b3, sage-1634), then calls `beforeWrite` (the fire's or the delete's credential
revoke), then `writer.write`.
- `writer.write` (`organization.mjs`) takes the lock, runs `recover`, checks the revision again (`:188`),
validates, prepares, checks the bytes once more before publication (`:221`), renames and commits.
- So two windows are left.
- A write that lands between `commit()`'s read and the writer's lock still gets a revoke and then a
`revision-conflict`.
- Any refusal after the revoke ran (the `:221` check, or an I/O failure the bus reports as
`outcome-unknown`) uses the same text as one before it, so nothing says the tokens may be gone.
- Row 281 left this path alone. Its fire job (`broker.mjs` `#fireJob`) runs step G (grants), then step B,
which is this same `write('instance.fire')`, and reports a step B failure as `fire.failed` along with a
human notice that names the code. Its delete job only does step G. The delete itself still commits
through `lifecycleDelete` → `instances.set` op delete → `commit()`.
## What changes
### 1. `beforeWrite` runs inside `writer.write`, under the lock (organization.mjs)
`write(id, document, { revision, actor, detail, context, beforeWrite = null })`. The order under the lock:
1. `recover`, read, then the `:188` revision check. A refusal here revokes nothing.
2. Projects-protected and both validations. A refusal here revokes nothing either. I put `beforeWrite`
after these rather than straight after `:188`, so a document the writer would refuse anyway never
costs a revoke. Q1 asks Duckworth to confirm this.
3. `beforeWrite()`. If it throws (today `credential-revoke-failed`), the error propagates as it is and
nothing has been written, as now.
4. Prepare, the `:221` check, rename and commit, wrapped so that any error thrown after step 3 gets
`revoked = true` set on it before it is rethrown. That covers `revision-conflict` from `:221`, an
`organization-refused` from `log()`, a barrier throw, and an fs error.
`record()` and the other writers (`launch-settings`, `plugin-settings`, `credentialVerbs`) pass no
`beforeWrite` and behave as before.
### 2. commit() passes beforeWrite through (instance-settings.mjs)
`commit()` passes `beforeWrite` to `writer.write` and no longer calls it itself. The row 194 b3 early check
stays. It costs one read, keeps T21's refusal before any validation work, and is no longer what protects
the revoke. Its comment is rewritten to say so, and the "(BUILD.md follow-up)" sentence goes.
`instanceSettings({ ..., writer = organizationWriter({ dir, rolesDir }) })` takes an optional writer, so a
test can inject one (the brief's "injected writer"). `runtime.mjs` passes none.
### 3. The bus names a refusal after a revoke (broker.mjs `#organizationFail`)
The bus answers with a code only, and the CLI and Console look the text up by code. So the "may already be
revoked" signal has to be a code. Two new codes:
- `revision-conflict-revoked`: `e.revoked && e.code === 'revision-conflict'`.
- `outcome-unknown-revoked`: `e.revoked` with any other code. The write may or may not have landed, since a
failure after the rename is recovered as committed.
Both are checked before the existing mappings. An error without `revoked` maps exactly as today, so a
refusal before any revoke keeps today's code and text. Q2 asks about the names.
### 4. The texts
- CLI `instances.mjs` REASONS:
- `revision-conflict-revoked`: "the business file changed before the write, after the agent's tokens
were revoked; the tokens may already be revoked and the instance can't use them; read the instances
again and run the same command again, which is safe".
- `outcome-unknown-revoked`: "the write's outcome is unknown and the agent's tokens may already be
revoked; read the instances before trying again".
- Console `serve.mjs` AGENT_REASONS: the same two, in the Console's wording ("delete again").
- `#fireJob`'s `fire.failed` notice: when the code ends in `-revoked`, it adds "Its credential tokens may
already be revoked." The chief's synchronous fire (no grants) answers with the code, as every chief verb
does.
- `transport.mjs` EXIT: `outcome-unknown-revoked` exits 1, as `outcome-unknown` does. Console
`bus.mjs` STATUS: `revision-conflict-revoked` 409, `outcome-unknown-revoked` 503. A delete's code
reaches both as a closed request's `refusal`, so these two only matter for a direct verb answer.
## Tests
- **T1, the brief's fire test** (business `instance-settings.test.mjs`). The fire uses an injected writer
that wraps the real one. Its `write` makes one hand edit of the business file (a vars change on another
instance) and then calls the real `write`, so the edit lands after `commit()`'s early check and before
the lock's `:188` check. Expected:
- the fire refuses `revision-conflict` without `revoked`;
- the revoke spy has no calls;
- the business file's bytes are the hand edit's;
- changes.jsonl has no new prepared entry.
- **T2** (same file). A fire on a real writer built with `barrier: stage => stage === 'prepared' && edit()`.
The revoke runs, then `:221` refuses. Expected: `revision-conflict` with `revoked === true`, one revoke
call, the file's bytes are the edit's, and the last receipt is `aborted`.
- **T3** (same file). The same, with a `prepared` barrier that throws. Expected: the error has
`revoked === true`, one revoke call, and the file unchanged. A delete through the same writer gives the
same result (T3b).
- **T4** (bus `fire-revokes-grants.test.mjs`, its injected `f.org`). `f.org.fireError` is a
`revision-conflict` with `revoked: true`. Expected:
- the job's `fire.failed` carries `revision-conflict-revoked`, and the inbox message says "may already
be revoked";
- the same with no `grants` (the synchronous fire) refuses `revision-conflict-revoked`;
- a plain `revision-conflict` still maps to `revision-conflict` and the message lacks the sentence.
- T4b: `outcome-unknown-revoked` for an fs-style error with `revoked`.
- **T5** (cli `lifecycle.test.mjs` or `instances.test.mjs`, whichever already reads a closed delete's
refusal). A delete closed with `revision-conflict-revoked` prints the new text, and one closed with
`revision-conflict` prints today's.
- **T6** (webui `agents.test.mjs`). The same pair for the Console's reason.
- T21 (bus `lifecycle-revoke.test.mjs`) stays as it is, for delete.
## Mutants
| Mutant | Change | Killed by |
| --- | --- | --- |
| M1 | `beforeWrite` before the lock: `commit()` calls `beforeWrite()` itself and passes none to `write` | T1 (the revoke spy has a call) |
| M2 | The fire refusal dropped: the `:188` revision check removed | T1 (the write lands over the hand edit) |
| M3a | The mark dropped: no `revoked = true` in the catch | T2, T3, and T4 through the codes |
| M3b | `#organizationFail` ignores `revoked` | T4 |
| M3c | CLI text: the two REASONS entries removed | T5 |
| M3d | Console text: the two AGENT_REASONS entries removed | T6 |
| M3e | The notice: the `fire.failed` sentence removed | T4 |
M3a-M3e together are the brief's "drop the may already be revoked text".
## Files
- `packages/business/src/organization.mjs`
- `packages/business/src/instance-settings.mjs`
- `packages/business/tests/instance-settings.test.mjs`
- `packages/bus/src/broker.mjs`
- `packages/bus/tests/fire-revokes-grants.test.mjs`
- `packages/cli/src/instances.mjs`
- `packages/cli/src/transport.mjs`
- one cli test file
- `packages/webui/src/serve.mjs`
- `packages/webui/src/bus.mjs`
- `packages/webui/tests/agents.test.mjs`
- This packet.
## Gate
As the brief says:
- Duckworth approves the manifest.
- The bus, business, cli and webui suites and every `scripts/test-*.sh` are green on Sage's slot, with
the touched test files run whole.
- M1-M3e are killed.
Before the in-review move I grep the tests for the changed comment and error text, and for hash pins on the
changed files.
## Questions for Duckworth
- **Q1.** Should `beforeWrite` run after the writer's validations (my pick) or straight after `:188` (the
brief's literal place)? Running it later means a document the writer would refuse revokes nothing.
- **Q2.** Are two new codes, `revision-conflict-revoked` and `outcome-unknown-revoked`, the right way to
carry the signal? The alternative is to give `BusError` a detail field, which every CLI and Console
reader would then have to learn. The codes are additive and no existing code changes meaning.
- **Q3.** The brief's mutant "drop the fire refusal": I read it as removing the `:188` check (M2). If you
meant the fire test's own refusal, say so and I'll redefine it.
+16
View File
@@ -258,3 +258,19 @@ Suites (20:01:47Z):
Not run here: every scripts/test-*.sh and the other packages. Those are Sage's 283 gate, after Webby's
APPROVE.
## 2026-10-23 G1: mos-1528 OK for the mapping.test draft deepEqual (sage-3713)
This entry completes the N3 line above (BUILD.md:42, "only the draft deepEqual at mapping.test:48 gains
`supporting: []`"). BUILD.md is append-only, so :42 stays as written. Mos OK'd the change of that old
assertion in mos-1528. It is now at packages/library/tests/mapping.test.mjs:52, and commit 331653b38
changed it. Everything else in that commit's hunk is new test lines, not changed old ones.
- Old, mapping.test.mjs:48 at 45dca69f6:
`assert.deepEqual(m.universes.idea, { kind: 'draft', name: 'New World', books: [], playground: ['Drafts/New World/'] });`
- New, mapping.test.mjs:52 at b2a1f4092:
`assert.deepEqual(m.universes.idea, { kind: 'draft', name: 'New World', books: [], playground: ['Drafts/New World/'], supporting: [] });`
The line gains only `, supporting: []`; nothing else in it moved. The business.test and scope.test hunks
add tests only (sage-3713: no OK needed). The other old-test change in this row is survey.test:73
(mos-1330 item 4, 28918824c). Doc only.
+8
View File
@@ -0,0 +1,8 @@
# Lena
Builder seat, Codex gpt-6.1-sol, started by Mos under Q245 (mos-1506). Owns row 296 (FED R7, handed over from Quackerjack).
No launcher in this directory. The seat runs as a T3 thread (thread db27faca) and works in its own worktree. It has no
credentials of its own; it pushes only its own `lena/*` branches through the repository credential helper (mos-0981),
never `refactor`, `main` or another seat's branch. Claude seats orchestrate and review (Q245). Registered by Sage on
2026-10-23 so the queue can name the seat as row owner (store.mjs isSeatDir).
-277
View File
@@ -1,277 +0,0 @@
# Row 286: C2-03b push and per-seat credentials for the library mirror (#1791)
Owner Ludwig. Reviewer Dewey. Gate owner Sage (sage-2909).
Brief: `docs/plans/2026-10-20_case2-rows.md`, "## C2-03b", at 94c33a43c. Design 7.2 and the ruling
after r11 "agents never write story" in `agents/gosalyn/work/case2/DESIGN.md` at b68d79663.
Base: `refactor` at 94c33a43c. The brief cites aca16404c, and lines have moved since:
`GRANT_EVIDENCE` is `broker.mjs:253` now, not `:246`.
Status: code written, local and unrun (18:48Z on). No node until Sage's CLEAR, after row 258's run.
## What the code does today (94c33a43c)
- `packages/library/src/sync.mjs:32` `syncCommand(kind, url, {mirror, branch, user, slot})`. It refuses
any kind but `fetch`. The env passes `MOSAIC_LIBRARY_HOST`, `_USER` and `_SLOT` to `bin/askpass`.
- `bin/askpass` checks `-f` and `! -L` on the slot, then reads it. It doesn't check the uid or the mode.
- `sync.mjs:51` `slotPresent` checks lstat: a regular file, our uid, no group or other bits.
- The slot path is built in `packages/bus/src/runtime.mjs:211-217` (`syncOptions`) as
`<configDir>/secrets/<business>/library-gitea`. The broker only calls `this.#library.sync(context,
{accept})` (`broker.mjs:4630`), and the timer calls `libraryModule.sync` directly (`runtime.mjs:533`).
- The sync state file has a strict key list in `packages/library/src/mirror.mjs:222`.
- `chief-of-staff` is a definition (`STAFF_TO`, `broker.mjs:240`), not a fixed instance name.
- A seat's Gitea user is in `gitea_grants.user` and `gitea_users`. Its token file is
`<storeRoot>/<business>/<agent>/gitea` (`gitea-grant.mjs:379`). `giteaKeys.held(business, agent)`
answers the held case.
## Plan
1. `syncCommand(kind, url, {mirror, branch, user, file, commit})`. `kind` is `fetch` or `push`. Same
`SAFE` prefix, `-c` keys and env for both. A push is
`push --porcelain --no-verify --end-of-options <url> <commit>:refs/heads/<branch>`, with no `+`.
`commit` must be a full sha. The env var stays `MOSAIC_LIBRARY_SLOT` but now names whichever file
answers: a seat file, the chief's file, slot `library-gitea` or slot `library-human`.
2. `push(context, {commit, credential, retried, command})` in `sync.mjs`. git's porcelain line for
the ref decides:
- `!` with `[rejected]` and `(fetch first)` or `(non-fast-forward)` means the tip moved. Fetch once
with the same credential and return `{pushed: false, raced: true, tip}`. With `retried: true`, the
same rejection refuses `stale-base`. C2-02 owns the re-apply.
- Any other failure refuses `library-push-failed`. git's stderr isn't kept.
- A remote that fails C2-04's URL rules refuses `library-remote-invalid` before any git call.
3. `bin/askpass` gets `readSecretFile`'s checks, the same way: no symlink, the bus's uid, mode 0600.
In sh: `test -f && test ! -L && test -O`, plus a mode check through `stat -c %a`. Only the path
reaches that argv. The user check stays an exact match on the one configured user. The check and the
read happen at different times (TOCTOU). The bus owns the directories, so I take that as the
accepted limit (Q1).
4. Credential choice for the fetch, as a pure function `fetchCredential(store, business, keys)` in the
bus. The broker exposes it, and `runtime.mjs` passes its answer to `sync` for the verb and the timer:
- The chief is the one instance whose definition is `chief-of-staff`.
- Evidence: `SELECT 1 FROM events WHERE business=? AND ${GRANT_EVIDENCE} AND
json_extract(body,'$.method')='gitea' AND json_extract(body,'$.agent')=?`, of any action. It
names no project and never reads `gitea_grants`.
- No evidence: slot `library-gitea`, `{kind: 'slot'}`.
- Evidence, a live `gitea_grants` row for the chief and not held: `{kind: 'chief', user, file}`,
with the user from that row. The fallback test never reads the table. This path does, because it
needs the user.
- Evidence and anything else (revoked, fired or held): `library-fetch-no-grant`, before any file is
opened.
- No chief instance (fired): Q2.
5. The sync state gets `credential: {kind, user} | null`. `library.status` shows it.
`library-fetch-no-grant` shows as `lastError.code`. This changes `mirror.mjs`'s key check (Q3).
6. Slot `library-human` is `<configDir>/secrets/<business>/library-human`. `humanCredential(...)`
refuses `library-human-missing` before any git call when the slot is missing or fails the file checks
(lstat: regular file, our uid, 0600). Her Gitea user: Q4.
## Files owned extension (sage-2922)
Added to the brief's list: `packages/bus/src/runtime.mjs` (`syncOptions` at :211-217 and the timer's
call at :533) and `packages/library/src/mirror.mjs` (the state key list at :222). sage-2922 wrote
`packages/library/src/runtime.mjs`, but the file is `packages/bus/src/runtime.mjs`. In mirror.mjs
the row 222 contract holds: keys are added and none renamed. Before in-review I grep `packages/*/tests`
for hash pins and path reads on both files and check them against every in-review manifest.
## Scope questions (for Dewey and Sage before code)
- Q1. The askpass TOCTOU above. Is it accepted as is, or should the helper be a node script that does
O_NOFOLLOW plus fstat? If node, it would read the token in process and print it to git's pipe.
- Q2. Fired chief. The instance and its `gitea_grants` row are gone, so I can't name the agent for the
evidence check. My recommendation fails safe: with no chief instance, the fetch refuses
`library-fetch-no-grant` when any gitea grant event exists in the business, and uses the slot only
when none exists.
- Q3. Files owned names `sync.mjs`, `askpass`, `broker.mjs` and the tests. The choice also needs
`packages/bus/src/runtime.mjs` (`syncOptions` and the timer's call) and
`packages/library/src/mirror.mjs` (the state key list for `credential`). I'd add both to the
manifest, with only those hunks changed.
- Q3: approved, sage-2922. See above.
- Q4: sage-2922 allowed `user` only if design 7.2 or the ruling after r11 makes it her account. Neither
does. `packages/library/README.md:31` at 94c33a43c says "`user` is the bot account name from design
step 3, required for sync", so it is the fetch identity and can't be reused for her save. Back to Sage.
My recommendation: `humanCredential(context, {user})` takes her login as a parameter, so this row adds no
mapping field. The row that adds the save, C2-02 or C2-11a with `editor`, names the field. That
needs a mapping schema change, which is Sage's call.
Ruled sage-2925: accepted. `humanCredential(context, {user})` refuses `library-human-missing` before
any git call when the slot is missing or bad or `user` is missing. This row adds no mapping field.
Row 283 (C2-01d) adds an optional `editor.user`, and row 288 (C2-02) passes it in.
- Q4 (original). Her Gitea user for `library-human`. The entry's `user` (`mapping.mjs:52`) is today the sync
user, the bot's. The design names `editor {name, email}` (C2-11a) but no Gitea login. My
recommendation: the entry's `user` becomes her Gitea login, used only with slot `library-human`. The
fallback fetch keeps that same user too, because the bot slot was set up for it. Otherwise this row
takes the user as a parameter and C2-02 or C2-12b names the field.
## Tests (brief list, mapped)
T1 push lands a fast-forward. T2 a moved tip reports the race. T3 a second race refuses `stale-base`.
T4 a dead remote refuses `library-push-failed`. T5 askpass answers with the named seat's user and file,
and refuses another seat's user, a symlink, 0644 and another uid (with a fallback note if the test can't
chown). T6 the fetch uses the chief's file with a live grant, and the slot only with no chief event.
T7 revoked (through `grants.revoke`), fired (through `instance.fire`) and held each refuse
`library-fetch-no-grant` with a valid slot present, and each asserts the `gitea_grants` row is gone
first. T8 a chief grant on another project ends the fallback. T9 T7's three cases with the slot at 0000.
T10 a missing `library-human` refuses `library-human-missing` and runs no git. T11 a token search of
argv, the mirror config, the run log and the test output. Mutant: a `+` added to the push refspec fails.
## Gate
Dewey approves the manifest. The library and bus suites, plus every `scripts/test-*.sh`, pass on Sage's
gate. The mutant dies. A token search of the run's output finds nothing.
## Early look (dewey-0860), folded
Q1, askpass: sh, with no gap between the check and the read. The helper keeps `test -f` and then:
- opens the slot with `exec 3<"$slot"`;
- stats the open file with `stat -L -c '%d:%i %u %a %s %F' /dev/fd/3`, and the path itself (an lstat)
with `stat -c '%d:%i' -- "$slot"`;
- refuses unless the two dev:inode values match, the type is regular, the uid is `id -u`, the mode is
600 and the size is at most 16384;
- reads the token from fd 3.
A symlink or a swap at either moment changes the inode, and the token comes from the file that was
checked. This matches `readSecretFile` (`gitea-grant.mjs:167-181`).
Residual, the same on both paths: a FIFO swapped in after `test -f` blocks the open. Neither side uses
O_NONBLOCK.
Swap test T5b: the direct helper test puts a `stat` shim on its own PATH. On its first call the shim
renames another file over the slot, then runs the real stat. The helper must exit 1 and print nothing.
Mutant M2 drops the inode compare and must fail T5b.
Q2, the chief: found through `roles` by definition, not through `launch.instances`. A fire only delists
the name (`packages/business/src/instance-settings.mjs:355`), and `roles[name]` stays. Only a delete
removes it (`deletedDocument`, :70).
- Gitea grant evidence for any `roles` entry whose definition is `chief-of-staff` ends the fallback.
That includes a fired chief beside a new listed one.
- A live credential comes only from the listed chief's live, unheld `gitea_grants` row.
- With no `roles` entry of that definition (deleted, or never a chief), any gitea grant event in the
business refuses `library-fetch-no-grant`.
- Cost, for Sage: row 236 lets seat gitea grants exist before C2-21. So a business with no chief
entry and one seat grant loses the slot fallback. That fails safe, but it narrows "an install that
runs before C2-21 still syncs".
- T7's fired case also asserts that `roles[chief]` still exists after `instance.fire`.
N1: the `credential` key is optional in `mirror.mjs`'s exact `keys(...)` check (:221), so a pre-286
state file still reads. The old fixtures have no `credential`: `library-sync.test.mjs:18`,
`library.test.mjs:106` and `mirror.test.mjs:13`. New test T12 reads a pre-286 state file. Row 224
(Della, 23816cf28) also changes `packages/bus/src/runtime.mjs`. Whichever lands second rebases and reruns
bus whole.
N2: `[remote rejected]`, a hook refusal, is `library-push-failed`, not a race. Only `[rejected]` with
`(fetch first)` or `(non-fast-forward)` counts as a race. The evidence query depends on
`body.method` and `body.agent`. gitea `grant.applied` carries both at `broker.mjs:2479` and
`grant.revoked` at :1862 and :2797. The spend event (`operation: 'grant.gitea'`, :1093) carries
neither, so it doesn't match.
N3: `fetchCredential` reads the store, so it is the bus's choice function, not a pure one.
## Rulings sage-2928
- Q1: Dewey's fix, in sh. On dragon-lin `/bin/sh` is bash, and GNU coreutils stat 9.11 gives
`stat -L -c '%d:%i %u %a %s %F' /dev/fd/3` on an open fd. Checked at 18:47Z with a scratch file, not
the repo. The helper runs as git's child in the bus process, not under bwrap. T5b stages the swap with
the PATH stat shim. If a run shows the swap can't be staged reliably, BUILD.md names M2, which drops the
fd compare, and it gets killed.
- Q2: chief by `roles[*].definition === 'chief-of-staff'`. The blanket refusal applies only with no such
entry. Departure from the brief's "an install that runs before C2-21 still syncs", accepted in
sage-2928: it refuses rather than widens, and every install enrolls the chief at initial configuration
(F40, Q226). The refusal's message names the fix: "add the chief of staff, or grant the library
through C2-21".
- N1: as above.
## Build notes (code written; nothing run yet; dewey-0864 folded)
Files changed:
- `packages/library/src/sync.mjs`: `syncCommand` takes `push` with a full-sha `commit`; `push()`;
`humanCredential()`; `sync()` takes `credential`; `HUMAN_SLOT`, `CREDENTIAL_KINDS`. The `slot` opt
and `MOSAIC_LIBRARY_SLOT` keep their names and now name whichever file answers.
- `packages/library/src/index.mjs`: the new exports.
- `packages/library/bin/askpass`: Dewey's fd 3 check.
- `packages/library/src/mirror.mjs`: optional `credential` in the state key check. Nothing renamed.
- `packages/bus/src/broker.mjs`: `LIBRARY_FETCH_FIX` and `libraryFetchCredential(business)`.
- `packages/bus/src/runtime.mjs`: `syncOptions` passes the broker's choice to the verb and the timer.
The timer's held line adds `fix` for `library-fetch-no-grant`.
- `packages/library/README.md`: "Push and credentials (C2-03b)".
- Tests: `packages/library/tests/sync.test.mjs` (appended), `packages/bus/tests/library-credential.test.mjs` (new).
Choices made without a ruling. Each is small and reversible:
- `humanCredential(context, { user, configDir })`: sage-2925 named `{user}`. The slot path needs the
config dir, and the library package doesn't know it, so the caller passes it. That's the same
source runtime's `slotDir` uses.
- `BusError` carries only a code, so the sage-2928 fix text can't ride on the verb's refusal. It
goes in the timer's log line (`fix`) and in the README. The verb answers `library-fetch-no-grant`.
- T7 and T9 run the real verbs (dewey-0864, ruled by sage-2947: no SQL staging; replaces the
staged state in cefebf65b). Until row 285 lands, the test passes its own definitions; once it lands
the real chief definition carries gitea. Whichever of 285 and 286 lands second rebases and reruns
library and bus whole (sage-2947). The chief's grant goes through decision.raise and the human's yes against fake-gitea-api.mjs. The test's own
definitions give chief-of-staff a gitea credential, as gitea-grant.test.mjs gives coder one. The
real roles/chief-of-staff.json has `credentials: []`, so a live chief can't get one before C2-21.
- Revoked: `grants.revoke`, then the row is gone and the fetch refuses.
- Fired: `instance.fire` can't fire the launch.by chief. Only the launch.by role calls it, and it
refuses its own name (`organization-instance-referenced`, broker.mjs `#chiefLifecycle`). So the
test's launch.by is `boss` (definition pm, the chief's authority), and boss fires the one listed
chief-of-staff instance. Step G deletes the row (row 281), `roles.chief` stays, the fetch refuses.
Only launch.by may call instance.fire (`role-not-chief`, broker.mjs:4308 at 94c33a43c) and it
refuses its own name (:4335), so this is the only fired chief the verb allows. Accepted by
sage-2951 as brief owner and read the same way in dewey-0869.
- T9's revoked case runs `grants.revoke` on the runtime's own data root and store, between starts.
T9's runtime gets a scratch roles/ whose chief-of-staff carries `{service: gitea}`, as row 285
ships it (case2-rows.md:1823-1824), so its definitions match the grant's (dewey-0869). After a
rebase onto 285 the copy needs no edit.
- Delisted with the row still there, a `fire.stopped` with no `fire.done`, held, two chiefs and
another project stay unit checks on the choice function with SQL fixtures.
- "Another uid" in T5: the suite can't chown, so a PATH `stat` shim reports uid+1 for the open file.
The real `id -u` compare is covered only through that shim (dewey-0864).
- Two listed chiefs, or none listed, refuse `library-fetch-no-grant` (T8).
- The race fetch inside `push()` takes sync's `running` guard (dewey-0864 R1, in this row per
sage-2947). While a sync of the mirror runs it refuses `library-sync-busy`, fetches nothing, and
the caller writes again. Test: "race fetch: while a sync of the mirror runs". Its sync fetch is a
git alias that touches a marker, then waits for a release file. The push starts after the marker
exists and the release comes after the refusal, so nothing depends on timing (dewey-0869).
- The slot at 0000: T9 covers the revoked case at runtime. Fired and held refuse inside the choice
function, which takes no path and opens no file. `sync` with any `{ refused }` runs no git (library
test, valid slot present).
- First-run reds in the new tests are mine to fix in setup and report afterwards (mos-1272).
- The chief's evidence is any gitea grant event naming the chief, of any action (grant.applied,
grant.revoked and the rest), per the plan. The spend event names no agent, so it doesn't count.
Test map:
- library sync.test.mjs: argv (push), T1, T2+T3, T4 (dead remote, hook, wrong token), refused or
unsafe credential runs no git, T10, fetch credential and state with N1/T12, T5+T5b.
- library sync.test.mjs also: race fetch busy (R1).
- bus library-credential.test.mjs: T6, T7 (real revoke and fire), T7 choice checks, T8, departure,
T9 runtime (real grant, chief file and user via timer and verb; real revoke, slot 0000: no git,
log `fix`, state `credential: null`).
- webby-0151 R3: T9 reads `library.status` for `credential` and `lastError`.
- T11 token search: T1 scans the data root and every file but the seat's; T9 scans the log lines.
The gate's output search uses the fixture tokens `fixture-token-*-made-up-00{42..49}`.
Mutants (each must die on a semantic assertion):
- M1: `+` before the push refspec in `syncCommand`. Expected to fail: the argv test, and T2 (the
forced push lands, so `raced` is never reported and her commit is gone).
- M2: drop `test "$1" = "$path"` from askpass. Expected to fail: T5b (the helper prints the checked
file's token).
## r2 rebase (sage-3579)
Sage ruled that 286 now goes before 258, because 222 is its only after row. Branch ludwig/row286-r2
rebases b9506b352 (base 94c33a43c) onto origin/refactor 45dca69f6. The rebase had no conflicts.
- Range-diff 94c33a43c..b9506b352 against 45dca69f6..r2: all 11 commits are `=`, so no patch
changed.
- Rows 254 (331597709) and 268 (c27207f6e) were already in the old base 94c33a43c. Between the two
bases nothing changed under packages/library.
- Paths the two test files import or read, diffed 94c33a43c..45dca69f6: bus broker.mjs, runtime.mjs
and store.mjs changed. None of the others changed: library/*, bus credentials, gitea-grant,
mapping, mirror, reader, survey, sync, the fake-gitea-api, helpers and host-fixtures modules,
business helpers (rolesCopy, systemFor), project git, seat checkout and fake-gitea, and roles/.
- broker.mjs: the constructor gains `accessStamp` and `compactions`, both defaulting to null, and
my tests pass neither. No base hunk falls in the fire job, the revoke job or the instance.fire
verb. Old :4308/:4335 are now :4852/:4879, with the same text. The new console-cap check refuses
a non-console session only on CONSOLE_VERBS, and the library verbs are not among them. The
request path's access re-read applies only to `s.user` sessions, and my tests open none.
- runtime.mjs: consoleOwners (default []), the access timer, compactions and the session-clear
hooks. The Credentials and giteaStart wiring that T9 uses is unchanged.
- store.mjs: schema 3l to 3n (row 206 thread_shares, row 271 session_ops and message_cancels).
Each test opens a fresh Store, and none pins a schema version or step count.
- Hash pins: no test or script line pairs a 64-hex value with a path I change. The positive
control finds 64-hex pins in, for example, account-migration.test.mjs.
- Row 285 has not landed. roles/chief-of-staff.json at 45dca69f6 still names no gitea credential,
so T9 keeps its scratch roles copy (sage-2947).
- sage-3589 freezes stack-release.sh, webui-service.sh, bus-service.sh, stack-copy.sh and common.sh.
This row changes none of them.
- Still to run, on CLEAR: library and bus whole, every scripts/test-*.sh, M1 and M2, and the token
search, all on r2.
+53
View File
@@ -182,3 +182,56 @@ has been thrown; the kill claims are unverified until CLEAR):
Built, not run. `node --check` has not been run on this round's files (no node before the CLEAR); the
phase A pass above covered the earlier text only. The commit is local and waits for no gate under Sage's
sage-2716 instruction, which allows git and docs work only; push and claim wait for Sage's go.
## Round 3: rebase onto 45dca69f6, drift check, hash-pin grep (2026-10-23T18:53:43Z, sage-3576)
Appended; nothing above is edited. Git only; nothing run, nothing pushed. Branch researcher/row216-r4 holds the
one row 216 commit on 45dca69f6 (origin/refactor, 10-23). Earlier base: 48e450ce8 (row 253).
- Rebase: clean. `git range-diff 48e450ce8..038089e5f 45dca69f6..researcher/row216-r4` shows the commit as `=`.
- Landed in 48e450ce8..45dca69f6: 1175 files. Path overlap with this row's 7 paths: none. packages/library: no
landed file. packages/harness/src/tools.mjs (imported by query-fixture.mjs or the tests): not landed.
- Hash-pin grep (the item 216 owed): 64-hex in packages/library: none. Positive control: 364 files in
packages/*/tests and scripts match 64-hex. Tests and scripts that name library files by path:
bus/tests/library.test.mjs and library-sync.test.mjs and bus/src/runtime.mjs import library/src/index.mjs;
business/src/business.mjs and its test import library/src/mapping.mjs (unchanged by this row);
cli/tests/stack-copy.test.mjs, stack-release-fixture.mjs:310 and stack-release.test.mjs:1991 copy
packages/library/src as a tree; scripts/stack-copy.sh:37 copies it; scripts/mosaic:41 runs survey.mjs. None pins
a hash of index.mjs, index-build.mjs or query.mjs.
- bus/src/runtime.mjs landed changes after 48e450ce8 and uses libraryModule by named members (ensureMirror, SLOT,
readLibraryFile, libraryStatus, sync, LibraryError, SYNC_INTERVAL_MS) only; the landed diff touches none of them,
and this row's two new index.mjs exports (query and index build) are not iterated by any caller.
- Gate additions for phase B: run bus library.test.mjs and library-sync.test.mjs whole (they import index.mjs), and
the cli stack-copy and stack-release tests that copy packages/library/src.
## Round 4: phase B on 4e5d28ab2, two test fixes for r5 (2026-10-23T20:20:51Z, sage-3702, mos-1528)
Appended; nothing above is edited.
Phase B receipts on 4e5d28ab2 (researcher-r216-kit/out-b1): library whole 114 pass, 2 fail; bus library.test and
library-sync.test 12 pass; cli 266 pass. The 3,000-file rebuild took 3807 ms (the test, with fixture setup, 4070 ms;
`t.diagnostic` in index-build.test.mjs). No row 216 mutant was required or thrown in that round.
The 2 library reds are test faults, not product faults. Both are placed as first-run reds in files this row adds
(mos-1272); Mos ruled both fixes in mos-1528 and Sage relayed it in sage-3712.
- R4: `packages/library/tests/index-build.test.mjs`, test "a different repo path, mapping or commit gets its own
index". Old: `writeFileSync(join(repo, 'Book One/Places/New.md'), …)` with no `Book One/Places` folder in FILES, so
the write failed with ENOENT. New: one `mkdirSync(join(repo, 'Book One/Places'), { recursive: true })` before the
write (import line gains `mkdirSync`). No assertion changes.
- R5: `packages/library/tests/query.test.mjs`, test "a hybrid sees its sources canon, minus exclusions, and no
playground". The assertion sorts the actual paths and compared them to an unsorted literal, so the literal had
the wrong order (Characters before Chapters; Second World Characters before Chapters). New: only the expected
literal is reordered into sorted order. The `.sort()` on the actual side stays, and the assertion still checks
order. The set of seven paths is unchanged.
- Product code: no edit.
Reruns owed after the r5 commit (run on Sage's CLEAR, after the 283 gate): index-build.test.mjs whole,
query.test.mjs whole, library whole, and the mutants those two files kill (M-a to M-e above). Results are appended
below as a new entry.
Run limit note: stack-release.test.mjs ran 644 s in the cli run. A per-file limit of 3 x 644 = 1932 s covers it.
Sage's gates run cli as one whole-package `node --test` under 2100 s.
Carry notes from Filbert's static check (doc only, no change in r5): N1 and N2 stay recorded as he gave them. The
`After` list in this file still names row 268; row 268 landed at c27207f6e.
+100
View File
@@ -0,0 +1,100 @@
# Row 220: C2-10a, no raw session view (M7) and no raw Discord engine (M8)
Phase A. No test, suite or mutant has been run. Sage opens the slot.
- Owner: researcher seat (Haiku 5.5 subagent), dispatched by Sage under lead decision 129.
- Reviewer: Filbert.
- Branch: `researcher/row220`, from `origin/refactor` at d37210288.
- Brief: `docs/plans/2026-10-20_case2-rows.md`, C2-10a (line 495) and "Rules every row keeps".
- Design: `agents/gosalyn/work/case2/DESIGN.md` on `origin/gosalyn/case2-design`, sections 5.1 (M7, M8), 7.6, 8 (row list).
## Status
| Item | State |
|---|---|
| M7 reader side (`conversation-not-listed`) | Built. Tests written, not run. |
| M7 production wiring (the caller that passes `isCreative`) | Not built. Outside the file list, and it needs a ruling (question 1). |
| M8 `discord check` and `discord run` refusals | Not built. `packages/discord/src/cli.mjs` is untouched. Blocked on question 1 and question 2. |
Phase A is therefore partial. The row cannot pass its acceptance until Sage rules on the questions below.
## Files
- `packages/conversation/src/reader.mjs`: exports `NOT_LISTED`; `createReader` takes `isCreative` (default `() => false`); `catalogue()`, `open()` and `next()` hide a root for which it returns truthy.
- `packages/conversation/tests/reader.test.mjs`: three new tests, inserted before the "unknown conversations" test.
- `agents/researcher/work/queue-220/BUILD.md`: this file.
Nothing else is changed. `node_modules` in the worktree is a symlink to the canonical checkout and is ignored by git.
## Brief and design items mapped to tests
| Item | Test |
|---|---|
| M7: a creative session file under the root isn't listed | "M7: a creative seat's session is not listed and won't open by id; an assistant seat still lists" |
| M7: and won't open by id (`conversation-not-listed`) | same test; second check of the open refusal in "M7: a creative session already open refuses its next page once the root is hidden" |
| M7: an assistant session still lists | same test (the `sage` seat is listed and opens with its text) |
| M7: an already-issued cursor stops once the root is hidden (my addition; the design's "won't open" implies it) | "M7: a creative session already open refuses its next page once the root is hidden" |
| M7: refused rows and the unsupported placeholder of a creative root are hidden too (my addition; the design hides "creative sessions", and a refused row or placeholder names one) | "M7: a creative root's refused files and its unsupported placeholder are hidden as well" |
| Default behavior without `isCreative` is unchanged | the existing reader suite; the default predicate returns false |
| M8: `discord check` / `discord run` refuse `discord-engine-not-allowed` on a library business, and a `mosaic-bus` binding with `tools` | none (not built, question 1) |
| M8: a pi binding on a business without a library still checks clean | none (not built, question 1) |
Every test's fixture text is `CREATIVE-MARKER` or a made-up assistant line. The M7 tests assert the marker is absent from the catalogue and refusal output.
## Choices made in phase A
- `isCreative(root)` is the reader's only input. The reader reads no business file. A truthy answer hides, so a doubtful answer fails closed. The predicate must depend on `root.seat` and `root.project` only, because a cursor is checked against the root object from an earlier listing.
- Hidden check placed after the cursor's actor/purpose/conversation/branch checks in `next()`, and before the source is read.
- `open()` checks hidden after the id resolves, so a creative id gets `conversation-not-listed`, and an unknown id still gets `unknown-conversation`.
- `conversation-not-listed` is `reconcile: false`. The design names no reconcile flag. `unknown-conversation` uses true. Question 3.
- The default predicate is `() => false`. Until a caller passes one, M7 does nothing. This is the open risk, and question 1 covers it.
## Grep over `packages/*/tests` and `scripts/test-*.sh` (static, phase A)
Changed path `packages/conversation/src/reader.mjs`:
- `packages/conversation/tests/reader.test.mjs:14` imports `rootsFromSpecs, createReader, conversationId, cwdInProject, UNSUPPORTED_HARNESS`. It is the file under change.
- `packages/control-board/tests/serve.test.mjs:26` imports `UNSUPPORTED_HARNESS`. That export is unchanged.
- `packages/library/tests/sync.test.mjs:15` imports `packages/library/src/reader.mjs`, a different file. Not a hit.
- `scripts/test-*.sh`: no reference to the conversation reader.
- 64-hex pins naming this path: none. `packages/bus/tests/grant-migration.test.mjs:24` has a 64-hex value, but it is a DDL digest, not a pin on this path. That file matched only the word "reader" in a test title.
Changed path `packages/conversation/tests/reader.test.mjs`:
- No other test or script names this file. It runs through `packages/conversation`'s `node --test tests/`.
- No 64-hex value in the file.
Changed path `agents/researcher/work/queue-220/BUILD.md`: no pin.
`node --check` passed on both changed `.mjs` files.
## Phase B plan (not run)
The reader test uses `os.tmpdir()`. Set `TMPDIR` to a scratch dir first, per the rule against `/tmp`.
```
export TMPDIR="$(mktemp -d /mnt/storage/scratch/tmp/r220XXXXXX)"
cd packages/conversation && node --test tests/reader.test.mjs
cd packages/conversation && node --test tests/
cd packages/discord && node --test tests/
cd packages/control-board && node --test tests/serve.test.mjs
```
The first command is the touched file whole. The second and third are the conversation and discord suites whole, as the brief asks. The control-board serve test is not in the brief. It consumes `reader.mjs`, so I recommend it. Sage can drop it.
## Questions for Sage
1. **Business link (blocks M8 and the M7 wiring).** Neither rule can be built from this row's file list, because the inputs don't exist in the code:
- A reader root carries `seat` (the spec's `agent`) and `project` (the repo directory name). It has no business id. Roots come from control-board scan specs (`packages/control-board/src/scan.mjs`, `discoverRepoAgents`) and seat registrations. Neither carries a definition.
- A Discord binding has `seat` and no business key (`packages/discord/src/binding.mjs`, `TOP_KEYS`).
- Creative status lives only in the business file: `roles.<instance>.definition` in `CREATIVE_DEFINITIONS` (`packages/business/src/vocabulary.mjs:176`). A library project is `projects.<id>.kind === "library"` (`packages/business/src/business.mjs:243`).
- Creative thread sessions are stored at `<dataRoot>/threads/<business>/<thread>/session` (`packages/seat/src/session.mjs:59-64`), outside the `.pi/state` roots the board scans. M7 may therefore reach only creative seats that have a `.pi/state` session root. Please confirm.
- The design does not define the mapping from a seat to a business.
Recommendation: add a required `business` key to the binding, validated against `businesses/<id>.json`. The board builds `isCreative` from `loadBusiness(id)`: a root is creative when its seat is a `roles` key whose definition is in `CREATIVE_DEFINITIONS`, and the business has a library project. This needs file scope for `packages/discord/src/binding.mjs` and `cli.mjs` (M8), and `packages/control-board/src/serve.mjs` (M7 wiring). None of those is on this row's list. I need that scope amendment and the mapping ruling before I build M8 or the wiring.
2. **M8 refusal code for a `mosaic-bus` binding with `tools`.** The design names `discord-engine-not-allowed` for the engine case and no code for the tools case. A new code goes to you first. My proposal is to reuse `discord-engine-not-allowed` with a message that names the tools key.
3. **`reconcile` on `conversation-not-listed`.** I chose `false`. Confirm or change.
4. **HTTP status for `conversation-not-listed`.** `REFUSAL_STATUS` in `packages/control-board/src/serve.mjs` has no entry, so the route returns 422. My proposal is 404, next to `unknown-conversation`. This needs that file on the scope list too.
Phase A stops here. On your "slot clear" I will run the phase B commands above. I will not build M8 or the wiring until question 1 is answered.
@@ -0,0 +1,481 @@
# Row 220 r2: phase A round 2 (M7, M8, business helper, REFUSAL_STATUS)
Phase A only. No node, npm, `node --check` or test run has happened in this round, and nothing is
committed. Phase B (the suites) waits for the coordinator's "slot clear".
- Owner: researcher seat (Haiku 5.5 subagent), dispatched by Sage under lead decision 129.
- Reviewer: Filbert.
- Branch: `researcher/row220-r2`, from `origin/refactor` at da9555ca2. The r1 cherry-pick 3fa833715 is
staged with `-n`.
- Rulings: `agents/sage/work/queue-220/RULINGS.md` on origin/refactor (da9555ca2). Import-by-path is
followed: no export line in `packages/business/src/index.mjs`, and `packages/discord/src/binding.mjs`
is untouched.
## Coordinator rulings, applied
Round 1 answers (earlier packet): applied as before. Absent `businesses/` gives empty sets only on
ENOENT; other failures throw. stack-copy test joins phase B. Webui fixtures pass `businessDir` (renamed `configDirectory` in round 2b below). Discord
refusals exit 2.
Round 2 rulings (coordinator message, this round):
1. **Dangling symlink at `businesses/` refuses.** `loadSeatSets` calls `lstatSync(join(dir, "businesses"))`
first. Only an lstat ENOENT (nothing at the path) returns empty sets. If something is there and
`readdirSync` fails for any reason, including ENOENT through a dangling link, it throws `BusinessError`.
Test added: "a businesses symlink to a missing target throws; no empty set". The absent-directory test is kept.
2. **Sets are read once per public reader call.** `createReader` takes `creativeCheck`, a factory. Each
`catalogue()`, `open()` and `next()` calls it once, then applies the returned predicate to every root.
A load failure refuses `conversation-business-unreadable` for the whole call. `serve.mjs` exports
`creativeCheck(dir = configDir())`, the factory, and `createServer` passes `creativeCheck(businessDir)`.
Test added: "one catalogue calls the creative check once, however many roots it lists". It counts factory
calls: 1 after `catalogue()`, 2 after one `open()`.
3. **Phase B adds three test files:** `packages/webui/tests/tester-browser.test.mjs`,
`tester-cli.test.mjs` and `proof-cli.test.mjs`, run whole (they reach `fixture.mjs` through
`tester-fixture.mjs`). Phase B is 36 files: 33 plus these 3.
4. **Scope additions approved** (coordinator round 2 ruling 4): `packages/control-board/tests/discord.test.mjs`
line 123 and the five webui test files (`fixture.mjs`, `history-fixture.mjs`, `relaunch.test.mjs`,
`return-flow.test.mjs`, `discord.test.mjs`). They stop tests reading the real config directory.
5. **TMPDIR** for phase B is set by the coordinator under `/mnt/storage/scratch/tmp`. No code change.
## Discord exit code
Refusals from the library-seat check exit 2, the code the Discord CLI already uses for configuration and
binding refusals.
- `packages/discord/src/errors.mjs` line 2: `// exitCode follows docs/TOOLS.md: 1 operation failed, 2 invalid data or configuration, 3 refused by a brake (STOP or a held binding; a supervisor must not retry), 4 usage.`
- `packages/discord/src/errors.mjs` line 5: `constructor(message, exitCode = 2, details = undefined)`.
- Config refusal precedent: `packages/discord/src/binding.mjs` line 67, `throw new DiscordError(\`config.dataRoot must be an absolute path: ${path}\`);`. No explicit code, so exit 2.
- `checkLibraryEngine` in `packages/discord/src/cli.mjs` lines 115 to 122. Each refusal passes `, 2)`:
`discord-business-unreadable` (115), `discord-engine-not-allowed` for a non-mosaic-bus engine (119),
and `discord-engine-not-allowed` for a mosaic-bus binding that declares `tools` (122).
- `grep -n ", 3)" packages/discord/src/cli.mjs` finds nothing. `grep -rn "status, 3" packages/discord/tests`
finds only existing brake tests in recover.test.mjs and binding.test.mjs. Not changed.
`library-seat.test.mjs` asserts 2 on all three refusals.
## Files (round 2, uncommitted)
| File | Change |
|---|---|
| `packages/business/src/library-seats.mjs` | new: `loadSeatSets({ dir, rolesDir })` returns `{ librarySeats, creativeSeats }`; lstat-first (ruling 1); read per call |
| `packages/business/tests/library-seats.test.mjs` | new: 7 tests (6 from r1 plus the dangling symlink) |
| `packages/conversation/src/reader.mjs` | r1 plus r2: `NOT_LISTED`; `creativeCheck` factory option, called once per `catalogue()`, `open()` and `next()`; `catalogue()` wrapped so a refusal returns `{ ok: false }` |
| `packages/conversation/tests/reader.test.mjs` | r1: 3 M7 tests, now on `creativeCheck`; r2: 1 spy test (one factory call per catalogue) |
| `packages/control-board/src/serve.mjs` | `REFUSAL_STATUS`: `conversation-not-listed` 404, `conversation-business-unreadable` 503; `export creativeCheck(dir = configDir())` (factory); `createServer({ businessDir = configDir() })` wires `creativeCheck: creativeCheck(businessDir)` |
| `packages/control-board/tests/creative-hidden.test.mjs` | new: 4 tests (3 from r1 plus known-and-unknown id both 503), switched to `creativeCheck` |
| `packages/control-board/tests/serve.test.mjs` | pin test adds `NOT_LISTED` and `conversation-business-unreadable`; conversation fixture passes `businessDir` |
| `packages/control-board/tests/discord.test.mjs` | line 123 passes `businessDir` (ruling 4) |
| `packages/discord/src/cli.mjs` | `checkLibraryEngine` called from `prepare()`; exit 2 |
| `packages/discord/tests/helpers.mjs` | `makeDeployment` creates an empty `businesses/` beside `config.json` |
| `packages/discord/tests/library-seat.test.mjs` | new: 5 tests, all `--offline`, all asserting exit 2 |
| `packages/webui/tests/fixture.mjs` | `businessDir` on the board start (ruling 4) |
| `packages/webui/tests/history-fixture.mjs` | `businessDir` on the board start (ruling 4) |
| `packages/webui/tests/relaunch.test.mjs` | `businessDir` on the board start (ruling 4) |
| `packages/webui/tests/return-flow.test.mjs` | `businessDir` on the board start (ruling 4) |
| `packages/webui/tests/discord.test.mjs` | `businessDir` on the board start (ruling 4) |
Not touched: `packages/business/src/index.mjs`, `packages/discord/src/binding.mjs`, `scripts/stack-copy.sh`.
## Brief item to test map
| Brief item | Test |
|---|---|
| Q1 helper: library and creative sets from business files | `business/tests/library-seats.test.mjs` "library seats come from library businesses..." |
| Q1 a non-library business puts no seat in either set | `library-seats.test.mjs` "a business with no library project..." |
| Q1 absent businesses directory gives empty sets | `library-seats.test.mjs` "an absent businesses directory gives empty sets" |
| Q1 any other failure throws, no empty set | `library-seats.test.mjs` "a businesses path that is not a directory throws"; "a businesses symlink to a missing target throws"; "a business file that can't be read throws"; "a business file that is not valid JSON throws" |
| Round 2 ruling 2: one read per public call | `conversation/tests/reader.test.mjs` "one catalogue calls the creative check once..." |
| M7 hidden from catalogue, open and next | `control-board/tests/creative-hidden.test.mjs` "the check hides the creative seat..."; r1 reader tests (catalogue, open, next, symlink and placeholder) |
| M7 second wall: thread store | `creative-hidden.test.mjs` "a thread store is not a root from a spec..." (asserts `rootsFromSpecs` drops it, then a root over it is hidden with 404 `conversation-not-listed`) |
| M7 unreadable business refuses listing and open | `creative-hidden.test.mjs` "an unreadable business file refuses the listing and open with 503" |
| Coordinator follow-up: known and unknown id both 503 when unreadable | `creative-hidden.test.mjs` "with an unreadable business file, a known and an unknown id both refuse with 503" |
| M8 non-mosaic-bus engine on a library seat | `discord/tests/library-seat.test.mjs` "a library seat's binding on a non-mosaic-bus engine is refused" (exit 2, message names the engine) |
| M8 mosaic-bus binding that declares tools | `library-seat.test.mjs` "...declares tools is refused, and the message names tools" (exit 2) |
| M8 mosaic-bus, no tools, allowed | `library-seat.test.mjs` "...with no tools passes the engine rule" |
| M8 unreadable business file | `library-seat.test.mjs` "an unreadable business file refuses check with discord-business-unreadable" (exit 2) |
| M8 seat in no library business checks clean | `library-seat.test.mjs` "a binding on a seat that is in no library business checks clean" |
| Q3 reconcile false | r1 reader test asserts `[false, "conversation-not-listed", false]` |
| Q4 HTTP 404 and 503 | `creative-hidden.test.mjs` (status asserted); `serve.test.mjs` pin test |
## Choices (for Filbert to check)
1. **Absent versus unreadable `businesses/`.** Only nothing at the path reads as empty (lstat ENOENT). A
dangling symlink, a file, or an unreadable directory throws. Coordinator ruling 1.
2. **Sets are read once per public call.** `creativeCheck()` runs once in each of `catalogue()`, `open()` and
`next()`. The returned predicate answers every root in that call. A catalogue with zero roots still
loads the sets once, so an unreadable business file refuses even an empty list. Coordinator ruling 2.
3. **Behavior change, kept on coordinator ruling (round 2 follow-up): an unknown id or cursor loads the sets
first.** In `open()`, the check runs after `checkCaller` and before `resolveConversation`. In `next()`, it
runs at the start of the try. So with an unreadable business file, a known id and an unknown id both give
503 `conversation-business-unreadable`, where round 1 gave 404 `unknown-conversation` for the unknown id.
Checking the id first would give 503 for a hidden creative id and 404 for an unknown one, which reveals
whether the hidden id exists. Loading first answers every id the same way (fail closed). This reverses
round 1 choice 3. Test: `creative-hidden.test.mjs` "with an unreadable business file, a known and an unknown id both refuse with 503".
4. **Discord refusals use the `code: message` form and exit 2.** Exit 3 is for brake refusals (STOP or a held
binding). A seat's engine or library membership is not a brake. The business CLI is not used as precedent.
5. **The thread-store wall exists in part already.** `rootsFromSpecs` (`reader.mjs` line 44) drops any
sessions directory that is not `<project>/.pi/state/<seat>/sessions`. The M7 check is the second wall, for
roots built another way. The test checks both.
## Static checks (read-only; no node)
- **COPY_PATHS** (`scripts/stack-copy.sh` 29 to 41): `packages/business/src`, `packages/conversation/src`,
`packages/discord/src` and `packages/library/src` are present. `packages/control-board/src` is not. COPY_PATHS
is not changed.
- **Stale names.** `grep -rn -E "isCreative|creativeRootPredicate" packages scripts` finds nothing after this round's edits.
- **Board starts without `businessDir`.** Webui: all five direct starts pass it. Control board:
- `serve.test.mjs` has seven single-line starts without it (lines 402, 445, 464, 483, 509, 528, 907) and four
multi-line starts without it (114, 149, 229, 258). None of those tests reaches a conversation route.
Every conversation route call in the file (lines 1027 to 1171) follows a start that passes `businessDir`
(1006, 1075, 1124). Checked by line order.
- `creative-hidden.test.mjs` builds `creativeCheck(f.dir)` on its own scratch directory. No default is used.
- `discord.test.mjs` passes `businessDir` (line 123).
- **Consumers of the two fixtures** (exact import strings, `from './fixture.mjs'`, `from './history-fixture.mjs'`):
- Direct `fixture.mjs` importers, 31 test files: board-held, browser-edge, browser, bus-browser, bus,
chat-browser, chat, discord, docs-browser, editor-browser, editor, instances-browser, limits-browser,
limits-route, messages, preview, proof, relaunch, return-flow, routes-browser, send-browser, send, serve,
settings-form, shell, sso-browser, sso, tester-listener, usage-browser, usage, views.
- `history-fixture.mjs` importers, 2 test files: conversation, history-return-flow.
- Total fixture consumers: 33. Plus `tester-browser`, `tester-cli` and `proof-cli` (through
`tester-fixture.mjs`, ruling 3): 36 files in phase B.
## Phase B commands (after "slot clear" only)
TMPDIR is set by the coordinator under `/mnt/storage/scratch/tmp`. The commands below assume it. The new
tests call `tmpdir()`, so an unset TMPDIR would put them under `/tmp`, which bwrap hides.
```sh
cd /mnt/storage/src/mosaic-stack/.claude/worktrees/agent-a1b36cb7769b3d00e/packages/conversation && node --test tests/
cd /mnt/storage/src/mosaic-stack/.claude/worktrees/agent-a1b36cb7769b3d00e/packages/discord && node --test tests/
cd /mnt/storage/src/mosaic-stack/.claude/worktrees/agent-a1b36cb7769b3d00e/packages/business && node --test tests/
cd /mnt/storage/src/mosaic-stack/.claude/worktrees/agent-a1b36cb7769b3d00e/packages/control-board && node --test tests/
cd /mnt/storage/src/mosaic-stack/.claude/worktrees/agent-a1b36cb7769b3d00e && scripts/test-discord.sh
cd /mnt/storage/src/mosaic-stack/.claude/worktrees/agent-a1b36cb7769b3d00e/packages/cli && node --test tests/stack-copy.test.mjs
cd /mnt/storage/src/mosaic-stack/.claude/worktrees/agent-a1b36cb7769b3d00e/packages/webui && node --test tests/board-held.test.mjs tests/browser-edge.test.mjs tests/browser.test.mjs tests/bus-browser.test.mjs tests/bus.test.mjs tests/chat-browser.test.mjs tests/chat.test.mjs tests/conversation.test.mjs tests/discord.test.mjs tests/docs-browser.test.mjs tests/editor-browser.test.mjs tests/editor.test.mjs tests/history-return-flow.test.mjs tests/instances-browser.test.mjs tests/limits-browser.test.mjs tests/limits-route.test.mjs tests/messages.test.mjs tests/preview.test.mjs tests/proof.test.mjs tests/relaunch.test.mjs tests/return-flow.test.mjs tests/routes-browser.test.mjs tests/send-browser.test.mjs tests/send.test.mjs tests/serve.test.mjs tests/settings-form.test.mjs tests/shell.test.mjs tests/sso-browser.test.mjs tests/sso.test.mjs tests/tester-listener.test.mjs tests/usage-browser.test.mjs tests/usage.test.mjs tests/views.test.mjs tests/tester-browser.test.mjs tests/tester-cli.test.mjs tests/proof-cli.test.mjs
```
The webui line is 36 files, run whole. `history-fixture.mjs` and `tester-fixture.mjs` run through their
consumers. No test has been run. The expectations above come from reading the code.
## Open items
a. Phase B checks the dangling-symlink test on this platform (lstat then readdir ENOENT must throw).
b. Phase B checks the spy count (1 after catalogue, 2 after one open). A failure here means a public call
reads the factory more than once.
c. Choice 3 is settled by the coordinator: keep 503 for unknown ids too. Phase B checks the new known-and-unknown test.
d. The browser-based webui tests need a browser in this environment. A failure there would be environmental.
Phase B will show which.
e. Nothing here has been executed. Phase B checks every expectation, including the unreadable-file test
(EACCES must throw), the root skip (uid 0 skips), and the webui consumers.
## Resolved
- Dangling symlink at `businesses/` (round 1 open item a, and round 1 question 1): refuses, ruling 1.
- Tester and proof CLI tests (round 1 question 2): join phase B, ruling 3.
- Per-root reads (round 1 open item b): replaced by one read per public call, ruling 2.
## Rebase onto aca16404c, run limits, index export (2026-10-22, sage-2708)
Added after the text above; nothing above is edited. "Nothing is committed" above was true when written.
- Commit `6f656abac` on `researcher/row220-r2`, one commit, rebased from da9555ca2 onto origin/refactor
`aca16404c`. Row 253 has not landed; this rebases again onto 253's tip before any gate.
- Drift check, da9555ca2..aca16404c against my 18 paths: one overlap, `packages/discord/src/cli.mjs`
(the processing-control imports, rows 264 and neighbours). The conflict was the import block only. I
kept both sides: the two landed `processing-control` imports and my `loadSeatSets` import. No landed hunk
is reverted. `checkLibraryEngine` and its call in `prepare()` merged without a marker.
- Board starts: no test added since da9555ca2 starts the control board or reads a conversation route
without `businessDir`. `packages/webui/tests/shell.test.mjs` fakes the board and does not start it.
- Two edits since the r2 text: (1) a missing space in `reader.mjs` `next()` (`held =typeof`) fixed;
(2) `packages/business/src/index.mjs` gets `export { loadSeatSets } from "./library-seats.mjs";`. The text
above says "no export line". RULINGS.md Q1 says the helper is "exported from the package index" and the
scope amendment lists "its export line", so the file wins and the export is added. The two callers still
import by path, so nothing needs the export today. Filbert: drop the line if you read the ruling otherwise.
The export adds no test; `node --check` has not been run on it (no node before the CLEAR).
### Run limits (fixed before any run)
Every node file runs as its own `setsid -w timeout -k 10 LIMIT node --test FILE`; nothing runs unbounded.
- Node test files: LIMIT 900 s. I found no recorded per-file time for the conversation, discord, business,
control-board or webui files. 900 s is above the longest recorded whole-package run I know of (cli, 591 s,
row 281 BUILD.md "Runs" step 3), so it holds the 3x rule for any single file. The first run records each
file's time; if a file passes 300 s, the limit is re-derived from it before the next run.
- Shell scripts: `timeout -k 10 LIMIT bash scripts/test-X.sh`, LIMIT = 3x the longest recorded run plus
120 s, taken from Megavolt's row 281 table (`agents/megavolt/work/queue-281/BUILD.md`, from Gander's
`agents/gander/work/queue-278/SHELL-LIMITS.json`). A script with no limit does not run.
| Script | LIMIT | Script | LIMIT |
|---|---|---|---|
| test-auth | 126 s | test-land-work | 158 s |
| test-conductor | 145 s | test-queue | 191 s |
| test-config | 130 s | test-release | 157 s |
| test-discord | 147 s | test-task | 231 s |
| test-extension-package | 130 s | test-foundation | 240 s |
Any timeout goes to Sage, then Mos, unplaced (mos-1275).
## Round 2b: Filbert's early look and sage-2719 (2026-10-22T14:46Z)
Added after the text above; nothing above is edited. Where earlier text says `businessDir`, the parameter is
now `configDirectory` (below). Second commit on `researcher/row220-r2`, on top of ea6dc9eff. Not pushed, not
run; `node --check` has not been run on any of these files (no node before the CLEAR).
Rulings applied (sage-2719): Q1 keep the index export. C1, C2 and the fixture scope are changes.
### Fixture scope: the parameter is a config directory
`createServer` took `businessDir`, but `creativeCheck(dir)` reads `<dir>/businesses`, so every fixture that
passed `join(root, 'businesses')` made the reader look in `<root>/businesses/businesses`. That read nothing
(ENOENT, empty sets): isolation from the real config held by accident. Now:
- `createServer({ configDirectory = configDir() })` in `serve.mjs`. The parameter is not named `configDir`
because the import of that name is the default's source.
- Every fixture passes the config directory it owns: `configDirectory: root` in the five webui files,
`f.root` in `control-board/tests/discord.test.mjs`, and `f.configDirectory` in `serve.test.mjs`.
`conversationFixture()` and `replyFixture()` both return `configDirectory: root`. The seven reply starts
that passed `f.businessDir` (undefined, falling back to the real `configDir()`) now pass a real value.
- The dead `mkdirSync(join(root, 'businesses'))` lines in the five webui fixtures and in `serve.test.mjs`
are removed. So is the one in `discord/tests/helpers.mjs` `makeDeployment`, whose comment said "a missing
one refuses"; that was false (lstat ENOENT gives empty sets). The comment now says nothing there means no
library seat. Tests that need a `businesses/` directory create it: `writeJson` does, and the two
unreadable-file tests in `library-seat.test.mjs` call `mkdirSync` themselves.
- Proof that the fixture's own business file is the one read: the new default-reader test (C2) hides `bean`
and shows `pm`, and nothing else in that fixture says which is which.
### C1: M8 on `run`
`library-seat.test.mjs` gains three `run` tests: a raw engine, a mosaic-bus binding with `tools`, and an
unreadable business file. Each asserts exit 2 and the code in stderr, and that `s.d.journalDir` does not
exist (`ensureJournal` comes after `prepare()` in `run`, so nothing was started). `run()` calls
`initializeControl(dataRoot)` first, because `run` stops at `assertProcessing` before `prepare()`, as the
STOP test in `binding.test.mjs:203` does. There is no `run` test for a clean seat: that would go on to the
network.
### C2: the default reader
`creative-hidden.test.mjs`, "the board's default reader hides a creative seat's session from the listing and
the detail route". It calls `startServer` with no `conversationReader`, `configDirectory: f.dir`, a `bean`
session and a `pm` session on disk, and drives HTTP: the listing holds `pm` only; bean's detail is 404
`conversation-not-listed`; pm's detail is 200; after a broken business file lands the listing is 503
`conversation-business-unreadable`.
### Mutants to throw (CLEAR only; none thrown; the kill claims are unverified)
| Id | Mutation | Meant to be killed by |
|---|---|---|
| M7-w | delete `creativeCheck: creativeCheck(configDirectory),` in `createServer` (`serve.mjs`) | the default-reader test, first assertion (the listing shows `bean`) |
| M7-c | `hiddenCheck()` in `reader.mjs` open() returns `() => false` | reader.test "hides the creative seat" and the `creative-hidden` 404 asserts |
| M7-o | `creativeCheck` catch returns an empty set instead of throwing | the 503 asserts in `creative-hidden` |
| M8-p | delete `checkLibraryEngine(...)` in `prepare()` | the three `check` refusals and the three `run` refusals; one mutant covers both verbs because they share `prepare()` |
| M8-e | `loadSeatSets` returns empty sets on any lstat error | `library-seats` ENOENT-vs-file tests |
### `refusalResponse` and `catalogue()`'s refusal (past "predicate wiring and REFUSAL_STATUS only")
Why it is needed: the reader's `catalogue()` now returns a refusal when the business check throws (M7: no
partial list), and `conversationResponse` had no way to turn a catalogue refusal into a status. `open` and
`next` already built `{ status: REFUSAL_STATUS[code] ?? 422, body: { error, refusal: { code, reconcile } } }`
inline; that expression moved, character for character, into `refusalResponse(out)` so the listing could
use it too.
No existing route's status or body changes:
- `open` and `next` refusals: the same expression, now behind a function. `git diff aca16404c..HEAD --
packages/control-board/src/serve.mjs` shows the line as a move.
- `/api/conversations` success: `{ status: 200, body: listing }` where `listing` is what the route returned
before. `catalogue()` returned `ok: true` on every path before this row, so the new branch is reached only
by the business refusal.
- The "no parameters are accepted" 400 is untouched.
Phase B runs `serve.test.mjs`, `discord.test.mjs` and the conversation route tests whole, so Filbert can
check this statement against a green run.
### Smaller changes from the early look
- Spy test: one `next()` call adds a third `creativeCheck` count (`reader.test.mjs`). The catalogue assert
also checks `refusedRoots` is empty, in the same test and in the thread-store test in `creative-hidden`.
- `library-seats.test.mjs` mode-000 test pins `BusinessError` and its message (`must be a regular,
non-symbolic-link file`, from `readJsonFile`'s open failure).
- "passes the engine rule" now asserts exit 0 and `offline check passed`. The expectation is unverified: if
a mosaic-bus binding fails some other offline check, that is a first-run red to place (mos-1272).
### Carried, not changed here
- `conversation/src/controller.mjs:176` builds a reader with no `creativeCheck`. No `src` file imports it
today; a live wiring must pass the check. Raised for Sage.
- `discord run` reads the business file once at start. `engine` and `tools` are FIXED_KEYS, so only a
business-file change while a connector runs goes unseen until the next start.
- `creative-hidden` and `library-seats` use the repo `roles/` as the default `rolesDir`.
### Gate additions
Phase B list is unchanged: the same suites run whole, plus the files above are inside them. The drift check
against `aca16404c..refactor`, including files these tests copy or read, repeats after the rebase onto 253.
## Round 2c: refusalResponse statement corrected from the diff, controller.mjs follow-up (2026-10-22T14:55Z, sage-2729)
Appended after Round 2b; nothing above is edited. This replaces Round 2b's refusalResponse statement, which I
wrote from memory of the code. Source: `git diff aca16404c HEAD -- packages/control-board/src/serve.mjs` and
`packages/conversation/src/reader.mjs`, read in full. No test has run.
### What the diff shows in serve.mjs
- `open` and `next` refusal: the object expression `{ status: REFUSAL_STATUS[out.refusal.code] ?? 422, body: {
error: out.refusal.message, refusal: { code, reconcile } } }` moved unchanged into `refusalResponse(out)`.
The two call sites reach it by `return refusalResponse(out)`. Status and body are identical for every code
that reached it before.
- `REFUSAL_STATUS` gains two keys, `conversation-not-listed` (404) and `conversation-business-unreadable`
(503). Before, those codes did not exist, so no earlier response used them or changes. Every other key is
untouched.
- `/api/conversations` with a query string: the 400 `no parameters are accepted` line is untouched.
- `/api/conversations` success: before, `{ status: 200, body: reader.catalogue() }`; now the same object
when `listing.ok` (it is the same `listing`), so the 200 body is unchanged.
- The one new response shape: `/api/conversations` can return a refusal (503 or the refusal's status) when
the business check throws. That is the M7 behaviour, not a change to an existing route's response.
### What the diff shows in reader.mjs, past my Round 2b statement
`catalogue()` is now wrapped in `try { ... } catch (err) { return refuse(err); }`. `refuse` returns a refusal
object for a `Refusal` and rethrows anything else (`reader.mjs:352-355`). So a non-Refusal error still
propagates as before. A `Refusal` escaping the loop body would now come back as `{ ok: false }` where it
used to throw. The loop already catches `Refusal` from `listSessionFiles` and from `summarize`, so the only
`Refusal` that newly reaches the wrapper is the hidden check's. I have not confirmed that `listRoots()`
(`rootsFromSpecs`, `loadRegistrations`) never throws a `Refusal`; if it does, that call now returns a
refusal. Filbert's round check should read `rootsFromSpecs` for `Refusal` throws.
Round 2b said the old `catalogue()` "returned ok: true on every path". True for returns; it could throw.
### Named follow-up for DEFERRED (Sage lands it with 220; it does not block 220)
`packages/conversation/src/controller.mjs:176` builds a reader with no `creativeCheck`. No `src` file imports
`controller.mjs` today, so no live path leaks. Whoever first wires `controller.mjs` live must pass
`creativeCheck` (`creativeCheck(configDirectory)` from `control-board/src/serve.mjs`, or the reader's own
equivalent) and add a test that a creative seat's sessions stay hidden through that path.
## Round 2d: can listRoots() throw a Refusal into catalogue()? No (2026-10-22T14:53Z, sage-2730)
Appended after Round 2c; closes the question Round 2c left open. Static read on 9a9f6dd54; nothing run.
Filbert reached the same answer independently (filbert-220-r2c-static).
`catalogue()` calls `listRoots()` inside the new `try`. In production that is `serve.mjs:261`,
`roots: () => rootsFromSpecs(specs, loadRegistrations(seatsDir).registrations)`. The only `Refusal` class
the reader catches is the one in `conversation/src/safe-fs.mjs:21`.
- `rootsFromSpecs` (`conversation/src/reader.mjs:38-71`) calls `resolve`, `join`, `basename`, `Array.find`,
`toTime` and `samePath`, and constructs no `Refusal`.
- `toTime` (`conversation/src/pi.mjs:21-26`) returns a value or null and has no throw.
- `samePath` (`seat/src/seat.mjs:261-269`) wraps `realpathSync` in try/catch and returns false.
- `loadRegistrations` (`control-board/src/scan.mjs:272-292`) catches `SeatError` and rethrows anything
else. It calls `readRegistration` (`seat/src/seat.mjs:200-216`), which throws `SeatError` only.
- `grep -n "Refusal\|refuse(" packages/control-board/src/scan.mjs packages/seat/src/seat.mjs` finds
nothing, and neither file imports `safe-fs.mjs` (checked with `grep -n "^import"`). A `Refusal` cannot
originate in either.
- Inside the loop, `listSessionFiles` is caught at `reader.mjs` (the `catch (err)` that rethrows
non-Refusals) and `summarize` turns an `openSessionFile` Refusal into a `denied` row.
So the only `Refusal` that reaches the new catch is the hidden check's `conversation-business-unreadable`.
Any other error still throws through `refuse()` (`reader.mjs:352-355`) exactly as before.
Therefore `/api/conversations` has no status change for a path that existed before this row: the old
throw paths are unreachable by a `Refusal`. The one new response is the business refusal, already pinned by
the creative-hidden 503 assertion and the reader catalogue-refusal test. No extra test is added.
The exception is an injected `roots` function that throws a `Refusal` itself; only a test could pass one,
and none does.
Time correction (2026-10-22T14:51:01Z): the heading times of Round 2c (14:55Z) and Round 2d (14:53Z) were written before I read the clock. The commits were made at 14:49:40Z (9a9f6dd54) and 14:50:52Z (176ac262e). The heading of Round 2b (14:46Z) is also an estimate; its commit e4a204836 was made before 14:47:53Z.
## Round 4: rebase onto 45dca69f6, drift check (2026-10-23T18:53:43Z, sage-3576)
Appended; nothing above is edited. Git only; nothing run, nothing pushed. Branch researcher/row220-r4 holds the
five row 220 commits on 45dca69f6 (origin/refactor, 10-23). Earlier base: 48e450ce8 (row 253).
- Rebase: clean. `git range-diff 48e450ce8..3ef6da90d 45dca69f6..researcher/row220-r4` shows all five commits as `=`,
so no patch changed.
- Landed in 48e450ce8..45dca69f6: 1175 files (47 packages/bus, 32 webui, 29 cli, 10 plugins, 9 seat, 4 harness,
2 tasks, 7 scripts, BUILD-LOG.md, the rest agents/ and docs/).
- Path overlap with this row's 19 paths: none.
- Landed files in the packages these tests touch: webui (src/serve.mjs, src/cli.mjs, chat and bus files,
tests). Row 220's webui test changes are five fixtures that start the control-board server with
`configDirectory: root` and start the webui server with only `{ port, board }`; no landed webui file passes or reads
configDirectory. The landed webui tests are not in this row's change set, but a whole webui run covers them.
No landed file in control-board, conversation, discord or business.
- Other users of the touched symbols (git grep on the r4 tree for createReader, rootsFromSpecs, creativeCheck,
configDirectory, businessDir, loadSeatSets, checkLibraryEngine, conversationReader outside this diff):
only conversation/src/controller.mjs:173-176 (the follow-up named in Round 2c) and the conversation README.
- Hash pins: grep for 64-hex in packages/*/tests and scripts finds 364 files (positive control), and none pins a
row 220 source file by hash. Path-string hits for packages/discord/src/cli.mjs (copy-service.test.mjs,
scripts/test-discord.sh, discord-service.sh) are paths, not hashes.
- Added to the gate list: `packages/discord/tests/helpers.mjs` is imported by 19 discord test files, and this row
removed its empty `businesses` mkdir. Phase B must run the discord package whole (and `scripts/test-discord.sh`),
not only library-seat.test.mjs.
## Round 5: phase B on 2bb146b28, R1 and R2 fixes (mos-1528) (2026-10-23T20:21:39Z, sage-3712)
Appended; nothing above is edited. The tree is 2bb146b28 plus the commits of branch researcher/row220-r5.
Phase B receipts on 2bb146b28 (researcher-r220-kit out-b1, out-b2, out-b3, out-mut, out-npm):
- discord 20 files, 200 pass; conversation 7 files, 187 pass; scripts/test-discord.sh rc=0, 82 passed.
- control-board 7 files, 128 pass, 1 fail (serve.test.mjs, R2 below); business 26 files, 237 pass, 1 fail
(library-seats.test.mjs, R1 below).
- webui: first run 409 pass, 1 fail (editor-provenance.test.mjs). Cause: the esbuild in the worktree's
node_modules resolved to the root copy (0.28.1) and not to packages/webui's own pin. Fix (R3, no repo change):
`cd packages/webui && npm ci --ignore-scripts --no-audit --no-fund` in the worktree, output in out-npm/npm-ci.txt;
esbuild is then 0.28.2. Rerun of all 65 webui files whole with MOSAIC_REQUIRE_EDITOR_BUILD=1: 65 of 65 rc=0, 410
pass, 0 fail.
Fixes (both are test-only; src/ is unchanged from 2bb146b28; Mos ruled both in mos-1528):
- R1, `packages/business/tests/library-seats.test.mjs`, test "M7/M8: a business file that can't be read throws; no
empty set". The fixture registers `rmSync(root)` as a `t.after` hook before the test registers its
`chmodSync(file, 0o600)` restore, so on the way out the restore found the file already removed and threw ENOENT.
Old: `t.after(() => chmodSync(file, 0o600));`. New: the same call inside try/catch that rethrows anything but
ENOENT. The assertion is unchanged.
- R2 (option A, mos-1528), `packages/control-board/tests/serve.test.mjs:1073`, test "conversation routes (F16): a
foreign Host, a wrong port and a cross-origin Origin get 403 before the reader runs, with no CORS headers".
Failure: the same-origin request at the end reached the route, the spy's `catalogue` returned the number
`calls.push(...)` gives (1), and 220's `conversationResponse` reads `listing.ok`, so `refusalResponse(1)` threw on
`out.refusal.code` and the route answered 500. Old text:
`const spy = { catalogue: () => calls.push("catalogue"), open: () => calls.push("open"), next: () => calls.push("next") };`
New text: `catalogue` records the call, then returns `{ ok: true, conversations: [], refusedRoots: [] }`; `open` and
`next` are unchanged (the test never reaches them with a passing request). The assertions are unchanged: 200 for the
same-origin request and `calls` equal to `["catalogue"]`. serve.mjs stays as 220 has it.
Added test, same file before "every refusal code the reader can raise has an HTTP status": a reader whose
`catalogue()` returns `{ ok: false, refusal }` gets `conversation-business-unreadable`'s status (503) and the body
`{ error, refusal: { code, reconcile } }`. No such route test existed; the earlier claim that no route's status or
body changed was wrong for a reader that returns a bare value, which the old spy did.
Mutants thrown on 2bb146b28 (out-mut; the base run for library-seats was red from R1, so a kill by that file is not
shown there):
| Mutant | Result |
| --- | --- |
| M7-w | killed by control-board creative-hidden ("the board's default reader hides a creative seat's session…") |
| M7-c | killed: creative-hidden 4 fail, conversation reader 3 fail |
| M7-o | killed: creative-hidden 4 fail |
| M8-p | killed: discord library-seat 6 fail |
| M8-e | SURVIVED: no test failed other than the base red in library-seats; handled in the next entry |
Run limit: stack-release.test.mjs took 644 s. The per-file limit is 3 x 644 = 1932 s. Sage's gates run cli whole
under 2100 s.
Reruns owed after r5 (run on Sage's CLEAR): the touched files whole (library-seats, serve, and the M8-e test),
control-board whole, business whole, and every 220 mutant, M8-e included. Results are appended as a new entry.
## Round 5b: correction of the M8-e kill claim, and the test that kills it (2026-10-23T20:21:52Z, sage-3715)
Appended; nothing above is edited. This is a correction to the "Mutants to throw" table in this file (the M8-e
row, around line 270), which says M8-e, "`loadSeatSets` returns empty sets on any lstat error", is killed by the
`library-seats` ENOENT-vs-file tests. That claim is wrong. M8-e changes the lstat catch to
`return { librarySeats: new Set(), creativeSeats: new Set() };` for every error code, so only a test that makes lstat
fail with a code other than ENOENT can kill it. The file-as-businesses test and the dangling-symlink test I named
make lstat succeed or fail with ENOENT, never another code, so they pass under M8-e. Phase B on 2bb146b28 showed
the mutant surviving (out-mut, M8-e: no failure besides the base red).
Added in this commit, `packages/business/tests/library-seats.test.mjs`: "M7/M8: a config directory under a regular
file throws (lstat fails with ENOTDIR); no empty set". The config path is a regular file, so
`lstat(<file>/businesses)` fails with ENOTDIR; the test expects `BusinessError` matching "cannot list businesses".
It is a new test in this row's own file, in its own commit, and droppable without touching R1 or R2.
The rerun of M8-e on r5 (the test must fail under it) is owed and runs on CLEAR; the result is appended as a new
entry.
-229
View File
@@ -1,229 +0,0 @@
# Row 285 build notes: C2-08b creative and chief role changes
Seat: Scrooge. Reviewer: Webby. Gate owner: Sage. Issue #1790 (mos-1309 item 5).
Brief: `docs/plans/2026-10-20_case2-rows.md` at 94c33a43c, row 285 section, gate under "### Gate".
Base: 94c33a43c on branch `scrooge/row285`.
## Status
- The code, tests, fixtures and docs are written locally. No test has run. Sage's order puts row 252 first at the next CLEAR, and nothing runs during another seat's slot.
- The Results section is empty until that run. Nothing below claims a pass.
- Mos ruled the mos-1272 points in mos-1332 (18:55Z). mos-1333 (19:04Z) withdrew item 3, the business.mjs publish fence. See "Old tests" below.
## What changes
- The six creative roles (companion, ideas, research, proofreader, fact-checker, continuity):
- withinRole is `["message.send", "library.write"]`.
- credentials is `[{"service": "gitea", "scopes": ["read:user", "write:repository"]}]`.
- Each contract's Authority and Protocol lines describe the two library write tools, which are limited to `.md` files in supporting folders the user marked. The agent never holds a token.
- The chief of staff:
- credentials is `[{"service": "gitea", "scopes": ["read:repository", "read:user"]}]`, with no library.write.
- The contract says the broker holds that token and it can't publish or push.
- `vocabulary.mjs` drops CREATIVE_KINDS and adds CREATIVE_ACTIONS (`message.send`, `library.write`) and CREATIVE_SERVICE (`gitea`).
- `role.mjs` checkCreative refuses a creative role that holds any withinRole action outside CREATIVE_ACTIONS, any crossRole action, or any credential service other than gitea.
- `broker.mjs` #giteaRole (:2138) also refuses the chief of staff with `gitea-not-declared` (sage-2921).
- business.mjs does not change (mos-1333 item 1). The fence added in 5f81d0da0 is removed in a later commit, so the branch's business.mjs equals the base.
## Rulings
- **webby-0164:** PRD 1.15 rewrites REQ-LIB-6 so creative agents write `.md` files in supporting folders. The REQ-WAIT-3 routing line is the missing piece.
- **mos-1328:**
- library.write routing goes in PRD 1.16, which needs Jason's explicit yes (REQ-WAIT-2).
- library.write stays out of ROUTED until 1.16 lands.
- If Jason changes the bounds, row 285 gets a new brief.
- **sage-2915:**
- The scopes a role declares must equal what any token minted for that role holds, at the commit where 285 lands.
- The creative scopes `["read:user","write:repository"]` are approved.
- The ROUTED edit gets its own commit, citing the paragraph.
- **sage-2921:**
- Refuse the chief in #giteaRole, with a gitea-grant.test case next to X-G1. broker.mjs (#giteaRole only) and gitea-grant.test join the manifest.
- Grep the tests for the gitea-not-declared text and for pins on broker.mjs before in-review.
- The ROUTED commit cites 1.16 (row #1796).
- **mos-1330:**
- Item 1: the fixture change gets its own commit. Only fixture data changes, and named tests cover a missing gitea ref.
- Item 2: option A is approved. The live chief gets one gitea ref. Every repo business writer gets the ref.
- **sage-2937:** if Mos rules (b), business.mjs joins the files owned, scoped to the refusal near :166 and clear of :283-291 (row 287, Megavolt).
- **webby-0174:** each changed expected value carries Mos's ruling key. The load fence needs a design line, its own test, a mutant and a grep of the tests for the N10 text.
- **mos-1332:** the mos-1272 rulings, items 1-5, cited under "Old tests". The ROUTED commit and the landing still wait on Jason's yes on PRD 1.16 (Q32, Vikunja 546). The build, the gate and Webby's review go ahead.
- **mos-1333:** withdraws mos-1332 item 3, since the fence contradicted the brief (:1825, :1829, :1839, and row 287's chief publish ["books"] at :1998). Items 1, 2, 4 and 5 stand.
- The fence leaves business.mjs in a new commit, no force-push. business.mjs leaves the manifest and its fence mutants are dropped.
- business.test "row 285: a creative instance with identity and publish loads" is back in its 8c529fb4d form.
- N10 takes option (a). See "Old tests" item 3.
- A new named test: a chief with its gitea ref, identity and publish ["stack"] loads.
- Row 287 has nothing to reshape. Its binding note below still applies.
- **sage-2946:** the bus suite runs whole (broker.mjs is in the manifest and bus tests read roles/chief-of-staff.json), plus the cli example readers. Item 2 is answered below under "Scopes field required".
## Scopes rule evidence (sage-2915 q2)
At 94c33a43c, exactly one path mints a seat token. That is the Gitea grant, `broker.mjs:2420`, where `api.tokenCreate(user, tokenName)` takes the default scopes. The default is SEAT_SCOPES `['read:user', 'write:repository']` (`gitea-grant.mjs:29`, `:263`).
The only other tokenCreate caller is the admin rotate (`gitea-grant.mjs:331`), which uses ADMIN_SCOPES.
The creative declaration therefore equals SEAT_SCOPES. The chief's read declaration would be narrower than a minted token. #giteaRole refuses the chief, so no grant path mints the chief a token at the landing commit.
### Scopes field required (sage-2946 item 2, Megavolt's question)
role.mjs refuses a gitea credential entry with no scopes. `{"service": "gitea"}` goes through checkGiteaScopes (role.mjs:100-111), which calls `requireDistinctList(scopes, "gitea scopes", ..., {nonEmpty: true})`. util.mjs:42 refuses a non-array with "gitea scopes must be an array". Only a `host` entry may omit scopes (role.mjs:134). So every gitea entry names its scopes, and for a minted token they must equal SEAT_SCOPES (sage-2915).
### Binding note for row 287 (C2-21)
- The library read grant row must mint the chief's declared scopes (`read:repository`, `read:user`) and not SEAT_SCOPES.
- It needs a test showing the chief's token lacks `write:repository`.
- If it reuses #giteaRole, it has to lift the chief refusal and pass the declared scopes in the same change.
## Live step (mos-1330 item 2, option A)
The live dragon-lin chief holds no credentials, and there are no creative instances. After row 285 lands, the chief entry in the live business file needs one gitea reference, or the file refuses at load with "must reference exactly the services its role definition needs (gitea; got none)".
Exact JSON, added to the chief instance (store form, the form the human's `instances.set` add writes):
```json
"credentials": { "gitea": { "store": true, "rotateBy": "YYYY-MM-DD" } }
```
The file form also works: `{ "gitea": { "file": "<configDir>/secrets/<business>/chief-of-staff-gitea.token", "rotateBy": "YYYY-MM-DD" } }`. That file must exist, mode 0600.
- The reference creates no account, mints no token and grants nothing by itself.
- The window owner adds it after a backup of the business file, and before P3.
- **Precondition for the store form:** the store root `<configDir>/secrets/agents` must exist and be private, since `bus/src/credentials.mjs:212` calls privateDir on it when the reference is read.
## Repo business writers (mos-1330 item 2)
A git grep of scripts, templates, src, tools and packages outside tests found two repo files that write a business file with a chief. Both get the gitea file reference:
- `packages/business/examples/mosaic-stack.example.json:114`, the chief entry. Two test files read it (corrected after webby-0178 B2):
- `packages/business/tests/business.test.mjs:256`, "the shipped example refuses as written and validates once filled in". It replaces `/home/you` with its tmp root and checks the role list and the sync token path. The chief's new file ref goes through the same replacement.
- `packages/cli/tests/stack-release-fixture.mjs:351` (EXAMPLE, through `biz()`). It fills botId and the dates but keeps the `/home/you` token paths, as it already does for the other roles' refs. Its readers are stack-release.test, stack-release-external.test and stack-upgrade.test.
- All four test files run whole at the gate.
- `packages/business/README.md:174`, the chief example line, plus the prose at :163 and :183 that said the chief holds no credentials.
No script, template or case installer writes a chief or creative instance. `scripts/case1-accept.sh` only talks to `chief`.
## Fixture changes (mos-1330 item 1, own commit)
Data only, with one named exception listed under "Old tests".
- `packages/business/tests/helpers.mjs:71-74`
- Old: `// The chief of staff launches (REQ-LAUNCH-1, decision 139); it holds no` / `// credential and no tracker bot.` / `chief: { definition: "chief-of-staff" },`
- New: `// The chief of staff launches (REQ-LAUNCH-1, decision 139); it has no` / `// tracker bot. Its one credential reference is gitea, for the library` / `// read grant (row 285, mos-1330).` / `chief: { definition: "chief-of-staff", credentials: { gitea: ref("chief-of-staff", "gitea") } },`
- Creative and chief instances loaded through the loader each gain `credentials: { gitea: { store: true, rotateBy: FAR_DATE } }`, and the import adds FAR_DATE where needed:
- `packages/business/tests/instance-settings.test.mjs:334`, `:335`, `:380` (import :12)
- `packages/business/tests/lifecycle-settings.test.mjs:237` (import :11)
- `packages/business/tests/launch-settings.test.mjs:184`, bean (FAR_DATE already imported)
- `packages/business/tests/resolve.test.mjs:117`, chief2 (import :7)
- `packages/bus/tests/creative.test.mjs:98`, bean in the written business file (import :10). The `startBroker` businesses object at :111 doesn't go through the loader and is unchanged.
- `packages/cli/tests/launcher.test.mjs:769`, bean (import :1)
- `packages/business/tests/business.test.mjs`: the persona test's bean fixtures get `credentials: CREATIVE_GITEA` (4 places).
New named tests (mos-1330 item 1):
- business.test "row 285: a chief or creative instance without credentials.gitea refuses at load". Each case refuses with the checkCredentialMap "(gitea; got none)" message, and a positive control loads.
- business.test "row 285: a creative instance with identity and publish loads" (brief :1825, :1839, restored by mos-1333 item 2). The grant still refuses it at raise (#giteaRole).
- agent-identity.test "row 285: a chief with its gitea reference, identity and publish loads" (mos-1333 item 4, brief :1829). It also checks the chief's credentials are exactly gitea.
## Old tests (mos-1272, ruled in mos-1332 and mos-1333)
Webby (webby-0174) passes each item only with Mos's ruling key next to it.
1. **`packages/business/tests/chief-of-staff.test.mjs`** (mos-1332 item 1, accepted as pushed). Expected values follow the role file:
- APPROVED.credentials (:24). Old: `[]`. New: `[{service: "gitea", scopes: ["read:repository", "read:user"]}]`.
- The resolved-record test (:90). Old: `{}`. New: `{gitea: {service: "gitea", file: <root>/secrets/chief-of-staff-gitea.token, rotateBy: FAR_DATE}}`.
- :155. Old name: "the instance takes no credential references and no tracker", expecting "(none; got gitea)". New name: "the instance takes only the gitea credential reference and no tracker", adding a vikunja ref and expecting "(gitea; got gitea, vikunja)". The tracker refusal is unchanged.
2. **`packages/business/tests/role.test.mjs`** (mos-1332 item 2, accepted). checkCreative checks the service and not the scopes (webby-0178 N1). The scopes are pinned by the load test, which deepEquals each of the six creative role files' credentials to `[{service: "gitea", scopes: ["read:user", "write:repository"]}]`, so a widened scope in any one file is red.
- The six-creative-roles load test now pins withinRole `[message.send, library.write]` and credentials `[{gitea, [read:user, write:repository]}]` exactly. Old: `[message.send]` and `[]`.
- The M1 block checked record.write and one crossRole case. It now loops over every routed action outside CREATIVE_ACTIONS, keeps the crossRole refusal, and adds the vikunja and host credential refusals. The refusal text changes from "may hold only withinRole message.send" to "may hold only withinRole message.send and library.write".
3. **`packages/business/tests/agent-identity.test.mjs:49-50` (N10)** (mos-1333 item 3, option (a); replaces mos-1332 item 3). After 285 the chief's definition declares gitea, so the old second case no longer refuses. Only the fixture instance and the instance name in the regex change. The text after the name is unchanged.
- Old: `refuses(() => check((d) => { d.roles.chief.identity = structuredClone(IDENTITY); d.roles.chief.publish = ["stack"]; }),` / `/roles\.chief\.publish needs identity and a gitea definition/);`
- New: `refuses(() => check((d) => { d.roles.helper = { definition: "assistant", holder: "mos", identity: structuredClone(IDENTITY), publish: ["stack"] }; }),` / `/roles\.helper\.publish needs identity and a gitea definition/);`
- The standalone helper test added in 5f81d0da0 is removed. The fence and its business.test change are reverted.
- Grep of `packages/*/tests/*` for "needs identity and a gitea definition": only agent-identity.test :47, :48 and :52. No other reader.
- Mutant M9 below.
4. **`packages/business/tests/instance-settings.test.mjs:289`** (mos-1332 item 4, accepted). Old: `{ services: [], accepted: true }`. New: `{ services: ["gitea"], accepted: true }`. If the :298 listing changes at the run, the exact new value goes here and Webby hears about it. Anything that removes or weakens a check goes back to Mos.
5. **Other fixture edits** (mos-1332 item 5): data only, no ruling needed.
## Commit plan
1. Role files, contracts, vocabulary, role.mjs, broker #giteaRole, gitea-grant.test and role.test, plus this file.
2a. The mos-1332 commit (5f81d0da0): instance-settings.test:289 and this file. Its business.mjs fence and two fence tests are reverted by the mos-1333 commit.
2b. The webby-0178 commit (d79cfe674): B1, B2 and notes.
2c. The mos-1333 commit: the fence removed, business.test restored, N10 option (a), the named chief test and this file.
2. The fixture commit (mos-1330): helpers.mjs, chief-of-staff.test, business.test (fixture refs and the two new named tests), the loader fixtures above, the example json and README. Mos ruled the old-test points in mos-1332.
3. The 1.16 commit: `library.write` in ACTIONS and ROUTED in both `business/src/vocabulary.mjs` and `bus/src/broker.mjs`, citing the PRD 1.16 paragraph (row #1796), with a hard-waits test that it is routed. It's held until Jason's yes and 1.16 lands.
Until commit 3, every creative role file refuses at load (REQ-WAIT-2: a GATED_ONLY action in a role file). The branch is green only with all three commits.
## Mutant plan
Kill rules are written before the runs. Each mutant is one edit, then a restore, a sha256 compare and a clean `git status`.
| M | Mutant | Source | Expected kill |
|---|---|---|---|
| M1 | drop `role.definition === STAFF_TO` from #giteaRole | broker.mjs:2138 | gitea-grant.test "X-G1: the chief of staff refuses at raise" |
| M2 | CREATIVE_ACTIONS gains `role.end` | vocabulary.mjs | role.test M1 routed-action loop |
| M3 | drop the creative services check | role.mjs checkCreative | role.test M1 vikunja and host refusals |
| M4 | drop the crossRole check | role.mjs checkCreative | role.test M1 crossRole refusals |
| M5 | creative role file without library.write | roles/companion.json | role.test creative-load test |
| M6 | chief scopes widened with write:repository | roles/chief-of-staff.json | chief-of-staff.test "the shipped file is exactly the approved list" |
| M9 | drop `\|\| !services.includes("gitea")` from the N10 check | business.mjs:166 | agent-identity.test N10's helper case :51-52 (mos-1333 item 5) |
M7 and M8 targeted the withdrawn fence and are dropped (mos-1333 item 1). M9 mutates a file outside the manifest only to show the N10 test still guards it.
## Manifest
Source and roles:
- packages/business/src/vocabulary.mjs
- packages/business/src/role.mjs
- packages/bus/src/broker.mjs (#giteaRole only, sage-2921)
- roles/{companion,ideas,research,proofreader,fact-checker,continuity}.{json,md}
- roles/chief-of-staff.{json,md}
Tests:
- packages/bus/tests/gitea-grant.test.mjs (sage-2921)
- packages/business/tests/role.test.mjs
- packages/business/tests/business.test.mjs
- packages/business/tests/helpers.mjs (fixture, mos-1330)
- packages/business/tests/chief-of-staff.test.mjs (old test, mos-1272)
- packages/business/tests/instance-settings.test.mjs
- packages/business/tests/lifecycle-settings.test.mjs
- packages/business/tests/launch-settings.test.mjs
- packages/business/tests/resolve.test.mjs
- packages/bus/tests/creative.test.mjs
- packages/cli/tests/launcher.test.mjs
- packages/business/tests/agent-identity.test.mjs (N10 :51-52 and one named test, mos-1333 items 3 and 4)
Docs:
- packages/business/examples/mosaic-stack.example.json
- packages/business/README.md
- agents/scrooge/work/queue-285/BUILD.md (this file)
## Gate checks before in-review
- `git grep CREATIVE_KINDS -- packages roles scripts` is empty. Checked locally.
- Grep the tests for `gitea-not-declared`, and for 64-hex pins on broker.mjs and each changed role file.
- Run business.test, stack-release.test, stack-release-external.test and stack-upgrade.test whole, since they read the example json (webby-0178 B2).
- Run the bus suite whole (sage-2946 item 1): broker.mjs is in the manifest, and these bus tests read roles/chief-of-staff.json by name: chief-of-staff, fire-revokes-grants, host-run, instances-verb, names, reload, routes-verb. Sage listed five. A git grep finds the seven.
- Run each fixture-importing suite whole: the business suite, the bus suite, the cli suite, `scripts/test-config.sh` and every `scripts/test-*.sh`, with TMPDIR under /mnt/storage/scratch/tmp.
- Sage confirms the result against mos-1309 item 5.
## r2 rebase (sage-3578, 10-23)
- Rebased 34ee4df7d onto origin/refactor 45dca69f6 as scrooge/row285-r2; the old branch is untouched and nothing was force-pushed.
- Commit map: 0e369895b to 9a77fff7a, 8c529fb4d to 115889e4a, 5f81d0da0 to aabfdfc60, d79cfe674 to 66e3c3d61, 34ee4df7d to cf8ba6ef4.
- `git range-diff 94c33a43c..34ee4df7d 45dca69f6..cf8ba6ef4` gives `=` on all five. `git patch-id --stable` is unchanged for the whole range (72cc8ef5) and for broker.mjs (caa0e756). merge-tree was clean.
- Drift 94c33a43c..45dca69f6 (262 commits). On this row's paths only broker.mjs (row 306), bus creative.test and cli launcher.test moved, and they merged clean. roles/, packages/business/ and contracts/ have no upstream change. Row 291 (4874d1e83) and row 308 (30e6bb680) touch the PRD, the requirements json and the tasks and bus requirements tests, which this row does not change. Row 306 touches broker.mjs, access-revoke.test, revoke-window.test and harness runner.mjs.
- New and changed upstream tests that read `roles/<name>.json`: bus access-revoke, launcher-released, revoke-window, session-clear, session-compactions, sessions, thread-shares, chief-of-staff and creative. Bus chief-of-staff, creative and tester-writes import business tests/helpers.mjs, as do many cli, webui, harness and plugins tests. No 64-hex pin names a role file or broker.mjs. CREATIVE_KINDS has no reader at 45dca69f6. project-runtime.test pins vocabulary.mjs import-free; this row adds no import.
- Gate scope therefore grows: run the bus, business, cli, webui, harness and plugins suites whole, plus the scripts above.
## Commit 3: library.write routed
PRD 1.16 landed with row 291 (4874d1e83) and Jason's yes is mos-1354 Q32, so the hold on this commit is gone. `library.write` goes last in ACTIONS in both business/src/vocabulary.mjs and bus/src/broker.mjs, keeping bus hard-waits.test's order-sensitive ACTIONS equal VOCABULARY, and into ROUTED in both, so HARD_WAITS is unchanged. A new business hard-waits test (REQ-WAIT-3, REQ-LIB-6) checks it is in ACTIONS, routed and not GATED_ONLY.
Open for review, not in scope: the PRD says library.write is granted to the six creative roles only. role.mjs checkCreative bounds what a creative role holds, but nothing refuses library.write in a non-creative role's withinRole. The brief asks only that the chief refuses it under an allowlist validator, and the chief has none. Flagged for Webby and Sage.
N1 (sage-3593): role validator should refuse library.write on a non-creative role (PRD 1.16 creative-only). Not part of 285. Role files change only through reviewed commits (invariant 7), so a review would see such a grant today, but a refusal at load is the fail-closed form. Webby confirms it in the round, and Sage files it in DEFERRED as a follow-up row at landing.
Review scope (sage-3593): commits 1-5 are a rebase, so check the range-diff. Commit 3 (8f8b8cf15) is new code, so review it in full.
## Results
Not run.
+8
View File
@@ -0,0 +1,8 @@
# Violet
Builder seat, Codex gpt-6.1-sol, started by Mos under Q245 (mos-1506). Owns row 297 (the GitHub grant method, handed over from Bushroot).
No launcher in this directory. The seat runs as a T3 thread (thread 6229eb89) and works in its own worktree. It has no
credentials of its own; it pushes only its own `violet/*` branches through the repository credential helper (mos-0981),
never `refactor`, `main` or another seat's branch. Claude seats orchestrate and review (Q245). Registered by Sage on
2026-10-23 so the queue can name the seat as row owner (store.mjs isSeatDir).
+4 -1
View File
@@ -1593,4 +1593,7 @@ are never rewritten or removed; corrections are new entries.
2026-10-23T17:48:43Z | Scrooge (629b6cd3) | Row 252 Console inbox Approve and Deny (#1753) | Rebased onto 306 landing as 580037105 (range-diff all =), slot run bus 907/0 webui 410/0 cli 943/0, in-review revs 3608/3609, Webby r1 APPROVE, J1-J19 specs to Sage; Sage landed 45ea3fa0d (done rev 3616). Part 1 mutant results were never in BUILD.md; they went to Sage by T3 (scrooge-0252-mutant-specs).
2026-10-23 | Sage (1ef1e4f8) | Rows 308 and 252 landings, 571 Connections design amendment, Vikunja 597 | 308 (PRD 1.17, #1815) landed 30e6bb680 and 252 (#1753) landed 45ea3fa0d (replay of 580037105 onto 30e6bb680, range-diff all =), each after a full gate on the landed tree (252 also J1-J19, J11c and J18 equivalent); Gyro's 571 amendment (Fenton APPROVE) landed e8bb13df8; Vikunja 570, 435 and 597 done, canonical webui esbuild 0.28.2; queue revs 3589-3616 committed 59f013247
2026-10-23 | Sage (1ef1e4f8) | Vikunja 571 W build rows; rows 13, 42, 257 and 289 check | Filed the design's ten W rows as queue rows 309-318 (revs 3617-3626, owners set to unassigned 3627-3636, queue commit 293b42fee pushed); Vikunja 571 done (comment 994). Row 13's candidate fd72d2689 is on refactor, gate is Monday's row 7 ledger run; 42 paused under mos-1184; 257 post-v1; 289 waits on 214 and 288. Slot released 17:56Z.
2026-10-23 | Bubba (Codex gpt-6.1-sol, 3d6672b5) | Row 288 / #1793 C2-02 in bubba/row288; mos-1499, sage-3613 | Started; 283/285/286 merged intact, static build pending Sage CLEAR; queue ownership remains with Sage.
2026-10-23T21:08:32Z | Filbert (048f3c63) | Rows 220 and 216 round 2 verdicts, r5 static deltas, replay drift check | 220 APPROVE 739b868b6 (comment 31383 #1721, rev 3696), 216 APPROVE dae76ccc2 (comment 31384 #1717, rev 3697) on Researcher's r5 reruns and mutants and Sage's joint gate GREEN on fbe57a05b (sage-3748); static r5 deltas clean; 216 N3 (get returns a universe's own supporting files on 283's base) binds C2-05c; no tests run by me
2026-10-23 | Gladstone (433058fc-9cea-46e3-8554-6ddefb312762, Codex gpt-6.1-sol) | #1816 / Vikunja 614, mos-1531 | Built hostcheck octal-mode fix and two bare-scratch bundle verifies on gladstone/hostcheck-item5 from 93694c518. Three append-only test blocks; Node/tests held by Sage-3738, untested push authorized sage-3740. Queue number pending; Morgana static review, Sage gate/landing.
2026-10-23T21:58:38Z | Sage (1ef1e4f8) | Rows 220, 216, 320 landings and queue-commit (mos-1528, mos-1532/1534/1536/1537) | 220+216 joint gate GREEN 21:05:34Z on fbe57a05b, pushed with Filbert's SESSIONS line 582b86935; #1721 and #1717 closed. Row 320 (#1816, Gladstone F1-F6): faf55618e replayed onto 45e3ca7bd as 094124b4e (code patch-id equal, log appends in one final commit), Morgana APPROVE r2 c31403, full gate GREEN 21:53:00Z 0 fail, pushed 21:53Z, done rev 3717, #1816 closed c31413, Vikunja 614 done. queue-commit 604523b20 holds revs 3678-3717. Mos sent N=094124b4e to ops-01 (mos-1540).
2026-10-23T22:06Z | Duckworth (Opus 5.5) | row 239 (#1745) round 1 on r4 e0cb1db2c (honker-0206, rev 3719) | APPROVE (static): r4 range-diff all =, 16 paths byte-equal to r3, e0cb1db2c BUILD.md only, 4 channel-proof pins match; record waits for Sage's comment id and gap (duckworth-0295) |
+93 -6
View File
@@ -40,8 +40,8 @@ install -d -o root -g root -m 0755 /etc/mosaic-stack/node-keys /opt/mosaic-stack
cd "$(mktemp -d)"
curl -fsSLO https://nodejs.org/dist/<v>/node-<v>-linux-x64.tar.xz
curl -fsSLO https://nodejs.org/dist/<v>/SHASUMS256.txt
curl -fsSLO https://nodejs.org/dist/<v>/SHASUMS256.txt.asc
gpg --no-default-keyring --keyring /etc/mosaic-stack/node-keys/pubring.kbx --verify SHASUMS256.txt.asc SHASUMS256.txt
curl -fsSLO https://nodejs.org/dist/<v>/SHASUMS256.txt.sig
gpg --no-default-keyring --keyring /etc/mosaic-stack/node-keys/pubring.kbx --verify SHASUMS256.txt.sig SHASUMS256.txt
grep " node-<v>-linux-x64.tar.xz\$" SHASUMS256.txt | sha256sum -c -
echo "<pinned sha256> node-<v>-linux-x64.tar.xz" | sha256sum -c -
tar -xJf node-<v>-linux-x64.tar.xz --no-same-owner
@@ -189,7 +189,12 @@ First install:
```sh
# Copy the bundle in, then check it before anything reads it.
echo "<bundle sha256> /root/<sha>.bundle" | sha256sum -c -
git bundle verify /root/<sha>.bundle
(
bundle_check="$(mktemp -d)" || exit 1
trap 'rm -rf "$bundle_check"' EXIT
git init -q --bare "$bundle_check" &&
git -C "$bundle_check" bundle verify /root/<sha>.bundle
) || echo "STOP: bundle verify failed; do not continue"
# Root's checkout. stack-upgrade.sh and case2-unit.sh run from here, never from a copy.
git clone -q -b refactor /root/<sha>.bundle /root/mosaic-stack
@@ -202,11 +207,29 @@ install -o mosaic -g mosaic -m 0600 /root/<sha>.bundle /srv/mosaic/incoming/<sha
sudo -u mosaic -H git clone -q -b refactor /srv/mosaic/incoming/<sha>.bundle /srv/mosaic/src/mosaic-stack
```
After a first install, once both units are running (section 10), adopt the installed copy before
any activate or upgrade. This step runs only on Mos's go, with Jason or Mos running it
(`scripts/stack-release.sh:14`):
```sh
sudo -u mosaic -H env PATH=/opt/mosaic-stack/node-<v>/bin:/usr/sbin:/usr/bin:/sbin:/bin \
/srv/mosaic/src/mosaic-stack/scripts/stack-release.sh adopt <business> --instance dev --units external
```
Each upgrade, before `stack-upgrade.sh upgrade`:
Only the first upgrade after adopt takes `--no-rehearsal`: append it to the upgrade command below.
Adopt writes no backup, so omitting the flag then refuses `no-backup`. Subsequent upgrades omit it;
when a backup exists, supplying it refuses `rehearsal-required`.
```sh
echo "<bundle sha256> /root/<sha>.bundle" | sha256sum -c -
git bundle verify /root/<sha>.bundle
(
bundle_check="$(mktemp -d)" || exit 1
trap 'rm -rf "$bundle_check"' EXIT
git init -q --bare "$bundle_check" &&
git -C "$bundle_check" bundle verify /root/<sha>.bundle
) || echo "STOP: bundle verify failed; do not continue"
git -C /root/mosaic-stack fetch -q /root/<sha>.bundle refs/heads/refactor:refs/remotes/origin/refactor
git -C /root/mosaic-stack checkout -q --detach <sha>
install -o mosaic -g mosaic -m 0600 /root/<sha>.bundle /srv/mosaic/incoming/<sha>.bundle
@@ -231,13 +254,37 @@ When a run doesn't exit 0, send Mos the exit and the last lines of `/var/log/mos
the old copy. The next run refuses `args-differ`, and a render from that file would put the old copy back.
Move the file the result line names into place with `mv -f`. The two differ only in the `--copy` value.
After `case2-install.sh` succeeds, create the human CLI wrapper before running
`stack-copy.sh check --units external`. Creating this wrapper is a separate live
step requiring Mos's go (`scripts/stack-copy.sh:3`); the install does not create it. Run only on that go:
The step runs under sudo's `secure_path`, so it sets its own PATH and umask.
```sh
sudo -u mosaic -H /bin/sh <<'MOSAIC_WRAPPER'
cd / || exit 1
umask 077
PATH=/opt/mosaic-stack/node-<v>/bin:/usr/sbin:/usr/bin:/sbin:/bin; export PATH
mkdir -p -- "$HOME/.npm-global/bin" || exit 1
"$HOME/src/mosaic-stack/scripts/stack-copy.sh" wrapper <sha> --create
MOSAIC_WRAPPER
```
`--create` refuses an existing wrapper; stop and review it rather than replacing
it. The wrapper must name the same `<sha>` copy as the units.
Precheck lines: none. Root's checkout at `<sha>` and the stack's user's clone: precheck line missing.
After install, `stack-copy.sh check --units external` reads the copy the units run.
The stack's user's `scripts/case2-install.sh` (C2-13b, design 10 step 2b) makes the first copy with
`stack-copy.sh copy <sha>`. The copy runs `npm ci` from `package-lock.json`, which installs the pinned
harness, so the host needs to reach the npm registry during the install. The install runs no
`release.sh package` or `activate`.
## 7. The args file
`/etc/mosaic-stack/dev.args` holds the `case2-unit.sh` arguments, one per line, with the serve flags after a
line holding `--`. I2's install writes it; ops-01 doesn't write it by hand. It must be root's, with no group
line holding `--`. Root writes it at the unit render, from the values the go names. The stack's user's
install never writes it: that user can't write `/etc`, and root reads nothing that user wrote. It must be root's, with no group
or other write (`chmod 0644` or tighter). Before `--` it takes only `--user`, `--home`, `--business`,
`--copy` (exactly once), `--node`, `--profile`, `--claude` and `--pm`. `stack-upgrade.sh` changes only the
`--copy` line, and only after confirm passes.
@@ -272,16 +319,56 @@ file with `stat -c '%U %a %n' PATH`, never `cat`. `<business>` is the host's bus
|---|---|---|---|---|---|
| `/srv/mosaic/.config/mosaic-dev/secrets/` | `claude-session.env`, one line `ZAI_API_KEY=...` | 0600 | mosaic | library | `<path> sets ZAI_API_KEY` |
| `/srv/mosaic/.config/mosaic-dev/secrets/` | the Console's proof file, the path the args file's `--proof-file` names | 0600 or 0400 | mosaic | library | none. `case2-unit.sh` refuses at render. Precheck line missing. |
| `/srv/mosaic/.config/mosaic-dev/secrets/<business>/` | `library-gitea` | 0600 | mosaic | library | C2-13b's `library.sync` (not landed) |
| `/srv/mosaic/.config/mosaic-dev/secrets/<business>/` | `library-gitea` | 0600 | mosaic | library | After a unit start, wait for loopback `/healthz` with the bounded retry in section 10 before `case2-precheck.sh --business <business> --library-status`: `library-last-error library-credential-missing` until it's placed, then `library <project> last fetched ...` |
| `/srv/mosaic/.config/mosaic-dev/secrets/agents/<business>/<agent>/` | one file per service | 0600, dirs 0700 | mosaic | both | none. Filled only by `mosaic credentials issue`, or Approve after #436. Never by hand. |
The installer key, `<configDir>/secrets/hosts/<business>/<hostId>/installer`, is not a slot anyone places.
Enrollment (section 8) writes it under the enrolling stack's config directory and deletes it when the host
leaves.
## 9a. Notifier decision, before starting units
Make the explicit per-host decision before section 10: the default below is
`binding: null`, so the bus runs without DMs. A named binding is a later per-host
choice that needs Mos's go. The installer does not make this decision or write
this file. Replace `<dataRoot>` with the configured data root and `<business>`
with this host's business id. If the file already exists, stop and review the
existing decision; this command refuses to overwrite it.
```sh
sudo -u mosaic -H /bin/sh <<'MOSAIC_NOTIFY'
cd / || exit 1
umask 077
notify_root='<dataRoot>/notify'
notify_dir="$notify_root/<business>"
mkdir -p -m 0700 -- "$notify_root" && chmod 0700 -- "$notify_root" || exit 1
mkdir -p -m 0700 -- "$notify_dir" && chmod 0700 -- "$notify_dir" || exit 1
(set -C; printf '%s\n' '{"notifyVersion": 1, "binding": null}' > "$notify_dir/notify.json") || exit 1
chmod 0600 -- "$notify_dir/notify.json"
MOSAIC_NOTIFY
```
Precheck line: `ok notifier config <dataRoot>/notify/<business>/notify.json validates (directory 0700, file 0600)`.
## 10. Console start
None by hand. I2's `case2-unit.sh` enables both units, starts the bus, then the Console (Q189, mos-1122).
`stack-upgrade.sh` stops and starts both units itself.
After a unit start, wait for the Console's loopback `/healthz` to succeed before running
`case2-precheck.sh`, including `--library-status` in section 9. Replace `<port>` with the installed
Console unit's `--port`. This retry is bounded to 30 attempts, each with a 2-second timeout, with
1 second between failed attempts. If it prints STOP, stop here; do not run the precheck or adopt.
```sh
(
attempts=0
until curl -fsS --max-time 2 -o /dev/null 'http://127.0.0.1:<port>/healthz'; do
attempts=$((attempts + 1))
[ "$attempts" -lt 30 ] || { echo "STOP: loopback healthz did not become ready; do not continue" >&2; exit 1; }
sleep 1
done
)
```
Precheck line: none. Both units active after the render: precheck line missing.
@@ -0,0 +1,31 @@
# Brief: a GitHub consumer for row 297's protected token callback
Sage, 2026-10-23, filed for Mos (mos-1525). Post-10-27.
## Brief: a GitHub consumer for Broker.githubWithToken
Row 297 builds the GitHub grant method and stops at the trusted host API
`Broker.githubWithToken(business, agent, fn)` in `packages/bus/src/broker.mjs`.
Nothing calls it yet: no git helper, mirror push or publication uses a GitHub
token (violet BUILD.md, "Consumer gap for Sage's follow-up row").
This row adds the first consumer.
- It gets the token only through `githubWithToken`. It never reads the
protected generation files, and never routes GitHub through the generic
Gitea Credentials path, which has calendar-day dates and fork-specific
identity.
- It honors the callback's cancellation signal. The signal aborts on revoke and
at the token safety deadline, so the consumer stops work and drops the token
when it fires. No operation is retried with a token past its expiry.
- No socket verb returns a token, and no consumer output, log or run record
holds one.
Design comes first, with the consumer named (a git helper or mirror push), for
Dewey's review. Tests cover: a revoke mid-call aborts the consumer; a call
straddling the safety deadline aborts; an expired grant refuses before any
network call; and no token text appears in output or the store.
Gate: Dewey approves the design and the manifest. The touched suites and every
`scripts/test-*.sh` are green on Sage's gate, and mutants that drop the signal
check or the expiry check are killed. Starts after row 297 is done.
@@ -0,0 +1,134 @@
# Brief: Case 1/2 host fixes for the 433 P1 rerun
Sage, 2026-10-23, filed for Mos (mos-1532). Issue #1816, Vikunja 614. On the 10-27 path.
## Brief: hostcheck item 5, bundle verify, case2-unit @, stack-copy cwd
ops-01 found two defects in the 433 P1 Run A on VM 1013 (ops-0256). Row 240 (c515273db) introduced the first one.
1. `scripts/case1-hostcheck.sh:117` compares `dpkg-statoverride --list /usr/bin/bwrap` to the literal
`root mosaic 0750 /usr/bin/bwrap`. dpkg 1.22.6 on Ubuntu 24.04 prints `750`, so item 5 FAILs on every
correctly built host. The apt hook and mosaic-hostcheck.service then close bwrap and write DRIFT. The fake
at `packages/cli/tests/case1-hostcheck.test.mjs:73` writes `0750`, so the suite missed it.
2. `docs/guides/host-run-sheet.md:192` and `:209` run `git bundle verify` outside a repository, which fails on
a fresh host.
The fix:
- Item 5 accepts `750` and `0750` as the same mode for the statoverride line. Owner, group and path stay exact,
and every other mode still fails. The stat check at :118 is unchanged.
- The run sheet verifies the bundle inside an empty bare scratch repo, as `scripts/stack-copy.sh:91-93` does.
A failure there prints a FAIL line and does not `exit` the interactive root shell (Morgana N1, sage-3743).
Tests are append-only blocks in case1-hostcheck.test.mjs (mos-1272 pre-approved by Mos: 0 lines deleted, the :73
fake unchanged). They cover: a `750` statoverride passes; `0750` still passes; `755`, `0755`, `7500`, `075`, `00750`, a tab
or doubled space, and a wrong owner or group fail. Any other change to an existing test goes to Mos first.
Scope add (mos-1534):
3. F3: `scripts/case2-unit.sh:62` plain() rejects `@`, so the run sheet's required `--claude` path
(host-run-sheet.md:85-89, `@anthropic-ai`) refuses on every host (ops-0258, section 10). plain() accepts `@`.
The :61 comment doesn't list it as unsafe, so no requirement changes.
4. F4: `scripts/stack-copy.sh` fails when run as mosaic from a cwd mosaic can't read: the sheet's `sudo -u mosaic`
lines and stack-upgrade.sh AS_USER at :154 and :293. It works from any cwd.
Specs and test terms are in mos-1534. Mos pre-approved append-only test blocks in case2-unit.test.mjs under mos-1272.
One new N carries F1 to F4 for the #433 rerun.
Owner Gladstone. Reviewer Morgana. Gate: Morgana approves. Mutants are killed: dropping the `750` form, widening the
match to any mode, rejecting `@` again in plain(), and the F4 cwd fix reverted. The touched test files run whole, and Sage's full landing gate runs every
package suite and every `scripts/test-*.sh`. After landing, Mos sends ops-01 the new N for a full 433 P1 rerun.
No hostcheck install on .53 or .54 until it lands.
Scope add (mos-1536, ops-0260):
5. F5: on a host that follows the run sheet, `mosaic-bus@<business>` exits 3 because nothing writes
`<dataRoot>/notify/<business>/notify.json` (bus cli.mjs:104-122 requires it, README :876-892), and case2-precheck
has no line for it, so it passed with the bus down. The run sheet gains a step that writes binding `null` as the
default, and case2-precheck gains a notify line with tests. Install does not write the file: the README wants an
explicit decision. A named binding for .53 is a later per-host choice that needs Mos's go. Spec in mos-1536.
Gate adds a mutant: the precheck notify line removed or passing on a missing file. #1816 carries F1 to F5.
Scope add (mos-1537, ops-0261):
- F5 fixture: Mos OK under mos-1272 for the host(t) notify fixture in case2-unit.test.mjs and the world(t) one in
case2-install.test.mjs (a 0700 notify/acme dir and a null notify.json, with no assertion changed or deleted).
Conditions: the negative F5 tests build their host without the file; one append-only install test shows
notify.json bytes and mode are unchanged after install; the fixture lines are their own follow-up commit.
- Section 9a creates both `notify/` and `notify/<business>` at 0700 (ops-0261 measured a 755 parent).
6. F6: sheet :235 runs `stack-copy.sh check`, which requires `$HOME/.npm-global/bin/mosaic` (stack-copy.sh:160-173).
Nothing creates it: install runs only `copy` (:178), bootstrap has no .npm-global, and the sheet has no wrapper
step. The sheet gains a step after install: as mosaic from cwd `/`, create the bin dir, then run
`wrapper <sha> --create`, naming the Mos gate (stack-copy.sh:3). No requirement change. #1816 carries F1 to F6.
## Brief: F7, the wrapper step's PATH and umask under sudo
Row: F7 for the 433 P1 rerun (ops-0271, mos-1544). Docs only. Builder: a Codex thread. Reviewer: a separate Codex
thread (mos-1542). It can land with any row and is not N+1.
Defect, from ops-01 on 094124b4e: the run sheet's wrapper step (`docs/guides/host-run-sheet.md` :249-253) fails
rc=127 `node: command not found`. `sudo -u mosaic -H /bin/sh` runs under sudo's `secure_path`, which drops
`/opt/mosaic-stack/node-<v>/bin`, and `scripts/stack-copy.sh wrapper` reaches `scripts/instance.sh:78`, which calls
bare `node`. The heredoc also sets no umask, so `$HOME/.npm-global/bin` came out 0775.
Change, inside the `MOSAIC_WRAPPER` heredoc only:
1. Before the `mkdir`, add `umask 077`, the same way the notify step does (:325).
2. Before the `mkdir`, add `PATH=/opt/mosaic-stack/node-<v>/bin:/usr/sbin:/usr/bin:/sbin:/bin; export PATH`, using the
sheet's own PATH form (:69).
3. Add one sentence above the block: the step runs under sudo's `secure_path`, so it sets its own PATH and umask.
Nothing else in the sheet changes, and no script changes. ops-01 is testing this exact form on 1013 (mos-1544).
Acceptance:
- The heredoc has `umask 077` and the PATH line before `mkdir`, with `<v>` written the same as the sheet's other
node paths.
- `git grep -n 'host-run-sheet' -- 'packages/*/tests/*' 'scripts/test-*.sh'` shows no test that reads the changed
lines (positive control: a grep for a path a test does read). If a test does read them, stop and report.
- BUILD.md under `agents/<seat>/work/queue-<row>/` records the diff and the grep.
F10, added to this row (ops-0274, mos-1548). Both are confirmed at 094124b4e.
- After a first install, the sheet has no `stack-release.sh adopt <business> --instance <i> --units external` step,
so the first activate refuses `no-pointer` (`scripts/stack-release.sh:1297`, "no $POINTER; run adopt first"). Add
that step where the sheet first moves from install to activate or upgrade. It runs on Mos's go, and Jason or Mos runs
it (`stack-release.sh:14`).
- The sheet doesn't say that the first `stack-upgrade.sh upgrade` after adopt needs `--no-rehearsal`. Adopt writes no
backup, so without the flag the upgrade refuses `no-backup` (`scripts/stack-upgrade.sh:324-325`), and with the flag
on a stack that has a backup it refuses `rehearsal-required`. Say so next to the upgrade command (sheet :210-223):
only the first upgrade after adopt takes `--no-rehearsal`.
ops-01 is testing both on 1013 (mos-1548). F10 is also docs only. The grep in the acceptance list covers its lines too,
and BUILD.md records them.
## Brief: F8 and F9, the library persona import runs without the clone's node_modules
Row: F8 and F9 for the 433 Run B rerun (ops-0273, mos-1546). Builder: a new Codex thread (mos-1542). Reviewer:
Morgana (Claude), because the row touches the install path (mos-1542 rule 4). When it lands, ops-01 reruns Run B P1
at that commit.
F8, confirmed at N = 094124b4e: `scripts/case2-install.sh:185` runs
`node "$REPO/scripts/case2-persona-import.mjs"` from the clone (`REPO`, :38). `case2-persona-import.mjs:32` imports
`yaml`, and a fresh clone has no `node_modules`, so the import fails `ERR_MODULE_NOT_FOUND`. The copy just made at
`$COPIES/$COMMIT` (:178) has `node_modules` (mos-1546). ops-01 reproduced `ERR_MODULE_NOT_FOUND` from a checkout
with no `node_modules`.
Fix F8 one of two ways, and say in BUILD.md which and why: run the importer from the copy
(`$COPIES/$COMMIT/scripts/case2-persona-import.mjs`), or make node resolve its modules from the copy. The importer's
relative import of `../packages/harness/src/bundle.mjs` must still resolve to the same commit's file. Whatever you
pick has to work when the clone has no `node_modules` at all.
F9: :186 keeps only `tail -n 1` of the importer's output. For an uncaught node error that line is the
node banner (`Node.js v24.22.1` on 1013, mos-1546), so the refusal hides the cause. Make the refusal carry the error line, for example the first line
matching `Error` or `ERR_`, falling back to the last line. Keep it to one line. Don't put a full stack trace in the
refusal.
Class check, same row: at N, `grep -n 'node "$REPO/' scripts/case2-install.sh scripts/case2-precheck.sh
scripts/stack-copy.sh` finds only :185. Rerun that grep. Also list every clone-side `.mjs` those three scripts run
that imports a package (a bare specifier, not `node:` or a relative path), and record the list in BUILD.md and the
review request. Fix any other hit in this row only if it is the same defect, and say so.
Test: add a new, append-only test block to `packages/cli/tests/case2-install.test.mjs`. It runs the library persona
import with no `node_modules` beside the script, and must fail at N. It needs no mos-1272 OK (mos-1546). Add a second
assertion that the F9 refusal carries the error line, not `Node.js v...`. In BUILD.md, explain why the existing
case2-install tests missed this. ops-01 thinks the checkout's `node_modules` hid it; check that.
Gate: Morgana approves the manifest. Every package suite (except queue) and every `scripts/test-*.sh` are green on
Sage's gate, the new test fails on N, and a mutant that puts back `$REPO` at :185 is killed by the new test.
+33
View File
@@ -678,3 +678,36 @@ claim aren't one (design D1's alternative). Bound to the next row that changes t
Morgana, row 306 BUILD.md (#1813, landed 2d0318a44). A revoked run that also has a pending limit stop gets
`#limitStop`'s `not-holder` on `message.receive` and `state`, because that check runs before `#agent`. It's
rare and the run still stops. Bound to the next row that changes `#limitStop` or the order of those checks.
## Row226 N1: the install id regex is narrower than ID_PATTERN
Webby, row 226 round 1 (webby-0225, #1727, landed 661890e90). case2-install.sh:56 refuses a business id
with `.` or `_`, which ID_PATTERN (vocabulary.mjs:199) and case2-precheck.sh:67 accept. Gosalyn confirmed
it isn't deliberate (gosalyn-0208). It fails closed, so a real id with either character is refused, not
mishandled. Bound to the next row that changes case2-install.sh: take the ID_PATTERN set, and add a test.
## Row226 N2: a first-run validate refusal leaves personas and the slot dir
Webby, row 226 round 1 (webby-0225). After a validate refusal on a first run, the staged personas and the
empty token slot dir stay behind, and a re-run counts them as present. Bound to the same follow-up as N1:
remove what this run created, as the business file path already does (install.sh:198/:202/:218).
## Row226 N3: the run sheet doesn't pin the clone to the copy's sha
Webby, row 226 round 1 (webby-0225). install.sh:217 validates with the checkout's scripts/mosaic, not the
copy's, and host-run-sheet.md:237 never says the clone must be at `<sha>`. Bound to the same follow-up:
a HEAD check in the install or one clause on the run sheet.
## Row226 N4: --library-status refuses after a 5 s lock wait
Webby, row 226 round 1 (webby-0225). If the bus holds the library lock for more than 5 s,
`case2-precheck.sh --library-status` refuses with `ERROR library-sync-busy`. A re-run clears it. Recorded
as a known operator step, no fix bound.
## Row283 N1: SURVEY-RUN.md shows the scopes line without supporting
Webby, row 283 round 1 (webby-0267, #1788, review note queue-283/REVIEW-manifest-b2a1f4092.md on
webby/reviews c6ea27aab). docs/case2/SURVEY-RUN.md:96 documents the `--mapping` line as
`scopes canon .., playground .., unmapped ..; indexed ..`, which predates the supporting scope 283 adds.
Nothing reads the file (decision 137). Bound to the next docs commit that touches SURVEY-RUN.md: add the
supporting count to that line.
+17 -13
View File
@@ -33,7 +33,7 @@ Gaps found while working go to `docs/plans/DEFERRED.md`, not here.
<!-- mosaic-queue:begin -->
Generated from `docs/plans/queue.json` revision 3636 by `queue render`. Do not edit between the markers; change the queue with `scripts/mosaic queue`.
Generated from `docs/plans/queue.json` revision 3732 by `queue render`. Do not edit between the markers; change the queue with `scripts/mosaic queue`.
| # | Piece | Owner | Issues | State | After | Gate | Brief | Note |
|---|---|---|---|---|---|---|---|---|
@@ -252,18 +252,18 @@ Generated from `docs/plans/queue.json` revision 3636 by `queue render`. Do not e
| 213 | Case 2 C2-08 creative roles, persona file and block, M1, M2, M6, M10, prompt passed by file | morgana; reviewers webby | #1714 | done | — | Webby approves the manifest. The business, bus and harness suites, `scripts/test-config.sh` and every `scripts/test-*.sh` are green on Sage's gate, and the `models` mutant is killed. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-08 creative roles, persona file and block, M1, M2, M6, M10, prompt passed by file | LANDED 361ba2387 (39 paths incl. 4 packet files). Patch-id f313e69b6f7e = c771a36f4..2b3e67e36; verify-commit ok, 35 manifest paths. Same combined gate as 195: business 200/0 bus 542/0 harness 140/0 cli 663/0, test-config 31/0 and all 10 scripts green, models mutant L1 killed. Webby N2 is row 235 acceptance (mos-1163). |
| 214 | Case 2 C2-11a editor wikilink node, after measuring whether [[ round-trips | herb; reviewers filbert | #1715 | in-progress | — | Filbert approves the manifest. The webui suite is green on Sage's gate, along with every `scripts/test-*.sh`. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-11a editor wikilink node, after measuring whether [[ round-trips | — |
| 215 | Case 2 C2-04 the library entry in the business file, consumer skips, M9, mirror, library.file and library.status | herb; reviewers filbert | #1716 | done | — | Filbert approves the manifest. The business, seat, cli, project, bus and webui suites are green on Sage's gate, along with every `scripts/test-*.sh`. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-04 the library entry in the business file, consumer skips, M9, mirror, library.file and library.status | LANDED e54e05463 on 6096b051b (sage-2094). Patch-id 2f68188b6c9d equals a36523713..dde3445ab; 118 paths, blobs and modes equal; tree 5b1613245 equals merge-tree. No path overlap with rows 66/243; no hash pins either way. Gate: Filbert APPROVE rev 2924; herb-0095 grant sage-2071 2634 pass 0 fail, 1 webui skip (editor rebuild needs esbuild 0.28.2, env, not a 215 path), accepted. |
| 216 | Case 2 C2-05a lookup index and queries | researcher; reviewers filbert | #1717 | briefed | 268 done | Filbert approves the manifest. The library suite is green on Sage's gate, along with every `scripts/test-*.sh`. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-05a lookup index and queries | Rulings on phase A: agents/sage/work/queue-216/RULINGS.md (da9555ca2). r2 rebases on row 268's landing and adds the four PRD 1.14 playground tests. |
| 217 | Case 2 C2-06 the citation guard, the page store, the runner texts and the retry | launchpad; reviewers webby | #1718 | briefed | 268 done | Webby approves the manifest. The library, bus and harness suites are green on Sage's gate, along with every `scripts/test-*.sh`. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-06 the citation guard, the page store, the runner texts and the retry | — |
| 216 | Case 2 C2-05a lookup index and queries | researcher; reviewers filbert | #1717 | done | 268 done | Filbert approves the manifest. The library suite is green on Sage's gate, along with every `scripts/test-*.sh`. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-05a lookup index and queries | LANDED fbe57a05b (replay of r5 dae76ccc2 onto 8e2885d26, 3 commits, 0 patch-id mismatches), pushed 21:09Z with 582b86935. Sage joint gate GREEN 21:05:34Z on fbe57a05b, every package suite but queue and every scripts/test-*.sh green. Filbert APPROVE r2 c31384 rev 3697. N3 (get returns a universe own supporting files) binds the C2-05c row; N1 doc, N2 universeInfo echo and BUILD.md pronoun nit go to a later docs commit. |
| 217 | Case 2 C2-06 the citation guard, the page store, the runner texts and the retry | beakley; reviewers webby | #1718 | briefed | 268 done, 283 done | Webby approves the manifest. The library, bus and harness suites are green on Sage's gate, along with every `scripts/test-*.sh`. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-06 the citation guard, the page store, the runner texts and the retry | — |
| 218 | Case 2 C2-12 the setup sheet for Melanie and the survey run sheet | sage; reviewers webby | #1719 | done | — | Doc only. Webby approves it against C2-01's real flags. Before landing, grep `packages/*/tests` and `scripts/test-*.sh` to confirm no test reads either file. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-12 the setup sheet for Melanie and the survey run sheet | LANDED f8276c5eb (pushed, on Darkwing sessions b65f3a0e8). Webby APPROVE r1-r3 (revs 2848, 2856, 2860; r3 candidate 1a38baf5af2a = 89ba79d94). Patch-id 18ba1e40ad29 seat 5c6f73ed7..89ba79d94 equals landed b65f3a0e8..f8276c5eb; three blobs equal 89ba79d94. Gate: doc only, 0 test readers (control 3). Melanie handover waits on C2-06 and Jason (#419). |
| 219 | Case 2 C2-09a one thread per creative instance | rocko; reviewers dewey | #1720 | done | — | Dewey approves the manifest. The bus, cli and webui suites are green on Sage's gate, along with every `scripts/test-*.sh`. Watch for hash pins on `bus.js` and `broker.mjs` (`packages/bus/tests/channel-proof.test.mjs` pins a webui file). (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-09a one thread per creative instance | LANDED 5fdfd7275 on refactor 10:40Z 10-23 (8 row commits cherry-picked onto 2efd127ce, range-diff all =, patch-ids match, tree e86a84a85 = gated merge 054da642f; top commit packet-only evidence). Gate manifest 4a2271dd: node 2523/0/2, ten shells 449/0, 24 mutants killed, audit ok (Rocko). Dewey approve rev 3507 c31108. N1 U6 persona label DEFERRED line follows. Slug fix Vikunja 590 and network leak 591 rows next. |
| 220 | Case 2 C2-10a no raw session view (M7) and no raw Discord engine (M8) | researcher; reviewers filbert | #1721 | briefed | — | Filbert approves the manifest. The conversation and discord suites and `scripts/test-discord.sh` are green on Sage's gate, along with every `scripts/test-*.sh`. No test reaches a Discord server. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-10a no raw session view (M7) and no raw Discord engine (M8) | Rulings on phase A: agents/sage/work/queue-220/RULINGS.md (da9555ca2). Scope adds packages/business/src/library-seats.mjs (imported by path, no index export), its test, and control-board serve.mjs. r2 building as a Haiku subagent. |
| 220 | Case 2 C2-10a no raw session view (M7) and no raw Discord engine (M8) | researcher; reviewers filbert | #1721 | done | — | Filbert approves the manifest. The conversation and discord suites and `scripts/test-discord.sh` are green on Sage's gate, along with every `scripts/test-*.sh`. No test reaches a Discord server. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-10a no raw session view (M7) and no raw Discord engine (M8) | LANDED fbe57a05b (replay of r5 739b868b6 onto 93694c518, 9 commits, 0 patch-id mismatches; tip 8e2885d26 for 220), pushed 21:09Z with 582b86935. Sage joint gate GREEN 21:05:34Z on fbe57a05b: every package suite but queue 0 fail 0 skipped, every scripts/test-*.sh rc 0. Filbert APPROVE r2 c31383 rev 3696. Researcher r5 reruns and mutants green. Filbert N1 (route test catalogue only) open, not blocking. |
| 221 | Case 2 C2-20 Bean and Chet persona import, with a count-only dry run | gosalyn; reviewers webby | #1722 | done | — | Webby approves the manifest. The test file runs green on its own and the cli suite is green on Sage's gate, along with every `scripts/test-*.sh`. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-20 Bean and Chet persona import, with a count-only dry run | LANDED 300766450, pushed. Cand 8f403d0d4, manifest 20f05e3a6ad5, 22 paths, verify-commit ok, patch-id dfbb754c6fb4 equals 62ddc96cc..8f403d0d4. Gate 11:07:50-11:19Z on b1fece6f0: test file alone 11/0, harness 140/0, cli 677/0, all scripts green. Brief Gate met: webby-0073 approve, test file alone, cli, scripts. No live run in the Gate; the import itself waits on Jason. N1 N2 N4 go to C2-20b, N3 to DEFERRED. |
| 222 | Case 2 C2-03a fetch-only sync | megavolt; reviewers dewey | #1723 | done | — | Dewey approves the manifest. The library and bus suites are green on Sage's gate, along with every `scripts/test-*.sh`, and the mutant is killed. A search of the test run's output for the fixture token finds nothing. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-03a fetch-only sync | sage-2024 on megavolt-0089: core.createObject=rename in the fetch argv is accepted as a brief departure, since C2-04 inspectMirror refuses nlink 2. Dewey checks it. The askpass env keys, export SAFE in project/src/git.mjs, bus/tests/library-sync.test.mjs and the SURVEY-RUN user line are accepted. The 5 s client timeout residual goes in BUILD.md and Dewey rules fix or defer. Slot after 197 proof 3 and the 249 gate. |
| 223 | Case 2 C2-07 runner retry on a guard refusal, and the runner's notices | researcher; reviewers filbert | #1724 | blocked (from briefed): Q226: C2-07 folded into C2-06 (row 217). No work here; Jason parks it. | — | Filbert approves the manifest. The harness suite is green on Sage's gate, along with every `scripts/test-*.sh`. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-07 folded into C2-06 | — |
| 224 | Case 2 C2-05b broker lookup verbs and typed tools | della; reviewers dewey | #1725 | in-progress | 216 done | Dewey approves the manifest. The bus and harness suites are green on Sage's gate, along with every `scripts/test-*.sh`. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-05b broker lookup verbs and typed tools | — |
| 225 | Case 2 C2-10b Console chat: replies, citations, write notices and the status line | researcher; reviewers dewey | #1726 | briefed | — | Dewey approves the manifest. The webui suite is green on Sage's gate, along with every `scripts/test-*.sh`. Grep for hash pins on `bus.js` and `serve.mjs` before in-review. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-10b Console chat: replies, citations, write notices and the status line | — |
| 226 | Case 2 C2-13 install script and precheck for the host | gosalyn; reviewers webby | #1727 | in-progress | 215 done, 221 done, 222 done, 230 done | Webby approves the manifest. The test file and the cli suite are green on Sage's gate, along with every `scripts/test-*.sh`. The run on the host is a separate window with Jason's go. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-13b install script and library precheck | — |
| 227 | Case 2 C2-14 end-to-end acceptance on a scratch root | launchpad; reviewers dewey | #1728 | briefed | — | Dewey runs the script and approves. It is green on Sage's gate with every `scripts/test-*.sh`. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-14 end-to-end acceptance on a scratch root | — |
| 225 | Case 2 C2-10b Console chat: replies, citations, write notices and the status line | fethry; reviewers dewey | #1726 | briefed | 217 done | Dewey approves the manifest. The webui suite is green on Sage's gate, along with every `scripts/test-*.sh`. Grep for hash pins on `bus.js` and `serve.mjs` before in-review. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-10b Console chat: replies, citations, write notices and the status line | — |
| 226 | Case 2 C2-13 install script and precheck for the host | gosalyn; reviewers webby | #1727 | done | 215 done, 221 done, 222 done, 230 done | Webby approves the manifest. The test file and the cli suite are green on Sage's gate, along with every `scripts/test-*.sh`. The run on the host is a separate window with Jason's go. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-13b install script and library precheck | landed 661890e90 (replay of bfed0aa6c 893b4fd25 f3fabf51b onto 8352da88c, patch-ids equal, four blobs and modes equal to f3fabf51b) and fd3d2a99f (Darkwing 8a6321790 replay, mos-1519), tree 78fc5ad21 equals merge-tree. Webby APPROVE rev 3641. Sage gate GREEN 19:56Z on f3fabf51b: 17 package suites and 10 scripts, 0 fail. Webby N1-N4 DEFERRED e2b873390. #1727 closed. |
| 227 | Case 2 C2-14 end-to-end acceptance on a scratch root | gizmoduck; reviewers dewey | #1728 | in-progress | — | Dewey runs the script and approves. It is green on Sage's gate with every `scripts/test-*.sh`. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-14 end-to-end acceptance on a scratch root | — |
| 228 | Row A: ZAI_API_KEY passes through ENV_ALLOW to sessions, README line, pass-through test (XS, Haiku high) | researcher; reviewers webby | #1729 | done | — | Webby approves the manifest. The mutant is killed. The seat suite and the cli suite are green on Sage's gate with every scripts/test-*.sh. (sage) | `docs/plans/2026-10-20_case2-rows.md` § Brief: row A, ZAI_API_KEY in the session env allowlist | Landed 86249ac55 (pushed 07:25Z) on 59f817c32: the 3 manifest paths from cf18c42b9. Patch-id b6ffe31feb0d equals the candidate's; modes and blobs match; verify-commit ok (3 paths). Sage's combined 228+238 gate on c515273db plus both rows' 6 paths, 07:11:30Z to 07:23:34Z: seat 165/0, cli 640/0, all ten scripts/test-*.sh 585/0. |
| 229 | Row B: per-instance pi agent dir for Chet's Codex login, design only, starts after 10-27 (#428) | gosalyn; reviewers webby | #1730 | briefed | — | A live check, with Jason's or Mos's go, that two clients on one ChatGPT login don't revoke each other's refresh tokens. No build row starts before it passes. Held until after 10-27. (sage) | `docs/plans/2026-10-20_case2-rows.md` § Brief: row B, a per-instance pi agent dir for Chet's Codex login (#428) | — |
| 230 | Case 2 C2-13a unit render and host precheck (case2-unit.sh, case2-precheck.sh) | gosalyn; reviewers webby | #1732 | done | — | Webby approves the manifest. The test file and the cli suite are green on Sage's gate, along with every scripts/test-*.sh. A run on a host is a separate window with Jason's go. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-13a unit render and host precheck | Landed c8bc5cf4c on refactor (base 390ea5261), pushed. Patch-id f4b49eb68997 matches git diff 722136772..96768766c on the 5 manifest paths (manifest fbb0d7e42c67, Webby approve r2 rev 2563). packages/cli/README.md 3-way with row 199, hunks apart. Gosalyn gate on 96768766c: cli 541/0, scripts 429/0, mutants 10/10. Merged tree check: case2-unit 30/0, host 42/0. |
@@ -275,7 +275,7 @@ Generated from `docs/plans/queue.json` revision 3636 by `queue render`. Do not e
| 236 | #436b Gitea grant path build: seat accounts and tokens through an approved grant, schema 3j-3k (design r5 1be535aca, due 10-27 at risk; live waits for Jason's section 8 approval and bootstrap step) | megavolt; reviewers dewey | #1742 | done | 210 done, 234 done | Dewey approves the manifest. The bus, business and cli suites and every scripts/test-*.sh are green on Sage's gate. Section 9's mutants are killed, N9's restart test included. (sage) (sage) | `docs/plans/2026-10-20_agent-credentials.md` § Brief: #436b Gitea grant path, build (schema 3j-3k) | Landed bd5f11ded on refactor, a fast-forward on be2b008cc. It is 08840f3c1 rebased past 194 (commit 1 unions only, 2-7 =) plus 2 stale-pin fixes and a gitea-not-configured raise test (sage-2559). Dewey approve on manifest 0b00269b. Megavolt gate under Sage CLEAR: 2c green, bus 765, business 228, cli 832, ten scripts rc=0, mutants 40/40; skips named, env-only. Overlap 13/257 clean. Schema 3j-3k. #1742 closed. |
| 237 | Row 199 follow-up N1: one decision publishes once (publish-busy or #spent recheck) | megavolt; reviewers duckworth | #1743 | done | 199 done | Duckworth approves the manifest. The bus suite and every scripts/test-*.sh are green on Sage's gate, and the mutant is killed. (sage) (sage) | `docs/plans/2026-10-20_agent-credentials.md` § Brief: row 199 follow-up N1, one decision publishes once | Landed d7d943199 on refactor (local, push pending), patch-id c5f4beb4 = e42415935, manifest bb777cb0 blobs checked. Sage gate 01:31-01:44Z on 816d48b03+4 paths: M1 killed (bus 1/13, cli 1/8), every package suite and scripts/test-*.sh green (bus 478, cli 564). |
| 238 | row 200 follow-up N1: the sso-config hint carries --instance NAME (#1744) | launchpad; reviewers webby | #1744 | done | 200 done | Webby approves the manifest; stack-release.test.mjs whole, cli suite and every scripts/test-*.sh green on Sage's gate; the mutant killed (sage) | `docs/plans/2026-10-20_stack-release-sso.md` § Brief: row 200 follow-up N1, the sso-config hint names the instance | Landed d49b1f2bd (pushed 07:25Z) on 86249ac55: the 3 manifest paths from 4c90099ea. Patch-id b9d0bb0ee3c7 equals the candidate's; modes and blobs match; verify-commit ok (3 paths). Sage's combined 228+238 gate on c515273db plus both rows' 6 paths, 07:11:30Z to 07:23:34Z: seat 165/0, cli 640/0, all ten scripts/test-*.sh 585/0. Mutant (sso-config drops --instance) killed, survived none. Round 1 N1 stays on the #1744 carry list. |
| 239 | Row 194 follow-up: the credential revoke runs under the writer's lock, refusals after a revoke say so, and a stale-revision fire test (duckworth-0074, mos-1158) | honker; reviewers duckworth | #1745 | in-progress | 194 done | Duckworth approves the manifest. The bus, business, cli and webui suites and every scripts/test-*.sh are green on Sage's gate, and the mutants are killed. (sage) (sage) | `docs/plans/2026-10-20_agent-lifecycle.md` § Brief: row 194 follow-up, the revoke under the writer's lock and a fire test | — |
| 239 | Row 194 follow-up: the credential revoke runs under the writer's lock, refusals after a revoke say so, and a stale-revision fire test (duckworth-0074, mos-1158) | honker; reviewers duckworth | #1745 | done | 194 done | Duckworth approves the manifest. The bus, business, cli and webui suites and every scripts/test-*.sh are green on Sage's gate, and the mutants are killed. (sage) (sage) | `docs/plans/2026-10-20_agent-lifecycle.md` § Brief: row 194 follow-up, the revoke under the writer's lock and a fire test | LANDED e0cb1db2c (ff from 546366f4a) 22:24:58Z 10-23. Duckworth APPROVE c31422 rev 3723. Honker slot: touched files 65/65, mutants 9/9. Sage full gate GREEN 22:24:24Z: all package suites 0 fail (bus 909, cli 976, plugins 119, webui 411) and every scripts/test-*.sh rc 0; skips are queue canonical-root and task live-provider only. Overlap: 298 shares broker.mjs, runtime.mjs, instance-settings.mjs and rebases. N+1 for 433 P2/P3 (mos-1540). |
| 240 | Installer I4: hostcheck, the bwrap profile check, pins and boot unit, from r6 B2 (MVP, Q187, Vikunja #432; split from I3) | darkwing; reviewers filbert | #1746 | done | 233 done | Filbert approves the manifest. The test file, the cli suite and every scripts/test-*.sh are green on Sage's gate, with the mutants killed. (sage) (sage) | `docs/plans/2026-10-20_installer-rows.md` § I4 hostcheck: the bwrap profile check, pins and boot unit | Landed c515273db (pushed 06:57Z) on da3051ccc: the 9 manifest paths from ad1b23ab2. Patch-id 48e376efe8a4 equals the candidate's; modes and blobs match; verify-commit ok (9 paths). Sage's gate on 060a17b54 plus the 9 paths, 06:45:05Z to 06:56:21Z: cli 639/0, all ten scripts/test-*.sh 585/0. Darkwing's r2: singles 37/0, M1-M8 8/8. Filbert N1 and N2 in DEFERRED (da3051ccc); N3 by design. |
| 241 | Row 237 follow-up: one decision lands once, a two-ticket broker land test and three mutants on the landing guards (megavolt-0069, sage-1651, P19 441) | megavolt; reviewers duckworth | #1747 | done | 237 done | Duckworth approves the manifest. The bus, seat and cli suites and every scripts/test-*.sh are green on Sage's gate, and the three mutants are killed. (sage) (sage) | `docs/plans/2026-10-20_agent-credentials.md` § Brief: row 237 follow-up, one decision lands once, with tests at the broker | Landed 5d4a61776 on refactor, pushed (base e65a3ab4d). Blobs from 3e3ed303e on 2 paths; patch-id a1649f80 equals git diff f5753c0e8..3e3ed303e on those paths; ls-tree modes equal; manifest e8266864 verifies on the landed files. Sage slot on bbf3b1ee8: M1-M3 killed; gate 15 packages 2797/0, 10 script suites 429/0. Duckworth approve 29870 rev 2628. |
| 242 | Row 237 follow-up N1: a retry after publish-timeout pushes once; hold the decision or kill and wait for the push, a slow-push retry test and a mutant (duckworth-0069, P19 440) | megavolt; reviewers duckworth | #1748 | done | 237 done | Duckworth approves the manifest. The bus and cli suites and every scripts/test-*.sh are green on Sage's gate, and the mutant is killed. (sage) (sage) | `docs/plans/2026-10-20_agent-credentials.md` § Brief: row 237 follow-up N1, a retry after publish-timeout pushes once | Landed 5fb736b92 on refactor, pushed (base 96bac588f). Blobs from 635c10924 on 3 paths; patch-id ceb741ee equals git diff 8fede5fc6..635c10924 on those paths; ls-tree modes equal; manifest 1fbfab6c verifies on the landed files. Megavolt M1/M2 killed on Sage's slot; Sage gate 15 packages 2826/0, 10 script suites 429/0. Duckworth approve 29889 rev 2639. |
@@ -319,12 +319,12 @@ Generated from `docs/plans/queue.json` revision 3636 by `queue render`. Do not e
| 280 | Bus tests: the scratch sshd proves it owns its port (194 gate follow-up, MVP, mos-1270) | rocko; reviewers duckworth | #1785 | done | — | Duckworth approves the manifest. Both files run whole, the bus suite is green on Sage's gate, the 30-run repeat has no timeout, and M1 is killed. Row 194 b17's full gate then runs on top. Any red goes to Mos (mos-1270). (sage) | `docs/plans/2026-10-22_sshd-port-race.md` § Brief: the scratch sshd's port is ours before a test uses it | Landed b0fd28b6f 07:57:30Z, ff from da5d3651d: b765f5cb8 (Duckworth approve rev 3153, manifest 27806c05) + slim packet. Sage gate bus 656/0/0, ge 41, hr 26 (c30431). Repeat 2010/2010 under cli 1588/1588, no timeout; M1/M2 killed 4/4. Full evidence d6c924764 on rocko/row280-da5d-20261022. N2-N4 carry in BUILD.md. 194 b17 rebases on b0fd28b6f. |
| 281 | A fire or a delete revokes the instance's host and Gitea grants (194/236 follow-up, MVP, mos-1271) | megavolt; reviewers dewey | #1786 | done | 236 done | Dewey approves the design, then the manifest. Bus, business, cli and every touched test file run whole, plus the Docker gitea-grant test and every scripts/test-*.sh, green on Sage's gate. M1-M4 killed. Lands before .53 Case 1 hires a granted instance. Red goes to Sage, then Mos. (sage) | `docs/plans/2026-10-22_fire-revokes-grants.md` § Brief: no grant outlives its instance | LANDED e479521d3 ff on 385a7194c (17 commits, manifest b73d4c81). Slot on 7979fb41e green: bus 819, business 231, cli 837, dewey-bus 76 with gitea-grant-docker run, shells green under 3x limits, M1-M22 killed. M1 hang fixed in b4a (mos-1273). Skips: test-task row 244 live-provider pair, test-queue canonical root. DEFERRED: N1 host-unknown hint verb, N2 fire tool text, to the follow-up row. Dewey APPROVE c30614. |
| 282 | PRD REQ-LIB-6 rewritten to Q223 and Q226 (mos-1320 item 8) | gosalyn; reviewers webby | #1787 | done | — | Webby approves against the ruling. requirements.test.mjs and every scripts/test-*.sh that reads the PRD or requirements.json are green on Sage's gate. Jason gets a report. (sage) | `docs/plans/2026-10-20_case2-rows.md` § PRD REQ-LIB-6 rewritten to Q223 and Q226 (mos-1320 item 8) | Landed 647424442 on 86a665bdf: 1841f7d4e and 6b5b06819 rebased, patch-ids equal (4e50b4b6, 16a7a02f), range-diff =, tree 4f30ed10a = Gosalyn's gated trial tree. Webby APPROVE rev 3308 c30764 on 6b5b06819. Gate 19:06Z on the tip tree: bus+tasks requirements and tasks verbs 37/0/0, 0 skips; no scripts/test-*.sh reads the PRD (control ok). PRD 1.15. 1.16 is row 291, waits for Jason. |
| 283 | Case 2 C2-01d supporting folders, the supporting scope, the editor field and supportingPath (M12) | honker; reviewers webby | #1788 | briefed | 268 done, 282 done | Webby approves the manifest. The library and business suites are green on Sage's gate, along with every scripts/test-*.sh. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-01d supporting folders, the supporting scope, the editor field and supportingPath (M12) | — |
| 283 | Case 2 C2-01d supporting folders, the supporting scope, the editor field and supportingPath (M12) | honker; reviewers webby | #1788 | done | 268 done, 282 done | Webby approves the manifest. The library and business suites are green on Sage's gate, along with every scripts/test-*.sh. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-01d supporting folders, the supporting scope, the editor field and supportingPath (M12) | LANDED 8d2856ee3 (replay of 0bf308dba onto 59226f878, 13 patch-ids equal) plus DEFERRED N1 93694c518. Webby APPROVE r1 c31338 rev 3677, r2 c31342 rev 3683 (mos-1528 G1 mapping.test:52). Sage full gate GREEN 20:37:16Z: all package suites but queue plus every scripts/test-*.sh, 0 fail, library 98/0, webui npm ci, editor build required. supporting.test first-run red placed (mos-1272, 54d9e07bb). #1788 closed c31358. Live unchanged 45dca69f6. |
| 284 | Case 2 C2-05c the supporting scope and blob in the lookups | della; reviewers dewey | #1789 | briefed | 224 done, 283 done | Dewey approves the manifest. Library, bus and harness suites and every scripts/test-*.sh green on Sage's gate. Grep packages/*/tests for the scope enum pin and ['canon', 'playground'] before in-review; update each. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-05c the supporting scope and blob in the lookups (sage-2833) | — |
| 285 | Case 2 C2-08b role changes for agent writes and the chief's read grant | scrooge; reviewers webby | #1790 | briefed | 213 done, 291 done | Webby approves the manifest. Business suite, test-config.sh and every scripts/test-*.sh green on Sage's gate. Grep for CREATIVE_KINDS and 64-hex pins of changed role files. Sage checks it against mos-1309 item 5. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-08b role changes for agent writes and the chief's read grant (mos-1309 item 5) | — |
| 286 | Case 2 C2-03b push and per-seat credentials for the library mirror (with R4, mos-1323) | ludwig; reviewers dewey | #1791 | briefed | 222 done | Dewey approves the manifest. Library and bus suites and every scripts/test-*.sh green on Sage's gate, mutant killed. A search of the run output for the fixture token finds nothing. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-03b push and per-seat credentials for the library mirror | — |
| 287 | Case 2 C2-21 the grant executor for a library project | megavolt; reviewers dewey | #1792 | briefed | 226 done, 285 done | Dewey approves the manifest. Bus suite, Gitea Docker test, install test and every scripts/test-*.sh green on Sage's gate. A search of the run output for the fixture admin and seat tokens finds nothing. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-21 the grant executor for a library project | — |
| 288 | Case 2 C2-02 agent writes, the notice, revert and her Console saves | honker; reviewers webby | #1793 | briefed | 215 done, 282 done, 283 done, 284 done, 285 done, 286 done | Webby approves the manifest. Library, bus and harness suites and every scripts/test-*.sh green on Sage's gate, mutants killed. A search of the run output for the fixture tokens finds nothing. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-02 agent writes, the notice, revert and her Console saves | — |
| 288 | Case 2 C2-02 agent writes, the notice, revert and her Console saves | bubba; reviewers webby | #1793 | briefed | 215 done, 282 done, 283 done, 284 done, 285 done, 286 done | Webby approves the manifest. Library, bus and harness suites and every scripts/test-*.sh green on Sage's gate, mutants killed. A search of the run output for the fixture tokens finds nothing. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-02 agent writes, the notice, revert and her Console saves | A2 revert contract (morgana-0199, sage-3596): library.revert is a human verb. Args {project, commit}, strict keys; project is the business.projects key (the chat repo link), not a UUID. Result {project, path, reverted, commit}. Refusals: 409 stale-base, and 409 library-revert-not-agent for an agent caller. Owner Bubba under Q245 (mos-1506). |
| 289 | Case 2 C2-11b Console library pages and her saves (Haiku subagent, decision 129) | researcher; reviewers filbert | #1794 | briefed | 214 done, 288 done | Filbert approves the manifest. The webui suite and every scripts/test-*.sh are green on Sage's gate. Grep for hash pins on bus.js and serve.mjs before in-review. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-11b Console library pages and her saves | — |
| 290 | Case 2 C2-12b the setup sheet rewrite for free chat, supporting folders and saves | louie; reviewers webby | #1795 | briefed | 217 done, 218 done, 285 done, 291 done | Doc only. Webby approves it against the ruling. Before landing, grep packages/*/tests and scripts/test-*.sh to confirm no test reads the file. (sage) | `docs/plans/2026-10-20_case2-rows.md` § C2-12b the setup sheet rewrite for free chat, supporting folders and saves | — |
| 291 | PRD 1.16 library.write routes under REQ-LIB-6 (mos-1328) | gosalyn; reviewers webby | #1796 | done | 282 done | Webby approves the text. Jason says yes to the exact text (Mos asks him, mos-1328 step 3); no landing before that. requirements.test.mjs and every scripts/test-*.sh that reads the PRD or requirements.json are green on Sage's gate. Mos gets the landing commit. (sage) | `docs/plans/2026-10-22_prd-1-16-brief.md` § PRD 1.16 library.write routes under REQ-LIB-6 (mos-1328) | Landed 4874d1e83 on e909ef51a: 482e865ac replayed, patch-id equal (cef7de74), range-diff =. Webby APPROVE c30848 on 482e865ac; Jason approved the text in Q229. Gate 16:15Z on the tip tree: every package suite but queue, 0 fail 0 skipped (tasks 100, bus 891, cli 941, plugins 119, webui 392, business 231), every scripts/test-*.sh rc 0 (queue-root and row 244 skips only). PRD 1.16. 1.17 is row 308. |
@@ -332,9 +332,9 @@ Generated from `docs/plans/queue.json` revision 3636 by `queue render`. Do not e
| 293 | 574: maintenance-free test fixture commits (Vikunja 574) | gander; reviewers filbert | #1805 | done | — | Filbert approves. The four whole files, then the seat and cli suites, are green on Sage's gate. (sage) | `docs/plans/2026-10-23_mvp-readiness-rows.md` § Brief: 574, maintenance-free test fixture commits (Vikunja 574) | LANDED e51d11640 03:55Z 10-23 (cherry-pick of gander b23783f39..a9cae2bd6 onto 464010fbe; range-diff 6/6 equal, range patch-id equal). Filbert APPROVE c30982 cdda41f5; run 2 4 files 153/0, seat 202/0, cli 905/0, 312 flagged/0 maintenance children. N1: lifecycle.test needs TMPDIR of 50 bytes or less. Residual: queue store.mjs, discord git.mjs, harness tools.mjs unflagged. #1805 closed c31013, P19 574 c888. |
| 294 | FED R6: Console granted-user sign-in, user-cli transport, peer links | launchpad; reviewers duckworth | #1800 | done | — | Duckworth approves the manifest. The webui, cli and bus suites and every scripts/test-*.sh are green on Sage's gate, and the mutants are killed. (sage) | `docs/plans/2026-10-23_mvp-readiness-rows.md` § Brief: FED R6, Console granted-user sign-in | landed d3059c2c3 on refactor 07:04Z: cherry-pick of c902a767d..24b745447 onto 09d0d6faf, range-diff 11 =, patch-id 8371405a equal. Duckworth approve c31053 rev 3469 on a1ff5d67, C1/C2 met. Run 4 on 8616b9a4f from npm ci: webui 365, cli 909, bus 873, 10 scripts, M1-M11 killed. Merged tree: stack-release-external 25, stack-upgrade 21, stack-release 223/224 (R9 transient, row 1810) then 224/224 rerun under mos-1422. Follow-ups rows 300, 301. Closes #1800. |
| 295 | FED R4: revocation | morgana; reviewers dewey | #1801 | done | — | Dewey approves the manifest. The bus, cli and business suites and every scripts/test-*.sh are green on Sage's gate, and the mutants are killed. (sage) | `docs/plans/2026-10-23_mvp-readiness-rows.md` § Brief: FED R4, revocation | LANDED 2efd127ce on refactor 10:10Z 10-23 (9 commits cherry-picked onto 07802dc57, range-diff all =, patch-ids match, HEAD~1 tree a86592ffc = gated tree, top commit BUILD.md doc-only). Gate d68b4300d manifest e94c9aeb: 13 whole files, bus 886/0, business 231/0, cli 924/0, harness 151/0, all test-*.sh rc 0, M1-M16 killed, M8 per mos-1436. Dewey approve rev 3500 c31102. Re-pin precheck mos-1436 cond 11 binds. |
| 296 | FED R7: scratch two-instance acceptance | quackerjack; reviewers filbert | #1802 | briefed | 190 done, 294 done, 295 done | Filbert approves the manifest. The script test and every scripts/test-*.sh are green on Sage's gate, and no unit, port or socket of the script's outlives the run. (sage) | `docs/plans/2026-10-23_mvp-readiness-rows.md` § Brief: FED R7, scratch two-instance acceptance | — |
| 297 | GitHub grant method (Bushroot's half of #436b) | bushroot; reviewers dewey | #1803 | briefed | 198 done | Dewey approves the manifest. The touched suites and every scripts/test-*.sh are green on Sage's gate, and the mutants are killed. (sage) | `docs/plans/2026-10-23_mvp-readiness-rows.md` § Brief: the GitHub grant method (Bushroot's half of #436b) | — |
| 298 | Q228: chief-of-staff grant scope | megavolt; reviewers dewey | #1804 | briefed | 252 done | Dewey approves the manifest. The touched suites and every scripts/test-*.sh are green on Sage's gate, and the mutants are killed. (sage) | `docs/plans/2026-10-23_mvp-readiness-rows.md` § Brief: the chief-of-staff grant scope (Q228) | — |
| 296 | FED R7: scratch two-instance acceptance | lena; reviewers filbert | #1802 | briefed | 190 done, 294 done, 295 done | Filbert approves the manifest. The script test and every scripts/test-*.sh are green on Sage's gate, and no unit, port or socket of the script's outlives the run. (sage) | `docs/plans/2026-10-23_mvp-readiness-rows.md` § Brief: FED R7, scratch two-instance acceptance | — |
| 297 | GitHub grant method (Bushroot's half of #436b) | violet; reviewers dewey | #1803 | briefed | 198 done | Dewey approves the manifest. The touched suites and every scripts/test-*.sh are green on Sage's gate, and the mutants are killed. (sage) | `docs/plans/2026-10-23_mvp-readiness-rows.md` § Brief: the GitHub grant method (Bushroot's half of #436b) | — |
| 298 | Q228: chief-of-staff grant scope | boyd; reviewers dewey | #1804 | in-review, round 1, request posted | 252 done | Dewey approves the manifest. The touched suites and every scripts/test-*.sh are green on Sage's gate, and the mutants are killed. (sage) | `docs/plans/2026-10-23_mvp-readiness-rows.md` § Brief: the chief-of-staff grant scope (Q228) | — |
| 299 | 573: the P10 hop band (Vikunja 573) | gander; reviewers filbert | #1806 | done | 293 done | Filbert approves. The whole file under load at least 3 times, then the cli suite, are green on Sage's gate. (sage) | `docs/plans/2026-10-23_mvp-readiness-rows.md` § Brief: 573, the P10 hop band (Vikunja 573) | landed ffb2fedfb 08:03Z on 15e688cc0 via Filbert SESSIONS c1f910b4c; 5 commits = gander/row299-gate-277ace0b 63db96d8b (range-diff 5/5 =, tree differs only BUILD-LOG/SESSIONS); manifest 277ace0b sha256 -c OK. Gate green on ffa93b054: case1 whole 3x 53/0/0, cli whole 917/0/0 (59 files), P10 inner 2.27 outer 4.01, M1-M6 killed (gander-0189). Filbert approve rev 3485 c31084; N1 M1 1.23 s margin. |
| 300 | R6-N1: HTTP-level test of the user-session option swap (294 N1) | launchpad; reviewers duckworth | #1807 | done | 294 done | Duckworth approves the manifest; new test file whole, webui suite, mutant M12 killed (sage) | `docs/plans/2026-10-23_r6-followup-rows.md` § Brief: R6-N1, an HTTP-level test of the user-session option swap | Landed on refactor as 9d929911c..07315e651 (from launchpad/row300 a00b25b37, range-diff equal), pushed 5b846b048 12:28Z. Duckworth approved r2 (c31158, rev 3559). Sage gate on bcf3c1dac: user-option-swap 1/0, webui 375/0 with pinned esbuild and MOSAIC_REQUIRE_EDITOR_BUILD=1, M12 killed at :151. Run 1 red placed under mos-1272 (headers). N1 deferred: board proxy upstream has no recorder. |
| 301 | R6-N4: fold user-bus.mjs back into bus.mjs (294 N4) | launchpad; reviewers duckworth | #1808 | done | 294 done | Duckworth approves the manifest; channel-proof.test, webui suite and 294 user-transport tests whole and green; re-pin only with Mos go (sage) | `docs/plans/2026-10-23_r6-followup-rows.md` § Brief: R6-N4, fold user-bus.mjs back into bus.mjs | Landed on refactor as bb031ec84..5b846b048 (from launchpad/row301 acc97fb9c, range-diff equal), pushed 12:28Z. Re-pin of webui bus.mjs to 39fcb27c is its own commit 59f0e44f4 (mos-1449); fixture stubs per mos-1451. Duckworth approved r2 (c31159, rev 3560). Sage gate: channel-proof 2/0, webui 374/0 pinned esbuild, granted-user 19/0. Live unchanged; 301 makes its own re-pin window. |
@@ -355,6 +355,10 @@ Generated from `docs/plans/queue.json` revision 3636 by `queue render`. Do not e
| 316 | 571 W5: read-only flags, citations and chat suggestions (post-10-27) | unassigned | — | queued | 315 done | Independent Opus 5.5 reviewer, not the author, approves the manifest; the brief section's Gate and G1 pass on Sage's slot: touched test files whole, affected package suites green, named mutants killed. Post-10-27; MVP rows keep slot priority (sage) | `docs/plans/2026-10-21_q195-writing-editor.md` § W5 read-only flags, citations and chat suggestions | — |
| 317 | 571 W7: human one-way chapter import and Case 2 format routing, production import closed; the first real import opens only after W8 lands (post-10-27, mos-1470) | unassigned | — | queued | 314 done, 315 done | Independent Opus 5.5 reviewer, not the author, approves the manifest; the brief section's Gate and G1 pass on Sage's slot: touched test files whole, affected package suites green, named mutants killed. Post-10-27; MVP rows keep slot priority (sage) | `docs/plans/2026-10-21_q195-writing-editor.md` § W7 human one-way chapter import and Case 2 format routing | — |
| 318 | 571 W8: Console Connections view for Markdown and DOCX story files, before W7's first real import (post-10-27, mos-1470) | unassigned | — | queued | 314 done, 315 done, 317 done | Independent Opus 5.5 reviewer, not the author, approves the manifest; the brief section's Gate and G1 pass on Sage's slot: touched test files whole, affected package suites green, named mutants killed. Post-10-27; MVP rows keep slot priority (sage) | `docs/plans/2026-10-21_q195-writing-editor.md` § W8 Console Connections view for Markdown and DOCX story files | fenton-0017 carry: connections.test.mjs must test that links inside comments and tracked deletions are excluded. W8 follows W7's closed routing candidate and lands before W7's first real import opens (mos-1470) |
| 319 | GitHub consumer for row 297's protected githubWithToken callback, honoring expiry and cancellation (post-10-27) | unassigned; reviewers dewey | — | queued | 297 done | Dewey approves the design and the manifest. The touched suites and every scripts/test-*.sh are green on Sage's gate, and the signal and expiry mutants are killed. (sage) | `docs/plans/2026-10-23_github-consumer-brief.md` § Brief: a GitHub consumer for Broker.githubWithToken | — |
| 320 | Case 1/2 host fixes for the 433 P1 rerun: hostcheck item 5 mode 750, run sheet bundle verify, case2-unit --claude @, stack-copy unreadable cwd, notify.json step and precheck, mosaic wrapper step (10-27 path) | gladstone; reviewers morgana | #1816 | required; done | — | Morgana approves. Touched test files run whole (case1-hostcheck, case2-unit, case2-install, stack-copy) and the 8 named mutants are killed; Sage's full landing gate runs every package suite and every scripts/test-*.sh. After landing Mos sends ops-01 the new N. (sage) | `docs/plans/2026-10-23_host-fixes-1816-brief.md` § Brief: hostcheck item 5, bundle verify, case2-unit @, stack-copy cwd | LANDED 094124b4e 21:53Z (replay of faf55618e onto 45e3ca7bd, code paths patch-id equal, log appends in one final commit). F1-F6 hostcheck item 5, bundle verify, case2-unit scoped paths and cwd, precheck notify decision, run sheet 9a notify dirs 0700, wrapper step. Morgana APPROVE r2 c31403 rev 3715. Full gate GREEN 21:53:00Z, 0 fail (mos-1453/1455/1456). Vikunja 614 done. 433 P1 reruns on this N (mos-1532). |
| 321 | F7 and F10: host run sheet wrapper step sets umask 077 and the node PATH under sudo secure_path; adopt step after a first install; --no-rehearsal on the first upgrade after adopt (433, ops-0271/0274); docs only | gladstone; reviewers boyd | #1817 | required; briefed | — | Boyd (Codex) approves. A git grep with a positive control shows no test reads the changed run sheet lines; BUILD.md records the diff and the grep. Doc only, lands with any row (mos-1544). (sage) | `docs/plans/2026-10-23_host-fixes-1816-brief.md` § Brief: F7, the wrapper step's PATH and umask under sudo | — |
| 322 | F8/F9: case2-install.sh runs the library persona import from the stack copy, and its refusal carries the error line (433 Run B, ops-0273) | goldie; reviewers morgana | #1818 | required; briefed | — | Morgana approves (install path). The new case2-install test fails on 094124b4e and passes on the candidate; a mutant restoring REPO at :185 is killed; Sage's full landing gate runs every package suite and scripts/test-*.sh. Then ops-01 reruns Run B P1. (sage) | `docs/plans/2026-10-23_host-fixes-1816-brief.md` § Brief: F8 and F9, the library persona import runs without the clone's node_modules | — |
<!-- mosaic-queue:end -->
+3117 -50
View File
File diff suppressed because it is too large. Load diff
+19 -175
View File
@@ -46,8 +46,6 @@ export const ACTIONS = Object.freeze([
'policy.change',
'prd.approve',
'decision.resolve.technical',
// Row 285 (C2-08b, #1790): routed under PRD 1.16 REQ-WAIT-3 and REQ-LIB-6, below.
'library.write',
]);
// PRD 1.5 REQ-WAIT-3 (row 139, #1633): every action is a hard wait unless listed here, so a new
// action stays one until a reviewed commit names it routed. Matches the business vocabulary's ROUTED.
@@ -77,8 +75,6 @@ const ROUTED = new Set([
// PRD 1.7 REQ-COS-3 (row 194, #1692): the chief's hire and fire, within the bounds the broker checks.
'role.hire',
'role.fire',
// PRD 1.16 REQ-WAIT-3 and REQ-LIB-6 (row 285, #1790): a creative agent's library write.
'library.write',
]);
// REQ-WAIT-1's hard waits: always gated, and a raise for one goes to the human, cited or not.
export const HARD_WAITS = Object.freeze(ACTIONS.filter((action) => !ROUTED.has(action)));
@@ -100,16 +96,7 @@ export const TASK_PAGE_MAX = 200;
// request allowed past the ordinary 64 KiB envelope (server.mjs and client.mjs), up to its content cap.
export const PROJECT_FILE_VERBS = Object.freeze(['project.files', 'project.file', 'project.file.save']);
// C2-03a: library.sync is the human's fetch, and with `accept` the one way past library-diverged.
// Row 224: pure agent lookups are separate from the three human-only verbs. Listing them
// here also makes server.mjs await their host effects instead of serializing a Promise as {}.
const LIBRARY_LOOKUPS = Object.freeze({
'library.find': { method: 'find', fields: ['universe', 'query', 'type', 'book', 'scope', 'offset'], required: ['universe', 'query'] },
'library.get': { method: 'get', fields: ['universe', 'path', 'scope', 'from', 'links_from'], required: ['universe', 'path'] },
'library.search': { method: 'search', fields: ['universe', 'text', 'book', 'scope', 'offset'], required: ['universe', 'text'] },
'library.manuscript': { method: 'manuscript', fields: ['universe', 'book', 'scope', 'chapter', 'from', 'to'], required: ['universe', 'book'] },
'library.universe': { method: 'universeInfo', fields: ['universe'], required: ['universe'] },
});
export const LIBRARY_VERBS = Object.freeze(['library.file', 'library.status', 'library.sync', 'library.file.save', 'library.revert', 'library.doc.write', 'library.doc.delete', ...Object.keys(LIBRARY_LOOKUPS)]);
export const LIBRARY_VERBS = Object.freeze(['library.file', 'library.status', 'library.sync']);
export const PROJECT_SAVE_VERB = 'project.file.save';
export const PROJECT_SAVE_REQUEST_MAX = 1024 * 1024 + 64 * 1024;
export const WEB_VERBS =Object.freeze(['web.search', 'web.fetch']);
@@ -272,9 +259,6 @@ const grantName = (body) => [body?.action, body?.operation].some(n => typeof n =
// Every grant-evidence read filters on this (duckworth-0067 N1): a look-alike under another kind or
// actor is not evidence.
export const GRANT_EVIDENCE = "kind='action.allowed' AND actor_role IS NULL AND actor_run='grant'";
// C2-03b: what a library-fetch-no-grant refusal tells the human (sage-2928). A BusError carries only its
// code, so the timer's log line and the library README carry this text.
export const LIBRARY_FETCH_FIX = 'add the chief of staff, or grant the library through C2-21';
// r6 R4: the host record's identity, hashed at raise and at each later check.
export const registrySha256 = ({ address, port, user, sudo, hostKeys }) =>
createHash('sha256').update(JSON.stringify({ address, port, user, sudo: !!sudo, hostKeys })).digest('hex');
@@ -1967,33 +1951,6 @@ export class Broker {
// grant.host.enrolled or grant.failed died after its registry step: the key file and the record
// go, and it ends grant.failed interrupted. A resolved, unspent one is spent and ends the same way.
// Neither runs late.
// C2-03b (#1791, design 7.2): the credential the library fetch runs with, the bus's choice and not a
// pure one: it reads the store. The chief is any roles entry of definition STAFF_TO; a fire keeps it
// there (dewey-0860 Q2). Gitea grant evidence for a chief ends the slot fallback, and only the one
// listed chief's live, unheld gitea_grants row answers. With no chief entry, any gitea grant evidence
// refuses: a departure from the brief's pre-C2-21 fallback, accepted in sage-2928.
libraryFetchCredential(business) {
const b = this.#business(business);
const chiefs = Object.entries(b.roles ?? {}).filter(([, r]) => r?.definition === STAFF_TO).map(([name]) => name);
const evidence = (agent) =>
this.#store.get(
`SELECT 1 FROM events WHERE business=? AND ${GRANT_EVIDENCE} AND json_extract(body,'$.method')='gitea' AND (? IS NULL OR json_extract(body,'$.agent')=?) LIMIT 1`,
business,
agent,
agent,
);
const refused = { refused: 'library-fetch-no-grant', fix: LIBRARY_FETCH_FIX };
if (!chiefs.length) return evidence(null) ? refused : { kind: 'slot' };
if (!chiefs.some((agent) => evidence(agent))) return { kind: 'slot' };
const listed = chiefs.filter(
(agent) => !this.#firing(business, agent) && (!Array.isArray(b.launch?.instances) || b.launch.instances.includes(agent) || b.launch.by === agent),
);
if (listed.length !== 1) return refused;
const [agent] = listed;
const live = this.#store.get('SELECT user FROM gitea_grants WHERE business=? AND agent=?', business, agent);
if (!live || !this.#giteaKeys || this.#giteaKeys.held(business, agent)) return refused;
return { kind: 'chief', agent, user: live.user };
}
reconcileGrants() {
const ended = [];
for (const business of Object.keys(this.#businesses)) {
@@ -2498,11 +2455,13 @@ export class Broker {
} catch (e) {
const code = e instanceof BusError ? e.code : 'outcome-unknown';
const list = out.grants.map((g) => g.grant).join(', ') || 'none';
// Row 239 (#1745): a step B refusal after the writer's revoke ran.
const tokens = code.endsWith('-revoked') ? ' Its credential tokens may already be revoked.' : '';
this.#store.transaction(() => {
this.#event(sc, 'action.allowed', { action: 'fire.failed', job, step, code }, name);
this.#humanNotice(
sc.business,
`Fire of ${name}: job ${job} revoked its grants (${list}) but stopped at step ${step} (${code}). The instance is still firing. Run the fire again once ${code} is cleared.`,
`Fire of ${name}: job ${job} revoked its grants (${list}) but stopped at step ${step} (${code}).${tokens} The instance is still firing. Run the fire again once ${code} is cleared.`,
);
});
}
@@ -2669,14 +2628,12 @@ export class Broker {
}
// Row 236 (#1742, #436b r5 section 2): the agent's role and definition, if the agent is a role of the
// business whose definition declares gitea and which has identity and a publish grant (199 D8). A
// creative role gets no grant, whatever its definition declares (mos-1163). Row 285 (#1790, sage-2921):
// nor does the chief of staff, whose definition declares gitea for a read grant only, since this path
// mints SEAT_SCOPES, write:repository included.
// creative role gets no grant, whatever its definition declares (mos-1163).
#giteaRole(business, agent) {
const b = this.#business(business);
if (!Object.hasOwn(b.roles, agent)) fail('gitea-not-declared');
const role = b.roles[agent];
if (CREATIVE_DEFINITIONS.includes(role.definition) || role.definition === STAFF_TO) fail('gitea-not-declared');
if (CREATIVE_DEFINITIONS.includes(role.definition)) fail('gitea-not-declared');
const definition = Object.hasOwn(b.definitions ?? {}, role.definition) ? b.definitions[role.definition] : null;
if (
!definition?.credentials?.some((c) => c.service === 'gitea') ||
@@ -4974,6 +4931,9 @@ export class Broker {
// The bus code for an organization writer's refusal. Anything the writer didn't refuse by name is
// outcome-unknown: the write may have committed.
#organizationFail(e, verb) {
// Row 239 (#1745): the writer marks an error raised after a fire's or a delete's revoke ran, so
// the human reads that the tokens may already be revoked. Without the mark, today's code.
if (e.revoked) fail(e.code === "revision-conflict" ? "revision-conflict-revoked" : "outcome-unknown-revoked");
if (e.code === "revision-conflict") fail("revision-conflict");
if (e.code?.startsWith("organization-")) fail(e.code);
if (e.code === "invalid-plugins" || e.code === "unknown-plugin") fail(e.code);
@@ -5170,147 +5130,31 @@ export class Broker {
throw this.#refused(s, ProjectFailure && e instanceof ProjectFailure ? new BusError(e.code) : e, request);
}
}
// C2-02: all authority and credential choice stays on the host. Neither an agent's tool
// arguments nor the human's save may supply a credential, identity or commit message.
#libraryWriter(s, project) {
if (s.tester) fail('tester-refused');
const b = this.#business(s.business), role = b.roles?.[s.role];
if (s.human || s.reader || !CREATIVE_DEFINITIONS.includes(role?.definition)
|| !role.authority?.withinRole?.includes('library.write')) fail('library-write-refused');
this.#agent(s);
const live = this.#store.get('SELECT user,projects,rotate_by FROM gitea_grants WHERE business=? AND agent=?', s.business, s.role);
if (!live || !this.#giteaKeys || this.#giteaKeys.held(s.business, s.role)
|| this.#firing(s.business, s.role) || live.rotate_by < this.#now().slice(0, 10)
|| !role.publish?.includes(project)) fail('library-write-no-grant');
let projects;
try { projects = JSON.parse(live.projects); } catch { fail('library-write-no-grant'); }
if (!Array.isArray(projects) || !projects.includes(project) || live.user !== role.identity?.gitea?.user)
fail('library-write-no-grant');
if (!role.identity?.name || !role.identity?.email) fail('library-write-refused');
return { identity: { name: role.identity.name, email: role.identity.email },
agent: `${s.business}/${s.role}`, credential: { kind: 'seat', agent: s.role, user: live.user } };
}
#libraryWriteNotice(s, op, result) {
const mid = randomUUID();
this.#store.run('INSERT INTO messages(id,at,business,from_role,from_run,to_role,class,in_reply_to,decision,corrects,body) VALUES(?,?,?,?,?,?,?,?,?,?,?)',
mid, this.#now(), s.business, s.role, s.run, 'human', 'INFO', null, null, null,
JSON.stringify({ notice: 'library-write', op, path: result.path, commit: result.commit }));
this.#route(s.business, mid, 'human', s.session);
}
// Row 224 C2-05b: the agent never supplies a host repo, commit or business. Its current
// holder and business entry are rechecked before/after awaits; runtime owns Git and queries.
async #requestLibraryLookup(s, { verb, args }) {
try {
this.#agent(s);
const business = this.#business(s.business);
const projects = Object.entries(business.projects ?? {}).filter(([, entry]) => entry.kind === 'library');
if (!projects.length || typeof this.#library?.lookup !== 'function') fail('library-not-configured');
const spec = LIBRARY_LOOKUPS[verb];
keys(args, ['project', ...spec.fields], spec.required);
if (!text(args.universe, 160)) fail('invalid-request');
if (args.project === undefined && projects.length !== 1) fail('invalid-request');
const project = args.project ?? projects[0][0];
if (!text(project, 160) || !projects.some(([name]) => name === project)) fail('library-not-configured');
const revision = JSON.stringify(business.projects[project]);
const authorize = () => {
this.#agent(s);
this.#processingGate(s, verb);
if (JSON.stringify(this.#business(s.business).projects?.[project]) !== revision) fail('library-not-configured');
};
const { project: ignored, ...query } = args;
authorize();
const result = await this.#library.lookup({ business, project }, { method: spec.method, args: query, authorize });
authorize();
this.#secretCheck(result);
return result;
} catch (error) {
const Failure = this.#library?.LibraryError;
throw this.#refused(s, Failure && error instanceof Failure ? new BusError(error.code) : error, { verb, args });
}
}
// C2-04 M4: only a verified human reads library text or status. Host Git
// functions stay injected, preserving this module's sandbox import closure.
async #requestLibrary(s, request) {
const { verb, args } = request;
if (Object.hasOwn(LIBRARY_LOOKUPS, verb)) return this.#requestLibraryLookup(s, request);
try {
const agent = verb === 'library.doc.write' || verb === 'library.doc.delete';
const b = this.#business(s.business);
let project = args.project, writer;
if (agent) {
// The caller gate precedes argument checks, including human and tester refusals.
if (s.tester) fail('tester-refused');
if (s.human || s.reader || !CREATIVE_DEFINITIONS.includes(b.roles?.[s.role]?.definition)
|| !b.roles[s.role].authority?.withinRole?.includes('library.write')) fail('library-write-refused');
this.#agent(s);
const fields = ['universe', 'path', 'base', ...(verb === 'library.doc.write' ? ['content'] : [])];
keys(args, fields, fields);
if (typeof args.universe !== 'string') fail('invalid-request');
const matches = Object.entries(b.projects ?? {}).filter(([, e]) => e.kind === 'library'
&& Object.hasOwn(e.universes ?? {}, args.universe));
if (matches.length !== 1) fail('project-not-configured');
project = matches[0][0];
writer = this.#libraryWriter(s, project);
} else {
this.#human(s);
const fields = verb === 'library.file' ? ['project', 'path'] : verb === 'library.sync' ? ['project', 'accept']
: verb === 'library.file.save' ? ['project', 'path', 'base', 'content']
: verb === 'library.revert' ? ['project', 'commit'] : ['project'];
keys(args, fields, verb === 'library.sync' ? ['project'] : fields);
}
if (typeof project !== 'string' || b.projects?.[project]?.kind !== 'library') fail('project-not-configured');
if (verb === 'library.revert' && (typeof args.commit !== 'string' || !/^[a-f0-9]{40}$/.test(args.commit))) fail('invalid-request');
if (agent || verb === 'library.file.save') {
if (args.base !== null && (typeof args.base !== 'string' || !/^[a-f0-9]{40}$/.test(args.base))) fail('invalid-request');
if (verb !== 'library.doc.delete' && (typeof args.content !== 'string' || args.content.includes('\0')
|| Buffer.byteLength(args.content, 'utf8') > 1024 * 1024
|| Buffer.from(args.content, 'utf8').toString('utf8') !== args.content)) fail('invalid-request');
}
const context = { business: b, project };
this.#human(s);
const fields = verb === 'library.file' ? ['project', 'path'] : verb === 'library.sync' ? ['project', 'accept'] : ['project'];
keys(args, fields, verb === 'library.sync' ? ['project'] : fields);
if (!this.#library?.readFile || !this.#library?.status) fail('project-not-configured');
if (verb === 'library.sync' && !this.#library.sync) fail('project-not-configured');
const context = { business: this.#business(s.business), project: args.project };
let result;
const method = agent ? 'writeDoc' : verb === 'library.file.save' ? 'saveFile'
: verb === 'library.revert' ? 'revert' : verb === 'library.file' ? 'readFile' : verb === 'library.status' ? 'status' : 'sync';
if (typeof this.#library?.[method] !== 'function') fail('project-not-configured');
if (agent) {
const op = verb === 'library.doc.delete' ? 'delete' : 'write';
result = await this.#library.writeDoc({ ...context, ...args }, { ...writer, op,
beforePush: () => { this.#processingWork(); this.#libraryWriter(s, project); },
onPushed: saved => {
try {
this.#store.transaction(() => {
this.#libraryWriteNotice(s, op, saved);
this.#event(s, 'action.allowed', { action: 'library.write', class: 'within-role', project, path: saved.path, commit: saved.commit });
});
} catch {
// A separate metadata-only sink survives a Console store failure. Never log args,
// file text, credentials or raw SQL/exception output.
try { this.#library.log?.({ event: 'library-notice-store-failed', code: 'outcome-unknown',
business: s.business, instance: s.role, op, commit: saved.commit }); } catch {}
fail('outcome-unknown');
}
} });
} else if (verb === 'library.file.save') {
this.#processingWork();
result = await this.#library.saveFile({ ...context, path: args.path, base: args.base, content: args.content });
} else if (verb === 'library.revert') {
this.#processingWork();
result = await this.#library.revert({ ...context, commit: args.commit });
} else if (verb === 'library.file') result = await this.#library.readFile({ ...context, path: args.path });
if (verb === 'library.file') result = await this.#library.readFile({ ...context, path: args.path });
else if (verb === 'library.status') result = await this.#library.status(context);
else {
// A fetch that did not move served still answers with the code, so the refusal is recorded.
const { state, code } = await this.#library.sync(context, { accept: args.accept ?? null });
if (code !== null) fail(code);
result = { project, ...state };
result = { project: args.project, ...state };
}
this.#secretCheck(result);
return result;
} catch (error) {
const Failure = this.#library?.LibraryError;
const mapped = Failure && error instanceof Failure ? new BusError(error.code) : error;
const refused = this.#refused(s, mapped, request);
// Once a push succeeded the remote effect is uncertain to the caller even if the store
// cannot record refusal evidence. Do not replace that with an ordinary storage refusal.
throw mapped instanceof BusError && mapped.code === 'outcome-unknown' ? mapped : refused;
throw this.#refused(s, Failure && error instanceof Failure ? new BusError(error.code) : error, request);
}
}
// The eight task verbs reach the trusted S3 handler here. It runs outside any transaction, gets the
+1 -1
View File
@@ -17,7 +17,7 @@ export class Client {
verb,
args,
}) + '\n';
if (Buffer.byteLength(request) > ([PROJECT_SAVE_VERB, 'library.file.save'].includes(verb) ? PROJECT_SAVE_REQUEST_MAX : 65536))
if (Buffer.byteLength(request) > (verb === PROJECT_SAVE_VERB ? PROJECT_SAVE_REQUEST_MAX : 65536))
return Promise.reject(new BusError('request-too-large'));
return new Promise((resolve, reject) => {
const socket = connect(this.path);
+9 -68
View File
@@ -4,7 +4,7 @@ import { fileURLToPath } from 'node:url';
import { Store } from './store.mjs';
import * as projectModule from '../../project/src/index.mjs';
import * as libraryModule from '../../library/src/index.mjs';
import { Broker, BusError, LIBRARY_FETCH_FIX } from './broker.mjs';
import { Broker, BusError } from './broker.mjs';
import { Credentials } from './credentials.mjs';
import { serve } from './server.mjs';
import { launchSettings } from '../../business/src/launch-settings.mjs';
@@ -24,7 +24,7 @@ import { busBusiness } from './business.mjs';
import { webService } from './web.mjs';
import { hostExecutor, sweepRunDir } from './host-run.mjs';
import { grantKeys, hostGrant, hostReference, sweepHostKeys } from './host-grant.mjs';
import { giteaGrant, giteaKeys, giteaStart, giteaReference } from './gitea-grant.mjs';
import { giteaGrant, giteaKeys, giteaStart } from './gitea-grant.mjs';
import { verifyPrincipal } from './principal.mjs';
import { loadAccess } from '../../business/src/access.mjs';
import { inspectInterpreter, recordInterpreterStart } from './interpreter.mjs';
@@ -87,38 +87,6 @@ export async function harnessLevels({ log = (e) => process.stderr.write(`plugins
}
return (name) => levels.get(name) ?? null;
}
// Row 224 C2-05b: a host-only adapter. A failed fetch keeps serving immutable old
// objects, as C2-03a requires; no caller may select a repo, commit or sync --accept.
export function createLibraryLookup({ dataRoot, sync, now = () => Date.now() }) {
const methods = { find: libraryModule.find, get: libraryModule.get, search: libraryModule.search,
manuscript: libraryModule.manuscript, universeInfo: libraryModule.universeInfo };
return async (context, { method, args, authorize }) => {
if (!Object.hasOwn(methods, method)) throw new libraryModule.LibraryError('query-argument-invalid', 'unknown lookup');
authorize();
const source = { ...context, dataRoot };
let state = await libraryModule.libraryStatus(source);
authorize();
// sage-2819 / dewey-0852: failed attempts also pace inline retries. Otherwise an
// outage makes every lookup refetch while lastFetch remains old or null.
const recentAttempt = Math.max(state.lastFetch === null ? -Infinity : Date.parse(state.lastFetch),
state.lastError === null ? -Infinity : Date.parse(state.lastError.at));
const age = now() - recentAttempt;
if (age > libraryModule.SYNC_INTERVAL_MS || age < 0) {
try { await sync(source); }
catch (error) {
// A timer may already be fetching this mirror. Its current served state is still safe.
if (!(error instanceof libraryModule.LibraryError) || error.code !== 'library-sync-busy') throw error;
}
authorize();
state = await libraryModule.libraryStatus(source);
}
if (!state.served) throw new libraryModule.LibraryError('library-commit', 'library has never been synced');
authorize();
return methods[method]({ repo: libraryModule.mirrorPath(source), commit: state.served,
mapping: libraryModule.checkMapping(context.business.projects[context.project]) }, args);
};
}
export async function startBroker({
dataRoot,
businesses,
@@ -193,11 +161,11 @@ export async function startBroker({
const levels=organization?await harnessLevels():()=>null;
const settings=organization?launchSettings({...organization,sessions:()=>readSessions(dataRoot),levels}):null;
// Row 194 (#1692, brief item 8, row 199 D13): a fire or a delete revokes the agent's credentials
// after the writer's checks and before its write. Fire revokes each service of the entry and keeps
// the store directory, delete calls remove (sage-1593). A service the running bus doesn't know (an
// agent created since the start) has nothing in memory, so it goes on, and then no token or tmp
// file may remain in the agent's store directory (sage-1592). Any failure stops the verb with the
// file unchanged.
// after the writer's checks and before its write, under the writer's lock (row 239). Fire revokes
// each service of the entry and keeps the store directory, delete calls remove (sage-1593). A
// service the running bus doesn't know (an agent created since the start) has nothing in memory,
// so it goes on, and then no token or tmp file may remain in the agent's store directory
// (sage-1592). Any failure stops the verb with the file unchanged.
const revokeFailed = (message) => new OrganizationError('credential-revoke-failed', message);
function revoke(business, agent, how, services) {
const instance = business + '/' + agent;
@@ -255,26 +223,11 @@ export async function startBroker({
}
// C2-03a: the slot is <configDir>/secrets/<business>/library-gitea (design 10 step 4). Sync only
// checks that it is there; the askpass helper reads it.
// C2-03b: the broker chooses. The chief's grant store file once a chief has Gitea grant evidence,
// the slot before that, or a refusal sync records. The answer carries no file to sync but this one.
const slotDir = librarySync?.configDir ?? organization?.dir ?? null;
const fetchCredential = business => {
const choice = broker.libraryFetchCredential(business.id);
if (choice.kind === 'chief')
return { kind: 'chief', user: choice.user, file: storeRoot ? giteaReference(storeRoot, business.id, choice.agent).file : null };
if (choice.kind === 'slot') return { kind: 'slot', file: slotDir ? join(slotDir, 'secrets', business.id, libraryModule.SLOT) : null };
return { refused: choice.refused };
};
const syncOptions = business => ({
credential: fetchCredential(business),
slot: slotDir ? join(slotDir, 'secrets', business.id, libraryModule.SLOT) : null,
...(librarySync ? { command: librarySync.command } : {}),
});
const humanWriteOptions = context => {
const mapping = libraryModule.checkMapping(context.business.projects[context.project]);
if (!mapping.editor) throw new libraryModule.LibraryError('library-mapping-invalid', 'editor is required');
return { credential: libraryModule.humanCredential(context, { user: mapping.editor.user, configDir: slotDir }),
...(librarySync ? { command: librarySync.command } : {}) };
};
// Row 194 (#1692, D3): after every write that commits, the broker takes the business as a restart
// would load it. The credential references, the project roots the Credentials store protects
// and the tracker bots are fixed at start (the Credentials store, the tasks adapter), so a file
@@ -348,20 +301,9 @@ export async function startBroker({
store,
businesses,
library: {
log: entry => process.stderr.write(`library: ${JSON.stringify(entry)}\n`),
lookup: createLibraryLookup({ dataRoot, sync: context =>
processing.work(() => libraryModule.sync(context, syncOptions(context.business))) }),
readFile: context => libraryModule.readLibraryFile({ ...context, dataRoot }),
status: context => libraryModule.libraryStatus({ ...context, dataRoot }),
sync: (context, { accept }) => processing.work(() => libraryModule.sync({ ...context, dataRoot }, { ...syncOptions(context.business), accept })),
// C2-02: trusted references only. The askpass helper alone opens a credential file.
writeDoc: (context, options) => processing.work(() => libraryModule.writeLibraryDoc({ ...context, dataRoot }, {
...options, credential: { ...options.credential,
file: storeRoot ? giteaReference(storeRoot, context.business.id, options.credential.agent).file : null },
...(librarySync ? { command: librarySync.command } : {}),
})),
saveFile: context => processing.work(() => libraryModule.saveLibraryFile({ ...context, dataRoot }, humanWriteOptions(context))),
revert: context => processing.work(() => libraryModule.revertLibraryCommit({ ...context, dataRoot }, humanWriteOptions(context))),
LibraryError: libraryModule.LibraryError,
},
project: {
@@ -623,8 +565,7 @@ export async function startBroker({
for (const { business, project } of timed) {
try {
const { code } = await libraryModule.sync({ business, project, dataRoot }, syncOptions(business));
if (code !== null) syncLog({ event: 'library-sync-held', business: business.id, project, code,
...(code === 'library-fetch-no-grant' ? { fix: LIBRARY_FETCH_FIX } : {}) });
if (code !== null) syncLog({ event: 'library-sync-held', business: business.id, project, code });
} catch (e) {
if (e?.code === 'library-sync-busy') continue;
syncLog({ event: 'library-sync-refused', business: business.id, project,
+2 -4
View File
@@ -6,9 +6,7 @@ import { createPeerReader } from './peercred.mjs';
const LIMIT = 65536;
// Row 148: a document save may carry up to 1 MiB of text. Only a request that names that verb near
// its start (the proof object comes first) may pass LIMIT; the parsed verb is checked again below.
const PROJECT_SAVE_AT_START = new RegExp(`"verb":"${PROJECT_SAVE_VERB.replaceAll('.', '\\.')}"`);
const LIBRARY_SAVE_AT_START = /"verb":"library\.file\.save"/;
const SAVE_VERB_AT_START = { test: text => PROJECT_SAVE_AT_START.test(text) || LIBRARY_SAVE_AT_START.test(text) };
const SAVE_VERB_AT_START = new RegExp(`"verb":"${PROJECT_SAVE_VERB.replaceAll('.', '\\.')}"`);
// One request per connection. There is deliberately no reconnect/retry or SQL verb.
// `tasks` ({handle, timeout}) is the trusted S3 adapter; only the eight task verbs reach it.
// `web` is the trusted web service (web.mjs), or a function from a business id to one (or null); only
@@ -62,7 +60,7 @@ export async function serve({ broker, path, authenticateHuman = null, authentica
try {
if (end !== input.length - 1) throw new BusError('invalid-envelope');
const r = JSON.parse(input.subarray(0, end).toString('utf8'));
if (input.length > LIMIT && ![PROJECT_SAVE_VERB, 'library.file.save'].includes(r?.verb)) throw new BusError('request-too-large');
if (input.length > LIMIT && r?.verb !== PROJECT_SAVE_VERB) throw new BusError('request-too-large');
if (
!r ||
Array.isArray(r) ||
+5 -2
View File
@@ -20,7 +20,8 @@ import { Client } from "../src/client.mjs";
const baselines = {
"packages/bus/src/human.mjs": "bb13c146717cdc46d75d157177e400edac4d3e10f14fe511027a25fd44cec885",
"packages/bus/src/human-cli.mjs": "271b9781d73cf31cc562a56180e3ebcd725b5fde148a83347a201fdef2fc28af",
"packages/cli/src/transport.mjs": "5129c44b4d9f642e825344df65c9bfb4bac4fc8d6b25343b42d39853dbd40774",
// Row 239 (#1745): EXIT outcome-unknown-revoked 1; no proof or transport change.
"packages/cli/src/transport.mjs": "662642a8ce739fcb6c188ad07125a94e008c8a305eced127c8041d472c56e55b",
// 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
@@ -29,7 +30,9 @@ const baselines = {
// Row 194 (#1692, brief item 7, sage-1610 a): organization-tracker-required 400 and
// organization-tracker-bot-taken 409; no proof or transport change.
// Row 301 (#1808, mos-1449): the user transport moved from user-bus.mjs into bus.mjs; humanCall unchanged.
"packages/webui/src/bus.mjs": "604092cb706b152d458f299ff1071f6cd488774629012f96b672f7e9a16c0b2c",
// Row 239 (#1745): outcome-unknown-revoked joins OPEN (duckworth-0165 C1), and STATUS gets
// revision-conflict-revoked 409 and outcome-unknown-revoked 503; no proof or transport change.
"packages/webui/src/bus.mjs": "e3f52172054676b7982eda420ce051854d404c3f0f81834c3f81138bd91c2a89",
};
const repoFile = path => new URL("../../../" + path, import.meta.url);
+2 -2
View File
@@ -7,7 +7,7 @@ import { fileURLToPath } from 'node:url';
import { Store } from '../src/store.mjs';
import { Broker } from '../src/broker.mjs';
import { startBroker } from '../src/runtime.mjs';
import { businessDoc, FAR_DATE, rolesCopy, systemFor, writeJson } from '../../business/tests/helpers.mjs';
import { businessDoc, rolesCopy, systemFor, writeJson } from '../../business/tests/helpers.mjs';
// Row 213 (C2-08, #1714, Case 2 design 5.1): a creative instance talks with the user only, and it has
// no decision channel (M6). The messaging lists are read from the shipped role files.
@@ -98,7 +98,7 @@ async function runtime(t) {
const rolesDir = rolesCopy(root);
const doc = businessDoc(root, 'demo');
doc.plugins = { ...doc.plugins, harness: ['pi'] };
doc.roles.bean = { definition: 'companion', credentials: { gitea: { store: true, rotateBy: FAR_DATE } } };
doc.roles.bean = { definition: 'companion' };
for (const r of Object.values(doc.roles)) r.vars = { harness: 'pi', model: 'claude-sonnet-5-5', thinking: 'high', ...r.vars };
// Only bean names the sonnet key, so the chief may still change every other key.
for (const [name, r] of Object.entries(doc.roles)) if (name !== 'bean') r.vars.model = 'claude-opus-5-5';
@@ -133,8 +133,9 @@ async function setup(t) {
},
};
// The fake organization writer. A fire delists the name and a delete drops the role, each with a
// reload, as the runtime reloads after a commit. `fireError` makes the fire's write refuse.
const org = { log: [], fireError: null };
// reload, as the runtime reloads after a commit. `fireError` makes the fire's write refuse, and
// `deleteError` the delete's (row 239).
const org = { log: [], fireError: null, deleteError: null };
const sw = { state: { version: 1, halted: false, generation: GENERATION } };
let broker;
const organization = (business, op, args) => {
@@ -146,6 +147,7 @@ async function setup(t) {
return { revision: REV, transaction: 't-' + org.log.length };
}
if (op === 'instances.set') {
if (org.deleteError) throw org.deleteError;
delete doc.roles[args.instance];
doc.launch.instances = doc.launch.instances.filter((n) => n !== args.instance);
broker.reloadBusiness('demo', doc);
@@ -952,3 +954,44 @@ test("row 281 T14 (N1, sage-2653): a host removed under an undecided decision st
assert.ok(!f.doc.launch.instances.includes('coder'));
assert.equal(f.grantEvents().filter((e) => e.action === 'grant.revoke.refused').length, 1);
});
// Row 239 (#1745): the writer marks an error raised after its own revoke ran (revoked: true), and the
// bus names it, so the human reads that the tokens may already be revoked. Unmarked, today's code.
test("row 239 T4: a refusal after the writer's revoke is named -revoked, in the job's fire.failed and notice, a synchronous fire and a delete", async (t) => {
const f = await setup(t);
await f.approveHost('coder', 'web1');
f.org.fireError = Object.assign(new Error('refused'), { code: 'revision-conflict', revoked: true });
const out = f.fire('coder');
await f.broker.grantsIdle();
const [failed] = f.allowed('fire.failed');
assert.deepEqual([failed.body.job, failed.body.step, failed.body.code], [out.job, 'B', 'revision-conflict-revoked']);
const [message] = f.inbox();
assert.ok(message.includes('(revision-conflict-revoked). Its credential tokens may already be revoked. The instance is still firing.'), message);
// helper has no grant, so its fire writes synchronously and answers with the code.
await rejects(() => f.fire('helper'), 'revision-conflict-revoked');
// Any other marked error: the write may have landed.
f.org.fireError = Object.assign(new Error('EIO: i/o error'), { code: 'EIO', revoked: true });
await rejects(() => f.fire('helper'), 'outcome-unknown-revoked');
f.org.fireError = Object.assign(new Error('refused'), { code: 'revision-conflict' });
await rejects(() => f.fire('helper'), 'revision-conflict');
f.org.fireError = null;
f.org.deleteError = Object.assign(new Error('refused'), { code: 'revision-conflict', revoked: true });
assert.equal(f.remove('helper').code, 'revision-conflict-revoked');
f.org.deleteError = Object.assign(new Error('EIO: i/o error'), { code: 'EIO', revoked: true });
assert.equal(f.remove('helper').code, 'outcome-unknown-revoked');
f.org.deleteError = Object.assign(new Error('refused'), { code: 'revision-conflict' });
assert.equal(f.remove('helper').code, 'revision-conflict');
});
test("row 239 T4b: an unmarked step B refusal keeps its code, and the notice says nothing of the tokens", async (t) => {
const f = await setup(t);
await f.approveHost('coder', 'web1');
f.org.fireError = Object.assign(new Error('refused'), { code: 'revision-conflict' });
const out = f.fire('coder');
await f.broker.grantsIdle();
const [failed] = f.allowed('fire.failed');
assert.deepEqual([failed.body.job, failed.body.code], [out.job, 'revision-conflict']);
const [message] = f.inbox();
assert.ok(message.includes('(revision-conflict). The instance is still firing.'), message);
assert.ok(!message.includes('may already be revoked'), message);
});
-16
View File
@@ -256,22 +256,6 @@ test('X-G1: a creative role, a role without identity and a missing or due slot r
for (const f of [creative, bare, noSlot, due, elsewhere]) assert.equal(f.gitea.requests.length, 0);
});
// Row 285 (#1790, sage-2921): the chief's definition declares gitea for a read grant only, and this path
// mints SEAT_SCOPES, so a chief with identity and publish still refuses at raise and stores nothing.
test('X-G1: the chief of staff refuses at raise, whatever its definition, identity and publish declare', async (t) => {
const f = await setup(t, {
business: (b) => {
b.definitions['chief-of-staff'].credentials = [{ service: 'gitea' }];
b.roles.chief.identity = { name: 'Chief', email: '[email protected]', gitea: { url: b.roles.coder.identity.gitea.url, user: 'demo-chief' } };
b.roles.chief.publish = ['app'];
},
});
const n = f.store.get('SELECT count(*) AS n FROM decisions').n;
await rejects(f.raise({ agent: 'chief' }), 'gitea-not-declared');
assert.equal(f.store.get('SELECT count(*) AS n FROM decisions').n, n);
assert.equal(f.gitea.requests.length, 0);
});
test('X-G2: admin set refuses each failed check and writes nothing, then writes the slot once', async (t) => {
const f = await setup(t, { slot: false });
const set = (token, over = {}) =>
@@ -1,317 +0,0 @@
// C2-03b (#1791, design 7.2): the credential the library fetch runs with. The chief's grant store file
// once a chief has Gitea grant evidence, slot library-gitea before that, and a refusal otherwise.
// T7's revoked and fired cases and T9's revoked case run the broker's real paths (dewey-0864): the
// chief's grant through decision.raise and the human's yes against the fake Gitea in fake-gitea-api.mjs
// on 127.0.0.1, then grants.revoke or instance.fire. roles/chief-of-staff.json names no gitea credential,
// so these tests give chief-of-staff one in their own definitions, as gitea-grant.test.mjs gives coder
// one. The choice function's other checks (listed, a fire under way, held, two chiefs, another project)
// use fixtures: the evidence and the gitea_grants row go in by SQL, as gitea-grant.test.mjs does for
// decisions. Tokens are made up or the fake's, and only ever compared.
import test from 'node:test';
import assert from 'node:assert/strict';
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { randomBytes } from 'node:crypto';
import { Store } from '../src/store.mjs';
import { Broker, GRANT_EVIDENCE, LIBRARY_FETCH_FIX, writeGrantEvent } from '../src/broker.mjs';
import { Credentials } from '../src/credentials.mjs';
import { giteaGrant, giteaKeys, giteaStart } from '../src/gitea-grant.mjs';
import { startBroker } from '../src/runtime.mjs';
import { gitEnv } from '../../seat/src/checkout.mjs';
import { mappingEntry, repo } from '../../library/tests/helpers.mjs';
import * as library from '../../library/src/index.mjs';
import { fakeGiteaApi } from './fake-gitea-api.mjs';
import { grantDecision } from './host-fixtures.mjs';
import { rolesCopy, systemFor } from '../../business/tests/helpers.mjs';
const AT = '2026-10-22T00:00:00.000Z';
const REV = 'b'.repeat(64);
const SLOT_TOKEN = 'fixture-token-2c90-made-up-0048';
const role = { authority: { withinRole: [], crossRole: [] } };
const none = { authority: { withinRole: ['message.send'], crossRole: [] } };
const options = [{ key: 'yes', text: 'Yes' }, { key: 'no', text: 'No' }];
const chiefAuthority = JSON.parse(readFileSync(fileURLToPath(new URL('../../../roles/chief-of-staff.json', import.meta.url)), 'utf8')).authority;
const SWITCH = { version: 1, halted: false, generation: '0b6e7f6e-4c1d-4a8e-9a51-6d2f3c4b5a69' };
const dayFrom = (n) => new Date(Date.now() + n * 86400000).toISOString().slice(0, 10);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function until(fn, ms = 10000) {
const end = Date.now() + ms;
while (!fn()) {
if (Date.now() > end) throw new Error('timed out');
await sleep(10);
}
}
const makeBusiness = ({ chief = true, instances = null } = {}) => ({
id: 'acme', human: 'jason', arbiters: { technical: 'coder', delivery: 'coder' },
roles: { ...(chief ? { chief: { definition: 'chief-of-staff', ...role } } : {}), coder: { definition: 'coder', ...role } },
projects: { books: { ...mappingEntry(), user: 'books-bot' } },
...(instances ? { launch: { instances } } : {}),
});
// A Gitea grant for `agent` as row 236 leaves it: the decision, the user and grant rows, and
// grant.applied. `project` is the grant's target; the evidence check names no project.
function grant(store, agent, { user = agent + '-bot', project = 'books', row = true } = {}) {
const decision = grantDecision(store, { business: 'acme', grant: { method: 'gitea', agent, target: { projects: [project] }, rotateBy: '2099-01-01' } });
writeGrantEvent(store, AT, 'acme', { operation: 'grant.gitea', decision }, decision);
writeGrantEvent(store, AT, 'acme', { action: 'grant.applied', method: 'gitea', agent, grantDecision: decision, user, projects: [project] }, decision);
if (!row) return decision;
store.run('INSERT INTO gitea_users(business,agent,user,id,nonce,decision) VALUES(?,?,?,?,?,?)', 'acme', agent, user, 7, randomBytes(8).toString('hex'), decision);
store.run('INSERT INTO gitea_grants(business,agent,user,token_id,token_name,projects,rotate_by,decision) VALUES(?,?,?,?,?,?,?,?)',
'acme', agent, user, 11, 'mosaic-' + agent, JSON.stringify([project]), '2099-01-01', decision);
return decision;
}
function world(t, options) {
const root = mkdtempSync(join(tmpdir(), 'bus-library-credential-')), store = new Store(root);
t.after(() => { store.close(); rmSync(root, { recursive: true, force: true }); });
const business = makeBusiness(options);
const held = new Set();
const broker = new Broker({ store, businesses: { acme: business }, giteaKeys: { held: (b, a) => held.has(b + '/' + a) } });
return { store, business, broker, held, choose: () => broker.libraryFetchCredential('acme') };
}
// The business for the real paths. `boss` is launch.by: instance.fire is the launch.by role's verb and
// refuses its own name (organization-instance-referenced), so the fired chief is the one listed
// chief-of-staff instance, fired by boss. The grant targets project app; books is the library.
function verbDoc(url) {
return {
id: 'acme', human: 'jason', arbiters: { technical: 'boss', delivery: 'boss' },
roles: {
boss: { definition: 'pm', authority: chiefAuthority },
chief: { definition: 'chief-of-staff', ...none, identity: { name: 'Chief', email: '[email protected]', gitea: { url, user: 'acme-chief' } }, publish: ['app'] },
coder: { definition: 'coder', ...none },
},
definitions: {
'chief-of-staff': { roleVersion: 2, credentials: [{ service: 'gitea' }] },
pm: { roleVersion: 2, credentials: [] },
coder: { roleVersion: 2, credentials: [] },
},
projects: { app: { remote: `${url}/acme/app` }, books: { ...mappingEntry(), user: 'books-bot' } },
launch: { by: 'boss', instances: ['chief', 'coder'] },
};
}
// A bare broker on the real grant paths, as gitea-grant.test.mjs and fire-revokes-grants.test.mjs run
// it. A second one on the same data root and store picks the grant up as runtime.mjs does: giteaStart,
// then Credentials with its references and held list. The admin slot sits outside storeRoot's config
// dir, so a runtime started on that dir finds no admin slot.
async function verbWorld(t, opts = {}) {
const dir = mkdtempSync(join(tmpdir(), 'bus-library-verbs-'));
t.after(() => rmSync(dir, { recursive: true, force: true }));
let gitea = opts.gitea;
if (!gitea) {
gitea = await fakeGiteaApi(t, join(dir, 'tls'));
gitea.addUser('acme');
gitea.addRepo('acme', 'app');
}
const adminDir = join(dir, 'admin');
mkdirSync(adminDir, { mode: 0o700 });
const dataRoot = opts.dataRoot ?? join(dir, 'data');
mkdirSync(dataRoot, { recursive: true, mode: 0o700 });
const storeRoot = opts.storeRoot ?? join(dir, 'secrets', 'agents');
const doc = opts.doc ?? verbDoc(gitea.url);
const store = new Store(dataRoot);
const references = {};
const { held } = giteaStart(store, storeRoot, { acme: doc }, references);
const credentials = new Credentials({ references, storeRoot, dataRoot, held });
let open = true;
const close = () => {
if (!open) return;
open = false;
credentials.close();
store.close();
};
t.after(close);
const grantApi = giteaGrant({ configDir: adminDir, ca: gitea.ca, timeoutMs: 5000 });
grantApi.writeAdmin('acme', gitea.adminToken, { url: gitea.url, account: 'mosaic-grant', rotateBy: dayFrom(60), setAt: AT });
let broker;
const organization = (business, op, args) => {
if (op === 'instance.fire') {
doc.launch.instances = doc.launch.instances.filter((n) => n !== args.name);
broker.reloadBusiness('acme', doc);
return { revision: REV, transaction: 't-fire' };
}
return { revision: REV };
};
broker = new Broker({
store, businesses: { acme: structuredClone(doc) }, secretCheck: (value) => credentials.assertClean(value), organization,
processing: { read: () => SWITCH }, giteaGrant: grantApi, giteaKeys: giteaKeys({ credentials, storeRoot }),
});
const boss = broker.bindLaunch({ business: 'acme', role: 'boss', run: 'boss-run', harness: 'pi', address: 'boss' });
broker.request(boss, { verb: 'role.claim' });
const human = broker.bindHuman({ business: 'acme', human: 'jason', via: 'cli', outsideAgent: true });
const events = () => store.all(`SELECT body FROM events WHERE business='acme' AND ${GRANT_EVIDENCE} ORDER BY seq`).map((e) => JSON.parse(e.body));
const ended = (id) => events().findLast((e) => e.grantDecision === id && ['grant.applied', 'grant.failed'].includes(e.action));
const row = () => store.get("SELECT 1 FROM gitea_grants WHERE business='acme' AND agent='chief'");
const approveChief = async () => {
const d = await broker.request(boss, {
verb: 'decision.raise',
args: {
action: 'credential.mint', question: 'Grant chief Gitea?', options, recommendation: 'yes', blocking: false,
grant: { method: 'gitea', agent: 'chief', target: { projects: ['app'] }, rotateBy: dayFrom(30) },
},
});
broker.request(human, { verb: 'decision.resolve', args: { id: d.id, choice: 'yes' } });
await until(() => ended(d.id));
await broker.giteaIdle();
assert.equal(ended(d.id).action, 'grant.applied', 'the chief\'s grant landed');
assert.ok(row(), 'with its gitea_grants row');
};
const revoke = async () => {
await broker.request(human, { verb: 'grants.revoke', args: { service: 'gitea', agent: 'chief', reason: 'test' } });
await broker.giteaIdle();
assert.equal(row(), undefined, 'grants.revoke deleted the row');
assert.ok(events().some((e) => e.action === 'grant.revoked' && e.agent === 'chief'));
};
const fire = async () => {
await broker.request(boss, { verb: 'instance.fire', args: { name: 'chief', reason: 'the work is done' } });
await until(() => !doc.launch.instances.includes('chief'));
await broker.grantsIdle();
assert.equal(row(), undefined, 'the fire\'s step G deleted the row (row 281)');
};
return { gitea, doc, store, broker, storeRoot, row, approveChief, revoke, fire, close, choose: () => broker.libraryFetchCredential('acme') };
}
const REFUSED = { refused: 'library-fetch-no-grant', fix: LIBRARY_FETCH_FIX };
test('C2-03b T6: the slot before any chief evidence, then the listed chief\'s live grant', t => {
const w = world(t);
assert.deepEqual(w.choose(), { kind: 'slot' });
grant(w.store, 'coder');
assert.deepEqual(w.choose(), { kind: 'slot' }, 'a seat grant is not the chief\'s: the chief entry keeps the fallback');
grant(w.store, 'chief', { user: 'chief-bot' });
assert.deepEqual(w.choose(), { kind: 'chief', agent: 'chief', user: 'chief-bot' });
assert.deepEqual(new Broker({ store: w.store, businesses: { acme: w.business } }).libraryFetchCredential('acme'), REFUSED,
'a bus with no grant store refuses rather than guess');
assert.throws(() => w.broker.libraryFetchCredential('other'), { code: 'unknown-business' });
assert.equal(LIBRARY_FETCH_FIX, 'add the chief of staff, or grant the library through C2-21');
});
test('C2-03b T7: a chief revoked through grants.revoke or fired through instance.fire refuses, and the fallback stays ended', { timeout: 60000 }, async t => {
const revoked = await verbWorld(t);
assert.deepEqual(revoked.choose(), { kind: 'slot' });
await revoked.approveChief();
assert.deepEqual(revoked.choose(), { kind: 'chief', agent: 'chief', user: 'acme-chief' });
await revoked.revoke();
assert.deepEqual(revoked.choose(), REFUSED, 'revoked');
const fired = await verbWorld(t);
await fired.approveChief();
assert.deepEqual(fired.choose(), { kind: 'chief', agent: 'chief', user: 'acme-chief' });
await fired.fire();
assert.equal(fired.doc.launch.instances.includes('chief'), false, 'delisted');
assert.ok(fired.doc.roles.chief, 'roles[chief] remains after a fire, so its evidence still ends the fallback');
assert.deepEqual(fired.choose(), REFUSED, 'fired');
});
test('C2-03b T7 choice checks: delisted, a fire under way and held each refuse; a rehire lists the chief again', t => {
const delisted = world(t, { instances: ['coder'] });
grant(delisted.store, 'chief');
assert.deepEqual(delisted.choose(), REFUSED, 'delisted with the row still there');
delisted.business.launch.instances.push('chief');
assert.deepEqual(delisted.choose(), { kind: 'chief', agent: 'chief', user: 'chief-bot' }, 'a rehire lists it again');
delisted.store.run("INSERT INTO events(id,at,business,kind,actor_role,actor_run,subject,body) VALUES('f1',?,?,'action.allowed','chief','run','chief',?)",
AT, 'acme', JSON.stringify({ action: 'fire.stopped' }));
assert.deepEqual(delisted.choose(), REFUSED, 'a fire under way');
const held = world(t);
grant(held.store, 'chief');
held.held.add('acme/chief');
assert.deepEqual(held.choose(), REFUSED, 'held');
});
test('C2-03b T8: a chief grant on another project ends the fallback, and two listed chiefs refuse library-fetch-no-grant', t => {
const w = world(t);
grant(w.store, 'chief', { project: 'other-project', row: false });
assert.deepEqual(w.choose(), REFUSED);
const two = world(t);
grant(two.store, 'chief');
assert.deepEqual(two.choose(), { kind: 'chief', agent: 'chief', user: 'chief-bot' });
two.business.roles.second = { definition: 'chief-of-staff', ...role };
assert.deepEqual(two.choose(), REFUSED, 'two chief-of-staff entries, both listed: one chief only');
two.business.launch = { instances: ['coder'] };
assert.deepEqual(two.choose(), REFUSED, 'neither listed');
});
test('C2-03b departure (sage-2928): with no chief entry, any Gitea grant evidence refuses', t => {
const w = world(t, { chief: false });
assert.deepEqual(w.choose(), { kind: 'slot' });
grant(w.store, 'coder');
assert.deepEqual(w.choose(), REFUSED);
});
// T9 and the runtime wiring. The timer and library.sync both take the broker's choice: the chief's
// store file, the slot, or a refusal that runs no git even with the slot at 0000. The grant and its
// revoke run through the real paths on the runtime's own data root and store.
test('C2-03b T9 runtime: the chief\'s store file and user, then a real revoke that runs no git with the slot at 0000', { timeout: 60000 }, async t => {
const f = repo(t), root = f.root, dataRoot = join(root, 'data');
mkdirSync(dataRoot, { mode: 0o700 });
const storeRoot = join(root, 'secrets', 'agents');
// A scratch roles/ whose chief-of-staff carries a gitea credential, as row 285 ships it
// (case2-rows.md:1823-1824), so the runtime's definitions match the ones the grant ran under
// (dewey-0869). Rebased onto 285, the copy needs no edit.
const rolesDir = rolesCopy(root);
const chiefRole = join(rolesDir, 'chief-of-staff.json');
const chiefDefinition = JSON.parse(readFileSync(chiefRole, 'utf8'));
if (!chiefDefinition.credentials.some(c => c.service === 'gitea')) chiefDefinition.credentials.push({ service: 'gitea' });
writeFileSync(chiefRole, JSON.stringify(chiefDefinition, null, 2) + '\n');
const slot = join(root, 'secrets', 'acme', library.SLOT);
mkdirSync(join(root, 'secrets', 'acme'), { recursive: true, mode: 0o700 });
writeFileSync(slot, SLOT_TOKEN + '\n', { mode: 0o600 });
const granted = await verbWorld(t, { dataRoot, storeRoot });
await granted.approveChief();
granted.close();
const gitea = granted.gitea;
const chiefFile = join(storeRoot, 'acme', 'chief', 'gitea');
assert.ok(existsSync(chiefFile), 'the grant wrote the chief\'s store file');
const tokens = () => [SLOT_TOKEN, ...gitea.issued];
const calls = [], lines = [], write = process.stderr.write;
const command = (kind, url, opts) => { calls.push({ kind, opts }); return { argv: ['--version'], env: gitEnv() }; };
process.stderr.write = function (chunk, ...rest) {
if (String(chunk).startsWith('library: ')) { lines.push(String(chunk)); return true; }
return write.call(this, chunk, ...rest);
};
t.after(() => { process.stderr.write = write; });
const start = () => startBroker({ dataRoot, businesses: { acme: verbDoc(gitea.url) }, organization: { dir: root, rolesDir, system: systemFor(root) },
librarySync: { command, intervalMs: 50 } });
const untilAsync = async (fn) => { const end = Date.now() + 10000; while (!fn() && Date.now() < end) await sleep(10); };
let runtime = await start();
await untilAsync(() => calls.length >= 1);
const human = runtime.broker.bindHuman({ business: 'acme', human: 'jason', via: 'cli', outsideAgent: true });
await runtime.broker.request(human, { verb: 'library.sync', args: { project: 'books' } }).catch(e => e);
// webby-0151 R3: library.status names the kind and user of the last fetch, never the file or value.
const shown = await runtime.broker.request(human, { verb: 'library.status', args: { project: 'books' } });
assert.deepEqual(shown.credential, { kind: 'chief', user: 'acme-chief' });
assert.equal(JSON.stringify(shown).includes(chiefFile) || tokens().some(tok => JSON.stringify(shown).includes(tok)), false);
await runtime.close();
assert.ok(calls.length >= 2, 'the timer and the verb');
assert.ok(calls.every(c => c.kind === 'fetch' && c.opts.slot === chiefFile && c.opts.user === 'acme-chief'), 'the chief\'s file and user, never the slot');
// Revoked through grants.revoke: the next start refuses before git, and the log names the fix.
const revoking = await verbWorld(t, { dataRoot, storeRoot, gitea });
await revoking.revoke();
revoking.close();
chmodSync(slot, 0o000);
calls.length = 0; lines.length = 0;
runtime = await start();
await untilAsync(() => lines.length >= 1);
const human2 = runtime.broker.bindHuman({ business: 'acme', human: 'jason', via: 'cli', outsideAgent: true });
await assert.rejects(runtime.broker.request(human2, { verb: 'library.sync', args: { project: 'books' } }), { code: 'library-fetch-no-grant' });
const after = await runtime.broker.request(human2, { verb: 'library.status', args: { project: 'books' } });
assert.equal(after.lastError.code, 'library-fetch-no-grant');
assert.equal(after.credential, null);
await runtime.close();
assert.equal(calls.length, 0, 'no git with a refusal');
assert.equal(statSync(slot).mode & 0o777, 0, 'the slot was never fixed up');
assert.deepEqual(JSON.parse(lines[0].slice('library: '.length)),
{ event: 'library-sync-held', business: 'acme', project: 'books', code: 'library-fetch-no-grant', fix: LIBRARY_FETCH_FIX });
for (const line of lines) assert.equal(tokens().some(tok => line.includes(tok)), false);
const mirror = library.mirrorPath({ business: verbDoc(gitea.url), project: 'books', dataRoot });
const state = await library.readSyncState(mirror, { branch: 'main' });
assert.equal(state.lastError.code, 'library-fetch-no-grant');
assert.equal(state.credential, null);
});
-251
View File
@@ -1,251 +0,0 @@
// Row 224: exercise broker authorization, real C2-05a queries and host served snapshots.
// All bodies and remotes are made up. External sync is replaced only at its trusted host seam.
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { Store } from '../src/store.mjs';
import { Broker } from '../src/broker.mjs';
import { createLibraryLookup, startBroker } from '../src/runtime.mjs';
import { serve } from '../src/server.mjs';
import { Client } from '../src/client.mjs';
import * as library from '../../library/src/index.mjs';
import { scratchRepo, note } from '../../library/tests/query-fixture.mjs';
import { mappingEntry, git } from '../../library/tests/helpers.mjs';
const NOW = Date.parse('2026-10-22T16:00:00.000Z');
const VERBS = ['library.find', 'library.get', 'library.search', 'library.manuscript', 'library.universe'];
const GET = { universe: 'harbor', path: 'Book One/Characters/Tomas.md' };
const ARGS = [
{ universe: 'harbor', query: 'Tomas' }, GET,
{ universe: 'harbor', text: 'ferry' }, { universe: 'harbor', book: 'Book One' }, { universe: 'harbor' },
];
const TEXTS = {
'Book One/Characters/Tomas.md': note('character', 'Tomas', 'He runs the ferry. [[Elsewhere]]'),
'Book One/Chapters/01.md': '# A ferry\nOne line.\n',
'Book One/Playground/What If.md': note('character', 'Maybe Tomas', 'Unwritten ferry.'),
'Second World/Characters/Elsewhere.md': note('character', 'Elsewhere', 'Other ferry.'),
};
async function world(t, { projects, adapter, claimed = true, now = () => NOW, files = TEXTS } = {}) {
const f = scratchRepo(t, files), dataRoot = join(f.root, 'data');
mkdirSync(dataRoot);
const business = { id: 'acme', human: 'jason', vars: { 'bus.tester': true },
projects: projects ?? { books: mappingEntry() }, arbiters: { technical: 'coder', delivery: 'coder' },
roles: { coder: { definition: 'coder', authority: { withinRole: [], crossRole: [] } } } };
const context = { business, project: 'books', dataRoot };
let mirror = null, state = null, fetches = 0;
if (business.projects.books?.kind === 'library') {
mirror = await library.ensureMirror(context);
git(f.repo, '-c', 'protocol.file.allow=always', 'push', '-q', mirror, 'HEAD:refs/heads/served');
state = { version: 1, branch: 'main', served: f.commit, lastFetch: new Date(NOW).toISOString(),
lastError: null, diverged: null, problems: [] };
writeFileSync(join(mirror, library.SYNC_STATE_FILE), JSON.stringify(state), { mode: 0o600 });
}
const setState = patch => {
state = { ...state, ...patch };
writeFileSync(join(mirror, library.SYNC_STATE_FILE), JSON.stringify(state), { mode: 0o600 });
};
const lookup = createLibraryLookup({ dataRoot, now, sync: async () => {
fetches++;
setState({ lastFetch: new Date(now()).toISOString() });
return { state, code: null };
} });
const store = new Store(dataRoot);
t.after(() => store.close());
const broker = new Broker({ store, businesses: { acme: business },
library: adapter ?? { lookup, LibraryError: library.LibraryError } });
const agent = broker.bindLaunch({ business: 'acme', role: 'coder', run: 'r224', harness: 'pi' });
if (claimed) broker.request(agent, { verb: 'role.claim' });
const human = broker.bindHuman({ business: 'acme', human: 'jason', via: 'cli', outsideAgent: true });
const reader = broker.bindReader({ business: 'acme' }), tester = broker.bindTester({ business: 'acme' });
const call = (verb, args = {}, cap = agent) => Promise.resolve().then(() => broker.request(cap, { verb, args }));
return { ...f, dataRoot, business, context, mirror, store, broker, agent, human, reader, tester,
call, lookup, setState, fetches: () => fetches };
}
test('all five agent verbs read the configured served commit through real queries', async t => {
const f = await world(t);
const [find, get, search, manuscript, universe] = await Promise.all(VERBS.map((verb, i) => f.call(verb, ARGS[i])));
for (const result of [find, get, search, manuscript, universe]) assert.equal(result.commit, f.commit);
assert.deepEqual(find.results.map(x => x.path), ['Book One/Characters/Tomas.md']);
assert.match(JSON.stringify(get.lines), /He runs the ferry/);
assert.deepEqual(get.links_out, []); // The only target is in another universe.
assert.ok(search.results.length > 0);
assert.ok(search.results.every(x => !x.path.startsWith('Second World/') && x.scope === 'canon'));
assert.equal(manuscript.path, 'Book One/Chapters/01.md');
assert.deepEqual(universe.books, ['Book One']);
assert.equal(f.fetches(), 0);
const playground = await f.call('library.find', { universe: 'harbor', query: '', scope: 'playground' });
assert.deepEqual(playground.results.map(x => x.path), ['Book One/Playground/What If.md']);
assert.equal(await f.call('library.get', { universe: 'harbor', path: 'Second World/Characters/Elsewhere.md' }), null);
});
test('each verb refuses missing universe and unknown keys before host work', async t => {
let calls = 0;
const f = await world(t, { adapter: { lookup: () => { calls++; } } });
for (const [i, verb] of VERBS.entries()) {
const { universe, ...missing } = ARGS[i];
await assert.rejects(f.call(verb, missing), { code: 'invalid-request' });
for (const extra of [{ repo: '/elsewhere' }, { commit: 'b'.repeat(40) }, { business: 'other' }, { accept: 'b'.repeat(40) }])
await assert.rejects(f.call(verb, { ...ARGS[i], ...extra }), { code: 'invalid-request' });
await assert.rejects(f.call(verb, { ...ARGS[i], universe: '' }), { code: 'invalid-request' });
}
assert.equal(calls, 0);
});
test('no library, missing host adapter and undeclared project refuse library-not-configured', async t => {
const noLibrary = await world(t, { projects: {} });
const noAdapter = await world(t, { adapter: {} });
const f = await world(t);
for (const [i, verb] of VERBS.entries()) {
await assert.rejects(noLibrary.call(verb, ARGS[i]), { code: 'library-not-configured' });
await assert.rejects(noAdapter.call(verb, ARGS[i]), { code: 'library-not-configured' });
await assert.rejects(f.call(verb, { ...ARGS[i], project: 'other' }), { code: 'library-not-configured' });
}
f.business.projects.second = mappingEntry();
await assert.rejects(f.call('library.get', GET), { code: 'invalid-request' });
assert.equal((await f.call('library.get', { ...GET, project: 'books' })).commit, f.commit);
});
test('reads need the current holder on each call; human/tester/reader are not agents', async t => {
const f = await world(t, { claimed: false });
for (const [i, verb] of VERBS.entries()) {
await assert.rejects(f.call(verb, ARGS[i]), { code: 'not-holder' });
await assert.rejects(f.call(verb, ARGS[i], f.human), { code: 'agent-required' });
await assert.rejects(f.call(verb, ARGS[i], f.tester), { code: 'tester-refused' });
await assert.rejects(f.call(verb, ARGS[i], f.reader), { code: 'read-only' });
}
f.broker.request(f.agent, { verb: 'role.claim' });
assert.equal((await f.call('library.get', GET)).commit, f.commit);
f.broker.request(f.agent, { verb: 'role.release' });
await assert.rejects(f.call('library.get', GET), { code: 'not-holder' });
});
test('releasing a claim during an async lookup fences the response', { timeout: 30_000 }, async t => {
let release, entered;
const started = new Promise(resolve => { entered = resolve; });
const f = await world(t, { adapter: { lookup: async () => {
entered(); await new Promise(resolve => { release = resolve; }); return { lines: [[1, 'not returned']] };
} } });
const pending = f.call('library.get', GET);
await started;
f.broker.request(f.agent, { verb: 'role.release' });
release();
await assert.rejects(pending, { code: 'not-holder' });
});
test('a business library removed during an async read cannot leak its result', { timeout: 30_000 }, async t => {
let release, entered;
const started = new Promise(resolve => { entered = resolve; });
const f = await world(t, { adapter: { lookup: async () => {
entered(); await new Promise(resolve => { release = resolve; }); return { lines: [[1, 'not returned']] };
} } });
const pending = f.call('library.get', GET);
await started;
delete f.business.projects.books;
release();
await assert.rejects(pending, { code: 'library-not-configured' });
});
test('freshness boundary, unknown last fetch and failed fetch still use immutable served state', async t => {
const f = await world(t);
f.setState({ lastFetch: new Date(NOW - 60_000).toISOString() });
await f.call('library.get', GET);
assert.equal(f.fetches(), 0);
f.setState({ lastFetch: new Date(NOW - 60_001).toISOString() });
await f.call('library.get', GET);
assert.equal(f.fetches(), 1);
f.setState({ lastFetch: null });
await f.call('library.universe', { universe: 'harbor' });
assert.equal(f.fetches(), 2);
let attempted = 0, clock = NOW;
const failing = createLibraryLookup({ dataRoot: f.dataRoot, now: () => clock, sync: async () => {
attempted++;
f.setState({ lastError: { code: 'library-fetch-failed', at: new Date(clock).toISOString() } });
return { code: 'library-fetch-failed' };
} });
f.setState({ lastFetch: null });
const result = await failing(f.context, { method: 'get', args: GET, authorize() {} });
assert.equal(attempted, 1);
assert.equal(result.commit, f.commit);
for (const elapsed of [1, 59_999, 60_000]) {
clock = NOW + elapsed;
const retry = await failing(f.context, { method: 'get', args: GET, authorize() {} });
assert.equal(retry.commit, f.commit, 'serve the old pin during the failure cooldown');
assert.equal(attempted, 1, 'recent lastError prevents another sync even though lastFetch is null');
}
clock = NOW + 60_001;
assert.equal((await failing(f.context, { method: 'get', args: GET, authorize() {} })).commit, f.commit);
assert.equal(attempted, 2, 'retry only after the failed-attempt interval expires');
});
test('an unreadable sync state fails closed; a busy sync keeps serving the existing pin', async t => {
const f = await world(t);
const lookup = createLibraryLookup({ dataRoot: f.dataRoot, now: () => NOW, sync: async () => {
throw new library.LibraryError('library-sync-busy', 'another fetch');
} });
f.setState({ lastFetch: null });
assert.equal((await lookup(f.context, { method: 'get', args: GET, authorize() {} })).commit, f.commit);
writeFileSync(join(f.mirror, library.SYNC_STATE_FILE), '{bad json', { mode: 0o600 });
await assert.rejects(f.call('library.get', GET), { code: 'library-state-invalid' });
});
test('a stale lookup sees the commit published by its sync, not the prior served commit', async t => {
const f = await world(t);
writeFileSync(join(f.repo, GET.path), note('character', 'Tomas', 'Changed ferry.'));
git(f.repo, 'add', '-A'); git(f.repo, 'commit', '-qm', 'second fixture');
const next = git(f.repo, 'rev-parse', 'HEAD');
const lookup = createLibraryLookup({ dataRoot: f.dataRoot, now: () => NOW, sync: async () => {
git(f.repo, '-c', 'protocol.file.allow=always', 'push', '-q', f.mirror, 'HEAD:refs/heads/served');
f.setState({ served: next, lastFetch: new Date(NOW).toISOString() });
return { code: null };
} });
f.setState({ lastFetch: null });
const result = await lookup(f.context, { method: 'get', args: GET, authorize() {} });
assert.equal(result.commit, next);
assert.match(JSON.stringify(result.lines), /Changed ferry/);
});
test('real socket awaits lookup results and rechecks rejected query arguments', { timeout: 30_000 }, async t => {
const f = await world(t);
const path = join(f.root, 'lookup.sock');
const server = await serve({ broker: f.broker, path }); t.after(() => server.close());
const client = new Client({ path, cap: f.agent });
const result = await client.call('library.get', GET);
assert.equal(result.commit, f.commit);
await assert.rejects(client.call('library.find', { universe: 'harbor', query: '', scope: 'anything' }), /query-argument-invalid/);
});
test('runtime actually injects the lookup adapter, without exposing human library.file', { timeout: 30_000 }, async t => {
const f = scratchRepo(t, TEXTS), dataRoot = join(f.root, 'runtime'); mkdirSync(dataRoot);
const business = { id: 'acme', human: 'jason', projects: { books: mappingEntry() },
arbiters: { technical: 'coder', delivery: 'coder' },
roles: { coder: { definition: 'coder', authority: { withinRole: [], crossRole: [] } } } };
const runtime = await startBroker({ dataRoot, businesses: { acme: business } }); t.after(() => runtime.close());
const mirror = library.mirrorPath({ business, project: 'books', dataRoot });
git(f.repo, '-c', 'protocol.file.allow=always', 'push', '-q', mirror, 'HEAD:refs/heads/served');
writeFileSync(join(mirror, library.SYNC_STATE_FILE), JSON.stringify({ version: 1, branch: 'main', served: f.commit,
lastFetch: new Date().toISOString(), lastError: null, diverged: null, problems: [] }), { mode: 0o600 });
const cap = runtime.broker.bindLaunch({ business: 'acme', role: 'coder', run: 'r224-runtime', harness: 'pi' });
runtime.broker.request(cap, { verb: 'role.claim' });
assert.equal((await runtime.broker.request(cap, { verb: 'library.get', args: GET })).commit, f.commit);
await assert.rejects(runtime.broker.request(cap, { verb: 'library.file', args: { project: 'books', path: GET.path } }),
{ code: 'human-required' });
});
test('C2-05c broker forwards supporting scope and returns the served blob without adding write verbs', async t => {
const projects = { books: mappingEntry() };
projects.books.universes.harbor.supporting = ['Book One/Support/'];
const path = 'Book One/Support/Helper.md';
const f = await world(t, { projects, files: { ...TEXTS, [path]: note('summary', 'Helper', 'Supporting fixture.') } });
assert.deepEqual((await f.call('library.find', { universe: 'harbor', query: '', scope: 'supporting' })).results.map(x => x.path), [path]);
assert.deepEqual((await f.call('library.search', { universe: 'harbor', text: 'Supporting fixture', scope: 'supporting' })).results.map(x => x.path), [path]);
assert.equal(await f.call('library.get', { universe: 'harbor', path }), null);
const result = await f.call('library.get', { universe: 'harbor', path, scope: 'supporting' });
assert.equal(result.scope, 'supporting');
assert.equal(result.commit, f.commit);
assert.equal(result.blob, git(f.mirror, 'rev-parse', `${f.commit}:${path}`));
assert.equal(await f.call('library.get', { universe: 'second', path, scope: 'supporting' }), null);
await assert.rejects(f.call('library.manuscript', { universe: 'harbor', book: 'Book One', scope: 'supporting' }), { code: 'query-argument-invalid' });
});
-332
View File
@@ -1,332 +0,0 @@
// Row 288: broker authority, exact notice and strict Console revert API. Fixture grant rows only.
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { connect } from 'node:net';
import { startBroker, createLibraryLookup } from '../src/runtime.mjs';
import { Store } from '../src/store.mjs';
import { Broker } from '../src/broker.mjs';
import { Client } from '../src/client.mjs';
import { serve } from '../src/server.mjs';
import { mappingEntry } from '../../library/tests/helpers.mjs';
import { LibraryError } from '../../library/src/problems.mjs';
import { grantDecision } from './host-fixtures.mjs';
import { world as bareWorld } from '../../library/tests/write-fixture.mjs';
import { sync } from '../../library/src/sync.mjs';
import { SYNC_STATE_FILE, servedCommit } from '../../library/src/mirror.mjs';
import { writeLibraryDoc, saveLibraryFile, revertLibraryCommit } from '../../library/src/write.mjs';
import { git } from '../../library/tests/helpers.mjs';
const SHA = 'a'.repeat(40), NEXT = 'b'.repeat(40), PATH = 'Book One/Notes/Agent.md';
function world(t, options = {}) {
const root = mkdtempSync(join(tmpdir(), 'bus-library-write-')), store = new Store(root);
t.after(() => { store.close(); rmSync(root, { recursive: true, force: true }); });
const projects = options.projects ?? { books: mappingEntry() }; projects.books.universes.harbor.supporting = ['Book One/Notes/'];
const authority = { withinRole: ['message.send', 'library.write'], crossRole: [] };
const roles = { bean: { definition: 'companion', authority, identity: { name: 'Bean', email: '[email protected]', gitea: { user: 'bean', url: 'https://git.example.invalid' } }, publish: ['books'] },
chief: { definition: 'chief-of-staff', authority }, quill: { definition: 'proofreader', authority: { withinRole: ['message.send'], crossRole: [] } } };
options.changeRole?.(roles.bean);
const business = { id: 'acme', human: 'jason', vars: { 'bus.tester': true }, projects, roles,
arbiters: { technical: 'chief', delivery: 'chief' }, definitions: { companion: {}, 'chief-of-staff': {}, proofreader: {} } };
const seen = [], held = new Set(), logs = [];
const result = { project: 'books', path: PATH, commit: NEXT };
const library = { LibraryError, log: entry => logs.push(entry), readFile: async () => ({}), status: async () => ({}),
writeDoc: async (context, options) => { seen.push({ context, options }); options.beforePush(); options.onPushed(result); return result; },
saveFile: async context => { seen.push({ context }); return result; },
revert: async context => { seen.push({ context }); return { ...result, reverted: context.commit }; } };
const broker = new Broker({ store, businesses: { acme: business }, library, giteaKeys: { held: (b, a) => held.has(a) } });
const caps = { human: broker.bindHuman({ business: 'acme', human: 'jason', via: 'cli', outsideAgent: true }),
tester: broker.bindTester({ business: 'acme' }) };
const p = broker.request(caps.human, { verb: 'project.create', args: { name: 'Library chat', repo: 'books' } }).id;
for (const role of ['bean', 'quill', 'chief']) {
const thread = role === 'chief' ? null : broker.request(caps.human,
{ verb: 'thread.create', args: { project: p, name: role, instance: role } }).id;
caps[role] = broker.bindLaunch({ business: 'acme', role, run: role + '-run', harness: 'pi', ...(thread ? { thread } : {}) });
broker.request(caps[role], { verb: 'role.claim' });
}
const grant = (project = 'books') => {
const decision = grantDecision(store, { business: 'acme', grant: { method: 'gitea', agent: 'bean', target: { projects: [project] }, rotateBy: '2099-01-01' } });
store.run('INSERT OR REPLACE INTO gitea_grants(business,agent,user,token_id,token_name,projects,rotate_by,decision) VALUES(?,?,?,?,?,?,?,?)',
'acme', 'bean', 'bean', 7, 'fixture', JSON.stringify([project]), '2099-01-01', decision);
};
grant();
const call = (who, verb, args = {}) => Promise.resolve().then(() => broker.request(caps[who], { verb, args }));
return { root, store, broker, caps, call, seen, held, business, grant, library, logs };
}
const args = () => ({ universe: 'harbor', path: PATH, base: SHA, content: 'fixture\n' });
test('C2-02: agent verbs require creative holder, action and live unheld project grant', async t => {
const f = world(t);
for (const verb of ['library.doc.write', 'library.doc.delete']) {
const a = args(); if (verb.endsWith('delete')) delete a.content;
for (const [who, code] of [['human', 'library-write-refused'], ['tester', 'tester-refused'], ['chief', 'library-write-refused'], ['quill', 'library-write-refused']])
await assert.rejects(f.call(who, verb, a), { code });
f.held.add('bean'); await assert.rejects(f.call('bean', verb, a), { code: 'library-write-no-grant' }); f.held.clear();
f.store.run('DELETE FROM gitea_grants');
await assert.rejects(f.call('bean', verb, a), { code: 'library-write-no-grant' });
f.grant('other'); await assert.rejects(f.call('bean', verb, a), { code: 'library-write-no-grant' });
f.store.run('DELETE FROM gitea_grants'); f.grant();
}
assert.equal(f.seen.length, 0);
});
test('C2-02: writing instance supplies neither ident nor notice text; broker inserts exact notice', async t => {
const f = world(t);
const result = await f.call('bean', 'library.doc.write', args());
assert.equal(result.commit, NEXT);
const m = f.store.get("SELECT * FROM messages WHERE from_role='bean' AND to_role='human'");
assert.equal(m.body, JSON.stringify({ notice: 'library-write', op: 'write', path: PATH, commit: NEXT }));
assert.equal(m.from_run, 'bean-run');
assert.ok(f.store.get('SELECT 1 FROM message_threads WHERE message=?', m.id));
assert.equal(f.seen[0].options.identity.name, 'Bean');
assert.equal(f.seen[0].options.credential.user, 'bean');
assert.equal(f.seen[0].options.credential.agent, 'bean');
for (const extra of [{ author: 'other' }, { agent: 'chief' }, { credential: { agent: 'chief' } }])
await assert.rejects(f.call('bean', 'library.doc.write', { ...args(), ...extra }), { code: 'invalid-request' });
});
test('C2-02 A2: strict human revert args/result and agent human-required refusal', async t => {
const f = world(t);
for (const who of ['bean', 'quill', 'chief', 'tester'])
for (const verb of ['library.revert', 'library.file.save'])
await assert.rejects(f.call(who, verb, {}), { code: 'human-required' });
for (const a of [{ commit: SHA }, { project: 'books' }, { project: 'books', commit: 'A'.repeat(40) },
{ project: 'books', commit: SHA, editor: {} }, { project: 'books', commit: SHA + 'a' }])
await assert.rejects(f.call('human', 'library.revert', a), { code: 'invalid-request' });
assert.deepEqual(await f.call('human', 'library.revert', { project: 'books', commit: SHA }),
{ project: 'books', path: PATH, reverted: SHA, commit: NEXT });
await assert.rejects(f.call('human', 'library.revert', { project: 'missing', commit: SHA }), { code: 'project-not-configured' });
});
test('C2-02: human revert independent of revoked seat and LibraryError codes survive', async t => {
const f = world(t); f.store.run('DELETE FROM gitea_grants'); f.held.add('bean');
assert.equal((await f.call('human', 'library.revert', { project: 'books', commit: SHA })).reverted, SHA);
for (const code of ['library-revert-not-agent', 'stale-base', 'library-mapping-invalid', 'library-human-missing']) {
f.library.revert = async () => { throw new LibraryError(code, 'fixture'); };
await assert.rejects(f.call('human', 'library.revert', { project: 'books', commit: SHA }), { code });
}
});
test('C2-02 transport: human library.file.save exceeds 64 KiB; agent write remains bounded', async t => {
const f = world(t), path = join(f.root, 'bus.sock');
const server = await serve({ broker: f.broker, path, authenticateHuman: () => f.broker.bindHuman({ business: 'acme', human: 'jason', via: 'cli', outsideAgent: true }) });
t.after(() => server.close());
const human = new Client({ path, human: { fixture: true } }), agent = new Client({ path, cap: f.caps.bean });
const content = 'x'.repeat(70000);
assert.equal((await human.call('library.file.save', { project: 'books', path: PATH, base: SHA, content })).commit, NEXT);
assert.equal(f.seen.at(-1).context.content, content);
await assert.rejects(agent.call('library.doc.write', { ...args(), content }), { code: 'request-too-large' });
await assert.rejects(human.call('library.file.save', { project: 'books', path: PATH, base: SHA, content: 'x'.repeat(2 * 1024 * 1024) }), { code: 'request-too-large' });
});
test('C2-02 M12 through broker: every refusal preserves remote, served and all mirror refs', async t => {
const bare = await bareWorld(t), f = world(t, { projects: bare.context.business.projects });
f.library.writeDoc = (context, options) => writeLibraryDoc({ ...context, dataRoot: bare.dataRoot },
{ ...options, credential: { ...options.credential, file: bare.file }, command: bare.command });
for (const path of ['Book One/Chapters/Chapter 01.md', 'Inbox Note.md', 'Book One/Playground/What If.md',
'Book One/Notes/X.canvas', 'Book One/Notes/X.base', 'Book One/Notes/X.png', 'Second World/Chapters/01.md',
'/Book One/Notes/X.md', 'Book One/Notes/../X.md', 'Book One/./Notes/X.md', 'Book One//Notes/X.md',
'Book One/Notes/X\\Y.md', 'Book One/Notes/X\nY.md', 'Book One/Notes/Link.md', 'Book One/Notes/Submodule.md',
'Book One/Notes/agent.md', `Book One/Notes/${'é'.repeat(512)}.md`]) {
for (const verb of ['library.doc.write', 'library.doc.delete']) {
const before = bare.refs(), head = bare.remoteHead(), a = { ...args(), path, base: null };
if (verb.endsWith('delete')) delete a.content;
await assert.rejects(f.call('bean', verb, a), { code: 'library-write-story-path' }, path);
assert.equal(bare.refs(), before); assert.equal(bare.remoteHead(), head);
}
}
assert.equal(f.store.get("SELECT count(*) n FROM messages WHERE from_role='bean'").n, 0);
});
test('C2-02 broker + bare: exact write/delete notices, then human revert with revoked seat grant', async t => {
const bare = await bareWorld(t), f = world(t, { projects: bare.context.business.projects });
f.library.writeDoc = (context, options) => writeLibraryDoc({ ...context, dataRoot: bare.dataRoot },
{ ...options, credential: { ...options.credential, file: bare.file }, command: bare.command });
f.library.revert = context => revertLibraryCommit({ ...context, dataRoot: bare.dataRoot },
{ credential: { ...bare.credential, kind: 'human' }, command: bare.command });
f.library.saveFile = context => saveLibraryFile({ ...context, dataRoot: bare.dataRoot },
{ credential: { ...bare.credential, kind: 'human' }, command: bare.command });
const base = git(bare.mirror, 'rev-parse', `served:${PATH}`);
const saved = await f.call('bean', 'library.doc.write', { ...args(), base });
assert.equal(saved.commit, bare.remoteHead());
f.store.run('DELETE FROM gitea_grants'); f.held.add('bean');
const reverted = await f.call('human', 'library.revert', { project: 'books', commit: saved.commit });
assert.equal(reverted.reverted, saved.commit);
assert.equal(git(bare.remote, 'show', `main:${PATH}`), 'before');
assert.equal(git(bare.remote, 'show', '-s', '--format=%an <%ae>', reverted.commit), 'Human Fixture <[email protected]>');
f.held.clear(); f.grant();
const deleted = await f.call('bean', 'library.doc.delete', { universe: 'harbor', path: PATH, base });
const messages = f.store.all("SELECT body FROM messages WHERE from_role='bean' AND to_role='human' ORDER BY seq");
assert.deepEqual(messages.map(m => JSON.parse(m.body)), [
{ notice: 'library-write', op: 'write', path: PATH, commit: saved.commit },
{ notice: 'library-write', op: 'delete', path: PATH, commit: deleted.commit }]);
assert.equal(git(bare.remote, 'ls-tree', '-r', deleted.commit, '--', PATH), '');
});
test('C2-02 socket: a save name nested in proof cannot enlarge an agent envelope', async t => {
const f = world(t), path = join(f.root, 'raw-bus.sock');
const server = await serve({ broker: f.broker, path, authenticateHuman: () => f.caps.human });
t.after(() => server.close());
const request = JSON.stringify({ human: { verb: 'library.file.save' }, verb: 'library.doc.write',
args: { ...args(), content: 'x'.repeat(70000) } }) + '\n';
const response = await new Promise((resolve, reject) => {
const socket = connect(path); let result = '';
socket.on('error', reject); socket.on('connect', () => socket.write(request));
socket.on('data', bytes => { result += bytes; if (result.includes('\n')) { socket.destroy(); resolve(JSON.parse(result)); } });
});
assert.deepEqual(response, { ok: false, error: 'request-too-large' });
assert.equal(f.seen.length, 0);
});
test('C2-02 E2: held grant during fetch refuses at beforePush and preserves every ref', async t => {
const bare = await bareWorld(t), f = world(t, { projects: bare.context.business.projects });
const before = bare.refs(), head = bare.remoteHead();
const command = (kind, url, options) => {
if (kind === 'fetch') f.held.add('bean');
return bare.command(kind, url, options);
};
f.library.writeDoc = (context, options) => writeLibraryDoc({ ...context, dataRoot: bare.dataRoot },
{ ...options, credential: { ...options.credential, file: bare.file }, command });
await assert.rejects(f.call('bean', 'library.doc.write', { ...args(), base: git(bare.mirror, 'rev-parse', `served:${PATH}`) }),
{ code: 'library-write-no-grant' });
assert.equal(bare.refs(), before); assert.equal(bare.remoteHead(), head);
assert.equal(f.store.get("SELECT count(*) n FROM messages WHERE from_role='bean'").n, 0);
});
test('C2-02 E3: expired, firing, missing publish, wrong grant user and missing ident refuse', async t => {
const cases = [
{ name: 'expired', prepare: f => f.store.run("UPDATE gitea_grants SET rotate_by='2000-01-01'"), code: 'library-write-no-grant' },
{ name: 'firing', prepare: f => f.store.run("INSERT INTO events(id,at,business,kind,actor_role,actor_run,subject,body) VALUES('fire-bean',?,'acme','action.allowed','chief','run','bean',?)",
new Date().toISOString(), JSON.stringify({ action: 'fire.stopped' })), code: 'library-write-no-grant' },
{ name: 'publish', changeRole: r => { r.publish = []; }, code: 'library-write-no-grant' },
{ name: 'grant user', prepare: f => f.store.run("UPDATE gitea_grants SET user='other-seat'"), code: 'library-write-no-grant' },
{ name: 'identity name', changeRole: r => { delete r.identity.name; }, code: 'library-write-refused' },
{ name: 'identity email', changeRole: r => { delete r.identity.email; }, code: 'library-write-refused' },
];
for (const c of cases) {
const f = world(t, { changeRole: c.changeRole }); c.prepare?.(f);
for (const verb of ['library.doc.write', 'library.doc.delete']) {
const a = args(); if (verb.endsWith('delete')) delete a.content;
await assert.rejects(f.call('bean', verb, a), { code: c.code }, c.name);
}
assert.equal(f.seen.length, 0);
}
});
test('C2-02 F2/E6 runtime: human saves/reverts use editor.user; no login never uses the fetch bot', { timeout: 30000 }, async t => {
for (const user of [undefined, 'her-gitea-login']) {
const bare = await bareWorld(t);
const agent = await writeLibraryDoc(bare.args(), bare.opts);
bare.entry.user = 'fetch-bot';
if (user) bare.entry.editor.user = user;
const configDir = join(bare.root, 'config'), slots = join(configDir, 'secrets', 'acme');
mkdirSync(slots, { recursive: true, mode: 0o700 });
for (const slot of ['library-human', 'library-gitea'])
writeFileSync(join(slots, slot), 'fixture-runtime-token-288\n', { mode: 0o600 });
const pushes = [];
const command = (kind, url, options) => { if (kind === 'push') pushes.push(options.user); return bare.command(kind, url, options); };
const initial = (await bare.state()).lastFetch;
const business = { ...bare.context.business, human: 'jason', roles: { coder: { authority: { withinRole: [], crossRole: [] } } },
arbiters: { technical: 'coder', delivery: 'coder' } };
const runtime = await startBroker({ dataRoot: bare.dataRoot, businesses: { acme: business },
librarySync: { configDir, command, intervalMs: 60000 } });
try {
const human = runtime.broker.bindHuman({ business: 'acme', human: 'jason', via: 'cli', outsideAgent: true });
const call = (verb, args) => Promise.resolve().then(() => runtime.broker.request(human, { verb, args }));
// Let the boot fetch finish before inspecting only the human operation's command count.
const deadline = Date.now() + 10000;
while (true) {
const state = await call('library.status', { project: 'books' });
if (state.lastFetch !== initial) break;
if (Date.now() > deadline) throw Error('boot fetch did not complete');
await new Promise(resolve => setTimeout(resolve, 10));
}
const path = 'Book One/Chapters/Chapter 01.md';
const saves = [
['library.file.save', { project: 'books', path, base: git(bare.mirror, 'rev-parse', `served:${path}`), content: 'her edit\n' }],
['library.revert', { project: 'books', commit: agent.commit }],
];
const before = bare.commands.length;
for (const [verb, args] of saves) {
if (user) assert.match((await call(verb, args)).commit, /^[a-f0-9]{40}$/);
else await assert.rejects(call(verb, args), { code: 'library-human-missing' });
}
assert.deepEqual(pushes, user ? [user, user] : []);
if (!user) assert.equal(bare.commands.length, before);
} finally { await runtime.close(); }
}
});
test('C2-02 E4: post-push publication failure stores the exact notice and returns outcome-unknown', async t => {
const bare = await bareWorld(t), f = world(t, { projects: bare.context.business.projects });
const state = join(bare.mirror, SYNC_STATE_FILE), original = readFileSync(state);
const previous = await servedCommit(bare.mirror), head = bare.remoteHead();
const command = (kind, url, options) => {
// Break only state decoding after push admission; the real remote push still executes.
if (kind === 'push') writeFileSync(state, 'invalid state\n');
return bare.command(kind, url, options);
};
f.library.writeDoc = (context, options) => writeLibraryDoc({ ...context, dataRoot: bare.dataRoot },
{ ...options, credential: { ...options.credential, file: bare.file }, command });
try {
await assert.rejects(f.call('bean', 'library.doc.write', { ...args(), base: git(bare.mirror, 'rev-parse', `served:${PATH}`) }),
{ code: 'outcome-unknown' });
assert.notEqual(bare.remoteHead(), head);
assert.equal(git(bare.mirror, 'rev-parse', 'served'), previous);
const messages = f.store.all("SELECT body FROM messages WHERE from_role='bean' AND to_role='human'");
assert.deepEqual(messages.map(m => JSON.parse(m.body)), [
{ notice: 'library-write', op: 'write', path: PATH, commit: bare.remoteHead() }]);
} finally { writeFileSync(state, original); }
const commit = bare.remoteHead();
const human = { credential: { ...bare.credential, kind: 'human' }, command: bare.command };
await assert.rejects(revertLibraryCommit({ ...bare.context, commit }, human), { code: 'library-revert-not-agent' });
await sync(bare.context, { credential: bare.credential, command: bare.command });
assert.equal((await revertLibraryCommit({ ...bare.context, commit }, human)).reverted, commit);
});
test('C2-02 mos-1520: failed notice insert logs metadata and returns outcome-unknown even if refusal evidence fails', async t => {
const bare = await bareWorld(t), f = world(t, { projects: bare.context.business.projects });
const previous = await servedCommit(bare.mirror), head = bare.remoteHead();
f.library.writeDoc = (context, options) => writeLibraryDoc({ ...context, dataRoot: bare.dataRoot },
{ ...options, credential: { ...options.credential, file: bare.file }, command: bare.command });
f.store.run(`CREATE TEMP TRIGGER fail_library_notice BEFORE INSERT ON messages
WHEN NEW.from_role='bean' BEGIN SELECT RAISE(ABORT, 'fixture store failure'); END;`);
f.store.run(`CREATE TEMP TRIGGER fail_refusal_log BEFORE INSERT ON events
WHEN NEW.kind='action.refused' BEGIN SELECT RAISE(ABORT, 'fixture evidence failure'); END;`);
await assert.rejects(f.call('bean', 'library.doc.write', { ...args(), base: git(bare.mirror, 'rev-parse', `served:${PATH}`) }),
{ code: 'outcome-unknown' });
assert.notEqual(bare.remoteHead(), head);
assert.equal(await servedCommit(bare.mirror), previous);
assert.equal(f.store.get("SELECT count(*) n FROM messages WHERE from_role='bean'").n, 0);
assert.deepEqual(f.logs, [{ event: 'library-notice-store-failed', code: 'outcome-unknown', business: 'acme',
instance: 'bean', op: 'write', commit: bare.remoteHead() }]);
});
test('C2-02 + C2-05c: broker get blob feeds write/delete and new served lookups immediately', async t => {
const bare = await bareWorld(t), f = world(t, { projects: bare.context.business.projects });
f.library.lookup = createLibraryLookup({ dataRoot: bare.dataRoot,
sync: context => sync({ ...context, dataRoot: bare.dataRoot }, { credential: bare.credential, command: bare.command }) });
f.library.writeDoc = (context, options) => writeLibraryDoc({ ...context, dataRoot: bare.dataRoot },
{ ...options, credential: { ...options.credential, file: bare.file }, command: bare.command });
const query = { universe: 'harbor', path: PATH, scope: 'supporting' };
const before = await f.call('bean', 'library.get', query);
assert.equal(before.blob, git(bare.mirror, 'rev-parse', `served:${PATH}`));
const saved = await f.call('bean', 'library.doc.write', { ...args(), base: before.blob, content: 'new served text\n' });
const after = await f.call('bean', 'library.get', query);
assert.equal(after.commit, saved.commit);
assert.equal(after.blob, git(bare.mirror, 'rev-parse', `${saved.commit}:${PATH}`));
assert.notEqual(after.blob, before.blob);
assert.ok(after.lines.includes('new served text'));
assert.equal(await f.call('bean', 'library.get', { universe: 'harbor', path: PATH }), null);
await f.call('bean', 'library.doc.delete', { universe: 'harbor', path: PATH, base: after.blob });
assert.equal(await f.call('bean', 'library.get', query), null);
});
+4 -6
View File
@@ -160,7 +160,7 @@ thread run, and it configures the assistant through `assistants` (Assistant
settings, below) and names instances through `set_name`. PRD 1.7 REQ-COS-3
(row 194) grants it `role.hire` and `role.fire` within role: it hires and
fires with a reason and no decision, through the broker's `instance.hire` and
`instance.fire`, which the harness's `hire` and `fire` tools call. It has the same read-only tools, and its one credential reference is gitea, for the read grant the library mirror fetches with (row 285). The broker holds that token, never the agent. It is the only shipped role that holds `role.launch`, so
`instance.fire`, which the harness's `hire` and `fire` tools call. It has no credentials and the same read-only tools. It is the only shipped role that holds `role.launch`, so
it is the only role `launch.by` can name. The PM holds no `role.launch`
(REQ-LAUNCH-1); it asks the chief of staff for a session.
@@ -171,7 +171,7 @@ use the shared, broker-backed organization writer. The instance names are the ow
example file's:
```json
"chief": { "definition": "chief-of-staff", "credentials": { "gitea": { "file": "/home/you/.config/mosaic-dev/secrets/mosaic-stack/chief-of-staff-gitea.token", "rotateBy": "YYYY-MM-DD" } }, "vars": { "model": "opus" } },
"chief": { "definition": "chief-of-staff", "vars": { "model": "opus" } },
"assistant": { "definition": "assistant", "holder": "mos", "vars": { "model": "opus" } }
...
"launch": { "by": "chief", "instances": ["coder", "reviewer"], "models": {
@@ -180,10 +180,8 @@ example file's:
}, "limits": { "models": { "anthropic": { "claude-opus-5-5": 4, "claude-sonnet-5-5": 4 } } } }
```
Neither entry has a `tracker`. The chief's `credentials` must name exactly
its definition's services, gitea alone, and the assistant has none. A
`{ "store": true, "rotateBy": "YYYY-MM-DD" }` reference works as well as a
file. Neither form creates an account, mints a token or grants anything. A session that launches needs a harness and a model, so give each
Neither entry has a `tracker` or `credentials`, because neither role holds
any. A session that launches needs a harness and a model, so give each
instance `vars` (`harness`, `model`) as the PM has, unless the system's
execution settings cover it. A `launch.by` that names a PM, an assistant or any other instance
whose role lacks `role.launch` is refused. A file that still names the PM
@@ -113,12 +113,6 @@
},
"chief": {
"definition": "chief-of-staff",
"credentials": {
"gitea": {
"file": "/home/you/.config/mosaic-dev/secrets/mosaic-stack/chief-of-staff-gitea.token",
"rotateBy": "YYYY-MM-DD"
}
},
"vars": {
"model": "opus"
}
+1
View File
@@ -13,3 +13,4 @@ export { configDir, businessFilePath, validateBusinessDocument, loadBusiness } f
export { LEVELS, accessFilePath, checkAccess, loadAccess, covers } from "./access.mjs";
export { projectFilePath, validateProjectDocument, loadProject } from "./project.mjs";
export { systemVars, resolveInstance, classify } from "./resolve.mjs";
export { loadSeatSets } from "./library-seats.mjs";
+9 -10
View File
@@ -144,9 +144,8 @@ function createdCredentials(old, instance, definition, args) {
// checkRoutes, row 65). Row 194 (brief item 8, row 199 D13): revoke(business, instance, how,
// services) revokes the instance's credentials for a fire or a delete and throws
// credential-revoke-failed when it can't. Null in a writer with no bus (the CLI's), which revokes
// nothing.
export function instanceSettings({ dir, rolesDir, system, levels = () => null, revoke = null }) {
const writer = organizationWriter({ dir, rolesDir });
// nothing. Row 239 (#1745): writer is the organization writer, injected only by tests.
export function instanceSettings({ dir, rolesDir, system, levels = () => null, revoke = null, writer = organizationWriter({ dir, rolesDir }) }) {
// The definitions in rolesDir and whether add and set accept each one.
function definitions() {
@@ -379,8 +378,9 @@ export function instanceSettings({ dir, rolesDir, system, levels = () => null, r
}
}
// The checks every write runs, then beforeWrite (a fire's or a delete's revoke), then the write. A
// check that refuses revokes nothing, and a revoke that throws writes nothing.
// The checks every write runs, then the write, which runs beforeWrite (a fire's or a delete's
// revoke) under its lock (row 239). A check that refuses revokes nothing, and a revoke that throws
// writes nothing. beforeWrite must not write this business: the writer holds its lock.
function commit(business, old, next, { revision, actor, context, beforeWrite = null }) {
if (canonicalJson(next) === canonicalJson(old)) throw new OrganizationError("organization-no-change");
@@ -410,12 +410,11 @@ export function instanceSettings({ dir, rolesDir, system, levels = () => null, r
}
}
// Row 194 N1 (sage-1634): a delete writes on the revision its request read when it was raised,
// so a write since then makes it stale. The revision is checked here, before the revoke, because
// the writer's own check comes after it. A write between this read and the writer's lock still
// revokes and then refuses (BUILD.md follow-up).
// so a write since then makes it stale. This early check refuses it without taking the lock. The
// writer checks again under its lock, before the revoke (row 239), and that check is what keeps
// a stale fire or delete from revoking.
if (writer.read(business).revision !== revision) throw new OrganizationError("revision-conflict", "organization revision changed; read again");
if (beforeWrite) beforeWrite();
const receipt = writer.write(business, next, { revision, actor, context });
const receipt = writer.write(business, next, { revision, actor, context, beforeWrite });
return { ...read(business, actor), transaction: receipt.transaction, restart: false };
}
+51
View File
@@ -0,0 +1,51 @@
// Case 2 design 5.1 (M7, M8, row 220): which seats work in a library business,
// and which of those hold a creative definition. Read from the business files on
// every call, so an edit takes effect without a restart. Fail closed: a business
// file that can't be read or validated throws. So does anything at the businesses
// path that can't be listed: a file, a dangling symlink, or a directory that can't
// be read. Only a path with nothing at it (lstat ENOENT) holds no library business,
// so both sets are empty. No caller turns a throw into an empty set.
import { lstatSync, readdirSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { BusinessError } from "./errors.mjs";
import { configDir, loadBusiness } from "./business.mjs";
import { CREATIVE_DEFINITIONS } from "./vocabulary.mjs";
const REPO = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
export function defaultRolesDir(env = process.env) {
return resolve(env.MOSAIC_ROLES_DIR || join(REPO, "roles"));
}
// Returns { librarySeats, creativeSeats }: Sets of seat names (the role keys of
// each business). A seat in two businesses counts when either one puts it in a
// set. creativeSeats is a subset of librarySeats.
export function loadSeatSets({ dir = configDir(), rolesDir = defaultRolesDir() } = {}) {
// lstat first: only nothing at the path is an absent directory. Anything else
// there (a file, a dangling symlink, a directory) must list, or it throws.
const businesses = join(dir, "businesses");
try {
lstatSync(businesses);
} catch (err) {
if (err.code === "ENOENT") return { librarySeats: new Set(), creativeSeats: new Set() };
throw new BusinessError(`cannot list businesses in ${dir}: ${err.message}`);
}
let names;
try {
names = readdirSync(businesses).filter((name) => name.endsWith(".json"));
} catch (err) {
throw new BusinessError(`cannot list businesses in ${dir}: ${err.message}`);
}
const librarySeats = new Set();
const creativeSeats = new Set();
for (const name of names.sort()) {
const business = loadBusiness(name.slice(0, -".json".length), { dir, rolesDir });
if (!Object.values(business.projects).some((project) => project.kind === "library")) continue;
for (const [seat, role] of Object.entries(business.roles)) {
librarySeats.add(seat);
if (CREATIVE_DEFINITIONS.includes(role.definition)) creativeSeats.add(seat);
}
}
return { librarySeats, creativeSeats };
}
+62 -47
View File
@@ -177,55 +177,70 @@ export function organizationWriter({ dir, rolesDir, barrier = () => {} }) {
// Row 199 (#1697, design section 6): `detail` says what a credential verb did (verb, agent, kind,
// date, reason), never a value; the other setters pass none. context, when given, is logged with
// the change: row 194's hire and fire carry the chief's run and the decision there (D2.2).
function write(id, document, { revision, actor, detail, context }) {
// Row 239 (#1745): beforeWrite (a fire's or a delete's credential revoke) runs under the lock,
// after the revision check and the validations, so a refusal there revokes nothing. An error
// after it returns carries revoked: true, the lock's release included (duckworth-0165 C2), and the
// bus names it so the human reads that the tokens may already be revoked. beforeWrite must not
// write this business itself: it would find its own lock and refuse organization-busy.
function write(id, document, { revision, actor, detail, context, beforeWrite = null }) {
requireId(actor, "authenticated actor");
requireId(id, "organization id");
return withLock(id, ({ home, parent }) => {
recover(id);
const file = businessFilePath(id, dir);
const oldBytes = regular(file);
const before = sha256(oldBytes);
if (revision !== before) fail("revision-conflict", "organization revision changed; read again");
const old = JSON.parse(oldBytes);
// C2-04 M9: every organization setter preserves the whole project
// mapping, including library playgrounds and hybrid universes.
if (canonicalJson(document?.projects) !== canonicalJson(old.projects))
fail('organization-projects-protected');
validateBusinessDocument(document, file, { rolesDir });
const bytes = JSON.stringify(document, null, 2) + "\n";
// Check and log exactly what lands on disk, for every setter: a value JSON
// can't carry (a Date, a Map) serializes as something else (row 131, sage-0314).
const written = JSON.parse(bytes);
if (canonicalJson(written.projects) !== canonicalJson(old.projects))
fail('organization-projects-protected');
validateBusinessDocument(written, file, { rolesDir });
const after = sha256(bytes);
const transaction = randomUUID();
const tx = join(home, transaction);
directory(tx);
const previous = join(tx, "previous.json");
durable(previous, oldBytes);
const candidate = join(parent, "." + id + "." + transaction + ".tmp");
durable(candidate, bytes);
syncDir(tx);
const event = {
transaction, actor, ...(context === undefined ? {} : { context }), business: id, before, after,
changes: changes(old, written), ...(detail === undefined ? {} : { detail }), at: new Date().toISOString(),
};
log(id, { ...event, state: "prepared" });
syncDir(home);
barrier("prepared");
if (sha256(regular(file)) !== before) {
log(id, { ...event, state: "aborted" });
rmSync(candidate);
fail("revision-conflict", "organization revision changed before publication");
}
renameSync(candidate, file);
syncDir(parent);
barrier("renamed");
log(id, { ...event, state: "committed" });
return { revision: after, transaction, previous };
});
let revoked = false;
try {
return withLock(id, ({ home, parent }) => {
recover(id);
const file = businessFilePath(id, dir);
const oldBytes = regular(file);
const before = sha256(oldBytes);
if (revision !== before) fail("revision-conflict", "organization revision changed; read again");
const old = JSON.parse(oldBytes);
// C2-04 M9: every organization setter preserves the whole project
// mapping, including library playgrounds and hybrid universes.
if (canonicalJson(document?.projects) !== canonicalJson(old.projects))
fail('organization-projects-protected');
validateBusinessDocument(document, file, { rolesDir });
const bytes = JSON.stringify(document, null, 2) + "\n";
// Check and log exactly what lands on disk, for every setter: a value JSON
// can't carry (a Date, a Map) serializes as something else (row 131, sage-0314).
const written = JSON.parse(bytes);
if (canonicalJson(written.projects) !== canonicalJson(old.projects))
fail('organization-projects-protected');
validateBusinessDocument(written, file, { rolesDir });
if (beforeWrite) {
beforeWrite();
revoked = true;
}
const after = sha256(bytes);
const transaction = randomUUID();
const tx = join(home, transaction);
directory(tx);
const previous = join(tx, "previous.json");
durable(previous, oldBytes);
const candidate = join(parent, "." + id + "." + transaction + ".tmp");
durable(candidate, bytes);
syncDir(tx);
const event = {
transaction, actor, ...(context === undefined ? {} : { context }), business: id, before, after,
changes: changes(old, written), ...(detail === undefined ? {} : { detail }), at: new Date().toISOString(),
};
log(id, { ...event, state: "prepared" });
syncDir(home);
barrier("prepared");
if (sha256(regular(file)) !== before) {
log(id, { ...event, state: "aborted" });
rmSync(candidate);
fail("revision-conflict", "organization revision changed before publication");
}
renameSync(candidate, file);
syncDir(parent);
barrier("renamed");
log(id, { ...event, state: "committed" });
return { revision: after, transaction, previous };
});
} catch (e) {
if (revoked && e instanceof Error) e.revoked = true;
throw e;
}
}
// Row 199: a receipt with no document change, for a credential verb that changes only the agents'
+6 -8
View File
@@ -9,7 +9,7 @@ import { basename, dirname, join } from "node:path";
import { refuse } from "./errors.mjs";
import {
ACTIONS, GATED_ONLY, TOOLS, NETWORKS, SERVICES, HOST_SERVICE, GITEA_SCOPE_CATEGORIES, VIKUNJA_GRANTABLE,
CREATIVE_DEFINITIONS, CREATIVE_TOOLS, CREATIVE_ACTIONS, CREATIVE_SERVICE, unhireableAction,
CREATIVE_DEFINITIONS, CREATIVE_TOOLS, unhireableAction,
} from "./vocabulary.mjs";
import {
requireObject, rejectUnknownKeys, requireId, requireString, requireDistinctList, readJsonFile, deepFreeze,
@@ -159,17 +159,15 @@ function checkContract(contract, file) {
}
// Row 213 (C2-08, Case 2 design 4, M1): a creative role only reads and answers the human. Its file
// may name no tool outside CREATIVE_TOOLS, and must carry a messaging key that names only the human,
// so it can't relay through another role. Row 285 (C2-08b, mos-1309 item 5) lets it write supporting
// docs: its authority is withinRole CREATIVE_ACTIONS at most, and its one credential is gitea.
// may name no tool outside CREATIVE_TOOLS, no authority but message.send, and must carry a messaging
// key that names only the human, so it can't relay through another role.
function checkCreative(role) {
const wider = role.tools.filter((tool) => !CREATIVE_TOOLS.includes(tool));
if (wider.length > 0) refuse(`creative role ${role.name} may not name tools ${wider.join(", ")} (allowed: ${CREATIVE_TOOLS.join(", ")})`);
if (role.authority.crossRole.length > 0 || role.authority.withinRole.some((a) => !CREATIVE_ACTIONS.includes(a))) {
refuse(`creative role ${role.name} may hold only withinRole ${CREATIVE_ACTIONS.join(" and ")}`);
const actions = [...role.authority.withinRole, ...role.authority.crossRole];
if (role.authority.crossRole.length > 0 || actions.some((a) => a !== "message.send")) {
refuse(`creative role ${role.name} may hold only withinRole message.send`);
}
const services = role.credentials.map((c) => c.service).filter((service) => service !== CREATIVE_SERVICE);
if (services.length > 0) refuse(`creative role ${role.name} may hold only the ${CREATIVE_SERVICE} credential (got ${services.join(", ")})`);
if (role.messaging === null) refuse(`creative role ${role.name} requires "messaging"`);
for (const key of ["sendTo", "receiveFrom"]) {
if (role.messaging[key].some((entry) => entry !== "human")) {
+11 -13
View File
@@ -57,10 +57,6 @@ export const ACTIONS = Object.freeze([
"policy.change",
"prd.approve",
"decision.resolve.technical",
// Row 285 (C2-08b, #1790): a creative agent writes a supporting Markdown file in the human's library.
// Added as a hard wait and routed under PRD 1.16 REQ-WAIT-3 and REQ-LIB-6; role.mjs grants it within-role
// to the creative roles only.
"library.write",
]);
// The actions that are not hard waits. PRD 1.5 REQ-WAIT-3: an action added
@@ -95,9 +91,6 @@ export const ROUTED = Object.freeze([
// PRD 1.7 REQ-COS-3 (row 194, #1692): the chief's hire and fire, within the bounds the broker checks.
"role.hire",
"role.fire",
// PRD 1.16 REQ-WAIT-3 and REQ-LIB-6 (row 285, #1790): a creative agent's library write, within the
// bounds that paragraph names.
"library.write",
]);
// The hard waits (PRD 1.5 REQ-WAIT-1): always gated, always the human's,
@@ -209,13 +202,18 @@ export const ID_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
// Row 155 (#1649) moves it here from the broker, so the organization writer reads the same name.
export const THREAD_DEFINITION = "assistant";
// Row 213 (C2-08, #1714, Case 2 design 4): the creative roles. Each reads and answers the human, and
// row 285 (C2-08b, #1790) lets it write supporting docs; its instances are the human's alone (M10).
// Row 213 (C2-08, #1714, Case 2 design 4): the creative roles. Each only reads and answers the human
// in cited items; its instances are the human's alone (M10).
export const CREATIVE_DEFINITIONS = Object.freeze(["companion", "ideas", "research", "proofreader", "fact-checker", "continuity"]);
// Row 285 (mos-1309 item 5): the only authority a creative role file may name, all withinRole, and
// the one credential service it may name, the definition credential the Gitea grant path reads.
export const CREATIVE_ACTIONS = Object.freeze(["message.send", "library.write"]);
export const CREATIVE_SERVICE = "gitea";
// The reply item kinds each creative definition may send (design 4, 5.2's reply-kind check).
export const CREATIVE_KINDS = Object.freeze({
companion: Object.freeze(["idea", "question", "finding", "fact"]),
ideas: Object.freeze(["idea", "question"]),
research: Object.freeze(["fact", "question"]),
proofreader: Object.freeze(["correction", "question"]),
"fact-checker": Object.freeze(["finding", "question"]),
continuity: Object.freeze(["finding", "question"]),
});
// The only tools a creative role file may name (M1): reading, and the broker's web grant.
export const CREATIVE_TOOLS = Object.freeze(["read", "grep", "find", "ls", "web"]);
// The definitions that may hold a thread: the assistant and the creative roles. The definition the
@@ -46,21 +46,8 @@ test("a granted agent loads with its identity, grant and the project's upstream"
test("N10: publish needs identity and a gitea definition, and the error names the grant", () => {
refuses(() => check((d) => { delete d.roles.coder.identity; }), /roles\.coder\.publish needs identity and a gitea definition/);
// Row 285 (mos-1333 item 3): the chief's definition now declares gitea, so this case names an
// instance whose definition has none.
refuses(() => check((d) => { d.roles.helper = { definition: "assistant", holder: "mos", identity: structuredClone(IDENTITY), publish: ["stack"] }; }),
/roles\.helper\.publish needs identity and a gitea definition/);
});
// Row 285 (mos-1333 item 4, brief :1829): the chief's grant needs identity and publish on the
// instance, so a chief with its gitea reference loads with both. X-G1 (gitea-grant.test) shows the
// same chief refuses at raise.
test("row 285: a chief with its gitea reference, identity and publish loads", () => {
const identity = { name: "Chief", email: "[email protected]", gitea: { url: "https://git.example", user: "acme-chief" } };
const business = check((d) => { d.roles.chief.identity = structuredClone(identity); d.roles.chief.publish = ["stack"]; });
assert.deepEqual({ ...business.roles.chief.identity, gitea: { ...business.roles.chief.identity.gitea } }, identity);
assert.deepEqual([...business.roles.chief.publish], ["stack"]);
assert.deepEqual(Object.keys(business.roles.chief.credentials), ["gitea"]);
refuses(() => check((d) => { d.roles.chief.identity = structuredClone(IDENTITY); d.roles.chief.publish = ["stack"]; }),
/roles\.chief\.publish needs identity and a gitea definition/);
});
test("publish names declared projects that have a remote, each once", () => {
+4 -33
View File
@@ -6,7 +6,6 @@ import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { BusinessError, businessFilePath, configDir, loadBusiness, validateBusinessDocument } from "../src/index.mjs";
import { THREAD_IDLE_SECONDS } from "../src/business.mjs";
import { CREATIVE_DEFINITIONS } from "../src/vocabulary.mjs";
import { launchDoc, businessDoc, REPO, REPO_ROLES, rolesCopy, tmp, writeJson } from "./helpers.mjs";
test('C2-04: library mappings load without roots, remain frozen, and retain mapping refusals', async t => {
@@ -274,56 +273,28 @@ test("the shipped example refuses as written and validates once filled in", () =
assert.equal(id, 15);
});
// Row 285 (C2-08b, #1790, mos-1330): a creative definition declares gitea, so its instance names
// the reference. The store form needs no token file, and the bus reads a missing one as no token.
const CREATIVE_GITEA = Object.freeze({ gitea: Object.freeze({ store: true, rotateBy: "2099-01-01" }) });
// Row 213 (C2-08, #1714), deviation D1: the persona vars sit on a creative instance only, and
// both or neither. The var checks themselves are vars.mjs's.
test("persona vars: agent layer, creative definition only, both or neither", () => {
const sha = "a".repeat(64);
const persona = { "persona.name": "Bean", "persona.sha256": sha };
const business = check((d) => { d.roles.bean = { definition: "companion", credentials: CREATIVE_GITEA, vars: { ...persona } }; });
const business = check((d) => { d.roles.bean = { definition: "companion", vars: { ...persona } }; });
assert.deepEqual({ ...business.roles.bean.vars }, persona);
assert.doesNotThrow(() => check((d) => { d.roles.bean = { definition: "ideas", credentials: CREATIVE_GITEA }; }));
assert.doesNotThrow(() => check((d) => { d.roles.bean = { definition: "ideas" }; }));
refuses(() => check((d) => { d.vars["persona.name"] = "Bean"; }), /persona\.name can't be set at the business layer/);
refuses(() => check((d) => { d.roles.pm.vars = { ...d.roles.pm.vars, ...persona }; }),
/roles\.pm\.vars: persona vars need a creative definition \(pm isn't one\)/);
refuses(() => check((d) => { d.roles.chief.vars = { ...persona }; }), /chief-of-staff isn't one/);
for (const key of Object.keys(persona)) {
refuses(() => check((d) => { d.roles.bean = { definition: "research", credentials: CREATIVE_GITEA, vars: { [key]: persona[key] } }; }),
refuses(() => check((d) => { d.roles.bean = { definition: "research", vars: { [key]: persona[key] } }; }),
/roles\.bean\.vars: persona\.name and persona\.sha256 are set together or not at all/);
}
for (const [key, value] of [["persona.name", "x".repeat(41)], ["persona.name", "Be\nan"], ["persona.name", "Be\u0007an"], ["persona.name", "Be\u2028an"], ["persona.name", "Be\u2029an"], ["persona.name", 7],
["persona.sha256", "A".repeat(64)], ["persona.sha256", sha.slice(1)], ["persona.sha256", `${sha}0`]]) {
refuses(() => check((d) => { d.roles.bean = { definition: "companion", credentials: CREATIVE_GITEA, vars: { ...persona, [key]: value } }; }), new RegExp(`variable ${key.replace(".", "\\.")}`), 2);
refuses(() => check((d) => { d.roles.bean = { definition: "companion", vars: { ...persona, [key]: value } }; }), new RegExp(`variable ${key.replace(".", "\\.")}`), 2);
}
});
// Row 285 (C2-08b, #1790, mos-1330): the chief and each creative definition declare gitea, so an
// instance without the reference refuses at load with the credential map's message.
test("row 285: a chief or creative instance without credentials.gitea refuses at load", () => {
refuses(() => check((d) => { delete d.roles.chief.credentials; }),
/roles\.chief\.credentials must reference exactly the services its role definition needs \(gitea; got none\)/);
for (const definition of CREATIVE_DEFINITIONS) {
refuses(() => check((d) => { d.roles.bean = { definition }; }),
/roles\.bean\.credentials must reference exactly the services its role definition needs \(gitea; got none\)/);
assert.doesNotThrow(() => check((d) => { d.roles.bean = { definition, credentials: CREATIVE_GITEA }; }), definition);
}
});
// Row 285 (C2-08b, brief): a creative instance may carry identity and publish, under the rules at
// business.mjs:155-166, which the grant path reads. The grant itself still refuses it (#giteaRole).
test("row 285: a creative instance with identity and publish loads", () => {
const identity = { name: "Bean", email: "[email protected]", gitea: { url: "https://git.example", user: "acme-bean" } };
const business = check((d) => {
d.projects.stack.remote = "https://git.example/acme/stack";
d.roles.bean = { definition: "companion", credentials: CREATIVE_GITEA, identity, publish: ["stack"] };
});
assert.deepEqual({ ...business.roles.bean.identity, gitea: { ...business.roles.bean.identity.gitea } }, identity);
assert.deepEqual([...business.roles.bean.publish], ["stack"]);
});
// Row 194 (#1692, D2.5, T17): the per-agent forbid and the retired list.
test("row 194 keep, noHire and retired validate, and a file without them loads as before", () => {
const plain = check();
@@ -10,7 +10,7 @@ import { readFileSync } from "node:fs";
import { join } from "node:path";
import { ACTIONS, BusinessError, classify, loadBusiness, loadRole, resolveInstance } from "../src/index.mjs";
import { THREAD_IDLE_SECONDS } from "../src/business.mjs";
import { businessDoc, FAR_DATE, launchDoc, REPO_ROLES, systemFor, tmp, writeJson } from "./helpers.mjs";
import { businessDoc, launchDoc, REPO_ROLES, systemFor, tmp, writeJson } from "./helpers.mjs";
// Decision 104's list plus role.launch (decision 139) plus role.end and
// organization.change (row 123, REQ-COS-1) and record.write (row 138), plus instance.name
@@ -20,8 +20,7 @@ const APPROVED = Object.freeze({
tools: ["read", "grep", "find", "ls"],
network: "api-only",
authority: Object.freeze({ withinRole: Object.freeze(["message.send", "role.launch", "role.end", "organization.change", "record.write", "instance.name", "role.hire", "role.fire"]), crossRole: Object.freeze([]) }),
// Row 285 (#1790, mos-1309 item 5, sage-2915): gitea for the library read grant, read scopes only.
credentials: Object.freeze([Object.freeze({ service: "gitea", scopes: Object.freeze(["read:repository", "read:user"]) })]),
credentials: Object.freeze([]),
// Row 194 (#1692, Q4, sage-1374): empty until a policy commit after the PRD 1.7 resolve.
hireable: Object.freeze([]),
});
@@ -80,17 +79,13 @@ test("the shipped file is exactly the approved list", () => {
});
test("the resolved record matches the approved list, so a widened file fails", () => {
const fixture = loadFixture();
const record = resolved(fixture);
const record = resolved(loadFixture());
assert.deepEqual(record.limits, {
tools: APPROVED.tools,
network: APPROVED.network,
authority: APPROVED.authority,
});
// Row 285 (mos-1330): the fixture's gitea reference, the chief's only one.
assert.deepEqual(record.credentials, {
gitea: { service: "gitea", file: join(fixture.root, "secrets", "chief-of-staff-gitea.token"), rotateBy: FAR_DATE },
});
assert.deepEqual(record.credentials, {});
});
test("the chief of staff holds role.launch, message.send, role.end, organization.change, record.write, instance.name, role.hire and role.fire; every other action is gated", () => {
@@ -154,13 +149,12 @@ test("the contract names no duty to talk to the human and the pm contract no lau
assert.match(pm, /You don't launch sessions/);
});
// Row 285 (mos-1330): the instance references exactly gitea, its definition's one service, and no tracker.
test("the instance takes only the gitea credential reference and no tracker", () => {
test("the instance takes no credential references and no tracker", () => {
refuses(
() => loadFixture((doc) => {
doc.roles[INSTANCE].credentials.vikunja = { file: "/x/token", expires: "2099-01-01" };
doc.roles[INSTANCE].credentials = { gitea: { file: "/x/token", rotateBy: "2099-01-01" } };
}),
/must reference exactly the services its role definition needs \(gitea; got gitea, vikunja\)/,
/must reference exactly the services its role definition needs \(none; got gitea\)/,
);
refuses(
() => loadFixture((doc) => {
@@ -38,13 +38,6 @@ test("REQ-COS-3: role.hire and role.fire are routed, not hard waits", () => {
for (const action of ["role.hire", "role.fire"]) assert.ok(ROUTED.includes(action) && !GATED_ONLY.includes(action), action);
});
// PRD 1.16 REQ-WAIT-3 and REQ-LIB-6 (row 285, #1790): library.write is in the vocabulary and routed.
test("REQ-WAIT-3: library.write is routed under REQ-LIB-6 (1.16), not a hard wait", () => {
assert.ok(ACTIONS.includes("library.write"));
assert.ok(ROUTED.includes("library.write"));
assert.ok(!GATED_ONLY.includes("library.write"));
});
test("REQ-WAIT-3: every action is routed or a hard wait, never both, and the routed list names only actions", () => {
for (const action of ROUTED) assert.ok(ACTIONS.includes(action), action);
for (const action of ACTIONS) assert.notEqual(ROUTED.includes(action), GATED_ONLY.includes(action), action);
+3 -4
View File
@@ -68,10 +68,9 @@ export function businessDoc(root, id = "acme") {
cto: role("cto", 4, { holder: "darkwing", vars: { harness: "claude-code" } }),
coder: role("coder", 5, { vars: { harness: "pi", "limits.network": "none" } }),
reviewer: role("reviewer", 6),
// The chief of staff launches (REQ-LAUNCH-1, decision 139); it has no
// tracker bot. Its one credential reference is gitea, for the library
// read grant (row 285, mos-1330).
chief: { definition: "chief-of-staff", credentials: { gitea: ref("chief-of-staff", "gitea") } },
// The chief of staff launches (REQ-LAUNCH-1, decision 139); it holds no
// credential and no tracker bot.
chief: { definition: "chief-of-staff" },
},
launch: launchDoc(),
};
@@ -9,7 +9,7 @@ import { mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync }
import { join } from "node:path";
import { instanceSettings } from "../src/instance-settings.mjs";
import { projectFilePath } from "../src/project.mjs";
import { businessDoc, FAR_DATE, REPO, rolesCopy, systemConfig, systemFor, tmp, writeJson } from "./helpers.mjs";
import { businessDoc, REPO, rolesCopy, systemConfig, systemFor, tmp, writeJson } from "./helpers.mjs";
const CLI = join(REPO, "packages", "business", "src", "cli.mjs");
const roots = [];
@@ -286,8 +286,7 @@ test("row 213 a creative instance is the human's: add, vars and definition chang
writeFileSync(join(f.root, "config", "personas", "acme", "bean.md"), text, { mode: 0o600 });
const persona = { "persona.name": "Bean", "persona.sha256": createHash("sha256").update(text).digest("hex") };
const view = f.settings.read("acme");
// Row 285 (mos-1332 item 4): the companion definition declares gitea.
assert.deepEqual(view.definitions.companion, { services: ["gitea"], accepted: true });
assert.deepEqual(view.definitions.companion, { services: [], accepted: true });
const add = { instance: "bean", op: "add", definition: "companion", vars: persona };
for (const actor of ["chief-of-staff.chief", "tester"]) {
assert.throws(() => f.settings.set("acme", { revision: view.revision, ...add }, actor), e => e.code === "organization-creative-human-only", actor);
@@ -332,8 +331,8 @@ test("row 213 a creative instance is the human's: add, vars and definition chang
// every actor, the human included. The listing's endProtected is that same check for its reader.
test("row 256 T1-T3, T5 the human deletes a creative instance, no other actor does, and the assistant stays", () => {
const f = fixture(doc => {
doc.roles.bean = { definition: "companion", credentials: { gitea: { store: true, rotateBy: FAR_DATE } } };
doc.roles.muse = { definition: "ideas", credentials: { gitea: { store: true, rotateBy: FAR_DATE } } };
doc.roles.bean = { definition: "companion" };
doc.roles.muse = { definition: "ideas" };
doc.roles.assistant = { definition: "assistant", holder: "mos" };
});
const del = (instance, actor) => () => f.settings.set("acme", { revision: f.settings.read("acme").revision, instance, op: "delete" }, actor);
@@ -378,7 +377,7 @@ test("row 256 T1-T3, T5 the human deletes a creative instance, no other actor do
// instance can't be kept, launch.by or an arbiter, so the check it reaches is the last-listed one.
test("row 256 T4 the human's delete of the only listed instance, a creative one, is the last-listed refusal", () => {
const f = fixture(doc => {
doc.roles.bean = { definition: "companion", credentials: { gitea: { store: true, rotateBy: FAR_DATE } } };
doc.roles.bean = { definition: "companion" };
doc.launch.instances = ["bean"];
});
const bytes = readFileSync(f.file, "utf8");
@@ -181,7 +181,7 @@ test('B7 kept instance: its route is the human\'s',async()=>{
// can't reach its model through the models table, the instances key or a route; the human can,
// except through the instances key, which refuses a creative instance for everyone.
test('M10 creative instance: models keys it names, the instances key and its route are the human\'s',async()=>{
const f=fixture();const doc=structuredClone(f.doc);doc.roles.bean={definition:'companion',credentials:{gitea:{store:true,rotateBy:FAR_DATE}},vars:{model:'sonnet'}};writeJson(f.file,doc);
const f=fixture();const doc=structuredClone(f.doc);doc.roles.bean={definition:'companion',vars:{model:'sonnet'}};writeJson(f.file,doc);
const g={...f,doc};const {settings}=await routeSettings(g);const file=()=>readFileSync(f.file,'utf8');
const chief='chief-of-staff.chief';let {revision}=settings.read('acme');
const models=structuredClone(settings.read('acme').models);
@@ -0,0 +1,107 @@
// Case 2 M7/M8 (design 5.1, row 220): loadSeatSets reads every business file in
// the config directory. A seat is a library seat when a business with a library
// project names it; a creative seat is a library seat whose definition is creative.
// Any file it can't read or validate throws, and so does a businesses path that is
// not a directory. An absent businesses directory gives empty sets.
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync, chmodSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { loadSeatSets } from "../src/library-seats.mjs";
import { BusinessError } from "../src/index.mjs";
import { businessDoc, writeJson, REPO_ROLES } from "./helpers.mjs";
import { mappingEntry } from "../../library/tests/helpers.mjs";
function fixture(t) {
const root = mkdtempSync(join(tmpdir(), "row220-seats-"));
t.after(() => rmSync(root, { recursive: true, force: true }));
const dir = join(root, "config");
mkdirSync(join(dir, "businesses"), { recursive: true });
return { root, dir };
}
const sets = (dir) => loadSeatSets({ dir, rolesDir: REPO_ROLES });
test("M7/M8: library seats come from library businesses, creative seats from their creative definitions", (t) => {
const { root, dir } = fixture(t);
const doc = businessDoc(root, "acme");
doc.projects = { books: mappingEntry(), ...doc.projects };
doc.roles.bean = { definition: "companion" };
writeJson(join(dir, "businesses", "acme.json"), doc);
const found = sets(dir);
assert.deepEqual([...found.librarySeats].sort(), ["bean", "chief", "coder", "cto", "pm", "reviewer"]);
assert.deepEqual([...found.creativeSeats], ["bean"]);
assert.ok([...found.creativeSeats].every((seat) => found.librarySeats.has(seat)));
});
test("M8: a business with no library project puts no seat in either set", (t) => {
const { root, dir } = fixture(t);
const doc = businessDoc(root, "other");
doc.roles.bean = { definition: "companion" };
writeJson(join(dir, "businesses", "other.json"), doc);
const found = sets(dir);
assert.equal(found.librarySeats.size, 0);
assert.equal(found.creativeSeats.size, 0);
});
test("M7/M8: a business file that is not valid JSON throws; no empty set", (t) => {
const { root, dir } = fixture(t);
writeJson(join(dir, "businesses", "acme.json"), businessDoc(root, "acme"));
const broken = join(dir, "businesses", "broken.json");
writeFileSync(broken, "{");
chmodSync(broken, 0o600);
assert.throws(() => sets(dir), BusinessError);
});
test("M7/M8: an absent businesses directory gives empty sets", (t) => {
const root = mkdtempSync(join(tmpdir(), "row220-seats-none-"));
t.after(() => rmSync(root, { recursive: true, force: true }));
const found = sets(join(root, "config"));
assert.equal(found.librarySeats.size, 0);
assert.equal(found.creativeSeats.size, 0);
});
test("M7/M8: a businesses path that is not a directory throws; no empty set", (t) => {
const root = mkdtempSync(join(tmpdir(), "row220-seats-file-"));
t.after(() => rmSync(root, { recursive: true, force: true }));
const dir = join(root, "config");
mkdirSync(dir);
writeFileSync(join(dir, "businesses"), "not a directory");
assert.throws(() => sets(dir), (err) => err instanceof BusinessError && /cannot list businesses/.test(err.message));
});
test("M7/M8: a businesses symlink to a missing target throws; no empty set", (t) => {
const root = mkdtempSync(join(tmpdir(), "row220-seats-dangling-"));
t.after(() => rmSync(root, { recursive: true, force: true }));
const dir = join(root, "config");
mkdirSync(dir);
symlinkSync(join(root, "missing"), join(dir, "businesses"));
assert.throws(() => sets(dir), (err) => err instanceof BusinessError && /cannot list businesses/.test(err.message));
});
test("M7/M8: a config directory under a regular file throws (lstat fails with ENOTDIR); no empty set", (t) => {
const root = mkdtempSync(join(tmpdir(), "row220-seats-notdir-"));
t.after(() => rmSync(root, { recursive: true, force: true }));
const dir = join(root, "config");
writeFileSync(dir, "not a directory");
assert.throws(() => sets(dir), (err) => err instanceof BusinessError && /cannot list businesses/.test(err.message));
});
test("M7/M8: a business file that can't be read throws; no empty set", (t) => {
const { root, dir } = fixture(t);
writeJson(join(dir, "businesses", "acme.json"), businessDoc(root, "acme"));
const file = join(dir, "businesses", "acme.json");
chmodSync(file, 0o000);
t.after(() => {
// The fixture's rmSync hook can run first, so the file may already be gone.
try {
chmodSync(file, 0o600);
} catch (err) {
if (err.code !== "ENOENT") throw err;
}
});
// Root reads a mode 000 file, so the check cannot hold there.
if (process.getuid?.() === 0) return t.skip("running as root: mode 000 files stay readable");
assert.throws(() => sets(dir), (err) => err instanceof BusinessError && /must be a regular, non-symbolic-link file/.test(err.message));
});
@@ -4,11 +4,12 @@
import test, { after } from "node:test";
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { readFileSync, rmSync } from "node:fs";
import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { instanceSettings } from "../src/instance-settings.mjs";
import { OrganizationError, organizationWriter } from "../src/organization.mjs";
import { CREATIVE_DEFINITIONS } from "../src/vocabulary.mjs";
import { businessDoc, FAR_DATE, REPO, rolesCopy, systemConfig, systemFor, tmp, writeJson } from "./helpers.mjs";
import { businessDoc, REPO, rolesCopy, systemConfig, systemFor, tmp, writeJson } from "./helpers.mjs";
const CLI = join(REPO, "packages", "business", "src", "cli.mjs");
const roots = [];
@@ -36,7 +37,7 @@ function fixture(mutate) {
const log = () => readFileSync(settings.writer.logFile("acme"), "utf8").trim().split("\n").map(line => JSON.parse(line));
const onDisk = () => JSON.parse(readFileSync(file, "utf8"));
const revision = () => settings.read("acme").revision;
return { root, file, settings, validate, log, onDisk, revision };
return { root, dir, rolesDir, file, settings, validate, log, onDisk, revision };
}
// Each refusal: its code (or the validator's BusinessError), and the file's bytes unchanged.
@@ -234,7 +235,7 @@ test("D2.2 fire delists and keeps the entry, a repeat is done with no write, and
// every actor's fire, the human's included.
test("row 256 checkDelete passes the human's creative delete and refuses another actor's; fire still refuses", () => {
const f = fixture(doc => {
doc.roles.bean = { definition: "companion", credentials: { gitea: { store: true, rotateBy: FAR_DATE } } };
doc.roles.bean = { definition: "companion" };
doc.launch.instances.push("bean");
});
const bytes = readFileSync(f.file, "utf8");
@@ -244,3 +245,73 @@ test("row 256 checkDelete passes the human's creative delete and refuses another
assert.throws(() => f.settings.checkFire("acme", "bean"), e => e.code === "organization-definition-refused");
assert.equal(readFileSync(f.file, "utf8"), bytes);
});
// Row 239 (#1745): a fire's or a delete's revoke runs inside the writer, under its lock, after the
// revision check. revoking(f, writer, fail) builds settings on f's files with a spy revoke and that writer.
function revoking(f, writer, fail = null) {
const calls = [];
const revoke = (business, agent, how, services) => {
calls.push([business, agent, how, services]);
if (fail) throw fail;
};
const settings = instanceSettings({ dir: f.dir, rolesDir: f.rolesDir, system: systemFor(f.root), revoke, ...(writer ? { writer } : {}) });
return { settings, calls };
}
const receipts = f => (existsSync(f.settings.writer.logFile("acme")) ? f.log() : []);
// A hand edit: the same document in other bytes, so the revision changes and the file still validates.
const handEdit = f => {
const bytes = JSON.stringify(f.onDisk()) + "\n";
writeFileSync(f.file, bytes);
return bytes;
};
test("row 239 T1 a fire on a revision that goes stale before the writer's lock refuses there and revokes nothing", () => {
const f = fixture();
const real = organizationWriter({ dir: f.dir, rolesDir: f.rolesDir });
let edited = null;
// The edit lands after commit()'s early check and before the writer takes its lock.
const writer = { ...real, write: (id, document, options) => { edited = handEdit(f); return real.write(id, document, options); } };
const { settings, calls } = revoking(f, writer);
const before = receipts(f).length;
assert.throws(() => settings.fire("acme", { name: "sec-1" }, { actor: "chief", context: CONTEXT }),
e => e.code === "revision-conflict" && e.revoked === undefined);
assert.deepEqual(calls, []);
assert.equal(readFileSync(f.file, "utf8"), edited);
assert.equal(receipts(f).length, before);
});
test("row 239 T2 a write after the revoke refused before publication carries revoked, and the file keeps the edit", () => {
const f = fixture();
let edited = null;
const writer = organizationWriter({ dir: f.dir, rolesDir: f.rolesDir, barrier: stage => { if (stage === "prepared") edited = handEdit(f); } });
const { settings, calls } = revoking(f, writer);
assert.throws(() => settings.fire("acme", { name: "sec-1" }, { actor: "chief", context: CONTEXT }),
e => e.code === "revision-conflict" && e.revoked === true);
assert.deepEqual(calls, [["acme", "sec-1", "fire", []]]);
assert.equal(readFileSync(f.file, "utf8"), edited);
assert.equal(receipts(f).at(-1).state, "aborted");
});
test("row 239 T3 any error after the revoke carries revoked, for a fire and a delete; a revoke that throws carries nothing", () => {
for (const [how, act] of [
["fire", settings => settings.fire("acme", { name: "sec-1" }, { actor: "chief", context: CONTEXT })],
["delete", (settings, f) => settings.set("acme", { revision: f.revision(), instance: "sec-1", op: "delete" }, "jason")],
]) {
const f = fixture();
const bytes = readFileSync(f.file, "utf8");
const writer = organizationWriter({ dir: f.dir, rolesDir: f.rolesDir, barrier: stage => { if (stage === "prepared") throw new Error("stopped at prepared"); } });
const { settings, calls } = revoking(f, writer);
assert.throws(() => act(settings, f), e => e.message === "stopped at prepared" && e.revoked === true, how);
assert.equal(calls.length, 1, how);
assert.equal(calls[0][2], how);
assert.equal(readFileSync(f.file, "utf8"), bytes, how);
const g = fixture();
const gBytes = readFileSync(g.file, "utf8");
const failing = revoking(g, null, new OrganizationError("credential-revoke-failed"));
assert.throws(() => act(failing.settings, g), e => e.code === "credential-revoke-failed" && e.revoked === undefined, how);
assert.equal(failing.calls.length, 1, how);
assert.equal(readFileSync(g.file, "utf8"), gBytes, how);
assert.deepEqual(receipts(g), [], how);
}
});
+2 -2
View File
@@ -4,7 +4,7 @@ import { join } from "node:path";
import {
BusinessError, classify, projectFilePath, resolveInstance, systemVars, validateBusinessDocument, validateProjectDocument,
} from "../src/index.mjs";
import { businessDoc, FAR_DATE, REPO_ROLES, systemFor, tmp } from "./helpers.mjs";
import { businessDoc, REPO_ROLES, systemFor, tmp } from "./helpers.mjs";
function refuses(fn, pattern) {
assert.throws(fn, (error) => {
@@ -114,7 +114,7 @@ test("role.launch stays within-role only for the instance the launch block names
// A second chief-of-staff instance is the launcher, so the first one may not launch.
const two = setup((d) => {
d.roles.chief2 = { definition: "chief-of-staff", credentials: { gitea: { store: true, rotateBy: FAR_DATE } } };
d.roles.chief2 = { definition: "chief-of-staff" };
d.launch.by = "chief2";
});
assert.equal(classify(resolve(two, "chief"), "role.launch"), "gated");
+5 -19
View File
@@ -226,16 +226,14 @@ test("contract: a non-empty regular Markdown file beside the role file", () => {
// Row 213 (C2-08, #1714, M1): a creative role reads and answers the human, and nothing else.
const CREATIVE = { companion: ["read", "web"], ideas: ["read"], research: ["read", "web"], proofreader: ["read"], "fact-checker": ["read"], continuity: ["read"] };
// Row 285 (C2-08b, #1790, mos-1309 item 5): each also holds library.write and the gitea credential, whose
// scopes equal what the Gitea grant path mints (gitea-grant.mjs SEAT_SCOPES, sage-2915).
test("the six creative roles load: read tools, message.send and library.write, gitea, messaging with the human only", () => {
test("the six creative roles load: read tools, message.send only, messaging with the human only", () => {
for (const [name, tools] of Object.entries(CREATIVE)) {
const role = loadRole(REPO_ROLES, name);
assert.equal(role.roleVersion, 2, name);
assert.deepEqual(role.tools, tools, name);
assert.equal(role.network, tools.includes("web") ? "api-only" : "none", name);
assert.deepEqual(role.authority, { withinRole: ["message.send", "library.write"], crossRole: [] }, name);
assert.deepEqual(role.credentials, [{ service: "gitea", scopes: ["read:user", "write:repository"] }], name);
assert.deepEqual(role.authority, { withinRole: ["message.send"], crossRole: [] }, name);
assert.deepEqual(role.credentials, [], name);
assert.deepEqual(role.messaging, { sendTo: ["human"], receiveFrom: ["human"] }, name);
}
});
@@ -257,20 +255,8 @@ test("M1: a creative role file wider than read and answer is refused", () => {
for (const tool of ["write", "edit", "bash"]) {
refuses(creative("ideas", { tools: ["read", tool] }), new RegExp(`^creative role ideas may not name tools ${tool} `));
}
const gitea = [{ service: "gitea", scopes: ["read:user", "write:repository"] }];
assert.doesNotThrow(creative("ideas", { authority: { withinRole: ["message.send", "library.write"], crossRole: [] }, credentials: gitea }));
// Row 285: any other action, at either class, refuses, each routed action looped from the list.
const only = /^creative role proofreader may hold only withinRole message\.send and library\.write$/;
for (const action of ACTIONS.filter((a) => !GATED_ONLY.includes(a) && !["message.send", "library.write"].includes(a))) {
refuses(creative("proofreader", { authority: { withinRole: ["message.send", "library.write", action], crossRole: [] } }), only);
}
refuses(creative("proofreader", { authority: { withinRole: [], crossRole: ["message.send"] } }), only);
refuses(creative("proofreader", { authority: { withinRole: ["message.send"], crossRole: ["library.write"] } }), only);
// Row 285: library.write with any credential but gitea refuses.
refuses(creative("ideas", { authority: { withinRole: ["message.send", "library.write"], crossRole: [] }, credentials: [...gitea, { service: "vikunja", scopes: { tasks: ["read_one"] } }] }),
/^creative role ideas may hold only the gitea credential \(got vikunja\)$/);
refuses(creative("ideas", { authority: { withinRole: ["message.send", "library.write"], crossRole: [] }, credentials: [{ service: "host" }] }),
/^creative role ideas may hold only the gitea credential \(got host\)$/);
refuses(creative("proofreader", { authority: { withinRole: ["message.send", "record.write"], crossRole: [] } }), /^creative role proofreader may hold only withinRole message.send$/);
refuses(creative("proofreader", { authority: { withinRole: [], crossRole: ["message.send"] } }), /^creative role proofreader may hold only withinRole message.send$/);
refuses(creative("continuity", { messaging: undefined }), /^creative role continuity requires "messaging"$/);
refuses(creative("research", { messaging: { sendTo: ["human", "pm"], receiveFrom: ["human"] } }), /^creative role research messaging.sendTo may name only human$/);
refuses(creative("research", { messaging: { sendTo: ["human"], receiveFrom: ["assistant"] } }), /^creative role research messaging.receiveFrom may name only human$/);
+6
View File
@@ -55,6 +55,12 @@ export const REASONS = {
"credential-revoke-failed": "a credential couldn't be revoked, so the business file is unchanged; tokens already revoked " +
"stay revoked and the instance can't use them; clear what else the agent's store directory holds and run the same " +
"command again, which is safe",
// Row 239 (#1745): a fire's or a delete's revoke runs under the writer's lock; these follow one that ran.
"revision-conflict-revoked": "the business file changed after the agent's tokens were revoked and before the write, so " +
"the file is unchanged; the tokens may already be revoked and the instance can't use them; read it again with " +
"`mosaic business instances` and run the same command again, which is safe",
"outcome-unknown-revoked": "the agent's tokens may already be revoked and the write's outcome is unknown; read the " +
"business file again with `mosaic business instances` before trying again",
"capacity-full": "a launch limit is reached; `mosaic limits --business BUSINESS` shows them",
"limit-reached": "a launch limit is reached; `mosaic limits --business BUSINESS` shows them",
"unknown-role": "the business has no such instance",
-1
View File
@@ -528,7 +528,6 @@ export function createLauncher({
contract: readFileSync(resolved.contract, "utf8"),
arbiter: Object.values(b.arbiters).includes(instance),
tracker,
library: Object.values(b.projects ?? {}).some(project => project.kind === "library"),
credentials,
session: { run, launchedBy, workspace: inSandbox, toolSocket, turnMarker, checkouts: inSandbox === workspace ? checkouts : checkouts.map((c) => ({ ...c, path: join(inSandbox, relative(workspace, c.path)) })) },
harness,
+1
View File
@@ -42,6 +42,7 @@ const EXIT = {
"tester-off": 3,
"tester-refused": 3,
"outcome-unknown": 1,
"outcome-unknown-revoked": 1,
"response-too-large": 1,
"invalid-response": 1,
};
@@ -333,3 +333,51 @@ test("row 240 pins and usage: the shipped pins are r6's, the script reads the pi
assert.deepEqual([u.status, u.stderr], [2, "hostcheck: refusing: run it as root\n"]);
}
});
test("Vikunja 614 check: item 5 accepts dpkg's bare octal mode and leading-zero equivalents", (t) => {
for (const mode of ["750", "0750"]) {
const h = host(t);
put(join(h.hc, "statoverride"), `root mosaic ${mode} /usr/bin/bwrap\n`);
const r = run(h, "--check");
assert.equal(r.status, 0, r.out + r.err);
assert.deepEqual(fails(r), []);
assert.ok(r.lines.some((line) => line.startsWith("ok 5 ")), r.out);
}
});
test("Vikunja 614 enforce: dpkg's bare 750 leaves bwrap open and writes no DRIFT", (t) => {
const h = host(t);
put(join(h.hc, "statoverride"), "root mosaic 750 /usr/bin/bwrap\n");
const r = run(h, "--enforce");
assert.equal(r.status, 0, r.out + r.err);
assert.deepEqual(fails(r), []);
assert.equal(r.lines.at(-1), "hostcheck: all seven hold");
assert.deepEqual([calls(h, "apparmor_parser"), calls(h, "chown"), calls(h, "chmod")], [[], [], []]);
assert.equal(existsSync(drift(h)), false);
assert.equal(existsSync(hlog(h)), false);
});
test("Vikunja 614 check: item 5 refuses other modes, owners, groups, paths and malformed overrides", (t) => {
const overrides = [
...["755", "0755", "4750", "75", "7500", "075", "00750", "000750", "0780", "8", "0o750", "+750", "-750", "7x0", "750+0", ""].map((mode) => `root mosaic ${mode} /usr/bin/bwrap\n`),
"root mosaic 750 /usr/bin/bwrap\n",
"root\tmosaic 750 /usr/bin/bwrap\n",
"mosaic mosaic 750 /usr/bin/bwrap\n",
"root root 750 /usr/bin/bwrap\n",
"root mosaic 750 /usr/bin/other\n",
"root mosaic 750 /usr/bin/bwrap extra\n",
"root mosaic 750\n",
"root mosaic 750 /usr/bin/bwrap\nroot mosaic 750 /usr/bin/bwrap\n",
"\n",
"",
null,
];
for (const override of overrides) {
const h = host(t);
if (override === null) rmSync(join(h.hc, "statoverride"));
else put(join(h.hc, "statoverride"), override);
const r = run(h, "--check");
assert.equal(r.status, 1, `${JSON.stringify(override)}: ${r.out}${r.err}`);
assert.deepEqual(fails(r).map((line) => line.split(" ")[1]), ["5"], r.out);
}
});
+419
View File
@@ -0,0 +1,419 @@
// Case 2 row C2-13b (#1727): scripts/case2-install.sh installs a hub as <user>, and
// scripts/case2-precheck.sh's library checks and --library-status mode. Brief:
// docs/plans/2026-10-20_case2-rows.md "C2-13b". Every case runs in a scratch home with its own
// MOSAIC_CONFIG, a stub stack-copy and fake getent, sudo, id, node, bwrap and systemctl. The library
// sync runs in-process against a local bare repo, as the bus would. Nothing here reads or writes
// ~/.mosaic-dev, ~/.config/mosaic-dev, /etc or a network host, and no fixture value is a credential.
import { test } from "node:test";
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { businessDoc, writeJson } from "../../business/tests/helpers.mjs";
import { BASE, MARKER, git, mappingEntry, repo } from "../../library/tests/helpers.mjs";
import { ensureMirror, mirrorPath, sync } from "../../library/src/index.mjs";
import { gitEnv } from "../../seat/src/checkout.mjs";
import { SAFE } from "../../project/src/git.mjs";
import { tmp } from "./helpers.mjs";
const REPO = fileURLToPath(new URL("../../../", import.meta.url));
const INSTALL = join(REPO, "scripts", "case2-install.sh");
const PRECHECK = join(REPO, "scripts", "case2-precheck.sh");
const COMMIT = "c".repeat(40);
const UID = process.getuid();
const GID = process.getgid();
// Made-up values; no output may hold them.
const FIXTURE_KEY = "fixture-zai-key-8d41a7";
const PERSONA_TEXT = { bean: "Bean is warm and brief. PERSONA-TEXT-bean-61f0\n", chet: "Chet is dry and exact. PERSONA-TEXT-chet-2b9e\n" };
const sha256 = (data) => createHash("sha256").update(data).digest("hex");
const mode = (p) => statSync(p).mode & 0o777;
function script(file, text) {
mkdirSync(dirname(file), { recursive: true });
writeFileSync(file, `#!/usr/bin/env bash\n${text}\n`);
chmodSync(file, 0o755);
return file;
}
// A scratch <user>: a home, an input business file, a persona staging dir and fakes.
function world(t, { profile = "library" } = {}) {
const root = tmp(t, "case2-install-");
const home = join(root, "home");
const configDir = join(home, ".config", "mosaic-dev");
// claude-session.env is in place before the install, as 2d would leave it on a re-run.
const secrets = join(configDir, "secrets");
mkdirSync(secrets, { recursive: true, mode: 0o700 });
chmodSync(configDir, 0o700);
writeFileSync(join(secrets, "claude-session.env"), `ZAI_API_KEY=${FIXTURE_KEY}\n`, { mode: 0o600 });
const doc = businessDoc(root);
for (const r of Object.values(doc.roles)) r.vars = { ...r.vars, harness: "pi" };
if (profile === "library") {
doc.projects.books = { ...mappingEntry(), user: "writer" };
doc.roles.bean = { definition: "companion", vars: { harness: "pi" } };
doc.roles.chet = { definition: "companion", vars: { harness: "pi" } };
} else doc.vars["bus.tester"] = true;
const input = writeJson(join(root, "input", "acme.json"), doc);
const staging = join(root, "staging");
mkdirSync(staging, { mode: 0o700 });
const personas = [];
for (const [instance, name] of [["bean", "Bean"], ["chet", "Chet"]]) {
writeFileSync(join(staging, `${instance}.md`), PERSONA_TEXT[instance], { mode: 0o600 });
personas.push({ instance, name, bytes: Buffer.byteLength(PERSONA_TEXT[instance]), sha256: sha256(PERSONA_TEXT[instance]) });
}
writeFileSync(join(staging, "manifest.json"), `${JSON.stringify({ version: 1, personas }, null, 2)}\n`, { mode: 0o600 });
const bin = join(root, "bin");
const log = join(root, "calls.log");
script(join(bin, "stack-copy"), `echo "stack-copy $*" >>'${log}'
[ "$1" = copy ] && [ "$3" = --copies ] || exit 4
mkdir -p "$4/$2/scripts" && : >"$4/$2/scripts/mosaic" && echo "copied: $4/$2"`);
script(join(bin, "systemctl"), `echo "systemctl $*" >>'${log}'`);
const me = spawnSync("id", ["-un"], { encoding: "utf8" }).stdout.trim();
script(join(bin, "getent"), `[ "$1" = passwd ] && [ "$2" = '${me}' ] && echo '${me}:x:${UID}:${GID}::${home}:/bin/bash'`);
script(join(bin, "sudo"), "exit 1");
script(join(bin, "id"), `if [ "$1" = -G ]; then echo '${GID}'; elif [ "$1" = -u ] && [ -n "\${CASE2_TEST_UID:-}" ]; then echo "$CASE2_TEST_UID"; else exec /usr/bin/id "$@"; fi`);
script(join(bin, "node"), `if [ "$1" = --version ]; then echo v24.3.0; exit 0; fi\nexec '${process.execPath}' "$@"`);
script(join(bin, "bwrap"), "exit 0");
const units = join(root, "units");
mkdirSync(units);
writeFileSync(join(units, "mosaic-webui.service"), "[Service]\nExecStart=/usr/bin/node /x/cli.mjs serve --port 443 --business acme\n");
writeFileSync(join(units, "[email protected]"), "[Service]\nEnvironment=PATH=/usr/bin\n");
const sys = join(root, "sys");
mkdirSync(join(sys, "net", "ipv4"), { recursive: true });
mkdirSync(join(sys, "kernel"), { recursive: true });
writeFileSync(join(sys, "net", "ipv4", "ip_unprivileged_port_start"), "1024\n");
writeFileSync(join(sys, "kernel", "apparmor_restrict_unprivileged_userns"), "1\n");
const notify = join(home, ".mosaic-dev", "notify", "acme");
mkdirSync(notify, { recursive: true, mode: 0o700 });
writeFileSync(join(notify, "notify.json"), '{"notifyVersion":1,"binding":null}\n', { mode: 0o600 });
return {
root, home, configDir, secrets, input, staging, bin, log, units, sys, doc,
config: join(configDir, "config.json"),
business: join(configDir, "businesses", "acme.json"),
personaDir: join(configDir, "personas", "acme"),
slot: join(secrets, "acme"),
dataRoot: join(home, ".mosaic-dev"),
};
}
function env(x, extra = {}) {
return { PATH: `${x.bin}:/usr/bin:/bin`, HOME: x.home, MOSAIC_CONFIG: x.config, CASE2_STACK_COPY: join(x.bin, "stack-copy"), ...extra };
}
function clean(out) {
assert.doesNotMatch(out, new RegExp(FIXTURE_KEY), "the output holds the fixture key");
assert.doesNotMatch(out, /PERSONA-TEXT/, "the output holds persona text");
assert.doesNotMatch(out, new RegExp(MARKER), "the output holds her text");
}
function install(x, { profile = "library", args = null, extra = {} } = {}) {
const argv = args ?? ["--business", "acme", "--business-file", x.input, "--commit", COMMIT, "--profile", profile,
...(profile === "library" ? ["--personas", x.staging] : [])];
const r = spawnSync(INSTALL, argv, { encoding: "utf8", timeout: 120000, env: env(x, extra) });
const out = r.stdout + r.stderr;
clean(out);
return { code: r.status, out };
}
function precheck(x, { args = ["--business", "acme", "--profile", "library"] } = {}) {
const r = spawnSync(PRECHECK, args, {
encoding: "utf8",
timeout: 60000,
env: env(x, { CASE2_UNIT_DIR: x.units, CASE2_PROC_SYS: x.sys, CASE2_GETENT: join(x.bin, "getent") }),
});
const out = r.stdout + r.stderr;
clean(out);
return { code: r.status, out };
}
const status = (x) => precheck(x, { args: ["--business", "acme", "--library-status"] });
function refused(r, pattern) {
assert.equal(r.code, 1, r.out);
assert.match(r.out, pattern);
}
const calls = (x) => (existsSync(x.log) ? readFileSync(x.log, "utf8") : "");
// ---- case2-install.sh ----
test("the library install writes the business file, personas and slot dir, makes the copy and starts nothing", (t) => {
const x = world(t);
const r = install(x);
assert.equal(r.code, 0, r.out);
assert.equal(mode(x.business), 0o600);
const doc = JSON.parse(readFileSync(x.business, "utf8"));
for (const [instance, name] of [["bean", "Bean"], ["chet", "Chet"]]) {
assert.equal(doc.roles[instance].vars["persona.name"], name);
assert.equal(doc.roles[instance].vars["persona.sha256"], sha256(PERSONA_TEXT[instance]));
assert.equal(doc.roles[instance].vars.harness, "pi");
const file = join(x.personaDir, `${instance}.md`);
assert.equal(readFileSync(file, "utf8"), PERSONA_TEXT[instance]);
assert.equal(mode(file), 0o600);
}
assert.equal(mode(join(x.configDir, "personas")), 0o700);
assert.equal(mode(x.personaDir), 0o700);
assert.equal(mode(x.slot), 0o700);
assert.deepEqual(readdirSync(x.slot), []);
assert.equal(calls(x), `stack-copy copy ${COMMIT} --copies ${join(x.home, ".local", "share", "mosaic-stack", "copies")}\n`);
assert.doesNotMatch(r.out, /release/);
assert.match(r.out, /business acme validates/);
assert.match(r.out, /--library-status/);
assert.ok(existsSync(x.config));
});
test("a library re-run passes and leaves every file as it was", (t) => {
const x = world(t);
assert.equal(install(x).code, 0);
const before = readFileSync(x.business);
const r = install(x);
assert.equal(r.code, 0, r.out);
assert.match(r.out, /already matches/);
assert.match(r.out, /personas already installed/);
assert.deepEqual(readFileSync(x.business), before);
});
test("a re-run refuses business-file-differs and leaves the file unchanged", (t) => {
const x = world(t);
assert.equal(install(x).code, 0);
const doc = JSON.parse(readFileSync(x.business, "utf8"));
doc.vars["tracker.pollSeconds"] = 120;
writeJson(x.business, doc);
const before = readFileSync(x.business);
refused(install(x), /business-file-differs/);
assert.deepEqual(readFileSync(x.business), before);
});
test("a re-run refuses persona-differs when an installed persona isn't the staged one, and writes nothing", (t) => {
const x = world(t);
assert.equal(install(x).code, 0);
rmSync(x.business);
writeFileSync(join(x.personaDir, "bean.md"), "Someone else. PERSONA-TEXT-other\n");
refused(install(x), /persona-differs/);
assert.equal(existsSync(x.business), false);
});
test("the factory install writes no library mapping, persona or slot dir", (t) => {
const x = world(t, { profile: "factory" });
const r = install(x, { profile: "factory" });
assert.equal(r.code, 0, r.out);
const doc = JSON.parse(readFileSync(x.business, "utf8"));
assert.equal(Object.values(doc.projects).some((p) => p.kind === "library"), false);
assert.equal(existsSync(join(x.configDir, "personas")), false);
assert.equal(existsSync(x.slot), false);
assert.doesNotMatch(r.out, /--library-status/);
});
test("the factory install refuses a library project and bus.tester off, before anything is written", (t) => {
const x = world(t, { profile: "factory" });
const doc = JSON.parse(readFileSync(x.input, "utf8"));
doc.projects.books = { ...mappingEntry(), user: "writer" };
writeJson(x.input, doc);
refused(install(x, { profile: "factory" }), /profile-library-business/);
delete doc.projects.books;
doc.vars["bus.tester"] = false;
writeJson(x.input, doc);
refused(install(x, { profile: "factory" }), /bus-tester-off/);
assert.equal(calls(x), "");
assert.equal(existsSync(x.business), false);
});
test("the library install refuses bus.tester on and a persona var in the input", (t) => {
const x = world(t);
const doc = JSON.parse(readFileSync(x.input, "utf8"));
doc.vars["bus.tester"] = true;
writeJson(x.input, doc);
refused(install(x), /bus-tester-on/);
doc.vars["bus.tester"] = false;
doc.roles.bean.vars["persona.name"] = "Bean";
writeJson(x.input, doc);
refused(install(x), /persona-var-input/);
assert.equal(calls(x), "");
});
test("the install refuses root, a business id mismatch, another --home and a config dir with group bits", (t) => {
const x = world(t);
refused(install(x, { extra: { CASE2_TEST_UID: "0" } }), /run-as-root/);
refused(install(x, { args: ["--business", "other", "--business-file", x.input, "--commit", COMMIT, "--personas", x.staging] }), /business-id-mismatch/);
refused(install(x, { args: ["--business", "acme", "--business-file", x.input, "--commit", COMMIT, "--personas", x.staging, "--home", x.root] }), /home-mismatch/);
chmodSync(x.configDir, 0o750);
refused(install(x), /config-dir-mode/);
assert.equal(calls(x), "");
assert.equal(existsSync(x.business), false);
});
test("the library install needs --personas", (t) => {
const x = world(t);
const r = install(x, { args: ["--business", "acme", "--business-file", x.input, "--commit", COMMIT] });
assert.equal(r.code, 4, r.out);
assert.match(r.out, /needs --personas/);
});
test("a validate refusal removes the business file this run wrote", (t) => {
const x = world(t);
unlinkSync(x.doc.roles.pm.credentials.gitea.file);
const r = install(x);
refused(r, /validate: .*the business file this run wrote is removed/);
assert.equal(existsSync(x.business), false);
});
test("N4: a validate refusal on a re-run leaves the matching business file in place, byte for byte", (t) => {
const x = world(t);
assert.equal(install(x).code, 0);
const before = readFileSync(x.business);
unlinkSync(x.doc.roles.pm.credentials.gitea.file);
const r = install(x);
refused(r, /validate: /);
assert.doesNotMatch(r.out, /is removed/);
assert.deepEqual(readFileSync(x.business), before);
});
// ---- case2-precheck.sh, the library profile (D6a) ----
test("a clean library host passes the precheck with no mirror yet", (t) => {
const x = world(t);
assert.equal(install(x).code, 0);
const r = precheck(x);
assert.equal(r.code, 0, r.out);
assert.match(r.out, /ok {6}business file .* with no group or other bit/);
assert.match(r.out, /ok {6}no history for acme yet/);
assert.match(r.out, new RegExp(`ok {6}persona bean sha256 ${sha256(PERSONA_TEXT.bean)}`));
assert.match(r.out, new RegExp(`ok {6}persona chet sha256 ${sha256(PERSONA_TEXT.chet)}`));
assert.match(r.out, /ok {6}no Discord binding/);
assert.equal(existsSync(mirrorPath({ business: { id: "acme", projects: { books: x.doc.projects.books } }, project: "books", dataRoot: x.dataRoot })), false);
});
test("the library precheck refuses a persona file at 0644", (t) => {
const x = world(t);
assert.equal(install(x).code, 0);
chmodSync(join(x.personaDir, "bean.md"), 0o644);
refused(precheck(x), /REFUSED persona-mode: .*bean\.md must be .* 0600 file \(mode 644\)/);
});
test("the library precheck refuses a persona whose digest isn't persona.sha256", (t) => {
const x = world(t);
assert.equal(install(x).code, 0);
writeFileSync(join(x.personaDir, "chet.md"), "Not Chet. PERSONA-TEXT-other\n");
refused(precheck(x), /REFUSED persona-mismatch: persona chet has sha256 [0-9a-f]{64}, and persona.sha256 is /);
});
test("the library precheck refuses a persona dir with group bits", (t) => {
const x = world(t);
assert.equal(install(x).code, 0);
chmodSync(x.personaDir, 0o750);
refused(precheck(x), /REFUSED persona-mode: .*personas\/acme must be .* 0700 directory/);
});
test("the library precheck refuses a business file at 0644", (t) => {
const x = world(t);
assert.equal(install(x).code, 0);
chmodSync(x.business, 0o644);
refused(precheck(x), /REFUSED business-file-mode: .*acme\.json .*\(mode 644\)/);
});
test("the library precheck refuses a changes.jsonl at 0644", (t) => {
const x = world(t);
assert.equal(install(x).code, 0);
const history = join(x.configDir, "businesses", ".history", "acme");
mkdirSync(history, { recursive: true, mode: 0o700 });
writeFileSync(join(history, "changes.jsonl"), "", { mode: 0o644 });
chmodSync(join(history, "changes.jsonl"), 0o644);
refused(precheck(x), /REFUSED history-mode: .*changes\.jsonl must be .* 0600 file \(mode 644\)/);
chmodSync(join(history, "changes.jsonl"), 0o600);
assert.equal(precheck(x).code, 0);
});
test("the library precheck refuses a Discord binding", (t) => {
const x = world(t);
assert.equal(install(x).code, 0);
mkdirSync(join(x.dataRoot, "discord"), { recursive: true });
writeFileSync(join(x.dataRoot, "discord", "her.json"), "{}\n", { mode: 0o600 });
refused(precheck(x), /REFUSED discord-binding: .*her\.json exists/);
});
// ---- case2-precheck.sh --library-status (D6b) ----
// The context the bus builds for books (runtime.mjs:161-164), and a sync the way the bus's timer
// runs it, against a local bare clone through the command parameter.
function library(x) {
const context = { business: { id: "acme", projects: { books: x.doc.projects.books } }, project: "books", dataRoot: x.dataRoot };
mkdirSync(x.dataRoot, { recursive: true, mode: 0o700 });
chmodSync(x.dataRoot, 0o700);
const run = (bare, slot) => sync(context, {
slot,
command: (kind, url, { mirror, branch }) => ({
argv: [...SAFE, "-c", "protocol.file.allow=always", "-c", "core.createObject=rename", "-C", mirror, "fetch", "--no-tags",
"--no-write-fetch-head", "--end-of-options", bare, `+refs/heads/${branch}:refs/remotes/library/${branch}`],
env: { ...gitEnv(), LC_ALL: "C", GIT_CEILING_DIRECTORIES: dirname(mirror) },
}),
});
return { context, run };
}
test("--library-status refuses library-mirror-missing before the bus has made the mirror", (t) => {
const x = world(t);
assert.equal(install(x).code, 0);
refused(status(x), /REFUSED library-mirror-missing: library books has no mirror at .*the bus makes it when it starts/);
});
test("--library-status refuses library-never-synced on a fresh mirror", async (t) => {
const x = world(t);
assert.equal(install(x).code, 0);
await ensureMirror(library(x).context);
const r = status(x);
refused(r, /REFUSED library-never-synced: library books has no fetch yet/);
assert.doesNotMatch(r.out, /library-last-error/);
});
test("--library-status names a recorded lastError before the null lastFetch it leaves (N3)", async (t) => {
const x = world(t);
assert.equal(install(x).code, 0);
const lib = library(x);
await lib.run("/nonexistent", join(x.slot, "library-gitea"));
const r = status(x);
refused(r, /REFUSED library-last-error: library books: library-credential-missing at \d{4}-\d\d-\d\dT/);
assert.doesNotMatch(r.out, /library-never-synced/);
});
test("--library-status prints each R-problem's path as an escaped JSON string, then the count, and passes", async (t) => {
const x = world(t);
assert.equal(install(x).code, 0);
const odd = "Odd‮Name\u0085.md";
const f = repo(t, { ...BASE, [odd]: `${MARKER}\n` });
const bare = join(f.root, "remote.git");
git(f.root, "clone", "-q", "--bare", "--no-local", f.repo, bare);
writeFileSync(join(x.slot, "library-gitea"), "placeholder-not-a-token\n", { mode: 0o600 });
const { state } = await library(x).run(bare, join(x.slot, "library-gitea"));
assert.equal(state.lastError, null);
const r = status(x);
assert.equal(r.code, 0, r.out);
assert.match(r.out, new RegExp(`ok {6}library books last fetched \\S+, serving ${f.commit}`));
assert.match(r.out, /^problem {3}R2 "Inbox Note\.md"$/m);
assert.match(r.out, /^problem {3}R\d+ "Odd\\u202eName\\u0085\.md"$/m);
assert.doesNotMatch(r.out, /[\u0085‮]/);
const lines = r.out.split("\n").filter((l) => l.startsWith("problem "));
assert.equal(lines.length, state.problems.length);
assert.match(r.out, new RegExp(`^problems ${state.problems.length}$`, "m"));
assert.match(r.out, /case2-precheck: library status passed/);
});
test("--library-status takes no --profile", (t) => {
const x = world(t);
const r = precheck(x, { args: ["--business", "acme", "--library-status", "--profile", "library"] });
assert.equal(r.code, 4, r.out);
});
test("Vikunja 614: install preserves the explicit notifier decision bytes and mode and creates none when absent", (t) => {
const x = world(t);
const file = join(x.dataRoot, "notify", "acme", "notify.json");
const before = readFileSync(file), beforeMode = mode(file);
const r = install(x);
assert.equal(r.code, 0, r.out);
assert.deepEqual(readFileSync(file), before);
assert.equal(mode(file), beforeMode);
const absent = world(t), missing = join(absent.dataRoot, "notify", "acme", "notify.json");
rmSync(missing);
const fresh = install(absent);
assert.equal(fresh.code, 0, fresh.out);
assert.equal(existsSync(missing), false);
});
+68
View File
@@ -626,6 +626,9 @@ function host(t, { roles = {}, vars = {}, keyFile = `ZAI_API_KEY=${FIXTURE_KEY}\
script(join(bin, "id"), `if [ "$1" = -G ]; then echo "\${CASE2_TEST_GROUPS:-${GID}}"; else exec /usr/bin/id "$@"; fi`);
script(join(bin, "node"), `if [ "$1" = --version ]; then echo "\${CASE2_TEST_NODE:-v24.3.0}"; exit 0; fi\nexec '${process.execPath}' "$@"`);
script(join(bin, "bwrap"), `exit "\${CASE2_TEST_BWRAP:-0}"`);
const notify = join(home, ".mosaic-dev", "notify", "acme");
mkdirSync(notify, { recursive: true, mode: 0o700 });
writeFileSync(join(notify, "notify.json"), '{"notifyVersion":1,"binding":null}\n', { mode: 0o600 });
return { root, home, configDir, config, secrets, units, sys, bin, dataRoot: join(home, ".mosaic-dev") };
}
@@ -872,3 +875,68 @@ test("inside a session's sandbox a bind below 1024 fails with EACCES, and a bind
assert.equal(bindIn(LOW_PORT), "EACCES");
assert.equal(bindIn(high), "bound");
});
test("Vikunja 614 factory: scoped @anthropic-ai Claude path renders and passes installed read-back", (t) => {
const h = hub(t);
const claude = script(join(h.root, "opt", "claude-pin", "node_modules", "@anthropic-ai", "claude-code", "bin", "claude.exe"), "exit 0");
// The suite runs unprivileged. Model root ownership for this regular executable
// and its ancestors only; file type/executable checks and both unit readers are real.
const ancestors = [];
for (let p = claude; p !== "/"; p = dirname(p)) ancestors.push(p);
script(join(h.bin, "stat"), `if [ "$1" = -c ] && [ "$3" = -- ]; then
case "$4" in ${ancestors.map((p) => JSON.stringify(p)).join("|")})
case "$2" in %u) echo 0; exit ;; %a) echo 755; exit ;; esac ;;
esac
fi
exec /usr/bin/stat "$@"`);
const first = unit(h, { profile: "factory", extra: ["--claude", claude] });
assert.equal(first.code, 0, first.out + first.err);
assert.ok(lines(read(busFile(h)), "Environment").includes(`MOSAIC_CLAUDE_BIN=${claude}`));
const again = unit(h, { profile: "factory", copy: COPY_B, extra: ["--claude", claude] });
assert.equal(again.code, 0, again.out + again.err);
assert.ok(lines(read(busFile(h)), "Environment").includes(`MOSAIC_CLAUDE_BIN=${claude}`));
assert.deepEqual(lines(read(busFile(h)), "WorkingDirectory"), [copyDir(h, COPY_B)]);
});
test("Vikunja 614 factory: plain paths still refuse every named unsafe character", (t) => {
const h = hub(t);
for (const char of [" ", "%", "$", "\"", "'", "\\", "&", "|"]) {
refuses(unit(h, { profile: "factory", extra: ["--claude", `/opt/claude${char}bin`] }), /--claude contains a character the unit cannot carry/);
}
});
test("Vikunja 614 precheck: explicit null and named notifier decisions pass", (t) => {
for (const binding of [null, "host-notify"]) {
const x = host(t);
const dir = join(x.dataRoot, "notify", "acme");
mkdirSync(dir, { recursive: true, mode: 0o700 });
writeFileSync(join(dir, "notify.json"), JSON.stringify({ notifyVersion: 1, binding }), { mode: 0o600 });
const r = precheck(x);
assert.equal(r.code, 0, r.out);
assert.ok(r.out.includes(`ok notifier config ${dir}/notify.json validates (directory 0700, file 0600)`), r.out);
}
});
test("Vikunja 614 precheck: notifier config refuses missing, public, malformed and extra-key decisions", (t) => {
for (const fault of ["missing", "mode", "directory", "extra", "json", "binding", "version", "symlink"]) {
const x = host(t);
const dir = join(x.dataRoot, "notify", "acme"), file = join(dir, "notify.json");
mkdirSync(dir, { recursive: true, mode: 0o700 });
writeFileSync(file, '{"notifyVersion":1,"binding":null}\n', { mode: 0o600 });
if (fault === "missing") rmSync(file);
if (fault === "mode") chmodSync(file, 0o644);
if (fault === "directory") chmodSync(dir, 0o755);
if (fault === "extra") writeFileSync(file, '{"notifyVersion":1,"binding":null,"extra":true}\n');
if (fault === "json") writeFileSync(file, '{bad json\n');
if (fault === "binding") writeFileSync(file, '{"notifyVersion":1,"binding":"bad binding"}\n');
if (fault === "version") writeFileSync(file, '{"notifyVersion":2,"binding":null}\n');
if (fault === "symlink") {
const target = join(dir, "target.json");
writeFileSync(target, readFileSync(file), { mode: 0o600 });
rmSync(file); symlinkSync(target, file);
}
const r = precheck(x);
assert.equal(r.code, 1, `${fault}: ${r.out}`);
assert.match(r.out, /REFUSED notifier config:/, `${fault}: ${r.out}`);
}
});
+22
View File
@@ -316,6 +316,28 @@ test("row 194 CLI V5: delete polls to the transaction and the read lists the nam
assert.match(failed.err, new RegExp(`^mosaic: workspace-rename-failed: .*run the same delete again to retry the rename \\(request [^,]+, transaction ${s.log().at(-1).transaction}\\)$`, "m"));
});
// Row 239 (#1745): a fire's or a delete's revoke runs under the writer's lock. A delete closed after
// that revoke ran says the tokens may already be revoked; a plain revision-conflict keeps its text.
test("row 239 T5 CLI: a delete closed -revoked says the tokens may already be revoked; a plain revision-conflict doesn't", async (t) => {
let refusal = "revision-conflict-revoked";
const s = await setup(t, { hook: closing(() => ({ refusal })) });
const added = await s.mosaic(["instance", "add", "acme", "sec-1", "--definition", "security-reviewer", "--revision", await s.revision()]);
assert.equal(added.code, 0, added.err);
const del = async () => s.mosaic(["instance", "delete", "acme", "sec-1", "--revision", await s.revision()]);
let r = await del();
assert.equal(r.code, 3, r.err);
assert.match(r.err, /^mosaic: revision-conflict-revoked: the business file changed after the agent's tokens were revoked .*; the tokens may already be revoked .*which is safe \(request [^)]+\)$/m);
refusal = "outcome-unknown-revoked";
r = await del();
assert.equal(r.code, 3, r.err);
assert.match(r.err, /^mosaic: outcome-unknown-revoked: the agent's tokens may already be revoked and the write's outcome is unknown; .* \(request [^)]+\)$/m);
refusal = "revision-conflict";
r = await del();
assert.equal(r.code, 3, r.err);
assert.match(r.err, /^mosaic: revision-conflict: the business file changed since that revision; .* \(request [^)]+\)$/m);
assert.doesNotMatch(r.err, /may already be revoked/);
});
test("row 194 CLI: lifecycle and veto usage errors exit 4 before any bus call", async (t) => {
const s = await setup(t);
const rev = "a".repeat(64);
+2 -2
View File
@@ -1,4 +1,4 @@
import { FAR_DATE, launchDoc } from "../../business/tests/helpers.mjs";
import { launchDoc } from "../../business/tests/helpers.mjs";
// The S6 launcher inside a real bus host: real broker child, real runners
// in the bwrap sandbox, the fake adapter from packages/harness standing in for the
// harness. The chief of staff launches a coder through its `launch` tool (row 119: the
@@ -766,7 +766,7 @@ test("row 64 a role skill that isn't enabled refuses skill-not-enabled, and one
test("row 213 a creative instance's persona is read from <configDir>/personas: off its digest the launch fails with the mismatch as its reason", { timeout: 30000 }, async (t) => {
const text = "Warm. PERSONA-MARKER-d2\n";
const given = prepare(t, (doc) => {
doc.roles.bean = { definition: "companion", credentials: { gitea: { store: true, rotateBy: FAR_DATE } }, vars: { harness: "pi", model: "claude-sonnet-5-5", thinking: "high", "persona.name": "Bean", "persona.sha256": createHash("sha256").update(text).digest("hex") } };
doc.roles.bean = { definition: "companion", vars: { harness: "pi", model: "claude-sonnet-5-5", thinking: "high", "persona.name": "Bean", "persona.sha256": createHash("sha256").update(text).digest("hex") } };
doc.launch.instances.push("bean");
return doc;
});
+22
View File
@@ -347,3 +347,25 @@ test('row 232: check --units external reads the system units, the default reads
rmSync(argv);
}
});
test('Vikunja 614: bundle and checkout copy leave an unreadable caller directory before find',t=>{
const s=setup(t),cwd=join(s.root,'unreadable');mkdirSync(cwd);
const bundle=join(s.root,'release.bundle');git(s.repo,'bundle','create','-q',bundle,'refactor');
// Enter while searchable, then reproduce a cwd inherited across a uid drop:
// the caller can neither read nor search it. Absolute bundle lookup must work.
const enter='cd "$1" && chmod 000 . && [ ! -r . ] && [ ! -x . ] && shift && exec "$@"';
for(const [name,args] of [['bundle',['copy','--bundle',bundle,s.id]],['checkout',['copy',s.id]]]){
const copies=join(s.root,`copies-${name}`);
try{
const r=spawnSync('/bin/sh',['-c',enter,'stack-copy-cwd',cwd,join(s.repo,'scripts','stack-copy.sh'),...args,'--copies',copies],{env:s.env,encoding:'utf8',timeout:30000});
assert.equal(statSync(cwd).mode&0o555,0,'the inherited cwd is neither readable nor searchable');
assert.equal(r.status,0,r.stdout+r.stderr);
assert.doesNotMatch(r.stderr,/Failed to (restore initial working|change) directory|Permission denied/);
assert.ok(existsSync(join(copies,s.id,'scripts','mosaic')));
assert.equal(statSync(join(copies,s.id)).mode&0o777,0o555);
}finally{
// Restore even after a failed assertion/mutant, before setup's recursive cleanup.
chmodSync(cwd,0o700);
}
}
});
-22
View File
@@ -27,7 +27,6 @@ import { bootConfig, loadSystem } from "../src/config.mjs";
import { startTimeOf } from "../src/host.mjs";
import { createLauncher } from "../src/launcher.mjs";
import { fakeHarnesses, fixture, tmp } from "./helpers.mjs";
import { mappingEntry } from "../../library/tests/helpers.mjs";
// Row 264a (#1769): a thread made by hand gets the default session the 3k-3l migration gives a
// legacy thread, with the thread's id.
const DEFAULT_SESSION = [
@@ -530,24 +529,3 @@ test('C2-09a: terminating one creative thread does not signal an unselected peer
await until(() => !readSessions(f.dataRoot).some(row => row.run === runs[0]));
assert.ok(readSessions(f.dataRoot).some(row => row.run === runs[1]));
});
// Row224: the launcher must derive library presence from business projects, not
// from session checkouts (a library never has an agent clone).
test("C2-05b a real launched bundle gets lookups for a library project without a library checkout", { skip, timeout: 60000 }, async t => {
const prepared = prepare(t, { idle: 10, edit: doc => {
doc.projects.books = mappingEntry();
return doc;
} });
const { f } = prepared;
const host = await start(t, prepared);
const project = host.call("project.create", { name: "library work", repo: "stack" }).id;
const thread = host.call("thread.create", { project, name: "lookup" }).id;
await ask(host.call, thread, "inspect bundle");
const run = launchLog(f).find(e => e.event === "launch" && e.thread === thread).run;
const tools = JSON.parse(readFileSync(join(f.dataRoot, "launches", "acme", run, "bundle", "tools.json"), "utf8"));
assert.deepEqual(tools.filter(tool => tool.name.startsWith("library_")).map(tool => tool.name),
["library_find", "library_get", "library_search", "library_manuscript", "library_universe"]);
const [session] = threadRuns(f, thread);
assert.ok(session);
assert.ok(!session.checkouts?.some(checkout => checkout.project === "books"));
});
+2
View File
@@ -45,6 +45,8 @@ test("a bus code on stderr becomes the exit code; garbage and timeouts are outco
test("busExit and refuseInsideAgent", () => {
assert.equal(busExit("unauthenticated"), 3);
assert.equal(busExit("invalid-request"), 2);
// Row 239 (#1745): a write whose outcome is unknown after its revoke exits as outcome-unknown does.
assert.equal(busExit("outcome-unknown-revoked"), 1);
assert.doesNotThrow(() => refuseInsideAgent(humanEnv()));
assert.throws(() => refuseInsideAgent({ PI_AGENT_DIR: "/x" }), (e) => e.exitCode === 3 && /PI_AGENT_DIR/.test(e.message));
});
+36 -4
View File
@@ -48,6 +48,9 @@ import { hostname } from "node:os";
import { spawnSync } from "node:child_process";
import { scan, markSeen, seenKey, ConfigError, loadRegistrations } from "./scan.mjs";
import { createReader, rootsFromSpecs } from "../../conversation/src/reader.mjs";
import { Refusal } from "../../conversation/src/safe-fs.mjs";
import { loadSeatSets } from "../../business/src/library-seats.mjs";
import { configDir } from "../../business/src/business.mjs";
const MAX_BODY = 4096;
@@ -170,6 +173,8 @@ export function foreignRequest(req) {
export const REFUSAL_STATUS = {
"unknown-conversation": 404,
"unknown-branch": 404,
"conversation-not-listed": 404,
"conversation-business-unreadable": 503,
unavailable: 404,
"cursor-unknown": 409,
"cursor-expired": 409,
@@ -210,7 +215,8 @@ function conversationQuery(url) {
export function conversationResponse(reader, url) {
if (url.pathname === "/api/conversations") {
if ([...url.searchParams.keys()].length) return { status: 400, body: { error: "no parameters are accepted" } };
return { status: 200, body: reader.catalogue() };
const listing = reader.catalogue();
return listing.ok ? { status: 200, body: listing } : refusalResponse(listing);
}
const query = conversationQuery(url);
if (query.error) return { status: 400, body: { error: query.error } };
@@ -218,17 +224,43 @@ export function conversationResponse(reader, url) {
? reader.next({ cursor: query.cursor, conversation: query.id, branch: query.branch })
: reader.open({ conversation: query.id, branch: query.branch ?? null });
if (out.ok) return { status: 200, body: out };
return refusalResponse(out);
}
function refusalResponse(out) {
return { status: REFUSAL_STATUS[out.refusal.code] ?? 422, body: { error: out.refusal.message, refusal: { code: out.refusal.code, reconcile: out.refusal.reconcile } } };
}
// Case 2 M7 (design 5.1): a root whose seat is creative in a library business is
// hidden from the catalogue and from open and next. creativeCheck(dir) returns the
// factory the reader calls once per public call: each call reads the business sets
// once and applies that one answer to every root, so an edited business file takes
// effect on the next call without a restart. A business file that can't be read
// refuses the whole call with conversation-business-unreadable.
export function creativeCheck(dir = configDir()) {
return () => {
let sets;
try {
sets = loadSeatSets({ dir });
} catch (err) {
throw new Refusal("conversation-business-unreadable", `a business file cannot be read: ${err.message}`);
}
return (root) => sets.creativeSeats.has(root.seat);
};
}
export function loadPage(path = join(import.meta.dirname, "page.html")) {
return readFileSync(path, "utf8");
}
// specs: agent specs to scan on each request. boardDir: where scan writes.
export function createServer({ specs, boardDir, isAlive, now, seatsDir = null, discordDataRoot = null, page = loadPage(), isPidAlive, agentSend = DEFAULT_AGENT_SEND, exec = spawnSync, conversationReader = null }) {
// specs: agent specs to scan on each request. boardDir: where scan writes. configDirectory: the config
// directory whose businesses/ the default conversation reader reads for M7 (the instance's, by default).
export function createServer({ specs, boardDir, isAlive, now, seatsDir = null, discordDataRoot = null, page = loadPage(), isPidAlive, agentSend = DEFAULT_AGENT_SEND, exec = spawnSync, conversationReader = null, configDirectory = configDir() }) {
const rescan = () => scan(specs, { boardDir, isAlive, now, seatsDir, isPidAlive, discordDataRoot });
const reader = conversationReader ?? createReader({ roots: () => rootsFromSpecs(specs, loadRegistrations(seatsDir).registrations) });
const reader = conversationReader ?? createReader({
roots: () => rootsFromSpecs(specs, loadRegistrations(seatsDir).registrations),
creativeCheck: creativeCheck(configDirectory),
});
return createHttpServer((req, res) => {
const refused = foreignRequest(req);
if (refused) {
@@ -0,0 +1,130 @@
// Case 2 M7 (design 5.1, row 220): a creative seat's conversations are hidden from
// the catalogue, from open and from next. The thread store is a second wall: a
// root built over it is hidden, and no spec under .pi/state reaches it. A business
// file the board can't read refuses the listing and open, never a partial list.
import { test } from "node:test";
import assert from "node:assert/strict";
import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { conversationResponse, creativeCheck, startServer, REFUSAL_STATUS } from "../src/serve.mjs";
import { conversationId, createReader, rootsFromSpecs } from "../../conversation/src/reader.mjs";
import { businessDoc, writeJson } from "../../business/tests/helpers.mjs";
import { mappingEntry } from "../../library/tests/helpers.mjs";
// A config directory holding one library business whose seat "bean" is creative,
// and a thread store for bean's session under <data>/threads/<business>/<thread>.
function fixture(t) {
const root = mkdtempSync(join(tmpdir(), "row220-board-"));
t.after(() => rmSync(root, { recursive: true, force: true }));
const dir = join(root, "config");
const doc = businessDoc(root, "acme");
doc.projects = { books: mappingEntry(), ...doc.projects };
doc.roles.bean = { definition: "companion" };
writeJson(join(dir, "businesses", "acme.json"), doc);
const threadDir = join(root, "data", "threads", "acme", "t1", "session");
mkdirSync(threadDir, { recursive: true });
writeFileSync(join(threadDir, "s.jsonl"), "{}\n");
const threadRoot = { seat: "bean", project: "acme", projectRoot: join(root, "data"), dir: threadDir, harness: "pi", unsupportedReason: null, engineStartedAt: null };
return { root, dir, threadDir, threadRoot };
}
function breakBusinessFile(dir) {
const file = join(dir, "businesses", "broken.json");
writeFileSync(file, "{");
chmodSync(file, 0o600);
}
const detail = (id) => new URL(`/api/conversation?id=${encodeURIComponent(id)}`, "http://localhost");
const listing = new URL("/api/conversations", "http://localhost");
test("M7: the check hides the creative seat, shows the others, and refuses when a business file is unreadable", (t) => {
const f = fixture(t);
const hidden = creativeCheck(f.dir)();
assert.equal(hidden({ seat: "bean" }), true);
assert.equal(hidden({ seat: "pm" }), false);
breakBusinessFile(f.dir);
assert.throws(() => creativeCheck(f.dir)(), (err) => err.code === "conversation-business-unreadable");
});
test("M7: a thread store is not a root from a spec, and a root built over it is hidden from the list and from open", (t) => {
const f = fixture(t);
// The spec layout check in rootsFromSpecs drops a thread-store directory.
assert.deepEqual(rootsFromSpecs([{ agent: "bean", project: "acme", sessionsDir: f.threadDir }]), []);
const reader = createReader({ roots: [f.threadRoot], creativeCheck: creativeCheck(f.dir) });
const cat = reader.catalogue();
assert.deepEqual([cat.conversations, cat.refusedRoots], [[], []], "the root is hidden, not refused");
const out = conversationResponse(reader, detail(conversationId(f.threadRoot, "s.jsonl")));
assert.equal(out.status, REFUSAL_STATUS["conversation-not-listed"]);
assert.equal(out.status, 404);
assert.equal(out.body.refusal.code, "conversation-not-listed");
});
test("M7: with an unreadable business file, a known and an unknown id both refuse with 503", (t) => {
const f = fixture(t);
breakBusinessFile(f.dir);
const reader = createReader({ roots: [f.threadRoot], creativeCheck: creativeCheck(f.dir) });
const known = conversationResponse(reader, detail(conversationId(f.threadRoot, "s.jsonl")));
const unknown = conversationResponse(reader, detail(conversationId(f.threadRoot, "missing.jsonl")));
for (const out of [known, unknown]) {
assert.equal(out.status, 503);
assert.equal(out.body.refusal.code, "conversation-business-unreadable");
}
});
test("M7: an unreadable business file refuses the listing and open with 503, never a partial list", (t) => {
const f = fixture(t);
breakBusinessFile(f.dir);
const reader = createReader({ roots: [f.threadRoot], creativeCheck: creativeCheck(f.dir) });
const cat = conversationResponse(reader, listing);
assert.equal(cat.status, 503);
assert.equal(cat.body.refusal.code, "conversation-business-unreadable");
assert.equal(cat.body.conversations, undefined);
const opened = conversationResponse(reader, detail(conversationId(f.threadRoot, "s.jsonl")));
assert.equal(opened.status, REFUSAL_STATUS["conversation-business-unreadable"]);
assert.equal(opened.status, 503);
});
// C2: every test above builds its own reader. This one starts the board with no
// injected reader, so the check reaches the reader only through createServer's
// wiring (serve.mjs: `creativeCheck: creativeCheck(configDirectory)`). Deleting that
// line shows bean's session in the listing and fails the first assertion below.
// It also shows the business file in the fixture's config directory is the one
// read: bean is hidden and pm is not, and no other file says so.
test("M7: the board's default reader hides a creative seat's session from the listing and the detail route", async (t) => {
const f = fixture(t);
const proj = join(f.root, "proj");
const specs = [];
for (const [n, seat] of ["bean", "pm"].entries()) {
const sessionsDir = join(proj, ".pi", "state", seat, "sessions");
mkdirSync(sessionsDir, { recursive: true });
const header = { type: "session", version: 3, id: `c0ffee00-0000-4000-8000-00000000000${n + 1}`, timestamp: "2026-10-22T12:00:00.000Z", cwd: proj };
const message = { type: "message", id: "e0", parentId: null, timestamp: "2026-10-22T12:00:01.000Z", message: { role: "user", content: [{ type: "text", text: `${seat.toUpperCase()}-TEXT` }] } };
writeFileSync(join(sessionsDir, "s.jsonl"), [header, message].map((l) => JSON.stringify(l)).join("\n") + "\n");
specs.push({ agent: seat, project: "proj", sessionsDir, tmux: {} });
}
const roots = rootsFromSpecs(specs);
const idOf = (seat) => conversationId(roots.find((r) => r.seat === seat), "s.jsonl");
const server = await startServer({ host: "127.0.0.1", port: 0, specs, boardDir: join(f.root, "board"), seatsDir: join(f.root, "seats"), configDirectory: f.dir, isAlive: () => true, page: "<html></html>" });
t.after(() => { server.closeAllConnections(); server.close(); });
const base = `http://127.0.0.1:${server.address().port}`;
const get = async (path) => {
const res = await fetch(base + path);
return { status: res.status, text: await res.text() };
};
const cat = await get("/api/conversations");
assert.equal(cat.status, 200, cat.text);
assert.deepEqual(JSON.parse(cat.text).conversations.map((c) => c.seat), ["pm"]);
assert.ok(!cat.text.includes("BEAN-TEXT"));
const hidden = await get(`/api/conversation?id=${encodeURIComponent(idOf("bean"))}`);
assert.equal(hidden.status, 404, hidden.text);
assert.equal(JSON.parse(hidden.text).refusal.code, "conversation-not-listed");
assert.ok(!hidden.text.includes("BEAN-TEXT"));
const shown = await get(`/api/conversation?id=${encodeURIComponent(idOf("pm"))}`);
assert.equal(shown.status, 200, shown.text);
// The file is read on every call: a broken business file now refuses the same route.
breakBusinessFile(f.dir);
const refused = await get("/api/conversations");
assert.equal(refused.status, 503, refused.text);
assert.equal(JSON.parse(refused.text).refusal.code, "conversation-business-unreadable");
});
@@ -120,7 +120,7 @@ test('server rescans connector discovery and refuses HTTP reply without transpor
try {
const sessionsDir = join(f.root, 'sessions', 'discord-demo'), seatsDir = join(f.root, 'seats');
writeRegistration(seatsDir, makeRegistration({ resolved: { seat: 'forged', project: 'fleet', sessionsDir, seatDir: sessionsDir, launchScript: join(f.root, 'unused.sh'), layout: 'repo', defaultWorkspace: f.root }, task: 'forged', tmux: { session: 'forged', socket: null }, pid: process.pid }));
server = await startServer({ port: 0, specs: [], seatsDir, boardDir: join(f.root, 'board'), discordDataRoot: f.root, exec: () => { throw Error('transport forbidden'); } });
server = await startServer({ port: 0, specs: [], seatsDir, configDirectory: f.root, boardDir: join(f.root, 'board'), discordDataRoot: f.root, exec: () => { throw Error('transport forbidden'); } });
const base = `http://127.0.0.1:${server.address().port}`;
let response = await fetch(base + '/api/board'); const board = await response.json();
assert.equal(board.sessions[0].state, 'idle'); assert.equal(board.sessions[0].connector.alive, true);
+36 -14
View File
@@ -23,7 +23,7 @@ import { request as httpRequest } from "node:http";
import { ConfigError, markSeen } from "../src/scan.mjs";
import { isLoopbackHost, startServer, DEFAULT_AGENT_SEND, REPLY_LIMIT, REPLY_TRAILER, REFUSAL_STATUS } from "../src/serve.mjs";
import { writeRegistration, makeRegistration } from "../../seat/src/seat.mjs";
import { UNSUPPORTED_HARNESS } from "../../conversation/src/reader.mjs";
import { UNSUPPORTED_HARNESS, NOT_LISTED } from "../../conversation/src/reader.mjs";
const pkgRoot = resolve(import.meta.dirname, "..");
const cli = join(pkgRoot, "src", "cli.mjs");
@@ -725,7 +725,7 @@ function replyFixture({ tmux = { socket: null, session: "agent1" }, pid = proces
}
const capture = join(root, "capture.json");
process.env.FAKE_SEND_CAPTURE = capture;
return { root, sessionsDir, seatsDir, boardDir: join(root, "board"), agentSend: writeFakeAgentSend(root), capture,
return { root, sessionsDir, seatsDir, configDirectory: root, boardDir: join(root, "board"), agentSend: writeFakeAgentSend(root), capture,
specs: [{ agent: "agent1", project: "proj", sessionsDir, tmux: {} }] };
}
@@ -736,7 +736,7 @@ async function postReply(base, body, headers = { "content-type": "application/js
test("POST /api/reply: runs agent-send.sh with -s from the registration, -S <host>:control-board, -m text plus the fixed trailer, no -L on the default socket, MOSAIC_TMUX_SOCKET stripped; answers delivered with the exit code and both streams", async () => {
const f = replyFixture();
const server = await startServer({ host: "127.0.0.1", port: 0, specs: f.specs, boardDir: f.boardDir, seatsDir: f.seatsDir, isAlive: () => true, page: "<html></html>", agentSend: f.agentSend, now: () => new Date("2026-09-12T18:00:00Z") });
const server = await startServer({ host: "127.0.0.1", port: 0, specs: f.specs, boardDir: f.boardDir, seatsDir: f.seatsDir, configDirectory: f.configDirectory, isAlive: () => true, page: "<html></html>", agentSend: f.agentSend, now: () => new Date("2026-09-12T18:00:00Z") });
const base = `http://127.0.0.1:${server.address().port}`;
process.env.MOSAIC_TMUX_SOCKET = "leaked-from-launcher";
delete process.env.FAKE_SEND_EXIT;
@@ -768,7 +768,7 @@ test("POST /api/reply: runs agent-send.sh with -s from the registration, -S <hos
test("POST /api/reply: a registration with a tmux socket adds -L <socket>", async () => {
const f = replyFixture({ tmux: { socket: "mosaic-fleet", session: "agent1" } });
const server = await startServer({ host: "127.0.0.1", port: 0, specs: f.specs, boardDir: f.boardDir, seatsDir: f.seatsDir, isAlive: () => true, page: "<html></html>", agentSend: f.agentSend });
const server = await startServer({ host: "127.0.0.1", port: 0, specs: f.specs, boardDir: f.boardDir, seatsDir: f.seatsDir, configDirectory: f.configDirectory, isAlive: () => true, page: "<html></html>", agentSend: f.agentSend });
const base = `http://127.0.0.1:${server.address().port}`;
try {
const { status, body } = await postReply(base, { agent: "proj/agent1", text: "hi" });
@@ -783,7 +783,7 @@ test("POST /api/reply: a registration with a tmux socket adds -L <socket>", asyn
test("POST /api/reply: a non-zero tool exit is a 200 with delivered false, the exit code and the stderr verbatim", async () => {
const f = replyFixture();
const server = await startServer({ host: "127.0.0.1", port: 0, specs: f.specs, boardDir: f.boardDir, seatsDir: f.seatsDir, isAlive: () => true, page: "<html></html>", agentSend: f.agentSend });
const server = await startServer({ host: "127.0.0.1", port: 0, specs: f.specs, boardDir: f.boardDir, seatsDir: f.seatsDir, configDirectory: f.configDirectory, isAlive: () => true, page: "<html></html>", agentSend: f.agentSend });
const base = `http://127.0.0.1:${server.address().port}`;
process.env.FAKE_SEND_EXIT = "4";
process.env.FAKE_SEND_STDERR = "agent-send.sh: REFUSING - session 'agent1' exists on multiple sockets\n";
@@ -814,7 +814,7 @@ test("POST /api/reply: refusals before the tool runs: empty or blank or long tex
];
for (const c of cases) {
const f = c.fixture;
const server = await startServer({ host: "127.0.0.1", port: 0, specs: f.specs, boardDir: f.boardDir, seatsDir: f.seatsDir, isAlive: () => true, page: "<html></html>", agentSend: f.agentSend, isPidAlive: c.isPidAlive });
const server = await startServer({ host: "127.0.0.1", port: 0, specs: f.specs, boardDir: f.boardDir, seatsDir: f.seatsDir, configDirectory: f.configDirectory, isAlive: () => true, page: "<html></html>", agentSend: f.agentSend, isPidAlive: c.isPidAlive });
const base = `http://127.0.0.1:${server.address().port}`;
try {
const { status, body } = await postReply(base, c.body);
@@ -829,7 +829,7 @@ test("POST /api/reply: refusals before the tool runs: empty or blank or long tex
test("POST /api/reply: a missing agent-send.sh is a 500 with the path in the error, not a crash", async () => {
const f = replyFixture();
const server = await startServer({ host: "127.0.0.1", port: 0, specs: f.specs, boardDir: f.boardDir, seatsDir: f.seatsDir, isAlive: () => true, page: "<html></html>", agentSend: join(f.root, "missing-agent-send.sh") });
const server = await startServer({ host: "127.0.0.1", port: 0, specs: f.specs, boardDir: f.boardDir, seatsDir: f.seatsDir, configDirectory: f.configDirectory, isAlive: () => true, page: "<html></html>", agentSend: join(f.root, "missing-agent-send.sh") });
const base = `http://127.0.0.1:${server.address().port}`;
try {
const { status, body } = await postReply(base, { agent: "proj/agent1", text: "hi" });
@@ -964,7 +964,7 @@ function rawRequest(port, { method = "GET", path = "/api/board", headers = {}, b
test("Host/Origin guard: GET /api/board and POST /api/reply refuse a foreign Host, a wrong port and a cross-origin Origin with 403 JSON, before any scan or send, and never send CORS headers", async () => {
const f = replyFixture();
const server = await startServer({ host: "127.0.0.1", port: 0, specs: f.specs, boardDir: f.boardDir, seatsDir: f.seatsDir, isAlive: () => true, page: "<html></html>", agentSend: f.agentSend });
const server = await startServer({ host: "127.0.0.1", port: 0, specs: f.specs, boardDir: f.boardDir, seatsDir: f.seatsDir, configDirectory: f.configDirectory, isAlive: () => true, page: "<html></html>", agentSend: f.agentSend });
const port = server.address().port;
const own = `127.0.0.1:${port}`;
const reply = JSON.stringify({ agent: "proj/agent1", text: "rebound page" });
@@ -1003,7 +1003,7 @@ test("Host/Origin guard: GET /api/board and POST /api/reply refuse a foreign Hos
test("Host/Origin guard: loopback names on this port are accepted, with or without a same-origin Origin", async () => {
const f = replyFixture();
const server = await startServer({ host: "127.0.0.1", port: 0, specs: f.specs, boardDir: f.boardDir, seatsDir: f.seatsDir, isAlive: () => true, page: "<html></html>", agentSend: f.agentSend });
const server = await startServer({ host: "127.0.0.1", port: 0, specs: f.specs, boardDir: f.boardDir, seatsDir: f.seatsDir, configDirectory: f.configDirectory, isAlive: () => true, page: "<html></html>", agentSend: f.agentSend });
const port = server.address().port;
delete process.env.FAKE_SEND_EXIT;
delete process.env.FAKE_SEND_STDERR;
@@ -1049,7 +1049,8 @@ function conversationFixture() {
resolved: { seat: "rocko", project: "proj", sessionsDir: join(proj, ".pi", "state", "rocko", "sessions"), seatDir: join(root, "rocko"), launchScript: join(root, "rocko", "launch.sh"), layout: "repo", defaultWorkspace: null },
harness: "claude-code",
}));
return { root, proj, sessionsDir, seatsDir, boardDir: join(root, "board"), specs: [{ agent: "agent1", project: "proj", sessionsDir, tmux: {} }] };
// Row 220 M7: the default reader reads <root>/businesses, which does not exist here, never the real config.
return { root, proj, sessionsDir, seatsDir, configDirectory: root, boardDir: join(root, "board"), specs: [{ agent: "agent1", project: "proj", sessionsDir, tmux: {} }] };
}
// Size, sha256, mtime, (dev, ino) and listing of every entry under dir.
@@ -1069,8 +1070,13 @@ function createHashHex(buf) {
test("conversation routes (F16): a foreign Host, a wrong port and a cross-origin Origin get 403 before the reader runs, with no CORS headers", async () => {
const f = conversationFixture();
const calls = [];
const spy = { catalogue: () => calls.push("catalogue"), open: () => calls.push("open"), next: () => calls.push("next") };
const server = await startServer({ host: "127.0.0.1", port: 0, specs: f.specs, boardDir: f.boardDir, seatsDir: f.seatsDir, isAlive: () => true, page: "<html></html>", conversationReader: spy });
const spy = {
// The route reads .ok on the listing, so the catalogue spy returns a listing, not the call count.
catalogue: () => { calls.push("catalogue"); return { ok: true, conversations: [], refusedRoots: [] }; },
open: () => calls.push("open"),
next: () => calls.push("next"),
};
const server = await startServer({ host: "127.0.0.1", port: 0, specs: f.specs, boardDir: f.boardDir, seatsDir: f.seatsDir, configDirectory: f.configDirectory, isAlive: () => true, page: "<html></html>", conversationReader: spy });
const port = server.address().port;
const own = `127.0.0.1:${port}`;
const cases = [
@@ -1096,18 +1102,34 @@ test("conversation routes (F16): a foreign Host, a wrong port and a cross-origin
}
});
test("conversation routes: a reader listing that refuses gets its refusal status and body, not a 200", async () => {
const f = conversationFixture();
const refusal = { code: "conversation-business-unreadable", reconcile: "fix the business file", message: "a business file can't be read" };
const spy = { catalogue: () => ({ ok: false, refusal }), open: () => ({ ok: false, refusal }), next: () => ({ ok: false, refusal }) };
const server = await startServer({ host: "127.0.0.1", port: 0, specs: f.specs, boardDir: f.boardDir, seatsDir: f.seatsDir, configDirectory: f.configDirectory, isAlive: () => true, page: "<html></html>", conversationReader: spy });
try {
const res = await fetch(`http://127.0.0.1:${server.address().port}/api/conversations`);
assert.equal(res.status, 503);
assert.deepEqual(await res.json(), { error: refusal.message, refusal: { code: refusal.code, reconcile: refusal.reconcile } });
} finally {
await closeServer(server);
}
});
test("every refusal code the reader can raise has an HTTP status", () => {
// Every source file in the reader package, so a refusal added in a new file is seen too.
const dir = join(pkgRoot, "..", "conversation", "src");
const src = readdirSync(dir).filter((f) => f.endsWith(".mjs")).map((f) => readFileSync(join(dir, f), "utf8")).join("\n");
const codes = new Set([...src.matchAll(/new Refusal\(\s*"([a-z-]+)"/g)].map((m) => m[1]));
codes.add(UNSUPPORTED_HARNESS); // raised by value, as a root's unsupportedReason
codes.add(NOT_LISTED); // raised by value (row 220 M7), so the literal scan misses it
codes.add("conversation-business-unreadable"); // raised by the board's creative predicate in serve.mjs (row 220 M7)
assert.ok(codes.size >= 15, [...codes].join(" "));
assert.deepEqual([...codes].filter((c) => !(c in REFUSAL_STATUS)), []);
assert.deepEqual(Object.keys(REFUSAL_STATUS).filter((c) => !codes.has(c)), [], "no stale entries");
// The statuses themselves, so a changed value fails here even where no route test reaches it.
assert.deepEqual(REFUSAL_STATUS, {
"unknown-conversation": 404, "unknown-branch": 404, unavailable: 404,
"unknown-conversation": 404, "unknown-branch": 404, unavailable: 404, "conversation-not-listed": 404, "conversation-business-unreadable": 503,
"cursor-unknown": 409, "cursor-expired": 409, "cursor-foreign": 409, "source-replaced": 409, "incomplete-header": 409,
"unsafe-path": 403, "foreign-project": 403, unreadable: 403, "unknown-actor": 403,
"unsupported-harness": 422, "not-a-pi-session": 422, "too-large": 422, "unsupported-purpose": 422,
@@ -1117,7 +1139,7 @@ test("every refusal code the reader can raise has an HTTP status", () => {
test("conversation routes: catalogue, first page, next page and follow over HTTP; refusals map to 4xx with their code; nothing is written", async () => {
const f = conversationFixture();
const before = treePrint(f.sessionsDir);
const server = await startServer({ host: "127.0.0.1", port: 0, specs: f.specs, boardDir: f.boardDir, seatsDir: f.seatsDir, isAlive: () => true, page: "<html></html>" });
const server = await startServer({ host: "127.0.0.1", port: 0, specs: f.specs, boardDir: f.boardDir, seatsDir: f.seatsDir, configDirectory: f.configDirectory, isAlive: () => true, page: "<html></html>" });
const base = `http://127.0.0.1:${server.address().port}`;
const get = async (path) => {
const res = await fetch(base + path);
+45 -18
View File
@@ -22,6 +22,8 @@ import { samePath } from "../../seat/src/seat.mjs";
export const ACTOR = "local-operator";
export const HISTORY = "pi";
export const UNSUPPORTED_HARNESS = "unsupported-harness";
// Case 2 design 5.1 M7: a creative root's conversations are not listed and do not open.
export const NOT_LISTED = "conversation-not-listed";
const NO_STREAM = "no-stream";
const HEAD_BYTES = 1024 * 1024;
const TAIL_BYTES = 2 * 1024 * 1024;
@@ -201,8 +203,20 @@ function readSnapshot(root, name, pinnedLength = null) {
}
}
export function createReader({ roots, now = () => Date.now(), ttlMs = 10 * 60 * 1000, maxCursors = 1000, cacheSize = 2 } = {}) {
// creativeCheck() is the caller's per-call answer: it returns a predicate that is
// true when a root's seat is a creative instance on a business with a library
// project (design 5.1 M7). The reader calls it once per public call (catalogue,
// open, next), so one call reads the business sets once for every root. It may
// throw (an unreadable business file), which refuses the whole call. The reader
// only hides; it reads no business file itself. A truthy answer hides, so a
// doubtful one fails closed. The answer must depend on root.seat and root.project
// alone, because a cursor is checked against a root object from an earlier listing.
export function createReader({ roots, now = () => Date.now(), ttlMs = 10 * 60 * 1000, maxCursors = 1000, cacheSize = 2, creativeCheck = () => () => false } = {}) {
const listRoots = typeof roots === "function" ? roots : () => roots ?? [];
const hiddenCheck = () => {
const answer = creativeCheck();
return (root) => Boolean(answer(root));
};
const cursors = new Map();
const parsedCache = new Map();
const partsCache = new Map();
@@ -241,26 +255,34 @@ export function createReader({ roots, now = () => Date.now(), ttlMs = 10 * 60 *
return null;
}
// A refusal from the hidden check (an unreadable business file) refuses the
// whole listing; it never lists some roots and drops the rest silently.
function catalogue() {
const conversations = [], refusedRoots = [];
for (const root of listRoots()) {
if (root.unsupportedReason) {
conversations.push({ ...baseRow(root, unsupportedId(root)), engineStartedAt: root.engineStartedAt, availability: "unsupported" });
continue;
try {
const hidden = hiddenCheck();
const conversations = [], refusedRoots = [];
for (const root of listRoots()) {
if (hidden(root)) continue;
if (root.unsupportedReason) {
conversations.push({ ...baseRow(root, unsupportedId(root)), engineStartedAt: root.engineStartedAt, availability: "unsupported" });
continue;
}
let listing;
try {
listing = listSessionFiles(root);
} catch (err) {
if (!(err instanceof Refusal)) throw err;
refusedRoots.push({ seat: root.seat, project: root.project, refusal: err.code });
continue;
}
for (const name of listing.files) conversations.push(summarize(root, name));
for (const r of listing.refused) conversations.push({ ...baseRow(root, conversationId(root, r.name)), availability: "denied", refusal: r.code });
}
let listing;
try {
listing = listSessionFiles(root);
} catch (err) {
if (!(err instanceof Refusal)) throw err;
refusedRoots.push({ seat: root.seat, project: root.project, refusal: err.code });
continue;
}
for (const name of listing.files) conversations.push(summarize(root, name));
for (const r of listing.refused) conversations.push({ ...baseRow(root, conversationId(root, r.name)), availability: "denied", refusal: r.code });
conversations.sort((a, b) => (b.lastActivityAt ?? "").localeCompare(a.lastActivityAt ?? "") || a.conversation.localeCompare(b.conversation));
return { ok: true, conversations, refusedRoots, generatedAt: new Date(now()).toISOString() };
} catch (err) {
return refuse(err);
}
conversations.sort((a, b) => (b.lastActivityAt ?? "").localeCompare(a.lastActivityAt ?? "") || a.conversation.localeCompare(b.conversation));
return { ok: true, conversations, refusedRoots, generatedAt: new Date(now()).toISOString() };
}
// Parsed snapshot plus one branch's entries, cached by content. A null
@@ -347,8 +369,10 @@ export function createReader({ roots, now = () => Date.now(), ttlMs = 10 * 60 *
function open({ conversation, branch = null, actor = ACTOR, purpose = "history" } = {}) {
try {
checkCaller(actor, purpose);
const hidden = hiddenCheck();
const found = resolveConversation(conversation);
if (!found) throw new Refusal("unknown-conversation", "no such conversation in the approved roots", { reconcile: true });
if (hidden(found.root)) throw new Refusal(NOT_LISTED, "this conversation is not listed");
if (found.root.unsupportedReason) throw new Refusal(found.root.unsupportedReason, "this harness has no history reader yet");
const snap = snapshot(found.root, found.name);
const built = build(snap, found.root, branch ?? null, conversation);
@@ -362,6 +386,7 @@ export function createReader({ roots, now = () => Date.now(), ttlMs = 10 * 60 *
function next({ cursor, conversation, branch, actor = ACTOR, purpose = "history" } = {}) {
try {
const hidden = hiddenCheck();
const held = typeof cursor === "string" ? cursors.get(cursor) : undefined;
if (!held) throw new Refusal("cursor-unknown", "the cursor is unknown", { reconcile: true });
const { record, state } = held;
@@ -372,6 +397,8 @@ export function createReader({ roots, now = () => Date.now(), ttlMs = 10 * 60 *
if (actor !== record.actor || purpose !== record.purpose || conversation !== record.conversation || branch !== record.branch) {
throw new Refusal("cursor-foreign", "the cursor belongs to another view", { reconcile: true });
}
// A cursor issued before the root became creative stops here (M7).
if (hidden(state.root)) throw new Refusal(NOT_LISTED, "this conversation is not listed");
// The source must still be the snapshot's file with the same prefix.
const pinned = snapshot(state.root, state.name, state.length);
if (pinned.shorter) throw new Refusal("source-replaced", "the session file is shorter than the snapshot", { reconcile: true });
@@ -692,6 +692,79 @@ test("F15: a Claude seat is an unsupported-harness placeholder whose directory i
}
});
// M7 (Case 2 design 5.1): a creative seat's conversations are left out of the catalogue
// and refuse to open by id. The fixture text stands in for creative prose and must not
// appear in any output.
test("M7: a creative seat's session is not listed and won't open by id; an assistant seat still lists", () => {
const creative = project("bean");
const assistant = project("sage");
writeSession(creative.dir, "s.jsonl", header(creative.proj), [user("c1", null, "CREATIVE-MARKER", 1)]);
writeSession(assistant.dir, "s.jsonl", header(assistant.proj), [user("a1", null, "assistant text", 1)]);
const roots = rootsFromSpecs([creative.spec, assistant.spec]);
const reader = createReader({ roots, creativeCheck: () => (root) => root.seat === "bean" });
const cat = noWrites(tmp, () => reader.catalogue());
assert.deepEqual(cat.conversations.map((c) => c.seat), ["sage"]);
const hiddenOpen = noWrites(tmp, () => reader.open({ conversation: conversationId(roots.find((r) => r.seat === "bean"), "s.jsonl") }));
assert.deepEqual([hiddenOpen.ok, hiddenOpen.refusal.code, hiddenOpen.refusal.reconcile], [false, "conversation-not-listed", false]);
const shown = noWrites(tmp, () => reader.open({ conversation: conversationId(roots.find((r) => r.seat === "sage"), "s.jsonl") }));
assert.deepEqual([shown.ok, texts(shown.page)], [true, ["assistant text"]]);
assert.equal(JSON.stringify([cat, hiddenOpen]).includes("CREATIVE-MARKER"), false);
});
test("M7: one catalogue calls the creative check once, however many roots it lists", () => {
const creative = project("bean");
const assistant = project("sage");
writeSession(creative.dir, "s.jsonl", header(creative.proj), [user("c1", null, "one", 1)]);
writeSession(assistant.dir, "s.jsonl", header(assistant.proj), [user("a1", null, "two", 1)]);
const roots = rootsFromSpecs([creative.spec, assistant.spec]);
let calls = 0;
const reader = createReader({ roots, creativeCheck: () => { calls += 1; return (root) => root.seat === "bean"; } });
const cat = noWrites(tmp, () => reader.catalogue());
assert.deepEqual(cat.conversations.map((c) => c.seat), ["sage"]);
assert.equal(calls, 1);
const shown = noWrites(tmp, () => reader.open({ conversation: conversationId(roots.find((r) => r.seat === "sage"), "s.jsonl") }));
assert.equal(shown.ok, true);
assert.equal(calls, 2, "open is one more public call, so one more check");
noWrites(tmp, () => reader.next({ cursor: shown.follow.id, conversation: conversationId(roots.find((r) => r.seat === "sage"), "s.jsonl"), branch: shown.page.branch }));
assert.equal(calls, 3, "next is one more public call, so one more check");
assert.deepEqual(cat.refusedRoots, [], "a hidden root is not a refused root");
});
test("M7: a creative session already open refuses its next page once the root is hidden", () => {
const fx = project("bean");
writeSession(fx.dir, "s.jsonl", header(fx.proj), [user("c1", null, "CREATIVE-MARKER", 1), assistant("c2", "c1", "reply", 2)]);
let hide = false;
const roots = rootsFromSpecs([fx.spec]);
const reader = createReader({ roots, creativeCheck: () => () => hide });
const id = conversationId(roots[0], "s.jsonl");
const first = noWrites(fx.base, () => reader.open({ conversation: id }));
assert.equal(first.ok, true);
hide = true;
const r = noWrites(fx.base, () => reader.next({ cursor: first.follow.id, conversation: id, branch: first.page.branch }));
assert.deepEqual([r.ok, r.refusal.code], [false, "conversation-not-listed"]);
});
test("M7: a creative root's refused files and its unsupported placeholder are hidden as well", () => {
const fx = project("bean");
writeSession(fx.dir, "s.jsonl", header(fx.proj), [user("c1", null, "CREATIVE-MARKER", 1)]);
symlinkSync(join(fx.dir, "s.jsonl"), join(fx.dir, "link.jsonl"));
const chetDir = join(fx.proj, ".pi", "state", "chet", "sessions");
const regs = [{ version: 1, seat: "chet", project: "proj", layout: "repo", harness: "claude-code", sessionsDir: chetDir, startedAt: time(-1) }];
const roots = rootsFromSpecs([fx.spec], regs);
const plain = noWrites(fx.base, () => createReader({ roots }).catalogue());
const placeholder = plain.conversations.find((c) => c.availability === "unsupported");
assert.ok(placeholder, "without M7 the unsupported placeholder is listed");
const reader = createReader({ roots, creativeCheck: () => (root) => root.seat === "bean" || root.seat === "chet" });
const cat = noWrites(fx.base, () => reader.catalogue());
assert.deepEqual(cat.conversations, []);
const bean = roots.find((r) => r.seat === "bean");
for (const conversation of [placeholder.conversation, conversationId(bean, "link.jsonl"), conversationId(bean, "s.jsonl")]) {
const r = noWrites(fx.base, () => reader.open({ conversation }));
assert.deepEqual([r.ok, r.refusal.code], [false, "conversation-not-listed"]);
}
assert.equal(JSON.stringify(cat).includes("CREATIVE-MARKER"), false);
});
test("unknown conversations, empty files and non-Pi files refuse", () => {
const fx = project();
writeFileSync(join(fx.dir, "empty.jsonl"), "");
+23 -1
View File
@@ -47,11 +47,12 @@
// not retry); 4 usage.
import { existsSync, mkdirSync, mkdtempSync, writeFileSync, statSync, readdirSync } from "node:fs";
import { join, resolve } from "node:path";
import { dirname, join, resolve } from "node:path";
import { createHash } from "node:crypto";
import { DiscordError } from "./errors.mjs";
import { assertProcessing, processingStatus, ProcessingError } from "../../processing-control/src/state.mjs";
import { registerRuntime, updateRuntime, unregisterRuntime, processIdentity } from "../../processing-control/src/runtimes.mjs";
import { loadSeatSets } from "../../business/src/library-seats.mjs";
import { defaultConfigPath, loadDataRoot, bindingPath, bindingDataDir, loadBinding, readToken, resolveContextFiles, resolveToolRoots, reloadDiff } from "./binding.mjs";
import { createRest } from "./rest.mjs";
import { createGateway, CONNECTOR_INTENTS } from "./gateway.mjs";
@@ -104,12 +105,33 @@ function warn(msg) {
process.stderr.write(`discord: ${msg}\n`);
}
// Case 2 M8 (design 5.1, row 220): a seat that works in a library business runs
// only on the mosaic-bus engine, with no tools key. The business files come from
// the config directory --config names. An unreadable file refuses; it never reads
// as "no library seats".
function checkLibraryEngine(configDirectory, binding) {
let sets;
try {
sets = loadSeatSets({ dir: configDirectory });
} catch (err) {
throw new DiscordError(`discord-business-unreadable: ${err.message}`, 2);
}
if (!sets.librarySeats.has(binding.seat)) return;
if (binding.engine.provider !== "mosaic-bus") {
throw new DiscordError(`discord-engine-not-allowed: binding ${binding.name} runs seat ${binding.seat}, which works in a library business; its engine must be mosaic-bus, not ${binding.engine.provider}`, 2);
}
if (binding.tools !== null) {
throw new DiscordError(`discord-engine-not-allowed: binding ${binding.name} runs seat ${binding.seat}, which works in a library business; a mosaic-bus binding there may not declare the tools key`, 2);
}
}
// Everything that can be checked without the network, shared by check and run.
function prepare(opts) {
const dataRoot = loadDataRoot(opts.config);
const bindingFile = bindingPath(dataRoot, opts.binding);
const binding = loadBinding(bindingFile);
if (binding.name !== opts.binding) throw new DiscordError(`binding name ${JSON.stringify(binding.name)} does not match file name ${opts.binding}`);
checkLibraryEngine(dirname(opts.config), binding);
const contextFiles = resolveContextFiles(binding, opts.repo);
const toolRoots = resolveToolRoots(binding, { dataRoot });
const pi = join(opts.repo, "node_modules", ".bin", "pi");
+3
View File
@@ -77,6 +77,9 @@ export function makeDeployment(root, overrides = {}, { tokenMode = 0o600, tokenC
writeFileSync(bindingFile, JSON.stringify(raw, null, 2), { mode: 0o600 });
const config = join(root, "config.json");
writeFileSync(config, JSON.stringify({ dataRoot }));
// Row 220 M8: check and run read <root>/businesses beside --config. Nothing
// there means no library seat, so a deployment starts with none; the tests
// that need one write a business file into it.
return { dataRoot, config, bindingFile, tokenFile, raw, journalDir: join(dataRoot, "discord", raw.name) };
}
@@ -0,0 +1,118 @@
// Case 2 M8 (design 5.1, row 220): a binding for a seat in a library business
// runs only on the mosaic-bus engine with no tools key. The business files sit
// in the directory beside --config. An unreadable file refuses with
// discord-business-unreadable. Both verbs refuse: check runs with --offline, and
// run refuses in prepare(), before the journal is made and before any network.
import test from "node:test";
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { chmodSync, existsSync, mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { makeRoot, makeRepo, makeDeployment } from "./helpers.mjs";
import { initializeControl } from "../../processing-control/src/state.mjs";
import { businessDoc, writeJson } from "../../business/tests/helpers.mjs";
import { mappingEntry } from "../../library/tests/helpers.mjs";
const CLI = fileURLToPath(new URL("../src/cli.mjs", import.meta.url));
const MOSAIC_BUS = { provider: "mosaic-bus", model: "glm-5.3", thinking: "high" };
// overrides may be a function of the root, for fixtures that need a path under it.
function setup(overrides = {}) {
const root = makeRoot();
const repo = makeRepo(root);
const extra = typeof overrides === "function" ? overrides(root) : overrides;
const d = makeDeployment(root, extra, { tokenContent: "MTAw.abcdefghijklmnopqrstuvwxyz0123456789" });
return { root, repo, d };
}
// Writes businesses/acme.json under the deployment's config directory. A library
// business puts its roles (the seat "sage" here) in the library sets.
function business(s, { library, role = "sage", definition = "companion" }) {
const doc = businessDoc(s.root, "acme");
if (library) doc.projects = { books: mappingEntry(), ...doc.projects };
doc.roles[role] = { definition };
writeJson(join(s.root, "businesses", "acme.json"), doc);
}
// run stops at the processing gate first, so the deployment's control state is initialised.
function run(s) {
initializeControl(s.d.dataRoot);
return spawnSync(process.execPath, [CLI, "run", s.d.raw.name, "--config", s.d.config, "--repo", s.repo], { encoding: "utf8", timeout: 10000 });
}
function check(s) {
return spawnSync(process.execPath, [CLI, "check", s.d.raw.name, "--config", s.d.config, "--repo", s.repo, "--offline"], { encoding: "utf8", timeout: 10000 });
}
test("M8: a library seat's binding on a non-mosaic-bus engine is refused before any network", () => {
const s = setup();
business(s, { library: true });
const r = check(s);
assert.equal(r.status, 2, r.stderr);
assert.match(r.stderr, /discord-engine-not-allowed: .*its engine must be mosaic-bus, not zai/);
});
test("M8: a library seat's mosaic-bus binding that declares tools is refused, and the message names tools", () => {
const s = setup((root) => ({ engine: MOSAIC_BUS, tools: { roots: [{ name: "docs", path: join(root, "docs") }] } }));
business(s, { library: true });
const r = check(s);
assert.equal(r.status, 2, r.stderr);
assert.match(r.stderr, /discord-engine-not-allowed: .*tools key/);
});
test("M8: a library seat's mosaic-bus binding with no tools passes the engine rule", () => {
const s = setup({ engine: MOSAIC_BUS });
business(s, { library: true });
const r = check(s);
assert.doesNotMatch(r.stderr, /discord-engine-not-allowed|discord-business-unreadable/);
assert.equal(r.status, 0, r.stderr);
assert.match(r.stdout, /offline check passed/);
});
test("M8: an unreadable business file refuses check with discord-business-unreadable", () => {
const s = setup();
mkdirSync(join(s.root, "businesses"));
writeFileSync(join(s.root, "businesses", "broken.json"), "{");
chmodSync(join(s.root, "businesses", "broken.json"), 0o600);
const r = check(s);
assert.equal(r.status, 2, r.stderr);
assert.match(r.stderr, /discord-business-unreadable/);
});
test("M8: a binding on a seat that is in no library business checks clean, whatever its engine", () => {
const s = setup();
business(s, { library: false });
const r = check(s);
assert.equal(r.status, 0, r.stderr);
assert.match(r.stdout, /offline check passed/);
});
test("M8: run refuses a library seat's raw engine with exit 2, before the journal is made and before any network", () => {
const s = setup();
business(s, { library: true });
const r = run(s);
assert.equal(r.status, 2, r.stderr);
assert.match(r.stderr, /discord-engine-not-allowed: .*its engine must be mosaic-bus, not zai/);
assert.equal(existsSync(s.d.journalDir), false, "nothing was started");
});
test("M8: run refuses a library seat's mosaic-bus binding that declares tools", () => {
const s = setup((root) => ({ engine: MOSAIC_BUS, tools: { roots: [{ name: "docs", path: join(root, "docs") }] } }));
business(s, { library: true });
const r = run(s);
assert.equal(r.status, 2, r.stderr);
assert.match(r.stderr, /discord-engine-not-allowed: .*tools key/);
assert.equal(existsSync(s.d.journalDir), false);
});
test("M8: an unreadable business file refuses run with discord-business-unreadable, before the journal is made", () => {
const s = setup();
mkdirSync(join(s.root, "businesses"));
writeFileSync(join(s.root, "businesses", "broken.json"), "{");
chmodSync(join(s.root, "businesses", "broken.json"), 0o600);
const r = run(s);
assert.equal(r.status, 2, r.stderr);
assert.match(r.stderr, /discord-business-unreadable/);
assert.equal(existsSync(s.d.journalDir), false);
});
+2 -3
View File
@@ -292,7 +292,6 @@ function prompt({ contract, resolved, session, tools, untyped, builtins, persona
// resolved resolveInstance(...) output
// contract the role contract's text
// arbiter true when the business names this instance as an arbiter
// library true when the trusted business configuration has a library project
// tracker true when the broker has task verbs for the business
// credentials the broker's credentialStatus(...) for the instance (metadata only)
// session { run, launchedBy, workspace, toolSocket, turnMarker, checkouts }
@@ -310,11 +309,11 @@ function prompt({ contract, resolved, session, tools, untyped, builtins, persona
// (row 213); an instance with persona.sha256 and no personaDir refuses
// Returns { manifest, files, policy, tools, env } with absolute paths; env is the module's
// adapter variables, which the host writes into session.json.
export function buildBundle({ dir, resolved, contract, arbiter = false, tracker = false, library = false, credentials = [], session, harness, route = "primary", routeReason = null, harnessVersion = null, models = null, land = false, skillsDir = null, personaDir = null }) {
export function buildBundle({ dir, resolved, contract, arbiter = false, tracker = false, credentials = [], session, harness, route = "primary", routeReason = null, harnessVersion = null, models = null, land = false, skillsDir = null, personaDir = null }) {
if (route !== "primary" && route !== "fallback") throw new BundleError(`route ${JSON.stringify(route)} isn't primary or fallback`);
const model = sessionModel(resolved, models, route);
const web = webPlan(resolved, model.harness, harness.builtinWeb());
const tools = typedTools({ resolved, arbiter, tracker, library, projects: (session.checkouts ?? []).map((c) => c.project), webTyped: !web.builtin, land });
const tools = typedTools({ resolved, arbiter, tracker, projects: (session.checkouts ?? []).map((c) => c.project), webTyped: !web.builtin, land });
const untyped = untypedActions(resolved, tools);
const persona = readPersona(resolved, personaDir);
mkdirSync(dir, { recursive: true, mode: 0o700 });
+2 -50
View File
@@ -78,10 +78,9 @@ const TASK_TOOLS = {
const MESSAGE_CLASSES = ["REQUEST", "ASSIGNMENT", "REVIEW-REQUEST", "REVIEW-RESULT", "RESULT", "INFO", "DECISION", "REACTION", "BLOCK"];
// typedTools({ resolved, arbiter, tracker, projects, land, library }) -> [{ name, verb, action, description, parameters }]
// typedTools({ resolved, arbiter, tracker, projects, land }) -> [{ name, verb, action, description, parameters }]
// resolved resolveInstance(...) output for the session's instance
// arbiter true when the business names this instance as an arbiter
// library true when the trusted business configuration has a library project
// tracker true when the broker has task verbs for the business
// projects the project ids the session has a clone of
// land true when the role and thread hold a merge decision a landing could use (landHeld)
@@ -89,7 +88,7 @@ const MESSAGE_CLASSES = ["REQUEST", "ASSIGNMENT", "REVIEW-REQUEST", "REVIEW-RESU
// `verb` is the broker verb; the `launch` tool has verb "launch" and goes
// to the host instead, and "working.push", "working.fetch" and
// "working.land" go to the host's git socket.
export function typedTools({ resolved, arbiter = false, tracker = false, projects = [], webTyped = true, land = false, library = false }) {
export function typedTools({ resolved, arbiter = false, tracker = false, projects = [], webTyped = true, land = false }) {
const held = new Set([...resolved.limits.authority.withinRole, ...resolved.limits.authority.crossRole]);
const tools = [];
const add = (name, verb, action, description, parameters) => tools.push({ name, verb, action, description, parameters });
@@ -223,48 +222,6 @@ export function typedTools({ resolved, arbiter = false, tracker = false, project
url: str("The https url to fetch", { maxLength: 2048 }),
}, ["url"]));
}
// Row224: no library clone or token reaches a session. The broker chooses the served
// commit and requires a universe on every call; cursors page without cutting replies.
if (library) {
const universe = str("Universe ID in the configured library", { minLength: 1 });
const project = str("Library project ID; omit only when the business has one library");
const scope = str("canon by default; playground and supporting are opt-in", { enum: ["canon", "playground", "supporting"] });
const manuscriptScope = str("canon by default; playground is opt-in", { enum: ["canon", "playground"] });
const book = str("Book folder from library_universe");
const offset = { type: "integer", minimum: 0, description: "next from the previous page" };
const line = { type: "integer", minimum: 1, description: "One-based line number" };
const base = { universe, project };
add("library_find", "library.find", null, "Find names in one universe, at the served commit. At most 50 results; continue with next as offset. Playground and supporting are opt-in.", obj({
...base, query: str("Case-insensitive name or filename substring; empty matches all"),
type: str("Mapped type", { enum: ["character", "place", "research", "tracker", "summary"] }),
book, scope, offset,
}, ["universe", "query"]));
add("library_get", "library.get", null, "Read a note and its blob at the served commit, canon by default. Playground/supporting paths need matching scope; mismatch returns null. next pages lines; links_next pages visible links in supporting/playground/canon order.", obj({
...base, path: str("Mapped note path relative to the library"), scope, from: line, links_from: offset,
}, ["universe", "path"]));
add("library_search", "library.search", null, "Search text in one universe at the served commit. At most 50 hits; use next as offset. Playground and supporting are opt-in.", obj({
...base, text: str("Nonempty case-insensitive substring", { minLength: 1 }), book, scope, offset,
}, ["universe", "text"]));
add("library_manuscript", "library.manuscript", null, "Read one chapter of a book at the served commit, at most 400 lines. Omit chapter for the first; continue with next or next_chapter.", obj({
...base, book, scope: manuscriptScope, chapter: str("Chapter filename without extension"), from: line, to: line,
}, ["universe", "book"]));
add("library_universe", "library.universe", null, "Read a universe's mapping at the served commit: books, types, playground prefixes, and hybrid sources/constraints/notes or draft metadata.", obj(base, ["universe"]));
// C2-02: write tools carry only the note/base/content. The broker supplies the writer,
// credential and fixed commit message; a creative within-role grant is required.
if (CREATIVE_DEFINITIONS.includes(resolved.definition) && resolved.limits.authority.withinRole.includes("library.write")) {
const writeBase = {
universe,
path: str("A .md path under this universe's human-marked supporting folder"),
base: { type: ["string", "null"], pattern: "^[a-f0-9]{40}$", description: "The blob from library_get, or null to create; never the commit id" },
};
add("library_doc_write", "library.doc.write", "library.write", "Create or edit one supporting .md note using the blob from library_get. One commit by your identity, with a fixed human notice. A stale base refuses; agent requests retain the 64 KiB envelope limit.", obj({
...writeBase, content: str("UTF-8 note text without NUL; at most 1 MiB and bounded by the agent socket envelope"),
}, ["universe", "path", "base", "content"]));
add("library_doc_delete", "library.doc.delete", "library.write", "Delete one existing regular supporting .md note using the blob from library_get. One commit and a fixed human notice. A stale base or nonregular/missing target refuses.", obj({ ...writeBase,
base: { ...writeBase.base, description: "The existing file's blob from library_get; a missing file cannot be deleted" },
}, ["universe", "path", "base"]));
}
}
add("read_spec", "spec.read", null, "Read a project's committed north-star spec and its file history. commit is an optional full reachable commit ID. The file commit, rather than HEAD, is what a decision cites. confirmed says the file commit was authored by the business's human.", obj({
project: str("Project ID from the business file"),
commit: str("Optional full historical commit ID", { pattern: "^[0-9a-f]{40}$" }),
@@ -320,11 +277,6 @@ export function typedTools({ resolved, arbiter = false, tracker = false, project
if (held.has("task.create"))
add("list_requirements", "requirements", null, "List the approved PRD's requirement ids, each with a one-line title. task_create takes only these. When none fits a request, raise a prd.approve decision instead of creating the task.", obj({}));
}
// mos-1308 / M3: no generic spec, evidence, tracker, decision or write tools. The
// C2-08 web grant still supplies broker web reads to companion and research only.
if (CREATIVE_DEFINITIONS.includes(resolved.definition))
return tools.filter(tool => tool.name === "send_message" || tool.name.startsWith("library_") ||
tool.name === "web_search" || tool.name === "web_fetch");
return tools;
}
@@ -1,82 +0,0 @@
// Row224 M3: exact creative tool sets preserve the existing C2-08 web grants.
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { typedTools } from '../src/tools.mjs';
import { buildBundle } from '../src/bundle.mjs';
import { TYPES } from '../../library/src/mapping.mjs';
import { HARNESS, REPO_SKILLS, resolvedFor, scratch } from './helpers.mjs';
const LOOKUPS = ['library_find', 'library_get', 'library_search', 'library_manuscript', 'library_universe'];
const CREATIVE = ['companion', 'research', 'ideas', 'proofreader', 'fact-checker', 'continuity'];
const role = (t, definition, harness = 'pi') => resolvedFor(t, 'bean', d => {
d.roles.bean = { definition, vars: { harness, model: 'claude-sonnet-5-5', thinking: 'high' } };
});
const expected = definition => ['send_message', ...(['companion', 'research'].includes(definition)
? ['web_search', 'web_fetch'] : []), ...LOOKUPS, 'library_doc_write', 'library_doc_delete'];
test('M3: per-role snapshots contain eight names, or ten with the C2-08 web grant', t => {
for (const definition of CREATIVE) {
const tools = typedTools({ resolved: role(t, definition), library: true, tracker: true, arbiter: true });
assert.deepEqual(tools.map(t => t.name), expected(definition), definition);
assert.ok(tools.every(t => t.parameters.additionalProperties === false));
}
});
test('every noncreative role gets lookups when a library is configured, not otherwise', t => {
for (const instance of ['coder', 'reviewer', 'pm', 'chief']) {
const resolved = resolvedFor(t, instance);
const ordinary = typedTools({ resolved }).map(t => t.name);
assert.ok(!ordinary.some(name => name.startsWith('library_')));
const tools = typedTools({ resolved, library: true });
assert.deepEqual(tools.filter(t => t.name.startsWith('library_')).map(t => t.name), LOOKUPS);
assert.deepEqual(tools.filter(t => !t.name.startsWith('library_')).map(t => t.name), ordinary);
}
});
test('lookup schemas require a universe even for get, include paging, and cannot select repo or commit', t => {
const tools = typedTools({ resolved: role(t, 'ideas'), library: true });
const required = [ ['universe', 'query'], ['universe', 'path'], ['universe', 'text'], ['universe', 'book'], ['universe'] ];
for (const [i, tool] of tools.filter(t => LOOKUPS.includes(t.name)).entries()) {
assert.deepEqual(tool.parameters.required, required[i]);
assert.equal(tool.verb, LOOKUPS[i].replace('_', '.'));
assert.equal(tool.action, null);
assert.equal(tool.parameters.additionalProperties, false);
for (const key of ['repo', 'commit', 'business', 'accept']) assert.equal(Object.hasOwn(tool.parameters.properties, key), false);
}
const byName = Object.fromEntries(tools.map(t => [t.name, t]));
assert.deepEqual(byName.library_find.parameters.properties.scope.enum, ['canon', 'playground', 'supporting']);
assert.deepEqual(byName.library_find.parameters.properties.type.enum, [...TYPES]);
assert.equal(byName.library_find.parameters.properties.offset.minimum, 0);
assert.equal(byName.library_get.parameters.properties.from.minimum, 1);
assert.equal(byName.library_get.parameters.properties.links_from.minimum, 0);
assert.equal(byName.library_manuscript.parameters.properties.chapter.type, 'string');
});
test('bundle flag reaches both harness tool manifests and creative prompt without generic tools', t => {
for (const definition of CREATIVE) for (const harness of ['pi', 'claude-code']) {
const dir = scratch(t), workspace = join(dir, 'ws'); mkdirSync(workspace);
const b = buildBundle({ dir: join(dir, 'bundle'), resolved: role(t, definition, harness), library: true,
contract: '# Creative\n', tracker: true, arbiter: true, skillsDir: REPO_SKILLS,
session: { run: 'r224', launchedBy: 'chief', workspace, toolSocket: join(dir, 't.sock'), turnMarker: join(dir, 'turn.done') },
harness: HARNESS[harness] });
assert.deepEqual(b.tools.map(t => t.name), expected(definition), `${definition} ${harness}`);
const serialized = JSON.parse(readFileSync(b.files.tools, 'utf8'));
assert.deepEqual(serialized.map(t => t.name), expected(definition));
const prompt = readFileSync(b.files.prompt, 'utf8');
assert.match(prompt, /library_find/);
assert.doesNotMatch(prompt, /Bus tools: [^\n]*(read_spec|list_agents|inbox|trail|write_record|raise_decision|list_tasks)/);
}
});
test('C2-05c scope schemas expand only find/search/get, keeping manuscript and tool names unchanged', t => {
const tools = typedTools({ resolved: role(t, 'ideas'), library: true });
assert.deepEqual(tools.map(t => t.name), ['send_message', ...LOOKUPS, 'library_doc_write', 'library_doc_delete']);
for (const name of ['library_find', 'library_search', 'library_get']) {
const tool = tools.find(t => t.name === name);
assert.deepEqual(tool.parameters.properties.scope.enum, ['canon', 'playground', 'supporting']);
assert.ok(!tool.parameters.required.includes('scope'));
}
assert.deepEqual(tools.find(t => t.name === 'library_manuscript').parameters.properties.scope.enum, ['canon', 'playground']);
});
@@ -1,60 +0,0 @@
// Row 288 M3: creative write tools and independent closed-schema coverage.
import test from 'node:test';
import assert from 'node:assert/strict';
import { typedTools, untypedActions } from '../src/tools.mjs';
import { resolvedFor } from './helpers.mjs';
const LOOKUPS = ['library_find', 'library_get', 'library_search', 'library_manuscript', 'library_universe'];
const WRITES = ['library_doc_write', 'library_doc_delete'];
const CREATIVE = ['companion', 'research', 'ideas', 'proofreader', 'fact-checker', 'continuity'];
const role = (t, definition) => resolvedFor(t, 'bean', doc => {
doc.roles.bean = { definition, vars: { harness: 'pi', model: 'claude-sonnet-5-5', thinking: 'high' } };
});
test('C2-02 M3: each creative role has eight tools, or ten with its web grant', t => {
for (const definition of CREATIVE) {
const resolved = role(t, definition), tools = typedTools({ resolved, library: true, tracker: true, arbiter: true });
const expected = ['send_message', ...(['companion', 'research'].includes(definition) ? ['web_search', 'web_fetch'] : []), ...LOOKUPS, ...WRITES];
assert.deepEqual(tools.map(tool => tool.name), expected, definition);
assert.equal(tools.length, ['companion', 'research'].includes(definition) ? 10 : 8);
assert.equal(untypedActions(resolved, tools).includes('library.write'), false);
}
});
test('C2-02 schemas: both write tools require universe/path/base, close keys, map verb and action', t => {
const tools = typedTools({ resolved: role(t, 'ideas'), library: true });
for (const [name, verb, required] of [
['library_doc_write', 'library.doc.write', ['universe', 'path', 'base', 'content']],
['library_doc_delete', 'library.doc.delete', ['universe', 'path', 'base']],
]) {
const tool = tools.find(tool => tool.name === name);
assert.ok(tool, name); assert.equal(tool.verb, verb); assert.equal(tool.action, 'library.write');
assert.equal(tool.parameters.type, 'object'); assert.equal(tool.parameters.additionalProperties, false);
assert.deepEqual(tool.parameters.required, required);
assert.deepEqual(Object.keys(tool.parameters.properties).sort(), [...required].sort());
assert.equal(tool.parameters.properties.universe.type, 'string');
assert.equal(tool.parameters.properties.path.type, 'string');
assert.deepEqual(tool.parameters.properties.base.type, ['string', 'null']);
assert.equal(tool.parameters.properties.base.pattern, '^[a-f0-9]{40}$');
if (name === 'library_doc_write') {
assert.equal(tool.parameters.properties.content.type, 'string');
assert.match(tool.parameters.properties.base.description, /null to create/);
} else {
assert.match(tool.parameters.properties.base.description, /existing file/);
assert.doesNotMatch(tool.parameters.properties.base.description, /create/);
}
for (const field of ['repo', 'commit', 'business', 'accept', 'project', 'identity', 'author', 'credential', 'agent', 'message'])
assert.equal(Object.hasOwn(tool.parameters.properties, field), false, `${name} ${field}`);
}
});
test('C2-02 tools: no library, noncreative or no within-role write grant exposes neither write tool', t => {
const creative = role(t, 'ideas');
assert.equal(typedTools({ resolved: creative }).some(tool => WRITES.includes(tool.name)), false);
for (const instance of ['coder', 'reviewer', 'pm', 'chief'])
assert.equal(typedTools({ resolved: resolvedFor(t, instance), library: true }).some(tool => WRITES.includes(tool.name)), false);
const narrowed = structuredClone(creative);
narrowed.limits.authority.withinRole = narrowed.limits.authority.withinRole.filter(action => action !== 'library.write');
narrowed.limits.authority.crossRole.push('library.write');
assert.deepEqual(typedTools({ resolved: narrowed, library: true }).map(tool => tool.name), ['send_message', ...LOOKUPS]);
});
-96
View File
@@ -219,45 +219,6 @@ and `library.status` shows the result once it ends. A sync that outlasts the 120
`request-timeout` from the server and still finishes the same way. The Console has no library route yet: `cli.mjs`
passes `librarySync` to `startServer`, and `serve.mjs` doesn't read it.
### Push and credentials (C2-03b)
`push(context, { commit, credential, retried })` sends a full commit id, already in the mirror, to the
entry's `branch` as `push --porcelain --no-verify --no-follow-tags --end-of-options <url>
<commit>:refs/heads/<branch>`, through the same prefix, env and helper as the fetch. The refspec has no
`+`, so the remote takes a fast-forward only.
| git says | Answer |
|---|---|
| the push landed | `{ pushed: true }` |
| `[rejected] (fetch first)` or `(non-fast-forward)` | one fetch with the same credential, then `{ pushed: false, raced: true, tip }` |
| the same, with `retried: true` | `stale-base` |
| the same, while a sync of the mirror runs | `library-sync-busy`, with no fetch |
| anything else, `[remote rejected]` (a hook) included | `library-push-failed` |
Push moves no local ref; C2-02 re-applies and moves `served`. git's output is never kept.
A credential is `{ kind, user, file }`, with `kind` one of `slot`, `chief`, `seat` or `human`, or the
bus's `{ refused: code }`. The helper reads only `file`. It opens the file on fd 3 and refuses unless
the open file and the path have the same device and inode, and the file is regular, the bus's uid's,
mode 0600 and at most 16384 bytes, as `readSecretFile` in `packages/bus/src/gitea-grant.mjs` checks a
grant store file. A FIFO swapped in after `test -f` blocks the open, the same residual
`readSecretFile` has.
- A seat writes with its own Gitea user and grant store file, `<storeRoot>/<business>/<agent>/gitea`.
- `humanCredential(context, { user, configDir })` gives her save its credential: her Gitea login and
`<configDir>/secrets/<business>/library-human`. A missing login, or a slot that is missing, a link,
another uid's or not 0600, refuses `library-human-missing` before any git call.
- The fetch takes the broker's choice, `libraryFetchCredential(business)`. The chief is a `roles`
entry whose definition is `chief-of-staff`; a fire keeps it there. With no Gitea grant evidence for
a chief, the fetch uses slot `library-gitea` and the entry's `user`. Once there is some, only the one
listed chief's live, unheld grant answers, with that grant's user and store file. Anything else
refuses `library-fetch-no-grant`, and so does any Gitea grant evidence in a business with no chief
entry. That refusal opens no file and runs no git. The bus answers its code; the timer's log line
adds `fix: "add the chief of staff, or grant the library through C2-21"`.
The sync state adds `credential`, `{ kind, user }` of the last fetch, or `null` when none ran. It is
optional, so a state written before C2-03b still reads.
## Tests
```sh
@@ -266,60 +227,3 @@ node --test packages/library/tests/
Fixtures are made-up repos built per test in a temp dir. A marker string stands in for her text, and
the survey tests check that it never appears in output.
### C2-02 supporting writes and human saves
The host exposes `library.doc.write {universe,path,base,content}` and
`library.doc.delete {universe,path,base}` only to a creative session holding
`library.write` and a live, unheld Gitea grant for the library project. The
broker chooses the project from the universe mapping, the author/committer
from the instance identity, and the credential from its grant store. `base`
is the served-tree blob id, or `null` to create. Supporting-path checks run
before remote effects and against each fetched tip; deletes require an
existing `100644` blob. Content is UTF-8 without NUL and at most 1 MiB;
agent requests still have the ordinary 64 KiB socket envelope limit.
Each operation is one plumbing commit with one parent, a fixed
`Mosaic: write <path>` or `Mosaic: delete <path>` message, and the trailer
`Mosaic-Agent: <business>/<instance>`. Pushes are fast-forward only. A moved
remote tip retries once when the target blob still equals `base`; otherwise
it refuses `stale-base`. A failed push leaves no queued work or local ref
change. A successful push updates served/tracking, rebuilds the index and
records `lastPush: {commit,at}`. The broker inserts the exact fixed notice
`{notice:"library-write",op,path,commit}` from the writer to the human in
that thread, independently of the agent-message citation guard.
`library.file.save {project,path,base,content}` and
`library.revert {project,commit}` are human-only. Project is the business
project key. A save reaches any mapped `.md` file under the structural path
rules, uses the mapping's `editor` as author and committer, and pushes with
slot `library-human`. Revert accepts only a reachable, one-parent,
one-path commit with this business's agent trailer, and restores its
parent's blob with the agent commit's blob as `base`. The result is
`{project,path,reverted,commit}`. Revoking/firing the original writer does
not prevent a human revert. Missing editor refuses
`library-mapping-invalid`; missing/unsafe human slot refuses
`library-human-missing`, before Git. An agent calling either human verb
gets `human-required`. Only `library.file.save` joins the larger Console
save envelope exception; agent writes retain 64 KiB.
The write guard excludes concurrent sync and admits a race fetch only for
its opaque owner token. The library flock spans fetch/build/push as the
brief requires, so readers can receive `library-sync-busy` after the
existing five-second lock wait while network Git runs (MVP tradeoff,
sage-3628). Publication errors return `outcome-unknown`: served is restored
to match old state unless the new state was already published. The remote
commit remains; callers must inspect status rather than retry blindly.
The human push login is `editor.user` (optional in the mapping, required
for save/revert), distinct from `user`, which names the fetch bot.
An absent editor login refuses `library-human-missing`; no fallback uses
the bot's login. Once an agent push succeeds, the broker stores the exact
write notice with that pushed commit id before local publication. If
publication then fails, the agent receives `outcome-unknown` and the
notice remains. Revert can refuse `library-revert-not-agent` until a sync
makes the commit reachable from served. No notice outbox or retry is
needed. If the Console store itself refuses the notice insert, the caller
still receives `outcome-unknown` and a separate metadata-only host log
records `library-notice-store-failed` with the business, instance, operation
and pushed commit id; it contains no file text or credential.
+1 -13
View File
@@ -2,11 +2,6 @@
# C2-03a: git's GIT_ASKPASS for library sync (packages/library/src/sync.mjs). It answers only the
# Username and Password prompts for the configured host and user, and exits 1 on anything else.
# The env names the slot path, never the token. printf is a shell builtin, so the token is in no argv.
# C2-03b: the slot is whichever file the bus chose (a grant store file, library-gitea or library-human),
# read with readSecretFile's checks (gitea-grant.mjs): a regular file the bus's uid owns, mode 0600, at
# most 16384 bytes. The checks run on the open fd 3, and its dev:inode must match the path's own
# (an lstat), so a link or a swap before the open refuses and the token comes from the checked file
# (dewey-0860). Residual, as in readSecretFile: a FIFO swapped in after test -f blocks the open.
host=$MOSAIC_LIBRARY_HOST user=$MOSAIC_LIBRARY_USER slot=$MOSAIC_LIBRARY_SLOT
test -n "$host" && test -n "$user" && test -n "$slot" || exit 1
case $host in *[!a-z0-9.:-]*) exit 1 ;; esac
@@ -15,14 +10,7 @@ case $1 in
"Username for 'https://$host': ") printf '%s\n' "$user" ;;
"Password for 'https://$user@$host': ")
test -f "$slot" && test ! -L "$slot" || exit 1
exec 3<"$slot" || exit 1
open=$(stat -L -c '%d:%i %u %a %s %F' /dev/fd/3 2>/dev/null) || exit 1
path=$(stat -c '%d:%i' -- "$slot" 2>/dev/null) || exit 1
set -- $open
test "$1" = "$path" && test "$2" = "$(id -u)" && test "$3" = 600 && test "$4" -le 16384 \
&& test "$5 $6" = "regular file" && test $# -eq 6 || exit 1
IFS= read -r token <&3 || test -n "$token" || exit 1
exec 3<&-
IFS= read -r token < "$slot" || test -n "$token" || exit 1
test -n "$token" || exit 1
printf '%s\n' "$token" ;;
*) exit 1 ;;
+1 -3
View File
@@ -8,8 +8,6 @@ export { readLibrary, listTree, readTexts, parseFile, parseFrontMatter, headComm
export { renderItems, KINDS, NOTICES, UNREADABLE } from './render.mjs';
export { survey, formatSurvey, surveyMain } from './survey.mjs';
export { SYNC_STATE_FILE, mirrorPath, ensureMirror, withLibraryLock, servedCommit, readSyncState, libraryStatus, readLibraryFile } from './mirror.mjs';
export { syncCommand, sync, push, humanCredential, ASKPASS, SLOT, HUMAN_SLOT, CREDENTIAL_KINDS, SYNC_INTERVAL_MS } from './sync.mjs';
export { writeLibraryDoc, saveLibraryFile, revertLibraryCommit } from './write.mjs';
export { syncCommand, sync, ASKPASS, SLOT, SYNC_INTERVAL_MS } from './sync.mjs';
export { buildIndex, indexFor, clearIndexCache, indexCacheSize } from './index-build.mjs';
export { sees, find, get, search, manuscript, universeInfo, QUERY_REPLY_CAP, LOOKUP_LIMIT, MANUSCRIPT_LINES } from './query.mjs';
+1 -7
View File
@@ -219,13 +219,7 @@ async function readStateHeld(mirror, { branch } = {}) {
value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, used)));
} catch { fail('library-state-invalid', 'invalid sync state'); }
finally { if (fd !== undefined) closeSync(fd); }
// C2-03b adds `credential`, { kind, user } or null. It is optional, so a state from before it reads.
const listed = ['version', 'branch', 'served', 'lastFetch', 'lastError', 'diverged', 'problems'];
const expected = [...listed, ...['credential', 'lastPush'].filter(key => Object.hasOwn(value ?? {}, key))];
if (!keys(value, expected)
|| !optional(value.lastPush ?? null, v => keys(v, ['commit', 'at']) && SHA.test(v.commit) && utc(v.at))
|| !optional(value.credential ?? null, v => keys(v, ['kind', 'user']) && ['slot', 'chief', 'seat', 'human'].includes(v.kind)
&& typeof v.user === 'string' && /^[A-Za-z0-9_.-]{1,100}$/.test(v.user))
if (!keys(value, ['version', 'branch', 'served', 'lastFetch', 'lastError', 'diverged', 'problems'])
|| value.version !== 1 || value.branch !== branch || value.served !== served
|| !optional(value.served, v => typeof v === 'string' && SHA.test(v)) || !optional(value.lastFetch, utc)
|| !optional(value.lastError, v => keys(v, ['code', 'at']) && typeof v.code === 'string' && /^[a-z-]{1,64}$/.test(v.code) && utc(v.at))
+9 -19
View File
@@ -7,15 +7,12 @@
import { raise } from './problems.mjs';
import { TYPES } from './mapping.mjs';
import { indexFor } from './index-build.mjs';
import { listTree } from './reader.mjs';
// The same cap as packages/harness/src/tools.mjs REPLY_CAP. The query tests assert the two stay equal.
export const QUERY_REPLY_CAP = 40_000;
export const LOOKUP_LIMIT = 50;
export const MANUSCRIPT_LINES = 400;
const SCOPES = Object.freeze(['canon', 'playground', 'supporting']);
const MANUSCRIPT_SCOPES = Object.freeze(['canon', 'playground']);
const SCOPE_RANK = Object.freeze({ supporting: 0, playground: 1, canon: 2 });
const SCOPES = Object.freeze(['canon', 'playground']);
const bytes = value => JSON.stringify(value).length;
const invalid = message => raise('query-argument-invalid', message);
@@ -25,9 +22,9 @@ function textArg(value, name) {
if (typeof value !== 'string') invalid(`${name} must be text`);
return value;
}
function scopeArg(value, allowed = SCOPES) {
function scopeArg(value) {
if (value === undefined) return 'canon';
if (!allowed.includes(value)) invalid(`scope must be one of ${allowed.join(", ")}`);
if (!SCOPES.includes(value)) invalid('scope must be "canon" or "playground"');
return value;
}
function positionArg(value, name, fallback) {
@@ -112,8 +109,7 @@ export async function find(source, { universe: name, query, type, book, scope, o
});
}
// get: one file in the requested scope (canon default), its served-tree blob, front matter,
// lines and visible links both ways. Links keep all visible scopes, ordered supporting/playground/canon.
// get: one visible file, its front matter, its lines from `from`, and its visible links both ways.
// Returns null when the file is missing or not visible, so a caller cannot tell the two apart. Lines page
// by `from` (reply `next`), links page together by `links_from` (reply `links_next`); `links_out` come
// before `links_in`. Every page carries the front matter. Links take at most half the cap, so a hub note
@@ -121,33 +117,27 @@ export async function find(source, { universe: name, query, type, book, scope, o
// least one line, so links shrink when a line needs the room; read on with `from: next` and
// `links_from: links_next`. A `from` past the last line returns links alone. Only front matter, or a
// line that cannot fit with no links beside it, is refused.
export async function get(source, { universe: name, path, scope, from, links_from: linksFrom } = {}) {
export async function get(source, { universe: name, path, from, links_from: linksFrom } = {}) {
const universe = universeArg(source.mapping, name);
const requestedScope = scopeArg(scope);
const startLine = positionArg(from, 'from', 1);
const linkStart = offsetArg(linksFrom);
if (typeof path !== 'string') invalid('path must be text');
const index = await indexFor(source);
const file = index.files.get(path);
if (!file || file.scope !== requestedScope || !sees(index.mapping, universe, file)) return null;
if (!file || !sees(index.mapping, universe, file)) return null;
const reachable = links => links.filter(link => {
const other = index.files.get(link.path);
return other !== undefined && sees(index.mapping, universe, other);
}).sort((a, b) => SCOPE_RANK[index.files.get(a.path).scope] - SCOPE_RANK[index.files.get(b.path).scope]);
});
const outs = reachable(index.linksOut.get(file.path) ?? []);
const ins = reachable(index.linksIn.get(file.path) ?? []);
const links = [...outs.map(link => ({ out: true, link })), ...ins.map(link => ({ out: false, link }))];
// The reader/index does not keep tree oids. Resolve only in this immutable served
// snapshot, never HEAD; listTree already checks/bounds the tree and its object IDs.
const entry = (await listTree(source.repo, index.commit)).find(entry => entry.path === file.path);
if (!entry || entry.mode !== '100644' || entry.type !== 'blob') raise('library-commit', 'indexed file is absent from the served tree');
const blob = entry.oid;
const lines = file.lines.slice(startLine - 1);
const linkRest = Math.max(0, links.length - linkStart);
const page = (nLines, nLinks) => {
const taken = links.slice(linkStart, linkStart + nLinks);
return {
path: file.path, commit: index.commit, blob, scope: file.scope, frontmatter: file.frontmatter,
path: file.path, commit: index.commit, scope: file.scope, frontmatter: file.frontmatter,
lines: lines.slice(0, nLines),
links_out: taken.filter(item => item.out).map(item => item.link),
links_in: taken.filter(item => !item.out).map(item => item.link),
@@ -211,7 +201,7 @@ export async function manuscript(source, { universe: name, book, scope, chapter,
const start = positionArg(from, 'from', 1);
const end = positionArg(to, 'to', Infinity);
if (end < start) invalid('to must not be before from');
const { index, files } = await visible(source, universe, { scope: scopeArg(scope, MANUSCRIPT_SCOPES), book: bookName, type: 'manuscript' });
const { index, files } = await visible(source, universe, { scope: scopeArg(scope), book: bookName, type: 'manuscript' });
let at = 0;
if (chapterName !== undefined) {
const matches = files.filter(file => file.stem === chapterName);
+12 -147
View File
@@ -2,9 +2,6 @@
// configured branch into refs/remotes/library/<branch>. A fast-forward moves refs/heads/served,
// a non-fast-forward holds it until a human accepts, and a failed fetch keeps serving. The token
// never reaches argv, env, config, a URL or a log: git's GIT_ASKPASS helper reads it from the slot.
// C2-03b: the same command pushes, fast-forward only, and the file the helper reads is the one
// credential the caller chose: a seat's grant store file, the chief's for the fetch, slot
// library-gitea before any chief grant, or slot library-human for her save (ruling after r11).
import { constants, closeSync, fsyncSync, lstatSync, openSync, renameSync, rmSync, writeSync } from 'node:fs';
import { randomBytes } from 'node:crypto';
import { dirname, join } from 'node:path';
@@ -14,13 +11,10 @@ import { SAFE, git } from '../../project/src/git.mjs';
import { checkMapping } from './mapping.mjs';
import { LibraryError } from './problems.mjs';
import { readLibrary } from './reader.mjs';
import { indexFor } from './index-build.mjs';
import { SYNC_STATE_FILE, ensureMirror, withLibraryLock, servedCommit } from './mirror.mjs';
export const ASKPASS = fileURLToPath(new URL('../bin/askpass', import.meta.url));
export const SLOT = 'library-gitea';
export const HUMAN_SLOT = 'library-human';
export const CREDENTIAL_KINDS = Object.freeze(['slot', 'chief', 'seat', 'human']);
export const SYNC_INTERVAL_MS = 60_000;
// Row 199's patterns (packages/seat/src/working.mjs).
const HOST = /^[a-z0-9.-]{1,253}(:[0-9]{1,5})?$/;
@@ -33,21 +27,10 @@ const fail = (code, message = code) => { throw new LibraryError(code, message);
// One sync per mirror in this process. The library lock covers publication only, so a second
// fetch into the same mirror is refused here rather than racing the first.
const running = new Set();
// C2-02: opaque identity lets only the owning write re-enter push's race fetch.
const writers = new Map();
export async function withLibraryWriteGuard(mirror, operation) {
if (running.has(mirror)) fail('library-sync-busy');
const token = Object.freeze({});
running.add(mirror); writers.set(mirror, token);
try { return await operation(token); }
finally { writers.delete(mirror); running.delete(mirror); }
}
// The one command builder for her remote. `kind` is 'fetch' or 'push'. A push sends `commit` to the
// branch with no '+', so the remote takes a fast-forward only (D6). `slot` is the file the helper reads.
export function syncCommand(kind, url, { mirror, branch, user, slot, commit = null }) {
if (kind !== 'fetch' && kind !== 'push') fail('library-remote-invalid', 'sync fetches or pushes');
if (kind === 'push' && (typeof commit !== 'string' || !SHA.test(commit))) fail('library-remote-invalid', 'a push takes a full commit id');
// The one command sync runs against her remote. `kind` is 'fetch'; there is no other.
export function syncCommand(kind, url, { mirror, branch, user, slot }) {
if (kind !== 'fetch') fail('library-remote-invalid', 'sync only fetches');
let parsed;
try { parsed = new URL(url); } catch { fail('library-remote-invalid', 'remote must be an https:// URL'); }
if (parsed.protocol !== 'https:' || parsed.username || parsed.password || parsed.search || parsed.hash
@@ -55,13 +38,10 @@ export function syncCommand(kind, url, { mirror, branch, user, slot, commit = nu
fail('library-remote-invalid', 'remote must be https:// with a plain host and no credentials');
// core.createObject=rename: git's default files each object by link then unlink, and a reader's
// inspectMirror (C2-04) refuses a file with two links while that runs.
const command = kind === 'fetch'
? ['fetch', '--no-tags', '--no-write-fetch-head', '--no-recurse-submodules', '--end-of-options',
parsed.href, `+refs/heads/${branch}:refs/remotes/library/${branch}`]
: ['push', '--porcelain', '--no-verify', '--no-follow-tags', '--end-of-options', parsed.href, `${commit}:refs/heads/${branch}`];
return {
argv: [...SAFE, '-c', 'protocol.https.allow=always', '-c', 'http.followRedirects=false', '-c', 'credential.helper=',
'-c', 'core.createObject=rename', '-C', mirror, ...command],
'-c', 'core.createObject=rename', '-C', mirror, 'fetch', '--no-tags', '--no-write-fetch-head', '--no-recurse-submodules', '--end-of-options',
parsed.href, `+refs/heads/${branch}:refs/remotes/library/${branch}`],
env: { ...gitEnv(), LC_ALL: 'C', GIT_CEILING_DIRECTORIES: dirname(mirror), GIT_ASKPASS: ASKPASS,
MOSAIC_LIBRARY_HOST: parsed.host, MOSAIC_LIBRARY_USER: user, MOSAIC_LIBRARY_SLOT: slot },
};
@@ -73,32 +53,6 @@ function slotPresent(slot) {
catch { return false; }
}
// A chosen credential, { kind, user, file }, or { refused: code } when the bus refused one.
function checkCredential(credential) {
if (credential === null || typeof credential !== 'object') fail('library-credential-missing', 'no credential chosen');
if (Object.hasOwn(credential, 'refused')) return credential;
const { kind, user, file } = credential;
if (!CREDENTIAL_KINDS.includes(kind) || (user !== undefined && (typeof user !== 'string' || !NAME.test(user)))
|| (file !== null && typeof file !== 'string'))
fail('library-credential-missing', 'credential must name a kind, a plain user and a file');
return credential;
}
// C2-03b: her save and revert push with slot library-human and her Gitea login. A missing login, or a
// slot that is missing, a link, another uid's or not 0600, refuses before any git call. Like sync, this
// never opens the slot; the helper reads it with readSecretFile's checks.
export function humanCredential(context, { user, configDir }) {
const missing = message => fail('library-human-missing', message);
if (typeof user !== 'string' || !NAME.test(user)) missing('her Gitea login is not configured');
if (typeof configDir !== 'string' || typeof context?.business?.id !== 'string') missing('slot library-human is not configured');
const file = join(configDir, 'secrets', context.business.id, HUMAN_SLOT);
let st;
try { st = lstatSync(file); } catch { missing('slot library-human is missing'); }
if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o777) !== 0o600 || st.size > 16384)
missing('slot library-human must be a regular 0600 file the bus owns');
return { kind: 'human', user, file };
}
async function isAncestor(mirror, older, newer) {
const result = await runGit([...SAFE, '-C', mirror, 'merge-base', '--is-ancestor', older, newer],
{ ...gitEnv(), GIT_CEILING_DIRECTORIES: dirname(mirror) });
@@ -135,27 +89,19 @@ const errorCode = error => typeof error?.code === 'string' && CODE.test(error.co
// 'library-credential-missing', 'library-diverged' or a reader refusal). It throws for a bad
// entry, a busy mirror, a stale --accept or an unreadable state. Sync never runs gc or prune:
// a reader holds `served` after the lock is released and reads its objects later (Filbert N2).
// C2-03b: `credential` is the bus's choice for the fetch, { kind, user, file } or { refused: code }.
// A refusal (library-fetch-no-grant) is recorded like any held fetch, and no file is opened. Without
// it, `slot` is slot library-gitea with the entry's user, as in C2-03a. The state names the kind and
// the user the last fetch ran with, never the file or the value.
export async function sync(context, { slot, credential = null, accept = null, command = syncCommand, now = () => new Date(), limits = GIT_LIMITS } = {}) {
export async function sync(context, { slot, accept = null, command = syncCommand, now = () => new Date(), limits = GIT_LIMITS } = {}) {
const mirror = await ensureMirror(context);
const mapping = checkMapping(context.business.projects[context.project]);
const { branch } = mapping;
if (typeof mapping.user !== 'string') fail('library-remote-invalid', 'library entry has no user for sync');
const chosen = credential === null ? { kind: 'slot', file: typeof slot === 'string' ? slot : null } : checkCredential(credential);
const user = chosen.user ?? mapping.user;
const { branch, user } = mapping;
if (typeof user !== 'string') fail('library-remote-invalid', 'library entry has no user for sync');
if (accept !== null && (typeof accept !== 'string' || !SHA.test(accept))) fail('library-accept-invalid', 'accept takes a full commit id');
if (running.has(mirror)) fail('library-sync-busy', 'a sync of this library is running');
running.add(mirror);
try {
let code = null, tip = null, read = null, used = null;
if (Object.hasOwn(chosen, 'refused')) code = typeof chosen.refused === 'string' && CODE.test(chosen.refused) ? chosen.refused : 'library-fetch-no-grant';
else if (typeof chosen.file !== 'string' || !slotPresent(chosen.file)) code = 'library-credential-missing';
let code = null, tip = null, read = null;
if (typeof slot !== 'string' || !slotPresent(slot)) code = 'library-credential-missing';
else {
used = { kind: chosen.kind, user };
const { argv, env } = command('fetch', mapping.remote, { mirror, branch, user, slot: chosen.file });
const { argv, env } = command('fetch', mapping.remote, { mirror, branch, user, slot });
const result = await runGit(argv, env, limits);
// git's stderr is never kept or logged: the code is the whole record.
if (!result.ok) code = 'library-fetch-failed';
@@ -181,7 +127,7 @@ export async function sync(context, { slot, credential = null, accept = null, co
const prev = accept !== null
? { version: 1, branch, served, lastFetch: null, lastError: null, diverged: null, problems: [] }
: await readSyncState({ branch });
let next = { ...prev, credential: used }, target = served;
let next = { ...prev }, target = served;
if (code !== null) next.lastError = { code, at };
else if (accept !== null) {
const problems = await problemsOf();
@@ -212,84 +158,3 @@ export async function sync(context, { slot, credential = null, accept = null, co
});
} finally { running.delete(mirror); }
}
// C2-03b: push `commit`, already in the mirror, to her branch with the writer's own credential. It
// resolves { pushed: true } or, when the remote tip moved, { pushed: false, raced: true, tip } after
// one fetch with the same credential; the caller re-applies once and calls again with retried: true,
// and a second race refuses stale-base. The fetch refuses library-sync-busy while a sync of the same
// mirror runs. A hook refusal ([remote rejected]) or any other failure
// refuses library-push-failed, and git's output is never kept. It moves no local ref: C2-02 moves the
// remote-tracking and served refs after a push.
export async function push(context, { commit, credential, retried = false, writeToken = null, command = syncCommand, limits = GIT_LIMITS } = {}) {
const mirror = await ensureMirror(context);
const mapping = checkMapping(context.business.projects[context.project]);
const { branch } = mapping;
const chosen = checkCredential(credential);
if (Object.hasOwn(chosen, 'refused'))
fail(typeof chosen.refused === 'string' && CODE.test(chosen.refused) ? chosen.refused : 'library-credential-missing', 'the bus refused a credential');
if (typeof chosen.user !== 'string') fail('library-credential-missing', 'a push names its user');
if (typeof chosen.file !== 'string' || !slotPresent(chosen.file))
fail(chosen.kind === 'human' ? 'library-human-missing' : 'library-credential-missing', 'credential file missing or unsafe');
if (typeof commit !== 'string' || !SHA.test(commit)) fail('library-remote-invalid', 'a push takes a full commit id');
const opts = { mirror, branch, user: chosen.user, slot: chosen.file };
const { argv, env } = command('push', mapping.remote, { ...opts, commit });
const result = await runGit(argv, env, limits);
if (result.ok) return { pushed: true };
// --porcelain: one tab-separated line per ref on stdout, '!' and the summary for a refusal.
const line = String(result.out ?? '').split('\n').find(l => l.split('\t')[1] === `${commit}:refs/heads/${branch}`);
const summary = line?.split('\t')[2] ?? '';
if (!line?.startsWith('!\t') || !/^\[rejected\] \((fetch first|non-fast-forward)\)$/.test(summary))
fail('library-push-failed', 'push refused');
if (retried) fail('stale-base', 'her branch moved again during the write');
// The race fetch writes the mirror, so it takes sync's guard (dewey-0864 R1). A held guard refuses
// library-sync-busy and the caller tries the write again.
const owned = writeToken !== null && writers.get(mirror) === writeToken;
if (running.has(mirror) && !owned) fail('library-sync-busy', 'a sync of this library is running');
if (!owned) running.add(mirror);
try {
const fetch = command('fetch', mapping.remote, opts);
if (!(await runGit(fetch.argv, fetch.env, limits)).ok) fail('library-push-failed', 'fetch after a moved tip failed');
let tip;
try { tip = await git(mirror, ['rev-parse', '--verify', '--end-of-options', `refs/remotes/library/${branch}^{commit}`]); }
catch { fail('library-push-failed', 'fetch after a moved tip found no branch'); }
if (!SHA.test(tip)) fail('library-push-failed', 'fetch after a moved tip found no branch');
return { pushed: false, raced: true, tip };
} finally { if (!owned) running.delete(mirror); }
}
// Called under the publication lock by C2-02; the raw state writer stays private.
export async function publishLibraryWrite(mirror, { mapping, commit, previous, readSyncState, now = () => new Date() }) {
if (!SHA.test(commit) || (previous !== null && !SHA.test(previous))) fail('library-state-invalid');
const state = await readSyncState({ branch: mapping.branch });
if (state.diverged !== null) fail('library-diverged');
if (state.served !== previous) fail('library-state-invalid');
const read = await indexFor({ repo: mirror, commit, mapping });
const at = now().toISOString();
const next = { ...state, served: commit, lastPush: { commit, at }, lastError: null,
problems: read.problems.map(p => ({ ...p })) };
const tracking = `refs/remotes/library/${mapping.branch}`;
// The remote push already succeeded. A local publication failure is outcome-unknown to the
// caller; it must never encourage an automatic second push.
let moved = false;
try {
await git(mirror, ['update-ref', 'refs/heads/served', commit, previous ?? ZERO]);
moved = true;
await git(mirror, ['update-ref', tracking, commit]);
writeState(mirror, next);
} catch {
if (moved) {
// A rename may have succeeded before directory fsync failed. Keep the new ref when the
// validated state already matches it; otherwise restore served by compare-and-swap.
let published = false;
try { published = (await readSyncState({ branch: mapping.branch })).served === commit; } catch {}
if (!published) {
try {
await git(mirror, ['update-ref', ...(previous === null
? ['-d', 'refs/heads/served', commit] : ['refs/heads/served', previous, commit])]);
} catch { fail('outcome-unknown'); }
}
}
fail('outcome-unknown');
}
return next;
}
-185
View File
@@ -1,185 +0,0 @@
// C2-02: one-path plumbing commits on the private bare mirror. No checkout and no pending push.
import { lstatSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { SAFE, git, gitBytes } from '../../project/src/git.mjs';
import { gitEnv, runGit, GIT_LIMITS } from '../../seat/src/checkout.mjs';
import { ID_PATTERN } from '../../business/src/vocabulary.mjs';
import { checkMapping } from './mapping.mjs';
import { classify } from './scope.mjs';
import { supportingPath } from './supporting.mjs';
import { LibraryError } from './problems.mjs';
import { listTree, MAX_BLOB } from './reader.mjs';
import { mirrorPath, ensureMirror, withLibraryLock } from './mirror.mjs';
import { syncCommand, push, withLibraryWriteGuard, publishLibraryWrite } from './sync.mjs';
const SHA = /^[a-f0-9]{40}$/;
const fail = code => { throw new LibraryError(code, code); };
const ident = identity => ({ GIT_AUTHOR_NAME: identity.name, GIT_AUTHOR_EMAIL: identity.email,
GIT_COMMITTER_NAME: identity.name, GIT_COMMITTER_EMAIL: identity.email });
function mappingOf(context) {
if (!Object.hasOwn(context.business?.projects ?? {}, context.project)) fail('project-not-configured');
return checkMapping(context.business.projects[context.project]);
}
function contentOf(value) {
if (typeof value !== 'string' || value.includes('\0') || Buffer.byteLength(value, 'utf8') > MAX_BLOB
|| Buffer.from(value, 'utf8').toString('utf8') !== value) fail('invalid-request');
return value;
}
function credentialOf(credential, human) {
const code = human ? 'library-human-missing' : 'library-write-no-grant';
if (!credential || credential.kind !== (human ? 'human' : 'seat')
|| typeof credential.user !== 'string' || !/^[A-Za-z0-9_.-]{1,100}$/.test(credential.user)
|| typeof credential.file !== 'string') fail(code);
try {
const st = lstatSync(credential.file);
if (!st.isFile() || st.uid !== process.getuid() || st.nlink !== 1 || (st.mode & 0o777) !== 0o600 || st.size > 16384) fail(code);
} catch { fail(code); }
return credential;
}
// Her save uses the same structural and folded-tree checks; only the supporting rule changes.
function pathOf(mapping, universe, path, tree, human) {
if (!human) return supportingPath(mapping, universe, path, tree);
if (typeof path !== 'string' || classify(mapping, path).scope === 'unmapped') fail('library-write-story-path');
const place = classify(mapping, path);
const universes = Object.fromEntries(Object.keys(mapping.universes).map(id => [id,
{ ...mapping.universes[id], supporting: id === place.universe ? [path.slice(0, path.lastIndexOf('/') + 1)] : [] }]));
return supportingPath({ ...mapping, universes }, place.universe, path, tree);
}
async function ref(mirror, name) {
const rows = await git(mirror, ['for-each-ref', '--format=%(refname) %(objectname)', name]);
const line = rows.split('\n').find(row => row.startsWith(name + ' '));
return line ? line.slice(name.length + 1) : null;
}
async function ancestor(mirror, older, newer) {
const result = await runGit([...SAFE, '-C', mirror, 'merge-base', '--is-ancestor', older, newer], gitEnv());
if (result.ok) return true;
if (result.why === 'exit 1') return false;
fail('library-git');
}
async function fetchTip(mirror, mapping, credential, command) {
const c = command('fetch', mapping.remote, { mirror, branch: mapping.branch, user: credential.user, slot: credential.file });
if (!(await runGit(c.argv, c.env)).ok) fail('library-push-failed');
const tip = await ref(mirror, `refs/remotes/library/${mapping.branch}`);
if (!tip || !SHA.test(tip)) fail('library-push-failed');
return tip;
}
async function plumbing(mirror, tip, path, content, identity, message, stage) {
const env = { ...gitEnv(), ...ident(identity), GIT_INDEX_FILE: join(stage, 'index'), GIT_CEILING_DIRECTORIES: dirname(mirror) };
const run = async (args, input = null) => {
const result = await runGit([...SAFE, '-c', 'core.createObject=rename', '-C', mirror, ...args], env, GIT_LIMITS, { stdin: input });
if (!result.ok) fail('library-git');
return result.out.trimEnd();
};
rmSync(env.GIT_INDEX_FILE, { force: true });
await run(['read-tree', tip]);
if (content === null) await run(['update-index', '--force-remove', '--', path]);
else {
const file = join(stage, 'content'); writeFileSync(file, content, { mode: 0o600 });
const blob = await run(['hash-object', '-w', '--no-filters', file]);
// --cacheinfo keeps the path a separate argv item; no pathspec expansion or filters.
await run(['update-index', '--add', '--cacheinfo', '100644', blob, path]);
}
const tree = await run(['write-tree']);
return run(['commit-tree', tree, '-p', tip, '-m', message]);
}
async function revertChange(mirror, served, context, mapping) {
const commit = context.commit;
const refuse = () => fail('library-revert-not-agent');
if (!served || !SHA.test(commit)) refuse();
let text, parents;
try {
if (!await ancestor(mirror, commit, served)) refuse();
text = await git(mirror, ['show', '-s', '--format=%(trailers:key=Mosaic-Agent,valueonly)', commit]);
parents = (await git(mirror, ['show', '-s', '--format=%P', commit])).split(' ');
} catch { refuse(); }
if (parents.length !== 1 || !SHA.test(parents[0])
|| !text.startsWith(context.business.id + '/')
|| !ID_PATTERN.test(text.slice(context.business.id.length + 1))) refuse();
const before = await listTree(mirror, parents[0]), after = await listTree(mirror, commit);
const old = new Map(before.map(e => [e.path, e])), current = new Map(after.map(e => [e.path, e]));
const changed = [...new Set([...old.keys(), ...current.keys()])].filter(path =>
old.get(path)?.oid !== current.get(path)?.oid || old.get(path)?.mode !== current.get(path)?.mode);
if (changed.length !== 1) refuse();
const path = changed[0], was = old.get(path), made = current.get(path);
if ((was && (was.mode !== '100644' || was.type !== 'blob' || was.size > MAX_BLOB))
|| (made && (made.mode !== '100644' || made.type !== 'blob'))) refuse();
pathOf(mapping, null, path, after, true);
const bytes = was ? await gitBytes(mirror, ['cat-file', 'blob', was.oid], MAX_BLOB) : null;
let content = null;
if (bytes !== null) {
try { content = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes); } catch { refuse(); }
contentOf(content);
}
return { path, base: made?.oid ?? null, content, reverted: commit };
}
async function write(context, options, human, revert = false) {
const mapping = mappingOf(context);
if (human && !mapping.editor) fail('library-mapping-invalid');
const credential = credentialOf(options.credential, human);
const identity = human ? mapping.editor : options.identity;
if (!identity || typeof identity.name !== 'string' || typeof identity.email !== 'string') fail('library-write-refused');
if (!human && (typeof options.agent !== 'string' || !options.agent.startsWith(context.business.id + '/'))) fail('library-write-refused');
const op = options.op ?? 'write';
if (!['write', 'delete'].includes(op)) fail('invalid-request');
let change = revert ? null : { path: context.path, base: context.base, content: op === 'delete' ? null : contentOf(context.content) };
if (change) {
if (change.base !== null && (typeof change.base !== 'string' || !SHA.test(change.base))) fail('invalid-request');
pathOf(mapping, context.universe, change.path, [], human);
}
const mirror = mirrorPath(context);
return withLibraryWriteGuard(mirror, writeToken => withLibraryLock(mirror, async lock => {
await ensureMirror(context);
const state = await lock.readSyncState({ branch: mapping.branch });
if (state.diverged !== null) fail('library-diverged');
const served = state.served;
if (!served) fail('library-commit');
if (revert) change = await revertChange(mirror, served, context, mapping);
// Check the served tree before any remote effect, then recheck against every fetched tip.
pathOf(mapping, context.universe, change.path, await listTree(mirror, served), human);
const tracking = `refs/remotes/library/${mapping.branch}`, previous = await ref(mirror, tracking);
let pushed = false;
const stage = mkdtempSync(join(dirname(mirror), '.library-write-'));
try {
let tip = await fetchTip(mirror, mapping, credential, options.command ?? syncCommand);
for (let attempt = 0; attempt < 2; attempt++) {
if (!await ancestor(mirror, served, tip)) fail('library-diverged');
const tree = await listTree(mirror, tip);
pathOf(mapping, context.universe, change.path, tree, human);
const entry = tree.find(e => e.path === change.path);
if ((!human && op === 'delete' && (!entry || entry.mode !== '100644' || entry.type !== 'blob'))
|| (entry && (entry.mode !== '100644' || entry.type !== 'blob'))
|| tree.some(e => e.path.startsWith(change.path + '/') || change.path.startsWith(e.path + '/')))
fail('library-write-story-path');
if ((entry?.oid ?? null) !== change.base) fail('stale-base');
const action = change.content === null ? 'delete' : 'write';
const message = `Mosaic: ${action} ${change.path}` + (human ? '' : `\n\nMosaic-Agent: ${options.agent}`);
const commit = await plumbing(mirror, tip, change.path, change.content, identity, message, stage);
// Broker rechecks live grants/holder immediately before each push.
options.beforePush?.();
const result = await push(context, { commit, credential, retried: attempt === 1, writeToken, command: options.command ?? syncCommand });
if (!result.pushed) { tip = result.tip; continue; }
pushed = true;
try {
// The broker records the pushed commit even if publication fails next (mos-1520).
options.onPushed?.({ project: context.project, path: change.path, commit });
await publishLibraryWrite(mirror, { mapping, commit, previous: served, readSyncState: lock.readSyncState, now: options.now });
} catch { fail('outcome-unknown'); }
return { project: context.project, path: change.path, ...(revert ? { reverted: change.reverted } : {}), commit };
}
fail('stale-base');
} finally {
rmSync(stage, { recursive: true, force: true });
if (!pushed) {
if (previous === null) await git(mirror, ['update-ref', '-d', tracking]);
else await git(mirror, ['update-ref', tracking, previous]);
}
}
}));
}
export const writeLibraryDoc = (context, options = {}) => write(context, options, false);
export const saveLibraryFile = (context, options = {}) => write(context, options, true);
export const revertLibraryCommit = (context, options = {}) => write(context, options, true, true);
+2 -1
View File
@@ -2,7 +2,7 @@
// time on a 3,000-file fixture. Fixtures are made up and built under the scratch area.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { symlinkSync, writeFileSync } from 'node:fs';
import { mkdirSync, symlinkSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { performance } from 'node:perf_hooks';
import { clearIndexCache, indexCacheSize, indexFor } from '../src/index-build.mjs';
@@ -40,6 +40,7 @@ test('a different repo path, mapping or commit gets its own index', async t => {
symlinkSync(repo, alias);
assert.notEqual(await indexFor({ repo: alias, commit, mapping: mapping() }), base);
assert.notEqual(await indexFor({ repo, commit, mapping: named('Renamed Harbor') }), base);
mkdirSync(join(repo, 'Book One/Places'), { recursive: true });
writeFileSync(join(repo, 'Book One/Places/New.md'), note('place', 'New'));
git(repo, 'add', '-A');
git(repo, 'commit', '-qm', 'second');
-19
View File
@@ -29,22 +29,3 @@ export const note = (type, name, body = '', extra = []) => ['---', `type: ${type
// `exclude` (a path prefix today); swapping these two constants is the whole change to the tests.
export const EXCLUSION = { exclude: 'Book One/Research' };
export const EXCLUDED_PATHS = ['Book One/Research/Ferry Logs.md'];
// C2-05c: synthetic scope fixture, including same-prefix precedence and a draft.
export const SUPPORT_FILES = {
'Book One/Characters/Canon.md': note('character', 'Canon', 'Scope fixture canon.'),
'Book One/Playground/Plan.md': note('summary', 'Plan', 'Scope fixture playground.'),
'Book One/Support/Notes/Helper.md': note('summary', 'Helper', 'Scope fixture supporting.'),
'Notes/HarborSupport/Loose.md': note('summary', 'Loose', 'Scope fixture supporting loose.'),
'Drafts/Idea/Support/Seed.md': note('summary', 'Seed', 'Scope fixture supporting draft.'),
};
export const withSupporting = entry => ({
...entry,
universes: {
...entry.universes,
harbor: { ...entry.universes.harbor,
playground: [...entry.universes.harbor.playground, 'Book One/Support/'],
supporting: ['Book One/Support/', 'Notes/HarborSupport/'] },
idea: { kind: 'draft', name: 'Idea', playground: ['Drafts/Idea/'], supporting: ['Drafts/Idea/Support/'] },
},
});
+9 -106
View File
@@ -1,13 +1,11 @@
// Query tests for design 3 (C2-05a): universe isolation, scope labels, unmapped files, hybrids, paging
// under the reply cap, refusals and manuscript paging. Fixtures are made up and built under the scratch area.
import { test } from 'node:test';
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import assert from 'node:assert/strict';
import { REPLY_CAP } from '../../harness/src/tools.mjs';
import { find, get, search, manuscript, universeInfo, QUERY_REPLY_CAP, LOOKUP_LIMIT, MANUSCRIPT_LINES } from '../src/query.mjs';
import { mapping, MARKER, git } from './helpers.mjs';
import { scratchRepo, note, EXCLUSION, EXCLUDED_PATHS, SUPPORT_FILES, withSupporting } from './query-fixture.mjs';
import { mapping, MARKER } from './helpers.mjs';
import { scratchRepo, note, EXCLUSION, EXCLUDED_PATHS } from './query-fixture.mjs';
// A hybrid over harbor and second. Its one constraint is EXCLUSION (query-fixture.mjs) and it declares no
// books or playground.
@@ -94,9 +92,9 @@ test('a hybrid sees its sources canon, minus exclusions, and no playground', asy
const s = src(scratchRepo(t, FILES), mapping(WITH_BLEND));
const reply = await find(s, { universe: 'blend', query: '' });
assert.deepEqual(paths(reply).sort(), [
'Book One/Characters/Mara Vell.md', 'Book One/Characters/Tomas.md', 'Book One/Chapters/Chapter 01.md',
'Book One/Chapters/Chapter 02.md', 'Book One/Places/Harbor Town.md',
'Second World/Characters/Ilse.md', 'Second World/Chapters/01.md',
'Book One/Chapters/Chapter 01.md', 'Book One/Chapters/Chapter 02.md',
'Book One/Characters/Mara Vell.md', 'Book One/Characters/Tomas.md', 'Book One/Places/Harbor Town.md',
'Second World/Chapters/01.md', 'Second World/Characters/Ilse.md',
]);
assert.ok(reply.results.every(r => r.scope === 'canon' && ['harbor', 'second'].includes(r.universe)));
assert.deepEqual((await find(s, { universe: 'blend', query: '', scope: 'playground' })).results, []);
@@ -347,9 +345,9 @@ test('PRD 1.14: a draft universe has no canon, so its lookups return files only
assert.ok(found.results.every(r => r.scope === 'playground' && r.universe === 'idea' && r.book === null));
const hits = (await search(s, { universe: 'idea', text: 'draft', scope: 'playground' })).results;
assert.equal(hits.length, 2);
const rin = await get(s, { universe: 'idea', path: 'Drafts/New World/Characters/Rin.md', scope: 'playground' });
const rin = await get(s, { universe: 'idea', path: 'Drafts/New World/Characters/Rin.md' });
assert.equal(rin.scope, 'playground');
assert.equal(await get(s, { universe: 'harbor', path: 'Drafts/New World/Characters/Rin.md', scope: 'playground' }), null);
assert.equal(await get(s, { universe: 'harbor', path: 'Drafts/New World/Characters/Rin.md' }), null);
});
test('PRD 1.14: library_universe on a draft returns its kind, name and prefixes', async t => {
@@ -365,102 +363,7 @@ test('PRD 1.14: library_universe on a draft returns its kind, name and prefixes'
test('a hybrid gets a source playground file as null, while the source gets it with scope playground', async t => {
const ref = scratchRepo(t, FILES);
const path = 'Book One/Playground/What If.md';
assert.equal(await get(src(ref, mapping(WITH_BLEND)), { universe: 'blend', path, scope: 'playground' }), null);
const own = await get(src(ref), { universe: 'harbor', path, scope: 'playground' });
assert.equal(await get(src(ref, mapping(WITH_BLEND)), { universe: 'blend', path }), null);
const own = await get(src(ref), { universe: 'harbor', path });
assert.equal(own.scope, 'playground');
});
// mos-1330 item3: the new get contract defaults to canon even for an explicit playground path.
test('C2-05c get without scope returns null for a playground path', async t => {
const s = src(scratchRepo(t, FILES));
assert.equal(await get(s, { universe: 'harbor', path: 'Book One/Playground/What If.md' }), null);
});
// Row284: scope is explicit for get as well as lists; blob and lines share a served snapshot.
test('C2-05c supporting find/search/get are opt-in at book, universe and draft level', async t => {
const s = src(scratchRepo(t, SUPPORT_FILES), mapping(withSupporting));
const expected = ['Book One/Support/Notes/Helper.md', 'Notes/HarborSupport/Loose.md'];
assert.deepEqual(paths(await find(s, { universe: 'harbor', query: '', scope: 'supporting' })), expected);
assert.deepEqual((await search(s, { universe: 'harbor', text: 'Scope fixture', scope: 'supporting' })).results.map(x => x.path), expected);
assert.deepEqual(paths(await find(s, { universe: 'harbor', query: '' })), ['Book One/Characters/Canon.md']);
assert.deepEqual((await search(s, { universe: 'harbor', text: 'Scope fixture' })).results.map(x => x.path), ['Book One/Characters/Canon.md']);
for (const path of expected) {
assert.equal(await get(s, { universe: 'harbor', path }), null);
assert.equal(await get(s, { universe: 'harbor', path, scope: 'playground' }), null);
assert.equal((await get(s, { universe: 'harbor', path, scope: 'supporting' })).scope, 'supporting');
assert.equal(await get(s, { universe: 'second', path, scope: 'supporting' }), null);
}
const draftPath = 'Drafts/Idea/Support/Seed.md';
assert.deepEqual(paths(await find(s, { universe: 'idea', query: '', scope: 'supporting' })), [draftPath]);
assert.equal((await get(s, { universe: 'idea', path: draftPath, scope: 'supporting' })).scope, 'supporting');
assert.equal(await get(s, { universe: 'idea', path: draftPath }), null);
assert.equal((await find(s, { universe: 'harbor', query: '', book: 'Book One', scope: 'supporting' })).results.length, 1);
});
test('C2-05c an absent supporting prefix returns nothing without refusal', async t => {
const s = src(scratchRepo(t, SUPPORT_FILES));
assert.deepEqual((await find(s, { universe: 'harbor', query: '', scope: 'supporting' })).results, []);
assert.deepEqual((await search(s, { universe: 'harbor', text: 'Scope fixture', scope: 'supporting' })).results, []);
assert.equal(await get(s, { universe: 'harbor', path: 'Book One/Characters/Canon.md', scope: 'supporting' }), null);
assert.equal(await get(s, { universe: 'harbor', path: 'Book One/Support/Notes/Helper.md', scope: 'supporting' }), null);
});
test('C2-05c each get blob equals its served tree object, even after source HEAD advances', async t => {
const ref = scratchRepo(t, SUPPORT_FILES), s = src(ref, mapping(withSupporting));
const canon = 'Book One/Characters/Canon.md';
const priorBlob = git(ref.repo, 'rev-parse', `${ref.commit}:${canon}`);
writeFileSync(join(ref.repo, canon), note('character', 'Canon changed', 'New HEAD must not be read.'));
git(ref.repo, 'add', '-A'); git(ref.repo, 'commit', '-qm', 'advance head fixture');
assert.notEqual(git(ref.repo, 'rev-parse', `HEAD:${canon}`), priorBlob);
for (const [scope, path] of [['canon', canon], ['playground', 'Book One/Playground/Plan.md'], ['supporting', 'Book One/Support/Notes/Helper.md']]) {
const result = await get(s, { universe: 'harbor', path, scope });
assert.equal(result.commit, ref.commit);
assert.equal(result.blob, git(ref.repo, 'rev-parse', `${ref.commit}:${path}`));
assert.ok(!JSON.stringify(result.lines).includes('New HEAD must not be read'));
}
});
test('C2-05c full outgoing and incoming links stay in scope order across pages without losing cross-scope links', async t => {
const files = {}, groups = { supporting: [], playground: [], canon: [] };
for (const [scope, folder] of [['canon', 'Book One/Characters'], ['playground', 'Book One/Playground'], ['supporting', 'Book One/Support']]) {
for (let n = 0; n < 100; n++) {
const path = `${folder}/${scope}-${String(n).padStart(3, '0')}-${'x'.repeat(80)}.md`;
groups[scope].push(path);
files[path] = `[[Book One/Characters/Hub]]\n`;
}
}
const all = [...groups.canon, ...groups.playground, ...groups.supporting];
files['Book One/Characters/Hub.md'] = all.map(path => `[[${path.slice(0, -3)}]]`).join('\n');
// Other-universe links are never returned, regardless of rank.
files['Second World/Other.md'] = '[[Book One/Characters/Hub]]\n';
const s = src(scratchRepo(t, files), mapping(withSupporting));
const outs = [], ins = [];
let offset = 0, pages = 0;
for (; pages < 20; pages++) {
const page = await get(s, { universe: 'harbor', path: 'Book One/Characters/Hub.md', from: 999_999, links_from: offset });
assert.ok(JSON.stringify(page).length <= QUERY_REPLY_CAP);
outs.push(...page.links_out.map(x => x.path)); ins.push(...page.links_in.map(x => x.path));
if (page.links_next === null) break;
offset = page.links_next;
}
const expected = [...groups.supporting, ...groups.playground, ...groups.canon];
assert.ok(pages > 0 && pages < 20, 'links occupy multiple bounded pages');
assert.deepEqual(outs, expected);
assert.deepEqual(ins, expected);
assert.equal(new Set(outs).size, 300);
assert.equal(new Set(ins).size, 300);
});
test('C2-05c manuscript still refuses supporting rather than silently widening its scope', async t => {
const s = src(scratchRepo(t, SUPPORT_FILES), mapping(withSupporting));
await assert.rejects(manuscript(s, { universe: 'harbor', book: 'Book One', scope: 'supporting' }), { code: 'query-argument-invalid' });
});
test('C2-05c scope expansion keeps hybrid sources canon-only and refuses all/array scopes', async t => {
const s = src(scratchRepo(t, SUPPORT_FILES), mapping(entry => withSupporting(WITH_BLEND(entry))));
assert.deepEqual((await find(s, { universe: 'blend', query: '', scope: 'supporting' })).results, []);
assert.equal(await get(s, { universe: 'blend', path: 'Book One/Support/Notes/Helper.md', scope: 'supporting' }), null);
assert.equal((await get(s, { universe: 'blend', path: 'Book One/Characters/Canon.md' })).scope, 'canon');
for (const scope of ['all', ['canon', 'supporting']])
await assert.rejects(get(s, { universe: 'harbor', path: 'Book One/Characters/Canon.md', scope }), { code: 'query-argument-invalid' });
});
+4 -227
View File
@@ -3,14 +3,14 @@
// argv and adds the CA to its env. The token is made up and must appear nowhere but the slot.
import test, { before, after } from 'node:test';
import assert from 'node:assert/strict';
import { accessSync, chmodSync, constants, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';
import { accessSync, constants, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { spawnSync } from 'node:child_process';
import { scratchCa, fakeGitea } from '../../seat/tests/fake-gitea.mjs';
import { SAFE } from '../../project/src/git.mjs';
import { mappingEntry, repo, git, BASE } from './helpers.mjs';
import { syncCommand, sync, push, humanCredential, ASKPASS, SLOT, HUMAN_SLOT, SYNC_INTERVAL_MS } from '../src/sync.mjs';
import { syncCommand, sync, ASKPASS, SLOT, SYNC_INTERVAL_MS } from '../src/sync.mjs';
import { mirrorPath, readSyncState, readLibraryFile, SYNC_STATE_FILE } from '../src/mirror.mjs';
import { readLibrary } from '../src/reader.mjs';
import { checkMapping } from '../src/mapping.mjs';
@@ -25,9 +25,9 @@ after(() => rmSync(scratch, { recursive: true, force: true }));
const clock = () => { let n = 0; return () => new Date(Date.UTC(2026, 9, 21, 12, 0, n++)); };
async function world(t, { token = TOKEN, redirect = null, user = USER, users = { [USER]: token } } = {}) {
async function world(t, { token = TOKEN, redirect = null, user = USER } = {}) {
const f = repo(t);
const gitea = await fakeGitea({ dir: join(f.root, 'gitea'), tls, user: USER, token, users, redirect });
const gitea = await fakeGitea({ dir: join(f.root, 'gitea'), tls, user: USER, token, redirect });
t.after(() => gitea.close());
const remote = gitea.repo('writer', 'books');
mkdirSync(dirname(remote), { recursive: true });
@@ -304,226 +304,3 @@ test('C2-03a one sync per mirror: an overlapping call refuses library-sync-busy'
assert.equal(results.find(r => r.status === 'rejected').reason.code, 'library-sync-busy');
assert.equal((await w.run()).code, null, 'the mirror is free again afterwards');
});
// C2-03b (#1791): push and per-seat credentials. A seat's grant store file is the token plus "\n", as
// Credentials writes it. SEAT_TOKEN is made up too and must also appear nowhere but its file.
const SEAT = 'writer-seat';
const SEAT_TOKEN = 'fixture-token-71ae-made-up-0044';
async function writeWorld(t) {
const w = await world(t, { users: { [USER]: TOKEN, [SEAT]: SEAT_TOKEN } });
const seatFile = join(w.root, 'store', 'acme', SEAT, 'gitea');
mkdirSync(dirname(seatFile), { recursive: true, mode: 0o700 });
writeFileSync(seatFile, SEAT_TOKEN + '\n', { mode: 0o600 });
const seat = { kind: 'seat', user: SEAT, file: seatFile };
assert.equal((await w.run()).code, null);
// A commit on top of `parent` in the mirror, as C2-02's apply would leave it.
const child = (parent, text = 'next') => git(w.mirror(), 'commit-tree', `${parent}^{tree}`, '-p', parent, '-m', text);
const remoteTip = () => git(w.remote, 'rev-parse', 'refs/heads/main');
const write = (options) => push(w.context, { command: w.command, credential: seat, ...options });
return { ...w, seatFile, seat, child, remoteTip, write };
}
test('C2-03b argv: a push sends one full commit to the branch, fast-forward only, with the fetch prefix', () => {
const opts = { mirror: '/srv/data/projects/acme/books', branch: 'main', user: SEAT, slot: '/srv/store/acme/writer-seat/gitea' };
const commit = 'c'.repeat(40);
const { argv, env } = syncCommand('push', 'https://git.example.invalid/writer/books.git', { ...opts, commit });
assert.deepEqual(argv, [...SAFE, '-c', 'protocol.https.allow=always', '-c', 'http.followRedirects=false', '-c', 'credential.helper=',
'-c', 'core.createObject=rename', '-C', opts.mirror, 'push', '--porcelain', '--no-verify', '--no-follow-tags', '--end-of-options',
'https://git.example.invalid/writer/books.git', `${commit}:refs/heads/main`]);
assert.equal(argv.some(a => a.startsWith('+') || a === '--force' || a === '-f' || a.startsWith('--force-')), false, 'no forced update (D6)');
assert.equal(env.MOSAIC_LIBRARY_SLOT, opts.slot);
assert.equal(env.MOSAIC_LIBRARY_USER, SEAT);
for (const bad of [null, undefined, 'main', 'c'.repeat(39), 'C'.repeat(40), `${'c'.repeat(40)}:refs/heads/x`])
assert.throws(() => syncCommand('push', 'https://git.example.invalid/b.git', { ...opts, commit: bad }), { code: 'library-remote-invalid' }, String(bad));
assert.throws(() => syncCommand('gc', 'https://git.example.invalid/b.git', opts), { code: 'library-remote-invalid' });
});
test('C2-03b T1 push: a fast-forward lands with the seat\'s own user and file, and moves no local ref', async t => {
const w = await writeWorld(t);
const before = git(w.mirror(), 'for-each-ref', '--format=%(refname) %(objectname)');
const next = w.child(w.commit);
w.gitea.requests.length = 0;
assert.deepEqual(await w.write({ commit: next }), { pushed: true });
assert.equal(w.remoteTip(), next);
assert.ok(w.gitea.requests.length > 0);
assert.ok(w.gitea.requests.every(r => r.user === null || r.user === SEAT), 'only the seat\'s user reaches the remote');
assert.ok(w.gitea.requests.some(r => r.user === SEAT));
assert.equal(git(w.mirror(), 'for-each-ref', '--format=%(refname) %(objectname)'), before, 'C2-02 moves the local refs, not push');
assert.equal(holdsToken(w.dataRoot), null, 'the bot token sits only in the slot');
for (const name of readdirSync(w.root, { recursive: true })) {
const file = join(w.root, name);
if (file !== w.seatFile && statSync(file).isFile()) assert.equal(readFileSync(file).includes(SEAT_TOKEN), false, file);
}
});
test('C2-03b T2 and T3: a moved tip reports the race after one fetch, and a second race refuses stale-base', async t => {
const w = await writeWorld(t);
const moved = w.push({ 'Inbox Note.md': 'she wrote more\n' });
const mine = w.child(w.commit);
const raced = await w.write({ commit: mine });
assert.deepEqual(raced, { pushed: false, raced: true, tip: moved });
assert.equal(w.remoteTip(), moved, 'her commit stands: nothing forced it out');
assert.equal(git(w.mirror(), 'rev-parse', 'refs/remotes/library/main'), moved, 'the one fetch ran with the same credential');
const again = w.push({ 'Inbox Note.md': 'and more\n' });
await assert.rejects(w.write({ commit: w.child(moved), retried: true }), { code: 'stale-base' });
assert.equal(w.remoteTip(), again);
});
// dewey-0864 R1: the race fetch takes sync's guard. A sync holds it: its fetch is a git alias that
// touches a marker, then waits for a release file. The push starts only once the marker exists and
// the release comes only after the refusal, so no step depends on timing (dewey-0869).
test('C2-03b race fetch: while a sync of the mirror runs, the race refuses library-sync-busy', async t => {
const w = await writeWorld(t);
const moved = w.push({ 'Inbox Note.md': 'she wrote more\n' });
const before = git(w.mirror(), 'rev-parse', 'refs/remotes/library/main');
const mark = join(w.root, 'hold.mark'), release = join(w.root, 'hold.release');
const hold = '!f() { touch "$LIB_HOLD_MARK"; i=0; while [ ! -e "$LIB_HOLD_RELEASE" ] && [ $i -lt 1200 ]; do sleep 0.05; i=$((i+1)); done; }; f';
const slow = (kind, url, opts) => {
const real = w.command(kind, url, opts);
return { argv: ['-c', 'alias.hold=' + hold, 'hold'], env: { ...real.env, LIB_HOLD_MARK: mark, LIB_HOLD_RELEASE: release } };
};
const syncing = sync(w.context, { slot: w.slot, command: slow });
t.after(() => { try { writeFileSync(release, ''); } catch {} });
const end = Date.now() + 30000;
while (!existsSync(mark) && Date.now() < end) await new Promise(r => setTimeout(r, 10));
assert.ok(existsSync(mark), 'the sync is inside its fetch, holding the guard');
await assert.rejects(w.write({ commit: w.child(w.commit) }), { code: 'library-sync-busy' });
assert.equal(w.remoteTip(), moved, 'her commit stands');
writeFileSync(release, '');
await syncing.catch(() => {});
assert.equal(git(w.mirror(), 'rev-parse', 'refs/remotes/library/main'), before, 'the refused race fetched nothing');
assert.deepEqual(await w.write({ commit: w.child(w.commit) }), { pushed: false, raced: true, tip: moved }, 'free again afterwards');
});
test('C2-03b T4: a dead remote, a hook refusal and a wrong token each refuse library-push-failed', async t => {
const w = await writeWorld(t);
// N2: [remote rejected] is a hook, not a race.
const hook = join(w.remote, 'hooks', 'pre-receive');
writeFileSync(hook, '#!/bin/sh\necho no >&2\nexit 1\n', { mode: 0o755 });
const next = w.child(w.commit);
await assert.rejects(w.write({ commit: next }), { code: 'library-push-failed' });
await assert.rejects(w.write({ commit: next, retried: true }), { code: 'library-push-failed' }, 'never stale-base for a hook');
rmSync(hook);
writeFileSync(w.seatFile, 'fixture-token-wrong-0045\n', { mode: 0o600 });
await assert.rejects(w.write({ commit: next }), { code: 'library-push-failed' });
writeFileSync(w.seatFile, SEAT_TOKEN + '\n', { mode: 0o600 });
await w.gitea.close();
await assert.rejects(w.write({ commit: next }), { code: 'library-push-failed' });
assert.equal(w.remoteTip(), w.commit);
});
test('C2-03b push: a refused, missing or unsafe credential runs no git', async t => {
const w = await writeWorld(t);
let called = 0;
const command = (...a) => { called++; return w.command(...a); };
const next = w.child(w.commit);
w.gitea.requests.length = 0;
const cases = [
[{ refused: 'library-fetch-no-grant' }, 'library-fetch-no-grant'],
[null, 'library-credential-missing'],
[{ kind: 'seat', file: w.seatFile }, 'library-credential-missing'],
[{ kind: 'seat', user: 'a b', file: w.seatFile }, 'library-credential-missing'],
[{ kind: 'nobody', user: SEAT, file: w.seatFile }, 'library-credential-missing'],
[{ ...w.seat, file: join(w.root, 'absent') }, 'library-credential-missing'],
[{ kind: 'human', user: 'her-login', file: join(w.root, 'absent') }, 'library-human-missing'],
];
for (const [credential, code] of cases)
await assert.rejects(push(w.context, { commit: next, credential, command }), { code }, JSON.stringify(credential));
chmodSync(w.seatFile, 0o644);
await assert.rejects(push(w.context, { commit: next, credential: w.seat, command }), { code: 'library-credential-missing' });
chmodSync(w.seatFile, 0o600);
await assert.rejects(push(w.context, { commit: 'main', credential: w.seat, command }), { code: 'library-remote-invalid' });
assert.equal(called, 0);
assert.equal(w.gitea.requests.length, 0);
});
test('C2-03b T10 humanCredential: her login and a 0600 slot library-human, or library-human-missing', t => {
const configDir = mkdtempSync(join(tmpdir(), 'library-human-'));
t.after(() => rmSync(configDir, { recursive: true, force: true }));
const context = { business: { id: 'acme' }, project: 'books' };
const file = join(configDir, 'secrets', 'acme', HUMAN_SLOT);
assert.throws(() => humanCredential(context, { user: 'her-login', configDir }), { code: 'library-human-missing' }, 'missing');
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
writeFileSync(file, 'fixture-token-human-0046\n', { mode: 0o600 });
assert.deepEqual(humanCredential(context, { user: 'her-login', configDir }), { kind: 'human', user: 'her-login', file });
for (const user of [undefined, null, '', 'a b', 'her@x'])
assert.throws(() => humanCredential(context, { user, configDir }), { code: 'library-human-missing' }, String(user));
assert.throws(() => humanCredential(context, { user: 'her-login' }), { code: 'library-human-missing' });
chmodSync(file, 0o644);
assert.throws(() => humanCredential(context, { user: 'her-login', configDir }), { code: 'library-human-missing' }, '0644');
chmodSync(file, 0o600);
const real = join(configDir, 'real'); writeFileSync(real, 'x\n', { mode: 0o600 });
rmSync(file); symlinkSync(real, file);
assert.throws(() => humanCredential(context, { user: 'her-login', configDir }), { code: 'library-human-missing' }, 'a link');
});
test('C2-03b fetch credential: the state names the kind and user, a refusal runs no git, and a pre-286 state still reads', async t => {
const w = await world(t, { users: { [USER]: TOKEN, [SEAT]: SEAT_TOKEN } });
const first = await w.run();
assert.equal(first.code, null);
assert.deepEqual(first.state.credential, { kind: 'slot', user: USER });
assert.deepEqual((await w.state()).credential, { kind: 'slot', user: USER });
// The chief's grant store file, with the chief's Gitea user.
const chiefFile = join(w.root, 'store', 'acme', 'chief', 'gitea');
mkdirSync(dirname(chiefFile), { recursive: true, mode: 0o700 });
writeFileSync(chiefFile, SEAT_TOKEN + '\n', { mode: 0o600 });
w.gitea.requests.length = 0;
const chief = await w.run({ slot: undefined, credential: { kind: 'chief', user: SEAT, file: chiefFile } });
assert.equal(chief.code, null);
assert.deepEqual(chief.state.credential, { kind: 'chief', user: SEAT });
assert.ok(w.gitea.requests.some(r => r.user === SEAT) && w.gitea.requests.every(r => r.user !== USER));
w.gitea.requests.length = 0;
let called = 0;
const refused = await sync(w.context, { credential: { refused: 'library-fetch-no-grant' }, slot: w.slot,
command: (...a) => { called++; return w.command(...a); }, now: clock() });
assert.equal(refused.code, 'library-fetch-no-grant');
assert.equal(refused.state.lastError.code, 'library-fetch-no-grant');
assert.equal(refused.state.credential, null);
assert.equal(called, 0);
assert.equal(w.gitea.requests.length, 0, 'a refusal opens no file and reaches no remote, even with a valid slot');
// N1: a state file written before C2-03b has no credential key and still reads.
const file = join(w.mirror(), SYNC_STATE_FILE);
const { credential, ...old } = JSON.parse(readFileSync(file, 'utf8'));
assert.equal(credential, null);
writeFileSync(file, JSON.stringify(old) + '\n');
assert.deepEqual(await w.state(), old);
writeFileSync(file, JSON.stringify({ ...old, credential: { kind: 'slot', user: USER, file: w.slot } }) + '\n');
await assert.rejects(w.state(), { code: 'library-state-invalid' }, 'the state never names a file');
});
// T5 and T5b: the helper on a seat's file. `stat` is the one external command between the open and the
// read, so a shim on the helper's PATH stands in for another uid and stages a swap.
test('C2-03b T5 helper: the named seat\'s user and file, never a link, 0644, another uid, or a swapped file', t => {
const dir = mkdtempSync(join(tmpdir(), 'library-askpass-seat-'));
t.after(() => rmSync(dir, { recursive: true, force: true }));
const file = join(dir, 'gitea'), other = join(dir, 'other');
writeFileSync(file, SEAT_TOKEN + '\n', { mode: 0o600 });
writeFileSync(other, 'fixture-token-other-0047\n', { mode: 0o600 });
const bin = join(dir, 'bin'); mkdirSync(bin);
const realStat = spawnSync('sh', ['-c', 'command -v stat'], { encoding: 'utf8' }).stdout.trim();
const env = { PATH: '/usr/bin:/bin', MOSAIC_LIBRARY_HOST: '127.0.0.1:4430', MOSAIC_LIBRARY_USER: SEAT, MOSAIC_LIBRARY_SLOT: file };
const prompt = `Password for 'https://${SEAT}@127.0.0.1:4430': `;
const ask = (change = {}, p = prompt) => spawnSync(ASKPASS, [p], { env: { ...env, ...change }, encoding: 'utf8' });
assert.equal(ask().stdout, SEAT_TOKEN + '\n');
assert.equal(ask({}, `Username for 'https://127.0.0.1:4430': `).stdout, SEAT + '\n');
const refused = (r, why) => { assert.equal(r.status, 1, why); assert.equal(r.stdout, '', why); };
refused(ask({}, `Password for 'https://${USER}@127.0.0.1:4430': `), 'another seat\'s user');
const link = join(dir, 'link'); symlinkSync(file, link);
refused(ask({ MOSAIC_LIBRARY_SLOT: link }), 'a link');
chmodSync(file, 0o644); refused(ask(), '0644');
chmodSync(file, 0o640); refused(ask(), '0640');
chmodSync(file, 0o600);
writeFileSync(other, 'x'.repeat(16385), { mode: 0o600 });
refused(ask({ MOSAIC_LIBRARY_SLOT: other }), 'over 16384 bytes');
writeFileSync(other, 'fixture-token-other-0047\n', { mode: 0o600 });
// Another uid: this suite can't chown, so the shim reports uid+1 for the open file.
writeFileSync(join(bin, 'stat'), `#!/bin/sh\ncase $1 in -L) out=$(${realStat} "$@") || exit 1; set -- $out; printf '%s %s %s %s %s %s\\n' "$1" "$(($2 + 1))" "$3" "$4" "$5" "$6" ;; *) exec ${realStat} "$@" ;; esac\n`, { mode: 0o755 });
refused(ask({ PATH: `${bin}:/usr/bin:/bin` }), 'another uid');
// T5b, the swap: on its first call the shim renames another file over the slot, then stats.
const marker = join(dir, 'swapped');
writeFileSync(join(bin, 'stat'), `#!/bin/sh\nif [ ! -e '${marker}' ]; then : > '${marker}'; mv -f '${other}' '${file}'; fi\nexec ${realStat} "$@"\n`, { mode: 0o755 });
refused(ask({ PATH: `${bin}:/usr/bin:/bin` }), 'a file swapped between the check and the read');
assert.ok(statSync(marker).isFile(), 'the swap ran');
assert.equal(readFileSync(file, 'utf8'), 'fixture-token-other-0047\n', 'the slot path names the other file now');
});
-56
View File
@@ -1,56 +0,0 @@
// Shared scratch bare-repository fixture for row 288 library and broker tests.
import assert from 'node:assert/strict';
import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { repo, git, mappingEntry, BASE } from './helpers.mjs';
import { sync, syncCommand } from '../src/sync.mjs';
import { mirrorPath, readSyncState } from '../src/mirror.mjs';
export const PATH = 'Book One/Notes/Agent.md';
export const IDENTITY = { name: 'Bean Fixture', email: '[email protected]' };
export const EDITOR = { name: 'Human Fixture', email: '[email protected]' };
export async function world(t, { business = 'acme' } = {}) {
const f = repo(t, { ...BASE, [PATH]: 'before\n',
'Book One/Notes/Executable.md': { text: 'exec\n', mode: 0o755 },
'Book One/Notes/Link.md': { link: 'Agent.md' } });
git(f.repo, 'update-index', '--add', '--cacheinfo', '160000', f.commit, 'Book One/Notes/Submodule.md');
git(f.repo, 'commit', '-qm', 'gitlink fixture');
const remote = join(f.root, 'remote.git');
git(f.root, 'clone', '-q', '--bare', '--no-local', f.repo, remote);
const dataRoot = join(f.root, 'data'); mkdirSync(dataRoot, { mode: 0o700 });
const entry = { ...mappingEntry(), user: 'human-fixture', editor: { ...EDITOR } };
entry.universes.harbor.supporting = ['Book One/Notes/'];
const context = { business: { id: business, projects: { books: entry } }, project: 'books', dataRoot };
const file = join(f.root, 'fixture-slot'); writeFileSync(file, 'fixture-write-token-288\n', { mode: 0o600 });
const credential = { kind: 'seat', user: 'bean-fixture', file };
// Keep the production refspec exactly: a '+' mutant on push would overwrite the racing remote.
let beforePush = null, reject = false;
const commands = [];
const command = (kind, url, opts) => {
commands.push(kind);
if (kind === 'push' && beforePush) { const fn = beforePush; beforePush = null; fn(); }
const c = syncCommand(kind, url, opts);
const argv = [...c.argv];
argv.splice(0, 0, '-c', 'protocol.file.allow=always');
const at = argv.indexOf(url);
assert.ok(at >= 0);
argv[at] = kind === 'push' && reject ? join(f.root, 'missing.git') : remote;
return { argv, env: c.env };
};
await sync(context, { credential, command });
const mirror = mirrorPath(context);
const refs = () => git(mirror, 'for-each-ref', '--format=%(refname) %(objectname)');
const remoteHead = () => git(remote, 'rev-parse', 'main');
const state = () => readSyncState(mirror, { branch: 'main' });
const external = (path, content) => {
writeFileSync(join(f.repo, path), content); git(f.repo, 'add', '-A'); git(f.repo, 'commit', '-qm', 'external');
git(f.repo, 'push', '-q', remote, 'HEAD:main');
};
const args = (extra = {}) => ({ ...context, universe: 'harbor', path: PATH,
base: git(mirror, 'rev-parse', `served:${PATH}`), content: 'after\n', ...extra });
const opts = { credential, identity: IDENTITY, agent: `${business}/bean`, command };
return { ...f, remote, context, entry, file, credential, command, mirror, refs, remoteHead, state, external, args, opts,
race: fn => { beforePush = fn; }, reject: () => { reject = true; }, commands };
}
-171
View File
@@ -1,171 +0,0 @@
// Row 288: real bare-repository plumbing and remote effects. All text and credentials are fixtures.
import test from 'node:test';
import assert from 'node:assert/strict';
import { writeFileSync, existsSync, renameSync, mkdirSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import { git } from './helpers.mjs';
import { sync, push, withLibraryWriteGuard } from '../src/sync.mjs';
import { servedCommit, withLibraryLock, readSyncState, SYNC_STATE_FILE } from '../src/mirror.mjs';
import { publishLibraryWrite } from '../src/sync.mjs';
import { checkMapping } from '../src/mapping.mjs';
import { writeLibraryDoc, saveLibraryFile, revertLibraryCommit } from '../src/write.mjs';
import { world, PATH, EDITOR } from './write-fixture.mjs';
test('C2-02: write/delete each publish one parent, seat ident, fixed trailer, index and lastPush', async t => {
const f = await world(t), parent = f.remoteHead();
const saved = await writeLibraryDoc(f.args(), f.opts);
assert.deepEqual(saved, { project: 'books', path: PATH, commit: f.remoteHead() });
assert.equal(git(f.remote, 'show', `${saved.commit}:${PATH}`), 'after');
assert.equal(git(f.remote, 'show', '-s', '--format=%P', saved.commit), parent);
assert.equal(git(f.remote, 'show', '-s', '--format=%an <%ae>|%cn <%ce>', saved.commit),
'Bean Fixture <[email protected]>|Bean Fixture <[email protected]>');
assert.equal(git(f.remote, 'show', '-s', '--format=%B', saved.commit), `Mosaic: write ${PATH}\n\nMosaic-Agent: acme/bean`);
assert.equal(await servedCommit(f.mirror), saved.commit);
assert.equal((await f.state()).lastPush.commit, saved.commit);
assert.equal(existsSync(join(f.mirror, 'index')), false);
const gone = await writeLibraryDoc(f.args({ content: undefined }), { ...f.opts, op: 'delete' });
assert.equal(git(f.remote, 'show', '-s', '--format=%P', gone.commit), saved.commit);
assert.equal(git(f.remote, 'ls-tree', '-r', gone.commit, '--', PATH), '');
assert.equal(git(f.remote, 'show', '-s', '--format=%B', gone.commit), `Mosaic: delete ${PATH}\n\nMosaic-Agent: acme/bean`);
});
test('C2-02 M12: each path refusal leaves every ref and remote unchanged', async t => {
const f = await world(t);
const paths = ['Book One/Chapters/Chapter 01.md', 'Book One/Playground/What If.md', 'Inbox Note.md',
'Book One/Notes/X.canvas', 'Book One/Notes/X.base', 'Book One/Notes/X.png', 'Second World/Chapters/01.md',
'/Book One/Notes/X.md', 'Book One/Notes/../X.md', 'Book One/./Notes/X.md', 'Book One//Notes/X.md',
'Book One/Notes/X\\Y.md', 'Book One/Notes/X\nY.md', 'Book One/Notes/Link.md',
'Book One/Notes/agent.md', `Book One/Notes/${'é'.repeat(512)}.md`];
for (const path of paths) {
const before = f.refs(), head = f.remoteHead();
await assert.rejects(writeLibraryDoc(f.args({ path, base: null }), f.opts), { code: 'library-write-story-path' }, path);
assert.equal(f.refs(), before); assert.equal(f.remoteHead(), head);
}
});
test('C2-02 Q4: delete requires an existing 100644 blob; null base never deletes a missing path', async t => {
const f = await world(t);
for (const path of ['Book One/Notes/Missing.md', 'Book One/Notes/Executable.md', 'Book One/Notes/Link.md', 'Book One/Notes/Submodule.md']) {
const before = f.refs();
await assert.rejects(writeLibraryDoc(f.args({ path, base: null, content: undefined }), { ...f.opts, op: 'delete' }),
{ code: 'library-write-story-path' });
assert.equal(f.refs(), before);
}
});
test('C2-02: stale base and failed push keep remote/served/tracking refs unchanged', async t => {
const f = await world(t), refs = f.refs(), head = f.remoteHead();
await assert.rejects(writeLibraryDoc(f.args({ base: 'a'.repeat(40) }), f.opts), { code: 'stale-base' });
assert.equal(f.refs(), refs); assert.equal(f.remoteHead(), head);
f.reject();
await assert.rejects(writeLibraryDoc(f.args(), f.opts), { code: 'library-push-failed' });
assert.equal(f.refs(), refs); assert.equal(f.remoteHead(), head);
});
test('C2-02: a moved unrelated blob retries once on the new parent, changed target refuses', async t => {
const f = await world(t);
const args = f.args(); let raced;
f.race(() => { f.external('Inbox Note.md', 'another\n'); raced = f.remoteHead(); });
const saved = await writeLibraryDoc(args, f.opts);
assert.equal(git(f.remote, 'show', '-s', '--format=%P', saved.commit), raced);
assert.equal(git(f.remote, 'show', `${saved.commit}:Inbox Note.md`), 'another');
const g = await world(t), before = g.refs();
g.race(() => g.external(PATH, 'raced target\n'));
await assert.rejects(writeLibraryDoc(g.args(), g.opts), { code: 'stale-base' });
assert.equal(g.refs(), before); assert.equal(git(g.remote, 'show', `main:${PATH}`), 'raced target');
});
test('C2-02: create with null base; human revert restores parent and does not require seat credentials', async t => {
const f = await world(t);
const made = await writeLibraryDoc(f.args({ path: 'Book One/Notes/New.md', base: null, content: 'new\n' }), f.opts);
const options = { credential: { ...f.credential, kind: 'human' }, command: f.command };
const reverted = await revertLibraryCommit({ ...f.context, commit: made.commit }, options);
assert.deepEqual(reverted, { project: 'books', path: 'Book One/Notes/New.md', reverted: made.commit, commit: f.remoteHead() });
assert.equal(git(f.remote, 'ls-tree', '-r', reverted.commit, '--', reverted.path), '');
assert.equal(git(f.remote, 'show', '-s', '--format=%an <%ae>|%cn <%ce>', reverted.commit),
'Human Fixture <[email protected]>|Human Fixture <[email protected]>');
assert.equal(git(f.remote, 'show', '-s', '--format=%(trailers:key=Mosaic-Agent,valueonly)', reverted.commit), '');
});
test('C2-02: revert requires reachable business trailer and refuses a later path change', async t => {
const f = await world(t), options = { credential: { ...f.credential, kind: 'human' }, command: f.command };
await assert.rejects(revertLibraryCommit({ ...f.context, commit: f.commit }, options), { code: 'library-revert-not-agent' });
const saved = await writeLibraryDoc(f.args(), f.opts);
await saveLibraryFile({ ...f.context, path: PATH, base: git(f.mirror, 'rev-parse', `served:${PATH}`), content: 'human later\n' }, options);
await assert.rejects(revertLibraryCommit({ ...f.context, commit: saved.commit }, options), { code: 'stale-base' });
});
test('C2-02: human save reaches story, preserves UTF-8 bytes and uses editor without a trailer', async t => {
const f = await world(t), path = 'Book One/Chapters/Chapter 01.md';
const content = '# Her text\n' + 'é'.repeat(40000) + '\n\n';
const saved = await saveLibraryFile({ ...f.context, path, base: git(f.mirror, 'rev-parse', `served:${path}`), content },
{ credential: { ...f.credential, kind: 'human' }, command: f.command });
assert.equal(git(f.remote, 'show', '-s', '--format=%an <%ae>', saved.commit), 'Human Fixture <[email protected]>');
// git helper trims; compare the stored blob byte count separately.
assert.equal(Number(git(f.remote, 'cat-file', '-s', `${saved.commit}:${path}`)), Buffer.byteLength(content));
});
test('C2-02: invalid content/editor/human credential refuse before any git command', async t => {
const f = await world(t), before = f.refs();
for (const content of ['nul\0', '\ud800', 'x'.repeat(1024 * 1024 + 1)])
await assert.rejects(writeLibraryDoc(f.args({ content }), f.opts), { code: 'invalid-request' });
const args = { ...f.context, path: PATH, base: null, content: 'x' };
writeFileSync(join(f.mirror, 'unexpected'), 'any local git inspection must refuse\n');
delete f.entry.editor;
await assert.rejects(saveLibraryFile(args, { credential: { ...f.credential, kind: 'human' }, command: f.command }), { code: 'library-mapping-invalid' });
await assert.rejects(revertLibraryCommit({ ...f.context, commit: f.commit }, { credential: { ...f.credential, kind: 'human' }, command: f.command }), { code: 'library-mapping-invalid' });
f.entry.editor = EDITOR;
const n = f.commands.length;
await assert.rejects(saveLibraryFile(args, { credential: { kind: 'human', user: 'human', file: '/absent' }, command: f.command }), { code: 'library-human-missing' });
await assert.rejects(revertLibraryCommit({ ...f.context, commit: f.commit }, { credential: { kind: 'human', user: 'human', file: '/absent' }, command: f.command }), { code: 'library-human-missing' });
assert.equal(f.commands.length, n); assert.equal(f.refs(), before);
});
test('C2-02 guard: only the exact owning token permits a push race fetch; sync refuses busy', async t => {
const f = await world(t), commit = f.remoteHead();
f.external('Inbox Note.md', 'remote moved\n');
await withLibraryWriteGuard(f.mirror, async token => {
await assert.rejects(sync(f.context, { credential: f.credential, command: f.command }), { code: 'library-sync-busy' });
for (const writeToken of [null, {}, Object.freeze({})])
await assert.rejects(push(f.context, { commit, credential: f.credential, command: f.command, writeToken }), { code: 'library-sync-busy' });
const raced = await push(f.context, { commit, credential: f.credential, command: f.command, writeToken: token });
assert.equal(raced.raced, true); assert.equal(raced.tip, f.remoteHead());
});
});
test('C2-02 publication F1: failed state rename restores served to match prior state', async t => {
const f = await world(t), previous = await servedCommit(f.mirror);
const commit = git(f.mirror, 'commit-tree', git(f.mirror, 'rev-parse', `${previous}^{tree}`), '-p', previous, '-m', 'candidate');
const statePath = join(f.mirror, SYNC_STATE_FILE), backup = join(f.root, 'state-backup');
await withLibraryLock(f.mirror, async lock => {
// A filesystem failure after the locked state read, before state publication. The original
// state is saved outside the mirror and restored after the failed rename.
const read = async options => {
const state = await lock.readSyncState(options);
renameSync(statePath, backup); mkdirSync(statePath, { mode: 0o700 });
return state;
};
try {
await assert.rejects(publishLibraryWrite(f.mirror, { mapping: checkMapping(f.entry), commit, previous, readSyncState: read }),
{ code: 'outcome-unknown' });
assert.equal(git(f.mirror, 'rev-parse', 'served'), previous);
} finally { rmSync(statePath, { recursive: true, force: true }); renameSync(backup, statePath); }
});
assert.equal((await readSyncState(f.mirror, { branch: 'main' })).served, previous);
});
test('C2-02 E1: a dotted business id never matches another business trailer', async t => {
const f = await world(t, { business: 'acme.co' });
writeFileSync(join(f.repo, PATH), 'foreign seat change\n');
git(f.repo, 'add', '-A'); git(f.repo, 'commit', '-qm', 'Foreign\n\nMosaic-Agent: acme-co/bean');
const foreign = git(f.repo, 'rev-parse', 'HEAD');
git(f.repo, 'push', '-q', f.remote, 'HEAD:main');
await sync(f.context, { credential: f.credential, command: f.command });
const before = f.refs();
await assert.rejects(revertLibraryCommit({ ...f.context, commit: foreign },
{ credential: { ...f.credential, kind: 'human' }, command: f.command }), { code: 'library-revert-not-agent' });
assert.equal(f.refs(), before); assert.equal(f.remoteHead(), foreign);
});
+4 -1
View File
@@ -155,7 +155,8 @@ export function userCaller({ dataRoot, socket, business = null, user, env = proc
// A send's error, sorted. The broker writes in one transaction, so any code it
// returns means nothing was written. A transport that lost the answer, or an
// answer that can't be read, leaves the outcome open: the message may exist.
const OPEN = ['outcome-unknown', 'invalid-response', 'response-too-large'];
// Row 239 (duckworth-0165 C1): so does a write that failed after its revoke.
const OPEN = ['outcome-unknown', 'invalid-response', 'response-too-large', 'outcome-unknown-revoked'];
export function sendOutcome(err) {
const code = err instanceof BusReadError ? err.code : 'outcome-unknown';
return OPEN.includes(code) ? { code: 'outcome-unknown', sent: 'unknown' } : { code, sent: false };
@@ -167,6 +168,8 @@ const STATUS = {
'human-required': 403, 'peercred-required': 403, unauthenticated: 403, 'unknown-business': 403, 'read-only': 403,
'outcome-unknown': 503, 'no-bus-host': 503, 'not-configured': 503,
'revision-conflict':409,'organization-busy':409,'organization-uncertain':503,
// Row 239 (#1745): a fire's or a delete's write refused after its revoke ran.
'revision-conflict-revoked': 409, 'outcome-unknown-revoked': 503,
'invalid-request': 400, 'unknown-role': 400, 'message-not-found': 400, 'request-too-large': 400,
// Row 148: the spec and docs editor. A stale base, a busy or dirty repository and an unchanged
// file are the user's to resolve by reloading; a path or content the project refuses is a 400.
+3 -3
View File
@@ -68,14 +68,14 @@ try {
// the system config, Business can't resolve authority and Settings has
// no notifier. A refusal printed here names no path (redactor).
// --send without a bus refuses to start rather than serve a composer that can't send.
let bus = null, send = null, settingsWrite = null, projectFiles = null, projectFile = null, libraryFile = null, libraryStatus = null, librarySync = null, librarySave = null, projectSave = null, chat = null, nameWrite = null, assistantStop = null, instancesWrite = null, routesWrite = null, agentWrite = null, decisionWrite = null, busLine, system = null;
let bus = null, send = null, settingsWrite = null, projectFiles = null, projectFile = null, libraryFile = null, libraryStatus = null, librarySync = null, projectSave = null, chat = null, nameWrite = null, assistantStop = null, instancesWrite = null, routesWrite = null, agentWrite = null, decisionWrite = null, busLine, system = null;
let processing = null, ownerCall = null;
try {
system = loadSystem();
const { dataRoot } = system;
const call = ownerCall = busCaller({ dataRoot, socket: socketPath(dataRoot), business: options.business ?? null });
// FED R6 (#1800): the bus-backed options, shared with each granted user's session (console-bus.mjs).
({ processing, chat, bus, projectFiles, projectFile, libraryFile, libraryStatus, send, librarySync, librarySave, settingsWrite, projectSave, nameWrite, assistantStop, instancesWrite, routesWrite, agentWrite } = consoleBus(call, { send: sendOn }));
({ processing, chat, bus, projectFiles, projectFile, libraryFile, libraryStatus, send, librarySync, settingsWrite, projectSave, nameWrite, assistantStop, instancesWrite, routesWrite, agentWrite } = consoleBus(call, { send: sendOn }));
// Row 252 (#1753): Approve and Deny on grant requests, through the console wrapper, only with
// --sso and --send.
if (ssoOn && sendOn) decisionWrite = consoleCall({ dataRoot, socket: socketPath(dataRoot), business: options.business ?? null });
@@ -107,7 +107,7 @@ try {
}
let server;
try {
server = await startServer({ board: options.board, port: options.port, bus, reads, preview: options.preview, sso, proof, send, settingsWrite, projectFiles, projectFile, libraryFile, libraryStatus, librarySync, librarySave, projectSave, chat, nameWrite, assistantStop, instancesWrite, routesWrite, agentWrite, processing, decisionWrite, userOptions, federation: system?.federation ?? null });
server = await startServer({ board: options.board, port: options.port, bus, reads, preview: options.preview, sso, proof, send, settingsWrite, projectFiles, projectFile, libraryFile, libraryStatus, librarySync, projectSave, chat, nameWrite, assistantStop, instancesWrite, routesWrite, agentWrite, processing, decisionWrite, userOptions, federation: system?.federation ?? null });
} catch (err) { sso?.close(); throw err; }
let testerServer = null;
if (testerSocket) {
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff. Show more