Skip to content

Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.

feat: require relay order for item moves [E15,H16]

Corey Olsonb64d7e164854
diff --git a/docs/api.md b/docs/api.md
index c5bb7afe..5f96f0b4 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -104,6 +104,7 @@ For example: `flow: review wait average 61 min (1 measured; > 60 min); bottlenec
| `relay` | `version:number`, `linked:boolean`, `board:string`, `url:string`, `link:string`, `sequence:number`, `behind:number`, `recovery:object` |
| `sync` | `version:number`, `ref:string`, `sequence:number`, `pending:string|null` |
| `list` | `version:number`, `items:array` |
+| `move` | `version:number`, `source:string`, `destination:string`, `moveId:string`, `item:object` |
| `queue` | `version:number`, `releases:array`, `unreleased:array`, `first:object` |
| `map` | `version:number`, `main:string`, `map:string` |
| `flow replay` | `version:number`, `history:object`, `replay:object` |
diff --git a/docs/formats.md b/docs/formats.md
index 8b1ad474..a17d82f2 100644
--- a/docs/formats.md
+++ b/docs/formats.md
@@ -106,6 +106,14 @@ Both text and JSON resumes record the displayed version once per checkout. Later
The board file is in the repository's Git common directory at `.git/pullboard/board.sqlite`. File-backed connections use WAL mode, so `board.sqlite-wal` and `board.sqlite-shm` can sit beside it while connections are open. SQLite `PRAGMA user_version` records the board schema version; it also marks whether trigger repairs are reported in the event log. Schema objects are created from `src/board.js` when a board opens.
+## Local board identities and cross-board moves
+
+A repository's team board lives in its Git common directory at `.git/pullboard/board.sqlite`. The device registry records the exact GitHub origin owner/name and immutable board ID; a display name or checkout path is not a board identity. New items go to the team board by default; `pullboard add --private` selects the device-local private board. That private board lives at `~/.pullboard/private/<team-board-id>/board.sqlite` (or under the configured `PULLBOARD_HOME`). Its private reference stores the signed-in person's GitHub login as owner metadata and the repository's origin owner/name as its handle; for example, `~acme/web` identifies the private board for `acme/web`, regardless of the signed-in person's login. The board itself remains device-local unless an item is deliberately moved to a team board (`src/projects.js`).
+
+Item numbers belong to one board. A bare number such as `12` means the current board; a team item can be named `web#12` or `owner/web#12`, and a private item `~web#12` or `~owner/web#12` uses the repository origin owner/name. A bare handle resolves only when unique in the authorized local inventory; ambiguous handles list the qualified choices (`src/board-reference.js`, `src/board-inventory.js`). A dependency on another repository is written `repo#id`; it is satisfied only by that item on its own board after verification, and `pullboard next` names the item it waits for.
+
+`pullboard move <item-ref> --to <handle>` moves an open or verified item between the current repository's team board and its private board; `--private` selects that repository's private board for a bare numeric source ID. An ordered destination reservation chooses the target ID first. The source move then records one stable MOVEID and leaves a permanent redirect at the old source ID, which is never reused; destination application is keyed to the source board and MOVEID, so retrying a failed delivery reuses the same ID and cannot create a second item (`src/commands/move.js`, `src/item-rehome.js`). Move a local parent or wait item first when the destination needs its corresponding item there. A verified import carries the original source ACCEPT, commit, digest and verifier as imported provenance; it is not a new review by the destination board.
+
The version table is generated from the source-owned declarations in `src/formats/*.json` and their existing version constants. Add a declaration beside the format source instead of editing the table; `node bin/update-formats.js` refreshes it, and the native landing train refreshes it after merging.
<!-- format-versions:start -->
diff --git a/docs/img/draw.mjs b/docs/img/draw.mjs
index 49a3b6c4..06eec8d7 100644
--- a/docs/img/draw.mjs
+++ b/docs/img/draw.mjs
@@ -196,6 +196,7 @@ const ROUTES = {
'claimed>verified': { points: [[375, 150], [375, 134], [695, 134], [695, 146]], label: [490, 126, 'middle'] },
'submitted>verified': { points: [[605, 179], [651, 179]], label: [628, 171, 'middle'] },
'open>submitted': { points: [[165, 208], [165, 248], [495, 248], [495, 208]], label: [405, 241, 'middle'] },
+ 'open>verified': { points: [[185, 198], [205, 198], [205, 268], [735, 268], [735, 212]], label: [650, 261, 'middle'] },
'claimed>open': { points: [[335, 150], [335, 120], [145, 120], [145, 146]], back: true, label: [240, 94, 'middle'], wrap: 2 },
'submitted>open': { points: [[545, 150], [545, 66], [115, 66], [115, 146]], back: true, label: [330, 58, 'middle'] },
'verified>open': { points: [[815, 179], [830, 179], [830, 8], [15, 8], [15, 179], [25, 179]], back: true, label: [425, 30, 'middle'] },
diff --git a/docs/img/lifecycle-dark.svg b/docs/img/lifecycle-dark.svg
index e05d521d..6e15ee4b 100644
--- a/docs/img/lifecycle-dark.svg
+++ b/docs/img/lifecycle-dark.svg
@@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 840 392" width="840" height="392" role="img" aria-labelledby="title desc">
-<title id="title">An item's life</title><desc id="desc">Drawn from src/machine.js. An item starts open and ends withdrawn. open to submitted: intake. open to claimed: claim. claimed to open: release, lapse (clock), escalate, refreeze. claimed to submitted: submit. claimed to verified: submit-merge. submitted to verified: accept. submitted to open: reject, reopen, refreeze. verified to open: reject, reopen. open to withdrawn: withdraw. claimed to withdrawn: withdraw. submitted to withdrawn: withdraw.</desc>
+<title id="title">An item's life</title><desc id="desc">Drawn from src/machine.js. An item starts open and ends withdrawn. open to verified: rehomeImport. open to submitted: intake. open to claimed: claim. claimed to open: release, lapse (clock), escalate, refreeze. claimed to submitted: submit. claimed to verified: submit-merge. submitted to verified: accept. submitted to open: reject, reopen, refreeze. verified to open: reject, reopen. open to withdrawn: withdraw. claimed to withdrawn: withdraw. submitted to withdrawn: withdraw.</desc>
<style>
text { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Noto Sans', Helvetica, Arial, sans-serif; fill: #1f2328; }
.mono { font-family: ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, 'Liberation Mono', monospace; }
@@ -58,6 +58,8 @@ text { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Noto Sans',
<g class="plain"><rect x="445" y="150" width="160" height="58" rx="8"/><text class="t1" x="525" y="175" text-anchor="middle">submitted</text><text class="t2" x="525" y="193" text-anchor="middle">↻ reserve</text></g>
<g class="done"><rect x="655" y="150" width="160" height="58" rx="8"/><text class="t1" x="735" y="175" text-anchor="middle">verified</text><text class="t2" x="735" y="193" text-anchor="middle">↻ accept</text></g>
<g class="plain" data-final="withdrawn"><rect x="445" y="284" width="160" height="58" rx="8"/><rect x="449" y="288" width="152" height="50" rx="5" fill="none"/><text class="t1" x="525" y="318" text-anchor="middle">withdrawn</text></g>
+<path class="edge" d="M 185 198 L 205 198 L 205 268 L 735 268 L 735 212" marker-end="url(#tip)"/>
+<text class="label" x="650" y="261" text-anchor="middle">rehomeImport</text>
<path class="edge" d="M 165 208 L 165 248 L 495 248 L 495 208" marker-end="url(#tip)"/>
<text class="label" x="405" y="241" text-anchor="middle">intake</text>
<path class="edge" d="M 185 179 L 231 179" marker-end="url(#tip)"/>
diff --git a/docs/img/lifecycle.svg b/docs/img/lifecycle.svg
index 2dd6e190..9b3d0854 100644
--- a/docs/img/lifecycle.svg
+++ b/docs/img/lifecycle.svg
@@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 840 392" width="840" height="392" role="img" aria-labelledby="title desc">
-<title id="title">An item's life</title><desc id="desc">Drawn from src/machine.js. An item starts open and ends withdrawn. open to submitted: intake. open to claimed: claim. claimed to open: release, lapse (clock), escalate, refreeze. claimed to submitted: submit. claimed to verified: submit-merge. submitted to verified: accept. submitted to open: reject, reopen, refreeze. verified to open: reject, reopen. open to withdrawn: withdraw. claimed to withdrawn: withdraw. submitted to withdrawn: withdraw.</desc>
+<title id="title">An item's life</title><desc id="desc">Drawn from src/machine.js. An item starts open and ends withdrawn. open to verified: rehomeImport. open to submitted: intake. open to claimed: claim. claimed to open: release, lapse (clock), escalate, refreeze. claimed to submitted: submit. claimed to verified: submit-merge. submitted to verified: accept. submitted to open: reject, reopen, refreeze. verified to open: reject, reopen. open to withdrawn: withdraw. claimed to withdrawn: withdraw. submitted to withdrawn: withdraw.</desc>
<style>
text { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Noto Sans', Helvetica, Arial, sans-serif; fill: #1f2328; }
.mono { font-family: ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, 'Liberation Mono', monospace; }
@@ -40,6 +40,8 @@ text { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Noto Sans',
<g class="plain"><rect x="445" y="150" width="160" height="58" rx="8"/><text class="t1" x="525" y="175" text-anchor="middle">submitted</text><text class="t2" x="525" y="193" text-anchor="middle">↻ reserve</text></g>
<g class="done"><rect x="655" y="150" width="160" height="58" rx="8"/><text class="t1" x="735" y="175" text-anchor="middle">verified</text><text class="t2" x="735" y="193" text-anchor="middle">↻ accept</text></g>
<g class="plain" data-final="withdrawn"><rect x="445" y="284" width="160" height="58" rx="8"/><rect x="449" y="288" width="152" height="50" rx="5" fill="none"/><text class="t1" x="525" y="318" text-anchor="middle">withdrawn</text></g>
+<path class="edge" d="M 185 198 L 205 198 L 205 268 L 735 268 L 735 212" marker-end="url(#tip)"/>
+<text class="label" x="650" y="261" text-anchor="middle">rehomeImport</text>
<path class="edge" d="M 165 208 L 165 248 L 495 248 L 495 208" marker-end="url(#tip)"/>
<text class="label" x="405" y="241" text-anchor="middle">intake</text>
<path class="edge" d="M 185 179 L 231 179" marker-end="url(#tip)"/>
diff --git a/docs/lifecycle.md b/docs/lifecycle.md
index 22ee1da2..3b206d3d 100644
--- a/docs/lifecycle.md
+++ b/docs/lifecycle.md
@@ -13,6 +13,7 @@ Private commands drain their output through pipes, retaining a bounded 8 MiB cap
```mermaid
stateDiagram-v2
[*] --> open
+ open --> verified: rehomeImport
open --> submitted: intake
open --> claimed: claim
claimed --> claimed: claim
@@ -47,7 +48,7 @@ stateDiagram-v2
| open | waiting for a builder; claimable once what it waits on is verified | none |
| claimed | an agent holds it under a lease, its criterion frozen | item_owner, item_lease_until, item_frozen_digest |
| submitted | a native build gated green, or an intaken outside commit awaiting sandbox verification, at a pinned commit | item_built_by, item_commit, item_frozen_digest |
-| verified | another agent accepted the frozen work at this commit or its canonically recorded trunk-only merge | item_verified_by, item_commit |
+| verified | another agent accepted it at the submitted commit, its canonically recorded trunk-only merge, or the item carries an attributed source-board acceptance | item_verified_by, item_commit |
| withdrawn (final) | nobody should build it; the reason stays on it | item_withdrawn_reason |
## Moves
@@ -56,20 +57,21 @@ Each move checks its guards in this order and refuses with the first one that do
| Move | From | To | Who | Guards, in order; result refusals |
| --- | --- | --- | --- | --- |
-| intake | open | submitted | agent, coordinator | joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_CLAIMABLE), outsideSubmission (OUTSIDE_SOURCE) |
-| claim | open, claimed | claimed | agent, coordinator | joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_CLAIMABLE), checkProvesSomething (CRITERION_PROVES_NOTHING), barReady (BAR_NOT_READY), itemNotHeld (ITEM_HELD), inLane (WRONG_LANE or OUTSIDE_NATIVE_BUILD), routeAllows (ROUTE), dependenciesVerified (BLOCKED), notHeldByAnother (HELD), builderFirstRefusal (REOPEN_HELD_FOR_BUILDER), correctionRefrozen (PENDING_REFREEZE), laneOpen (LANE_HELD), lineCapacity (LINE_WIP_LIMIT or LINE_SETTING_RANGE), oneLiveClaim (ONE_CLAIM), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION or NO_POLICY or BAD_CONFIG or SPEC_BEHIND_MAIN or AGENT_APPROVAL_REQUIRED or BAR_NOT_READY), result (BAD_DEPENDENCIES) |
-| release | open, claimed | open | agent, coordinator | joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_YOURS), releaseOwnsWork (NOT_YOURS), reviewReleaseExplained (NOTE_REQUIRED) |
+| rehomeImport | open | verified | agent | joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), itemExists (NO_ITEM or ITEM_MOVED), inState (REHOME_VERDICT), sourceAcceptance (REHOME_VERDICT), atSubmittedCommit (NOT_AT_COMMIT or OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), notBuilder (SELF_VERIFY or VERIFIER_STANDING or SELF_SESSION_VERIFY), criterionUnchanged (CRITERIA_CHANGED), proofNoted (PROOF_REQUIRED) |
+| intake | open | submitted | agent, coordinator | joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), itemExists (NO_ITEM or ITEM_MOVED), inState (NOT_CLAIMABLE), outsideSubmission (OUTSIDE_SOURCE) |
+| claim | open, claimed | claimed | agent, coordinator | joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), itemExists (NO_ITEM or ITEM_MOVED), inState (NOT_CLAIMABLE), checkProvesSomething (CRITERION_PROVES_NOTHING), barReady (BAR_NOT_READY), itemNotHeld (ITEM_HELD), inLane (WRONG_LANE or OUTSIDE_NATIVE_BUILD), routeAllows (ROUTE), dependenciesVerified (BLOCKED), notHeldByAnother (HELD), builderFirstRefusal (REOPEN_HELD_FOR_BUILDER), correctionRefrozen (PENDING_REFREEZE), laneOpen (LANE_HELD), lineCapacity (LINE_WIP_LIMIT or LINE_SETTING_RANGE), oneLiveClaim (ONE_CLAIM), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION or NO_POLICY or BAD_CONFIG or SPEC_BEHIND_MAIN or AGENT_APPROVAL_REQUIRED or BAR_NOT_READY), result (BAD_DEPENDENCIES) |
+| release | open, claimed | open | agent, coordinator | joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), itemExists (NO_ITEM or ITEM_MOVED), inState (NOT_YOURS), releaseOwnsWork (NOT_YOURS), reviewReleaseExplained (NOTE_REQUIRED) |
| lapse | claimed | open | clock, when its lease runs out | none |
-| submit | claimed | submitted | agent, coordinator | joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_YOURS), isHolder (NOT_YOURS or OUTSIDE_NATIVE_BUILD), correctionRefrozen (PENDING_REFREEZE), checkProvesSomething (CRITERION_PROVES_NOTHING), barReady (BAR_NOT_READY), criterionUnchanged (CRITERIA_CHANGED), treeClean (DIRTY), nothingUntracked (UNTRACKED), hasCommit (NO_COMMIT or HOST_NAME), withinLane (OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), trunkInCandidate (MAIN_NOT_COMPOSED), noUnverifiedStack (STACKED_ON_UNVERIFIED), infraExplained (INFRA_NOTE_REQUIRED), doctrineHolds (RATCHET_ROSE or RATCHET_UNCOUNTED), gateConfigured (NO_GATE), queuedItemLease (ITEM_LEASE_LOST or A5_GRAMMAR_VERSION or SPEC_BEHIND_MAIN or NOT_A_REPO or NO_CONFIG), gateGreen (GATE_RED or RUNNER_WAIT_DEADLINE or RUNNER_GUI_SESSION_REQUIRED or LAND_TIMEOUT_CUSTODY or LAND_GATE_OUTPUT or SLOT_DB_LOCKED or TIMING_SLOT_REQUIRED or RUNNER_BROWSER_SLOT_REQUIRED or PIPEFAIL_UNAVAILABLE), proofRecorded (PROOF_RUN_UNAVAILABLE or PROOF_RUN_UNBOUND or PROOF_RUN_ACTOR or PROOF_RUN_STALE or PROOF_RUN_CHANGED), treeStillDuringGate (MOVED_DURING_GATE), submissionProofValid (SUBMISSION_PROOF), childrenDone (CHILDREN_OPEN), headIsNew (HEAD_NOT_NEW), result (BAD_DEPENDENCIES), result (AGENT_GRANT_EXPIRED), result (AGENT_GRANT_ITEM), result (AGENT_GRANT_LANE), result (LINE_SETTING_RANGE), result (MERGE_ONLY_PROOF), result (SELF_VERIFY), result (SELF_SESSION_VERIFY), result (PROOF_REQUIRED) |
-| submit-merge | claimed | verified | agent, coordinator, when only an unchanged accepted bar and a proved trunk-only merge; no new reviewer verdict is created | joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_YOURS), isHolder (NOT_YOURS or OUTSIDE_NATIVE_BUILD), correctionRefrozen (PENDING_REFREEZE), checkProvesSomething (CRITERION_PROVES_NOTHING), barReady (BAR_NOT_READY), criterionUnchanged (CRITERIA_CHANGED), treeClean (DIRTY), nothingUntracked (UNTRACKED), hasCommit (NO_COMMIT or HOST_NAME), withinLane (OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), trunkInCandidate (MAIN_NOT_COMPOSED), noUnverifiedStack (STACKED_ON_UNVERIFIED), infraExplained (INFRA_NOTE_REQUIRED), doctrineHolds (RATCHET_ROSE or RATCHET_UNCOUNTED), gateConfigured (NO_GATE), queuedItemLease (ITEM_LEASE_LOST or A5_GRAMMAR_VERSION or SPEC_BEHIND_MAIN or NOT_A_REPO or NO_CONFIG), gateGreen (GATE_RED or RUNNER_WAIT_DEADLINE or RUNNER_GUI_SESSION_REQUIRED or LAND_TIMEOUT_CUSTODY or LAND_GATE_OUTPUT or SLOT_DB_LOCKED or TIMING_SLOT_REQUIRED or RUNNER_BROWSER_SLOT_REQUIRED or PIPEFAIL_UNAVAILABLE), proofRecorded (PROOF_RUN_UNAVAILABLE or PROOF_RUN_UNBOUND or PROOF_RUN_ACTOR or PROOF_RUN_STALE or PROOF_RUN_CHANGED), treeStillDuringGate (MOVED_DURING_GATE), submissionProofValid (SUBMISSION_PROOF), childrenDone (CHILDREN_OPEN), headIsNew (HEAD_NOT_NEW), mergeOnlyRecorded (MERGE_ONLY_PROOF), atSubmittedCommit (NOT_AT_COMMIT or OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), notBuilder (SELF_VERIFY or VERIFIER_STANDING or SELF_SESSION_VERIFY), proofNoted (PROOF_REQUIRED), result (BAD_DEPENDENCIES), result (AGENT_GRANT_EXPIRED), result (AGENT_GRANT_ITEM), result (AGENT_GRANT_LANE) |
-| reserve | submitted | submitted | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), roadmapReadable (MILESTONES_CORRUPT or LINE_SETTING_RANGE), itemExists (NO_ITEM), inState (NOT_SUBMITTED), reviewCooldownElapsed (REVIEW_COOLDOWN), notBuilder (SELF_VERIFY or VERIFIER_STANDING or SELF_SESSION_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), result (BAD_DEPENDENCIES) |
-| accept | submitted, verified | verified | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_SUBMITTED), atSubmittedCommit (NOT_AT_COMMIT or OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), notMerged (ALREADY_MERGED), verdictReviewRecorded (BAD_VERDICT_REVIEW), reviewTreeCurrent (STALE_VERDICT or DIRTY or UNTRACKED or VERDICT_TRUNK_MOVED), notBuilder (SELF_VERIFY or VERIFIER_STANDING or SELF_SESSION_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), criterionUnchanged (CRITERIA_CHANGED), reasonIsMet (BAD_REASON), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), noUnverifiedStack (STACKED_ON_UNVERIFIED), queuedItemLease (ITEM_LEASE_LOST or A5_GRAMMAR_VERSION or SPEC_BEHIND_MAIN or NOT_A_REPO or NO_CONFIG), itemCheckGreen (CHECK_RED or RUNNER_WAIT_DEADLINE or RUNNER_BROWSER_SLOT_REQUIRED or RUNNER_GUI_SESSION_REQUIRED or SANDBOX_PROVIDER_REQUIRED or SANDBOX_IMAGE_REQUIRED or SANDBOX_RUNTIME or SANDBOX_EXPORT or SANDBOX_EXECUTION or SANDBOX_CLEANUP_REQUIRED or SANDBOX_CHECK_REQUIRED or CHECK_NO_PROOF or OUTSIDE_SANDBOX_REQUIRED or SLOT_DB_LOCKED or TIMING_SLOT_REQUIRED or CHECK_UNVERIFIED or GUARD_CANNOT_FAIL or GUARD_NOT_FOUND), proofRecorded (PROOF_RUN_UNAVAILABLE or PROOF_RUN_UNBOUND or PROOF_RUN_ACTOR or PROOF_RUN_STALE or PROOF_RUN_CHANGED), proofNoted (PROOF_REQUIRED), result (BAD_DEPENDENCIES), result (AGENT_GRANT_EXPIRED), result (AGENT_GRANT_ITEM), result (AGENT_GRANT_LANE), result (VERDICT_ENVIRONMENT), result (LAND_HEADER), result (ENGINE_VERSION) |
-| reject | submitted, verified | open | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_SUBMITTED), atSubmittedCommit (NOT_AT_COMMIT or OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), notMerged (ALREADY_MERGED), verdictReviewRecorded (BAD_VERDICT_REVIEW), reviewTreeCurrent (STALE_VERDICT or DIRTY or UNTRACKED or VERDICT_TRUNK_MOVED), notBuilder (SELF_VERIFY or VERIFIER_STANDING or SELF_SESSION_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), criterionUnchanged (CRITERIA_CHANGED), reasonCoded (BAD_REASON), noteGiven (NOTE_REQUIRED), causeWellFormed (BAD_CAUSE), result (BAD_DEPENDENCIES), result (AGENT_GRANT_EXPIRED), result (AGENT_GRANT_ITEM), result (AGENT_GRANT_LANE), result (VERDICT_ENVIRONMENT), result (LAND_HEADER), result (ENGINE_VERSION), result (NOT_YOURS), result (CLOSED) |
-| reopen | submitted, verified | open | agent, coordinator | joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_SUBMITTED), reopenAuthority (COORDINATOR_ONLY or NO_POLICY or GIT_GRAFTS or GIT_REPLACE_REFS or VERDICT_WITHDRAW_FORBIDDEN or VERDICT_WITHDRAW_STATE), noteGiven (NOTE_REQUIRED), causeWellFormed (BAD_CAUSE), notMerged (ALREADY_MERGED), landingFailureRecorded (LANDING_FAILURE_REQUIRED), trunkConflicts (NOT_CONFLICTING or CONFLICT_FILES or NO_TRUNK or MERGE_CHECK_FAILED), conflictAccepted (NOT_ACCEPTED or BAD_CONFLICT or ENGINE_VERSION), result (BAD_VERDICT_WITHDRAW), result (ENGINE_VERSION), result (BAD_CONFIG) |
-| escalate | open, claimed | open | agent, coordinator | joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), noteGiven (NOTE_REQUIRED), itemExists (NO_ITEM), holderOrCoordinator (NOT_YOURS), inState (CLOSED) |
-| refreeze | open, claimed, submitted | open | coordinator, when there is no live claim awaiting a coordinator correction | joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), coordinatorOnly (COORDINATOR_ONLY), itemExists (NO_ITEM), inState (CLOSED), barReady (BAR_NOT_READY), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION or NO_POLICY or BAD_CONFIG or SPEC_BEHIND_MAIN or AGENT_APPROVAL_REQUIRED or BAR_NOT_READY) |
-| refreeze | claimed | claimed | agent, coordinator, when a live claim has a pending coordinator correction | joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), itemExists (NO_ITEM), holderOrCoordinator (NOT_YOURS), inState (CLOSED), barReady (BAR_NOT_READY), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION or NO_POLICY or BAD_CONFIG or SPEC_BEHIND_MAIN or AGENT_APPROVAL_REQUIRED or BAR_NOT_READY) |
-| withdraw | open, claimed, submitted | withdrawn | coordinator | joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), coordinatorOnly (COORDINATOR_ONLY), noteGiven (NOTE_REQUIRED), itemExists (NO_ITEM), inState (CLOSED) |
+| submit | claimed | submitted | agent, coordinator | joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), itemExists (NO_ITEM or ITEM_MOVED), inState (NOT_YOURS), isHolder (NOT_YOURS or OUTSIDE_NATIVE_BUILD), correctionRefrozen (PENDING_REFREEZE), checkProvesSomething (CRITERION_PROVES_NOTHING), barReady (BAR_NOT_READY), criterionUnchanged (CRITERIA_CHANGED), treeClean (DIRTY), nothingUntracked (UNTRACKED), hasCommit (NO_COMMIT or HOST_NAME), withinLane (OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), trunkInCandidate (MAIN_NOT_COMPOSED), noUnverifiedStack (STACKED_ON_UNVERIFIED), infraExplained (INFRA_NOTE_REQUIRED), doctrineHolds (RATCHET_ROSE or RATCHET_UNCOUNTED), gateConfigured (NO_GATE), queuedItemLease (ITEM_LEASE_LOST or A5_GRAMMAR_VERSION or SPEC_BEHIND_MAIN or NOT_A_REPO or NO_CONFIG), gateGreen (GATE_RED or RUNNER_WAIT_DEADLINE or RUNNER_GUI_SESSION_REQUIRED or LAND_TIMEOUT_CUSTODY or LAND_GATE_OUTPUT or SLOT_DB_LOCKED or TIMING_SLOT_REQUIRED or RUNNER_BROWSER_SLOT_REQUIRED or PIPEFAIL_UNAVAILABLE), proofRecorded (PROOF_RUN_UNAVAILABLE or PROOF_RUN_UNBOUND or PROOF_RUN_ACTOR or PROOF_RUN_STALE or PROOF_RUN_CHANGED), treeStillDuringGate (MOVED_DURING_GATE), submissionProofValid (SUBMISSION_PROOF), childrenDone (CHILDREN_OPEN), headIsNew (HEAD_NOT_NEW), result (BAD_DEPENDENCIES), result (AGENT_GRANT_EXPIRED), result (AGENT_GRANT_ITEM), result (AGENT_GRANT_LANE), result (LINE_SETTING_RANGE), result (MERGE_ONLY_PROOF), result (SELF_VERIFY), result (SELF_SESSION_VERIFY), result (PROOF_REQUIRED) |
+| submit-merge | claimed | verified | agent, coordinator, when only an unchanged accepted bar and a proved trunk-only merge; no new reviewer verdict is created | joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), itemExists (NO_ITEM or ITEM_MOVED), inState (NOT_YOURS), isHolder (NOT_YOURS or OUTSIDE_NATIVE_BUILD), correctionRefrozen (PENDING_REFREEZE), checkProvesSomething (CRITERION_PROVES_NOTHING), barReady (BAR_NOT_READY), criterionUnchanged (CRITERIA_CHANGED), treeClean (DIRTY), nothingUntracked (UNTRACKED), hasCommit (NO_COMMIT or HOST_NAME), withinLane (OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), trunkInCandidate (MAIN_NOT_COMPOSED), noUnverifiedStack (STACKED_ON_UNVERIFIED), infraExplained (INFRA_NOTE_REQUIRED), doctrineHolds (RATCHET_ROSE or RATCHET_UNCOUNTED), gateConfigured (NO_GATE), queuedItemLease (ITEM_LEASE_LOST or A5_GRAMMAR_VERSION or SPEC_BEHIND_MAIN or NOT_A_REPO or NO_CONFIG), gateGreen (GATE_RED or RUNNER_WAIT_DEADLINE or RUNNER_GUI_SESSION_REQUIRED or LAND_TIMEOUT_CUSTODY or LAND_GATE_OUTPUT or SLOT_DB_LOCKED or TIMING_SLOT_REQUIRED or RUNNER_BROWSER_SLOT_REQUIRED or PIPEFAIL_UNAVAILABLE), proofRecorded (PROOF_RUN_UNAVAILABLE or PROOF_RUN_UNBOUND or PROOF_RUN_ACTOR or PROOF_RUN_STALE or PROOF_RUN_CHANGED), treeStillDuringGate (MOVED_DURING_GATE), submissionProofValid (SUBMISSION_PROOF), childrenDone (CHILDREN_OPEN), headIsNew (HEAD_NOT_NEW), mergeOnlyRecorded (MERGE_ONLY_PROOF), atSubmittedCommit (NOT_AT_COMMIT or OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), notBuilder (SELF_VERIFY or VERIFIER_STANDING or SELF_SESSION_VERIFY), proofNoted (PROOF_REQUIRED), result (BAD_DEPENDENCIES), result (AGENT_GRANT_EXPIRED), result (AGENT_GRANT_ITEM), result (AGENT_GRANT_LANE) |
+| reserve | submitted | submitted | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), roadmapReadable (MILESTONES_CORRUPT or LINE_SETTING_RANGE), itemExists (NO_ITEM or ITEM_MOVED), inState (NOT_SUBMITTED), reviewCooldownElapsed (REVIEW_COOLDOWN), notBuilder (SELF_VERIFY or VERIFIER_STANDING or SELF_SESSION_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), result (BAD_DEPENDENCIES) |
+| accept | submitted, verified | verified | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), itemExists (NO_ITEM or ITEM_MOVED), inState (NOT_SUBMITTED), atSubmittedCommit (NOT_AT_COMMIT or OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), notMerged (ALREADY_MERGED), verdictReviewRecorded (BAD_VERDICT_REVIEW), reviewTreeCurrent (STALE_VERDICT or DIRTY or UNTRACKED or VERDICT_TRUNK_MOVED), notBuilder (SELF_VERIFY or VERIFIER_STANDING or SELF_SESSION_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), criterionUnchanged (CRITERIA_CHANGED), reasonIsMet (BAD_REASON), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), noUnverifiedStack (STACKED_ON_UNVERIFIED), queuedItemLease (ITEM_LEASE_LOST or A5_GRAMMAR_VERSION or SPEC_BEHIND_MAIN or NOT_A_REPO or NO_CONFIG), itemCheckGreen (CHECK_RED or RUNNER_WAIT_DEADLINE or RUNNER_BROWSER_SLOT_REQUIRED or RUNNER_GUI_SESSION_REQUIRED or SANDBOX_PROVIDER_REQUIRED or SANDBOX_IMAGE_REQUIRED or SANDBOX_RUNTIME or SANDBOX_EXPORT or SANDBOX_EXECUTION or SANDBOX_CLEANUP_REQUIRED or SANDBOX_CHECK_REQUIRED or CHECK_NO_PROOF or OUTSIDE_SANDBOX_REQUIRED or SLOT_DB_LOCKED or TIMING_SLOT_REQUIRED or CHECK_UNVERIFIED or GUARD_CANNOT_FAIL or GUARD_NOT_FOUND), proofRecorded (PROOF_RUN_UNAVAILABLE or PROOF_RUN_UNBOUND or PROOF_RUN_ACTOR or PROOF_RUN_STALE or PROOF_RUN_CHANGED), proofNoted (PROOF_REQUIRED), result (BAD_DEPENDENCIES), result (AGENT_GRANT_EXPIRED), result (AGENT_GRANT_ITEM), result (AGENT_GRANT_LANE), result (VERDICT_ENVIRONMENT), result (LAND_HEADER), result (ENGINE_VERSION) |
+| reject | submitted, verified | open | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), itemExists (NO_ITEM or ITEM_MOVED), inState (NOT_SUBMITTED), atSubmittedCommit (NOT_AT_COMMIT or OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), notMerged (ALREADY_MERGED), verdictReviewRecorded (BAD_VERDICT_REVIEW), reviewTreeCurrent (STALE_VERDICT or DIRTY or UNTRACKED or VERDICT_TRUNK_MOVED), notBuilder (SELF_VERIFY or VERIFIER_STANDING or SELF_SESSION_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), criterionUnchanged (CRITERIA_CHANGED), reasonCoded (BAD_REASON), noteGiven (NOTE_REQUIRED), causeWellFormed (BAD_CAUSE), result (BAD_DEPENDENCIES), result (AGENT_GRANT_EXPIRED), result (AGENT_GRANT_ITEM), result (AGENT_GRANT_LANE), result (VERDICT_ENVIRONMENT), result (LAND_HEADER), result (ENGINE_VERSION), result (NOT_YOURS), result (CLOSED) |
+| reopen | submitted, verified | open | agent, coordinator | joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), itemExists (NO_ITEM or ITEM_MOVED), inState (NOT_SUBMITTED), reopenAuthority (COORDINATOR_ONLY or NO_POLICY or GIT_GRAFTS or GIT_REPLACE_REFS or VERDICT_WITHDRAW_FORBIDDEN or VERDICT_WITHDRAW_STATE), noteGiven (NOTE_REQUIRED), causeWellFormed (BAD_CAUSE), notMerged (ALREADY_MERGED), landingFailureRecorded (LANDING_FAILURE_REQUIRED), trunkConflicts (NOT_CONFLICTING or CONFLICT_FILES or NO_TRUNK or MERGE_CHECK_FAILED), conflictAccepted (NOT_ACCEPTED or BAD_CONFLICT or ENGINE_VERSION), result (BAD_VERDICT_WITHDRAW), result (ENGINE_VERSION), result (BAD_CONFIG) |
+| escalate | open, claimed | open | agent, coordinator | joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), noteGiven (NOTE_REQUIRED), itemExists (NO_ITEM or ITEM_MOVED), holderOrCoordinator (NOT_YOURS), inState (CLOSED) |
+| refreeze | open, claimed, submitted | open | coordinator, when there is no live claim awaiting a coordinator correction | joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), coordinatorOnly (COORDINATOR_ONLY), itemExists (NO_ITEM or ITEM_MOVED), inState (CLOSED), barReady (BAR_NOT_READY), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION or NO_POLICY or BAD_CONFIG or SPEC_BEHIND_MAIN or AGENT_APPROVAL_REQUIRED or BAR_NOT_READY) |
+| refreeze | claimed | claimed | agent, coordinator, when a live claim has a pending coordinator correction | joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), itemExists (NO_ITEM or ITEM_MOVED), holderOrCoordinator (NOT_YOURS), inState (CLOSED), barReady (BAR_NOT_READY), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION or NO_POLICY or BAD_CONFIG or SPEC_BEHIND_MAIN or AGENT_APPROVAL_REQUIRED or BAR_NOT_READY) |
+| withdraw | open, claimed, submitted | withdrawn | coordinator | joined (NOT_JOINED or AGENT_REPLACED or SESSION_LEDGER), coordinatorOnly (COORDINATOR_ONLY), noteGiven (NOTE_REQUIRED), itemExists (NO_ITEM or ITEM_MOVED), inState (CLOSED) |
## Required transition guards
@@ -82,6 +84,7 @@ Each move checks its guards in this order and refuses with the first one that do
| Code | Raised when this does not hold | Next step |
| --- | --- | --- |
+| REHOME_VERDICT | rehomeImport: the item is in open | pullboard show <id> |
| NOT_CLAIMABLE | intake: the item is in open | pullboard show <id> |
| NOT_CLAIMABLE | claim: the item is in open, claimed | pullboard show <id> |
| NOT_YOURS | release: the item is in open, claimed | pullboard show <id> |
@@ -95,12 +98,14 @@ Each move checks its guards in this order and refuses with the first one that do
| CLOSED | refreeze: the item is in open, claimed, submitted | pullboard show <id> |
| CLOSED | refreeze: the item is in claimed | pullboard show <id> |
| CLOSED | withdraw: the item is in open, claimed, submitted | pullboard show <id> |
+| REHOME_VERDICT | the authenticated destination mover attests to an exact source board ACCEPT reference keyed by the ordered source MOVEID and result digest | preserve the imported source acceptance attribution, frozen digest, commit and verifier reference |
| MERGE_ONLY_PROOF | the sealed submit records the origin’s Git-derived carry, unchanged bar and original verifier; landing re-proves its heads, trees and resolution hash before merging | submit normally for outside review if the origin cannot prove the merge |
| OUTSIDE_SOURCE | an outside author and exact fetched commit/tree are recorded with a trusted frozen criterion, without pretending a native builder gated it | fetch and intake the exact GitHub pull request again |
| NOT_JOINED | the caller is the main checkout, or an unreplaced worktree seat that joined a lane; an agent session's claims, submits and verdicts can be checked against its local ledger | pullboard join <lane> --model "<model name>" (see: pullboard lanes) |
| AGENT_REPLACED | the caller is the main checkout, or an unreplaced worktree seat that joined a lane; an agent session's claims, submits and verdicts can be checked against its local ledger | read the takeover and only shout on its exact hand-off item; continue work from the incoming agent worktree |
| SESSION_LEDGER | the caller is the main checkout, or an unreplaced worktree seat that joined a lane; an agent session's claims, submits and verdicts can be checked against its local ledger | make the agent-session ledger named in the message readable and writable by this user, then run the command again |
-| NO_ITEM | the item exists | pullboard list --all |
+| NO_ITEM | the item exists and has not been moved | pullboard list --all |
+| ITEM_MOVED | the item exists and has not been moved | use the recorded destination reference shown in the refusal; do not move the old ID again |
| COORDINATOR_ONLY | the coordinator reopens, the native board computes an automatic submitted-head conflict, or the exact accepting reviewer withdraws its verdict; older recorded submitted-conflict moves keep their joined-seat authority | ask the coordinator or the reviewer who recorded the accept |
| NO_POLICY | the coordinator reopens, the native board computes an automatic submitted-head conflict, or the exact accepting reviewer withdraws its verdict; older recorded submitted-conflict moves keep their joined-seat authority | restore the local Git configuration so the current trunk can be read, then compute a fresh automatic return |
| GIT_GRAFTS | the coordinator reopens, the native board computes an automatic submitted-head conflict, or the exact accepting reviewer withdraws its verdict; older recorded submitted-conflict moves keep their joined-seat authority | ask the coordinator to remove the replica graft file, then resume the same move |
diff --git a/src/agent-grant.js b/src/agent-grant.js
index 03f3903c..73d388c4 100644
--- a/src/agent-grant.js
+++ b/src/agent-grant.js
@@ -10,6 +10,8 @@ const ADMINISTRATIVE = new Set(['shout', 'claim', 'release', 'reserveReview', 'a
/** Bind only item mutations declared by the public operation, including item creation. */
function target(move) {
if (move.operation === 'addItem') return { lane: move.args?.[0]?.lane, creating: true };
+ if (move.operation === 'applyRehomeItem') return { item: move.args?.[0]?.destinationItemId,
+ lane: move.args?.[0]?.item?.item_lane, creating: true };
if (MOVE_REGISTRY[move.operation]?.itemIdFirstArgument) return { item: move.args?.[0] };
return null;
}
diff --git a/src/board-inventory.js b/src/board-inventory.js
new file mode 100644
index 00000000..954bb839
--- /dev/null
+++ b/src/board-inventory.js
@@ -0,0 +1,76 @@
+/** Authorized device-local team and private BoardRefs for cross-board commands [E14,E15,H16]. */
+import * as store from './board.js';
+import { listProjects } from './projects.js';
+import { withPrivateBoard } from './projects.js';
+import { Refused } from './refused.js';
+import { boardReference } from './board-reference.js';
+
+/** Read a private board's exact durable reference without creating storage or inferring its owner. */
+async function privateReference(project) {
+ if (!project.boardId) return null;
+ try {
+ return await withPrivateBoard(project.boardId, board => {
+ const row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get('private_board_reference');
+ if (!row) return null;
+ const value = JSON.parse(row.meta_value);
+ if (value.version !== 1 || value.kind !== 'private' || value.repoBoardId !== project.boardId
+ || typeof value.owner !== 'string' || !/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/u.test(value.owner)
+ || typeof value.organization !== 'string' || typeof value.handle !== 'string') return null;
+ return { ...boardReference({ boardId: store.boardId(board), organization: value.organization, handle: value.handle }),
+ kind: 'private', root: project.root, repoBoardId: project.boardId };
+ }, { create: false });
+ } catch { return null; }
+}
+
+/** Load only registry-recorded team identities and private references from existing private files. */
+export async function localBoardInventory() {
+ const projects = listProjects();
+ const rows = new Map();
+ for (const project of projects) {
+ if (project.boardId && project.owner && project.handle) {
+ try {
+ const reference = boardReference({ boardId: project.boardId, organization: project.owner, handle: project.handle });
+ rows.set(`${reference.boardId}:team`, { ...reference, kind: 'team', root: project.root });
+ } catch { /* An invalid local record cannot authorize a board reference. */ }
+ }
+ const privateBoard = await privateReference(project);
+ if (privateBoard) rows.set(`${privateBoard.boardId}:private`, privateBoard);
+ }
+ return [...rows.values()];
+}
+
+/** Resolve an item handle or destination handle only from the caller's authorized local inventory. */
+export function resolveLocalBoard(inventory, requested, { kind = 'team' } = {}) {
+ if (!Array.isArray(inventory) || typeof requested !== 'string' || requested.length > 260) {
+ throw new Refused('BOARD_REFERENCE', 'use one exact local board handle');
+ }
+ let privateBoard = kind === 'private';
+ let name = requested;
+ if (name.startsWith('~')) { privateBoard = true; name = name.slice(1); }
+ const choices = inventory.filter(row => row.kind === (privateBoard ? 'private' : 'team'));
+ const matches = name.includes('/')
+ ? choices.filter(row => `${row.organization}/${row.handle}` === name)
+ : choices.filter(row => row.handle === name);
+ if (matches.length !== 1) {
+ const listed = [...new Set(matches.map(row => `${privateBoard ? '~' : ''}${row.organization}/${row.handle}`))].sort();
+ const detail = matches.length > 1 ? `; choose ${listed.join(', ')}` : '';
+ throw new Refused('BOARD_REFERENCE', `use one exact authorized ${privateBoard ? 'private ' : ''}board handle${detail}`);
+ }
+ return { ...matches[0] };
+}
+
+/** Resolve `handle#id`, `owner/handle#id`, private `~handle#id`, or the current-board numeric ID. */
+export function resolveLocalItemReference(inventory, reference, currentBoardId) {
+ const text = String(reference ?? '');
+ if (/^[1-9][0-9]*$/u.test(text)) {
+ const itemId = Number(text);
+ if (!Number.isSafeInteger(itemId)) throw new Refused('BAD_ITEM_ID', 'use one safe positive item number');
+ return { boardId: currentBoardId, itemId };
+ }
+ const split = text.lastIndexOf('#');
+ const name = split > 0 ? text.slice(0, split) : '';
+ const itemId = split > 0 ? Number(text.slice(split + 1)) : NaN;
+ if (!Number.isSafeInteger(itemId) || itemId < 1) throw new Refused('BAD_ITEM_ID', 'use handle#id, owner/handle#id, ~handle#id, or one current-board item number');
+ const board = resolveLocalBoard(inventory, name);
+ return { boardId: board.boardId, itemId };
+}
diff --git a/src/board-item-dependencies.js b/src/board-item-dependencies.js
new file mode 100644
index 00000000..956aaebf
--- /dev/null
+++ b/src/board-item-dependencies.js
@@ -0,0 +1,28 @@
+/** Validate retained item dependencies independently of board write orchestration. */
+import { itemById } from './board-query.js';
+import { Refused } from './refused.js';
+import * as itemDependencies from './item-dependencies.js';
+
+/** Validate that dependencies exist, remain usable, and cannot lead back to the edited item. */
+export function validateItemDependencies(board, itemId, after) {
+ itemDependencies.dependencyValues(after);
+ const direct = itemDependencies.localDependencyIds(after).map((dependency) => itemById(board, dependency));
+ const withdrawn = direct.find((dependency) => dependency.item_status === 'withdrawn');
+ if (withdrawn) {
+ throw new Refused('WITHDRAWN', `item #${withdrawn.item_id} is withdrawn; nothing can wait on it`);
+ }
+ if (itemId === null) return;
+
+ const visited = new Set();
+ const pending = itemDependencies.localDependencyIds(after);
+ while (pending.length) {
+ const dependency = pending.pop();
+ if (dependency === itemId) {
+ throw new Refused('DEPENDENCY_CYCLE', `item #${itemId} cannot wait on itself through its dependencies; change --after to remove the cycle`);
+ }
+ if (visited.has(dependency)) continue;
+ const item = itemById(board, dependency);
+ visited.add(dependency);
+ pending.push(...itemDependencies.localDependencyIds(item));
+ }
+}
diff --git a/src/board-item-read.js b/src/board-item-read.js
index 3d4d5a65..96cd7546 100644
--- a/src/board-item-read.js
+++ b/src/board-item-read.js
@@ -8,6 +8,11 @@ import { Refused } from './refused.js';
* @returns {any}
*/
export function itemById(board, id) {
+ const redirect = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(`item_redirect:${id}`);
+ if (redirect) {
+ const target = JSON.parse(redirect.meta_value);
+ throw new Refused('NO_ITEM', `item #${id} moved to ${target.destinationHandle ?? target.destinationBoardId}#${target.destinationItemId}; use that destination reference`);
+ }
const item = board.db.prepare('SELECT * FROM item WHERE item_id = ?').get(id);
if (!item) throw new Refused('NO_ITEM', `no item #${id}; see: pullboard list`);
return item;
diff --git a/src/board-query.js b/src/board-query.js
index 349fd2b2..3afac2a2 100644
--- a/src/board-query.js
+++ b/src/board-query.js
@@ -104,10 +104,17 @@ export function boardId(board) {
* @returns {any}
*/
export function getItem(board, id) {
+ const redirect = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(`item_redirect:${id}`);
+ if (redirect) {
+ const target = JSON.parse(redirect.meta_value);
+ throw new Refused('ITEM_MOVED', `item #${id} moved to ${target.destinationHandle ?? target.destinationBoardId}#${target.destinationItemId}`);
+ }
const item = current(board, itemById(board, id));
const baseline = itemCheckBaseline(board, item);
const source = outsideSource(board, id);
- return { ...item, ...(baseline ? { item_check_baseline: baseline } : {}), ...(source ? { outside: source } : {}) };
+ const rehome = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(`rehome_import:${id}`);
+ return { ...item, ...(baseline ? { item_check_baseline: baseline } : {}), ...(source ? { outside: source } : {}),
+ ...(rehome ? { item_rehome_import: JSON.parse(rehome.meta_value) } : {}) };
}
/** Read an item's coordinator hold, or null when it is available for claims. */
@@ -130,15 +137,19 @@ export function itemHold(board, id) {
export function listItems(board, { lane, all = false } = {}) {
const hasLane = lane !== undefined && lane !== null;
const rows = board.db
- .prepare(`SELECT * FROM item WHERE ${all ? '1' : "item_status NOT IN ('verified','withdrawn')"}${hasLane ? ' AND item_lane=?' : ''} ORDER BY item_id DESC`)
+ .prepare(`SELECT item.*, imported.meta_value AS imported_rehome FROM item LEFT JOIN board_meta imported
+ ON imported.meta_key='rehome_import:' || item.item_id
+ WHERE NOT EXISTS (SELECT 1 FROM board_meta redirect WHERE redirect.meta_key='item_redirect:' || item.item_id)
+ AND ${all ? '1' : "item_status NOT IN ('verified','withdrawn')"}${hasLane ? ' AND item_lane=?' : ''} ORDER BY item_id DESC`)
.all(...(hasLane ? [lane] : []));
- const items = rows.map((item) => current(board, item));
+ const items = rows.map(({ imported_rehome: imported, ...item }) => ({ ...current(board, item),
+ ...(imported ? { item_rehome_import: JSON.parse(imported) } : {}) }));
return items;
}
/** Read a stored status/owner slice, excluding claims whose leases have expired rather than caching items. */
export function itemsInStatus(board, status, owner = null) {
- return board.db.prepare(`SELECT * FROM item WHERE item_status=?${owner === null ? '' : ' AND item_owner=?'} ORDER BY item_id DESC`)
+ return board.db.prepare(`SELECT * FROM item WHERE item_status=? AND NOT EXISTS (SELECT 1 FROM board_meta redirect WHERE redirect.meta_key='item_redirect:' || item.item_id)${owner === null ? '' : ' AND item_owner=?'} ORDER BY item_id DESC`)
.all(status, ...(owner === null ? [] : [owner])).map(item => current(board, item)).filter(item => item.item_status === status);
}
diff --git a/src/board-rehome.js b/src/board-rehome.js
new file mode 100644
index 00000000..fb860fa8
--- /dev/null
+++ b/src/board-rehome.js
@@ -0,0 +1,52 @@
+/** Re-homing facades share the board's ordinary mutations without growing its central store. */
+import {
+ itemRedirect as readItemRedirect,
+ rehomeImport as readRehomeImport,
+ rehomeDestinationItemId as destinationRehomeId,
+ rehomeItem as recordRehome,
+ reserveRehomeItemId as reserveRehomeId,
+} from './item-rehome.js';
+import {
+ boardId,
+ current,
+ itemById,
+ now,
+} from './board-query.js';
+import {
+ atomic,
+ logEvent,
+} from './board-event-log.js';
+import { Refused } from './refused.js';
+
+/** Preserve an existing check only when the validated source move carries that exact check [E15]. */
+export function validateRehomeCheck(by, check, sourceMove) {
+ const source = sourceMove?.item;
+ if (sourceMove.agentId !== by || !/^[A-Za-z0-9_-]{1,80}$/u.test(sourceMove.moveId ?? '')
+ || !Number.isSafeInteger(sourceMove.sourceReceipt?.eventId) || sourceMove.sourceReceipt.eventId < 1
+ || sourceMove.sourceReceipt.resultDigest !== sourceMove.digest || typeof source?.item_check !== 'string'
+ || source.item_check !== check || !['open', 'verified'].includes(source.item_status)) {
+ throw new Refused('COORDINATOR_CHECK', 'preserve an existing item check only as part of its exact open or verified source move');
+ }
+ return source.item_check;
+}
+
+/** Reserve an append-only item ID through a replayable destination operation [E15]. */
+export function reserveRehomeItemId(board, sourceBoardId, sourceMoveId, options) {
+ return reserveRehomeId(board, sourceBoardId, sourceMoveId, options, { atomic, boardId, logEvent });
+}
+
+/** Read the retained destination from a source-board tombstone [E15]. */
+export function itemRedirect(board, id) { return readItemRedirect(board, id); }
+
+/** Read the imported source acceptance as attributed metadata, not a destination verdict [E15]. */
+export function rehomeImport(board, id) { return readRehomeImport(board, id); }
+
+/** Resolve a previously imported source item ID on this destination board [E15]. */
+export function rehomeDestinationItemId(board, sourceBoardId, sourceItemId) {
+ return destinationRehomeId(board, sourceBoardId, sourceItemId, boardId);
+}
+
+/** Record the one ordered source-board move and its permanent old-ID redirect [E15]. */
+export function rehomeItem(board, id, options) {
+ return recordRehome(board, id, options, { atomic, boardId, current, itemById, logEvent });
+}
diff --git a/src/board.js b/src/board.js
index 0e31c1b7..aad98396 100644
--- a/src/board.js
+++ b/src/board.js
@@ -89,6 +89,16 @@ import {
requireOutsideOwner,
saveOutsideSource,
} from './outside-source.js';
+import { validateItemDependencies } from './board-item-dependencies.js';
+import { validateRehomeCheck } from './board-rehome.js';
+import { applyRehomeItem as applyRehomeRecord } from './item-rehome.js';
+export {
+ itemRedirect,
+ rehomeDestinationItemId,
+ rehomeImport,
+ rehomeItem,
+ reserveRehomeItemId,
+} from './board-rehome.js';
import { FILE_GROWTH_NOTICE_ENGINE } from './file-growth-notice-engine.js';
import {
recordBarRevision,
@@ -702,38 +712,20 @@ export function requestCompanion(board, options) {
return applyCompanionRequest(board, options, { validateAddition: validateItemAddition, insertItem });
}
-/** Validate that dependencies exist, remain usable, and cannot lead back to the edited item. */
-function validateItemDependencies(board, itemId, after) {
- itemDependencies.dependencyValues(after);
- const direct = itemDependencies.localDependencyIds(after).map((dependency) => itemById(board, dependency));
- const withdrawn = direct.find((dependency) => dependency.item_status === 'withdrawn');
- if (withdrawn) {
- throw new Refused('WITHDRAWN', `item #${withdrawn.item_id} is withdrawn; nothing can wait on it`);
- }
- if (itemId === null) return;
-
- const visited = new Set();
- const pending = itemDependencies.localDependencyIds(after);
- while (pending.length) {
- const dependency = pending.pop();
- if (dependency === itemId) {
- throw new Refused('DEPENDENCY_CYCLE', `item #${itemId} cannot wait on itself through its dependencies; change --after to remove the cycle`);
- }
- if (visited.has(dependency)) continue;
- const item = itemById(board, dependency);
- visited.add(dependency);
- pending.push(...itemDependencies.localDependencyIds(item));
- }
-}
-
/** Validate an addition before its sender runs a new check, and again when the ordered move applies. */
-export function validateItemAddition(board, { by, lane, title, criterion = '', parentId = null, after = [], brief = '', route = 'strong', check, referenceAuthors, referenceAuthority }) {
- const command = coordinatorCheck(by, check) ?? '';
+export function validateItemAddition(board, { by, lane, title, criterion = '', parentId = null, after = [], brief = '', route = 'strong', check, referenceAuthors, referenceAuthority }, { sourceMove = null } = {}) {
+ const command = sourceMove
+ ? validateRehomeCheck(by, check, sourceMove)
+ : coordinatorCheck(by, check) ?? '';
const cleanTitle = title.trim();
if (!cleanTitle) throw new Refused('NO_TITLE', 'an item needs a title');
checkRoute(route);
const engine = board.executionEngineVersion ?? ENGINE_VERSION;
- if (engine >= REFERENCE_ENGINE) validateReferences(brief, { actor: by, authors: referenceAuthors, authority: referenceAuthority });
+ if (engine >= REFERENCE_ENGINE) {
+ const proof = sourceMove?.referenceProof;
+ validateReferences(brief, { actor: proof?.actor ?? by,
+ authors: proof?.authors ?? referenceAuthors, authority: proof?.authority ?? referenceAuthority });
+ }
checkRouted({ brief: brief.trim(), route, criterion, check: command }, engine);
if (parentId !== null) {
const parent = itemById(board, parentId);
@@ -2345,6 +2337,11 @@ function tellDeferredLandingReviews(board, batch) {
/** File or refresh an outside source through the ordinary ordered engine. */
export function intakeOutside(board, options) { return applyOutsideIntake(board, options, { atomic, addItem, moveItem, validateItemAddition }); }
+/** Apply a source move once, retaining its source MOVEID receipt [E15,H16]. */
+export function applyRehomeItem(board, record, options) {
+ return applyRehomeRecord(board, { record, ...options }, { atomic, boardId, logEvent, moveItem, validateItemAddition, now });
+}
+
/** Record the person's exact-commit owner approval. */
export function approveOutside(board, id, options) { return applyOutsideApproval(board, id, options, atomic); }
diff --git a/src/cli-main.js b/src/cli-main.js
index d04692fa..fcad7137 100644
--- a/src/cli-main.js
+++ b/src/cli-main.js
@@ -63,6 +63,7 @@ const OPTIONS = {
after: { type: 'string' },
brief: { type: 'string' },
'brief-file': { type: 'string' },
+ private: { type: 'boolean' },
'coverage-file': { type: 'string' },
text: { type: 'string' },
gate: { type: 'string' },
@@ -293,6 +294,8 @@ async function runMain(argv, streams) {
values: Object.fromEntries(Object.keys(parsed.values).filter(key => key !== 'json').sort().map(key => [key, parsed.values[key]])) };
sync = Boolean(command) && !parsed.values.help && !parsed.values.version
&& !['help', 'version', 'hook', 'init', 'relay', 'tour', 'mcp', 'health', 'watch', 'digest'].includes(command)
+ // A private item never makes an otherwise unrelated repo transport on the way in or out.
+ && !(command === 'add' && parsed.values.private === true)
// A coordinator declaration on a linked clone must refuse before auto-link or relay sync.
&& !(command === 'join' && parsed.positionals[1] === (await import('./config.js')).COORDINATOR);
needsRepo = !(parsed.values.help || parsed.values.version || command === 'help' || command === 'version');
diff --git a/src/cli-read-context.js b/src/cli-read-context.js
index 68e6b5c7..49343090 100644
--- a/src/cli-read-context.js
+++ b/src/cli-read-context.js
@@ -163,7 +163,7 @@ export function firstLineOf(note) {
*/
export function itemLine(item, name = (id) => id, mainMerge = false) {
const holder = item.item_status === 'claimed' ? ` ${name(item.item_owner)}` : '';
- const verifier = item.item_status === 'verified' ? ` by ${name(item.item_verified_by)}` : '';
+ const verifier = item.item_status === 'verified' && !item.item_rehome_import ? ` by ${name(item.item_verified_by)}` : '';
const specs = item.item_spec_ids ? ` [${item.item_spec_ids}]` : '';
const parent = item.item_parent_id ? ` under #${item.item_parent_id}` : '';
const after = item.item_after ? ` after ${dependencyReferences(item).map(dependencyLabel).join(',')}` : '';
diff --git a/src/cli-resource-display.js b/src/cli-resource-display.js
new file mode 100644
index 00000000..48e50e5e
--- /dev/null
+++ b/src/cli-resource-display.js
@@ -0,0 +1,21 @@
+/** Pure CLI resource labels and browser-admission diagnostics. */
+/** Label the kind and item of a queued run without hiding older queue-class labels.
+ * With short slots on, a holder also names the slot it holds and a waiter says it may take a short one.
+ */
+export function resourceRunLabel(entry, shortSlots = 0) {
+ const priority = entry.landing ? 'landing' : entry.itemCheck ? 'item check' : entry.diagnostic ? 'diagnostic' : '';
+ const slot = !shortSlots ? '' : entry.slot ? `${entry.slot} slot` : entry.requestedSlot === 'short-eligible' ? 'may use a short slot' : '';
+ const details = [slot, entry.kind !== priority ? entry.kind : '', entry.item ? `#${entry.item}` : '', entry.leaseUntil ? `lease until ${entry.leaseUntil}` : '', entry.browser ? 'browser' : ''].filter(Boolean);
+ return `${priority ? ` (${priority})` : ''}${details.length ? ` (${details.join(', ')})` : ''}`;
+}
+
+/** Print the file and reason when conservative uncertainty reserves browser capacity.
+ * @param {any} io
+ * @param {boolean} jsonMode
+ * @returns {(decision:{file:string,reason:string})=>void}
+ */
+export function browserAdmissionReporter(io, jsonMode = false) {
+ return ({ file, reason }) => {
+ if (!jsonMode) io.stderr.write(`browser admission fallback: ${file}: ${reason}\n`);
+ };
+}
diff --git a/src/cli.js b/src/cli.js
index a90294d8..de95ccd9 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -1,3 +1,5 @@
+export { resourceRunLabel } from './cli-resource-display.js';
+export { browserAdmissionReporter } from './cli-resource-display.js';
import { dependencyValues } from './item-dependencies.js';
import { computedReturnArgs } from './computed-conflict-return.js';
import { ENGINE_VERSION as NATIVE_ENGINE } from './engine-metadata.js';
@@ -300,6 +302,7 @@ import {
sweepItems,
} from './sweep.js';
import { renderSpecView } from './view.js';
+import { runPrivateBoard } from './private-board.js';
import {
listApiProjects,
registerProjectAndLink,
@@ -585,7 +588,7 @@ export async function ordered(ctx, board, operation, args) {
const joined = store.agentAt(board, ctx.info.root)?.agent_id;
args = [{ ...args[0], createdBy: ctx.info.isMain ? COORDINATOR : joined ?? 'machine' }, ...args.slice(1)];
}
- const command = ['add', 'companion', 'edit', 'merged'].includes(ctx.io.relayCommand?.cliOperation) ? ctx.io.relayCommand : undefined;
+ const command = ['add', 'companion', 'edit', 'merged', 'move'].includes(ctx.io.relayCommand?.cliOperation) ? ctx.io.relayCommand : undefined;
/** Dispatch while this session holds the checkout, including long-running next/run loops. */
const execute = async () => {
/** Keep bootstrap in the same authenticated seat, without borrowing a person's action receipt. */
@@ -593,7 +596,9 @@ export async function ordered(ctx, board, operation, args) {
const values = [{ agentId, baseline: initialBaseline }];
const baselineIo = ctx.io.personRequest || ctx.io.personRequestMoveId
? { ...ctx.io, personRequest: undefined, personRequestMoveId: undefined } : ctx.io;
- return gitSyncLinked(ctx.info.root)
+ return ctx.privateBoard
+ ? store.recordSpecApprovalBaseline(board, ...values)
+ : gitSyncLinked(ctx.info.root)
? (await import('./sync.js')).gitBoardOperation(ctx.info.root, board, 'recordSpecApprovalBaseline', values, baselineIo)
: relayLinked(ctx.info.root) || relayRecovered(ctx.info.root)
? relayOperation(ctx.info.root, 'recordSpecApprovalBaseline', values, baselineIo, undefined,
@@ -609,7 +614,8 @@ export async function ordered(ctx, board, operation, args) {
return store[operation](board, ...args);
});
if (initialBaseline && actor) await recordBaseline(actor);
- const requested = requestedCommandMove(ctx.io.relayCommand?.cliOperation, operation);
+ const requestedCommand = ctx.io.relayCommand?.cliOperation ?? (ctx.privateBoard ? ctx.io.requestedCommand : undefined);
+ const requested = requestedCommandMove(requestedCommand, operation);
const heartbeat = requested ? (await import('./cli-presence.js')).heartbeatCommand : null;
/** Observe a committed requested write before its relay checkpoint captures the presentation. */
const observeRequested = () => {
@@ -623,12 +629,14 @@ export async function ordered(ctx, board, operation, args) {
if (requested && board.lastEvent !== before) observeRequested();
return result;
};
- const result = await withItemSession(ctx.info, operation, args, async () => gitSyncLinked(ctx.info.root)
- ? (await import('./sync.js')).gitBoardOperation(ctx.info.root, board, operation, args, ctx.io)
- : relayLinked(ctx.info.root) || relayRecovered(ctx.info.root)
- ? relayOperation(ctx.info.root, operation, args, ctx.io, command, applyRequested,
- requested ? observeRequested : undefined) : applyRequested());
- if (requested && gitSyncLinked(ctx.info.root)) ctx.io.recordedMove = true;
+ const result = await withItemSession(ctx.info, operation, args, async () => ctx.privateBoard
+ ? applyRequested()
+ : gitSyncLinked(ctx.info.root)
+ ? (await import('./sync.js')).gitBoardOperation(ctx.info.root, board, operation, args, ctx.io)
+ : relayLinked(ctx.info.root) || relayRecovered(ctx.info.root)
+ ? relayOperation(ctx.info.root, operation, args, ctx.io, command, applyRequested,
+ requested ? observeRequested : undefined) : applyRequested());
+ if (!ctx.privateBoard && requested && gitSyncLinked(ctx.info.root)) ctx.io.recordedMove = true;
if (requested && ctx.io.recordedMove) (await import('./cli-presence.js')).heartbeatCommand(ctx.io, { ctx, board });
return result;
};
@@ -1651,23 +1659,15 @@ export async function sweepHere(ctx, board, me, values) {
return blind.length ? 1 : 0;
}
-/** Run board work for the caller's checkout: open the board, find who is calling, then hand all three to the work. */
-export function actOn(io, work) {
+/** Run board work for the caller's checkout, or select its device-local repo board for a private add. */
+export function actOn(io, work, { privateBoard = false } = {}) {
const ctx = context(io);
+ if (privateBoard) return runPrivateBoard(ctx, work, { withBoard, whoAmI,
+ checkoutLeases: CHECKOUT_LEASES, checkoutBoardOnly: CHECKOUT_BOARD_ONLY });
return withBoard(ctx, (board) => work(ctx, board, whoAmI(ctx, board)));
}
-/** Label the kind and item of a queued run without hiding older queue-class labels.
- * With short slots on, a holder also names the slot it holds and a waiter says it may take a short one.
- */
-export function resourceRunLabel(entry, shortSlots = 0) {
- const priority = entry.landing ? 'landing' : entry.itemCheck ? 'item check' : entry.diagnostic ? 'diagnostic' : '';
- const slot = !shortSlots ? '' : entry.slot ? `${entry.slot} slot` : entry.requestedSlot === 'short-eligible' ? 'may use a short slot' : '';
- const details = [slot, entry.kind !== priority ? entry.kind : '', entry.item ? `#${entry.item}` : '', entry.leaseUntil ? `lease until ${entry.leaseUntil}` : '', entry.browser ? 'browser' : ''].filter(Boolean);
- return `${priority ? ` (${priority})` : ''}${details.length ? ` (${details.join(', ')})` : ''}`;
-}
-
/** Name a known board seat for queue diagnostics without requiring an unjoined checkout to join. */
export function resourceAgent(ctx) {
return ctx.info.isMain ? COORDINATOR : withBoard(ctx, board => store.agentAt(board, ctx.info.root)?.agent_id);
@@ -1716,19 +1716,6 @@ export function queuedItemLease(ctx, initial, agentId, kind) {
};
}
-/** Print the file and reason when conservative uncertainty reserves browser capacity.
- * @param {any} io
- * @param {boolean} jsonMode
- * @returns {(decision:{file:string,reason:string})=>void}
- */
-export function browserAdmissionReporter(io, jsonMode = false) {
- return ({ file, reason }) => {
- if (!jsonMode) io.stderr.write(`browser admission fallback: ${file}: ${reason}\n`);
- };
-}
-
-
-
/**
* Every spec id something cites (S8): commit headers since the spec's first commit, and every item
* on the board, open or closed. The connection is read-only: spec lint never migrates a shared board. Each must still be in the spec. The board is shared by every
diff --git a/src/commands/add.js b/src/commands/add.js
index 33622da1..21fba03f 100644
--- a/src/commands/add.js
+++ b/src/commands/add.js
@@ -42,9 +42,9 @@ import {
export async function run(io, args) {
const command = 'add';
const { first, second, rest, values } = args;
- const act = (work) => actOn(io, work);
+ const act = (work) => actOn(io, work, { privateBoard: values.private === true });
return act(async (ctx, board, me) => {
- const recovered = await relayCommandReceipt(ctx.info.root, io.relayCommand);
+ const recovered = values.private ? null : await relayCommandReceipt(ctx.info.root, io.relayCommand);
if (recovered) {
io.recordedMove = true;
for (const event of recovered.events) io.onEvent?.(event);
diff --git a/src/commands/init.js b/src/commands/init.js
index fd0d09ec..5999a8fc 100644
--- a/src/commands/init.js
+++ b/src/commands/init.js
@@ -32,6 +32,7 @@ import {
agentSessionDigest,
} from '../person.js';
import {
+ projectBoardIdentity,
registerProjectAndLink,
} from '../projects.js';
import {
@@ -101,7 +102,8 @@ export async function run(io, { values }) {
const { result } = reportInitSetup(io, info, notes, landed, { verbose: values.verbose });
const setupCommit = await finishInitCommit(setupPlan, { io, yes: values.yes, landed, permissions: !values['no-permissions'] });
result.setupCommit = setupCommit;
- if (await registerProjectAndLink(info.root, new Date(), loadConfig(info.root), io)) io.say('registered this project on this machine, so pullboard view lists it');
+ const handleIdentity = await withBoard(context(io), board => projectBoardIdentity(info.root, store.boardId(board)));
+ if (await registerProjectAndLink(info.root, new Date(), loadConfig(info.root), io, handleIdentity)) io.say('registered this project on this machine, so pullboard view lists it');
// Once registered, a background view lists this board for pullboard.dev [H5,N26].
const view = await keepViewRunning();
io.result?.({ ...result, view });
diff --git a/src/commands/join.js b/src/commands/join.js
index c05a4b77..5a66dc02 100644
--- a/src/commands/join.js
+++ b/src/commands/join.js
@@ -20,6 +20,9 @@ import {
import {
relayLinked,
} from '../relay.js';
+import * as store from '../board.js';
+import { projectBoardIdentity } from '../projects.js';
+import { registerProject } from '../projects.js';
import {
context,
ordered,
@@ -27,6 +30,7 @@ import {
requiredModel,
shellWord,
withBoard,
+ primaryCheckoutRoot,
} from '../cli.js';
/** Run `pullboard join` and return its exit code. */
@@ -41,9 +45,14 @@ export async function run(io, { first, values }) {
const route = values.route ?? 'strong';
const model = requiredModel(values.model, process.env, `join ${shellWord(COORDINATOR)}${values.route ? ` --route ${shellWord(values.route)}` : ''}${values.family ? ` --family ${shellWord(values.family)}` : ''}`);
if (relayLinked(ctx.info.root)) refuseRemoteCoordinatorModel(ctx, 'join coordinator');
- const id = await withBoard(ctx, async (board) => await ordered(ctx, board, 'register', [
- { lane: COORDINATOR, path: ctx.info.root, route, family: values.family, model, parentDigest, sessionDigest },
- ]));
+ const joined = await withBoard(ctx, async (board) => ({
+ id: await ordered(ctx, board, 'register', [
+ { lane: COORDINATOR, path: ctx.info.root, route, family: values.family, model, parentDigest, sessionDigest },
+ ]),
+ boardId: store.boardId(board),
+ }));
+ registerProject(ctx.info.root, new Date(), ctx.config, projectBoardIdentity(ctx.info.root, joined.boardId));
+ const id = joined.id;
const displayName = displayAgentName({ agent_id: id, agent_model: model }, ctx.config.agents.names);
io.result?.({ agent: id, lane: COORDINATOR, route, path: ctx.info.root, model, displayName });
io.say(`declared ${displayName} in the coordinator lane`);
@@ -54,7 +63,14 @@ export async function run(io, { first, values }) {
}
const route = values.route ?? 'strong';
const model = requiredModel(values.model, process.env, `join ${shellWord(first)}${values.route ? ` --route ${shellWord(values.route)}` : ''}${values.family ? ` --family ${shellWord(values.family)}` : ''}`);
- const id = await withBoard(ctx, async (board) => await ordered(ctx, board, 'register', [{ lane: first, path: ctx.info.root, route, family: values.family, model, parentDigest, sessionDigest }]));
+ const projectRoot = primaryCheckoutRoot(ctx.info);
+ if (!projectRoot) throw new Refused('NO_POLICY', 'cannot safely register the project without locating its main checkout; restore Git worktree metadata and retry join');
+ const joined = await withBoard(ctx, async (board) => ({
+ id: await ordered(ctx, board, 'register', [{ lane: first, path: ctx.info.root, route, family: values.family, model, parentDigest, sessionDigest }]),
+ boardId: store.boardId(board),
+ }));
+ registerProject(projectRoot, new Date(), ctx.config, projectBoardIdentity(projectRoot, joined.boardId));
+ const id = joined.id;
const displayName = displayAgentName({ agent_id: id, agent_model: model }, ctx.config.agents.names);
io.result?.({ agent: id, lane: first, route, path: ctx.info.root, model, displayName });
io.say(`joined as ${displayName} in the ${first} lane${route === 'light' ? ', on the light route' : ''}`);
diff --git a/src/commands/move.js b/src/commands/move.js
new file mode 100644
index 00000000..9cf5c4a3
--- /dev/null
+++ b/src/commands/move.js
@@ -0,0 +1,163 @@
+/** Move one item between this repo's team and device-local boards [E14,E15]. */
+import { randomUUID } from 'node:crypto';
+import * as store from '../board.js';
+import { localBoardInventory } from '../board-inventory.js';
+import { resolveLocalBoard } from '../board-inventory.js';
+import { resolveLocalItemReference } from '../board-inventory.js';
+import { runPrivateBoard } from '../private-board.js';
+import { projectBoardIdentity } from '../projects.js';
+import { registerProject } from '../projects.js';
+import { relayCommandReceipt } from '../relay.js';
+import { relayCommandReceiptReported } from '../relay.js';
+import { assertRehomeSourceItemOrdered } from '../relay.js';
+import { Refused } from '../refused.js';
+import { CHECKOUT_BOARD_ONLY } from '../cli-main.js';
+import { CHECKOUT_LEASES } from '../cli-main.js';
+import { actOn } from '../cli.js';
+import { ordered } from '../cli.js';
+import { primaryCheckoutRoot } from '../cli.js';
+import { whoAmI } from '../cli.js';
+import { withBoard } from '../cli.js';
+
+/** Run an operation against one of the current repo's authorized team/private boards. */
+async function withLocalBoard(ctx, teamBoard, teamAgent, currentBoardId, reference, work) {
+ if (reference.kind === 'team') {
+ if (reference.boardId !== currentBoardId) throw new Refused('BOARD_REFERENCE', 'open a joined checkout of the referenced repo before moving its items');
+ return work(ctx, teamBoard, teamAgent);
+ }
+ if (reference.repoBoardId !== currentBoardId) throw new Refused('BOARD_REFERENCE', 'open the repo checkout that owns this private board before moving its items');
+ if (ctx.privateBoard) return withBoard(ctx, board => work(ctx, board, whoAmI(ctx, board)));
+ return runPrivateBoard(ctx, work, { withBoard, whoAmI, checkoutLeases: CHECKOUT_LEASES, checkoutBoardOnly: CHECKOUT_BOARD_ONLY });
+}
+
+/** Run an internal ordered operation without reusing the outer CLI command's relay receipt. */
+function internalOperationContext(ctx) {
+ const io = { ...ctx.io, relayCommand: undefined };
+ for (const leases of [CHECKOUT_LEASES, CHECKOUT_BOARD_ONLY]) {
+ if (leases.has(ctx.io)) leases.set(io, leases.get(ctx.io));
+ }
+ return { ...ctx, io };
+}
+
+/** Render only the authorized handle used in the command's receipt and old-ID redirect. */
+function referenceName(reference) {
+ return `${reference.kind === 'private' ? '~' : ''}${reference.organization}/${reference.handle}`;
+}
+
+/** Apply one move from the selected current board while retaining the repo board for local handles. */
+async function moveFromContext(io, teamCtx, currentCtx, teamBoard, teamAgent, currentBoard, { first, values }) {
+ const teamBoardId = store.boardId(teamBoard);
+ const projectRoot = primaryCheckoutRoot(teamCtx.info);
+ if (!projectRoot) throw new Refused('NO_POLICY', 'cannot safely register the project without locating its main checkout; restore Git worktree metadata and retry the move');
+ registerProject(projectRoot, new Date(), teamCtx.config, projectBoardIdentity(projectRoot, teamBoardId));
+ const inventory = await localBoardInventory();
+ const sourceRef = resolveLocalItemReference(inventory, first, store.boardId(currentBoard));
+ const sourceBoardRef = inventory.find(entry => entry.boardId === sourceRef.boardId);
+ if (!sourceBoardRef) throw new Refused('BOARD_REFERENCE', 'use a team handle recorded at init or join, or this repo’s signed-in private handle');
+ if (typeof values.to !== 'string' || !values.to) throw new Refused('USAGE', 'pullboard move <item reference> --to <handle>');
+ const destinationRef = resolveLocalBoard(inventory, values.to);
+ if (destinationRef.boardId === sourceRef.boardId) throw new Refused('REHOME_SAME_BOARD', 'choose a different local board');
+
+ if (sourceBoardRef.kind === 'team') {
+ await assertRehomeSourceItemOrdered(teamCtx.info.root, sourceRef.itemId, teamCtx.io);
+ }
+
+ const sourceItem = await withLocalBoard(sourceBoardRef.kind === 'team' ? teamCtx : currentCtx,
+ teamBoard, teamAgent, teamBoardId, sourceBoardRef,
+ (_sourceCtx, sourceBoard) => {
+ const previous = store.itemRedirect(sourceBoard, sourceRef.itemId);
+ return previous?.item ?? store.getItem(sourceBoard, sourceRef.itemId);
+ });
+ if (!['open', 'verified'].includes(sourceItem.item_status)) {
+ throw new Refused('REHOME_STATE', `item #${sourceRef.itemId} is ${sourceItem.item_status}; move open or verified items only`);
+ }
+ const linkedIds = [...(sourceItem.item_parent_id === null ? [] : [sourceItem.item_parent_id]),
+ ...(sourceItem.item_after ? sourceItem.item_after.split(',').map(value => value.trim())
+ .filter(value => /^\d+$/u.test(value)).map(Number) : [])];
+ if (linkedIds.length) {
+ const unresolved = await withLocalBoard(destinationRef.kind === 'team' ? teamCtx : currentCtx,
+ teamBoard, teamAgent, teamBoardId, destinationRef,
+ (_destinationCtx, destinationBoard) => linkedIds.filter(id => !store.rehomeDestinationItemId(destinationBoard, sourceRef.boardId, id)));
+ if (unresolved.length) throw new Refused('REHOME_LINKS', `move linked item${unresolved.length === 1 ? '' : 's'} ${unresolved.map(id => `#${id}`).join(', ')} to ${referenceName(destinationRef)} first`);
+ }
+
+ const resumed = await withLocalBoard(sourceBoardRef.kind === 'team' ? teamCtx : currentCtx,
+ teamBoard, teamAgent, teamBoardId, sourceBoardRef,
+ (sourceCtx, sourceBoard, sourceAgent) => {
+ const previous = store.itemRedirect(sourceBoard, sourceRef.itemId);
+ if (previous && previous.destinationBoardId !== destinationRef.boardId) {
+ throw new Refused('REHOME_PENDING', `item #${sourceRef.itemId} already has a pending move to ${previous.destinationHandle ?? previous.destinationBoardId}#${previous.destinationItemId}; retry that same destination`);
+ }
+ return { previous, sourceCtx, sourceAgent };
+ });
+ const commandReceipt = sourceBoardRef.kind === 'team'
+ ? await relayCommandReceipt(teamCtx.info.root, teamCtx.io.relayCommand) : null;
+ let moveId = commandReceipt?.move.id ?? resumed.previous?.moveId ?? randomUUID();
+ let destinationItemId = resumed.previous?.destinationItemId;
+ const destinationHandle = referenceName(destinationRef);
+ let record = commandReceipt?.result ?? null;
+ if (commandReceipt) {
+ destinationItemId = record?.destinationItemId;
+ if (!record || record.destinationBoardId !== destinationRef.boardId) {
+ throw new Refused('REHOME_PENDING', 'retry the same destination named in the recorded source MOVEID');
+ }
+ } else if (!destinationItemId) {
+ destinationItemId = await withLocalBoard(destinationRef.kind === 'team' ? teamCtx : currentCtx,
+ teamBoard, teamAgent, teamBoardId, destinationRef,
+ async (destinationCtx, destinationBoard, destinationAgent) => ordered(internalOperationContext(destinationCtx),
+ destinationBoard, 'reserveRehomeItemId', [sourceRef.boardId, moveId, { agentId: destinationAgent.id }]));
+ }
+
+ if (!commandReceipt) {
+ const sourceOptions = { agentId: resumed.sourceAgent.id, sourceMoveId: moveId,
+ sourceHandle: referenceName(sourceBoardRef), destinationBoardId: destinationRef.boardId,
+ destinationItemId, destinationHandle };
+ resumed.sourceCtx.io.rehomeMoveId = moveId;
+ record = await withLocalBoard(sourceBoardRef.kind === 'team' ? teamCtx : currentCtx,
+ teamBoard, teamAgent, teamBoardId, sourceBoardRef,
+ (sourceCtx, sourceBoard) => ordered(sourceCtx, sourceBoard, 'rehomeItem', [sourceRef.itemId, sourceOptions]));
+ }
+ if (!record || record.moveId !== moveId || record.destinationBoardId !== destinationRef.boardId
+ || record.destinationItemId !== destinationItemId) {
+ throw new Refused('REHOME_CONFLICT', 'resume the exact source MOVEID and destination ID recorded on the source board');
+ }
+ io.recordedMove = true;
+
+ const destinationId = await withLocalBoard(destinationRef.kind === 'team' ? teamCtx : currentCtx,
+ teamBoard, teamAgent, teamBoardId, destinationRef,
+ async (destinationCtx, destinationBoard, destinationAgent) => {
+ const deliveryIo = { ...destinationCtx.io, relayCommand: undefined, rehomeMoveId: undefined };
+ for (const leases of [CHECKOUT_LEASES, CHECKOUT_BOARD_ONLY]) {
+ if (leases.has(destinationCtx.io)) leases.set(deliveryIo, leases.get(destinationCtx.io));
+ }
+ const deliveryCtx = { ...destinationCtx, io: deliveryIo };
+ let id;
+ try {
+ id = await ordered(deliveryCtx, destinationBoard, 'applyRehomeItem', [record, { destinationAgentId: destinationAgent.id }]);
+ } catch (error) {
+ if (error instanceof Refused && /^RELAY_/u.test(error.code)) {
+ throw new Refused('REHOME_PENDING', `the source move ${moveId} is recorded; retry this same move and destination to finish delivery`);
+ }
+ throw error;
+ }
+ if (deliveryCtx.io.recordedMove) io.recordedMove = true;
+ return id;
+ });
+ if (sourceBoardRef.kind === 'team' && teamCtx.io.relayCommand && (commandReceipt || io.recordedMove)) {
+ await relayCommandReceiptReported(teamCtx.info.root, moveId);
+ }
+ io.result?.({ source: `${referenceName(sourceBoardRef)}#${sourceRef.itemId}`,
+ destination: `${destinationHandle}#${destinationId}`, moveId, item: record });
+ io.say(`${referenceName(sourceBoardRef)}#${sourceRef.itemId} moved to ${destinationHandle}#${destinationId}`);
+ return 0;
+}
+
+/** Run `pullboard move <item reference> --to <handle>` and return its exit code. */
+export async function run(io, args) {
+ return actOn(io, async (ctx, teamBoard, teamAgent) => {
+ if (!args.values.private) return moveFromContext(io, ctx, ctx, teamBoard, teamAgent, teamBoard, args);
+ return runPrivateBoard(ctx, (privateCtx, privateBoard, privateAgent) =>
+ moveFromContext(io, ctx, privateCtx, teamBoard, teamAgent, privateBoard, args),
+ { withBoard, whoAmI, checkoutLeases: CHECKOUT_LEASES, checkoutBoardOnly: CHECKOUT_BOARD_ONLY });
+ });
+}
diff --git a/src/commands/show.js b/src/commands/show.js
index c5ad2dbe..fdeef812 100644
--- a/src/commands/show.js
+++ b/src/commands/show.js
@@ -70,6 +70,13 @@ export async function run(io, { first, values }) {
}
const agentName = (id) => displayAgentName(agents.find((agent) => agent.agent_id === id) ?? { agent_id: id }, ctx.config.agents.names);
io.say(itemLine(item, agentName, Boolean(mainMerge)));
+ if (item.item_rehome_import) {
+ const imported = item.item_rehome_import;
+ io.say(`${imported.sourceStatus === 'verified' ? 'verified' : 'imported'} on ${imported.sourceHandle}, moved by ${agentName(imported.attestedBy)}; source verdicts are imported references, not reviews on this board`);
+ if (values.history) for (const verdict of imported.sourceVerdicts ?? []) {
+ io.say(` source ${verdict.verdict_decision} ${verdict.verdict_reason} by ${verdict.verdict_by} at ${verdict.verdict_commit}: ${verdict.verdict_note}`);
+ }
+ }
if (item.item_status === 'verified' && approvalQualification) io.say(approvalQualification);
if (item.item_verdict_state) io.say(staleVerdictRefusal(item, item.item_verdict_state).message);
if (item.item_criterion) io.say(`criterion: ${item.item_criterion}`);
diff --git a/src/engine.js b/src/engine.js
index 3267f0ed..53249381 100644
--- a/src/engine.js
+++ b/src/engine.js
@@ -98,6 +98,10 @@ export function prepareEngineMove(board, operation, args, { id = randomUUID(), a
if (!ENGINE_OPERATIONS.includes(operation) || !Array.isArray(args)) throw new Refused('RELAY_MOVE', 'use a supported board-engine operation with its argument array');
if (operation === 'reopen') args = computedReturnArgs(board, args);
const values = args.map((value) => value && typeof value === 'object' ? { ...value } : value);
+ if (operation === 'rehomeItem' && values[1] && typeof values[1] === 'object') {
+ if (values[1].sourceMoveId !== undefined && values[1].sourceMoveId !== id) throw new Refused('RELAY_MOVE', 'a re-home must retain its exact source MOVEID');
+ values[1] = { ...values[1], sourceMoveId: id };
+ }
if (operation === 'reopen' && values[1] && typeof values[1] === 'object'
&& manualLandingFailureQuoted(values[1].note)) values[1].quotedLandingFailure = true;
// Seal native stored facts at origin; replicas replay these bytes without the origin file.
@@ -169,6 +173,7 @@ function validateMove(move) {
/** Restore only the frozen criterion callback; no receiver runs another machine's Git or shell. */
export function executableArgs(move, board) {
const args = structuredClone(move.args);
+ if (move.operation === 'rehomeItem' && args[1]?.sourceMoveId !== move.id) throw new Refused('RELAY_MOVE', 'a re-home source MOVEID does not match its sealed move');
if (move.operation === 'appendFact') {
if (!args[1] || typeof args[1] !== 'object' || Array.isArray(args[1])) throw new Refused('RELAY_MOVE', 'a fact needs its typed arguments; use the current Pullboard engine');
args[1].factId = move.id;
diff --git a/src/help.js b/src/help.js
index bc89f997..c7cae43f 100644
--- a/src/help.js
+++ b/src/help.js
@@ -81,10 +81,15 @@ Set up
Work
pullboard map [<module or function>] [--for <item>] [--budget <tokens>] source map for main, a card, or an item's one-hop slice
slices default to 4k tokens and cap at 8k; effects the scan cannot see say "not detected"
- pullboard add <lane> <title> [--criterion "..."] [--specs G1.2,K3] [--after 3,4] [--parent <id>]
+ pullboard add <lane> <title> [--criterion "..."] [--specs G1.2,K3] [--after 3,4] [--parent <id>] [--private]
[--brief "..." | --brief-file <file>] [--route light|mid]
--after: ids or repo#id; claiming waits for verified items on their own boards
--brief: what a cold agent needs; --route light: any model can build it
+ --private: keep this item in your device-local board for this repo
+ pullboard move <handle#id|owner/handle#id|~handle#id|id> --to <handle|owner/handle|~handle> [--private]
+ --private makes a bare item ID refer to this repo's device-local board
+ move one open or verified item between this repo's team and private boards; old IDs forward
+ private references start with ~; ambiguous bare handles require owner/handle
[--check "<command>"] [--wait] the command that proves it; --wait waits for its main baseline
with --criterion and a brief, --check is needed below strong
pullboard edit <id> [--brief "..." | --brief-file <file>] [--route light|mid|strong] [--criterion "..."] [--check "..."]
@@ -342,7 +347,7 @@ const HELP_EXAMPLES = {
join: 'pullboard join web --model "my-model"', resume: 'pullboard resume',
intake: 'pullboard intake https://github.com/owner/repo/pull/7 --criterion "behavior" --check "npm test"',
companion: 'pullboard companion 12 api "Provide the API" --key api-part',
- add: ADD_EXAMPLE, list: 'pullboard list web', show: 'pullboard show 12',
+ add: ADD_EXAMPLE, move: 'pullboard move ~web#3 --to web', list: 'pullboard list web', show: 'pullboard show 12',
claim: 'pullboard claim 12', submit: 'pullboard submit 12', 'next --verify': 'pullboard next --verify',
fact: 'pullboard fact 12 measurement "The check passes in 8 seconds"',
why: 'pullboard why 12',
@@ -430,6 +435,7 @@ const HELP_FLAG_EXPLANATIONS = {
'--json': 'prints one versioned document',
'--note': 'what was checked stays with the receipt',
'--note-file': 'keeps quotes, $ and backticks intact',
+ '--private': 'keeps an added item in this device-local repo board, or selects that board for move IDs',
'--route': 'sets which work the model can take',
'--source': 'where the person gave the ruling; required with --doctrine',
};
diff --git a/src/item-list.js b/src/item-list.js
index 4dad6a7a..4cd984b2 100644
--- a/src/item-list.js
+++ b/src/item-list.js
@@ -15,7 +15,7 @@ export function milestoneNamesByItem(milestones) {
/** What a board-state item summary keeps: what the lists and the roadmap read (A2, N26). */
const SUMMARY_FIELDS = Object.freeze(['id', 'title', 'lane', 'status', 'route', 'milestone', 'specs', 'claim', 'builtBy',
- 'blockedBy', 'updatedAt', 'stage', 'since', 'counts', 'verdict', 'verdictState']);
+ 'blockedBy', 'updatedAt', 'stage', 'since', 'counts', 'imported', 'verdict', 'verdictState']);
export const SUMMARY_KEYS = new Set(SUMMARY_FIELDS);
const CLOCK_MOVES = MACHINE.moves.filter((move) => move.by.includes('clock'));
diff --git a/src/item-rehome.js b/src/item-rehome.js
new file mode 100644
index 00000000..9f93bcfa
--- /dev/null
+++ b/src/item-rehome.js
@@ -0,0 +1,377 @@
+/** Durable source tombstones and idempotent destination application for cross-board re-homing [E15,H16]. */
+import { createHash } from 'node:crypto';
+import { IN_STATE } from './machine.js';
+import { MOVES } from './machine.js';
+import { REFERENCE_ENGINE } from './reference-engine.js';
+import { handledReferences } from './reference-lines.js';
+import { validateReferences } from './reference-authors.js';
+import { Refused } from './refused.js';
+
+const REHOME_IMPORT_MOVE = MOVES.find(move => move.verb === 'rehomeImport');
+
+/** Name the permanent redirect row for one retained source item ID. */
+const redirectKey = id => `item_redirect:${id}`;
+/** Name one destination receipt by source board identity and immutable source MOVEID. */
+const applicationKey = (source, move) => `item_rehome:${source}:${move}`;
+/** Name the destination's durable ID reservation by its source identity. */
+const reservationKey = (source, move) => `item_rehome_reservation:${source}:${move}`;
+
+/** Find the ordered destination event that makes a reserved ID portable across replicas. */
+function reservationEvent(board, sourceBoardId, sourceMoveId, destinationBoardId, destinationItemId) {
+ return board.db.prepare(`SELECT event_id FROM event WHERE event_kind='rehome_reserved'
+ AND json_extract(event_detail,'$.sourceBoardId')=? AND json_extract(event_detail,'$.sourceMoveId')=?
+ AND json_extract(event_detail,'$.destinationBoardId')=? AND json_extract(event_detail,'$.destinationItemId')=?
+ ORDER BY event_id LIMIT 1`).get(sourceBoardId, sourceMoveId, destinationBoardId, destinationItemId);
+}
+
+/** Encode exact JSON records with stable object-key order before binding a replay identity. */
+function stable(value) {
+ if (Array.isArray(value)) return value.map(stable);
+ if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().map(key => [key, stable(value[key])]));
+ return value;
+}
+
+/** Bind one source MOVEID to the full immutable move content. */
+function digest(value) { return createHash('sha256').update(JSON.stringify(stable(value))).digest('hex'); }
+
+/** Keep the result hash stable while appending the ordered event that names the result. */
+function moveDigest(value) {
+ const { digest: ignoredDigest, sourceReceipt: ignoredSourceReceipt, deliveryStatus: ignoredDeliveryStatus, ...content } = value;
+ return digest(content);
+}
+
+/** Match retries on the exact receipt pointer as well as the sealed move result. */
+function sourceBinding(value) {
+ const { digest: ignoredDigest, deliveryStatus: ignoredDeliveryStatus, ...content } = value;
+ return digest(content);
+}
+
+/** Carry only a current checked-reference attestation from the source board's ordered receipt. */
+function checkedReferenceReceipt(board, id, item) {
+ const rows = board.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key GLOB 'relay_receipt_*'").all();
+ const candidates = [];
+ for (const row of rows) {
+ let receipt;
+ try { receipt = JSON.parse(row.meta_value); } catch { return null; }
+ if (!receipt || typeof receipt !== 'object' || Array.isArray(receipt) || !receipt.move
+ || !receipt.outcome || typeof receipt.outcome !== 'object' || Array.isArray(receipt.outcome)) return null;
+ if (receipt.outcome.error) continue;
+ let move;
+ try { move = JSON.parse(receipt.move); } catch { return null; }
+ if (!move || typeof move !== 'object' || Array.isArray(move)) return null;
+ if (!['addItem', 'editItem'].includes(move.operation)) continue;
+ const index = move.operation === 'addItem' ? 0 : 1;
+ const args = move.args?.[index];
+ const itemId = move.operation === 'addItem' ? receipt.outcome.result : move.args?.[0];
+ if (itemId !== id || typeof args?.brief !== 'string') continue;
+ if (!Array.isArray(receipt.outcome.events)) return null;
+ const event = receipt.outcome.events.find(entry => entry.item_id === id
+ && entry.event_kind === (move.operation === 'addItem' ? 'add' : 'edit'));
+ if (!event) continue;
+ candidates.push({ sequence: receipt.sequence, moveId: move.id, engine: move.engine,
+ operation: move.operation, itemId: id, eventId: event.event_id, brief: args.brief,
+ actor: move.operation === 'addItem' ? args.by : args.agentId,
+ authority: args.referenceAuthority, authors: args.referenceAuthors });
+ }
+ if (candidates.some(candidate => !Number.isSafeInteger(candidate.eventId) || candidate.eventId < 1)) return null;
+ const latest = candidates.sort((a, b) => b.eventId - a.eventId)[0];
+ return latest?.brief === item.item_brief && Number.isSafeInteger(latest.engine)
+ && latest.engine >= REFERENCE_ENGINE && Number.isSafeInteger(latest.sequence) && latest.sequence > 0
+ && Number.isSafeInteger(latest.eventId) && latest.eventId > 0 && latest.authority === 'person'
+ && Array.isArray(latest.authors) && ['coordinator', 'person'].includes(latest.actor)
+ ? latest : null;
+}
+
+/** Check the mover-attested source receipt before forwarding a handled marker. */
+function carriesCheckedReferences(record, source) {
+ const proof = record.referenceProof;
+ return Boolean(proof && proof.itemId === record.sourceItemId && proof.brief === source.item_brief
+ && Number.isSafeInteger(proof.engine) && proof.engine >= REFERENCE_ENGINE
+ && ['addItem', 'editItem'].includes(proof.operation)
+ && typeof proof.moveId === 'string' && Number.isSafeInteger(proof.sequence) && proof.sequence > 0
+ && Number.isSafeInteger(proof.eventId) && proof.eventId > 0
+ && proof.authority === 'person' && ['coordinator', 'person'].includes(proof.actor) && Array.isArray(proof.authors)
+ && handledReferences(source.item_brief).length > 0);
+}
+
+/** A stale or incomplete source attestation loses only its handled marker, never its text. */
+function validReferenceProof(record, source) {
+ if (!carriesCheckedReferences(record, source)) return false;
+ try {
+ validateReferences(source.item_brief, { actor: record.referenceProof.actor,
+ authors: record.referenceProof.authors, authority: record.referenceProof.authority });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** Keep reference text and rationale while removing handles that lack a current checked source receipt. */
+function unhandleReferences(brief) {
+ return brief.split('\n').map(line => /^\s*Reference\s*:/iu.test(line)
+ ? line.replace(/\s+@[A-Za-z0-9][A-Za-z0-9-]{0,38}(?=\s*$)/u, '') : line).join('\n');
+}
+
+/** Reserve a destination ID as its own ordered, replayable destination-board operation. */
+export function reserveRehomeItemId(board, sourceBoardId, sourceMoveId, options, { atomic, boardId, logEvent }) {
+ if (!/^[0-9a-f]{32}$/u.test(sourceBoardId ?? '') || !/^[A-Za-z0-9_-]{1,80}$/u.test(sourceMoveId ?? '')) {
+ throw new Refused('REHOME_FORMAT', 'restore the exact source move identity before reserving a destination ID');
+ }
+ const agentId = options?.agentId;
+ if (typeof agentId !== 'string' || agentId !== 'coordinator'
+ && !board.db.prepare('SELECT 1 FROM agent WHERE agent_id=?').get(agentId)) {
+ throw new Refused('NOT_JOINED', 'join this destination board before reserving its item ID');
+ }
+ return atomic(board, () => {
+ const key = reservationKey(sourceBoardId, sourceMoveId);
+ const previous = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(key);
+ if (previous) {
+ const reservation = JSON.parse(previous.meta_value);
+ if (reservation.sourceBoardId !== sourceBoardId || reservation.moveId !== sourceMoveId
+ || reservation.destinationBoardId !== boardId(board)
+ || !Number.isSafeInteger(reservation.destinationItemId) || reservation.destinationItemId < 1) {
+ throw new Refused('REHOME_CONFLICT', 'this source move ID already has a different destination reservation');
+ }
+ if (!reservationEvent(board, sourceBoardId, sourceMoveId, boardId(board), reservation.destinationItemId)) {
+ logEvent(board, agentId, 'rehome_reserved', null, { sourceBoardId, sourceMoveId,
+ destinationBoardId: boardId(board), destinationItemId: reservation.destinationItemId });
+ }
+ return reservation.destinationItemId;
+ }
+ const max = Number(board.db.prepare('SELECT COALESCE(MAX(item_id),0) AS value FROM item').get().value);
+ const sequence = board.db.prepare("SELECT seq FROM sqlite_sequence WHERE name='item'").get()?.seq ?? 0;
+ const id = Math.max(max, sequence) + 1;
+ const updated = board.db.prepare("UPDATE sqlite_sequence SET seq=? WHERE name='item'").run(id);
+ if (updated.changes === 0) board.db.prepare("INSERT INTO sqlite_sequence(name,seq) VALUES('item',?)").run(id);
+ board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?)').run(key, JSON.stringify({
+ sourceBoardId, moveId: sourceMoveId, destinationBoardId: boardId(board), destinationItemId: id,
+ }));
+ logEvent(board, agentId, 'rehome_reserved', null, { sourceBoardId, sourceMoveId, destinationBoardId: boardId(board), destinationItemId: id });
+ return id;
+ });
+}
+
+/** Read the immutable source redirect, or null before the item has moved. */
+export function itemRedirect(board, id) {
+ const row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(redirectKey(id));
+ return row ? JSON.parse(row.meta_value) : null;
+}
+
+/** Read imported-source attribution without presenting it as a destination-board verdict. */
+export function rehomeImport(board, id) {
+ const row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(`rehome_import:${id}`);
+ return row ? JSON.parse(row.meta_value) : null;
+}
+
+/** Find the one destination item already applied for a source item on this destination board. */
+export function rehomeDestinationItemId(board, sourceBoardId, sourceItemId, boardId) {
+ if (!/^[0-9a-f]{32}$/u.test(sourceBoardId ?? '') || !Number.isSafeInteger(sourceItemId) || sourceItemId < 1) return null;
+ const prefix = `item_rehome:${sourceBoardId}:`;
+ const rows = board.db.prepare('SELECT meta_key,meta_value FROM board_meta WHERE meta_key>=? AND meta_key<? ORDER BY meta_key')
+ .all(prefix, `${prefix}\uffff`);
+ const matches = rows.map(row => JSON.parse(row.meta_value)).filter(row => row.sourceBoardId === sourceBoardId
+ && row.sourceItemId === sourceItemId && row.destinationBoardId === boardId(board));
+ if (matches.length > 1 || matches.some(row => row.destinationItemId !== matches[0]?.destinationItemId)) {
+ throw new Refused('REHOME_CONFLICT', 'one source item has conflicting destination receipts; preserve both board records');
+ }
+ return matches[0]?.destinationItemId ?? null;
+}
+
+/** Write one source-ordered tombstone while retaining enough source content for a safe retry. */
+export function rehomeItem(board, id, options, { atomic, boardId, current, itemById, logEvent }) {
+ if (!options || typeof options !== 'object' || !/^[A-Za-z0-9_-]{1,80}$/u.test(options.sourceMoveId ?? '')
+ || !/^[0-9a-f]{32}$/u.test(options.destinationBoardId ?? '')
+ || !Number.isSafeInteger(options.destinationItemId) || options.destinationItemId < 1) {
+ throw new Refused('REHOME_FORMAT', 'refresh the local board inventory and move to one exact destination board');
+ }
+ return atomic(board, () => {
+ const saved = itemRedirect(board, id);
+ if (saved) {
+ if (saved.moveId !== options.sourceMoveId || saved.destinationBoardId !== options.destinationBoardId
+ || saved.destinationItemId !== options.destinationItemId || saved.agentId !== options.agentId) {
+ throw new Refused('ITEM_MOVED', `item #${id} already moved to ${saved.destinationHandle}#${saved.destinationItemId}`);
+ }
+ return saved;
+ }
+ const item = current(board, itemById(board, id));
+ if (typeof options.agentId !== 'string' || options.agentId !== 'coordinator'
+ && !board.db.prepare('SELECT 1 FROM agent WHERE agent_id=?').get(options.agentId)) {
+ throw new Refused('NOT_JOINED', 'join this source board before moving one of its items');
+ }
+ if (!['open', 'verified'].includes(item.item_status)) {
+ throw new Refused('REHOME_STATE', `item #${id} is ${item.item_status}; move open or verified items only`);
+ }
+ const sourceBoardId = boardId(board);
+ if (sourceBoardId === options.destinationBoardId) throw new Refused('REHOME_SAME_BOARD', 'choose a different local board');
+ const verdicts = board.db.prepare('SELECT * FROM verdict WHERE item_id=? ORDER BY verdict_id').all(id);
+ const content = { ...item, verdicts };
+ const record = { version: 1, moveId: options.sourceMoveId, sourceBoardId, sourceItemId: id,
+ destinationBoardId: options.destinationBoardId, destinationItemId: options.destinationItemId,
+ agentId: options.agentId, item: content };
+ const referenceProof = checkedReferenceReceipt(board, id, item);
+ if (referenceProof) record.referenceProof = referenceProof;
+ if (typeof options.destinationHandle === 'string') record.destinationHandle = options.destinationHandle;
+ if (typeof options.sourceHandle === 'string') record.sourceHandle = options.sourceHandle;
+ record.digest = moveDigest(record);
+ logEvent(board, options.agentId, 'rehome', id, { moveId: options.sourceMoveId,
+ sourceBoardId, sourceItemId: id, destinationBoardId: options.destinationBoardId,
+ destinationItemId: options.destinationItemId, resultDigest: record.digest });
+ record.sourceReceipt = { eventId: board.lastEvent.event_id, resultDigest: record.digest };
+ board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?)').run(redirectKey(id), JSON.stringify(record));
+ return record;
+ });
+}
+
+/** Apply one source record once; replay returns the original destination ID without another item. */
+export function applyRehomeItem(board, request, { atomic, boardId, logEvent, moveItem, validateItemAddition, now }) {
+ const record = request?.record;
+ const agentId = request?.destinationAgentId ?? request?.agentId;
+ if (!record || record.version !== 1 || !/^[A-Za-z0-9_-]{1,80}$/u.test(record.moveId ?? '')
+ || !/^[0-9a-f]{32}$/u.test(record.sourceBoardId ?? '') || !/^[0-9a-f]{32}$/u.test(record.destinationBoardId ?? '')
+ || !Number.isSafeInteger(record.sourceItemId) || !Number.isSafeInteger(record.destinationItemId)
+ || !record.item || typeof record.item !== 'object' || !['open', 'verified'].includes(record.item.item_status)
+ || !Number.isSafeInteger(record.sourceReceipt?.eventId) || record.sourceReceipt.eventId < 1
+ || record.sourceReceipt.resultDigest !== record.digest) {
+ throw new Refused('REHOME_FORMAT', 'restore the exact source move record before applying it');
+ }
+ if (boardId(board) !== record.destinationBoardId) throw new Refused('REHOME_DESTINATION', 'apply the source move on its named destination board');
+ if (record.digest !== moveDigest(record)) throw new Refused('REHOME_FORMAT', 'restore the exact source move record before applying it');
+ return atomic(board, () => {
+ const key = applicationKey(record.sourceBoardId, record.moveId);
+ const binding = sourceBinding(record);
+ const applied = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(key);
+ if (applied) {
+ const saved = JSON.parse(applied.meta_value);
+ if (saved.binding !== binding) throw new Refused('REHOME_CONFLICT', 'the source move ID already names different destination content');
+ return saved.destinationItemId;
+ }
+ if (typeof agentId !== 'string' || agentId !== 'coordinator'
+ && !board.db.prepare('SELECT 1 FROM agent WHERE agent_id=?').get(agentId)) {
+ throw new Refused('NOT_JOINED', 'join this destination board before applying its source move');
+ }
+ const source = record.item;
+ const retainHandledReferences = validReferenceProof(record, source);
+ let destinationBrief = source.item_brief;
+ let referenceAuthors;
+ let referenceAuthority;
+ if (handledReferences(source.item_brief).length) {
+ if (retainHandledReferences) {
+ referenceAuthors = record.referenceProof.authors;
+ referenceAuthority = record.referenceProof.authority;
+ } else destinationBrief = unhandleReferences(destinationBrief);
+ }
+ const keyReservation = reservationKey(record.sourceBoardId, record.moveId);
+ const reservation = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(keyReservation);
+ const reserved = reservation ? JSON.parse(reservation.meta_value) : null;
+ if (reserved && (reserved.destinationBoardId !== record.destinationBoardId || reserved.destinationItemId !== record.destinationItemId)) {
+ throw new Refused('REHOME_CONFLICT', 'the source move differs from its durable destination ID reservation');
+ }
+ if (!reserved || reserved.sourceBoardId !== record.sourceBoardId || reserved.moveId !== record.moveId
+ || !reservationEvent(board, record.sourceBoardId, record.moveId, record.destinationBoardId, record.destinationItemId)) {
+ throw new Refused('REHOME_ID', 'reserve this destination ID through its ordered destination operation, then retry the same source MOVEID');
+ }
+ if (record.item.verdicts !== undefined && !Array.isArray(record.item.verdicts)) throw new Refused('REHOME_FORMAT', 'restore the source item verdict history before applying its move');
+ let accepted = null;
+ if (source.item_status === 'verified') {
+ accepted = (record.item.verdicts ?? []).find(verdict => verdict.verdict_decision === 'ACCEPT'
+ && verdict.verdict_commit === source.item_commit && verdict.verdict_digest === source.item_frozen_digest
+ && verdict.verdict_by === source.item_verified_by && verdict.verdict_by !== source.item_built_by);
+ if (!accepted || source.item_verdict !== 'ACCEPT' || !source.item_commit || !source.item_frozen_digest || !source.item_verified_by) {
+ throw new Refused('REHOME_VERDICT', 'the source verified item has no exact current ACCEPT reference to carry');
+ }
+ }
+ const parentId = source.item_parent_id === null ? null : rehomeDestinationItemId(board, record.sourceBoardId, source.item_parent_id, boardId);
+ const after = source.item_after ? source.item_after.split(',').map(value => value.trim()).map(value => {
+ if (/^\d+$/u.test(value)) return rehomeDestinationItemId(board, record.sourceBoardId, Number(value), boardId);
+ return /^[^\s#]+#\d+$/u.test(value) ? value : null;
+ }) : [];
+ if (source.item_parent_id !== null && !parentId || after.some(id => id === null || id === undefined)) {
+ throw new Refused('REHOME_LINKS', 'move each parent or wait item to this destination first, then retry the same source MOVEID');
+ }
+ const addition = { by: agentId, lane: source.item_lane, title: source.item_title,
+ criterion: source.item_criterion, parentId, after, brief: destinationBrief,
+ route: source.item_route, check: source.item_check, referenceAuthors, referenceAuthority };
+ const { command, cleanTitle } = validateItemAddition(board, { ...addition, parentId: null, after: [], by: agentId }, {
+ sourceMove: { agentId, moveId: record.moveId, digest: record.digest, sourceReceipt: record.sourceReceipt,
+ item: source, ...(retainHandledReferences ? { referenceProof: record.referenceProof } : {}) },
+ });
+ if (command !== source.item_check) throw new Refused('REHOME_CHECK', 'the destination must accept the source item check unchanged');
+ if (parentId !== null) {
+ const parent = board.db.prepare('SELECT item_lane FROM item WHERE item_id=?').get(parentId);
+ if (!parent || parent.item_lane !== source.item_lane || itemRedirect(board, parentId)) {
+ throw new Refused('REHOME_LINKS', 'move the current parent item to this destination first, then retry the same source MOVEID');
+ }
+ }
+ for (const dependency of after) {
+ if (typeof dependency === 'string') continue;
+ const item = board.db.prepare('SELECT item_status FROM item WHERE item_id=?').get(dependency);
+ if (!item || item.item_status === 'withdrawn' || itemRedirect(board, dependency)) {
+ throw new Refused('REHOME_LINKS', 'move the current wait items to this destination first, then retry the same source MOVEID');
+ }
+ }
+ const occupied = board.db.prepare('SELECT 1 FROM item WHERE item_id=?').get(record.destinationItemId);
+ if (occupied) {
+ throw new Refused('REHOME_ID', 'the reserved destination item ID is already in use; keep the same source MOVEID and resolve the collision before retrying');
+ }
+ const at = now(board);
+ const verifiedReference = accepted ? {
+ decision: 'ACCEPT', commit: accepted.verdict_commit, digest: accepted.verdict_digest,
+ by: accepted.verdict_by, sourceVerdictId: accepted.verdict_id,
+ } : null;
+ const importReference = { sourceBoardId: record.sourceBoardId, sourceItemId: record.sourceItemId,
+ sourceHandle: record.sourceHandle ?? record.sourceBoardId, sourceReceipt: record.sourceReceipt,
+ sourceMoveDigest: record.digest, moveId: record.moveId, attestedBy: agentId,
+ sourceStatus: source.item_status, sourceVerdicts: record.item.verdicts ?? [],
+ ...(verifiedReference ? { verdict: verifiedReference } : {}) };
+ board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?)')
+ .run(`rehome_import:${record.destinationItemId}`, JSON.stringify(importReference));
+ const itemColumns = `item_id,item_parent_id,item_lane,item_title,item_criterion,item_spec_ids,item_after,item_brief,item_route,item_check,
+ item_created_by,item_created_at,item_updated_at,item_status,item_frozen,item_frozen_digest,item_built_by,item_builder_family,item_commit,item_tree,item_verdict,item_verified_by`;
+ const result = board.db.prepare(`INSERT INTO item (${itemColumns}) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`)
+ .run(record.destinationItemId, parentId, source.item_lane, cleanTitle, source.item_criterion, source.item_spec_ids, after.join(','), destinationBrief,
+ source.item_route, source.item_check, source.item_created_by, source.item_created_at, at, 'open',
+ source.item_frozen, source.item_frozen_digest, source.item_built_by, source.item_builder_family,
+ source.item_commit, source.item_tree, source.item_verdict, source.item_verified_by);
+ if (Number(result.lastInsertRowid) !== record.destinationItemId) throw new Refused('REHOME_ID', 'the reserved destination item ID is no longer available');
+ const inserted = itemByIdForRehome(board, record.destinationItemId);
+ if (accepted) moveItem(board, record.destinationItemId, 'rehomeImport', {
+ transition: REHOME_IMPORT_MOVE,
+ checks: {
+ joined: null,
+ [IN_STATE]: item => item.item_status === 'open' ? null : new Refused('REHOME_VERDICT', 'restore the imported item to its original open state before carrying its ACCEPT reference'),
+ sourceAcceptance: item => importReference.attestedBy === agentId
+ && importReference.moveId === record.moveId && importReference.sourceMoveDigest === record.digest
+ && importReference.sourceReceipt?.eventId === record.sourceReceipt.eventId
+ && item.item_commit === accepted.verdict_commit
+ && item.item_frozen_digest === accepted.verdict_digest && item.item_verified_by === accepted.verdict_by
+ && item.item_built_by !== accepted.verdict_by && typeof accepted.verdict_note === 'string'
+ ? null : new Refused('REHOME_VERDICT', 'keep the exact source ACCEPT, frozen digest, commit, builder and verifier reference together'),
+ atSubmittedCommit: item => item.item_commit === accepted.verdict_commit ? null : new Refused('NOT_AT_COMMIT', 'preserve the source ACCEPT commit on the imported item'),
+ notBuilder: item => item.item_built_by !== accepted.verdict_by ? null : new Refused('SELF_VERIFY', 'preserve an independent source verifier reference'),
+ criterionUnchanged: item => item.item_frozen_digest === accepted.verdict_digest ? null : new Refused('CRITERIA_CHANGED', 'preserve the exact frozen digest accepted on the source board'),
+ proofNoted: () => typeof accepted.verdict_note === 'string' && accepted.verdict_note.trim()
+ ? null : new Refused('PROOF_REQUIRED', 'preserve the source verifier note with the ACCEPT reference'),
+ },
+ set: () => ({ item_verified_by: accepted.verdict_by, item_commit: accepted.verdict_commit }),
+ });
+ board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?)').run(key, JSON.stringify({
+ sourceBoardId: record.sourceBoardId, sourceItemId: record.sourceItemId, moveId: record.moveId,
+ destinationBoardId: record.destinationBoardId, destinationItemId: record.destinationItemId, binding,
+ attestedBy: agentId, sourceReceipt: record.sourceReceipt,
+ ...(verifiedReference ? { verifiedReference } : {}),
+ }));
+ logEvent(board, agentId, accepted ? 'rehome_import' : 'rehome_applied', record.destinationItemId, {
+ sourceBoardId: record.sourceBoardId, sourceMoveId: record.moveId, sourceItemId: record.sourceItemId,
+ sourceReceipt: record.sourceReceipt, resultDigest: record.digest, attestedBy: agentId,
+ ...(verifiedReference ? { sourceVerdict: verifiedReference.sourceVerdictId, commit: verifiedReference.commit, verifier: verifiedReference.by } : {}),
+ });
+ return inserted.item_id;
+ });
+}
+
+/** Return the inserted destination row without exposing a separate read API dependency. */
+function itemByIdForRehome(board, id) {
+ const item = board.db.prepare('SELECT * FROM item WHERE item_id=?').get(id);
+ if (!item) throw new Refused('REHOME_ID', 'the destination item was not created; preserve the source move and retry its application');
+ return item;
+}
diff --git a/src/json.js b/src/json.js
index 40a765b0..38ebdfa4 100644
--- a/src/json.js
+++ b/src/json.js
@@ -32,6 +32,7 @@ export const JSON_SHAPES = {
relay: shape({ linked: 'boolean', board: 'string', url: 'string', link: 'string', sequence: 'number', behind: 'number', recovery: 'object' }),
sync: shape({ ref: 'string', sequence: 'number', pending: 'string|null' }),
list: shape({ items: 'array' }),
+ move: shape({ source: 'string', destination: 'string', moveId: 'string', item: 'object' }),
queue: shape({ releases: 'array', unreleased: 'array', first: 'object' }),
map: shape({ main: 'string', map: 'string' }),
'flow replay': shape({ history: 'object', replay: 'object' }),
diff --git a/src/machine.js b/src/machine.js
index 1ea7dbfe..f7a7a4cf 100644
--- a/src/machine.js
+++ b/src/machine.js
@@ -84,10 +84,10 @@ export const STATES = [
{ id: 'claimed', means: 'an agent holds it under a lease, its criterion frozen', requires: ['item_owner', 'item_lease_until', 'item_frozen_digest'] },
{ id: 'submitted', means: 'a native build gated green, or an intaken outside commit awaiting sandbox verification, at a pinned commit', requires: ['item_built_by', 'item_commit', 'item_frozen_digest'] },
{
- id: 'verified', means: 'another agent accepted the frozen work at this commit or its canonically recorded trunk-only merge', requires: ['item_verified_by', 'item_commit'],
+ id: 'verified', means: 'another agent accepted it at the submitted commit, its canonically recorded trunk-only merge, or the item carries an attributed source-board acceptance', requires: ['item_verified_by', 'item_commit'],
proof: {
- says: 'an immutable ACCEPT on the frozen criterion by its independent verifier, at this commit or bound by an ordered merge-only receipt',
- sql: "EXISTS (SELECT 1 FROM verdict v WHERE v.item_id = NEW.item_id AND v.verdict_decision = 'ACCEPT' AND v.verdict_digest = NEW.item_frozen_digest AND v.verdict_by = NEW.item_verified_by AND v.verdict_by <> NEW.item_built_by AND (v.verdict_commit = NEW.item_commit OR EXISTS (SELECT 1 FROM event e WHERE e.item_id = NEW.item_id AND e.event_kind = 'merge-only-accept' AND json_extract(e.event_detail,'$.verdict') = v.verdict_id AND json_extract(e.event_detail,'$.commit') = NEW.item_commit AND json_extract(e.event_detail,'$.tree') = NEW.item_tree AND json_extract(e.event_detail,'$.digest') = NEW.item_frozen_digest AND json_extract(e.event_detail,'$.by') = v.verdict_by)))",
+ says: 'an ACCEPT on the frozen criterion by its independent verifier at this commit or bound by an ordered merge-only receipt, or an authenticated destination move attesting to an exact source acceptance',
+ sql: "EXISTS (SELECT 1 FROM verdict v WHERE v.item_id = NEW.item_id AND v.verdict_decision = 'ACCEPT' AND v.verdict_digest = NEW.item_frozen_digest AND v.verdict_by = NEW.item_verified_by AND v.verdict_by <> NEW.item_built_by AND (v.verdict_commit = NEW.item_commit OR EXISTS (SELECT 1 FROM event e WHERE e.item_id = NEW.item_id AND e.event_kind = 'merge-only-accept' AND json_extract(e.event_detail,'$.verdict') = v.verdict_id AND json_extract(e.event_detail,'$.commit') = NEW.item_commit AND json_extract(e.event_detail,'$.tree') = NEW.item_tree AND json_extract(e.event_detail,'$.digest') = NEW.item_frozen_digest AND json_extract(e.event_detail,'$.by') = v.verdict_by))) OR EXISTS (SELECT 1 FROM board_meta r WHERE r.meta_key = 'rehome_import:' || NEW.item_id AND json_extract(r.meta_value, '$.sourceBoardId') IS NOT NULL AND json_extract(r.meta_value, '$.sourceItemId') IS NOT NULL AND json_extract(r.meta_value, '$.moveId') IS NOT NULL AND json_extract(r.meta_value, '$.attestedBy') IS NOT NULL AND json_extract(r.meta_value, '$.sourceMoveDigest') IS NOT NULL AND json_extract(r.meta_value, '$.sourceReceipt.resultDigest') = json_extract(r.meta_value, '$.sourceMoveDigest') AND json_extract(r.meta_value, '$.verdict.decision') = 'ACCEPT' AND json_extract(r.meta_value, '$.verdict.commit') = NEW.item_commit AND json_extract(r.meta_value, '$.verdict.digest') = NEW.item_frozen_digest AND json_extract(r.meta_value, '$.verdict.by') = NEW.item_verified_by AND json_extract(r.meta_value, '$.verdict.by') <> NEW.item_built_by)",
},
},
{ id: 'withdrawn', final: true, means: 'nobody should build it; the reason stays on it', requires: ['item_withdrawn_reason'] },
@@ -95,11 +95,12 @@ export const STATES = [
/** @type {Guard[]} */
export const GUARDS = [
+ { id: 'sourceAcceptance', refuse: 'REHOME_VERDICT', rule: 'the authenticated destination mover attests to an exact source board ACCEPT reference keyed by the ordered source MOVEID and result digest', next: 'preserve the imported source acceptance attribution, frozen digest, commit and verifier reference', source: 'board' },
{ id: 'mergeOnlyRecorded', refuse: 'MERGE_ONLY_PROOF', rule: 'the sealed submit records the origin’s Git-derived carry, unchanged bar and original verifier; landing re-proves its heads, trees and resolution hash before merging', next: 'submit normally for outside review if the origin cannot prove the merge', source: 'board' },
{ id: 'outsideSubmission', refuse: 'OUTSIDE_SOURCE', rule: 'an outside author and exact fetched commit/tree are recorded with a trusted frozen criterion, without pretending a native builder gated it', next: 'fetch and intake the exact GitHub pull request again', source: 'board' },
{ id: IN_STATE, refuse: '', rule: "the move can start from the item's current state", next: 'pullboard show <id>', source: 'board' },
{ id: 'joined', refuse: 'NOT_JOINED', alsoRefuses: [{ code: 'AGENT_REPLACED', next: 'read the takeover and only shout on its exact hand-off item; continue work from the incoming agent worktree' }, { code: 'SESSION_LEDGER', next: 'make the agent-session ledger named in the message readable and writable by this user, then run the command again' }], rule: 'the caller is the main checkout, or an unreplaced worktree seat that joined a lane; an agent session\'s claims, submits and verdicts can be checked against its local ledger', next: 'pullboard join <lane> --model "<model name>" (see: pullboard lanes)', source: 'cli' },
- { id: 'itemExists', refuse: 'NO_ITEM', rule: 'the item exists', next: 'pullboard list --all', source: 'board' },
+ { id: 'itemExists', refuse: 'NO_ITEM', alsoRefuses: [{ code: 'ITEM_MOVED', next: 'use the recorded destination reference shown in the refusal; do not move the old ID again' }], rule: 'the item exists and has not been moved', next: 'pullboard list --all', source: 'board' },
{ id: 'reopenAuthority', refuse: 'COORDINATOR_ONLY', rule: 'the coordinator reopens, the native board computes an automatic submitted-head conflict, or the exact accepting reviewer withdraws its verdict; older recorded submitted-conflict moves keep their joined-seat authority', next: 'ask the coordinator or the reviewer who recorded the accept', source: 'board', alsoRefuses: [{ code: 'NO_POLICY', next: 'restore the local Git configuration so the current trunk can be read, then compute a fresh automatic return' }, { code: 'GIT_GRAFTS', next: 'ask the coordinator to remove the replica graft file, then resume the same move' }, { code: 'GIT_REPLACE_REFS', next: 'ask the coordinator to remove the replica replacement refs, then resume the same move' }, { code: 'VERDICT_WITHDRAW_FORBIDDEN', next: 'ask the accepting reviewer or coordinator to withdraw the verdict' }, { code: 'VERDICT_WITHDRAW_STATE', next: 'refresh the item; only a current acceptance before landing can be withdrawn' }] },
{ id: 'coordinatorOnly', refuse: 'COORDINATOR_ONLY', rule: 'the caller is the coordinator', next: 'run it from the main checkout', source: 'board' },
{ id: 'roadmapReadable', refuse: 'MILESTONES_CORRUPT', alsoRefuses: [{ code: 'LINE_SETTING_RANGE', rule: 'the recorded board line-order setting has a valid registry value', next: 'restore the recorded board line setting from its ordered event history, then retry next --verify' }], rule: 'the recorded queue policy and roadmap are readable when selecting the next review', next: 'restore board metadata from a known-good board export', source: 'board', when: 'only next --verify selection; a review reserved by id does not consult the roadmap' },
@@ -169,6 +170,10 @@ const AGENT_GRANT_REFUSALS = [
/** @type {Move[]} */
export const MOVES = [
+ { verb: 'rehomeImport', from: ['open'], to: 'verified', by: ['agent'], refuse: 'REHOME_VERDICT',
+ guards: ['joined', 'itemExists', IN_STATE, 'sourceAcceptance', 'atSubmittedCommit', 'notBuilder', 'criterionUnchanged', 'proofNoted'],
+ sets: ['item_verified_by', 'item_commit'],
+ command: 'pullboard move <item reference> --to <handle>' },
{ verb: 'intake', from: ['open'], to: 'submitted', by: ['agent', 'coordinator'], refuse: 'NOT_CLAIMABLE',
guards: ['joined', 'itemExists', IN_STATE, 'outsideSubmission'], sets: ['item_built_by', 'item_commit', 'item_frozen_digest'], command: 'pullboard intake <PR> --criterion \"...\" --check \"...\"' },
{
@@ -520,7 +525,7 @@ export function storeTriggers(machine = MACHINE) {
}
for (const state of machine.states.filter((entry) => entry.proof)) {
const complete = state.requires.length ? ` AND NOT (${missingOf(state)})` : '';
- triggers.push(trigger(`machine_proof_${state.id}`, onWrite, `WHEN ${holds(state.id)}${complete} AND NOT ${state.proof.sql}\n${refuse('NOT_PROVEN', `${state.id} needs ${state.proof.says}`)}`));
+ triggers.push(trigger(`machine_proof_${state.id}`, onWrite, `WHEN ${holds(state.id)}${complete} AND NOT (${state.proof.sql})\n${refuse('NOT_PROVEN', `${state.id} needs ${state.proof.says}`)}`));
}
for (const [table, kept] of Object.entries(machine.records)) {
for (const change of kept === 'append' ? ['update', 'delete'] : ['delete']) {
diff --git a/src/moves/applyRehomeItem.js b/src/moves/applyRehomeItem.js
new file mode 100644
index 00000000..4d98dba8
--- /dev/null
+++ b/src/moves/applyRehomeItem.js
@@ -0,0 +1,19 @@
+import { PRIVATE_REHOME_ENGINE } from '../private-rehome-engine.js';
+
+/** Destination application uses the source identity as its idempotency key [H16]. */
+function minimumEngine() { return PRIVATE_REHOME_ENGINE; }
+/** Destination replay is attributed to the authenticated local/relay actor [H2,H16]. */
+function actor(move) { return move.args[1]?.destinationAgentId ?? move.args[1]?.agentId ?? null; }
+
+export default Object.freeze({ operation: 'applyRehomeItem', order: 10002, engine: PRIVATE_REHOME_ENGINE,
+ itemIdFirstArgument: false, minimumEngine, actor,
+ nextSteps: Object.freeze({
+ REHOME_CHECK: 'keep the source check unchanged and choose a destination board whose policy accepts it',
+ REHOME_CONFLICT: 'keep the original source move ID and resolve the destination board conflict before retrying',
+ REHOME_DESTINATION: 'apply the source move on its named destination board',
+ REHOME_FORMAT: 'restore the exact source move record and retry it with an authorized destination handle',
+ REHOME_ID: 'preserve the source MOVEID and its reserved destination ID; resolve the item-ID conflict before retrying',
+ REHOME_LINKS: 'move each parent or wait item to this destination first, then retry the same source MOVEID',
+ REHOME_PENDING: 'retry the same move ID and destination to finish delivery; do not allocate another destination ID',
+ REHOME_VERDICT: 'keep the source board acceptance intact and inspect its exact commit, digest and verifier reference',
+ }) });
diff --git a/src/moves/rehomeItem.js b/src/moves/rehomeItem.js
new file mode 100644
index 00000000..f79d48a9
--- /dev/null
+++ b/src/moves/rehomeItem.js
@@ -0,0 +1,17 @@
+import { PRIVATE_REHOME_ENGINE } from '../private-rehome-engine.js';
+
+/** Preserve the ordered source move ID in its arguments for idempotent destination application. */
+function minimumEngine(args) { return PRIVATE_REHOME_ENGINE; }
+/** Read the actor from the re-home options [H2,H16]. */
+function actor(move) { return move.args[1]?.agentId ?? null; }
+
+export default Object.freeze({ operation: 'rehomeItem', order: 10001, engine: PRIVATE_REHOME_ENGINE,
+ itemIdFirstArgument: true, minimumEngine, actor,
+ nextSteps: Object.freeze({
+ ITEM_MOVED: 'use the recorded destination reference shown in the refusal; do not move the old ID again',
+ REHOME_PENDING: 'retry the same move ID and destination to finish delivery; do not allocate another destination ID',
+ REHOME_FORMAT: 'restore the exact source move record and retry it with an authorized destination handle',
+ REHOME_LINKS: 'move each parent or wait item to this destination first, then retry the same source MOVEID',
+ REHOME_SAME_BOARD: 'choose a different local board',
+ REHOME_STATE: 'open or verified items can move; keep other items on their current board',
+ }) });
diff --git a/src/moves/reserveRehomeItemId.js b/src/moves/reserveRehomeItemId.js
new file mode 100644
index 00000000..cc5d0760
--- /dev/null
+++ b/src/moves/reserveRehomeItemId.js
@@ -0,0 +1,14 @@
+import { PRIVATE_REHOME_ENGINE } from '../private-rehome-engine.js';
+
+/** Reserve an item ID before the matching source move names it [E15,H16]. */
+function minimumEngine() { return PRIVATE_REHOME_ENGINE; }
+/** Read the actor from the reservation options [H2,H16]. */
+function actor(move) { return move.args[2]?.agentId ?? null; }
+
+export default Object.freeze({ operation: 'reserveRehomeItemId', order: 10000, engine: PRIVATE_REHOME_ENGINE,
+ itemIdFirstArgument: false, minimumEngine, actor,
+ nextSteps: Object.freeze({
+ NOT_JOINED: 'join a lane from this worktree: pullboard join <lane> --model "<model name>" (see: pullboard lanes)',
+ REHOME_CONFLICT: 'keep the original source move ID and resolve the destination board conflict before retrying',
+ REHOME_FORMAT: 'restore the exact source move record and retry it with an authorized destination handle',
+ }) });
diff --git a/src/next-step-defaults.js b/src/next-step-defaults.js
index 6276bb72..f923eced 100644
--- a/src/next-step-defaults.js
+++ b/src/next-step-defaults.js
@@ -31,6 +31,9 @@ export const DEFAULT_NEXT_STEPS = Object.freeze({
"ITEM_RECEIPT": "obtain the exact minimal source receipt and verify its item, commit and verifier/verdict through the established trust port",
"SEAT_ADDRESS_BOARD": "open a linked checkout of the addressed board with your own grant, then run pullboard shout <address> <text>",
"BAD_COMPUTER_NAME": "retry relay on or relay join with --name containing 1 to 80 characters and no control characters or path separators",
+ "BAD_ITEM_ID": "use owner/repo#id, ~owner/repo#id, or one safe positive item number on the current board",
+ "PRIVATE_BOARD_NOT_FOUND": "run pullboard add <lane> <title> --private from that repo's checkout before using its private handle",
+ "PRIVATE_BOARD_IDENTITY": "open the original repo checkout under its recorded GitHub login; keep the existing private board files and identity intact",
"GIT_SYNC_LOG": "restore the append-only refs/pullboard/board history on origin before running pullboard sync",
"GIT_SYNC_REMOTE": "restore read/write access to origin, then retry the original command or run pullboard sync; keep its pending sealed move",
"GIT_SYNC_LOCAL_CHANGED": "run pullboard export to preserve local moves, then ask the coordinator to reconcile the local and remote prefixes before syncing",
diff --git a/src/pr-proof-snapshot.js b/src/pr-proof-snapshot.js
index 7b368673..75878273 100644
--- a/src/pr-proof-snapshot.js
+++ b/src/pr-proof-snapshot.js
@@ -20,7 +20,7 @@ export function capturePrProof(board) {
const verdicts = byItem(board.db.prepare('SELECT * FROM verdict ORDER BY verdict_id').all());
const events = byItem(store.eventsOfKinds(board, ['accept', 'reject', 'reopen']));
const metadata = new Map(board.db.prepare(`SELECT meta_key,meta_value FROM board_meta
- WHERE meta_key GLOB 'verdict_assurance:*' OR meta_key GLOB 'outside:*'`).all()
+ WHERE meta_key GLOB 'verdict_assurance:*' OR meta_key GLOB 'outside:*' OR meta_key GLOB 'rehome_import:*'`).all()
.map(row => [row.meta_key, row]));
const batches = store.landingBatches(board);
// This private reader accepts only the canonical interpreter's known queries. Carry lookups
@@ -49,6 +49,6 @@ export function capturePrProof(board) {
if (raw !== undefined) outside.set(item.item_id, JSON.parse(raw));
}
return { items, accepted, outside, batches,
- assurance: verdict => metadata.get('verdict_assurance:' + verdict?.verdict_id)?.meta_value };
+ assurance: verdict => verdict?.imported ? 'imported' : metadata.get('verdict_assurance:' + verdict?.verdict_id)?.meta_value };
} finally { board.db.exec('RELEASE pr_proof_snapshot'); }
}
diff --git a/src/pr-publish.js b/src/pr-publish.js
index d6bcfb8b..f348dcfb 100644
--- a/src/pr-publish.js
+++ b/src/pr-publish.js
@@ -74,7 +74,7 @@ function releaseEntries(root, board, base, head) {
if (!verdict) throw new Refused('PUBLISH_UNPROVEN', `item #${item.item_id} has no acceptance at its submitted commit; restore its recorded review before publishing`);
return [{ id: item.item_id, merge, commit: item.item_commit, verdict: verdict.verdict_decision,
reviewer: verdict.verdict_by, environment: verdict.environment ?? null,
- references: handledReferences(item.item_brief),
+ imported: verdict.imported ?? null, references: handledReferences(item.item_brief),
files: git(root, ['diff', '--name-only', `${merge}^1`, merge]).split('\n').filter(Boolean) }];
});
}
@@ -84,9 +84,12 @@ function receiptBody(head, entries) {
return [`Pullboard publication head: ${head}`, '', 'Accepted item receipts:', ...entries.map(entry => {
const env = entry.environment;
const where = env ? `${env.platform}/${env.arch}, Node ${env.node}` : 'execution environment unknown (historical receipt)';
+ const accepted = entry.imported
+ ? `- #${entry.id}: ${entry.commit}; imported source ${entry.verdict} from ${entry.imported.sourceHandle}; source reviewer ${entry.reviewer}; moved by ${entry.imported.attestedBy} (not a destination-board review)`
+ : `- #${entry.id}: ${entry.commit}; ${entry.verdict}; reviewer ${entry.reviewer}; ${where}`;
const references = (entry.references ?? []).map(reference =>
` Reference: ${reference.target} @${reference.handle}`);
- return [`- #${entry.id}: ${entry.commit}; ${entry.verdict}; reviewer ${entry.reviewer}; ${where}`, ...references].join('\n');
+ return [accepted, ...references].join('\n');
}), '', 'The whole project gate passed at the publication head before this branch was pushed.',
'Item receipts certify their recorded accepted commits; they do not invent a second-agent verdict on this publication composition.',
'Changes outside those item receipts remain unverified by a second agent.'].join('\n');
diff --git a/src/private-board.js b/src/private-board.js
new file mode 100644
index 00000000..545950e2
--- /dev/null
+++ b/src/private-board.js
@@ -0,0 +1,47 @@
+/** Select a repo's device-local board for an add without changing the shared repo board [E11,E13]. */
+import * as store from './board.js';
+import { withPrivateBoard } from './projects.js';
+import { originRepository } from './github-origin.js';
+import { relayMachineOwner } from './relay-machine.js';
+import { relayStatus } from './relay.js';
+import { Refused } from './refused.js';
+
+/** Run one add on its device-local board while keeping the repo checkout's own seat binding. */
+export function runPrivateBoard(ctx, work, { withBoard, whoAmI, checkoutLeases, checkoutBoardOnly }) {
+ return withBoard(ctx, async (repoBoard) => {
+ const repoActor = whoAmI(ctx, repoBoard);
+ const repository = originRepository(ctx.info.root, { optional: true });
+ const [repoOwner, repoName] = repository?.split('/') ?? [];
+ let signedOwner = null;
+ try {
+ const machineOwner = relayMachineOwner();
+ signedOwner = machineOwner ? machineOwner.login : relayStatus(ctx.info.root)?.login;
+ } catch { /* Missing readable sign-in metadata is refused below. */ }
+ if (!signedOwner) throw new Refused('AUTH_REQUIRED', 'sign in to GitHub with pullboard relay on before creating a private-board reference');
+ return withPrivateBoard(store.boardId(repoBoard), async (board, file) => {
+ const privateIo = { ...ctx.io, relayCommand: undefined,
+ requestedCommand: ctx.io.relayCommand?.cliOperation ?? ctx.io.requestedCommand };
+ const checkoutLease = checkoutLeases.get(ctx.io);
+ if (checkoutLease) checkoutLeases.set(privateIo, checkoutLease);
+ const boardOnly = checkoutBoardOnly.get(ctx.io);
+ if (boardOnly) checkoutBoardOnly.set(privateIo, boardOnly);
+ const privateCtx = { ...ctx, io: privateIo, file, allowSchemaUpgrade: true, privateBoard: true };
+ if (ctx.info.isMain) store.ensureCoordinator(board, ctx.info.root);
+ else if (!store.agentAt(board, ctx.info.root)) store.register(board, {
+ lane: repoActor.lane,
+ path: ctx.info.root,
+ route: repoActor.route,
+ family: repoActor.family,
+ model: repoActor.model,
+ createdBy: 'machine',
+ });
+ const actor = store.agentAt(board, ctx.info.root);
+ try {
+ return await work(privateCtx, board, { id: actor.agent_id, lane: actor.agent_lane, route: actor.agent_route,
+ family: actor.agent_family, model: actor.agent_model });
+ } finally {
+ if (privateIo.recordedMove) ctx.io.recordedMove = true;
+ }
+ }, { create: true, clock: ctx.clock, reference: repository ? { handle: repoName, organization: repoOwner, owner: signedOwner } : null });
+ });
+}
diff --git a/src/private-rehome-engine.js b/src/private-rehome-engine.js
new file mode 100644
index 00000000..e40072ed
--- /dev/null
+++ b/src/private-rehome-engine.js
@@ -0,0 +1,4 @@
+import { unassignedEngine } from './engine-next.js';
+
+/** The first engine that can replay a source board's durable re-home move. */
+export const PRIVATE_REHOME_ENGINE = unassignedEngine();
diff --git a/src/projects.js b/src/projects.js
index 45a426eb..7ec518ec 100644
--- a/src/projects.js
+++ b/src/projects.js
@@ -4,6 +4,7 @@
*/
import {
closeSync,
+ chmodSync,
existsSync,
fsyncSync,
mkdirSync,
@@ -16,13 +17,19 @@ import {
import { homedir } from 'node:os';
import {
basename,
+ dirname,
join,
resolve,
} from 'node:path';
import { randomUUID } from 'node:crypto';
import { DatabaseSync } from 'node:sqlite';
import { loadConfig } from './config.js';
+import { originRepository } from './github-origin.js';
import { withMachineHomeWrite } from './machine-home.js';
+import { boardReferenceId } from './board-reference.js';
+import { repoInfo } from './git.js';
+import * as store from './board.js';
+import { Refused } from './refused.js';
/**
* The registry file.
@@ -33,6 +40,95 @@ export function registryFile() {
return join(process.env.PULLBOARD_HOME || join(homedir(), '.pullboard'), 'projects.json');
}
+/** Return a stable team handle only when Git origin and the opened board identity are both exact. */
+export function projectBoardIdentity(root, boardId) {
+ const id = boardReferenceId(boardId);
+ const repository = originRepository(root, { optional: true });
+ if (!repository) return null;
+ const [owner, name] = repository.split('/');
+ return { boardId: id, owner, name };
+}
+
+/**
+ * Locate one repo's device-local private board from the repo board's immutable identity.
+ * @param {string} repoBoardId
+ * @param {string} [home]
+ * @returns {string}
+ */
+export function privateBoardPath(repoBoardId, home = process.env.PULLBOARD_HOME || join(homedir(), '.pullboard')) {
+ const id = boardReferenceId(repoBoardId);
+ return join(resolve(home), 'private', id, 'board.sqlite');
+}
+
+/**
+ * Prepare owner-only storage for one repo's private board without changing the shared repo board.
+ * @param {string} repoBoardId
+ * @param {string} [home]
+ * @returns {string}
+ */
+export function preparePrivateBoardPath(repoBoardId, home) {
+ const file = privateBoardPath(repoBoardId, home);
+ const directory = dirname(file);
+ const privateRoot = dirname(directory);
+ withMachineHomeWrite(privateRoot, () => {
+ mkdirSync(privateRoot, { recursive: true, mode: 0o700 });
+ chmodSync(privateRoot, 0o700);
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
+ chmodSync(directory, 0o700);
+ });
+ return file;
+}
+
+/** Keep the private SQLite file readable and writable only by this machine account. */
+export function protectPrivateBoard(file) {
+ withMachineHomeWrite(file, () => chmodSync(file, 0o600));
+}
+
+/**
+ * Open this device's private board for one repo; a reader may require an existing board, while add creates it.
+ * @param {string} repoBoardId
+ * @param {(board: any, file: string) => any} work
+ * @param {{ create?: boolean, clock?: any }} [options]
+ * @returns {Promise<any>}
+ */
+export async function withPrivateBoard(repoBoardId, work, { create = false, clock, reference = null } = {}) {
+ const ownerBoardId = boardReferenceId(repoBoardId);
+ const file = create ? preparePrivateBoardPath(repoBoardId) : privateBoardPath(repoBoardId);
+ if (!create && !existsSync(file)) throw new Refused('PRIVATE_BOARD_NOT_FOUND', 'this device has no private board for that repo; open it from the repo checkout first');
+ const board = store.openBoard(file, clock, { isMain: true });
+ try {
+ protectPrivateBoard(file);
+ const registered = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get('private_repo_board_id');
+ if (!registered && create) store.atomic(board, () => board.db.prepare('INSERT OR IGNORE INTO board_meta (meta_key, meta_value) VALUES (?, ?)')
+ .run('private_repo_board_id', ownerBoardId));
+ const owner = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get('private_repo_board_id');
+ if (!owner || owner.meta_value !== ownerBoardId) {
+ throw new Refused('PRIVATE_BOARD_IDENTITY', 'the device-local board belongs to a different repo; keep its existing identity intact');
+ }
+ if (reference) {
+ if (typeof reference.handle !== 'string' || !/^[A-Za-z0-9_.-]{1,128}$/u.test(reference.handle)
+ || typeof reference.organization !== 'string' || !/^[A-Za-z0-9_.-]{1,128}$/u.test(reference.organization)
+ || typeof reference.owner !== 'string' || !/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/u.test(reference.owner)) {
+ throw new Refused('BOARD_REFERENCE', 'record the exact repository owner/name and signed-in GitHub login for a private board');
+ }
+ store.atomic(board, () => {
+ const savedReference = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get('private_board_reference');
+ const value = JSON.stringify({ version: 1, kind: 'private', repoBoardId: ownerBoardId, ...reference });
+ if (!savedReference) board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?)').run('private_board_reference', value);
+ else {
+ const previous = JSON.parse(savedReference.meta_value);
+ if (previous.version !== 1 || previous.kind !== 'private' || previous.repoBoardId !== ownerBoardId
+ || previous.handle !== reference.handle || previous.organization !== reference.organization
+ || previous.owner !== reference.owner) {
+ throw new Refused('PRIVATE_BOARD_IDENTITY', 'the saved private board reference belongs to a different repo or signed-in GitHub login');
+ }
+ }
+ });
+ }
+ return await work(board, file);
+ } finally { store.closeBoard(board); }
+}
+
/**
* Read the registry, treating unreadable or malformed content as empty without authorizing a rewrite.
*
@@ -245,12 +341,21 @@ export function listApiProjects() {
* @param {object} [config]
* @returns {boolean} Whether it was new.
*/
-export function registerProject(root, now = new Date(), config = {}) {
+export function registerProject(root, now = new Date(), config = {}, identity = null) {
const normalizedRoot = resolve(root);
return withRegistry((stored, readable) => {
if (!readable) return false;
const projects = stored.map((entry) => ({ ...entry, root: resolve(entry.root) }));
const metadata = configMetadata(normalizedRoot, config);
+ const handle = identity && typeof identity === 'object' ? {
+ ...(typeof identity.boardId === 'string' && /^[0-9a-f]{32}$/u.test(identity.boardId) ? { boardId: identity.boardId } : {}),
+ ...(typeof identity.owner === 'string' && /^[A-Za-z0-9_.-]{1,128}$/u.test(identity.owner) ? { owner: identity.owner } : {}),
+ ...(typeof identity.name === 'string' && /^[A-Za-z0-9_.-]{1,128}$/u.test(identity.name) ? { handle: identity.name } : {}),
+ kind: 'team',
+ } : null;
+ if (handle && (!handle.boardId || !handle.owner || !handle.handle)) {
+ throw new Refused('BOARD_REFERENCE', 'record a complete origin owner/name and immutable board ID before adding it to the local board inventory');
+ }
const existing = projects.find((project) => project.root === normalizedRoot);
if (existing) {
if (metadata) {
@@ -260,10 +365,14 @@ export function registerProject(root, now = new Date(), config = {}) {
writeRegistry(projects);
}
}
+ if (handle && (existing.boardId !== handle.boardId || existing.owner !== handle.owner || existing.handle !== handle.handle || existing.kind !== 'team')) {
+ Object.assign(existing, handle);
+ writeRegistry(projects);
+ }
return false;
}
const initialMetadata = metadata ?? { name: basename(normalizedRoot), project: '' };
- projects.push({ root: normalizedRoot, ...initialMetadata, added: now.toISOString() });
+ projects.push({ root: normalizedRoot, ...initialMetadata, ...(handle ?? {}), added: now.toISOString() });
writeRegistry(projects);
return true;
});
@@ -287,8 +396,17 @@ export function forgetProject(path) {
}
/** Register locally and complete opted-in automatic relay linking before the CLI returns. */
-export async function registerProjectAndLink(root, now, config, io) {
- const added = registerProject(root, now, config);
+export async function registerProjectAndLink(root, now, config, io, identity) {
+ let exactIdentity = identity;
+ if (!exactIdentity) {
+ const file = join(repoInfo(root).commonDir, 'pullboard', 'board.sqlite');
+ if (existsSync(file)) {
+ const board = store.openBoardForRead(file);
+ try { exactIdentity = projectBoardIdentity(root, store.boardId(board)); }
+ finally { store.closeBoard(board); }
+ }
+ }
+ const added = registerProject(root, now, config, exactIdentity);
const { autoLinkProject } = await import('./relay-setup.js');
await autoLinkProject(root, io);
return added;
diff --git a/src/recorded-move.js b/src/recorded-move.js
index 3fd5384b..57a6d85b 100644
--- a/src/recorded-move.js
+++ b/src/recorded-move.js
@@ -23,7 +23,7 @@ export function recordedMoveRefusal(io, error) {
export function requestedCommandMove(command, operation) {
if (!command) return false;
const forms = {
- add: ['addItem'], companion: ['requestCompanion'], edit: ['editItem'], merged: ['merged'], submit: ['submit'],
+ add: ['addItem'], companion: ['requestCompanion'], edit: ['editItem'], merged: ['merged'], move: ['rehomeItem'], submit: ['submit'],
claim: ['claim'], release: ['release'], verify: ['verify'], withdraw: ['withdraw', 'editMilestoneItems'],
refreeze: ['refreeze'], reopen: ['reopen'], escalate: ['escalate', 'shout'],
next: ['claim', 'reserveReview', 'reserveNextReview'], run: ['claim', 'release', 'submit', 'reserveReview', 'reserveNextReview', 'verify', 'escalate', 'shout'],
diff --git a/src/relay-command-order.js b/src/relay-command-order.js
new file mode 100644
index 00000000..c3375ad5
--- /dev/null
+++ b/src/relay-command-order.js
@@ -0,0 +1,10 @@
+/** Classify requested command intent before an ordered relay refusal is reported. */
+const ORDERED_MOVE_COMMANDS = new Set(['add', 'edit', 'move', 'fact', 'escalate', 'run', 'sweep', 'next', 'claim', 'hold', 'release',
+ 'submit', 'done', 'verify', 'merged', 'land', 'withdraw', 'refreeze', 'shout', 'answer', 'pass', 'import', 'milestone', 'takeover', 'forget', 'join', 'worktree']);
+
+/** Whether the CLI command will make an ordered move whose refusal should be reported at dispatch. */
+export function orderedMoveCommand(io) {
+ const command = io.relayCommand;
+ if (command?.cliOperation === 'spec') return ['approve', 'decline', 'apply'].includes(command.positionals?.[0]);
+ return ORDERED_MOVE_COMMANDS.has(command?.cliOperation);
+}
diff --git a/src/relay-device-poll.js b/src/relay-device-poll.js
index 7712c0d6..f0a7d5bc 100644
--- a/src/relay-device-poll.js
+++ b/src/relay-device-poll.js
@@ -21,4 +21,3 @@ export function waitForDevicePoll(seconds, signal) {
if (signal?.aborted) cancel();
});
}
-
diff --git a/src/relay-machine.js b/src/relay-machine.js
index 79dc161c..1d8d52bc 100644
--- a/src/relay-machine.js
+++ b/src/relay-machine.js
@@ -62,7 +62,9 @@ function validate(state) {
}
if (state.v === 2 && (!/^[A-Za-z0-9_-]{1,128}$/u.test(state.machine ?? '') || !Array.isArray(state.approvals) ||
(state.owner !== null && (!state.owner || typeof state.owner.account !== 'string' || !state.owner.account ||
- typeof state.owner.url !== 'string' || !state.owner.url || Object.keys(state.owner).some(key => !['account', 'url'].includes(key)))))) {
+ typeof state.owner.url !== 'string' || !state.owner.url ||
+ state.owner.login !== undefined && (typeof state.owner.login !== 'string' || !/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/u.test(state.owner.login)) ||
+ Object.keys(state.owner).some(key => !['account', 'url', 'login'].includes(key)))))) {
throw new Refused('RELAY_MACHINE_STORAGE', 'Restore the supported machine identity and phone-link metadata, or sign in again explicitly.');
}
for (const entry of state.approvals ?? []) {
@@ -111,7 +113,7 @@ export function readRelayMachine() {
export function relayMachineOwner() {
const state = readState();
const owner = state.owner ?? (state.session ? { account: state.session.account, url: state.session.url } : null);
- return owner ? { account: owner.account, url: owner.url } : null;
+ return owner ? { account: owner.account, login: owner.login ?? null, url: owner.url } : null;
}
/** Read a public root pinned through native person setup; relay replies never establish this trust. */
diff --git a/src/relay-outbox.js b/src/relay-outbox.js
index 97c98c9d..c40bd72e 100644
--- a/src/relay-outbox.js
+++ b/src/relay-outbox.js
@@ -88,6 +88,13 @@ export async function readOutbox(file, key, boardId) {
return document;
}
+/** The item currently created by a queued move, before the relay has made its number authoritative. */
+export async function outboxHasPendingCreatedItem(file, key, boardId, itemId) {
+ if (!Number.isSafeInteger(itemId) || itemId < 1) return false;
+ const outbox = await readOutbox(file, key, boardId);
+ return Boolean(outbox?.moves.some(entry => entryCreatedItems(entry).some(created => created.item === itemId)));
+}
+
/** Seal and atomically replace the outbox, readable only by this user. */
export async function writeOutbox(file, key, boardId, document) {
// Old clients must refuse richer result bindings rather than treating temporary item numbers as final.
@@ -184,6 +191,8 @@ export const ITEM_SLOTS = Object.freeze({
recordHealthFindings: [], decideSentinel: [], beginSentinelRun: [], finishSentinelRun: [],
recordFlakeObservation: [], recordGateRun: [], recordProofRun: [[0, 'itemId'], [0, 'receipt', 'proof', 'item']], declareJob: [], recordJobRun: [], takeCoordinator: [], openHandoff: [], landingLeaseMove: [],
recordActivityDelivery: [], actOnActivity: [], recordRowVerification: [], setBoardMembers: [],
+ // Re-home IDs are acknowledged-only; foreign board/source IDs are never locally rewritten.
+ reserveRehomeItemId: [], rehomeItem: [[0]], applyRehomeItem: [[0, 'destinationItemId']],
...Object.fromEntries(FIRST_ITEM.map((operation) => [operation, [[0]]])),
intakeOutside: [[0, 'item', 'parentId'], [0, 'item', 'after', '*']],
addItem: [[0, 'parentId'], [0, 'after', '*']],
@@ -240,6 +249,12 @@ function slot(move, path, value) {
/** Keys under which a move might name an item that no declared slot reaches. */
const ITEM_KEYS = /^(id|ids|item|items|itemId|parentId|after|implies|add|remove|skipIds)$/u;
+/** Moves whose IDs and results have to be ordered by the relay; they cannot become provisional outbox state [E15,H16]. */
+export const ACKNOWLEDGED_OPERATIONS = Object.freeze([
+ 'register', 'ensureCoordinator', 'takeCoordinator', 'landingLeaseMove',
+ 'reserveRehomeItemId', 'rehomeItem', 'applyRehomeItem',
+]);
+
/**
* Item numbers of offline adds that a move names outside its declared slots. Such a move is refused rather than
* queued, because the outbox could not follow the item if the relay renumbers it (#922).
@@ -318,7 +333,7 @@ function outboxEnabled(io) {
export function outboxQueueable(state, error, operation, io, args = []) {
return state.mode === 'ordered' && state.baselineAccepted === true && !state.baselineConflict && !state.environment
&& process.env.PULLBOARD_RELAY_TOKEN === undefined && !io?.relayCanary && !io?.personRequest && !io?.personRequestMoveId
- && !['register', 'ensureCoordinator', 'takeCoordinator', 'landingLeaseMove'].includes(operation)
+ && !ACKNOWLEDGED_OPERATIONS.includes(operation)
&& !args.some(arg => arg?.landingFence !== undefined) && transientRelayFailure(error) && outboxEnabled(io);
}
@@ -388,6 +403,9 @@ function bumpGeneration(linkFile) {
*/
export async function queueMove(link, { operation, args, command, move, error, applyLocally, quiet = false }) {
const { root, file, state, io, localRecords, safePauseCode, safePauseMessage } = link;
+ if (ACKNOWLEDGED_OPERATIONS.includes(operation)) {
+ throw new Refused('RELAY_OUTBOX_UNBOUND', 'this move needs the relay to acknowledge its IDs and result; retry it when the relay answers');
+ }
const key = readBoardKey(state.board);
const where = outboxFile(file);
// A new outbox holds no board image: the moves are taken back by their own rows, so queuing costs no export.
diff --git a/src/relay-setup.js b/src/relay-setup.js
index de531833..56d5438e 100644
--- a/src/relay-setup.js
+++ b/src/relay-setup.js
@@ -429,7 +429,7 @@ export async function relayOnAll(address, io, { signal, onPairingURL, onSignIn,
// The view's sign-in links every board itself; a terminal run waits for cards already on the phone.
const waiting = onPairingURL ? [] : waitingLinkApprovals(session);
const waitingIds = new Set(waiting.map(entry => entry.context.id));
- updateRelayMachine(state => { state.autoLink = true; state.owner = { account: session.account, url: session.url }; state.approvals = state.approvals.filter(entry => waitingIds.has(entry.context.id)); });
+ updateRelayMachine(state => { state.autoLink = true; state.owner = { account: session.account, ...(session.login ? { login: session.login } : {}), url: session.url }; state.approvals = state.approvals.filter(entry => waitingIds.has(entry.context.id)); });
const result = await linkProjects(session, io, { onBoardOutcome, waiting: new Set(waiting.map(entry => entry.root)) });
const devices = readRelayMachine().devices.filter(device => device.account === session.account && device.url === session.url);
if (devices.length && !pairAdditional) io.say('Your phone is already paired; the linked boards appear there.');
diff --git a/src/relay-ssh-proof.js b/src/relay-ssh-proof.js
index 1ac391d4..03f4f1cc 100644
--- a/src/relay-ssh-proof.js
+++ b/src/relay-ssh-proof.js
@@ -66,4 +66,3 @@ export async function verifySshVouch(bytes, signature, login, githubKeys, namesp
return sshKeygen(['-Y', 'verify', '-f', join(folder, 'allowed'), '-I', login, '-n', namespace, '-s', join(folder, 'statement.sig')], bytes).status === 0;
});
}
-
diff --git a/src/relay.js b/src/relay.js
index 05826339..6c48e347 100644
--- a/src/relay.js
+++ b/src/relay.js
@@ -1,3 +1,4 @@
+import { orderedMoveCommand } from './relay-command-order.js';
import * as conflictRecords from './relay-conflict-record.js';
import { withRelayExclusion } from './relay-exclusion-state.js';
import { relinkReplacement } from './relay-relink.js';
@@ -141,9 +142,11 @@ import {
transportFailure,
} from './relay-move-fallback.js';
import {
+ ACKNOWLEDGED_OPERATIONS,
flushOutbox,
outboxFields,
outboxFile,
+ outboxHasPendingCreatedItem,
outboxQueueable,
readOutboxSummary,
queueMove,
@@ -204,9 +207,23 @@ const CHECKPOINT_MOVES = new WeakMap();
const BASELINE_FAILURES = new WeakMap();
const AUTH_NOTICES = new WeakSet();
const DELETION_NOTICES = new WeakSet();
-const ORDERED_MOVE_COMMANDS = new Set(['add', 'edit', 'fact', 'escalate', 'run', 'sweep', 'next', 'claim', 'hold', 'release',
- 'submit', 'done', 'verify', 'merged', 'land', 'withdraw', 'refreeze', 'shout', 'answer', 'pass', 'import', 'milestone', 'takeover', 'forget', 'join', 'worktree']);
+/** Refuse a re-home that names an ID still owned by an unacknowledged local add. */
+async function requireAuthoritativeRehomeItem(file, state, itemId) {
+ if (!state || !Number.isSafeInteger(itemId) || itemId < 1 || !existsSync(outboxFile(file))) return;
+ await withOutboxGuard(file, async () => {
+ if (!existsSync(outboxFile(file))) return;
+ if (await outboxHasPendingCreatedItem(outboxFile(file), readBoardKey(state.board), state.board, itemId)) {
+ throw new Refused('RELAY_OUTBOX_UNBOUND', `item #${itemId} is still waiting for relay order; run pullboard status until it is sent, look up the current item ID, then retry the move`);
+ }
+ });
+}
+
+/** Check a selected team item before move-command destination reservation can choose another ID. */
+export async function assertRehomeSourceItemOrdered(root, itemId, io) {
+ const file = linkFile(root);
+ await locked(file, async () => requireAuthoritativeRehomeItem(file, loadLink(file), itemId), io);
+}
/** Find the shared local link metadata without opening a board or connecting for an unlinked repo. */
function linkFile(root) { return relayFiles(repoInfo(root).commonDir).link; }
@@ -496,13 +513,6 @@ export function pendingSnapshotSize(root) {
return snapshotSize(loadLink(linkFile(root)));
}
-/** Whether the CLI command will make an ordered move whose refusal should be reported at dispatch. */
-function orderedMoveCommand(io) {
- const command = io.relayCommand;
- if (command?.cliOperation === 'spec') return ['approve', 'decline', 'apply'].includes(command.positionals?.[0]);
- return ORDERED_MOVE_COMMANDS.has(command?.cliOperation);
-}
-
/** Give a local read a single safe explanation when its signed relay read is refused. */
function reportExpiredSignIn(state, io) {
if (AUTH_NOTICES.has(io)) return;
@@ -1031,7 +1041,7 @@ function localFirstLink(file, operation, args, io) {
|| state.baselineConflict || state.baselinePause || state.baselineStale || state.environment) return null;
if (process.env.PULLBOARD_RELAY_TOKEN !== undefined || io?.relayCanary || io?.personRequest || io?.personRequestMoveId) return null;
// A takeover needs the relay's authenticated sign-in lineage, which only the relay's order carries.
- if (['register', 'ensureCoordinator', 'takeCoordinator', 'landingLeaseMove'].includes(operation) || args?.[0]?.landingFence !== undefined) return null;
+ if (ACKNOWLEDGED_OPERATIONS.includes(operation) || args?.[0]?.landingFence !== undefined) return null;
if (credentialActor({ operation, args }) === 'person') return null;
try { if (io?.relayOutbox?.() !== true) return null; } catch { return null; }
return state;
@@ -1062,6 +1072,7 @@ export async function relayOperation(root, operation, args, io, command, applyLo
if (local) return queueLocally(root, file, local, operation, args, io, command, applyLocally, onRecorded);
return locked(file, async () => {
const state = loadLink(file);
+ if (operation === 'rehomeItem') await requireAuthoritativeRehomeItem(file, state, args?.[0]);
const guarded = landingRelayCallbacks(operation, args, {
apply: () => typeof applyLocally === 'function' ? applyLocally() : localRecords(root, (board) => store[operation](board, ...args)),
queue: (error, move, apply) => queueMove(outboxLink(root, file, state, io), { operation, args, command, move, error, applyLocally: apply }),
@@ -1123,7 +1134,8 @@ export async function relayOperation(root, operation, args, io, command, applyLo
try {
if (!move) {
const sent = withSeatName(root, operation, args);
- move = stampCoordinatorHolder(localRecords(root, (board) => prepareEngineMove(board, operation, sent, io.personRequestMoveId ? { id: io.personRequestMoveId } : {})), state.machine, state.computerName);
+ move = stampCoordinatorHolder(localRecords(root, (board) => prepareEngineMove(board, operation, sent,
+ io.personRequestMoveId ? { id: io.personRequestMoveId } : operation === 'rehomeItem' && io.rehomeMoveId ? { id: io.rehomeMoveId } : {})), state.machine, state.computerName);
requestedMove = move;
if (io.personRequest) move.personRequest = structuredClone(io.personRequest);
const problem = move.personRequest && localRecords(root, board => requestMoveProblem(board, move, { checkExecutorLease: false }));
@@ -1318,7 +1330,7 @@ export async function relayCommandReceipt(root, command) {
if (!state) {
const recovered = deletedRecovery(root);
if (!recovered || recovered.marker.recovered.commandIntent !== intentDigest(operationIntent('cli:' + command.cliOperation, command))) return null;
- const expected = { add: 'addItem', companion: 'requestCompanion', edit: 'editItem', merged: 'merged' }[command.cliOperation];
+ const expected = { add: 'addItem', companion: 'requestCompanion', edit: 'editItem', merged: 'merged', move: 'rehomeItem' }[command.cliOperation];
if (recovered.move.operation !== expected) throw new Refused('RELAY_STORAGE', 'restore the interrupted command receipt before retrying');
if (recovered.receipt.outcome.error) {
clearDeletedRecovery(root, recovered.marker);
@@ -1332,7 +1344,7 @@ export async function relayCommandReceipt(root, command) {
if (recovered.commandIntent !== operationIntent('cli:' + recovered.command?.cliOperation, recovered.command)) {
throw new Refused('RELAY_STORAGE', 'restore the interrupted command metadata before retrying');
}
- const expected = { add: 'addItem', companion: 'requestCompanion', edit: 'editItem', merged: 'merged' }[command.cliOperation];
+ const expected = { add: 'addItem', companion: 'requestCompanion', edit: 'editItem', merged: 'merged', move: 'rehomeItem' }[command.cliOperation];
if (!recovered.move || recovered.move.operation !== expected) throw new Refused('RELAY_STORAGE', 'restore the interrupted command metadata before retrying');
const move = recoveredMove(root, state, recovered.move.operation, recovered.move.args, command);
const receipt = localRecords(root, board => engineReceipt(board, move.id));
diff --git a/src/sync.js b/src/sync.js
index 0aaf432a..163d29d2 100644
--- a/src/sync.js
+++ b/src/sync.js
@@ -236,7 +236,8 @@ export async function gitBoardOperation(root, board, operation, args, io = {}) {
}
if (outcome.error) throw new Refused(outcome.error.code, outcome.error.message, outcome.error.next);
}
- pending = { version: 1, command, at: new Date().toISOString(), move: prepareEngineMove(board, operation, args) };
+ const moveOptions = operation === 'rehomeItem' && io.rehomeMoveId ? { id: io.rehomeMoveId } : {};
+ pending = { version: 1, command, at: new Date().toISOString(), move: prepareEngineMove(board, operation, args, moveOptions) };
save(file.pending, pending);
outcome = await settle(root, board, pending);
if (outcome.error) throw new Refused(outcome.error.code, outcome.error.message, outcome.error.next);
diff --git a/src/templates.js b/src/templates.js
index ee93837b..33a5f2fb 100644
--- a/src/templates.js
+++ b/src/templates.js
@@ -152,6 +152,8 @@ When a reject names a structured cause, add \`--cause <key>\` (\`test:<file>::<t
The coordinator merges verified items into the main line; builders never merge. When a release ships, the coordinator runs \`pullboard milestone ship <name>\`: it records main's commit and moves the items that have not landed into the next milestone. The queue orders itself by what each item unblocks and what it costs; the coordinator holds an item above that order with \`pullboard milestone pin <name> <ids> --reason "<why>"\`, below it with \`pullboard milestone sink <name> <ids> --reason "<why>"\`, and returns it with \`pullboard milestone lift <name> <ids>\`. \`pullboard health\` lists every stuck item: a lapsed claim, a review nobody took, accepted work that never landed, an old hold, an unanswered decision. Each line says why, since when, the next step and who takes it; run it at the start of a session and take the steps that name you.
+**Private work.** \`pullboard add <lane> <title> --private\` keeps an item on this device's private board beside the repo board; ordinary add stays on the repo board. Move an open or verified item with \`pullboard move ~acme/web#3 --to acme/web\`, or use \`pullboard move acme/web#3 --to ~acme/web\` for the reverse direction. Use the repository's qualified handle when a short name is ambiguous. The old item id permanently points to its destination; a source acceptance remains attributed to its original verifier rather than becoming a new destination verdict.
+
**Replay flow.** Run \`pullboard flow replay --json\` to reproduce recorded landing order and stage quartiles from text-free lifecycle history. To compare a hypothetical order and board line settings, run \`pullboard flow replay --history history.json --policy policy.json --json\` with the exported version-1 history and a JSON policy containing \`order\` and \`settings\`. Recorded work durations stay fixed; alternate queue times are deterministic predictions, not measured speedups.
Lane leads are off until the coordinator names an existing lane seat with \`pullboard lanes lead <lane> <seat|off>\`. Questions and blockers sent with \`pullboard shout coordinator "<text>" --kind question|blocker --decision\` reach that lead. The lead answers or uses \`pullboard pass <shout-id> "<why>"\` to escalate to the coordinator; only its decisions and escalations go upward. Status stays activity, not a coordination shout. A lead gains no claim, lease or person-approval authority.
diff --git a/src/verdict-freshness.js b/src/verdict-freshness.js
index cba04be2..8ee39d3b 100644
--- a/src/verdict-freshness.js
+++ b/src/verdict-freshness.js
@@ -95,6 +95,7 @@ export function verdictProjector(root, board, { main } = {}) {
/** Derive pending proof freshness and an older landing's explicitly recorded review mismatch. */
const state = item => {
if (item.item_status !== 'verified') return null;
+ if (item.item_rehome_import?.sourceStatus === 'verified') return null;
const accepted = store.acceptedVerdict(board, item);
const carryProblem = !item.item_merged_commit && mergeOnlyLandingProblem(root, board, item);
if (carryProblem) return { code: 'STALE_VERDICT', reason: carryProblem.message, main: tip ?? null };
diff --git a/src/verdict-reviews.js b/src/verdict-reviews.js
index 0af8027f..03fd4e6a 100644
--- a/src/verdict-reviews.js
+++ b/src/verdict-reviews.js
@@ -41,6 +41,23 @@ export function acceptedVerdict(board, item) {
const latest = verdicts.findLast(verdict =>
verdict.verdict_decision === 'ACCEPT' && verdict.verdict_commit === item.item_commit);
if (latest) return latest.withdrawn ? undefined : latest;
+ if (item.item_status === 'verified') {
+ const row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(`rehome_import:${item.item_id}`);
+ if (row) {
+ let imported;
+ try { imported = JSON.parse(row.meta_value); } catch { imported = null; }
+ const source = (imported?.sourceVerdicts ?? []).findLast(verdict => verdict.verdict_decision === 'ACCEPT'
+ && verdict.verdict_commit === item.item_commit && verdict.verdict_digest === item.item_frozen_digest
+ && verdict.verdict_by === item.item_verified_by && verdict.verdict_by !== item.item_built_by);
+ if (source && imported.sourceStatus === 'verified' && imported.sourceMoveDigest === imported.sourceReceipt?.resultDigest
+ && typeof imported.attestedBy === 'string' && imported.moveId) {
+ return { ...source, verdict_id: `import:${imported.sourceBoardId}:${imported.moveId}:${source.verdict_id}`,
+ assurance: 'imported', imported: { sourceBoardId: imported.sourceBoardId, sourceItemId: imported.sourceItemId,
+ sourceHandle: imported.sourceHandle, moveId: imported.moveId, attestedBy: imported.attestedBy,
+ sourceReceipt: imported.sourceReceipt } };
+ }
+ }
+ }
const event = board.db.prepare("SELECT event_detail FROM event WHERE item_id = ? AND event_kind = 'merge-only-accept' AND json_extract(event_detail,'$.commit') = ? ORDER BY event_id DESC LIMIT 1")
.get(item.item_id, item.item_commit);
if (!event) return undefined;
diff --git a/test/api-catalog.test.js b/test/api-catalog.test.js
index f7ac5a6c..f3924bdb 100644
--- a/test/api-catalog.test.js
+++ b/test/api-catalog.test.js
@@ -30,6 +30,7 @@ import { registerProject } from '../src/projects.js';
import { SSH_SHELL_MARKERS } from '../src/person.js';
import { fetchFresh } from './http-fixture.js';
import { fixtureJSON as intakeFixtureJSON, intakeFixture } from './intake-fixture.js';
+import { relayClientFixture } from './relay-client-fixture.js';
const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');
const TEMP_DIRS = [];
@@ -684,6 +685,27 @@ catalogCase('[A1,A10] view exports a static folder through its JSON variant', as
});
+catalogCase('[A1,E13,E14,E15] move returns its real CLI result across local boards', async (t) => {
+ const box = await relayClientFixture(t);
+ await box.link();
+ const team = await box.cli('add', box.lane, 'Catalog move source');
+ assert.equal(team.code, 0, JSON.stringify(team.document?.error));
+ const local = await box.cli('add', box.lane, 'Catalog move destination', '--private');
+ assert.equal(local.code, 0, JSON.stringify(local.document?.error));
+
+ const shape = shapeFor('move');
+ const moved = await box.cli('move', String(team.document.item.item_id), '--to', '~fixture/repository');
+ assert.equal(moved.code, 0, JSON.stringify(moved.document?.error));
+ assertRequiredShape(moved.document, shape.required, 'move');
+ assert.equal(moved.document.source, `fixture/repository#${team.document.item.item_id}`);
+ assert.equal(moved.document.item.moveId, moved.document.moveId);
+ assert.equal(moved.document.item.sourceItemId, team.document.item.item_id);
+ assert.notEqual(moved.document.item.destinationItemId, local.document.item.item_id, 'the moved item gets a new private-board ID');
+ assert.equal(moved.document.destination, `~fixture/repository#${moved.document.item.destinationItemId}`);
+ assert.match(moved.document.moveId, /^[0-9a-f-]{36}$/u);
+ assert.equal(moved.document.item.item.item_title, 'Catalog move source');
+});
+
catalogCase('[A1] catalog commands keep their real repository exercises', async () => {
const source = await project();
const target = await project();
diff --git a/test/machine.test.js b/test/machine.test.js
index 7326e406..1f582e78 100644
--- a/test/machine.test.js
+++ b/test/machine.test.js
@@ -467,7 +467,8 @@ test('the declared lifecycle is sound: reachable, no traps, no second door, ever
assert.deepEqual(machineProblems(), []);
assert.deepEqual(MACHINE.states.map((state) => state.id), ['open', 'claimed', 'submitted', 'verified', 'withdrawn']);
assert.deepEqual(MACHINE.states.filter((state) => state.final).map((state) => state.id), ['withdrawn']);
- assert.deepEqual(MACHINE.moves.map((move) => move.verb), ['intake', 'claim', 'release', 'lapse', 'submit', 'submit-merge', 'reserve', 'accept', 'reject', 'reopen', 'escalate', 'refreeze', 'refreeze', 'withdraw']);
+ assert.deepEqual(MACHINE.moves.map((move) => move.verb), ['rehomeImport', 'intake', 'claim', 'release', 'lapse', 'submit', 'submit-merge', 'reserve', 'accept', 'reject', 'reopen', 'escalate', 'refreeze', 'refreeze', 'withdraw']);
+ assert.deepEqual(MACHINE.moves.find((move) => move.verb === 'rehomeImport').sets, ['item_verified_by', 'item_commit']);
});
for (const broken of BROKEN) {
@@ -728,7 +729,9 @@ test('the board file refuses, written by hand: an unknown state, an undeclared m
const raw = lab.raw();
const refused = (sql, args, code) => assert.throws(() => raw.prepare(sql).run(...args), new RegExp(code), sql);
refused('UPDATE item SET item_status = ? WHERE item_id = ?', ['shipped', open], 'UNDECLARED_STATE');
- refused('UPDATE item SET item_status = ? WHERE item_id = ?', ['verified', open], 'UNDECLARED_MOVE');
+ refused('UPDATE item SET item_status = ? WHERE item_id = ?', ['verified', open], 'MISSING_FIELD');
+ refused("UPDATE item SET item_status = 'verified', item_verified_by = 'web-2', item_commit = ?, item_frozen_digest = 'digest:Forged', item_built_by = 'web-1' WHERE item_id = ?",
+ [SHA_A, open], 'NOT_PROVEN');
refused("UPDATE item SET item_status = 'verified', item_verified_by = 'web-2' WHERE item_id = ?", [built], 'NOT_PROVEN');
forgeAccept(raw, built, 'web-1', SHA_A);
refused("UPDATE item SET item_status = 'verified', item_verified_by = 'web-1' WHERE item_id = ?", [built], 'NOT_PROVEN');
@@ -809,7 +812,7 @@ test('an older board gets the triggers quietly on its next open; one dropped by
assert.deepEqual(triggerNames(restored), every);
const logged = restored.db.prepare("SELECT event_by, event_detail FROM event WHERE event_kind = 'guards'").all();
assert.deepEqual(logged.map((row) => [row.event_by, JSON.parse(row.event_detail)]), [['board', { missing: ['machine_proof_verified'], changed: ['machine_item_move'], stale: [] }]]);
- assert.throws(() => lab.raw().prepare("UPDATE item SET item_status = 'verified' WHERE item_id = ?").run(id), /UNDECLARED_MOVE/);
+ assert.throws(() => lab.raw().prepare("UPDATE item SET item_status = 'verified' WHERE item_id = ?").run(id), /MISSING_FIELD/);
} finally {
store.closeBoard(restored);
}
@@ -822,14 +825,19 @@ test('the triggers come from the declaration, so a changed declaration changes t
const moveSql = (machine) => storeTriggers(machine).find(({ name }) => name === 'machine_item_move').sql;
const pairs = MACHINE.moves.flatMap((move) => move.from.filter((from) => from !== move.to).map((from) => `'${from}>${move.to}'`));
for (const pair of pairs) assert.ok(moveSql(MACHINE).includes(pair), `the move trigger allows ${pair}`);
- // Intake and a locally proved merge carry are declared; open>verified still has no direct door.
- assert.ok(!moveSql(MACHINE).includes("'open>verified'"));
+ // The only open-to-verified edge is the source-acceptance import, not a direct verdict.
+ assert.deepEqual(MACHINE.moves.filter((move) => move.from.includes('open') && move.to === 'verified').map((move) => move.verb), ['rehomeImport']);
+ assert.ok(moveSql(MACHINE).includes("'open>verified'"));
const machine = copy();
- machine.moves.push({ verb: 'testDirectVerdict', from: ['open'], to: 'verified', by: ['coordinator'], refuse: 'CLOSED', guards: ['joined', 'coordinatorOnly', 'itemExists', IN_STATE], sets: ['item_built_by', 'item_commit', 'item_frozen_digest'] });
- assert.ok(moveSql(machine).includes("'open>verified'"));
+ machine.moves.push({ verb: 'testDirectVerdict', from: ['withdrawn'], to: 'verified', by: ['coordinator'], refuse: 'CLOSED', guards: ['joined', 'coordinatorOnly', 'itemExists', IN_STATE], sets: ['item_built_by', 'item_commit', 'item_frozen_digest'] });
+ assert.ok(!moveSql(MACHINE).includes("'withdrawn>verified'"));
+ assert.ok(moveSql(machine).includes("'withdrawn>verified'"));
const names = storeTriggers().map(({ name }) => name);
for (const state of MACHINE.states.filter((entry) => entry.requires.length)) assert.ok(names.includes(`machine_fields_${state.id}`), `${state.id} has a fields trigger`);
assert.ok(names.includes('machine_proof_verified'));
+ const proof = storeTriggers().find(({ name }) => name === 'machine_proof_verified').sql;
+ assert.match(proof, /AND NOT \(EXISTS[\s\S]+ OR EXISTS[\s\S]+\)\nBEGIN/u,
+ 'the imported proof alternative stays inside the verified proof refusal condition');
});
test("a verified item's proof cannot be rewritten afterwards: its commit, builder, verifier or criterion [M3]", () => {
@@ -1345,7 +1353,7 @@ test('the lifecycle page and the help show the reservation: reserve, and reviewF
assert.match(page, /^\| reserve \| submitted \| submitted \| agent, coordinator \| .*reviewFree \(REVIEW_HELD\), result \(BAD_DEPENDENCIES\) \|$/m);
for (const verb of ['accept', 'reject']) assert.match(page, new RegExp(`^\\| ${verb} \\| submitted, verified \\| .*policyAllows \\(COORDINATOR_VERIFIES\\), familyAllows \\(O2_FAMILY_MATCH\\), reviewFree \\(REVIEW_HELD\\), criterionUnchanged`, 'm'));
assert.match(page, /^\| REVIEW_HELD \| no other agent holds its review under a live lease \| pullboard next --verify/m);
- assert.match(HELP.all, /^ {2}agent +intake, claim, release, submit, reserve, accept, reject, reopen, escalate, submit-merge \(when only an unchanged accepted bar and a proved trunk-only merge; no new reviewer verdict is created\), refreeze \(when a live claim has a pending coordinator correction\)$/m);
+ assert.match(HELP.all, /^ {2}agent +rehomeImport, intake, claim, release, submit, reserve, accept, reject, reopen, escalate, submit-merge \(when only an unchanged accepted bar and a proved trunk-only merge; no new reviewer verdict is created\), refreeze \(when a live claim has a pending coordinator correction\)$/m);
assert.match(HELP.all, /pullboard next --verify +reserve the next submitted item you can check/);
});
diff --git a/test/move-registry.test.js b/test/move-registry.test.js
index 71ec5b53..c2a710ae 100644
--- a/test/move-registry.test.js
+++ b/test/move-registry.test.js
@@ -24,9 +24,27 @@ import { importsIn } from '../src/module-imports.js';
import { readdirSync } from 'node:fs';
import { minimumMoveEngine } from '../src/move-registry.js';
import { SPEC_REVISION_ENGINE } from '../src/spec-revision-engine.js';
+import { PRIVATE_REHOME_ENGINE } from '../src/private-rehome-engine.js';
const SNAPSHOT = JSON.parse(readFileSync(new URL('./move-registry-baseline.json', import.meta.url), 'utf8'));
const CONSUMERS = ['src/engine.js', 'src/relay-sender.js', 'src/next-step-words.js'];
+const REHOME_OPERATIONS = ['reserveRehomeItemId', 'rehomeItem', 'applyRehomeItem'];
+const REHOME_STEPS = Object.freeze({
+ BAD_ITEM_ID: 'use owner/repo#id, ~owner/repo#id, or one safe positive item number on the current board',
+ PRIVATE_BOARD_NOT_FOUND: "run pullboard add <lane> <title> --private from that repo's checkout before using its private handle",
+ PRIVATE_BOARD_IDENTITY: 'open the original repo checkout under its recorded GitHub login; keep the existing private board files and identity intact',
+ ITEM_MOVED: 'use the recorded destination reference shown in the refusal; do not move the old ID again',
+ REHOME_PENDING: 'retry the same move ID and destination to finish delivery; do not allocate another destination ID',
+ REHOME_FORMAT: 'restore the exact source move record and retry it with an authorized destination handle',
+ REHOME_LINKS: 'move each parent or wait item to this destination first, then retry the same source MOVEID',
+ REHOME_SAME_BOARD: 'choose a different local board',
+ REHOME_STATE: 'open or verified items can move; keep other items on their current board',
+ REHOME_CHECK: 'keep the source check unchanged and choose a destination board whose policy accepts it',
+ REHOME_DESTINATION: 'apply the source move on its named destination board',
+ REHOME_CONFLICT: 'keep the original source move ID and resolve the destination board conflict before retrying',
+ REHOME_ID: 'preserve the source MOVEID and its reserved destination ID; resolve the item-ID conflict before retrying',
+ REHOME_VERDICT: 'keep the source board acceptance intact and inspect its exact commit, digest and verifier reference',
+});
/** Hash the real consumer bytes so seed declarations cannot quietly edit a central list. */
function consumerHashes(root) {
@@ -53,8 +71,8 @@ export default { operation: ${JSON.stringify(name)}, order: ${engine + 1000}, en
}
test('today\'s move order, actors, refusal recovery text and recorded SQLite prefix are unchanged [C7,V4,H3,H16]', t => {
- assert.deepEqual(ENGINE_OPERATIONS, SNAPSHOT.operations);
- assert.deepEqual(NEXT_STEPS, SNAPSHOT.nextSteps);
+ assert.deepEqual(ENGINE_OPERATIONS.filter(operation => !REHOME_OPERATIONS.includes(operation)), SNAPSHOT.operations);
+ assert.deepEqual(NEXT_STEPS, { ...SNAPSHOT.nextSteps, ...REHOME_STEPS });
assert.equal(minimumMoveEngine('recordProofRun', [{ landingFence: {}, receipt: { environment: {} } }, { cause: 'conflict:new' }]), PROOF_RUN_ENGINE);
assert.equal(MOVE_REGISTRY.recordProofRun.engine, PROOF_RUN_ENGINE);
assert.equal(MOVE_REGISTRY.recordProofRun.itemIdFirstArgument, false);
@@ -63,6 +81,10 @@ test('today\'s move order, actors, refusal recovery text and recorded SQLite pre
for (const operation of SNAPSHOT.operations) {
assert.deepEqual(SNAPSHOT.actorVectors.map(vector => relayMoveActor({ operation, ...vector })), SNAPSHOT.actors[operation], operation);
}
+ assert.equal(relayMoveActor({ operation: 'reserveRehomeItemId', args: ['0'.repeat(32), 'move-1', { agentId: 'destination' }] }), 'destination');
+ assert.equal(relayMoveActor({ operation: 'rehomeItem', args: [1, { agentId: 'source' }] }), 'source');
+ assert.equal(relayMoveActor({ operation: 'applyRehomeItem', args: [{}, { destinationAgentId: 'destination' }] }), 'destination');
+ for (const operation of REHOME_OPERATIONS) assert.equal(minimumMoveEngine(operation, []), PRIVATE_REHOME_ENGINE, `${operation} uses the declared re-home floor`);
assert.equal(relayMoveActor({ operation: 'toString', args: [] }), null, 'object prototype names are not moves');
const directory = mkdtempSync(join(tmpdir(), 'pullboard-registry-replay-'));
const board = store.openBoard(join(directory, 'replica.sqlite'), { now: () => new Date(REGISTRY_AT) });
@@ -171,13 +193,13 @@ process.stdout.write(JSON.stringify(result));`;
const result = JSON.parse(run(root, process.execPath, ['--input-type=module', '-e', child]));
assert.ok(result.operations.includes('seedAlpha'), 'the first independent operation file is discovered');
assert.ok(result.operations.includes('seedBeta'), 'the second independent operation file is discovered');
- assert.deepEqual(result.operations.filter(name => !name.startsWith('seed')), SNAPSHOT.operations, 'existing order does not move');
+ assert.deepEqual(result.operations.filter(name => !name.startsWith('seed') && !REHOME_OPERATIONS.includes(name)), SNAPSHOT.operations, 'existing order does not move');
assert.deepEqual(result.seedFloors, [9, 11]);
assert.equal(result.pureImportClosure, true, 'routing metadata never imports its consumers, board writers or Git/process launchers');
assert.equal(result.alphaActor, 'seed-agent');
assert.equal(result.alphaStep, 'repair the first seeded move');
assert.equal(result.betaStep, 'repair the second seeded move');
- assert.deepEqual(result.itemIds.filter(name => !name.startsWith('seed')).sort(), [...SNAPSHOT.itemIdFirstArgument].sort());
+ assert.deepEqual(result.itemIds.filter(name => !name.startsWith('seed')).sort(), [...SNAPSHOT.itemIdFirstArgument, 'rehomeItem'].sort());
assert.ok(result.itemIds.includes('seedAlpha'));
assert.ok(!result.itemIds.includes('seedBeta'));
assert.deepEqual(result.floors, SNAPSHOT.floorCases.map(entry => entry.expected), 'all historical first-match floor vectors retain their results');
diff --git a/test/private-board-move-fixture.js b/test/private-board-move-fixture.js
new file mode 100644
index 00000000..ab1cab97
--- /dev/null
+++ b/test/private-board-move-fixture.js
@@ -0,0 +1,657 @@
+/** @pullboard-test-loads src/relay-machine.js */
+/** Real private-board CLI and ordered-replay fixture controls [E11,E13,E14,E15,H16]. */
+import assert from 'node:assert/strict';
+import { chmodSync, existsSync } from 'node:fs';
+import { mkdirSync } from 'node:fs';
+import { readFileSync } from 'node:fs';
+import { writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { dirname } from 'node:path';
+import { DatabaseSync } from 'node:sqlite';
+import * as store from '../src/board.js';
+import { exportBoard } from '../src/exchange.js';
+import { importBoard } from '../src/exchange.js';
+import { appliedSequence } from '../src/engine.js';
+import { applyEngineMove } from '../src/engine.js';
+import { applyRelayMove } from '../src/engine.js';
+import { engineReceipt } from '../src/engine.js';
+import { prepareEngineMove } from '../src/engine.js';
+import { ENGINE_VERSION } from '../src/machine.js';
+import { REFERENCE_ENGINE } from '../src/reference-engine.js';
+import { preparePersonRequest } from '../src/person-request.js';
+import { personRequestRecords } from '../src/relay-requests.js';
+import { decodeBoardKey, seal } from '../src/seal.js';
+import { privateBoardPath } from '../src/projects.js';
+import { heartbeatSeat } from '../src/seat-presence.js';
+import { runFixtureGit } from './fixture-child.js';
+import { submitFixture } from './board-submit-fixture.js';
+import { enrollProtocolPhone } from './relay-device-enrollment-fixture.js';
+
+/** Open only an explicitly named private fixture SQLite file and always close its connection. */
+function withMoveBoard(file, work) {
+ const board = store.openBoard(file);
+ try { return work(board); }
+ finally { store.closeBoard(board); }
+}
+
+/** Capture move-relevant native state, including reserved IDs, without local cache or heartbeat noise. */
+function moveState(file) {
+ return withMoveBoard(file, board => ({
+ items: board.db.prepare('SELECT * FROM item ORDER BY item_id').all(),
+ verdicts: board.db.prepare('SELECT * FROM verdict ORDER BY verdict_id').all(),
+ moves: board.db.prepare("SELECT * FROM event WHERE event_kind IN ('rehome','rehome_reserved','rehome_import','rehome_applied') ORDER BY event_id").all(),
+ bindings: board.db.prepare("SELECT * FROM board_meta WHERE meta_key GLOB 'item_rehome*' OR meta_key GLOB 'item_redirect:*' OR meta_key GLOB 'rehome_import:*' ORDER BY meta_key").all(),
+ sequence: board.db.prepare("SELECT seq FROM sqlite_sequence WHERE name='item'").get(),
+ }));
+}
+
+/** Enable the linked fixture's real local-first setting before testing acknowledged re-home moves. */
+function enableRehomeOutbox(box, root) {
+ const file = join(root, 'pullboard.json');
+ const config = JSON.parse(readFileSync(file, 'utf8'));
+ writeFileSync(file, JSON.stringify({ ...config, relay: { ...(config.relay ?? {}), outbox: true } }, null, 2) + '\n');
+ runFixtureGit(['add', 'pullboard.json'], { cwd: root, env: box.env });
+ runFixtureGit(['commit', '-q', '-m', 'chore(config): enable the linked local-first outbox [H21]'], { cwd: root, env: box.env });
+}
+
+/** Read only the key-free summary used by public relay status, never the sealed outbox payload. */
+function outboxOperations(box) {
+ const file = join(dirname(box.linkFile), 'relay-outbox.summary.json');
+ if (!existsSync(file)) return [];
+ return JSON.parse(readFileSync(file, 'utf8')).moves.map(move => move.operation);
+}
+
+/** Initialize a real local repository using the already authenticated fixture's isolated machine home. */
+async function moveRepository(box, name, owner) {
+ const root = join(box.root, '..', name);
+ mkdirSync(root);
+ runFixtureGit(['init', '-q', '-b', 'main'], { cwd: root, env: box.env });
+ writeFileSync(join(root, 'README.md'), 'private board move fixture\n');
+ runFixtureGit(['add', 'README.md'], { cwd: root, env: box.env });
+ runFixtureGit(['commit', '-q', '-m', 'fixture move repository'], { cwd: root, env: box.env });
+ runFixtureGit(['remote', 'add', 'origin', `[email protected]:${owner}/web.git`], { cwd: root, env: box.env });
+ const initialized = await box.cliAt(root, 'init', '--model', 'fixture-model');
+ assert.equal(initialized.code, 0, JSON.stringify(initialized.document?.error));
+ return root;
+}
+
+/** Seed genuine native lifecycle records; this synthetic acceptance does not claim a gate or review ran. */
+function privateMoveStatus(file, id, status, root, lane, commit) {
+ return withMoveBoard(file, board => {
+ const builder = store.register(board, { lane, path: join(root, `builder-${id}`), model: 'fixture-builder' });
+ const reviewer = store.register(board, { lane, path: join(root, `reviewer-${id}`), model: 'fixture-reviewer' });
+ const digest = `private-move-${id}`;
+ store.claim(board, id, { agentId: builder, lane, leaseMs: 3_600_000, head: commit,
+ freeze: item => ({ text: JSON.stringify({ criterion: item.item_criterion, rows: [],
+ policy: { version: 1, commit, verify: { policy: 'any', family: 'off' } } }), digest }) });
+ if (status !== 'claimed') submitFixture(board, id, { agentId: builder, commit, tree: 'fixture-tree' });
+ if (status === 'verified') store.verify(board, id, { agentId: reviewer, decision: 'ACCEPT',
+ note: 'Synthetic native acceptance for source attribution; no executed review is claimed.',
+ head: commit, digest, policy: 'any' });
+ return { builder, reviewer, commit, digest };
+ });
+}
+
+/** Replay the exact destination operation in an isolated native replica, retaining all source attribution. */
+function assertMoveReplay(file, record, id) {
+ const document = withMoveBoard(file, exportBoard);
+ const replica = store.openBoard(':memory:');
+ try {
+ importBoard(replica, document);
+ const before = exportBoard(replica);
+ assert.equal(store.applyRehomeItem(replica, record, { destinationAgentId: 'coordinator' }), id);
+ assert.deepEqual(exportBoard(replica), before, 'same-source-MOVEID redelivery creates no item, verdict, event or receipt');
+ const receipts = before.tables.board_meta.filter(row => row.meta_key.startsWith('relay_receipt_'))
+ .map(row => JSON.parse(row.meta_value));
+ const receipt = receipts.find(row => {
+ const move = JSON.parse(row.move);
+ return move.operation === 'applyRehomeItem' && move.args[0]?.moveId === record.moveId;
+ });
+ assert.ok(receipt, 'the CLI delivered this source MOVEID in a real ordered destination envelope');
+ const move = JSON.parse(receipt.move);
+ const outcome = applyEngineMove(replica, move, { sequence: receipt.sequence, at: new Date().toISOString() });
+ assert.deepEqual(outcome, receipt.outcome, 'exact ordered replay returns the original receipt');
+ assert.equal(outcome.result, id);
+ assert.deepEqual(exportBoard(replica), before, 'exact ordered replay changes no native row');
+ } finally { store.closeBoard(replica); }
+}
+
+/** Add a handled source reference through the real phone request, relay journal and native coordinator. */
+async function authenticatedPersonAdd(box, root, { requestId, title, criterion, brief }) {
+ const teamFile = join(root, '.git', 'pullboard', 'board.sqlite');
+ const link = JSON.parse(readFileSync(join(root, '.git', 'pullboard', 'relay.json'), 'utf8'));
+ const minimum = box.auth.minimumEngineVersion(link.board);
+ assert.ok(ENGINE_VERSION >= minimum, 'the fixture client meets this linked board’s retained engine floor');
+ const phone = await box.phoneSession();
+ const headers = { authorization: 'Bearer ' + phone.token, 'x-pullboard-engine': String(ENGINE_VERSION) };
+ const stateResponse = await fetch(box.origin + '/api/v2/boards/' + link.board + '/state', { headers });
+ const stateReply = await stateResponse.json();
+ assert.equal(stateResponse.status, 200, JSON.stringify(stateReply.error ?? {}));
+ const state = stateReply.state;
+ assert.ok(Number.isSafeInteger(state.sequence) && state.sequence >= 0, 'the snapshot supplies the event cursor');
+ const eventsResponse = await fetch(box.origin + '/api/v1/boards/' + link.board + '/events?after=' + state.sequence, { headers });
+ const eventsReply = await eventsResponse.json();
+ assert.equal(eventsResponse.status, 200, JSON.stringify(eventsReply.error ?? {}));
+ const prefix = eventsReply;
+ assert.ok(Array.isArray(prefix.events), 'the relay returns ordered events after the snapshot cursor');
+ const sequence = Math.max(state.sequence, ...prefix.events.map(event => event.event_id)) + 1;
+ const intent = preparePersonRequest({ verb: 'add', args: { lane: box.lane, title, criterion, brief, route: 'strong' } }, requestId);
+ const keyPath = join(box.env.PULLBOARD_HOME, 'relay-keys', link.board + '.key');
+ const key = decodeBoardKey(readFileSync(keyPath, 'utf8').trim());
+ const encrypted = await seal(key, new TextEncoder().encode(JSON.stringify(intent)), {
+ boardId: link.board, kind: 'request', sequence,
+ });
+ const posted = await fetch(box.origin + '/api/v1/boards/' + link.board + '/requests', {
+ method: 'POST', headers: { ...headers, 'content-type': 'application/json' },
+ body: JSON.stringify({ sequence, sealed: Buffer.from(encrypted).toString('base64url') }),
+ });
+ assert.equal(posted.status, 200, 'the authenticated person request is appended to the relay journal');
+ const accepted = await posted.json();
+ assert.equal(accepted.event.kind, 'request');
+ assert.equal(accepted.event.event_id, sequence);
+ const executed = await box.cliAt(root, 'relay');
+ assert.equal(executed.code, 0, JSON.stringify(executed.document?.error));
+ return withMoveBoard(teamFile, board => {
+ const request = personRequestRecords(board).find(record => record.id === requestId && !record.duplicateOf);
+ assert.ok(request, 'the native board retained the authenticated request receipt');
+ assert.equal(request.status, 'done');
+ const intake = JSON.parse(request.received);
+ assert.equal(intake.sender.kind, 'person');
+ assert.equal(intake.sender.login, 'alice');
+ const receipts = board.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key GLOB 'relay_receipt_*'").all()
+ .map(row => JSON.parse(row.meta_value));
+ const matching = receipts.filter(receipt => {
+ const move = JSON.parse(receipt.move);
+ return move.operation === 'addItem' && move.personRequest?.id === requestId
+ && move.personRequest?.phase === 'execute' && move.args[0]?.title === title;
+ });
+ assert.equal(matching.length, 1, 'exactly one native add receipt fulfils the person request');
+ const sourceReceipt = matching[0];
+ const recordedMove = JSON.parse(sourceReceipt.move);
+ assert.ok(recordedMove.engine >= REFERENCE_ENGINE, 'the accepted request uses checked-reference engine semantics');
+ assert.equal(recordedMove.args[0].brief, brief, 'the ordered receipt is bound to the exact handled brief');
+ assert.equal(sourceReceipt.outcome.result, request.result, 'the request result identifies the receipt’s source item');
+ const event = board.db.prepare("SELECT event_by,event_detail FROM event WHERE event_kind='add' AND item_id=?").get(request.result);
+ assert.equal(event.event_by, 'person', 'the native add is attributed to the person request');
+ assert.equal(JSON.parse(event.event_detail).person, 'alice', 'the source event retains the authenticated person login');
+ assert.equal(engineReceipt(board, recordedMove.id).outcome.result, request.result);
+ return request.result;
+ });
+}
+
+/** Supply only the one public GitHub issue author needed by this isolated relay fixture. */
+function installReferenceAuthorFixture(box) {
+ const path = join(box.env.PATH, 'gh');
+ if (!existsSync(path)) {
+ writeFileSync(path, [
+ '#!/bin/sh',
+ 'if [ "$#" -eq 8 ] && [ "$1" = api ] && [ "$2" = --method ] && [ "$3" = GET ] && [ "$4" = repos/fixture/repository/issues/6 ] && [ "$5" = --header ] && [ "$6" = "Accept: application/vnd.github+json" ] && [ "$7" = --header ] && [ "$8" = "X-GitHub-Api-Version: 2022-11-28" ]; then',
+ " printf '%s\\n' '{\"user\":{\"login\":\"issue-author\"}}'",
+ 'else',
+ ' exit 64',
+ 'fi',
+ ].join('\n') + '\n');
+ chmodSync(path, 0o700);
+ }
+}
+
+/** Age an existing authenticated fixture seat observation without inventing an actor or shared event. */
+function agePrivateHeartbeat(file, root) {
+ const key = withMoveBoard(file, board => {
+ const actor = store.agentAt(board, root);
+ assert.ok(actor, 'the real private add already registered this checkout');
+ assert.equal(heartbeatSeat(board, actor.agent_id), true, 'seed only this real private seat observation');
+ return JSON.stringify([store.boardId(board), actor.agent_id]);
+ });
+ const db = new DatabaseSync(file + '.presence.sqlite');
+ const at = new Date(Date.now() - 120_000).toISOString(); // budget: measured stale age only; no elapsed-time margin is asserted.
+ try { assert.equal(db.prepare('UPDATE heartbeat SET at=? WHERE seat=?').run(at, key).changes, 1); } // budget: measured row count only; this seeds stale state and does not assert elapsed time.
+ finally { db.close(); }
+ return { key, at };
+}
+
+/** Require a real successful private command to refresh the deliberately stale local observation. */
+function assertPrivateHeartbeat(file, before) {
+ const db = new DatabaseSync(file + '.presence.sqlite', { readOnly: true });
+ try {
+ const row = db.prepare('SELECT at FROM heartbeat WHERE seat=?').get(before.key);
+ assert.ok(row && Date.parse(row.at) > Date.parse(before.at), 'the private write refreshes its stale heartbeat');
+ } finally { db.close(); }
+}
+
+/** Private local writes never acquire a relay receipt or publish their private board identity. */
+function assertPrivateTransportIsolation(box, file) {
+ withMoveBoard(file, board => {
+ assert.equal(board.db.prepare("SELECT COUNT(*) AS n FROM board_meta WHERE meta_key GLOB 'relay_receipt_*'").get().n, 0,
+ 'private source operations have no ordered relay receipt');
+ const id = store.boardId(board);
+ assert.equal(box.calls.some(call => call.path.includes(id)), false, 'private board identity never addresses the shared relay');
+ });
+}
+
+/** Distinct repository origins disambiguate private boards owned by the same signed-in person. */
+async function privateHandleCollision(box, root, bobRoot, teamFile, localFile, openId) {
+ const bobTeamFile = join(bobRoot, '.git', 'pullboard', 'board.sqlite');
+ const bobPrivateFile = privateBoardPath(withMoveBoard(bobTeamFile, store.boardId), box.env.PULLBOARD_HOME);
+ for (const title of ['other private one', 'other private two', 'other private open move']) {
+ const added = await box.cliAt(bobRoot, 'add', box.lane, title, '--private');
+ assert.equal(added.code, 0, JSON.stringify(added.document?.error));
+ }
+ assert.notEqual(withMoveBoard(localFile, store.boardId), withMoveBoard(bobPrivateFile, store.boardId));
+ for (const file of [localFile, bobPrivateFile]) withMoveBoard(file, board => {
+ const reference = JSON.parse(board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get('private_board_reference').meta_value);
+ assert.equal(reference.owner, 'alice', 'the same signed-in person owns both private boards');
+ });
+ const files = [localFile, teamFile, bobPrivateFile, bobTeamFile];
+ const before = files.map(moveState);
+ for (const [source, destination] of [['~web#3', 'acme/web'], [`acme/web#${openId}`, '~web']]) {
+ const ambiguous = await box.cliAt(root, 'move', source, '--to', destination);
+ assert.notEqual(ambiguous.code, 0);
+ assert.equal(ambiguous.document.error.code, 'BOARD_REFERENCE');
+ assert.match(ambiguous.document.error.message, /~acme\/web/u);
+ assert.match(ambiguous.document.error.message, /~bob\/web/u);
+ }
+ assert.deepEqual(files.map(moveState), before, 'ambiguous private handles do not mutate either source or destination board');
+ const moved = await box.cliAt(bobRoot, 'move', '~bob/web#3', '--to', 'bob/web');
+ assert.equal(moved.code, 0, JSON.stringify(moved.document?.error));
+ assert.equal(moved.document.source, '~bob/web#3');
+ const record = moved.document.item;
+ assert.equal(record.sourceBoardId, withMoveBoard(bobPrivateFile, store.boardId));
+ withMoveBoard(bobTeamFile, board => assert.equal(store.getItem(board, record.destinationItemId).item_title, 'other private open move'));
+ assertMoveReplay(bobTeamFile, record, record.destinationItemId);
+}
+
+/** Exercise real CLI handles and both move directions beside the original linked-device privacy controls. */
+export async function privateBoardMoves(box, privateFile) {
+ Object.assign(box.providerState, {
+ signer: 'alice',
+ people: { alice: { id: 7, permission: 'write' }, bob: { id: 8, permission: 'write' } },
+ qualifiedRepositories: {
+ 'acme/web': { id: 201, installationId: 43,
+ people: { alice: { id: 7, permission: 'write' } } },
+ 'bob/web': { id: 202, installationId: 44,
+ people: { alice: { id: 7, permission: 'write' }, bob: { id: 8, permission: 'write' } } },
+ },
+ });
+ const root = await moveRepository(box, 'acme-web', 'acme');
+ const bobRoot = await moveRepository(box, 'bob-web', 'bob');
+ await enrollProtocolPhone(box);
+ const signedIn = await box.cli('relay', 'on', '--all', '--url', box.origin);
+ assert.equal(signedIn.code, 0, 'the real machine sign-in writer records its GitHub login: ' + JSON.stringify(signedIn.document?.error));
+ assert.equal(signedIn.document.paired, true, 'existing authenticated protocol enrollment avoids waiting for a new browser pairing');
+ const owner = await box.script(`
+ import { relayMachineOwner } from ${JSON.stringify(new URL('../src/relay-machine.js', import.meta.url).href)};
+ const owner = relayMachineOwner();
+ process.stdout.write(JSON.stringify({ account: owner.account, login: owner.login }));
+ `);
+ assert.equal(owner.code, 0);
+ assert.deepEqual(owner.document, { account: '7', login: 'alice' }, 'the numeric account stays separate from its authenticated login');
+ const addHeartbeat = agePrivateHeartbeat(privateFile, box.root);
+ const callsBeforePrivateAdd = box.calls.length;
+ const linkedPrivate = await box.cli('add', box.lane, 'private item delivered through the relay', '--private');
+ assert.equal(linkedPrivate.code, 0);
+ assert.equal(box.calls.length, callsBeforePrivateAdd, 'a successful private add makes no shared request or publication');
+ assertPrivateHeartbeat(privateFile, addHeartbeat);
+ assertPrivateTransportIsolation(box, privateFile);
+ const sharedBeforeMove = withMoveBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'), exportBoard);
+ assert.equal(JSON.stringify(sharedBeforeMove).includes('private item delivered through the relay'), false,
+ 'private add does not place its prose in shared native history');
+ const linkedId = linkedPrivate.document.item.item_id;
+ const moveHeartbeat = agePrivateHeartbeat(privateFile, box.root);
+ let sourceAtDelivery = null;
+ box.beforeNextMove(() => {
+ assert.equal(withMoveBoard(privateFile, board => store.itemRedirect(board, linkedId)), null,
+ 'destination reservation precedes the durable private source move');
+ box.beforeNextMove(() => {
+ sourceAtDelivery = withMoveBoard(privateFile, board => store.itemRedirect(board, linkedId));
+ assert.ok(sourceAtDelivery, 'the private source move is durable before destination delivery');
+ box.refuseReads(true); // The real relay accepts delivery, then its event read refuses, as in relay-outbox.test.js.
+ });
+ });
+ let interrupted;
+ try { interrupted = await box.cli('move', `~repository#${linkedId}`, '--to', 'fixture/repository'); }
+ finally { box.refuseReads(false); }
+ assert.ok(sourceAtDelivery, 'the destination failure control was exercised after source commit');
+ assert.equal(interrupted.code, 1);
+ assert.equal(interrupted.document.error.code, 'REHOME_PENDING');
+ assert.ok(interrupted.document.error.message.includes(sourceAtDelivery.moveId), 'the refusal names the already-recorded source MOVEID');
+ assert.match(interrupted.document.error.message, /source move .* is recorded/u);
+ assert.match(interrupted.document.error.message, /retry this same move and destination/u);
+ assertPrivateHeartbeat(privateFile, moveHeartbeat);
+ assertPrivateTransportIsolation(box, privateFile);
+ withMoveBoard(privateFile, board => assert.equal(store.events(board).filter(event => event.event_kind === 'rehome' && event.item_id === linkedId).length, 1,
+ 'a later destination failure cannot duplicate the committed private source write'));
+ const delivered = await box.cli('move', `~repository#${linkedId}`, '--to', 'fixture/repository');
+ assert.equal(delivered.code, 0, JSON.stringify(delivered.document?.error));
+ assert.equal(delivered.document.moveId, sourceAtDelivery.moveId, 'retry finishes the original source MOVEID');
+ assert.equal(delivered.document.item.destinationItemId, sourceAtDelivery.destinationItemId, 'retry retains the original destination reservation');
+ assertPrivateTransportIsolation(box, privateFile);
+ const linkedDestination = delivered.document.item.destinationItemId;
+ const shared = (await box.cli('export')).document.tables;
+ assert.ok(shared.item.some(item => item.item_id === linkedDestination && item.item_title === 'private item delivered through the relay'),
+ 'the CLI destination operation reaches the real linked team board');
+ assert.equal(shared.event.filter(event => event.event_kind === 'rehome_applied' && event.item_id === linkedDestination).length, 1);
+ withMoveBoard(privateFile, board => {
+ assert.equal(store.itemRedirect(board, linkedId).moveId, delivered.document.moveId);
+ assert.equal(store.events(board).filter(event => event.event_kind === 'rehome' && event.item_id === linkedId).length, 1,
+ 'the private source records exactly one sequenced move');
+ });
+
+ const teamFile = join(root, '.git', 'pullboard', 'board.sqlite');
+ const teamId = withMoveBoard(teamFile, store.boardId);
+ const linkedTeamFile = join(box.root, '.git', 'pullboard', 'board.sqlite');
+ const localFile = privateBoardPath(teamId, box.env.PULLBOARD_HOME);
+ enableRehomeOutbox(box, box.root);
+
+ // If delivery loses its acknowledgment, the source redirect retains the exact reservation for retry.
+ const interruptedPrivate = await box.cli('add', box.lane, 'private source waits for destination delivery', '--private');
+ assert.equal(interruptedPrivate.code, 0, JSON.stringify(interruptedPrivate.document?.error));
+ box.beforeNextMove(() => box.refuseMoves(true));
+ const interruptedDelivery = await box.cli('move', `~fixture/repository#${interruptedPrivate.document.item.item_id}`, '--to', 'fixture/repository');
+ box.refuseMoves(false);
+ assert.notEqual(interruptedDelivery.code, 0);
+ assert.equal(interruptedDelivery.document.error.code, 'REHOME_PENDING');
+ const sourceDelivery = withMoveBoard(privateFile, board => store.itemRedirect(board, interruptedPrivate.document.item.item_id));
+ assert.equal(sourceDelivery.moveId, interruptedDelivery.document.error.message.match(/source move ([A-Za-z0-9_-]+)/u)?.[1]);
+ assert.ok(Number.isSafeInteger(sourceDelivery.destinationItemId) && sourceDelivery.destinationItemId > 0,
+ 'the destination reservation is a positive ordered ID');
+ assert.equal(withMoveBoard(linkedTeamFile, board => board.db.prepare('SELECT 1 FROM item WHERE item_id=?')
+ .get(sourceDelivery.destinationItemId)), undefined, 'a refused application creates no destination item');
+ assert.deepEqual(outboxOperations(box), [], 'an interrupted destination application is never queued');
+ const recoveredDelivery = await box.cli('move', `~fixture/repository#${interruptedPrivate.document.item.item_id}`, '--to', 'fixture/repository');
+ assert.equal(recoveredDelivery.code, 0, JSON.stringify(recoveredDelivery.document?.error));
+ assert.equal(recoveredDelivery.document.moveId, sourceDelivery.moveId);
+ assert.equal(recoveredDelivery.document.item.destinationItemId, sourceDelivery.destinationItemId,
+ 'retry uses the original acknowledged reservation rather than selecting a new ID');
+ assert.deepEqual(outboxOperations(box), [], 'the recovered application is not queued');
+
+ // A private destination ID is local, but a linked team reservation cannot be chosen while the relay is down.
+ await box.stopRelay();
+ const pendingPrivate = await box.cli('add', box.lane, 'private source waits for a team reservation', '--private');
+ assert.equal(pendingPrivate.code, 0, JSON.stringify(pendingPrivate.document?.error));
+ const beforeReserveFailure = moveState(linkedTeamFile), beforePrivateReserveFailure = moveState(privateFile);
+ const reserveOffline = await box.cli('move', `~fixture/repository#${pendingPrivate.document.item.item_id}`, '--to', 'fixture/repository');
+ assert.notEqual(reserveOffline.code, 0);
+ assert.equal(reserveOffline.document.error.code, 'RELAY_UNAVAILABLE');
+ assert.match(reserveOffline.document.error.message, /retry the move when the relay accepts/u);
+ assert.deepEqual(moveState(linkedTeamFile), beforeReserveFailure, 'an unavailable reservation allocates no team ID');
+ assert.deepEqual(moveState(privateFile), beforePrivateReserveFailure, 'an unavailable reservation leaves its private source unchanged');
+ assert.deepEqual(outboxOperations(box), [], 'a reservation is refused instead of becoming a provisional outbox result');
+
+ // A pending local add has only a provisional ID. Re-home must refuse it before reserving any destination ID.
+ const provisional = await box.cli('add', box.lane, 'provisional item cannot be re-homed');
+ assert.equal(provisional.code, 0, JSON.stringify(provisional.document?.error));
+ const provisionalId = provisional.document.item.item_id;
+ assert.deepEqual(outboxOperations(box), ['addItem'], 'the linked CLI keeps the unavailable add in its local outbox');
+ const sourceState = moveState(linkedTeamFile), privateState = moveState(privateFile);
+ const pendingRehome = await box.cli('move', `fixture/repository#${provisionalId}`, '--to', '~fixture/repository');
+ assert.notEqual(pendingRehome.code, 0);
+ assert.equal(pendingRehome.document.error.code, 'RELAY_OUTBOX_UNBOUND');
+ assert.match(pendingRehome.document.error.message, /current item ID/u,
+ 'the refusal requires relay order and a fresh item lookup rather than guessing a remapped number');
+ assert.deepEqual(moveState(linkedTeamFile), sourceState, 'a provisional source ID creates no source re-home record');
+ assert.deepEqual(moveState(privateFile), privateState, 'a provisional source ID is refused before destination ID reservation');
+ assert.deepEqual(outboxOperations(box), ['addItem'], 'the re-home never joins the provisional local outbox');
+ await box.restartRelay();
+ const synchronized = await box.cli('relay', 'status');
+ assert.equal(synchronized.code, 0, JSON.stringify(synchronized.document?.error));
+ assert.deepEqual(outboxOperations(box), [], 'the add receives relay order before a move can use its ID');
+ const authoritative = await box.cli('show', String(provisionalId));
+ assert.equal(authoritative.code, 0, JSON.stringify(authoritative.document?.error));
+ assert.equal(authoritative.document.item.item_id, provisionalId, 'the current relay-authoritative ID is looked up explicitly');
+ const movedProvisional = await box.cli('move', `fixture/repository#${authoritative.document.item.item_id}`, '--to', '~fixture/repository');
+ assert.equal(movedProvisional.code, 0, JSON.stringify(movedProvisional.document?.error));
+ assert.equal(movedProvisional.document.item.sourceItemId, provisionalId);
+ assert.ok(movedProvisional.document.item.destinationItemId > pendingPrivate.document.item.item_id,
+ 'the acknowledged private reservation does not reuse the existing private item ID');
+ assert.deepEqual(outboxOperations(box), [], 'neither source move nor destination application is queued');
+
+ // A private destination reservation is local and durable, but a team source tombstone still needs relay order.
+ const teamSource = await box.cli('add', box.lane, 'acknowledged source remains put while relay is offline');
+ assert.equal(teamSource.code, 0, JSON.stringify(teamSource.document?.error));
+ const synchronizedSource = await box.cli('relay', 'status');
+ assert.equal(synchronizedSource.code, 0, JSON.stringify(synchronizedSource.document?.error));
+ assert.deepEqual(outboxOperations(box), [], 'the team source receives relay order before the outage control');
+ const authoritativeTeamSource = await box.cli('show', String(teamSource.document.item.item_id));
+ assert.equal(authoritativeTeamSource.code, 0, JSON.stringify(authoritativeTeamSource.document?.error));
+ assert.equal(authoritativeTeamSource.document.item.item_id, teamSource.document.item.item_id);
+ const beforeOfflineSourceMove = moveState(linkedTeamFile);
+ const beforeOfflineDestinationReservation = moveState(privateFile);
+ await box.stopRelay();
+ const unavailableSourceMove = await box.cli('move', `fixture/repository#${authoritativeTeamSource.document.item.item_id}`, '--to', '~fixture/repository');
+ assert.notEqual(unavailableSourceMove.code, 0);
+ assert.equal(unavailableSourceMove.document.error.code, 'RELAY_UNAVAILABLE');
+ assert.match(unavailableSourceMove.document.error.message, /retry the move when the relay accepts/u);
+ assert.deepEqual(outboxOperations(box), [], 'a rehome source move is refused instead of being queued');
+ withMoveBoard(linkedTeamFile, board => assert.equal(store.itemRedirect(board, authoritativeTeamSource.document.item.item_id), null,
+ 'no source tombstone is written without an acknowledged source move'));
+ withMoveBoard(linkedTeamFile, board => assert.equal(store.getItem(board, authoritativeTeamSource.document.item.item_id).item_title,
+ 'acknowledged source remains put while relay is offline'));
+ const afterOfflineDestinationReservation = moveState(privateFile);
+ assert.ok((afterOfflineDestinationReservation.sequence?.seq ?? 0) > (beforeOfflineDestinationReservation.sequence?.seq ?? 0),
+ 'the private destination reservation may consume an ID, but does not rewrite or replace an item');
+ await box.restartRelay();
+ await box.cli('relay', 'status');
+ const movedAfterReconnect = await box.cli('move', `fixture/repository#${authoritativeTeamSource.document.item.item_id}`, '--to', '~fixture/repository');
+ assert.equal(movedAfterReconnect.code, 0, JSON.stringify(movedAfterReconnect.document?.error));
+ assert.equal(movedAfterReconnect.document.item.sourceItemId, authoritativeTeamSource.document.item.item_id);
+ assert.ok(movedAfterReconnect.document.item.destinationItemId > (afterOfflineDestinationReservation.sequence?.seq ?? 0),
+ 'a consumed reservation ID is never reused after retry');
+ assert.notDeepEqual(moveState(linkedTeamFile), beforeOfflineSourceMove, 'the source move is recorded only after relay order returns');
+ assert.deepEqual(outboxOperations(box), [], 'the acknowledged move remains outside the outbox after recovery');
+
+ for (const title of ['private one', 'private two', 'private open move', 'private accepted move', 'private claimed move', 'private submitted move']) {
+ const added = await box.cliAt(root, 'add', box.lane, title, '--criterion', 'The private move keeps its source evidence.', '--private');
+ assert.equal(added.code, 0, JSON.stringify(added.document?.error));
+ }
+ const beforeSource = moveState(localFile), beforeTeam = moveState(teamFile);
+ for (const [source, destination] of [['~web#3', 'web'], ['web#3', '~web']]) {
+ const ambiguous = await box.cliAt(root, 'move', source, '--to', destination);
+ assert.notEqual(ambiguous.code, 0);
+ assert.equal(ambiguous.document.error.code, 'BOARD_REFERENCE');
+ assert.match(ambiguous.document.error.message, /acme\/web/u);
+ assert.match(ambiguous.document.error.message, /bob\/web/u);
+ }
+ assert.deepEqual(moveState(localFile), beforeSource, 'ambiguous handles do not reserve or move a source item');
+ assert.deepEqual(moveState(teamFile), beforeTeam, 'ambiguous handles do not mutate the destination');
+ const moved = await box.cliAt(root, 'move', '~web#3', '--to', 'acme/web');
+ assert.equal(moved.code, 0, JSON.stringify(moved.document?.error));
+ assert.equal(moved.document.source, '~acme/web#3', 'the private qualifier is its repository origin, while the signed-in person remains owner metadata');
+ const openRecord = moved.document.item;
+ assert.equal(openRecord.sourceBoardId, withMoveBoard(localFile, store.boardId));
+ assert.equal(openRecord.sourceItemId, 3);
+ withMoveBoard(localFile, board => {
+ assert.equal(store.itemRedirect(board, 3).moveId, moved.document.moveId);
+ assert.throws(() => store.getItem(board, 3), error => error.code === 'ITEM_MOVED' && error.message.includes(moved.document.destination));
+ assert.equal(store.events(board).filter(event => event.event_kind === 'rehome' && event.item_id === 3).length, 1);
+ });
+ const beforeRetry = moveState(teamFile);
+ const retried = await box.cliAt(root, 'move', '~acme/web#3', '--to', 'acme/web');
+ assert.equal(retried.code, 0, JSON.stringify(retried.document?.error));
+ assert.equal(retried.document.moveId, moved.document.moveId);
+ assert.equal(retried.document.destination, moved.document.destination);
+ assert.deepEqual(moveState(teamFile), beforeRetry, 'retrying a source MOVEID does not duplicate destination rows or reservations');
+ assertMoveReplay(teamFile, openRecord, openRecord.destinationItemId);
+ await privateHandleCollision(box, root, bobRoot, teamFile, localFile, openRecord.destinationItemId);
+
+ const commit = runFixtureGit(['rev-parse', 'HEAD'], { cwd: root, env: box.env });
+ const accepted = privateMoveStatus(localFile, 4, 'verified', root, box.lane, commit);
+ const imported = await box.cliAt(root, 'move', '~acme/web#4', '--to', 'acme/web');
+ assert.equal(imported.code, 0, JSON.stringify(imported.document?.error));
+ const importedRecord = imported.document.item;
+ withMoveBoard(teamFile, board => {
+ const item = store.getItem(board, importedRecord.destinationItemId);
+ assert.equal(item.item_status, 'verified');
+ assert.equal(item.item_commit, accepted.commit);
+ assert.equal(item.item_frozen_digest, accepted.digest);
+ assert.equal(item.item_verified_by, accepted.reviewer);
+ assert.deepEqual(store.verdictsFor(board, item.item_id), [], 'a source acceptance never becomes a destination-board verdict');
+ assert.equal(item.item_rehome_import.sourceBoardId, importedRecord.sourceBoardId);
+ assert.equal(item.item_rehome_import.moveId, imported.document.moveId);
+ assert.equal(item.item_rehome_import.verdict.by, accepted.reviewer);
+ assert.equal(item.item_rehome_import.attestedBy, 'coordinator');
+ });
+ assertMoveReplay(teamFile, importedRecord, importedRecord.destinationItemId);
+ for (const [id, status] of [[5, 'claimed'], [6, 'submitted']]) {
+ privateMoveStatus(localFile, id, status, root, box.lane, commit);
+ const sourceBefore = moveState(localFile), destinationBefore = moveState(teamFile);
+ const refused = await box.cliAt(root, 'move', `~acme/web#${id}`, '--to', 'acme/web');
+ assert.notEqual(refused.code, 0);
+ assert.equal(refused.document.error.code, 'REHOME_STATE', `${status} source work stays put`);
+ assert.deepEqual(moveState(localFile), sourceBefore);
+ assert.deepEqual(moveState(teamFile), destinationBefore, 'a refused source state allocates no destination ID');
+ }
+ const ordinary = await box.cliAt(root, 'add', box.lane, 'team item moving to private');
+ assert.equal(ordinary.code, 0);
+ const reverse = await box.cliAt(root, 'move', `acme/web#${ordinary.document.item.item_id}`, '--to', '~acme/web');
+ assert.equal(reverse.code, 0, JSON.stringify(reverse.document?.error));
+ const reverseId = reverse.document.item.destinationItemId;
+ assert.ok(reverseId > 6, 'old private IDs are never reused');
+ withMoveBoard(localFile, board => assert.equal(store.getItem(board, reverseId).item_title, 'team item moving to private'));
+
+ const target = 'https://github.com/fixture/repository/issues/6';
+ const carriedBrief = `Change: keep the source acknowledgement.\nReference: ${target} @issue-author`;
+ installReferenceAuthorFixture(box);
+ const carriedId = await authenticatedPersonAdd(box, root, { requestId: 'rehome-reference-valid-proof',
+ title: 'Receipt-backed handled reference', criterion: 'Preserve checked source attribution.', brief: carriedBrief });
+ const carried = await box.cliAt(root, 'move', `acme/web#${carriedId}`, '--to', '~acme/web');
+ assert.equal(carried.code, 0, JSON.stringify(carried.document?.error));
+ const carriedDestination = carried.document.item.destinationItemId;
+ withMoveBoard(localFile, board => {
+ assert.equal(store.getItem(board, carriedDestination).item_brief, carriedBrief,
+ 'a current-engine source receipt carries its checked handle and exact brief');
+ });
+
+ const staleBrief = `Change: original explanation.\nReference: ${target} @issue-author`;
+ const currentBrief = `Change: revised explanation.\nReference: ${target} @issue-author`;
+ const staleProofId = await authenticatedPersonAdd(box, root, { requestId: 'rehome-reference-stale-person-proof',
+ title: 'Handled reference with later brief edit', criterion: 'Keep current source content.', brief: staleBrief });
+ const edit = await box.cliAt(root, 'edit', String(staleProofId), '--brief', currentBrief);
+ assert.equal(edit.code, 0, JSON.stringify(edit.document?.error));
+ withMoveBoard(teamFile, board => {
+ const receipt = board.db.prepare("SELECT meta_value FROM board_meta WHERE meta_key GLOB 'relay_receipt_*'").all()
+ .map(row => JSON.parse(row.meta_value)).find(candidate => {
+ const move = JSON.parse(candidate.move);
+ return move.operation === 'editItem' && move.args[0] === staleProofId && move.args[1]?.brief === currentBrief;
+ });
+ assert.ok(receipt, 'the ordinary edit has its own ordered source receipt');
+ const recordedEdit = JSON.parse(receipt.move);
+ assert.equal(recordedEdit.args[0], staleProofId);
+ assert.equal(recordedEdit.args[1].brief, currentBrief);
+ assert.equal(recordedEdit.args[1].referenceAuthority, undefined,
+ 'a signed-in editor does not carry authority to acknowledge the handled reference');
+ assert.notEqual(recordedEdit.personRequest?.phase, 'execute',
+ 'the later edit is not an authenticated person acknowledgement request');
+ const sourceEvent = board.db.prepare("SELECT event_detail FROM event WHERE event_kind='edit' AND item_id=? ORDER BY event_id DESC LIMIT 1").get(staleProofId);
+ assert.equal(JSON.parse(sourceEvent.event_detail).person, 'alice',
+ 'the signed-in sender login is not itself a reference-authority receipt');
+ });
+ const staleProof = await box.cliAt(root, 'move', `acme/web#${staleProofId}`, '--to', '~acme/web');
+ assert.equal(staleProof.code, 0, JSON.stringify(staleProof.document?.error));
+ withMoveBoard(localFile, board => {
+ const importedItem = store.getItem(board, staleProof.document.item.destinationItemId);
+ assert.match(importedItem.item_brief, /Reference: https:\/\/github\.com\/fixture\/repository\/issues\/6/u);
+ assert.match(importedItem.item_brief, /Change: revised explanation\./u);
+ assert.doesNotMatch(importedItem.item_brief, /@issue-author/u,
+ 'a same-item person receipt for an older brief cannot authorize the current handled marker');
+ });
+
+ const unreceiptedBrief = 'Change: keep the explanation.\nReference: https://example.com/private-source @PrivateAuthor';
+ const privateHandled = await box.cliAt(root, 'add', box.lane, 'Private handled reference without team receipt',
+ '--private', '--brief', unreceiptedBrief);
+ assert.equal(privateHandled.code, 0, JSON.stringify(privateHandled.document?.error));
+ const privateHandledId = privateHandled.document.item.item_id;
+ assertPrivateTransportIsolation(box, localFile);
+ withMoveBoard(localFile, board => assert.match(store.getItem(board, privateHandledId).item_brief, /@PrivateAuthor$/u));
+ const downgraded = await box.cliAt(root, 'move', `~acme/web#${privateHandledId}`, '--to', 'acme/web');
+ assert.equal(downgraded.code, 0, JSON.stringify(downgraded.document?.error));
+ withMoveBoard(teamFile, board => {
+ const importedItem = store.getItem(board, downgraded.document.item.destinationItemId);
+ assert.match(importedItem.item_brief, /Reference: https:\/\/example\.com\/private-source/u);
+ assert.match(importedItem.item_brief, /Change: keep the explanation\./u);
+ assert.doesNotMatch(importedItem.item_brief, /@PrivateAuthor/u,
+ 'a private handled marker without a source receipt is preserved as an unhandled reference');
+ });
+
+ const oldEngineBrief = `Change: keep the legacy explanation.\nReference: ${target} @issue-author`;
+ const legacyRoot = await moveRepository(box, 'legacy-web', 'legacy');
+ const legacyTeamFile = join(legacyRoot, '.git', 'pullboard', 'board.sqlite');
+ assert.equal(existsSync(join(legacyRoot, '.git', 'pullboard', 'relay.json')), false,
+ 'the historical fixture is deliberately unlinked and cannot submit an old-engine write to the current relay');
+ const legacyPrivate = await box.cliAt(legacyRoot, 'add', box.lane, 'legacy private destination', '--private');
+ assert.equal(legacyPrivate.code, 0, JSON.stringify(legacyPrivate.document?.error));
+ const legacyPrivateFile = privateBoardPath(withMoveBoard(legacyTeamFile, store.boardId), box.env.PULLBOARD_HOME);
+ const oldEngineId = withMoveBoard(legacyTeamFile, board => {
+ const prepared = prepareEngineMove(board, 'addItem', [{ by: 'coordinator', lane: 'web',
+ title: 'Historical handled reference with legacy receipt', criterion: 'Keep the old item content.',
+ brief: oldEngineBrief, route: 'strong' }], { id: 'rehome-reference-old-engine-only' });
+ const move = { ...prepared, engine: REFERENCE_ENGINE - 1 };
+ const outcome = applyRelayMove(board, move, { sequence: appliedSequence(board) + 1,
+ at: new Date().toISOString(), kind: 'move',
+ sender: { kind: 'agent', userId: 'fixture-user', agent: 'coordinator' } });
+ assert.equal(outcome.error, undefined, JSON.stringify(outcome.error));
+ const receipt = engineReceipt(board, move.id);
+ assert.ok(receipt, 'the historical handled item has an ordered receipt');
+ assert.ok(JSON.parse(receipt.move).engine < REFERENCE_ENGINE,
+ 'the receipt predates checked-reference semantics and cannot prove the handled marker');
+ assert.equal(JSON.parse(receipt.move).args[0].brief, oldEngineBrief);
+ assert.equal(receipt.outcome.result, outcome.result);
+ return outcome.result;
+ });
+ const oldEngine = await box.cliAt(legacyRoot, 'move', `legacy/web#${oldEngineId}`, '--to', '~legacy/web');
+ assert.equal(oldEngine.code, 0, JSON.stringify(oldEngine.document?.error));
+ withMoveBoard(legacyPrivateFile, board => {
+ const importedItem = store.getItem(board, oldEngine.document.item.destinationItemId);
+ assert.match(importedItem.item_brief, /Reference: https:\/\/github\.com\/fixture\/repository\/issues\/6/u);
+ assert.match(importedItem.item_brief, /Change: keep the legacy explanation\./u);
+ assert.doesNotMatch(importedItem.item_brief, /@issue-author/u,
+ 'a pre-reference-engine receipt cannot confer handled status');
+ });
+
+ const legacyBrief = `Change: keep the older explanation.\nReference: ${target} @issue-author`;
+ const unprovenId = withMoveBoard(legacyTeamFile, board => {
+ const oldAdd = prepareEngineMove(board, 'addItem', [{ by: 'coordinator', lane: 'web',
+ title: 'Historical handled reference without person proof', criterion: 'Keep the legacy item.',
+ brief: legacyBrief, route: 'strong' }], { id: 'rehome-reference-old-add' });
+ const oldMove = { ...oldAdd, engine: REFERENCE_ENGINE - 1 };
+ const oldOutcome = applyRelayMove(board, oldMove,
+ { sequence: appliedSequence(board) + 1, at: new Date().toISOString(), kind: 'move',
+ sender: { kind: 'agent', userId: 'fixture-user', agent: 'coordinator' } });
+ assert.equal(oldOutcome.error, undefined, JSON.stringify(oldOutcome.error));
+ const oldReceipt = engineReceipt(board, oldMove.id);
+ assert.ok(oldReceipt, 'the legacy add has an ordered source receipt');
+ assert.ok(JSON.parse(oldReceipt.move).engine < REFERENCE_ENGINE, 'the legacy receipt predates checked-reference semantics');
+ assert.equal(JSON.parse(oldReceipt.move).args[0].brief, legacyBrief);
+ assert.equal(oldReceipt.outcome.result, oldOutcome.result);
+ const edit = prepareEngineMove(board, 'editItem', [oldOutcome.result, { agentId: 'coordinator',
+ brief: legacyBrief, referenceAuthors: [{ target, author: 'issue-author' }] }], { id: 'rehome-reference-unproven-edit' });
+ const editOutcome = applyRelayMove(board, edit, { sequence: appliedSequence(board) + 1,
+ at: new Date().toISOString(), kind: 'move',
+ sender: { kind: 'agent', userId: 'fixture-user', agent: 'coordinator' } });
+ assert.equal(editOutcome.error, undefined, JSON.stringify(editOutcome.error));
+ const editReceipt = engineReceipt(board, edit.id);
+ assert.ok(editReceipt, 'the current brief receipt exists but has no person-authority proof');
+ const recordedEdit = JSON.parse(editReceipt.move);
+ assert.ok(recordedEdit.engine >= REFERENCE_ENGINE);
+ assert.equal(recordedEdit.args[0], oldOutcome.result, 'the non-person receipt refers to this exact source item');
+ assert.equal(recordedEdit.args[1].brief, legacyBrief, 'the non-person receipt covers the exact current brief');
+ const event = board.db.prepare("SELECT event_detail FROM event WHERE event_kind='edit' AND item_id=? ORDER BY event_id DESC LIMIT 1").get(oldOutcome.result);
+ assert.equal(JSON.parse(event.event_detail).person, undefined, 'the receipt did not originate from the authenticated person');
+ return oldOutcome.result;
+ });
+ const unproven = await box.cliAt(legacyRoot, 'move', `legacy/web#${unprovenId}`, '--to', '~legacy/web');
+ assert.equal(unproven.code, 0, JSON.stringify(unproven.document?.error));
+ withMoveBoard(legacyPrivateFile, board => {
+ const importedItem = store.getItem(board, unproven.document.item.destinationItemId);
+ assert.match(importedItem.item_brief, new RegExp(target.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')));
+ assert.match(importedItem.item_brief, /Change: keep the older explanation\./u);
+ assert.doesNotMatch(importedItem.item_brief, /@issue-author/u,
+ 'a receipt without authenticated person authority cannot preserve the handled marker');
+ });
+
+ const fresh = await box.cliAt(root, 'add', box.lane, 'new private item after moves', '--private');
+ assert.equal(fresh.code, 0);
+ assert.ok(fresh.document.item.item_id > reverseId);
+ withMoveBoard(localFile, board => assert.equal(store.itemRedirect(board, 3).moveId, moved.document.moveId,
+ 'the old source ID keeps its permanent redirect after later adds'));
+}
diff --git a/test/private-rehome-grants.test.js b/test/private-rehome-grants.test.js
new file mode 100644
index 00000000..62fa71e3
--- /dev/null
+++ b/test/private-rehome-grants.test.js
@@ -0,0 +1,78 @@
+/** @pullboard-test-loads src/board.js src/engine.js src/exchange.js */
+/** Destination imports obey the same creation grants as ordinary additions [E15,E21,H16]. */
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { join } from 'node:path';
+import { after } from 'node:test';
+import { test } from 'node:test';
+import * as store from '../src/board.js';
+import { appliedSequence } from '../src/engine.js';
+import { applyEngineMove } from '../src/engine.js';
+import { prepareEngineMove } from '../src/engine.js';
+import { exportBoard } from '../src/exchange.js';
+import { importBoard } from '../src/exchange.js';
+import { createE2eHelpers } from './e2e-helpers.js';
+
+const helpers = createE2eHelpers();
+after(helpers.cleanup);
+
+test('a rehome destination import obeys lane and claimed item grants on independent replicas [E15,E21,H16]', t => {
+ const sourceBox = helpers.project();
+ const destinationBox = helpers.project();
+ const source = store.openBoard(join(sourceBox.repo, '.git', 'pullboard', 'board.sqlite'));
+ const destination = store.openBoard(join(destinationBox.repo, '.git', 'pullboard', 'board.sqlite'));
+ const peer = store.openBoard(':memory:');
+ t.after(() => [source, destination, peer].forEach(board => store.closeBoard(board)));
+ const web = store.agentAt(destination, destinationBox.web).agent_id;
+ const api = store.register(destination, { lane: 'api', path: join(destinationBox.dir, 'api-seat'), model: 'fixture-model' });
+ /** Reserve a genuine destination id and retain the exact source move's immutable record. */
+ const recordFor = title => {
+ const id = store.addItem(source, { by: 'coordinator', lane: 'web', title,
+ criterion: 'The original proof file exists.', check: 'test -f web/grant-proof' });
+ const moveId = `destination-grant-${id}`;
+ const destinationItemId = store.reserveRehomeItemId(destination, store.boardId(source), moveId, { agentId: 'coordinator' });
+ return store.rehomeItem(source, id, { agentId: 'coordinator', sourceMoveId: moveId,
+ destinationBoardId: store.boardId(destination), destinationItemId });
+ };
+ const records = ['Allowed import', 'Wrong lane import', 'Claimed seat import'].map(recordFor);
+ importBoard(peer, exportBoard(destination));
+ /** Replay one authentic public operation against two separately opened SQLite boards. */
+ const apply = (record, actor) => {
+ const move = prepareEngineMove(destination, 'applyRehomeItem', [record, { destinationAgentId: actor }]);
+ const receipt = { sequence: appliedSequence(destination) + 1, at: new Date().toISOString() };
+ const outcomes = [destination, peer].map(board => applyEngineMove(board, move, receipt));
+ assert.deepEqual(outcomes[0], outcomes[1], 'independent replicas agree on the permission result');
+ return { move, receipt, outcome: outcomes[0] };
+ };
+ const allowed = apply(records[0], web);
+ assert.equal(allowed.outcome.error, undefined, 'an unclaimed seat may create an item in its own lane');
+ assert.equal(allowed.outcome.result, records[0].destinationItemId);
+ const wrongLane = apply(records[1], api);
+ assert.equal(wrongLane.outcome.error?.code, 'AGENT_GRANT_LANE');
+ for (const board of [destination, peer]) {
+ assert.equal(board.db.prepare('SELECT 1 FROM item WHERE item_id=?').get(records[1].destinationItemId), undefined,
+ 'a refused import creates no destination item');
+ }
+ const head = destinationBox.git(destinationBox.repo, 'rev-parse', 'HEAD');
+ /** Freeze a real private Git revision before replaying identical claim bytes on both replicas. */
+ const freeze = item => {
+ const text = JSON.stringify({ title: item.item_title, criterion: item.item_criterion,
+ check: item.item_check, rows: [], policy: { version: 1, commit: head, verify: { policy: 'any', family: 'off' } } });
+ return { text, digest: createHash('sha256').update(text).digest('hex') };
+ };
+ const claim = prepareEngineMove(destination, 'claim', [records[0].destinationItemId,
+ { agentId: web, lane: 'web', leaseMs: 60_000, freeze, head }]); // budget: a live authority fixture, not an elapsed-time assertion.
+ const claimReceipt = { sequence: appliedSequence(destination) + 1, at: new Date().toISOString() };
+ const claimed = [destination, peer].map(board => applyEngineMove(board, claim, claimReceipt));
+ assert.deepEqual(claimed[0], claimed[1]);
+ assert.equal(claimed[0].error, undefined, JSON.stringify(claimed[0]));
+ assert.equal(apply(records[2], web).outcome.error?.code, 'AGENT_GRANT_ITEM',
+ 'holding one item cannot authorize creation of another through a rehome operation');
+ for (const board of [destination, peer]) {
+ assert.equal(board.db.prepare('SELECT 1 FROM item WHERE item_id=?').get(records[2].destinationItemId), undefined);
+ const before = exportBoard(board);
+ assert.deepEqual(applyEngineMove(board, allowed.move, allowed.receipt), allowed.outcome,
+ 'an exact historical receipt remains replayable after authority narrows');
+ assert.deepEqual(exportBoard(board), before, 'exact replay does not append another event or item');
+ }
+});
diff --git a/test/relay-credential.test.js b/test/relay-credential.test.js
index 2e88e665..e8965525 100644
--- a/test/relay-credential.test.js
+++ b/test/relay-credential.test.js
@@ -30,6 +30,7 @@ test('every current operation selects its native actor credential without a seco
if (operation === 'release') args = [999999, actor];
if (['claim', 'refreeze'].includes(operation)) args = [box.before.tables.item[0].item_id, options];
if (operation === 'reserveNextReview') args = [options];
+ if (operation === 'reserveRehomeItemId') args = ['a'.repeat(32), 'credential-rehome-reservation', { agentId: actor }];
if (operation === 'setLineSetting') args = [{ agentId: actor, key: 'reviewsFirst', value: true, reason: 'credential fixture', window: { windowMinutes: 60, activeReviewers: 1 } }];
if (operation === 'setLaneLead') args = [{ agentId: actor, lane: box.lane, seat: null, lanes: [box.lane] }];
if (operation === 'setBoardMembers') args = [{ agentId: actor, document: null }]; // Native format refusal still exercises the authenticated credential.
diff --git a/test/relay-fixture.js b/test/relay-fixture.js
index 8de79667..83766ba6 100644
--- a/test/relay-fixture.js
+++ b/test/relay-fixture.js
@@ -7,17 +7,49 @@ import { once } from 'node:events';
/** Start a provider with real signed JWT verification and one-use browser/device grants. */
export async function githubFixture(t) {
const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
- const state = { access: true, permission: 'write', public: false, installed: true, repositoryID: 100, repositories: ['repository', 'repository-2', 'repository-3'], accountID: 7, permissionAccountID: 7, deviceAuthorized: false, deviceDeclined: false, deviceExpired: false, slow: false, redirect: null, beforeDevicePoll: null, beforeUser: null };
+ const state = { access: true, permission: 'write', public: false, installed: true, repositoryID: 100, repositories: ['repository', 'repository-2', 'repository-3'], qualifiedRepositories: {}, accountID: 7, permissionAccountID: 7, deviceAuthorized: false, deviceDeclined: false, deviceExpired: false, slow: false, redirect: null, beforeDevicePoll: null, beforeUser: null };
const calls = [];
const codes = new Map();
// Each user credential remembers who signed in. state.signer picks the next person and state.people gives each
// one an id and repository role; without them there is one person, fixture-user, as before.
const userTokens = new Map();
const installationTokens = new Set();
+ const installationScopes = new Map();
const deviceCode = randomBytes(24).toString('base64url');
const clientSecret = randomBytes(24).toString('base64url');
let origin;
+ /** Resolve one exact repository record; non-fixture origins require explicit test provisioning. */
+ function repositoryRecord(owner, name) {
+ const fullName = `${owner}/${name}`;
+ if (Object.hasOwn(state.qualifiedRepositories, fullName)) {
+ const configured = state.qualifiedRepositories[fullName];
+ assert.ok(Number.isSafeInteger(configured.id) && configured.id > 0, `${fullName} has a stable repository ID`);
+ assert.ok(Number.isSafeInteger(configured.installationId) && configured.installationId > 0, `${fullName} has a stable installation ID`);
+ assert.ok(configured.people && typeof configured.people === 'object' && !Array.isArray(configured.people), `${fullName} has an explicit people allowlist`);
+ const duplicates = Object.entries(state.qualifiedRepositories)
+ .filter(([other, value]) => other !== fullName && (value.id === configured.id || value.installationId === configured.installationId));
+ assert.equal(duplicates.length, 0, `${fullName} has distinct repository and installation IDs`);
+ return { owner, name, fullName, id: configured.id, installationId: configured.installationId,
+ people: configured.people, public: configured.public === true };
+ }
+ if (owner !== 'fixture') return null;
+ const index = state.repositories.indexOf(name);
+ return index < 0 ? null : { owner, name, fullName, id: state.repositoryID + index, installationId: 42,
+ people: null, public: state.public };
+ }
+
+ /** Installation tokens are scoped to one explicitly provisioned qualified repository. */
+ function repositoryForInstallation(installationId, name) {
+ const fixtureRepositories = state.repositories.map((repositoryName, index) => repositoryRecord('fixture', repositoryName));
+ const qualifiedRepositories = Object.entries(state.qualifiedRepositories)
+ .map(([fullName]) => { const [owner, repositoryName] = fullName.split('/'); return repositoryRecord(owner, repositoryName); });
+ const matches = [...fixtureRepositories, ...qualifiedRepositories]
+ .filter(repository => repository?.installationId === installationId && repository.name === name);
+ assert.ok(matches.length <= 1, `installation ${installationId} and repository ${name} resolve uniquely`);
+ return matches[0] ?? null;
+ }
+
/** Return JSON without recording provider credentials in fixture diagnostics. */
function reply(res, status, value) {
res.writeHead(status, { 'Content-Type': 'application/json' });
@@ -100,25 +132,36 @@ export async function githubFixture(t) {
// The public SSH keys on an account, as GitHub lists them; state.sshKeys maps a login to its key lines [E17].
const keysOf = /^\/users\/([^/]+)\/keys$/u.exec(url.pathname)?.[1];
if (keysOf) return reply(res, 200, (state.sshKeys?.[decodeURIComponent(keysOf)] ?? []).map((key, index) => ({ id: index + 1, key })));
- const repositoryPath = url.pathname.match(/^\/repos\/fixture\/([^/]+)(?:\/(.*))?$/u);
- const repositoryName = repositoryPath?.[1];
- const allowedRepository = state.repositories.includes(repositoryName);
- if (allowedRepository && repositoryPath[2] === 'installation') return reply(res, isApp && state.installed ? 200 : 404, { id: 42 });
- if (url.pathname === '/app/installations/42/access_tokens') {
+ const repositoryPath = /^\/repos\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)(?:\/(.*))?$/u.exec(url.pathname);
+ const repository = repositoryPath ? repositoryRecord(repositoryPath[1], repositoryPath[2]) : null;
+ const allowedRepository = Boolean(repository);
+ const installationAccess = /^\/app\/installations\/(\d+)\/access_tokens$/u.exec(url.pathname);
+ if (allowedRepository && repositoryPath[3] === 'installation') {
+ return reply(res, isApp && state.installed ? 200 : 404, { id: repository.installationId });
+ }
+ if (installationAccess) {
assert.ok(isApp, 'installation request has a valid RSA App JWT');
const request = JSON.parse(raw);
assert.equal(request.repositories.length, 1, 'installation token is scoped to one allowed fixture repository');
- assert.ok(state.repositories.includes(request.repositories[0]), 'installation token names an explicitly allowed fixture repository');
assert.deepEqual(request, { repositories: request.repositories, permissions: { metadata: 'read' } });
+ const scopedRepository = repositoryForInstallation(Number(installationAccess[1]), request.repositories[0]);
+ if (!scopedRepository) return reply(res, 404, { message: 'not available' });
const token = 'ghs_' + randomBytes(32).toString('base64url');
installationTokens.add(token);
+ installationScopes.set(token, scopedRepository.fullName);
return reply(res, 201, { token, expires_at: new Date(Date.now() + 3600_000).toISOString() });
}
- if (allowedRepository && !repositoryPath[2]) return reply(res, isInstallation || state.public ? 200 : 404, { id: state.repositoryID + state.repositories.indexOf(repositoryName), full_name: 'fixture/' + repositoryName, private: !state.public });
- const asked = /^collaborators\/([^/]+)\/permission$/u.exec(repositoryPath?.[2] ?? '')?.[1];
- if (allowedRepository && asked && (asked === 'fixture-user' || state.people?.[asked])) {
+ const installationForRepository = isInstallation && installationScopes.get(bearer) === repository?.fullName;
+ if (allowedRepository && !repositoryPath[3]) {
+ return reply(res, installationForRepository || repository.public ? 200 : 404,
+ { id: repository.id, full_name: repository.fullName, private: !repository.public });
+ }
+ const asked = /^collaborators\/([^/]+)\/permission$/u.exec(repositoryPath?.[3] ?? '')?.[1];
+ const people = repository?.people ?? state.people;
+ const person = people && Object.hasOwn(people, asked) ? people[asked] : null;
+ const legacyFixturePerson = repository?.people === null && asked === 'fixture-user';
+ if (allowedRepository && asked && (person || legacyFixturePerson)) {
if (state.beforePermission) await state.beforePermission();
- const person = state.people?.[asked];
const role = person ? person.permission : state.access ? state.permission : 'none';
const permission = { triage: 'read', maintain: 'write' }[role] || role;
const permissions = state.permissions ?? {
@@ -132,7 +175,7 @@ export async function githubFixture(t) {
answer.role_name = state.roleName ?? role;
answer.user.permissions = permissions;
}
- return reply(res, isInstallation ? 200 : 403, answer);
+ return reply(res, installationForRepository ? 200 : 403, answer);
}
return reply(res, 404, { message: 'not available' });
}
diff --git a/test/relay-outbox.test.js b/test/relay-outbox.test.js
index 4b3bd924..0f961a1b 100644
--- a/test/relay-outbox.test.js
+++ b/test/relay-outbox.test.js
@@ -16,6 +16,8 @@ import {
import { runFixtureGit } from './fixture-child.js';
import { relayClientFixture } from './relay-client-fixture.js';
import { relayFixtureChild } from './relay-client-fixture.js';
+import { Refused } from '../src/refused.js';
+import { outboxQueueable } from '../src/relay-outbox.js';
const CLI = fileURLToPath(new URL('../bin/pullboard.js', import.meta.url));
@@ -277,6 +279,17 @@ test('every ordered move kind says where it names an item, and each place follow
assert.ok(places >= 30, `the walk covers every declared place (${places})`);
});
+test('re-home reservation and delivery moves always require relay order [E15,H16]', () => {
+ const state = { mode: 'ordered', baselineAccepted: true, baselineConflict: false, environment: false };
+ const io = { relayOutbox: () => true };
+ const unavailable = new Refused('RELAY_UNAVAILABLE', 'the relay did not answer');
+ const itemSlots = { reserveRehomeItemId: [], rehomeItem: [[0]], applyRehomeItem: [[0, 'destinationItemId']] };
+ for (const operation of ['reserveRehomeItemId', 'rehomeItem', 'applyRehomeItem']) {
+ assert.deepEqual(ITEM_SLOTS[operation], itemSlots[operation], `${operation} declares only its local item IDs`);
+ assert.equal(outboxQueueable(state, unavailable, operation, io), false, `${operation} waits for an acknowledged result`);
+ }
+});
+
test('a move that names an offline item where the outbox cannot follow it is refused, never sent [B26,H16]', () => {
const outbox = { moves: [{ move: { id: 'offline-add', operation: 'addItem', args: [{}] }, visible: 7 }] };
assert.deepEqual(strayItemRefs(outbox, { operation: 'recordHealthFindings', args: [{ agentId: 'coordinator', findings: [{ item: 7, cause: 'x' }] }] }), [7]);
diff --git a/test/relay-parity-operations.js b/test/relay-parity-operations.js
index 979edd41..510e2652 100644
--- a/test/relay-parity-operations.js
+++ b/test/relay-parity-operations.js
@@ -10,7 +10,7 @@ import { captureSpecApprovalBaseline } from '../src/spec-approval.js';
import { loadConfig } from '../src/config.js';
import { decodeBoardKey } from '../src/seal.js';
import { createParityReader, assertReaderParity } from './relay-parity-reader.js';
-import { createStudyExercise, seedStudyState, seedHandoff } from './relay-parity-seeds.js';
+import { createStudyExercise, seedStudyState, seedRehome, seedHandoff } from './relay-parity-seeds.js';
import { submitFixture } from './board-submit-fixture.js';
import { seedOutside, seedLandingObservations, seedMembership, seedAdministrative, seedBatch, seedCoordinatorAuthority, seedSpecOutcomes, seedBarSignature, seedCurrentOperations } from './relay-parity-extra-seeds.js';
import { syntheticFlakeObservation } from './flake-observation-fixture.js';
@@ -56,6 +56,7 @@ export async function exerciseOperationParity({ root, origin, token, boardId, la
await seedCurrentOperations(context);
await seedBarSignature(context);
await seedCoordinatorAuthority(context);
+ await seedRehome(context);
await seedHandoff(context);
const missing = tracking.missing(MOVE_OPERATIONS);
assert.deepEqual(missing, [], `every declared native operation must pass the complete oracle; setup refusals=${JSON.stringify(tracking.setupRefusals)}`);
diff --git a/test/relay-parity-seeds.js b/test/relay-parity-seeds.js
index 9a476f22..d5f4b61b 100644
--- a/test/relay-parity-seeds.js
+++ b/test/relay-parity-seeds.js
@@ -182,6 +182,37 @@ export async function seedSpecAndHandoff(context) {
return context;
}
+/** Cover rehome operations with real source records and an auxiliary in-memory board. */
+export async function seedRehome(context) {
+ const { board, box, store, exercise, agent } = context;
+ const auxiliary = store.openBoard(':memory:');
+ try {
+ store.ensureCoordinator(auxiliary, join(box.root, '.parity-rehome-auxiliary'));
+ const sourceBoardId = store.boardId(auxiliary);
+ const destinationBoardId = store.boardId(board);
+ const incomingMoveId = 'parity-rehome-incoming';
+ const incomingItem = store.addItem(auxiliary, { by: 'coordinator', lane: box.lane,
+ title: 'Parity incoming item', criterion: 'A real open source item.' });
+ const incomingDestinationId = await exercise('reserveRehomeItemId', () =>
+ store.reserveRehomeItemId(board, sourceBoardId, incomingMoveId, { agentId: 'coordinator' }));
+ const incomingRecord = store.rehomeItem(auxiliary, incomingItem, { agentId: 'coordinator',
+ sourceMoveId: incomingMoveId, destinationBoardId, destinationItemId: incomingDestinationId });
+ await exercise('applyRehomeItem', () => store.applyRehomeItem(board, incomingRecord,
+ { destinationAgentId: 'coordinator' }));
+
+ const outgoingItem = await exercise('addItem', () => store.addItem(board, { by: 'coordinator', lane: box.lane,
+ title: 'Parity outgoing item', criterion: 'A real open source item.' }));
+ const outgoingMoveId = 'parity-rehome-outgoing';
+ const outgoingDestinationId = store.reserveRehomeItemId(auxiliary, destinationBoardId,
+ outgoingMoveId, { agentId: 'coordinator' });
+ await exercise('rehomeItem', () => store.rehomeItem(board, outgoingItem, { agentId: agent,
+ sourceMoveId: outgoingMoveId, destinationBoardId: sourceBoardId, destinationItemId: outgoingDestinationId }));
+ } finally {
+ store.closeBoard(auxiliary);
+ }
+ return context;
+}
+
/** Retire the outgoing native seat only after its remaining projection recipes have completed. */
export async function seedHandoff(context) {
const { board, store, exercise, agent, reviewer } = context;
diff --git a/test/team.test.js b/test/team.test.js
index f9da3b4a..4ca16db1 100644
--- a/test/team.test.js
+++ b/test/team.test.js
@@ -32,6 +32,10 @@ import { handOverBoardKeys, statementBytes } from '../src/relay-handover.js';
import { signSshVouch } from '../src/relay-ssh-proof.js';
import { assertMatchingLandingHost, assertNoCulpritTrunkHold } from './landing-environment-fixture.js';
import { landingQueueCase } from './landing-queue-fixture.js';
+import { privateBoardPath } from '../src/projects.js';
+import { checkoutSessionFile } from '../src/agent-session.js';
+import { repoInfo } from '../src/git.js';
+import { privateBoardMoves } from './private-board-move-fixture.js';
import {
prepareKeylessInbox,
readKeylessInbox,
@@ -79,6 +83,75 @@ function run(box, root, ...args) {
return result.out;
}
+test('a private board sits beside the repo board [E11,E13,E14,E15]', { timeout: relayWorkBudgetMs(12) }, async (t) => { // budget: linked-device CLI and relay round trips, not a speed target.
+ const box = await teamBoard(t, ['alice']);
+ const shared = await box.cli('add', box.lane, 'repo item');
+ assert.equal(shared.code, 0, 'ordinary add stays on the linked repo board');
+ const repoBoardId = box.before.tables.board_meta.find(row => row.meta_key === 'board_id').meta_value;
+ const callsBeforePrivate = box.calls.length;
+ const local = await box.cli('add', box.lane, 'private item', '--private');
+ assert.equal(local.code, 0, `private add stays available beside a linked team board: ${JSON.stringify(local.document?.error ?? null)}`);
+ assert.equal(box.calls.length, callsBeforePrivate, 'private add makes no relay request');
+ const privateFile = privateBoardPath(repoBoardId, box.env.PULLBOARD_HOME);
+ assert.ok(privateFile.startsWith(box.env.PULLBOARD_HOME + '/'), 'the private board is kept under this device’s Pullboard home');
+ assert.equal(lstatSync(join(box.env.PULLBOARD_HOME, 'private')).mode & 0o777, 0o700, 'the private-board root is owner-only');
+ assert.equal(lstatSync(join(box.env.PULLBOARD_HOME, 'private', repoBoardId)).mode & 0o777, 0o700, 'the private board directory is owner-only');
+ assert.equal(lstatSync(privateFile).mode & 0o777, 0o600, 'the private SQLite file is owner-only');
+ const sessionEnv = { ...box.env, CODEX_SHELL: '1', CODEX_THREAD_ID: 'private-board-binding-fixture' };
+ const decoy = join(box.root, '..', 'private-decoy');
+ runFixtureGit(['worktree', 'add', '-q', '--detach', decoy, 'HEAD'], { cwd: box.root, env: box.env });
+ const decoyJoined = await relayFixtureChild(decoy, sessionEnv, [CLI, 'join', box.lane, '--model', 'fixture-model', '--json']);
+ assert.equal(decoyJoined.code, 0, `a first worktree takes the first repository lane ID: ${JSON.stringify(decoyJoined.document?.error ?? null)}`);
+ const decoySeat = (await relayFixtureChild(decoy, sessionEnv, [CLI, 'whoami', '--json'])).document;
+ const worker = join(box.root, '..', 'private-worker');
+ runFixtureGit(['worktree', 'add', '-q', '--detach', worker, 'HEAD'], { cwd: box.root, env: box.env });
+ const joined = await relayFixtureChild(worker, sessionEnv, [CLI, 'join', box.lane, '--model', 'fixture-model', '--json']);
+ assert.equal(joined.code, 0, `another worktree joins the same repo board: ${JSON.stringify(joined.document?.error ?? null)}`);
+ const repoSeat = (await relayFixtureChild(worker, sessionEnv, [CLI, 'whoami', '--json'])).document;
+ assert.notEqual(repoSeat.id, decoySeat.id, 'the worker has a later ID on the repository board');
+ const sessionFile = checkoutSessionFile(repoInfo(worker, { env: sessionEnv }));
+ const checkoutBindingBefore = readFileSync(sessionFile, 'utf8');
+ const reopened = await relayFixtureChild(worker, sessionEnv, [CLI, 'add', box.lane, 'private item from another worktree', '--private', '--json']);
+ assert.equal(reopened.code, 0, `another process opens the same repo’s private board: ${JSON.stringify(reopened.document?.error ?? null)}`);
+ assert.equal(readFileSync(sessionFile, 'utf8'), checkoutBindingBefore, 'private-board identity does not rewrite the checkout’s repository-session binding');
+ const privateBoard = store.openBoard(privateFile);
+ try {
+ const privateItems = store.listItems(privateBoard, { all: true }).sort((left, right) => left.item_id - right.item_id);
+ assert.deepEqual(privateItems.map(item => item.item_title), ['private item', 'private item from another worktree']);
+ assert.deepEqual(privateItems.map(item => item.item_id), [1, 2], 'local IDs persist across worktrees and processes');
+ assert.notEqual(store.boardId(privateBoard), repoBoardId, 'the private board has its own immutable identity');
+ const privateWorker = store.agentAt(privateBoard, worker);
+ assert.ok(privateWorker, 'the second process has a private-board seat');
+ assert.notEqual(privateWorker.agent_id, repoSeat.id, 'private-board agent identity is independent of the repository-board ID');
+ assert.equal(privateBoard.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get('private_repo_board_id').meta_value,
+ repoBoardId, 'the local registration stays bound to the repo board ID');
+ const reference = JSON.parse(privateBoard.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get('private_board_reference').meta_value);
+ assert.equal(reference.owner, 'alice', 'ordinary repo sign-in supplies the authenticated private handle login before any bulk setup');
+ } finally { store.closeBoard(privateBoard); }
+ const sharedExport = (await box.cli('export')).document;
+ assert.equal(JSON.stringify(sharedExport).includes('private item'), false, 'shared board exports contain no private prose');
+
+ const bobRoot = join(box.root, '..', 'bob-clone');
+ runFixtureGit(['clone', '-q', box.root, bobRoot], { cwd: box.root, env: box.env });
+ runFixtureGit(['remote', 'set-url', 'origin', '[email protected]:fixture/repository.git'], { cwd: bobRoot, env: box.env });
+ cpSync(join(box.root, '.git', 'pullboard'), join(bobRoot, '.git', 'pullboard'), { recursive: true, filter: path => !path.endsWith('.lock') });
+ const bobHome = join(box.root, '..', 'bob-home');
+ const bobEnv = { ...box.env, HOME: bobHome, PULLBOARD_HOME: join(bobHome, '.pullboard'), PULLBOARD_MACHINE_HOME: join(bobHome, 'machine') };
+ mkdirSync(join(bobEnv.PULLBOARD_HOME, 'relay-keys'), { recursive: true, mode: 0o700 });
+ cpSync(box.keyFile, join(bobEnv.PULLBOARD_HOME, 'relay-keys', repoBoardId + '.key'));
+ box.providerState.signer = 'bob';
+ const linked = await relayFixtureChild(bobRoot, bobEnv, [CLI, 'relay', 'on', '--url', box.origin, '--json']);
+ box.providerState.signer = 'alice';
+ assert.equal(linked.code, 0, `another team member links their own device: ${JSON.stringify(linked.document?.error ?? null)}`);
+ const bobItems = await relayFixtureChild(bobRoot, bobEnv, [CLI, 'list', '--all', '--json']);
+ assert.equal(bobItems.code, 0, `another member reads the shared board: ${JSON.stringify(bobItems.document?.error ?? null)}`);
+ const titles = (bobItems.document?.items ?? []).map(item => item.title ?? item.item_title);
+ assert.ok(titles.includes('repo item'), 'the ordinary item reaches the other member');
+ assert.equal(titles.includes('private item'), false, 'the private item stays on this device');
+ assert.equal(existsSync(privateBoardPath(repoBoardId, bobEnv.PULLBOARD_HOME)), false, 'another device has no local private board file');
+ await privateBoardMoves(box, privateFile);
+});
+
/** Occupy this fixture's actual gate until its stale re-review enters the ordinary queue. */
async function holdForReviewQueue(box) {
const ready = join(box.dir, 'review-gate-held');