Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(agents): prove pane ownership at runtime — a project's grant cannot reach a pane it did not spawn
Claude Code9ecd0c5f3b61
diff --git a/src/core/agents/agent-message-decide.ts b/src/core/agents/agent-message-decide.tsindex 159506ec0..5ec9e710d 100644--- a/src/core/agents/agent-message-decide.ts+++ b/src/core/agents/agent-message-decide.ts@@ -35,6 +35,13 @@ export type NotPermittedReason =* the per-project grant cannot be attributed (PR #237 review I-1); its own word because the* human's fix is de-duplicating ids, not moving nodes. See `agent-message-scope.ts`. */| 'ambiguous-target-node-id'+ /** No RUNTIME proof of which project spawned the target pane: the ledger has no entry (never+ * spawned this run, or only re-attached after a restart), or its owner disagrees with the sole+ * store claimant (a project.json listing a pane it did not spawn). The store's node-set is+ * attacker-writable, so ownership is proven at spawn, not read from the file (PR #237 fix+ * round 2 — the confused deputy driven end-to-end); unprovable ⇒ refuse. Not retryable: the+ * pane must be freshly (re)spawned by its real owner before it can be messaged. */+ | 'unproven-target-owner'/** Which signal satisfied the delivery receipt (Task 3.4). */export type ReceiptSignal = 'newTurn' | 'working'diff --git a/src/core/agents/pane-ownership.test.ts b/src/core/agents/pane-ownership.test.tsnew file mode 100644index 000000000..93944fe46--- /dev/null+++ b/src/core/agents/pane-ownership.test.ts@@ -0,0 +1,49 @@+import { describe, it, expect, beforeEach } from 'vitest'+import {+ recordFreshSpawnOwner,+ paneOwnerProject,+ forgetPaneOwner,+ resetPaneOwnershipForTests+} from './pane-ownership'++beforeEach(() => resetPaneOwnershipForTests())++describe('pane-ownership ledger', () => {+ it('records and returns the project that freshly spawned a node', () => {+ recordFreshSpawnOwner('n1', 'proj-a')+ expect(paneOwnerProject('n1')).toBe('proj-a')+ })++ it('an unrecorded node is UNPROVEN (undefined) — the fail-closed default after a restart', () => {+ // The whole cold-state contract: nothing recorded ⇒ the delivery gate must refuse. This is the+ // state every node is in immediately after an app restart (re-attach records nothing).+ expect(paneOwnerProject('never-spawned')).toBeUndefined()+ })++ it('a genuine respawn OVERWRITES — the live pane is the one that just came into being', () => {+ recordFreshSpawnOwner('n1', 'proj-a')+ recordFreshSpawnOwner('n1', 'proj-b')+ expect(paneOwnerProject('n1')).toBe('proj-b')+ })++ it('a missing owner is a no-op — an old caller passing none leaves the pane unproven, not owned', () => {+ recordFreshSpawnOwner('n1', undefined)+ expect(paneOwnerProject('n1')).toBeUndefined()+ recordFreshSpawnOwner('', 'proj-a')+ expect(paneOwnerProject('')).toBeUndefined()+ })++ it('forget drops ownership back to unproven — a deleted/recycled session is no longer owned', () => {+ recordFreshSpawnOwner('n1', 'proj-a')+ forgetPaneOwner('n1')+ expect(paneOwnerProject('n1')).toBeUndefined()+ })++ it('nodes are independent — forgetting one leaves the others', () => {+ recordFreshSpawnOwner('n1', 'proj-a')+ recordFreshSpawnOwner('n2', 'proj-a')+ forgetPaneOwner('n1')+ expect(paneOwnerProject('n1')).toBeUndefined()+ expect(paneOwnerProject('n2')).toBe('proj-a')+ })+})diff --git a/src/core/agents/pane-ownership.ts b/src/core/agents/pane-ownership.tsnew file mode 100644index 000000000..b8b4f975b--- /dev/null+++ b/src/core/agents/pane-ownership.ts@@ -0,0 +1,72 @@+/**+ * The runtime pane-ownership ledger: nodeId → the project that actually SPAWNED that node's pane,+ * this process run. It exists because the persisted store cannot be trusted to answer "who owns+ * this pane?" — `.nodeterm/project.json` is git-shared and hand-editable, so a hostile/cloned+ * project can LIST any node id, including one a different project is really running. A messaging+ * grant is per project, and panes are keyed by the BARE node id globally (tmux `nt-<nodeId>`), so+ * ownership derived from the file is a confused-deputy hole: PR #237's re-review drove it end to+ * end (a granted project A delivered into ungranted project B's live pane just by listing B's id).+ *+ * THE ONE FACT THAT IS NOT FORGEABLE BY A CLONED FILE is which project's `create()` actually+ * brought the tmux session into being. That is what this records, and only that:+ *+ * - Recorded ONLY on a GENUINE FRESH SPAWN (`PtyManager.spawnNew` with `fresh === true` — no live+ * session existed to reattach to). An attach/co-attach to a session someone else spawned never+ * records, so a second project that merely OPENS a node id another project is running cannot+ * claim it. `fresh` is the manager's own signal, not anything off the wire or the file.+ * - The owner value is the machine-local project id the renderer passed at the create call+ * (`PtyCreateOptions.ownerProjectId`) — the entry id (`IndexEntryV3.id`), never the file's+ * git-copied `id`. A cloned repo gets a fresh entry id, so it cannot inherit another copy's+ * ownership either.+ *+ * ── COLD STATE / RESTART (stated honestly) ──────────────────────────────────────────────────────+ * This ledger is IN-MEMORY and starts empty every run. After an app restart the tmux SERVER+ * usually survives, so the renderer's re-open of a node ATTACHES (`fresh === false`) and records+ * nothing — the pane is then UNPROVEN and messaging to it is REFUSED (fail-closed) until the+ * session is truly respawned (or the machine reboots, killing the tmux server, after which the+ * next open is a real fresh spawn and records correctly). We do NOT repopulate on attach: there is+ * no cheap cross-restart signal a hostile agent could not also write (a tmux session-env var is+ * settable from any pane's shell), and guessing the owner on attach is exactly how the attacker+ * would re-acquire ownership by opening the victim's id first. Fail-closed is the safe direction+ * and is pinned by a test (`ownerOf` empty ⇒ the delivery gate refuses).+ *+ * ── SCOPE ───────────────────────────────────────────────────────────────────────────────────────+ * This is scoped to tmux-pane messaging ownership but is intentionally feature-neutral: S8 PR 4's+ * BrowserControlLedger and messaging PR 7's deliver-on-idle queue want the same "who really spawned+ * this node" answer and can consume `paneOwnerProject` directly. It lives in `src/core` (no+ * electron, no main import) so it ships on both shells; the Server Edition never records or reads it+ * because messaging does not exist there (`setControlHandler` is never called).+ */++/** nodeId → owning projectId (machine-local entry id), for panes freshly spawned THIS run. */+const owners = new Map<string, string>()++/**+ * Record the owner of a node whose pane was just GENUINELY spawned. Call site: `spawnNew`, guarded+ * by `fresh === true` and a present `persistKey` + `ownerProjectId`. A fresh spawn for an id that+ * somehow already has an entry OVERWRITES it — the live pane is the one that just came into being.+ * A missing owner is a no-op (old callers / tests that pass no `ownerProjectId` simply leave the+ * pane unproven, which fails closed downstream — the correct direction).+ */+export function recordFreshSpawnOwner(nodeId: string, ownerProjectId: string | undefined): void {+ if (!nodeId || !ownerProjectId) return+ owners.set(nodeId, ownerProjectId)+}++/** The project that provably spawned this node's pane this run, or `undefined` when unproven+ * (never spawned here, or only ever attached — e.g. after a restart). Undefined MUST fail closed+ * at every gate: an unprovable owner is not an absent restriction. */+export function paneOwnerProject(nodeId: string): string | undefined {+ return owners.get(nodeId)+}++/** Drop a node's ownership — its session is ending (delete or recycle). A later genuine respawn+ * re-records; until then the id is unproven again, which fails closed. */+export function forgetPaneOwner(nodeId: string): void {+ owners.delete(nodeId)+}++/** Test seam only: wipe the ledger between cases. Never called in production. */+export function resetPaneOwnershipForTests(): void {+ owners.clear()+}diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 147f29e8b..97a9ec81b 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -35,6 +35,7 @@ import {remotePaneCursorArgs} from './remote-ssh/control-master'import { parsePaneCursor } from './pane-cursor'+import { recordFreshSpawnOwner, forgetPaneOwner } from './agents/pane-ownership'import { PANE_OWNER_FMT, foregroundArgvArgs, paneOwnerFrom, parsePaneOwner } from './agents/pane-owner'import type { PaneOwner } from '../shared/agents/pane-owner-predicate'import { readSpawnResources, spawnResourceNote } from './spawn-resources'@@ -1648,6 +1649,12 @@ export class PtyManager {}const sessionId = this.spawnSession(options, clientId, undefined)const spawned = this.sessions.get(sessionId)+ // PANE OWNERSHIP (agent messaging, PR #237 fix round 2): record the OWNING project of a pane+ // this process just GENUINELY spawned. Gated on `fresh` — an attach/co-attach to a session+ // someone else spawned (incl. an app-restart re-attach) leaves the pane UNPROVEN, so a second+ // project that merely opens another's node id cannot claim it. The owner is the renderer's+ // machine-local project id, never the git-shared file id. See `agents/pane-ownership.ts`.+ if (fresh && options.persistKey) recordFreshSpawnOwner(options.persistKey, options.ownerProjectId)// Surface a missing-account-dir fallback so the renderer can flag the node's account chip.const accountFallback = spawned?.accountFallback// The session's `persistKey` is set iff the spawn actually landed on a tmux, local or remote@@ -3137,6 +3144,10 @@ export class PtyManager {// Also drop any in-flight create for this node: a create racing the kill-session below must// spawn a fresh session, not await (and then join) the one we are ending.this.inflight.delete(persistKey)+ // The session is ending (delete or recycle), so its pane ownership no longer holds — a later+ // genuine respawn re-records it; until then the id is unproven, which fails closed for+ // messaging (agents/pane-ownership.ts). Safe on either intent: recycle's respawn overwrites.+ forgetPaneOwner(persistKey)// The tmux session is about to be killed, so everything attached to it goes now: a shadow would// otherwise linger until tmux dropped its client, and what we remembered about the released// session describes a pane that is about to stop existing.diff --git a/src/main/agent-messaging-switch.test.ts b/src/main/agent-messaging-switch.test.tsindex 83f093b42..9fc983082 100644--- a/src/main/agent-messaging-switch.test.ts+++ b/src/main/agent-messaging-switch.test.ts@@ -24,6 +24,11 @@ import {} from './agent-messaging'import type { CapabilityAckMap } from '../core/project-capability-consent'import { resetMessageFlow } from '../core/agents/agent-message-flow'+import {+ recordFreshSpawnOwner,+ paneOwnerProject,+ resetPaneOwnershipForTests+} from '../core/agents/pane-ownership'import { resetAgentMessageTraceForTests } from '../core/agents/agent-message-trace'import { MANAGED_SCRIPT_REVISION } from '../core/agents/hooks/managed-script'import type { MirrorEntry } from '../core/agent-status-mirror'@@ -71,6 +76,10 @@ function baseDeps(}],isRemoteNode: () => false,+ // Default: the target (b1) is proven-owned by its store project (p1), so the pure-wiring tests+ // exercise the GRANT, not the ownership gate. Tests that probe ownership override this or use+ // the real ledger via storeDeps.+ paneOwnerProject: () => 'p1',messagingEnabled: () => {throw new Error('each test wires messagingEnabled itself')},@@ -90,6 +99,7 @@ const req = { verb: 'send', sourceNodeId: 'a1', targetNodeId: 'b1', body: 'hellobeforeEach(() => {resetMessageFlow()resetAgentMessageTraceForTests()+ resetPaneOwnershipForTests()})describe('messagingEnabledVia — the grant, never the raw file bit', () => {@@ -165,14 +175,16 @@ describe('end to end through a REAL WorkspaceStore — the desktop wiring, minusawait fs.rm(projRoot, { recursive: true, force: true })})- /** Exactly the desktop's two lines: `projects` off the store, the switch off the store. */+ /** Exactly the desktop's THREE lines: `projects` off the store, the switch off the store, and+ * the target's owner off the RUNTIME ledger (never the store). */const storeDeps = (store: WorkspaceStore) =>baseDeps({projects: () => store.persistedCanvases(),- messagingEnabled: messagingEnabledVia((id) => store.capabilityProjectFor(id))+ messagingEnabled: messagingEnabledVia((id) => store.capabilityProjectFor(id)),+ paneOwnerProject: (id) => paneOwnerProject(id)})- it('flag committed in project.json + KEPT on this machine: delivered', async () => {+ it('flag committed in project.json + KEPT + owner PROVEN: delivered', async () => {const store = new WorkspaceStore()await store.save(ws(project({ cwd: projRoot, agentMessaging: true, capabilityAck: { agentMessaging: 'kept' } }))@@ -181,6 +193,8 @@ describe('end to end through a REAL WorkspaceStore — the desktop wiring, minusconst raw = await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8')expect(raw).toContain('"agentMessaging": true')expect(raw).not.toContain('capabilityAck')+ // The runtime fact: this project's own create() freshly spawned the target pane.+ recordFreshSpawnOwner('b1', 'p1')const deps = storeDeps(store)const { outcome } = await deliverFromControl(req, deps)expect(outcome.kind).toBe('delivered')@@ -190,6 +204,7 @@ describe('end to end through a REAL WorkspaceStore — the desktop wiring, minusit('flag committed but the notice never answered: refused as switch-off', async () => {const store = new WorkspaceStore()await store.save(ws(project({ cwd: projRoot, agentMessaging: true })))+ recordFreshSpawnOwner('b1', 'p1') // ownership proven, so the refusal is the GRANT's, not the gate'sconst deps = storeDeps(store)const { outcome } = await deliverFromControl(req, deps)expect(outcome).toEqual({ kind: 'notPermitted', reason: 'switch-off' })@@ -201,6 +216,7 @@ describe('end to end through a REAL WorkspaceStore — the desktop wiring, minusawait store.save(ws(project({ cwd: projRoot, agentMessaging: true, capabilityAck: { agentMessaging: 'declined' } })))+ recordFreshSpawnOwner('b1', 'p1')const { outcome } = await deliverFromControl(req, storeDeps(store))expect(outcome).toEqual({ kind: 'notPermitted', reason: 'switch-off' })})@@ -216,6 +232,7 @@ describe('end to end through a REAL WorkspaceStore — the desktop wiring, minus// A fresh app run loads the forged file; the machine-local entry still holds no answer.const fresh = new WorkspaceStore()await fresh.load()+ recordFreshSpawnOwner('b1', 'p1')const { outcome } = await deliverFromControl(req, storeDeps(fresh))expect(outcome).toEqual({ kind: 'notPermitted', reason: 'switch-off' })})@@ -229,6 +246,7 @@ describe('end to end through a REAL WorkspaceStore — the desktop wiring, minusawait fs.writeFile(filePath, JSON.stringify(edited))const fresh = new WorkspaceStore()await fresh.load()+ recordFreshSpawnOwner('b1', 'p1')const { outcome } = await deliverFromControl(req, storeDeps(fresh))expect(outcome).toEqual({ kind: 'notPermitted', reason: 'switch-off' })})@@ -276,8 +294,151 @@ describe('end to end through a REAL WorkspaceStore — the desktop wiring, minusawait store.save(ws(project({ agentMessaging: true, capabilityAck: { agentMessaging: 'kept' } })))+ recordFreshSpawnOwner('b1', 'p1')const deps = storeDeps(store)const { outcome } = await deliverFromControl(req, deps)expect(outcome.kind).toBe('delivered')})})++describe('runtime pane-ownership gate (PR #237 fix round 2) — over a REAL store + ledger', () => {+ let userData: string+ let projRoot: string++ const project = (over: Partial<Project> = {}): Project => ({+ id: 'p1',+ name: 'msg',+ color: '#7aa2f7',+ viewport: { x: 0, y: 0, zoom: 1 },+ nodes: [] as Project['nodes'],+ ...over+ })+ const node = (id: string, title: string) =>+ ({ id, kind: 'terminal', position: { x: 0, y: 0 }, size: { width: 1, height: 1 }, title, color: '#fff', group: null, agentId: 'claude' })+ const ws2 = (p: Project): Workspace => ({ version: 2, activeProjectId: p.id, projects: [p] })++ beforeEach(async () => {+ userData = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-own-'))+ projRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-own-proj-'))+ initPlatform(fakePlatform({ userDataDir: userData }))+ })+ afterEach(async () => {+ resetPlatformForTests()+ await fs.rm(userData, { recursive: true, force: true })+ await fs.rm(projRoot, { recursive: true, force: true })+ })++ const storeDeps = (store: WorkspaceStore) =>+ baseDeps({+ projects: () => store.persistedCanvases(),+ messagingEnabled: messagingEnabledVia((id) => store.capabilityProjectFor(id)),+ paneOwnerProject: (id) => paneOwnerProject(id)+ })++ it('FAIL-OPEN CLOSED: victim project ABSENT from the store, its pane live — granted attacker listing the id is REFUSED, not delivered', async () => {+ // The re-review's Critical, driven end to end. Project A is granted+kept and its (hostile)+ // project.json is the SOLE store claimant of `victim-1` — the real owner B is not persisted at+ // all, so the round-1 ambiguity check (which needs two store claimants) does NOT fire and scope+ // resolves same-project=A. Pre-round-2 the switch then passed on A and the envelope reached+ // victim-1's one global pane (outcome=delivered, reply.ok=true). Now the RUNTIME ledger is the+ // authority: victim-1 was freshly spawned by B this run, so its proven owner is 'victim-proj',+ // which is NOT A — refused, nothing written.+ const store = new WorkspaceStore()+ const attacker = project({+ id: 'attacker',+ name: 'cloned-hostile',+ cwd: projRoot,+ agentMessaging: true,+ capabilityAck: { agentMessaging: 'kept' },+ nodes: [node('atk-1', 'Atk'), node('victim-1', 'Stolen')] as Project['nodes']+ })+ // Victim B is NOT in the persisted store — only its pane runs. That is the whole point.+ await store.save({ version: 2, activeProjectId: 'attacker', projects: [attacker] })+ recordFreshSpawnOwner('victim-1', 'victim-proj') // B's create() genuinely spawned it this run+ const deps = storeDeps(store)+ const { outcome, reply } = await deliverFromControl(+ { verb: 'send', sourceNodeId: 'atk-1', targetNodeId: 'victim-1', body: 'sneak' } as never,+ deps+ )+ expect(outcome).toEqual({ kind: 'notPermitted', reason: 'unproven-target-owner' })+ expect(reply.ok).toBe(false)+ expect(deps.sent).toEqual([]) // NOTHING reached the victim's pane+ })++ it('LEDGER EMPTY (post-restart re-attach): a live pane with no runtime owner is UNPROVEN → refused', async () => {+ // After an app restart the tmux server survives, the renderer re-ATTACHES (fresh===false, so+ // nothing is recorded), and the ledger is empty. A pane in that state is unproven and must be+ // refused — the fail-closed cold-state direction. (Same store shape as the attack, minus the+ // ledger record.)+ const store = new WorkspaceStore()+ const attacker = project({+ id: 'attacker',+ name: 'cloned-hostile',+ cwd: projRoot,+ agentMessaging: true,+ capabilityAck: { agentMessaging: 'kept' },+ nodes: [node('atk-1', 'Atk'), node('victim-1', 'Stolen')] as Project['nodes']+ })+ await store.save({ version: 2, activeProjectId: 'attacker', projects: [attacker] })+ // resetPaneOwnershipForTests() in beforeEach already emptied it; record NOTHING.+ const deps = storeDeps(store)+ const { outcome } = await deliverFromControl(+ { verb: 'send', sourceNodeId: 'atk-1', targetNodeId: 'victim-1', body: 'x' } as never,+ deps+ )+ expect(outcome).toEqual({ kind: 'notPermitted', reason: 'unproven-target-owner' })+ expect(deps.sent).toEqual([])+ })++ it('LEGITIMATE self-delivery: a project messaging a node IT freshly spawned, granted+kept → delivered', async () => {+ // Proves the fix is not "refuse everything": when the ledger owner matches the store project+ // AND that project holds the grant, the delivery proceeds to the pane write.+ const store = new WorkspaceStore()+ await store.save(+ ws2(+ project({+ id: 'p1',+ cwd: projRoot,+ agentMessaging: true,+ capabilityAck: { agentMessaging: 'kept' },+ nodes: [node('a1', 'Alpha'), node('b1', 'Beta')] as Project['nodes']+ })+ )+ )+ recordFreshSpawnOwner('b1', 'p1') // p1's own create() spawned b1+ const deps = storeDeps(store)+ const { outcome } = await deliverFromControl(+ { verb: 'send', sourceNodeId: 'a1', targetNodeId: 'b1', body: 'hi' } as never,+ deps+ )+ expect(outcome.kind).toBe('delivered')+ expect(deps.sent).toHaveLength(1)+ })++ it('ledger owner DISAGREES with the sole store claimant → refused even when that claimant is granted', async () => {+ // The cross-check leg: the store says p1 owns b1 and p1 is granted, but the RUNTIME ledger+ // says someone else spawned b1 (a stale/forged store claim over a live foreign pane). The+ // disagreement itself is disqualifying — the grant of a project that did not spawn the pane+ // cannot authorize a write into it.+ const store = new WorkspaceStore()+ await store.save(+ ws2(+ project({+ id: 'p1',+ cwd: projRoot,+ agentMessaging: true,+ capabilityAck: { agentMessaging: 'kept' },+ nodes: [node('a1', 'Alpha'), node('b1', 'Beta')] as Project['nodes']+ })+ )+ )+ recordFreshSpawnOwner('b1', 'someone-else')+ const deps = storeDeps(store)+ const { outcome } = await deliverFromControl(+ { verb: 'send', sourceNodeId: 'a1', targetNodeId: 'b1', body: 'hi' } as never,+ deps+ )+ expect(outcome).toEqual({ kind: 'notPermitted', reason: 'unproven-target-owner' })+ expect(deps.sent).toEqual([])+ })+})diff --git a/src/main/agent-messaging.test.ts b/src/main/agent-messaging.test.tsindex e9f10043c..2f70f467d 100644--- a/src/main/agent-messaging.test.ts+++ b/src/main/agent-messaging.test.ts@@ -36,6 +36,12 @@ interface Recorded {function fakeDeps(over: Partial<AgentMessagingDeps> = {}): AgentMessagingDeps & { rec: Recorded } {const rec: Recorded = { paneOwnerCalls: [], sent: [] }+ const projectsFn =+ over.projects ??+ (() => [+ { id: 'p1', nodes: [{ id: 'a1', title: 'Alpha', agentId: 'claude' }, { id: 'b1', title: 'Beta', agentId: 'claude' }] },+ { id: 'p2', nodes: [{ id: 'c2', title: 'Gamma', agentId: 'claude' }] }+ ])return {rec,paneOwner: async (nodeId) => {@@ -55,12 +61,13 @@ function fakeDeps(over: Partial<AgentMessagingDeps> = {}): AgentMessagingDeps &},hasLiveSession: () => true,mirrorEntry: () => idle,- projects: () => [- { id: 'p1', nodes: [{ id: 'a1', title: 'Alpha', agentId: 'claude' }, { id: 'b1', title: 'Beta', agentId: 'claude' }] },- { id: 'p2', nodes: [{ id: 'c2', title: 'Gamma', agentId: 'claude' }] }- ],+ projects: projectsFn,isRemoteNode: () => false,messagingEnabled: () => true,+ // Ownership gate (PR #237 fix round 2): default to "proven-owned by whatever project the store+ // lists it in", so these pre-existing tests keep exercising the flow/scope/switch they were+ // written for. The ownership gate itself is proven in agent-messaging-switch.test.ts.+ paneOwnerProject: (id) => projectsFn().find((p) => p.nodes.some((n) => n.id === id))?.id,customAgents: () => undefined,appendBoardLog: async () => false,subscribeReceipts: (cb) => {diff --git a/src/main/agent-messaging.ts b/src/main/agent-messaging.tsindex 3310949b3..dda80a1a5 100644--- a/src/main/agent-messaging.ts+++ b/src/main/agent-messaging.ts@@ -74,6 +74,15 @@ export interface AgentMessagingDeps {* file bit. Read per call, so an off-toggle or a decline takes effect on the next delivery.*/messagingEnabled(projectId: string): boolean+ /**+ * The project that PROVABLY spawned the target node's pane this run, or `undefined` when+ * unproven (runtime ledger, `core/agents/pane-ownership.ts`). The delivery gate trusts THIS,+ * not the persisted store's node-set, to decide whose grant applies — the store is+ * attacker-writable (`project.json` lists any node id) and cannot tell a real owner from a+ * project that merely listed a live pane it never spawned (PR #237 fix round 2). Undefined ⇒+ * refuse `unproven-target-owner`.+ */+ paneOwnerProject(nodeId: string): string | undefinedcustomAgents(): readonly { id: string; launchCmd: string }[] | undefinedappendBoardLog(projectId: string, entry: BoardLogEntry): Promise<boolean>/** Test seam: override the receipt subscription. Production uses the module bus below. */@@ -167,7 +176,11 @@ const NOT_PERMITTED_TEXT: Record<NotPermittedReason, string> = {'ambiguous-target-node-id':'that node id exists in more than one project, so the target pane cannot be attributed to a ' +'single project\'s messaging grant. De-duplicate the id (re-add the cloned folder to mint ' +- 'fresh ids) before messaging it.'+ 'fresh ids) before messaging it.',+ 'unproven-target-owner':+ 'the target pane\'s owning project cannot be proven at runtime (it was not freshly spawned in ' ++ 'this session, or its ownership is disputed), so a per-project messaging grant cannot be ' ++ 'applied to it. Re-open the target node so its owner is recorded, then try again.'}/**@@ -327,8 +340,18 @@ export async function deliverFromControl(const scope = resolveDeliveryScope(projects, req.sourceNodeId, req.targetNodeId)let notPermitted = scopeRefusal(scope)const projectId = scope.kind === 'same-project' ? scope.projectId : undefined- if (!notPermitted && (!projectId || !deps.messagingEnabled(projectId)))- notPermitted = 'switch-off'+ if (!notPermitted) {+ // OWNERSHIP IS PROVEN AT RUNTIME, NOT READ FROM THE STORE (PR #237 fix round 2). The scope+ // above resolved `projectId` from the persisted node-set, which is attacker-writable — a+ // hostile `project.json` can LIST a live pane's node id it never spawned, and when the real+ // owner is absent from the store that hostile project is the sole claimant. The ledger records+ // who actually SPAWNED the pane this run; the grant is evaluated against THAT owner, and the+ // store's `projectId` is only a cross-check. Unprovable — no ledger entry (restart / never+ // spawned here), or the ledger owner disagrees with the sole store claimant — fails closed.+ const owner = projectId ? deps.paneOwnerProject(req.targetNodeId) : undefined+ if (!projectId || !owner || owner !== projectId) notPermitted = 'unproven-target-owner'+ else if (!deps.messagingEnabled(owner)) notPermitted = 'switch-off'+ }// Flow control (PR #208), taken as a RESERVATION rather than a pure read: `checkFlowLimits`// followed later by `noteSent` is not atomic, and N parallel sends to N distinct targets woulddiff --git a/src/main/index.ts b/src/main/index.tsindex 8d49b4b5c..e1612db84 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -78,6 +78,7 @@ import {nodeSessionName,workingNodes} from '../core/agent-status-mirror'+import { paneOwnerProject } from '../core/agents/pane-ownership'import { createPushNotify, createLiveUpdatePush } from '../core/push-notify'import { createGrantsAccessor, type PushGrant } from '../core/push-grants'import { createRemoteGrantsCache } from '../core/remote-push-grants'@@ -935,6 +936,10 @@ app.whenReady().then(async () => {// clone notice (projectCapabilityGrantedFor — never the raw file bit). Read per call off// the store's index, so a decline or an off-toggle refuses the very next delivery.messagingEnabled: messagingEnabledVia((id) => workspaceStore.capabilityProjectFor(id)),+ // Runtime pane ownership: which project actually SPAWNED the target's pane this run+ // (core/agents/pane-ownership.ts). The gate trusts this over the attacker-writable store to+ // decide whose grant applies; unproven ⇒ refused (PR #237 fix round 2).+ paneOwnerProject: (id) => paneOwnerProject(id),customAgents: () => settingsStore.get().customAgents,appendBoardLog: (projectId, entry) => appendBoardLogVia(boardLogRouter, projectId, entry)})diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 013ff9dfd..990933647 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -2413,6 +2413,12 @@ export function TerminalNode({shellArgs: localSsh ? buildSshArgs(ssh) : undefined,cwd: data.cwd,persistKey: id,+ // The project that OWNS this node, for the runtime pane-ownership ledger (agent+ // messaging, src/core/agents/pane-ownership.ts): the ssh project's own scope for a remote+ // node, else the active project whose canvas this node lives on. Recorded main-side ONLY+ // on a genuine fresh spawn, so a second project opening another's live node id cannot+ // claim it. Machine-local id, never the git-shared project.json id.+ ownerProjectId: sshProjectId ?? useProjects.getState().activeProjectId,agentId: data.agentId,accountId: data.accountId,sshRemote,diff --git a/src/shared/types.ts b/src/shared/types.tsindex 585c3deab..c5e26cd4a 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -21,6 +21,14 @@ export interface PtyCreateOptions {* terminal reattaches to the same session across remounts and app restarts.*/persistKey?: string+ /**+ * The machine-local id (`IndexEntryV3.id`) of the project this node belongs to, as the renderer+ * knows it at the create call. Recorded in the runtime pane-ownership ledger on a GENUINE FRESH+ * spawn (`agents/pane-ownership.ts`) so agent messaging can prove which project actually spawned+ * a pane rather than trusting the git-shared, forgeable `project.json`. Optional: absent ⇒ the+ * pane is left unproven and messaging to it fails closed (never derived from the file id).+ */+ ownerProjectId?: string/*** Which agent runs in this session (claude/codex/gemini/custom). Drives the hook env* injected at spawn. Defaults to 'claude' for backward compat; the renderer passes a