diff --git a/docs/changelog/2026-12-04.md b/docs/changelog/2026-12-04.md new file mode 100644 index 000000000..6964b0032 --- /dev/null +++ b/docs/changelog/2026-12-04.md @@ -0,0 +1,41 @@ +# 4 December 2026 — Agents never own rooms, and legacy agent-owned canvases recover + +An agent (`isocan identity --session` or proxy session claim) creating a +canvas left `project.createdBy` stamped with the agent's own actor ID. On a +hosted home like `isocan.corp.goog`, the browser badge held the person's own +actor and verified email rather than the proxy agent's claim — so setting +the link to `read` swept the human down to read-only, locked the Share dialog +out, and `namesTheCreator` refused an explicit owner grant because it treated +the creator as already owning the canvas by right. + +Ownership is now human-only, and existing agent-owned canvases resolve back to +their person: + +- **Server enforcement (`AGENT_OWNER` / `agent-owner`):** `project.create` + (`Engine.submit` and `createProject`), `POST /api/spaces`, and + `POST /api/groups` refuse actors classified as `"agent"` in `actorKinds`. +- **Client owner resolution (`resolveOwnerActor`):** `@isocan/api` (`ctx.ts` + directory binding/creation), `@isocan/cli` (room, space, group, and mutating + share commands via `ownerCtx`), and `@isocan/voice-agent` (`POST /canvas/create` + and `project_create`) resolve the badge's human actor (`home:person`, another + person-harness claim, or `~/.isocan/identity.json` reclaimed under + `home:person`) before creating or administering ownership. +- **Recovery and floor fixes:** `admittingGrant` and `heldRung` share + `claimsCanvasCreator` (via `CreatorOwnership`), recognizing the human who + `ownsAgent` a legacy agent `createdBy`; `admittingGrant` checks the + creator/space floor before returning any grant below `edit`; `ws.ts` and + `GET /api/projects/:id/canvas` elevate capability to `own` for legacy + agent-owned canvases owned by the caller's person; and `namesTheCreator` + returns `false` when `createdBy` is an agent so explicit email grants remain + issuable. + +Also landed today on `main`: + +- **Embedded mode & navigation:** Web app preserves `?embed=1&chat=0` across + client-side navigation, emits `isocan:active-canvas` (`ed7626e51`), moves + the home `TopNav` inline to top-left without the redundant wordmark + (`7a69801ba`), and cleans a literal canvas path from a `panels.ts` comment + (`07b41dd56`). +- **CI & daily reviews:** Fixed `catalog-budget` test guards and closed + `2026-11-30` reviewer findings (`af779e65d`), merged daily persona runs + (`d09ea404f`), and synced the `2026-11-29` changelog (`ec7f423d2`). diff --git a/docs/changelog/README.md b/docs/changelog/README.md index 7631c9c87..24cc8c8b0 100644 --- a/docs/changelog/README.md +++ b/docs/changelog/README.md @@ -17,6 +17,7 @@ screen per day, one row per week, open to anyone with the address. | Day | | What happened | | --- | --- | --- | +| **[4 Dec](2026-12-04.md)** | Agents never own rooms, and legacy agent-owned canvases recover | Refused agent actors on `project.create`, spaces, and groups (`agent-owner`); resolved the human owner in `@isocan/api`, `@isocan/cli`, and `@isocan/voice-agent`; and fixed `admittingGrant`/`heldRung`/`namesTheCreator` so legacy agent-created canvases resolve `own` back to the human who owns the agent. Also preserved `?embed=1&chat=0` across web navigation and moved home `TopNav` inline. | | **[29 Nov](2026-11-29.md)** | *Draft* | Not written up yet: the day's commits, quoted in full. Whoever writes the entry replaces this row. | | **[28 Nov](2026-11-28.md)** | *Draft* | Not written up yet: the day's commits, quoted in full. Whoever writes the entry replaces this row. | | **[27 Nov](2026-11-27.md)** | *Draft* | Not written up yet: the day's commits, quoted in full. Whoever writes the entry replaces this row. | diff --git a/index.mjs b/index.mjs index 8e899483d..51bf7f42e 100644 --- a/index.mjs +++ b/index.mjs @@ -161,6 +161,7 @@ export const { requireIdentity, resolveExplicitIdentity, resolveIdentity, + resolveOwnerActor, resolved, retireStrandedIdentities, writeIdentity, diff --git a/packages/api/src/ctx.ts b/packages/api/src/ctx.ts index 5b8d5b738..af8288225 100644 --- a/packages/api/src/ctx.ts +++ b/packages/api/src/ctx.ts @@ -25,6 +25,7 @@ import { requireIdentity, resolveExplicitIdentity, resolveIdentity, + resolveOwnerActor, reclaimIdentity, retireStrandedIdentities, type ExplicitIdentity, @@ -808,7 +809,8 @@ function refuseOfflineBirth(binding: DirBinding): void { */ async function materializeBinding(ctx: Ctx, binding: DirBinding): Promise { const title = binding.title ?? path.basename(binding.root); - await ctx.client.sendOp(null, ctx.actor, { + const owner = await resolveOwnerActor(ctx.client, ctx.home, ctx.actor); + await ctx.client.sendOp(null, owner, { type: "project.create", canvasId: binding.canvasId, title, @@ -843,9 +845,10 @@ async function bindFresh(ctx: Ctx): Promise { // byte what it was. const birth = ctx.birthHome; const markerHome = birth ?? (ctx.client.direct ? ctx.client.base : null); + const owner = await resolveOwnerActor(ctx.client, ctx.home, ctx.actor); await ctx.client.sendOp( null, - ctx.actor, + owner, { type: "project.create", canvasId, title }, undefined, birth ?? undefined, @@ -905,9 +908,10 @@ export async function ensureDirBinding( // marker's id could be minted a second time locally. refuseOfflineBirth(binding); const title = binding.title ?? path.basename(binding.root); + const owner = await resolveOwnerActor(client, home, actor); await client.sendOp( null, - actor, + owner, { type: "project.create", canvasId: binding.canvasId, title }, undefined, birthHome ?? undefined, @@ -923,9 +927,10 @@ export async function ensureDirBinding( if (!root) return null; const canvasId = newCanvasId(); const title = path.basename(root); + const owner = await resolveOwnerActor(client, home, actor); await client.sendOp( null, - actor, + owner, { type: "project.create", canvasId, title }, undefined, birthHome ?? undefined, diff --git a/packages/api/src/identity.ts b/packages/api/src/identity.ts index 6e0d18ccd..a40c7c0d4 100644 --- a/packages/api/src/identity.ts +++ b/packages/api/src/identity.ts @@ -19,7 +19,7 @@ import os from "node:os"; import path from "node:path"; import readline from "node:readline/promises"; import type { Actor, ActorBindingRecord, ActorClaimOp } from "@isocan/core"; -import { BADGE_ENDED, elapsedLabel } from "@isocan/core"; +import { agentOwnerMessage, BADGE_ENDED, elapsedLabel, harnessOf, isAgentHarness } from "@isocan/core"; import { adoptIdentity as adoptStoredIdentity, paths, writeIdentityActor, writeIdentityName } from "@isocan/server"; import { ApiError } from "./routes.ts"; import type { DaemonClient } from "./client.ts"; @@ -608,3 +608,42 @@ export async function requireIdentity(client: DaemonClient, home: string): Promi console.error(`Hi ${actor.name} — identity saved to ${paths.identityFile(home)}`); return actor; } + +/** + * Resolve the human actor who owns rooms/spaces/groups created from this + * machine or proxy badge. If `current` is already a person (or unknown to be an + * agent), return `current`; if `current` is an agent, resolve `home:person` or + * another person claim on the badge, or claim `identity.json` under `home:person`. + */ +export async function resolveOwnerActor( + client: DaemonClient, + home: string, + current: Actor, + noun: "canvas" | "space" | "group" = "canvas", +): Promise { + if (isBadgeUpstream()) return current; + await client.ensureDaemon(); + const [kinds, bindings] = await Promise.all([ + client.actorKinds().catch(() => null), + legacyTolerant(client.actorBindings()).catch(() => null), + ]); + const isAgent = kinds + ? kinds[current.id] === "agent" + : bindings?.some((b) => b.actor.id === current.id && isAgentHarness(harnessOf(b.key))) ?? false; + if (!isAgent) return current; + + const homePerson = bindings?.find((b) => b.key === HOME_CLAIM_KEY && kinds?.[b.actor.id] !== "agent"); + if (homePerson) return homePerson.actor; + const anyPerson = bindings?.find((b) => { + const harness = harnessOf(b.key); + return !isAgentHarness(harness) && harness?.toLowerCase() !== "replica" && kinds?.[b.actor.id] !== "agent"; + }); + if (anyPerson) return anyPerson.actor; + + const localPerson = await readIdentity(home); + if (localPerson) { + await reclaimIdentity(client, { actor: localPerson, key: HOME_CLAIM_KEY }); + return localPerson; + } + throw new Error(agentOwnerMessage(noun, current.name)); +} diff --git a/packages/api/test/connect.test.ts b/packages/api/test/connect.test.ts index 19f24c501..382ee18fe 100644 --- a/packages/api/test/connect.test.ts +++ b/packages/api/test/connect.test.ts @@ -113,8 +113,9 @@ describe("connect()", () => { it("canvases open by ref off one connection, and the only canvas is the default reach", async () => { await claim("acme-board", "acme", "Roster"); const h = await connect({ port, identity: { session: "acme-board", harness: "acme" } }); + const owner = (await h.ctx.client.claimActor({ type: "actor.claim", sessionKey: "home:owner", name: "Owner" })).envelope.actor; const canvasId = newCanvasId(); - await h.ctx.client.sendOp(null, h.actor, { + await h.ctx.client.sendOp(null, owner, { type: "project.create", canvasId, title: "Acme Panels", @@ -129,8 +130,9 @@ describe("connect()", () => { it("content goes in as a value and the op returns what it made — version, blobHash, place", async () => { await claim("acme-board", "acme", "Roster"); const h = await connect({ port, identity: { session: "acme-board", harness: "acme" } }); + const owner = (await h.ctx.client.claimActor({ type: "actor.claim", sessionKey: "home:owner", name: "Owner" })).envelope.actor; const canvasId = newCanvasId(); - await h.ctx.client.sendOp(null, h.actor, { + await h.ctx.client.sendOp(null, owner, { type: "project.create", canvasId, title: "Acme Panels", @@ -189,8 +191,9 @@ describe("connect()", () => { it("unreachable is a typed refusal, not a stack trace", async () => { await claim("acme-board", "acme", "Roster"); const h = await connect({ port, identity: { session: "acme-board", harness: "acme" } }); + const owner = (await h.ctx.client.claimActor({ type: "actor.claim", sessionKey: "home:owner", name: "Owner" })).envelope.actor; const canvasId = newCanvasId(); - await h.ctx.client.sendOp(null, h.actor, { + await h.ctx.client.sendOp(null, owner, { type: "project.create", canvasId, title: "Acme Panels", diff --git a/packages/api/test/design-audit.test.ts b/packages/api/test/design-audit.test.ts index 72a5161cf..0108738f0 100644 --- a/packages/api/test/design-audit.test.ts +++ b/packages/api/test/design-audit.test.ts @@ -33,9 +33,9 @@ beforeEach(async () => { const address = daemon.app.server.address(); if (!address || typeof address === "string") throw new Error("No daemon address"); const client = new DaemonClient(`http://127.0.0.1:${address.port}`, home); - await client.claimActor({ type: "actor.claim", sessionKey: "acme:design-audit", name: "Acme Audit" }); - const actor = (await client.actorBindings(["acme:design-audit"]))[0]!.actor; - ctx = { client, actor, home, harness: "acme", birthHome: null, binding: null, + await client.claimActor({ type: "actor.claim", sessionKey: "home:design-audit", name: "Acme Audit" }); + const actor = (await client.actorBindings(["home:design-audit"]))[0]!.actor; + ctx = { client, actor, home, harness: null, birthHome: null, binding: null, homeOf: async () => null, homes: async () => ({ birth: null, links: [], rows: {}, legacy: false, rowFor: () => null }) }; }); diff --git a/packages/api/test/design-craft.test.ts b/packages/api/test/design-craft.test.ts index 6f3acf913..fab2cc0ba 100644 --- a/packages/api/test/design-craft.test.ts +++ b/packages/api/test/design-craft.test.ts @@ -142,7 +142,7 @@ it("distinguishes known absence from denied inherited authority and preserves it const f = await designReviewFixture(true); fixture = f; await f.agentCanvas.remove(f.system.id); expect((await f.agentCanvas.designCraft(f.requestId, "new-work")).governing.status).toBe("none"); - const libraryId = newCanvasId(); await f.client.sendOp(null, f.agent.actor, { type: "project.create", canvasId: libraryId, title: "Acme craft library" }); + const libraryId = newCanvasId(); await f.client.sendOp(null, f.person.actor, { type: "project.create", canvasId: libraryId, title: "Acme craft library" }); const library = new CanvasHandle(f.agent, (await f.client.snapshot(libraryId)).project); await library.add({ title: "Acme inherited system", content: auditDesign(), mime: "text/markdown", filename: "DESIGN.md", properties: designSystemProperties() }); await f.agentCanvas.add({ title: "Acme inherited link", content: f.base, mime: "text/plain", properties: { ...canvasItemOf(f.base, libraryId).properties, memory: "inherit" } }); diff --git a/packages/api/test/design-system.test.ts b/packages/api/test/design-system.test.ts index be76bb9fd..a98a36b0e 100644 --- a/packages/api/test/design-system.test.ts +++ b/packages/api/test/design-system.test.ts @@ -71,7 +71,7 @@ it("retains lost-ack intent, refuses stale metadata before upload, and keeps acc it("opens and reconciles inherited bytes through policy-bearing actual reads and writes, retaining exemption independently", async () => { const f = fixture = await questionnaireFixture(), libraryId = newCanvasId(); - await f.client.sendOp(null, f.agent.actor, { type: "project.create", canvasId: libraryId, title: "Acme library" }); + await f.client.sendOp(null, f.person.actor, { type: "project.create", canvasId: libraryId, title: "Acme library" }); const library = new CanvasHandle(f.agent, (await f.client.snapshot(libraryId)).project); const item = await library.add({ title: "Acme inherited system", content: auditDesign("Acme library"), mime: "text/markdown", filename: "DESIGN.md", properties: designSystemProperties() }); await f.agentCanvas.add({ title: "Acme library source", content: f.base, mime: "text/plain", properties: { ...canvasItemOf(f.base, libraryId).properties, memory: "inherit" } }); diff --git a/packages/api/test/tail.test.ts b/packages/api/test/tail.test.ts index f74980f1f..05e9b6d2b 100644 --- a/packages/api/test/tail.test.ts +++ b/packages/api/test/tail.test.ts @@ -96,8 +96,9 @@ async function opened(): Promise<{ await client.claimActor({ type: "actor.claim", sessionKey: "acme:acme-other", name: "Other" }) ).envelope.actor; const h = await connect({ port, identity: { session: "acme-watch", harness: "acme" } }); + const owner = (await client.claimActor({ type: "actor.claim", sessionKey: "home:owner", name: "Owner" })).envelope.actor; const canvasId = newCanvasId(); - await h.ctx.client.sendOp(null, h.actor, { + await h.ctx.client.sendOp(null, owner, { type: "project.create", canvasId, title: "Acme Panels", diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts index a12c4eef2..436415a6e 100644 --- a/packages/cli/src/main.ts +++ b/packages/cli/src/main.ts @@ -513,6 +513,7 @@ import { becomeHomePerson, readIdentity, claimSessionIdentity, + resolveOwnerActor, linkedCanvasesOf, readDesignSystem, designSystemPort, @@ -2960,6 +2961,14 @@ program const ctx = await ctxOf(cmd); if (opts.space !== undefined) return shareSpace(ctx, await resolveSpace(ctx, opts.space), who, opts); const canvas = await resolveCanvas(ctx); + const mutatingShare = + opts.public !== undefined || + opts.link !== undefined || + who !== undefined || + opts.revoke !== undefined || + opts.bar !== undefined || + opts.unbar !== undefined; + const writeCtx = mutatingShare ? await ownerCtx(ctx) : ctx; /** * **The desk check first** (proactive-agent phase 8): before an act that * lets people in, or a look at the address, the canvas is read the way a @@ -2989,7 +2998,7 @@ program if (opts.public !== undefined) { const live = (await ctx.client.grants(canvas.id)).grants.find((grant) => grant.subject === LINK); if (!live || !canListGrant(live)) throw new Error("--public needs a current Canvas Viewer or Presentation Viewer link; choose --link read or --link view first"); - await ctx.client.setPublicListing(canvas.id, live.id, opts.public === "on", ctx.actor.id); + await writeCtx.client.setPublicListing(canvas.id, live.id, opts.public === "on", writeCtx.actor.id); } /** * What the sweeps this invocation ran did, added up. @@ -3029,7 +3038,7 @@ program // one of them into a failure. if (capability !== null) { if (!live || capabilityOf(live) !== capability) { - sweepAlso((await ctx.client.createGrant(canvas.id, LINK, capability, ctx.actor.id)).swept); + sweepAlso((await writeCtx.client.createGrant(canvas.id, LINK, capability, writeCtx.actor.id)).swept); } } // Off with no live row is not an error either — the gesture is "the @@ -3041,13 +3050,13 @@ program // BELOW the status lines, not above them, or the command opens with // a number nobody has been given a subject for yet. Absent from a // home that predates the sweep, which reads as nothing swept. - sweepAlso((await ctx.client.revokeGrant(canvas.id, live.id, ctx.actor.id)).swept); + sweepAlso((await writeCtx.client.revokeGrant(canvas.id, live.id, writeCtx.actor.id)).swept); } } // The four row gestures — un-invite, keep out, let back in, invite — // are one function for a canvas and for a space (`shareRows`). - await shareRows(ctx, canvasScope(ctx, canvas), who, opts, sweepAlso); + await shareRows(writeCtx, canvasScope(writeCtx, canvas), who, opts, sweepAlso); // `turnedOff` (operator phase 5): the rows the operator of this home // turned off and nothing has replaced — absent from a home that has @@ -3385,12 +3394,24 @@ async function shareRows( * own. Every other flag is `shareRows` over the space's rows, and each write * sweeps every canvas in the space. */ +async function ownerCtx(ctx: Ctx, noun: "canvas" | "space" | "group" = "canvas"): Promise { + const actor = await resolveOwnerActor(ctx.client, ctx.home, ctx.actor, noun); + return actor.id === ctx.actor.id ? ctx : { ...ctx, actor }; +} + async function shareSpace( ctx: Ctx, space: Space, who: string | undefined, opts: { link?: string; as?: string; revoke?: string; bar?: string | boolean; unbar?: string }, ): Promise { + const mutating = + opts.link !== undefined || + who !== undefined || + opts.revoke !== undefined || + opts.bar !== undefined || + opts.unbar !== undefined; + const writeCtx = mutating ? await ownerCtx(ctx, "space") : ctx; let swept: SweepReport | undefined; const sweepAlso = (report: SweepReport | undefined): void => { if (!report) return; @@ -3405,7 +3426,7 @@ async function shareSpace( if (capability === null) { throw new Error(`--link wants on, off, edit, read or view, got: ${opts.link}`); } - const answer = await ctx.client.setSpaceLink(space.id, capability, ctx.actor.id); + const answer = await writeCtx.client.setSpaceLink(space.id, capability, writeCtx.actor.id); sweepAlso(answer.swept); const reached = answer.reached === 1 ? "1 canvas" : `${answer.reached} canvases`; if (!ctx.json) { @@ -3416,7 +3437,7 @@ async function shareSpace( ); } } - await shareRows(ctx, spaceScope(ctx, space), who, opts, sweepAlso); + await shareRows(writeCtx, spaceScope(writeCtx, space), who, opts, sweepAlso); const { grants, turnedOff = [] } = await ctx.client.spaceGrants(space.id); const names = await ctx.client.actorNames(); @@ -3492,7 +3513,8 @@ spaceCommand .action( run(async (name: string, _opts: unknown, cmd: Command) => { const ctx = await ctxOf(cmd); - const { space } = await ctx.client.createSpace(name, ctx.actor.id); + const writeCtx = await ownerCtx(ctx, "space"); + const { space } = await writeCtx.client.createSpace(name, writeCtx.actor.id); if (ctx.json) return printJson(space); console.log( `made the space ${space.name} (${space.id}) — \`isocan space add ${space.name} …\` puts ` + @@ -3532,11 +3554,12 @@ spaceCommand .action( run(async (name: string, refs: string[], _opts: unknown, cmd: Command) => { const ctx = await ctxOf(cmd); + const writeCtx = await ownerCtx(ctx, "space"); const space = await resolveSpace(ctx, name); const canvases = await ctx.client.listCanvases(); for (const ref of refs) { const canvas = matchRef(canvases, ref); - const answer = await ctx.client.addToSpace(space.id, canvas.id, ctx.actor.id); + const answer = await writeCtx.client.addToSpace(space.id, canvas.id, writeCtx.actor.id); if (ctx.json) printJson(answer); else console.log(`${canvas.title} (${canvas.id}) is in ${space.name}${answer.reached === 0 ? " — it already was" : ""}`); } @@ -3549,11 +3572,12 @@ spaceCommand .action( run(async (name: string, refs: string[], _opts: unknown, cmd: Command) => { const ctx = await ctxOf(cmd); + const writeCtx = await ownerCtx(ctx, "space"); const space = await resolveSpace(ctx, name); const canvases = await ctx.client.listCanvases(); for (const ref of refs) { const canvas = matchRef(canvases, ref); - const answer = await ctx.client.removeFromSpace(space.id, canvas.id, ctx.actor.id); + const answer = await writeCtx.client.removeFromSpace(space.id, canvas.id, writeCtx.actor.id); if (ctx.json) printJson(answer); else if (answer.reached === 0) console.log(`${canvas.title} (${canvas.id}) was not in ${space.name}`); else console.log(`${canvas.title} (${canvas.id}) is out of ${space.name} — ${sweptLine(answer.swept)}`); @@ -3568,8 +3592,9 @@ spaceCommand .action( run(async (name: string, _opts: unknown, cmd: Command) => { const ctx = await ctxOf(cmd); + const writeCtx = await ownerCtx(ctx, "space"); const space = await resolveSpace(ctx, name); - const answer = await ctx.client.deleteSpace(space.id, ctx.actor.id); + const answer = await writeCtx.client.deleteSpace(space.id, writeCtx.actor.id); if (ctx.json) return printJson(answer); const reached = answer.reached === 1 ? "1 canvas" : `${answer.reached} canvases`; console.log(`deleted the space ${space.name} (${space.id}) — ${reached} kept, each with its own sharing; ${sweptLine(answer.swept)}`); @@ -3652,7 +3677,8 @@ groupCommand .action( run(async (name: string, _opts: unknown, cmd: Command) => { const ctx = await ctxOf(cmd); - const { group } = await ctx.client.createGroup(name, ctx.actor.id); + const writeCtx = await ownerCtx(ctx, "group"); + const { group } = await writeCtx.client.createGroup(name, writeCtx.actor.id); if (ctx.json) return printJson(group); console.log( `made the group ${group.name} (${group.id}) — \`isocan group add ${group.name}
…\` puts ` + @@ -3691,11 +3717,12 @@ groupCommand .action( run(async (name: string, addresses: string[], _opts: unknown, cmd: Command) => { const ctx = await ctxOf(cmd); + const writeCtx = await ownerCtx(ctx, "group"); const group = await resolveGroup(ctx, name); for (const address of addresses) { // Spelled as the home stores it, so the line names the row written. const member = normalizeSubject(grantSubjectOf(address)); - const answer = await ctx.client.addGroupMember(group.id, member, ctx.actor.id); + const answer = await writeCtx.client.addGroupMember(group.id, member, writeCtx.actor.id); if (ctx.json) printJson(answer); else if (answer.reached === 0 && answer.group.size === group.size) { console.log(`${member} was already in ${group.name}`); @@ -3716,10 +3743,11 @@ groupCommand .action( run(async (name: string, addresses: string[], _opts: unknown, cmd: Command) => { const ctx = await ctxOf(cmd); + const writeCtx = await ownerCtx(ctx, "group"); const group = await resolveGroup(ctx, name); for (const address of addresses) { const member = normalizeSubject(grantSubjectOf(address)); - const answer = await ctx.client.removeGroupMember(group.id, member, ctx.actor.id); + const answer = await writeCtx.client.removeGroupMember(group.id, member, writeCtx.actor.id); if (ctx.json) printJson(answer); else if (answer.reached === 0 && answer.group.size === group.size) { console.log(`${member} was not in ${group.name}`); @@ -3741,8 +3769,9 @@ groupCommand .action( run(async (name: string, _opts: unknown, cmd: Command) => { const ctx = await ctxOf(cmd); + const writeCtx = await ownerCtx(ctx, "group"); const group = await resolveGroup(ctx, name); - const answer = await ctx.client.deleteGroup(group.id, ctx.actor.id); + const answer = await writeCtx.client.deleteGroup(group.id, writeCtx.actor.id); if (ctx.json) return printJson(answer); const reached = answer.reached === 1 ? "1 canvas" : `${answer.reached ?? 0} canvases`; console.log(`deleted the group ${group.name} (${group.id}) — reached ${reached}; ${sweptLine(answer.swept ?? { expelled: 0, rerooted: 0 })}`); @@ -5280,7 +5309,8 @@ canvas const ctx = await ctxOf(cmd); const space = opts.space === undefined ? null : await resolveSpace(ctx, opts.space); const canvasId = newCanvasId(); - await sendOp(ctx, null, { + const writeCtx = await ownerCtx(ctx); + await sendOp(writeCtx, null, { type: "project.create", canvasId, title, @@ -11259,7 +11289,8 @@ sprintCmd const name = words.join(" ").trim(); if (!name) throw new Error("whose desk? — `isocan sprint desk Theo`"); const canvasId = newCanvasId(); - await sendOp(ctx, null, { + const writeCtx = await ownerCtx(ctx); + await sendOp(writeCtx, null, { type: "project.create", canvasId, title: deskTitle(name), @@ -11269,7 +11300,7 @@ sprintCmd // The link grant every canvas is born with is the one thing that would // let anybody with the address in. Off, before the address exists. const link = (await ctx.client.grants(canvasId)).grants.find((g) => g.subject === LINK); - if (link) await ctx.client.revokeGrant(canvasId, link.id); + if (link) await writeCtx.client.revokeGrant(canvasId, link.id, writeCtx.actor.id); // One pass, one browser, once. Admit-only: the sketcher names // themselves at the door, the way anyone entering a canvas does. const origin = (await ctx.homeOf(canvasId)) ?? ctx.client.base; diff --git a/packages/cli/test/agent-semantics.test.ts b/packages/cli/test/agent-semantics.test.ts index d1f427d0a..79cdd5294 100644 --- a/packages/cli/test/agent-semantics.test.ts +++ b/packages/cli/test/agent-semantics.test.ts @@ -80,7 +80,7 @@ beforeAll(async () => { actor = ( await client.sendOp(null, { id: "", name: "Acme Builder" }, { type: "actor.claim", - sessionKey: "test:cli-agent-semantics", + sessionKey: "home:cli-agent-semantics", name: "Acme Builder", }) ).envelope.actor; diff --git a/packages/cli/test/badge.ts b/packages/cli/test/badge.ts index 2e8d4d40c..c1716a06e 100644 --- a/packages/cli/test/badge.ts +++ b/packages/cli/test/badge.ts @@ -57,7 +57,7 @@ export async function mintTestBadge(base: string): Promise { badgeId: door.badgeId, token, headers, - async speakAs(actor, sessionKey = `test:${actor.id}`) { + async speakAs(actor, sessionKey = `home:${actor.id}`) { const claimed = await fetch(`${base}/api/ops`, { method: "POST", headers: { "Content-Type": "application/json", ...headers }, diff --git a/packages/cli/test/binding.test.ts b/packages/cli/test/binding.test.ts index 3eb76b557..b729b99cb 100644 --- a/packages/cli/test/binding.test.ts +++ b/packages/cli/test/binding.test.ts @@ -97,6 +97,7 @@ describe("the handshake binds a directory to its canvas", () => { expect(listed).toHaveLength(1); expect(listed[0]!.id).toBe(bound.projectId); expect(listed[0]!.title).toBe(path.basename(work)); + expect(listed[0]!.createdBy.id).toBe(nico.id); // The roster remembers where the canvas's directory lives. const roster = JSON.parse(await fs.readFile(path.join(home, "dirs.json"), "utf8")) as Record< string, diff --git a/packages/cli/test/direct.test.ts b/packages/cli/test/direct.test.ts index 63fceb111..ec51482b2 100644 --- a/packages/cli/test/direct.test.ts +++ b/packages/cli/test/direct.test.ts @@ -135,6 +135,12 @@ async function hasStore(): Promise { describe("declaring the mode", () => { it("ISOCAN_DIRECT= works the canvas with no daemon and no replica", async () => { + const person = await isocan(["identity", "--home", "--name", "Nico"], { + ISOCAN_DIRECT: homeUrl, + CLAUDE_CODE_SESSION_ID: "", + }); + expect(person.code, person.stderr).toBe(0); + // `--name` without `--session`: naming the agent, not binding the // directory. `identity --session` in a fresh directory would CREATE a // canvas, and this test is about the one it makes on purpose. @@ -391,6 +397,11 @@ describe("files, with nowhere to keep them", () => { * test in this file still passed. */ it("uploads, downloads and re-versions a file with no local store", async () => { + const person = await isocan(["identity", "--home", "--name", "Nico"], { + ISOCAN_DIRECT: homeUrl, + CLAUDE_CODE_SESSION_ID: "", + }); + expect(person.code, person.stderr).toBe(0); await isocan(["identity", "--name", "Sonia", "--session"], { ISOCAN_DIRECT: homeUrl }); const svg = (size: number) => ``; diff --git a/packages/cli/test/ground.test.ts b/packages/cli/test/ground.test.ts index 2e4688c4d..026ef2a19 100644 --- a/packages/cli/test/ground.test.ts +++ b/packages/cli/test/ground.test.ts @@ -58,6 +58,10 @@ beforeEach(async () => { homeStore = await fs.mkdtemp(path.join(os.tmpdir(), "isocan-ground-home-")); machine = await fs.mkdtemp(path.join(os.tmpdir(), "isocan-ground-machine-")); work = await fs.mkdtemp(path.join(os.tmpdir(), "isocan-ground-work-")); + await fs.writeFile( + path.join(machine, "identity.json"), + JSON.stringify({ id: "usr_nico", name: "Nico", createdAt: new Date().toISOString() }), + ); homeDaemon = await startDaemon({ port: 0, home: homeStore }); const address = homeDaemon.app.server.address(); homePort = typeof address === "object" && address ? address.port : 0; diff --git a/packages/cli/test/home.test.ts b/packages/cli/test/home.test.ts index 880f66196..5ed1e58b5 100644 --- a/packages/cli/test/home.test.ts +++ b/packages/cli/test/home.test.ts @@ -63,6 +63,10 @@ beforeEach(async () => { isocanHome = await fs.mkdtemp(path.join(os.tmpdir(), "isocan-home-verb-")); upstreamDir = await fs.mkdtemp(path.join(os.tmpdir(), "isocan-home-verb-up-")); work = await fs.mkdtemp(path.join(os.tmpdir(), "isocan-home-verb-work-")); + await fs.writeFile( + path.join(isocanHome, "identity.json"), + JSON.stringify({ id: "usr_nico", name: "Nico", createdAt: new Date().toISOString() }), + ); port = await reservePort(); upstream = await startDaemon({ port: 0, home: upstreamDir, birthHome: null }); const address = upstream.app.server.address(); diff --git a/packages/cli/test/identity.test.ts b/packages/cli/test/identity.test.ts index f28cdd1da..5db29b307 100644 --- a/packages/cli/test/identity.test.ts +++ b/packages/cli/test/identity.test.ts @@ -126,9 +126,25 @@ describe("two parties, two identity slots", () => { await isocan(claude("s-1"), "canvas", "create", "Agent Canvas"); await isocan({}, "canvas", "create", "Human Canvas"); - const by = Object.fromEntries((await canvases()).map((p) => [p.title, p.createdBy.name])); - expect(by["Agent Canvas"]).toBe("Isaac"); + // Canvas ownership always resolves to the person, never the agent. + const list = await canvases(); + const by = Object.fromEntries(list.map((p) => [p.title, p.createdBy.name])); + expect(by["Agent Canvas"]).toBe("Nico"); expect(by["Human Canvas"]).toBe("Nico"); + + // Canvas ops with a session still belong to Isaac; without one, to Nico. + const agentCanvas = list.find((p) => p.title === "Agent Canvas")!; + const humanCanvas = list.find((p) => p.title === "Human Canvas")!; + await isocan(claude("s-1"), "comment", "add", "from isaac", "--at", "0,0", "--canvas", agentCanvas.id); + await isocan({}, "comment", "add", "from nico", "--at", "0,0", "--canvas", humanCanvas.id); + const authorsOf = async (id: string) => + Object.values( + ((await fetch(`${base}/api/projects/${id}/canvas`, { headers: badge.headers }).then((r) => + r.json(), + )) as { canvas: { threads: Record } }).canvas.threads, + ).map((t) => t.createdBy.name); + expect(await authorsOf(agentCanvas.id)).toEqual(["Isaac"]); + expect(await authorsOf(humanCanvas.id)).toEqual(["Nico"]); }); it("--new makes you a different person instead of renaming this one", async () => { diff --git a/packages/cli/test/jobs.test.ts b/packages/cli/test/jobs.test.ts index f5437221a..af17906ed 100644 --- a/packages/cli/test/jobs.test.ts +++ b/packages/cli/test/jobs.test.ts @@ -91,7 +91,7 @@ beforeAll(async () => { client = new DaemonRoutes(`http://127.0.0.1:${port}`, badges); const claimed = await client.sendOp(null, { id: "", name: "Acme CLI" }, { type: "actor.claim", - sessionKey: "test:cli-jobs", + sessionKey: "home:cli-jobs", name: "Acme CLI", }); actor = claimed.envelope.actor; diff --git a/packages/cli/test/operator.test.ts b/packages/cli/test/operator.test.ts index fa5719c0c..eac5c58b7 100644 --- a/packages/cli/test/operator.test.ts +++ b/packages/cli/test/operator.test.ts @@ -333,7 +333,7 @@ describe("the real verbs, driven end to end", () => { headers, body: JSON.stringify({ canvasId: null, - op: { type: "actor.claim", sessionKey: "test:usr_priya", as: "usr_priya", name: "Priya" }, + op: { type: "actor.claim", sessionKey: "home:usr_priya", as: "usr_priya", name: "Priya" }, }), }); if (!claimed.ok) throw new Error(`could not claim Priya: ${await claimed.text()}`); diff --git a/packages/cli/test/park.test.ts b/packages/cli/test/park.test.ts index 74c5d5d10..79a1986f7 100644 --- a/packages/cli/test/park.test.ts +++ b/packages/cli/test/park.test.ts @@ -68,6 +68,10 @@ async function run(args: string[]): Promise<{ code: number; stdout: string; stde beforeEach(async () => { home = await fs.mkdtemp(path.join(os.tmpdir(), "isocan-park-home-")); work = await fs.mkdtemp(path.join(os.tmpdir(), "isocan-park-work-")); + await fs.writeFile( + path.join(home, "identity.json"), + JSON.stringify({ id: "usr_nico", name: "Nico", createdAt: new Date().toISOString() }), + ); port = await reservePort(); // A name first: `canvas create` speaks as somebody, and an unclaimed CLI // has nobody to be. Then a canvas for the park to watch. diff --git a/packages/cli/test/physics.test.ts b/packages/cli/test/physics.test.ts index f7ba29b8a..c0e7f369f 100644 --- a/packages/cli/test/physics.test.ts +++ b/packages/cli/test/physics.test.ts @@ -90,7 +90,7 @@ beforeAll(async () => { client = new DaemonRoutes(`http://127.0.0.1:${port}`, badges); const claimed = await client.sendOp(null, { id: "", name: "Acme Physics" }, { type: "actor.claim", - sessionKey: "test:cli-physics", + sessionKey: "home:cli-physics", name: "Acme Physics", }); actor = claimed.envelope.actor; diff --git a/packages/cli/test/session-identity.test.ts b/packages/cli/test/session-identity.test.ts index 5dec2cd26..6f6810295 100644 --- a/packages/cli/test/session-identity.test.ts +++ b/packages/cli/test/session-identity.test.ts @@ -100,6 +100,10 @@ const registry = async (): Promise<{ return { claims }; }; +/** Session claims excluding `home:person` (claimed when binding a directory canvas for the human owner). */ +const sessionKeys = (r: { claims: Record }): string[] => + Object.keys(r.claims).filter((k) => k !== "home:person"); + /** * Put a claim in the past. The claims table lives in the daemon's memory, so * aging a binding means editing the desk's snapshot UNDER a stopped daemon @@ -140,11 +144,30 @@ describe("two agents in one directory", () => { expect((await asAgent(claude("s-1"), "whoami")).stdout).toContain("Kenny"); expect((await asAgent(claude("s-2"), "whoami")).stdout).toContain("Isaac"); - await asAgent(claude("s-1"), "canvas", "create", "Kenny's Canvas"); - await asAgent(claude("s-2"), "canvas", "create", "Isaac's Canvas"); - const by = Object.fromEntries((await canvases()).map((p) => [p.title, p.createdBy.name])); - expect(by["Kenny's Canvas"]).toBe("Kenny"); - expect(by["Isaac's Canvas"]).toBe("Isaac"); + const kennyCanvas = await asAgent(claude("s-1"), "canvas", "create", "Kenny's Canvas"); + expect(kennyCanvas.code, kennyCanvas.stderr).toBe(0); + const isaacCanvas = await asAgent(claude("s-2"), "canvas", "create", "Isaac's Canvas"); + expect(isaacCanvas.code, isaacCanvas.stderr).toBe(0); + + // Canvas ownership always belongs to the human, while ops by each agent carry their own actor. + const list = await canvases(); + const by = Object.fromEntries(list.map((p) => [p.title, p.createdBy.name])); + expect(by["Kenny's Canvas"]).toBe("Nico"); + expect(by["Isaac's Canvas"]).toBe("Nico"); + + const kc = list.find((p) => p.title === "Kenny's Canvas")!; + const ic = list.find((p) => p.title === "Isaac's Canvas")!; + expect((await asAgent(claude("s-1"), "comment", "add", "hi from kenny", "--at", "0,0", "--canvas", kc.id)).code).toBe(0); + expect((await asAgent(claude("s-2"), "comment", "add", "hi from isaac", "--at", "0,0", "--canvas", ic.id)).code).toBe(0); + const headers = await badgeHeaders(); + const authorOf = async (canvasId: string) => + Object.values( + ((await fetch(`${base}/api/projects/${canvasId}/canvas`, { headers }).then((r) => + r.json(), + )) as { canvas: { threads: Record } }).canvas.threads, + ).map((t) => t.createdBy.name); + expect(await authorOf(kc.id)).toEqual(["Kenny"]); + expect(await authorOf(ic.id)).toEqual(["Isaac"]); // The one file they share is untouched: no directory identity was written. await expect(fs.access(path.join(work, ".isocan", "identity.json"))).rejects.toThrow(); @@ -186,7 +209,7 @@ describe("a session is a key, not a person", () => { expect(idOf(back.stdout)).toBe(kenny); // One actor is one session: the abandoned key no longer speaks as Kenny. - expect(Object.keys((await registry()).claims)).toEqual(["claude-code:s-9"]); + expect(sessionKeys(await registry())).toEqual(["claude-code:s-9"]); }); it("--as is refused while the actor is visibly somebody", async () => { @@ -402,7 +425,7 @@ describe("harnesses isocan has not met", () => { "Sonia", "--session", ); - expect(Object.keys((await registry()).claims)).toEqual(["isocan:own-1"]); + expect(sessionKeys(await registry())).toEqual(["isocan:own-1"]); }); it("config.json adopts a harness isocan never shipped", async () => { @@ -413,7 +436,7 @@ describe("harnesses isocan has not met", () => { const out = await asAgent({ ANTIGRAVITY_CONVO: "j-1" }, "identity", "--name", "Cana", "--session"); expect(out.code).toBe(0); expect(out.stdout).toContain("(antigravity session)"); // and the typo alongside it was ignored - expect(Object.keys((await registry()).claims)).toEqual(["antigravity:j-1"]); + expect(sessionKeys(await registry())).toEqual(["antigravity:j-1"]); expect((await asAgent({ ANTIGRAVITY_CONVO: "j-1" }, "whoami")).stdout).toContain("Cana"); }); }); @@ -428,7 +451,7 @@ describe("one name, one agent", () => { expect(second.code).not.toBe(0); expect(second.stderr).toContain("taken here"); - expect(Object.keys((await registry()).claims)).toEqual(["claude-code:s-1"]); + expect(sessionKeys(await registry())).toEqual(["claude-code:s-1"]); // And the loser is still nobody, rather than quietly being the winner. expect((await asAgent(claude("s-2"), "whoami")).stdout).not.toContain("Kenny"); }); diff --git a/packages/cli/test/shelf.test.ts b/packages/cli/test/shelf.test.ts index be2ba7e14..4454e9c24 100644 --- a/packages/cli/test/shelf.test.ts +++ b/packages/cli/test/shelf.test.ts @@ -64,6 +64,10 @@ beforeEach(async () => { homeStore = await fs.mkdtemp(path.join(os.tmpdir(), "isocan-away-home-")); machine = await fs.mkdtemp(path.join(os.tmpdir(), "isocan-away-machine-")); work = await fs.mkdtemp(path.join(os.tmpdir(), "isocan-away-work-")); + await fs.writeFile( + path.join(machine, "identity.json"), + JSON.stringify({ id: "usr_nico", name: "Nico", createdAt: new Date().toISOString() }), + ); homeDaemon = await startDaemon({ port: 0, home: homeStore }); const address = homeDaemon.app.server.address(); homePort = typeof address === "object" && address ? address.port : 0; diff --git a/packages/cli/test/space.test.ts b/packages/cli/test/space.test.ts index 3fd1b1f55..5e2c057e9 100644 --- a/packages/cli/test/space.test.ts +++ b/packages/cli/test/space.test.ts @@ -349,8 +349,7 @@ describe("isocan space", () => { it("inbox uses the remote home's addressed comments and marks without writing on read", async () => { const canvasId = await bornCanvas(); - const snapshot = await homeDaemon.engine.getSnapshot(canvasId); - const recipient = snapshot.project.createdBy; + const recipient = JSON.parse((await cli("whoami", "--json")).stdout) as { id: string; name: string }; const author = await mintTestBadge(homeBase); await author.speakAs(jordan); const response = await fetch(`${homeBase}/api/ops`, { @@ -372,7 +371,7 @@ it("inbox uses the remote home's addressed comments and marks without writing on it("seen --mark reaches each addressed home before the CLI inbox reads it on a mixed rig", async () => { const firstId = await bornCanvas(); - const recipient = (await homeDaemon.engine.getSnapshot(firstId)).project.createdBy; + const recipient = JSON.parse((await cli("whoami", "--json")).stdout) as { id: string; name: string }; const secondDir = await fs.mkdtemp(path.join(os.tmpdir(), "isocan-inbox-second-home-")); const second = await startDaemon({ port: 0, home: secondDir, birthHome: null }); const secondBase = baseOf(second); diff --git a/packages/core/src/claims.ts b/packages/core/src/claims.ts index d71ee5984..dfdbe143d 100644 --- a/packages/core/src/claims.ts +++ b/packages/core/src/claims.ts @@ -880,6 +880,17 @@ export function personRequired(name: string): string { ); } +/** Refusal code when an agent actor attempts to create/own a canvas, space, or group. */ +export const AGENT_OWNER = "agent-owner"; + +/** Refusal message when an agent actor attempts to create/own a canvas, space, or group. */ +export function agentOwnerMessage(noun: "canvas" | "space" | "group", name: string): string { + return ( + `${name} is recorded at this home as an agent, and an agent cannot own a ${noun}. ` + + "Create it as your person (`isocan identity --home --name \"Your Name\"` in your terminal, or in the web app)." + ); +} + /** The actors folded into others, old id → new id — the wire shape. */ export function actorJoins(registry: ActorRegistry): ActorJoins { return { ...(registry.joined ?? {}) }; diff --git a/packages/core/src/errors.ts b/packages/core/src/errors.ts index ee2f7610d..20b9478fc 100644 --- a/packages/core/src/errors.ts +++ b/packages/core/src/errors.ts @@ -76,6 +76,7 @@ type OpErrorCode = * `note`: a critic's notes, replies and reactions) and this op is above * it. Nothing was written; the remedy is the person who enrolled it. */ | "beyond-ceiling" + | "agent-owner" | "bad-op"; /** diff --git a/packages/house-agent/test/house-agent.test.ts b/packages/house-agent/test/house-agent.test.ts index 3c3892c0d..e94e5c5a5 100644 --- a/packages/house-agent/test/house-agent.test.ts +++ b/packages/house-agent/test/house-agent.test.ts @@ -57,7 +57,7 @@ async function setupDaemonCanvas() { const client = new DaemonClient(base, home); const humanClaim = await client.claimActor({ type: "actor.claim", - sessionKey: `test:human:${Date.now()}`, + sessionKey: `home:human:${Date.now()}`, name: "Alex", }); const houseClaim = await client.claimActor({ diff --git a/packages/mcp/test/context-summary.test.ts b/packages/mcp/test/context-summary.test.ts index 68c3b422e..ab426224f 100644 --- a/packages/mcp/test/context-summary.test.ts +++ b/packages/mcp/test/context-summary.test.ts @@ -33,8 +33,8 @@ it("reads live local/inherited layers without leaking private memory or unadmitt const base = `http://127.0.0.1:${typeof address === "object" && address ? address.port : 0}`; const routes = new DaemonClient(base, home); const otherRoutes = new DaemonClient(base, otherHome); - const owner = (await routes.claimActor({ type: "actor.claim", sessionKey: "test:owner", name: "Acme Owner" })).envelope.actor; - const stranger = (await otherRoutes.claimActor({ type: "actor.claim", sessionKey: "test:private", name: "Acme Other" })).envelope.actor; + const owner = (await routes.claimActor({ type: "actor.claim", sessionKey: "home:owner", name: "Acme Owner" })).envelope.actor; + const stranger = (await otherRoutes.claimActor({ type: "actor.claim", sessionKey: "home:private", name: "Acme Other" })).envelope.actor; const make = async (client: DaemonClient, actor: Actor, title: string) => { const id = newCanvasId(); await client.sendOp(null, actor, { type: "project.create", canvasId: id, title, groupMode: "groups" }); diff --git a/packages/mcp/test/known-address.test.ts b/packages/mcp/test/known-address.test.ts index c2709e285..f05c3f65d 100644 --- a/packages/mcp/test/known-address.test.ts +++ b/packages/mcp/test/known-address.test.ts @@ -41,7 +41,7 @@ it("admits known addresses through API, MCP and CLI without discovering other li const base = `http://127.0.0.1:${port}`; const ownerRoutes = new DaemonClient(base, home); const visitorRoutes = new DaemonClient(base, visitorHome); - const owner = (await ownerRoutes.claimActor({ type: "actor.claim", sessionKey: "test:owner", name: "Acme Owner" })).envelope.actor; + const owner = (await ownerRoutes.claimActor({ type: "actor.claim", sessionKey: "home:owner", name: "Acme Owner" })).envelope.actor; const visitor = (await visitorRoutes.claimActor({ type: "actor.claim", sessionKey: "test:visitor", name: "Acme Visitor" })).envelope.actor; const make = async (title: string) => { const id = newCanvasId(); diff --git a/packages/mcp/test/module-tools.test.ts b/packages/mcp/test/module-tools.test.ts index d0ef34863..987bcda50 100644 --- a/packages/mcp/test/module-tools.test.ts +++ b/packages/mcp/test/module-tools.test.ts @@ -67,9 +67,12 @@ beforeEach(async () => { cwdBefore = process.cwd(); process.chdir(work); const client = new DaemonClient(base, home); + const owner = (await client.claimActor({ type: "actor.claim", sessionKey: "home:owner", name: "Acme Person" })).envelope.actor; await client.claimActor({ type: "actor.claim", sessionKey: "mcp:ambient", name: "Acme Owner" }); await client.claimActor({ type: "actor.claim", sessionKey: "mcp:conversation-a", name: "Cedar" }); ambient = await connect({ port, identity: { session: "ambient", harness: "mcp" } }); + const canvasId = newCanvasId(); + await ambient.ctx.client.sendOp(null, owner, { type: "project.create", canvasId, title: "Acme board" }); }); afterEach(async () => { @@ -102,8 +105,7 @@ function payload(result: unknown): Record { } async function aCanvas(): Promise { - const canvasId = newCanvasId(); - await ambient.ctx.client.sendOp(null, ambient.actor, { type: "project.create", canvasId, title: "Acme board" }); +const canvasId = ambient.ctx.binding?.canvasId ?? (await ambient.canvas()).id; return canvasId; } diff --git a/packages/mcp/test/stdio-feedback-setup.test.ts b/packages/mcp/test/stdio-feedback-setup.test.ts index 9d39edbea..25a2fb8d5 100644 --- a/packages/mcp/test/stdio-feedback-setup.test.ts +++ b/packages/mcp/test/stdio-feedback-setup.test.ts @@ -51,9 +51,10 @@ it("releases stalled identity and known-ID admission HTTP on stdio timeout and c const proxyAddress = proxy.address(); const origin = `http://127.0.0.1:${typeof proxyAddress === "object" && proxyAddress ? proxyAddress.port : 0}`; const routes = new DaemonClient(origin, home); - const actor = (await routes.claimActor({ type: "actor.claim", sessionKey: "mcp:setup", name: "Acme Setup" })).envelope.actor; + await routes.claimActor({ type: "actor.claim", sessionKey: "mcp:setup", name: "Acme Setup" }); + const owner = (await routes.claimActor({ type: "actor.claim", sessionKey: "home:owner", name: "Acme Owner" })).envelope.actor; const canvas = newCanvasId(); - await routes.sendOp(null, actor, { type: "project.create", canvasId: canvas, title: "Acme setup", groupMode: "groups" }); + await routes.sendOp(null, owner, { type: "project.create", canvasId: canvas, title: "Acme setup", groupMode: "groups" }); const env: Record = Object.fromEntries(Object.entries(process.env).filter((entry): entry is [string, string] => entry[1] !== undefined)); for (const key of harnessVars) delete env[key]; Object.assign(env, { ISOCAN_HOME: home, ISOCAN_DIRECT: origin }); diff --git a/packages/mcp/test/stdio-module-tools.test.ts b/packages/mcp/test/stdio-module-tools.test.ts index 34910e72e..622e5d476 100644 --- a/packages/mcp/test/stdio-module-tools.test.ts +++ b/packages/mcp/test/stdio-module-tools.test.ts @@ -43,9 +43,10 @@ it("offers a loaded module's verb as _ over stdio and lands the ve const address = daemon.app.server.address(); const port = typeof address === "object" && address ? address.port : 0; const routes = new DaemonClient(`http://127.0.0.1:${port}`, home); - const ambient = (await routes.claimActor({ type: "actor.claim", sessionKey: "test:ambient", name: "Acme Owner" })).envelope.actor; + const ambient = (await routes.claimActor({ type: "actor.claim", sessionKey: "test:ambient", name: "Acme Agent" })).envelope.actor; + const owner = (await routes.claimActor({ type: "actor.claim", sessionKey: "home:owner", name: "Acme Owner" })).envelope.actor; const canvas = newCanvasId(); - await routes.sendOp(null, ambient, { type: "project.create", canvasId: canvas, title: "Acme stickers", groupMode: "groups" }); + await routes.sendOp(null, owner, { type: "project.create", canvasId: canvas, title: "Acme stickers", groupMode: "groups" }); const env: Record = Object.fromEntries(Object.entries(process.env).filter((entry): entry is [string, string] => entry[1] !== undefined)); for (const key of harnessVars) delete env[key]; delete env.ISOCAN_DIRECT; diff --git a/packages/mcp/test/stdio-sessions.test.ts b/packages/mcp/test/stdio-sessions.test.ts index 306372c7c..2de223617 100644 --- a/packages/mcp/test/stdio-sessions.test.ts +++ b/packages/mcp/test/stdio-sessions.test.ts @@ -34,9 +34,10 @@ it("keeps two stdio sessions attributed, addressed, cancellable and durable acro const address = daemon.app.server.address(); const port = typeof address === "object" && address ? address.port : 0; const routes = new DaemonClient(`http://127.0.0.1:${port}`, home); - const ambient = (await routes.claimActor({ type: "actor.claim", sessionKey: "test:ambient", name: "Acme Owner" })).envelope.actor; + const ambient = (await routes.claimActor({ type: "actor.claim", sessionKey: "test:ambient", name: "Acme Agent" })).envelope.actor; + const owner = (await routes.claimActor({ type: "actor.claim", sessionKey: "home:owner", name: "Acme Owner" })).envelope.actor; const canvas = newCanvasId(); - await routes.sendOp(null, ambient, { type: "project.create", canvasId: canvas, title: "Acme collaboration", groupMode: "groups" }); + await routes.sendOp(null, owner, { type: "project.create", canvasId: canvas, title: "Acme collaboration", groupMode: "groups" }); const handle = new CanvasHandle({ client: routes, actor: ambient, home, homeOf: async () => null } as unknown as Ctx, (await routes.snapshot(canvas)).project); const env: Record = Object.fromEntries(Object.entries(process.env).filter((entry): entry is [string, string] => entry[1] !== undefined)); for (const key of harnessVars) delete env[key]; diff --git a/packages/mcp/test/tools.test.ts b/packages/mcp/test/tools.test.ts index 0b20a8f1b..7d5e5caa8 100644 --- a/packages/mcp/test/tools.test.ts +++ b/packages/mcp/test/tools.test.ts @@ -71,8 +71,8 @@ beforeEach(async () => { process.chdir(work); const client = new DaemonClient(base, home); - await client.claimActor({ type: "actor.claim", sessionKey: "mcp:t-1", name: "Ada" }); - connected = await connect({ port, identity: { session: "t-1", harness: "mcp" } }); + await client.claimActor({ type: "actor.claim", sessionKey: "home:t-1", name: "Ada" }); + connected = await connect({ port, identity: { session: "t-1", harness: "home" } }); }); afterEach(async () => { diff --git a/packages/modules/audio/test/audio.test.ts b/packages/modules/audio/test/audio.test.ts index 2c845f073..c4841b94a 100644 --- a/packages/modules/audio/test/audio.test.ts +++ b/packages/modules/audio/test/audio.test.ts @@ -90,7 +90,7 @@ function authHeaders(badge: StoredBadge, json = false): Record { }; } -async function mintEditor(base: string, sessionKey = "test:acme-audio"): Promise<{ badge: StoredBadge; actor: Actor }> { +async function mintEditor(base: string, sessionKey = "home:acme-audio"): Promise<{ badge: StoredBadge; actor: Actor }> { const knocked = await askTheDoor(base); if (!("badge" in knocked)) throw new Error(`door refused: ${knocked.refused.error}`); const { badge } = knocked; @@ -382,7 +382,7 @@ describe("@isocan/audio server routes", () => { }, }); const base = daemonBase(daemon); - const editor = await mintEditor(base, "test:acme-audio-scrub"); + const editor = await mintEditor(base, "home:acme-audio-scrub"); const canvasId = await createCanvas(base, editor.badge, editor.actor); const err1 = await fetch(`${base}${AUDIO_MUSIC_ROUTE}`, { diff --git a/packages/modules/clipper/test/clipper.test.ts b/packages/modules/clipper/test/clipper.test.ts index d6f224dc8..4ac2c4300 100644 --- a/packages/modules/clipper/test/clipper.test.ts +++ b/packages/modules/clipper/test/clipper.test.ts @@ -86,7 +86,7 @@ async function mintEditor(base: string): Promise<{ badge: StoredBadge; actor: Ac body: JSON.stringify({ canvasId: null, actor: { id: "", name: "Acme Clipper" }, - op: { type: "actor.claim", sessionKey: "test:acme-clip", name: "Acme Clipper" }, + op: { type: "actor.claim", sessionKey: "home:acme-clip", name: "Acme Clipper" }, }), }); expect(claimRes.status).toBe(200); diff --git a/packages/modules/describe/test/describe.test.ts b/packages/modules/describe/test/describe.test.ts index 9c81dfd04..207d50341 100644 --- a/packages/modules/describe/test/describe.test.ts +++ b/packages/modules/describe/test/describe.test.ts @@ -85,7 +85,7 @@ function authHeaders(badge: StoredBadge, json = false): Record { }; } -async function mintEditor(base: string, sessionKey = "test:acme-describe"): Promise<{ badge: StoredBadge; actor: Actor }> { +async function mintEditor(base: string, sessionKey = "home:acme-describe"): Promise<{ badge: StoredBadge; actor: Actor }> { const knocked = await askTheDoor(base); if (!("badge" in knocked)) throw new Error(`door refused: ${knocked.refused.error}`); const { badge } = knocked; @@ -361,7 +361,7 @@ describe("@isocan/describe server route", () => { }, }); const base = daemonBase(daemon); - const editor = await mintEditor(base, "test:acme-describe-errors"); + const editor = await mintEditor(base, "home:acme-describe-errors"); const canvasId = await createCanvas(base, editor.badge, editor.actor); const docId = await addItem(base, editor.badge, editor.actor, canvasId, { bytes: new TextEncoder().encode("# Acme Notes\nShort test note."), diff --git a/packages/modules/design-system/test/design-system.test.ts b/packages/modules/design-system/test/design-system.test.ts index fb8e973e7..741a2e793 100644 --- a/packages/modules/design-system/test/design-system.test.ts +++ b/packages/modules/design-system/test/design-system.test.ts @@ -85,7 +85,7 @@ function authHeaders(badge: StoredBadge): Record { }; } -async function mintEditor(base: string, sessionKey = "test:acme-ds"): Promise<{ badge: StoredBadge; actor: Actor }> { +async function mintEditor(base: string, sessionKey = "home:acme-ds"): Promise<{ badge: StoredBadge; actor: Actor }> { const knocked = await askTheDoor(base); if (!("badge" in knocked)) throw new Error(`door refused: ${knocked.refused.error}`); const claimRes = await fetch(`${base}/api/ops`, { diff --git a/packages/modules/image/test/image.test.ts b/packages/modules/image/test/image.test.ts index b92251f34..97858ecf0 100644 --- a/packages/modules/image/test/image.test.ts +++ b/packages/modules/image/test/image.test.ts @@ -84,7 +84,7 @@ function authHeaders(badge: StoredBadge, json = false): Record { }; } -async function mintEditor(base: string, sessionKey = "test:acme-image"): Promise<{ badge: StoredBadge; actor: Actor }> { +async function mintEditor(base: string, sessionKey = "home:acme-image"): Promise<{ badge: StoredBadge; actor: Actor }> { const knocked = await askTheDoor(base); if (!("badge" in knocked)) throw new Error(`door refused: ${knocked.refused.error}`); const { badge } = knocked; @@ -294,7 +294,7 @@ describe("@isocan/image server route", () => { modules: { image: { key: () => SECRET_KEY, fetch: fakeFetch } }, }); const base = daemonBase(daemon); - const editor = await mintEditor(base, "test:acme-image-fail"); + const editor = await mintEditor(base, "home:acme-image-fail"); const canvasId = await createCanvas(base, editor.badge, editor.actor); const res = await fetch(`${base}${IMAGE_GENERATE_ROUTE}`, { diff --git a/packages/modules/media-edit/test/media-edit.test.ts b/packages/modules/media-edit/test/media-edit.test.ts index 0d82a5322..250a4b3c9 100644 --- a/packages/modules/media-edit/test/media-edit.test.ts +++ b/packages/modules/media-edit/test/media-edit.test.ts @@ -85,7 +85,7 @@ function authHeaders(badge: StoredBadge, json = false): Record { }; } -async function mintEditor(base: string, sessionKey = "test:acme-media-edit"): Promise<{ badge: StoredBadge; actor: Actor }> { +async function mintEditor(base: string, sessionKey = "home:acme-media-edit"): Promise<{ badge: StoredBadge; actor: Actor }> { const knocked = await askTheDoor(base); if (!("badge" in knocked)) throw new Error(`door refused: ${knocked.refused.error}`); const { badge } = knocked; diff --git a/packages/modules/memory/test/memory.test.ts b/packages/modules/memory/test/memory.test.ts index 1e119c4b1..6c9a8fdc7 100644 --- a/packages/modules/memory/test/memory.test.ts +++ b/packages/modules/memory/test/memory.test.ts @@ -183,8 +183,8 @@ describe("@isocan/memory against real daemon", () => { const daemon = await boot(home); const base = daemonBase(daemon); - const alice = await mintEditor(base, "test:acme-alice", "Alice"); - const bob = await mintEditor(base, "test:acme-bob", "Bob"); + const alice = await mintEditor(base, "home:acme-alice", "Alice"); + const bob = await mintEditor(base, "home:acme-bob", "Bob"); const sharedCanvasId = await createCanvas(base, alice.badge, alice.actor, "Acme Launch"); const aboutAliceId = await createCanvas(base, alice.badge, alice.actor, "About you (Alice)"); @@ -406,8 +406,8 @@ describe("@isocan/memory against real daemon", () => { const daemon = await boot(home); const base = daemonBase(daemon); - const alice = await mintEditor(base, "test:acme-forget-alice", "Alice"); - const bob = await mintEditor(base, "test:acme-forget-bob", "Bob"); + const alice = await mintEditor(base, "home:acme-forget-alice", "Alice"); + const bob = await mintEditor(base, "home:acme-forget-bob", "Bob"); const sharedCanvasId = await createCanvas(base, alice.badge, alice.actor, "Acme Forget Shared"); const aboutAliceId = await createCanvas(base, alice.badge, alice.actor, "About you (Alice)"); diff --git a/packages/modules/model3d/test/model3d.test.ts b/packages/modules/model3d/test/model3d.test.ts index d8606f384..99a702fda 100644 --- a/packages/modules/model3d/test/model3d.test.ts +++ b/packages/modules/model3d/test/model3d.test.ts @@ -240,7 +240,7 @@ describe("@isocan/model3d CLI", () => { body: JSON.stringify({ canvasId: null, actor: { id: "", name: "Acme 3D Editor" }, - op: { type: "actor.claim", sessionKey: "test:acme-3d", name: "Acme 3D Editor" }, + op: { type: "actor.claim", sessionKey: "home:acme-3d", name: "Acme 3D Editor" }, }), }); const actor = ((await claimRes.json()) as { envelope: { actor: Actor } }).envelope.actor; diff --git a/packages/modules/prototype/test/prototype.test.ts b/packages/modules/prototype/test/prototype.test.ts index 4c860a86b..f9aeacb15 100644 --- a/packages/modules/prototype/test/prototype.test.ts +++ b/packages/modules/prototype/test/prototype.test.ts @@ -88,7 +88,7 @@ async function mintEditor(base: string): Promise<{ badge: StoredBadge; actor: Ac body: JSON.stringify({ canvasId: null, actor: { id: "", name: "Acme Builder" }, - op: { type: "actor.claim", sessionKey: "test:acme-proto", name: "Acme Builder" }, + op: { type: "actor.claim", sessionKey: "home:acme-proto", name: "Acme Builder" }, }), }); expect(claimRes.status).toBe(200); diff --git a/packages/modules/research/test/research.test.ts b/packages/modules/research/test/research.test.ts index 3a7a349ad..f534a0669 100644 --- a/packages/modules/research/test/research.test.ts +++ b/packages/modules/research/test/research.test.ts @@ -127,7 +127,7 @@ function authHeaders(badge: StoredBadge, json = false): Record { }; } -async function mintEditor(base: string, sessionKey = "test:acme-research"): Promise<{ badge: StoredBadge; actor: Actor }> { +async function mintEditor(base: string, sessionKey = "home:acme-research"): Promise<{ badge: StoredBadge; actor: Actor }> { const knocked = await askTheDoor(base); if (!("badge" in knocked)) throw new Error(`door refused: ${knocked.refused.error}`); const { badge } = knocked; @@ -307,7 +307,7 @@ describe("@isocan/research server route + home-polled job runner", () => { modules: { research: { key: () => SECRET_KEY, fetch: fakeFetch } }, }); const base = daemonBase(daemon); - const editor = await mintEditor(base, "test:acme-research-fail"); + const editor = await mintEditor(base, "home:acme-research-fail"); const canvasId = await createCanvas(base, editor.badge, editor.actor); const startRes = await fetch(`${base}${RESEARCH_RUN_ROUTE}`, { diff --git a/packages/modules/video/test/video.test.ts b/packages/modules/video/test/video.test.ts index bbf7551de..18c6dc90b 100644 --- a/packages/modules/video/test/video.test.ts +++ b/packages/modules/video/test/video.test.ts @@ -136,7 +136,7 @@ function authHeaders(badge: StoredBadge, json = false): Record { }; } -async function mintEditor(base: string, sessionKey = "test:acme-video"): Promise<{ badge: StoredBadge; actor: Actor }> { +async function mintEditor(base: string, sessionKey = "home:acme-video"): Promise<{ badge: StoredBadge; actor: Actor }> { const knocked = await askTheDoor(base); if (!("badge" in knocked)) throw new Error(`door refused: ${knocked.refused.error}`); const { badge } = knocked; @@ -475,7 +475,7 @@ describe("@isocan/video server route + home-polled async job runner", () => { modules: { video: { key: () => SECRET_KEY, fetch: fakeFetch } }, }); const base = daemonBase(daemon); - const editor = await mintEditor(base, "test:acme-video-fail"); + const editor = await mintEditor(base, "home:acme-video-fail"); const canvasId = await createCanvas(base, editor.badge, editor.actor); const startRes = await fetch(`${base}${VIDEO_GENERATE_ROUTE}`, { diff --git a/packages/modules/workbench/test/workbench.test.ts b/packages/modules/workbench/test/workbench.test.ts index 7cf50ae40..663b52724 100644 --- a/packages/modules/workbench/test/workbench.test.ts +++ b/packages/modules/workbench/test/workbench.test.ts @@ -190,7 +190,7 @@ async function setupDaemonWithDrivers() { body: JSON.stringify({ canvasId: null, actor: { id: "", name: "Acme Tester" }, - op: { type: "actor.claim", sessionKey: "test:acme-workbench", name: "Acme Tester" }, + op: { type: "actor.claim", sessionKey: "home:acme-workbench", name: "Acme Tester" }, }), }); const claimed = (await claimRes.json()) as { envelope: { actor: Actor } }; diff --git a/packages/modules/workspace/test/workspace.test.ts b/packages/modules/workspace/test/workspace.test.ts index c3e6febf6..327930d62 100644 --- a/packages/modules/workspace/test/workspace.test.ts +++ b/packages/modules/workspace/test/workspace.test.ts @@ -88,7 +88,7 @@ async function mintEditor(base: string): Promise<{ badge: StoredBadge; actor: Ac body: JSON.stringify({ canvasId: null, actor: { id: "", name: "Acme Writer" }, - op: { type: "actor.claim", sessionKey: "test:acme-ws", name: "Acme Writer" }, + op: { type: "actor.claim", sessionKey: "home:acme-ws", name: "Acme Writer" }, }), }); expect(claimRes.status).toBe(200); diff --git a/packages/server/src/engine.ts b/packages/server/src/engine.ts index 0c30a844b..f21aa9518 100644 --- a/packages/server/src/engine.ts +++ b/packages/server/src/engine.ts @@ -64,6 +64,8 @@ import { mergeJoins, actorMarks, actorKinds, + AGENT_OWNER, + agentOwnerMessage, personIntoAgent, actorNames, allocateName, @@ -1308,6 +1310,16 @@ export class Engine { isSystemActor(request.actor.id) && (request.op.type === "thread.create" || request.op.type === "thread.reply"); if (!systemComment) await this.requireActor(request.badgeId, request.actor.id); + if (request.op.type === "project.create") { + const { registry } = await this.actors(true); + const ownerId = resolveActor(registry.joined, request.actor.id); + if (actorKinds(registry)[ownerId] === "agent") { + throw new OpValidationError( + AGENT_OWNER, + agentOwnerMessage("canvas", actorNames(registry)[ownerId] ?? request.actor.name), + ); + } + } /** * **Which home this op goes to, resolved once** (phase 10.3). * @@ -3175,6 +3187,14 @@ export class Engine { op: Operation & { type: "project.create" }, personalBirth?: PersonalSourceRecord, ): Promise { + const { registry } = await this.actors(true); + const ownerId = resolveActor(registry.joined, request.actor.id); + if (actorKinds(registry)[ownerId] === "agent") { + throw new OpValidationError( + AGENT_OWNER, + agentOwnerMessage("canvas", actorNames(registry)[ownerId] ?? request.actor.name), + ); + } const reserved = await this.desk.personalSource(op.canvasId); if (reserved || await this.desk.personalReplica(op.canvasId)) { const joins = await this.actorJoins(); diff --git a/packages/server/src/grants.ts b/packages/server/src/grants.ts index 80b77e587..74f9a9740 100644 --- a/packages/server/src/grants.ts +++ b/packages/server/src/grants.ts @@ -30,9 +30,11 @@ import { narrowed, newId, NOT_ADMITTED, - ownerOf, + ownsAgent, resolveActor, + type ActorClaim, type ActorJoins, + type ActorKinds, RUNGS, VIEW_ONLY, WITHDRAWN, @@ -223,6 +225,36 @@ function groupMemo(via: Pick): (groupId: string) => Promise }; } +/** Optional registry state passed to the door and sweep so legacy agent-owned canvases resolve to their person owner. */ +export interface CreatorOwnership { + joined?: ActorJoins | undefined; + kinds?: ActorKinds | undefined; +} + +async function claimsCanvasCreator( + desk: Desk, + creator: string, + claims: readonly ActorClaim[], + asActor: string | null, + ownership?: CreatorOwnership, +): Promise { + const joined = ownership?.joined; + const owner = resolveActor(joined, creator); + const asPerson = asActor === null ? null : resolveActor(joined, asActor); + if ((asPerson === null || asPerson === owner) && claimsActor(claims, owner, joined)) { + return true; + } + if (ownership?.kinds?.[owner] !== "agent") return false; + const ids = owner === creator ? [creator] : [creator, owner]; + const holderSets = await Promise.all(ids.map((id) => desk.claimants(id))); + const badgeIds = [...new Set(holderSets.flat().map((held) => held.badgeId))]; + const holders = await Promise.all(badgeIds.map((badgeId) => desk.claimsOf(badgeId))); + if (asPerson !== null) { + return claimsActor(claims, asPerson, joined) && ownsAgent(holders, asPerson, true, joined); + } + return claims.some((claim) => ownsAgent(holders, claim.actorId, true, joined)); +} + export async function admittingGrant( desk: Desk, canvasId: string, @@ -232,6 +264,7 @@ export async function admittingGrant( /** Discovery has no presented address, so a link cannot answer it. Bars, * named grants and creator floors are still judged by the same door. */ scope: "entry" | "discovery" = "entry", + ownership?: CreatorOwnership, ): Promise { /** * **Both scopes** (roles design, "Who holds what"): the canvas's rows and @@ -267,6 +300,7 @@ export async function admittingGrant( break; } } + let matched: Grant | null = null; if (!barred) { const rung = (grant: Grant) => RUNGS.indexOf(capabilityOf(grant)); const rows = live @@ -274,7 +308,11 @@ export async function admittingGrant( .sort((a, b) => rung(b) - rung(a) || a.at.localeCompare(b.at)); for (const grant of rows) { if (await subjectAdmits(grant.subject, attestations, groupOf)) { - return { grant, provenance: { root: "grant", grantId: grant.id }, capability: capabilityOf(grant) }; + if (atLeast(capabilityOf(grant), "edit")) { + return { grant, provenance: { root: "grant", grantId: grant.id }, capability: capabilityOf(grant) }; + } + matched = grant; + break; } // Anything else falls through, and falling through is the correct answer // rather than a gap: a subject nobody has proved is a row that admits @@ -283,21 +321,23 @@ export async function admittingGrant( // door offers the attesters". } } - // The floor, asked only when a bar matched or no row did: one `claimsOf` - // read, off the common path where a row answers. A creator-claiming badge - // is admitted here whatever the bars say — the creator cannot be barred. - // The space's creator holds the same floor over every canvas in it (roles - // phase 4), under a root of its own that every sweep re-asks, because a - // canvas can leave a space and `created` is never re-asked. + // The floor, asked when a bar matched, no row matched, or the best row was + // below `edit` (so a creator or space creator is never swept down to `read` + // or `view` on a second browser): one `claimsOf` read, off the common `edit` + // path where a row answers. A creator-claiming badge is admitted here + // whatever the bars say — the creator cannot be barred. if (creator !== null || space !== null) { const claims = await desk.claimsOf(badge.badgeId); - if (creator !== null && claimsActor(claims, creator)) { + if (creator !== null && (await claimsCanvasCreator(desk, creator, claims, null, ownership))) { return { grant: null, provenance: { root: "created" }, capability: "own" }; } - if (space !== null && claimsActor(claims, space.createdBy)) { + if (space !== null && claimsActor(claims, space.createdBy, ownership?.joined)) { return { grant: null, provenance: { root: "space", spaceId: space.id }, capability: "own" }; } } + if (matched) { + return { grant: matched, provenance: { root: "grant", grantId: matched.id }, capability: capabilityOf(matched) }; + } return null; } @@ -437,13 +477,14 @@ export async function heldRung( * has never seen a join has an empty map and an unchanged answer. */ joined?: ActorJoins, + kinds?: ActorKinds, ): Promise { const held = capabilityIn(badge, project.id) ?? "edit"; if (atLeast(held, "own")) return held; - const owner = ownerOf(project, joined); const claims = await desk.claimsOf(badge.badgeId); - const asPerson = asActor === null ? null : resolveActor(joined, asActor); - if ((asPerson === null || asPerson === owner) && claimsActor(claims, owner)) return "own"; + if (await claimsCanvasCreator(desk, project.createdBy.id, claims, asActor, { joined, kinds })) { + return "own"; + } /** * **The space's creator owns every canvas in it** (roles phase 4): the * same floor, one scope wider. Asked last and only here, so a canvas in no @@ -573,12 +614,13 @@ export async function heldCapability( canvasId: string, badge: BadgeRecord, creator: string | null = null, + ownership?: CreatorOwnership, ): Promise { const held = capabilityIn(badge, canvasId); if (held === null || atLeast(held, "edit")) return held; // A look is a ceiling until expiry, even when a pass later adds a claim. if (admissionIn(badge, canvasId)?.provenance.root === "operator") return held; - const answer = await admittingGrant(desk, canvasId, badge, creator); + const answer = await admittingGrant(desk, canvasId, badge, creator, desk, "entry", ownership); if (!answer || answer.capability === held) return held; await desk.reroot(badge.badgeId, canvasId, answer.provenance, answer.capability); badge.admissions = badge.admissions.map((a) => diff --git a/packages/server/src/http.ts b/packages/server/src/http.ts index 5c2db24a7..fdf44d4fd 100644 --- a/packages/server/src/http.ts +++ b/packages/server/src/http.ts @@ -165,6 +165,8 @@ import { PARK_ADOPTED_CODE, parseCommandFile, atLeast, + AGENT_OWNER, + agentOwnerMessage, isCapability, LINK, ownerOf, @@ -736,6 +738,39 @@ async function buildAttestOffer( }; } +async function ownershipOf(engine: Engine): Promise<{ joined: Record; kinds: Record }> { + const [joined, kinds] = await Promise.all([engine.actorJoins(), engine.actorKinds()]); + return { joined, kinds }; +} + +async function refuseAgentOwner( + engine: Engine, + reply: FastifyReply, + noun: "space" | "group", + actorId: string | undefined, +): Promise { + if (!actorId) return false; + const { joined, kinds } = await ownershipOf(engine); + const resolved = resolveActor(joined, actorId); + if (kinds[resolved] !== "agent") return false; + const name = actorNameIn(await engine.actorNames(), { id: resolved, name: resolved }); + reply.status(403).send({ error: agentOwnerMessage(noun, name), code: AGENT_OWNER }); + return true; +} + +async function snapshotOwnIfLegacyAgent( + desk: Desk, + engine: Engine, + project: { id: string; createdBy: { id: string } }, + badge: BadgeRecord, + held: Capability | null, +): Promise { + if (held !== null && atLeast(held, "own")) return held; + const { joined, kinds } = await ownershipOf(engine); + if (kinds[ownerOf(project, joined)] !== "agent") return held; + return atLeast(await heldRung(desk, project, badge, null, joined, kinds), "own") ? "own" : held; +} + export function registerRoutes( app: FastifyInstance, engine: Engine, @@ -1145,6 +1180,8 @@ export function registerRoutes( const ownerName = async (project: { createdBy: { id: string; name: string } }): Promise => actorNameIn(await engine.actorNames(), project.createdBy); + const creatorOwnership = () => ownershipOf(engine); + /** * The read-only refusal, naming the owner (roles journey 1 step 5: *ask * Priya, who owns it*). The snapshot is read for the name only on the @@ -1597,7 +1634,7 @@ export function registerRoutes( if (held !== null && !atLeast(held, "edit")) { const project = metadataOnly ? await store.canvasRecord(canvasId) : (await engine.getSnapshot(canvasId).catch(() => null))?.project; if (metadataOnly && !project) throw new CanvasNotFoundError(canvasId); - await heldCapability(desk, canvasId, req.badge, project?.createdBy.id ?? null); + await heldCapability(desk, canvasId, req.badge, project?.createdBy.id ?? null, await creatorOwnership()); } return; } @@ -1641,7 +1678,7 @@ export function registerRoutes( // canvas, which is what an admission costs. const project = metadataOnly ? await store.canvasRecord(canvasId) : (await engine.getSnapshot(canvasId).catch(() => null))?.project; if (!project) { if (metadataOnly) throw new CanvasNotFoundError(canvasId); return; } - const answer = await admittingGrant(desk, canvasId, req.badge, project.createdBy.id); + const answer = await admittingGrant(desk, canvasId, req.badge, project.createdBy.id, desk, "entry", await creatorOwnership()); if (!answer) throw new NotAdmittedError(canvasId); provenance = answer.provenance; capability = answer.capability; @@ -2002,7 +2039,7 @@ export function registerRoutes( } const joins = await engine.actorJoins(); if (!mayRemoveComment(comment, body.actor.id, false, joins) && - !atLeast(await heldRung(desk, snapshot.project, req.badge!, body.actor.id, joins), "own")) { + !atLeast(await heldRung(desk, snapshot.project, req.badge!, body.actor.id, joins, await engine.actorKinds()), "own")) { return reply.status(403).send({ error: `ask ${await ownerName(snapshot.project)}, who owns this canvas — only an owner can remove a message somebody else wrote`, code: NOT_OWNER, @@ -2350,6 +2387,8 @@ export function registerRoutes( return found; }, }; + let cachedOwnership: Promise<{ joined: Record; kinds: Record }> | null = null; + const getOwnership = () => (cachedOwnership ??= creatorOwnership()); return async (canvas: Canvas): Promise => { const context = sourceContexts.get(req); if (context) { @@ -2358,7 +2397,7 @@ export function registerRoutes( } if (admitted.has(canvas.id) || (!admittedOnly && shelf && local)) return true; if (admittedOnly) return false; - return (await admittingGrant(desk, canvas.id, badge, canvas.createdBy.id, via, local ? "entry" : "discovery")) !== null; + return (await admittingGrant(desk, canvas.id, badge, canvas.createdBy.id, via, local ? "entry" : "discovery", await getOwnership())) !== null; }; }; @@ -2585,7 +2624,7 @@ export function registerRoutes( const home = homes?.for(id) ?? null; if (home) return home.setPublicListing(id, grantId, body.listed, await actorNamed(actorId)); const snapshot = await engine.getSnapshot(id); - if (!atLeast(await heldRung(desk, snapshot.project, req.badge!, actorId ?? null, await engine.actorJoins()), "own")) { + if (!atLeast(await heldRung(desk, snapshot.project, req.badge!, actorId ?? null, await engine.actorJoins(), await engine.actorKinds()), "own")) { return reply.status(403).send({ error: notOwnerMessage(await ownerName(snapshot.project)), code: NOT_OWNER }); } await sourceMutation(req, id); @@ -2668,7 +2707,7 @@ export function registerRoutes( * Checked here rather than in the client, and after the replica forward * above, so the home that owns the canvas is the one that answers. */ - if (!atLeast(await heldRung(desk, snapshot.project, req.badge!, actorId ?? null, await engine.actorJoins()), "own")) { + if (!atLeast(await heldRung(desk, snapshot.project, req.badge!, actorId ?? null, await engine.actorJoins(), await engine.actorKinds()), "own")) { return reply .status(403) .send({ error: notOwnerMessage(await ownerName(snapshot.project)), code: NOT_OWNER }); @@ -2733,7 +2772,7 @@ export function registerRoutes( } await desk.putGrant(grant); if (live || bars) { - const swept = await sweepCanvas(desk, id, snapshot.project.createdBy.id, sweeps.report); + const swept = await sweepCanvas(desk, id, snapshot.project.createdBy.id, sweeps.report, await creatorOwnership()); return { grant, swept } satisfies GrantResponse; } return { grant } satisfies GrantResponse; @@ -2797,6 +2836,8 @@ export function registerRoutes( project: { createdBy: { id: string } }, ): Promise => { if (subject === LINK) return false; + const { joined, kinds } = await creatorOwnership(); + if (kinds[ownerOf(project, joined)] === "agent") return false; for (const { badgeId } of await desk.claimants(ownerOf(project))) { const holder = await desk.badge(badgeId); if (holder && attestationSatisfying(subject, holder.attestations ?? [])) return true; @@ -3031,7 +3072,7 @@ export function registerRoutes( } // Revoking is a write to grants, and every write to grants is an owner's // (roles phase 2) — the link's off switch included. - if (!atLeast(await heldRung(desk, snapshot.project, req.badge!, actorId ?? null, await engine.actorJoins()), "own")) { + if (!atLeast(await heldRung(desk, snapshot.project, req.badge!, actorId ?? null, await engine.actorJoins(), await engine.actorKinds()), "own")) { return reply .status(403) .send({ error: notOwnerMessage(await ownerName(snapshot.project)), code: NOT_OWNER }); @@ -3064,7 +3105,7 @@ export function registerRoutes( if (written) await desk.putGrant(written); // The creator rides along for the floor: turning the link off must not // expel the creator's own browser (roles journey 1, step 2). - const swept = await sweepCanvas(desk, id, snapshot.project.createdBy.id, sweeps.report); + const swept = await sweepCanvas(desk, id, snapshot.project.createdBy.id, sweeps.report, await creatorOwnership()); /** * **What would still admit them**, read off the live rows AFTER the * revoke, so the dialog and the CLI can say *they can still enter by the @@ -3309,6 +3350,7 @@ export function registerRoutes( const stuck = refuseAmbiguousHome(reply, homes, "make a space"); if (stuck) return stuck; const actorId = await actingActor(req, body.actorId); + if (await refuseAgentOwner(engine, reply, "space", actorId)) return; const home = homes?.homeScoped() ?? null; if (home) return home.createSpace(name, await actorNamed(actorId)); if (!actorId) { @@ -3399,7 +3441,7 @@ export function registerRoutes( } const snapshot = await engine.getSnapshot(canvasId); // 404 for a canvas that is not here await admit(req, canvasId); // the door, since the hook did not ask - if (!atLeast(await heldRung(desk, snapshot.project, req.badge!, actorId ?? null, await engine.actorJoins()), "own")) { + if (!atLeast(await heldRung(desk, snapshot.project, req.badge!, actorId ?? null, await engine.actorJoins(), await engine.actorKinds()), "own")) { return reply .status(403) .send({ error: notOwnerMessage(await ownerName(snapshot.project)), code: NOT_OWNER }); @@ -3420,7 +3462,7 @@ export function registerRoutes( const next: Space = { ...owned.space, canvasIds: [...owned.space.canvasIds, canvasId] }; await sourceMutation(req, canvasId); await desk.putSpace(next); - const swept = await sweepCanvas(desk, canvasId, snapshot.project.createdBy.id, sweeps.report); + const swept = await sweepCanvas(desk, canvasId, snapshot.project.createdBy.id, sweeps.report, await creatorOwnership()); return { space: next, swept, reached: 1 } satisfies SpaceCanvasResponse; }); @@ -3670,6 +3712,7 @@ export function registerRoutes( const stuck = refuseAmbiguousHome(reply, homes, "make a group"); if (stuck) return stuck; const actorId = await actingActor(req, body.actorId); + if (await refuseAgentOwner(engine, reply, "group", actorId)) return; const home = homes?.homeScoped() ?? null; if (home) return home.createGroup(name, await actorNamed(actorId)); if (!actorId) { @@ -4083,7 +4126,7 @@ export function registerRoutes( // whose admission is not edit learns its rung here, with the canvas, // instead of discovering it as a refusal per gesture. Absent means edit, // so a pre-capability client parsing this response sees nothing new. - const held = sourceCaps.get(req) ?? (req.badge ? capabilityIn(req.badge, id) : null); + const held = sourceCaps.get(req) ?? (req.badge ? await snapshotOwnIfLegacyAgent(desk, engine, snapshot.project, req.badge, capabilityIn(req.badge, id)) : null); if (held !== null && narrowed(held)) { return { ...snapshot, capability: held }; } @@ -4194,7 +4237,7 @@ export function registerRoutes( // Naming an address is entry; an unscoped watch is discovery. Cursors // are positions, not a request to widen discovery to every link. const allowed = only?.has(canvas.id) - ? admitted.has(canvas.id) || Boolean(await admittingGrant(desk, canvas.id, badge, canvas.createdBy.id)) + ? admitted.has(canvas.id) || Boolean(await admittingGrant(desk, canvas.id, badge, canvas.createdBy.id, desk, "entry", await creatorOwnership())) : await mayDiscover(canvas); judged.set(canvas.id, allowed); /** diff --git a/packages/server/src/sweep.ts b/packages/server/src/sweep.ts index c070fc158..33734587d 100644 --- a/packages/server/src/sweep.ts +++ b/packages/server/src/sweep.ts @@ -16,7 +16,7 @@ import type { BadgeEnd, Capability, EndReach, Grant, OperatorEnd, SweepReport } from "@isocan/core"; import { endOf } from "./badges.ts"; -import { admittingGrant, rungOfAdmission } from "./grants.ts"; +import { admittingGrant, rungOfAdmission, type CreatorOwnership } from "./grants.ts"; import type { Admission, BadgeRecord, Desk, Provenance } from "./desk.ts"; /** @@ -284,6 +284,7 @@ export async function sweepCanvas( canvasId: string, creator: string | null = null, report: SweepListener = () => {}, + ownership?: CreatorOwnership, ): Promise { let expelled = 0; let rerooted = 0; @@ -352,7 +353,7 @@ export async function sweepCanvas( * re-rooted at `created` — the root this sweep never disturbs again. */ const door = async (badgeId: string): Promise => { - const answer = await admittingGrant(desk, canvasId, byId.get(badgeId)!, creator); + const answer = await admittingGrant(desk, canvasId, byId.get(badgeId)!, creator, desk, "entry", ownership); if (!answer) return expel(badgeId); return reroot(badgeId, answer.provenance, answer.capability); }; @@ -365,7 +366,7 @@ export async function sweepCanvas( */ const standing = async (badgeId: string, admission: Admission): Promise => { const held = rungOfAdmission(admission); - const answer = await admittingGrant(desk, canvasId, byId.get(badgeId)!, creator); + const answer = await admittingGrant(desk, canvasId, byId.get(badgeId)!, creator, desk, "entry", ownership); if (!answer) return expel(badgeId); if (answer.capability === held) return { fate: "keep", capability: held }; return reroot(badgeId, answer.provenance, answer.capability); @@ -423,7 +424,7 @@ export async function sweepCanvas( */ if (root.root === "space") { const held = rungOfAdmission(admission); - const answer = await admittingGrant(desk, canvasId, badge, creator); + const answer = await admittingGrant(desk, canvasId, badge, creator, desk, "entry", ownership); if (!answer) return expel(badge.badgeId); const same = answer.provenance.root === "space" && diff --git a/packages/server/src/ws.ts b/packages/server/src/ws.ts index 5075227db..a86203c2f 100644 --- a/packages/server/src/ws.ts +++ b/packages/server/src/ws.ts @@ -28,6 +28,7 @@ import { atLeast, narrowed, newId, + ownerOf, staleClientRefusal, WS_BAD_ORIGIN, WS_NO_BADGE, @@ -48,7 +49,7 @@ import { supportsQuestionnaires } from "@isocan/core"; import { supportsDesignRequests } from "@isocan/core"; import { DesignRequestClientError, designRequestOperation } from "./design-request-capability.ts"; import type { Desk } from "./desk.ts"; -import { admissionIn, admittingGrant, heldCapability } from "./grants.ts"; +import { admissionIn, admittingGrant, heldCapability, heldRung } from "./grants.ts"; import { ensureProxyAttestation, resolveProxyPrincipal, type ProxyAuthConfig } from "./attest.ts"; import { isSecureRequest, @@ -678,33 +679,43 @@ export function attachWebSockets( return { code: WS_NOT_ADMITTED, reason: REFUSED }; } let capability: Capability = "edit"; - if (canvasId && !admissionIn(badge, canvasId)) { + if (canvasId) { // The snapshot first, for the creator's floor: a canvas that is not // here at all falls through to `handleConnection`, which closes 4404. // A replica dialling a canvas its home has deleted takes this path, // and 4404 is what makes it stop dialling. const snapshot = await engine.getSnapshot(canvasId).catch(() => null); - const answer = snapshot - ? await admittingGrant(desk, canvasId, badge, snapshot.project.createdBy.id) - : null; - if (answer) { - // Provenance is revocation's grip: the grant that actually admitted - // this socket (or the creator's floor), so phase 9's sweep can find - // it. The capability rides with it (#88), because the door test - // short-circuits on the admission ever after. - capability = answer.capability; - await desk.admit(badge.badgeId, canvasId, answer.provenance, capability); - } else if (snapshot) { - return { code: WS_NOT_ADMITTED, reason: "not admitted" }; + const [joined, kinds] = snapshot + ? await Promise.all([engine.actorJoins(), engine.actorKinds()]) + : [undefined, undefined]; + const ownership = snapshot ? { joined, kinds } : undefined; + if (!admissionIn(badge, canvasId)) { + const answer = snapshot + ? await admittingGrant(desk, canvasId, badge, snapshot.project.createdBy.id, desk, "entry", ownership) + : null; + if (answer) { + // Provenance is revocation's grip: the grant that actually admitted + // this socket (or the creator's floor), so phase 9's sweep can find + // it. The capability rides with it (#88), because the door test + // short-circuits on the admission ever after. + capability = answer.capability; + await desk.admit(badge.badgeId, canvasId, answer.provenance, capability); + } else if (snapshot) { + return { code: WS_NOT_ADMITTED, reason: "not admitted" }; + } + } else { + // Already admitted — the same re-ask an admission below edit gets at + // the HTTP door, so a socket opened after proving an email connects as + // the editor the invitation makes them (see `heldCapability`). + capability = + (await heldCapability(desk, canvasId, badge, snapshot?.project.createdBy.id ?? null, ownership)) ?? + "edit"; + } + if (snapshot && !atLeast(capability, "own") && kinds?.[ownerOf(snapshot.project, joined)] === "agent") { + if (await heldRung(desk, snapshot.project, badge, null, joined, kinds) === "own") { + capability = "own"; + } } - } else if (canvasId) { - // Already admitted — the same re-ask an admission below edit gets at - // the HTTP door, so a socket opened after proving an email connects as - // the editor the invitation makes them (see `heldCapability`). - const snapshot = await engine.getSnapshot(canvasId).catch(() => null); - capability = - (await heldCapability(desk, canvasId, badge, snapshot?.project.createdBy.id ?? null)) ?? - "edit"; } return { badgeId: badge.badgeId, bearer: presented?.carrier === "bearer", capability }; } diff --git a/packages/server/test/agent-semantics.test.ts b/packages/server/test/agent-semantics.test.ts index 69dc239ef..19929c43a 100644 --- a/packages/server/test/agent-semantics.test.ts +++ b/packages/server/test/agent-semantics.test.ts @@ -93,7 +93,7 @@ beforeAll(async () => { actorHuman = ( await client.sendOp(null, { id: "", name: "Acme Person" }, { type: "actor.claim", - sessionKey: "human:acme", + sessionKey: "person:acme", name: "Acme Person", }) ).envelope.actor; diff --git a/packages/server/test/badge.ts b/packages/server/test/badge.ts index 9d05fd814..d8ac24cec 100644 --- a/packages/server/test/badge.ts +++ b/packages/server/test/badge.ts @@ -65,7 +65,7 @@ export async function mintTestBadge(base: string): Promise { badgeId: door.badgeId, token, headers, - async speakAs(actor, sessionKey = `test:${actor.id}`) { + async speakAs(actor, sessionKey = `home:${actor.id}`) { const claimed = await fetch(`${base}/api/ops`, { method: "POST", headers: { "Content-Type": "application/json", ...headers }, diff --git a/packages/server/test/canvas-group-context.test.ts b/packages/server/test/canvas-group-context.test.ts index 89ddfece7..5a6d265bd 100644 --- a/packages/server/test/canvas-group-context.test.ts +++ b/packages/server/test/canvas-group-context.test.ts @@ -43,7 +43,7 @@ beforeEach(async () => { desk = new FileDesk(home); await desk.init(); const badge = mintBadge("bearer"); badgeId = badge.record.badgeId; await desk.put(badge.record); engine = new Engine(store, desk); - await engine.claim({ badgeId, op: { type: "actor.claim", sessionKey: "test:context", as: actor.id, name: actor.name } }); + await engine.claim({ badgeId, op: { type: "actor.claim", sessionKey: "home:context", as: actor.id, name: actor.name } }); await post({ type: "project.create", canvasId, title: "Acme context", groupMode: "groups" }); }); afterEach(async () => { diff --git a/packages/server/test/canvas-group-migration.test.ts b/packages/server/test/canvas-group-migration.test.ts index 8e5f57a68..41ec558d2 100644 --- a/packages/server/test/canvas-group-migration.test.ts +++ b/packages/server/test/canvas-group-migration.test.ts @@ -43,7 +43,7 @@ beforeEach(async () => { desk = new FileDesk(home); await desk.init(); const badge = mintBadge("bearer"); badgeId = badge.record.badgeId; await desk.put(badge.record); engine = new Engine(store, desk); - for (const actor of [a, b, c]) await engine.claim({ badgeId, op: { type: "actor.claim", sessionKey: `test:${actor.id}`, as: actor.id, name: actor.name } }); + for (const actor of [a, b, c]) await engine.claim({ badgeId, op: { type: "actor.claim", sessionKey: `home:${actor.id}`, as: actor.id, name: actor.name } }); await post({ type: "project.create", canvasId, title: "Acme", groupMode: "legacy" }); }); afterEach(async () => { await desk.close(); await store.close(); await fs.rm(home, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); }); diff --git a/packages/server/test/grants.test.ts b/packages/server/test/grants.test.ts index 40f99df96..34ee7191a 100644 --- a/packages/server/test/grants.test.ts +++ b/packages/server/test/grants.test.ts @@ -713,7 +713,7 @@ describe("a free name, for a badge that has been nowhere", () => { } async function canvasHeldBy(name: string): Promise { const isaac = { id: "usr_isaac", name }; - await owner.speakAs(isaac, "test:isaac"); + await owner.speakAs(isaac, "home:isaac"); const made = await op(owner, { canvasId: null, actor: isaac, diff --git a/packages/server/test/jobs.test.ts b/packages/server/test/jobs.test.ts index 85d68bf84..8dadd00aa 100644 --- a/packages/server/test/jobs.test.ts +++ b/packages/server/test/jobs.test.ts @@ -153,7 +153,7 @@ function authHeaders(badge: StoredBadge, json = false): Record { }; } -async function mintEditor(base: string, sessionKey = "test:acme-editor"): Promise<{ badge: StoredBadge; badgeId: string; actor: Actor }> { +async function mintEditor(base: string, sessionKey = "home:acme-editor"): Promise<{ badge: StoredBadge; badgeId: string; actor: Actor }> { const knocked = await askTheDoor(base); if (!("badge" in knocked)) throw new Error(`door refused: ${knocked.refused.error}`); const { badge } = knocked; diff --git a/packages/server/test/membership.test.ts b/packages/server/test/membership.test.ts index b35d7a96b..a9866c1ab 100644 --- a/packages/server/test/membership.test.ts +++ b/packages/server/test/membership.test.ts @@ -475,7 +475,7 @@ describe("two tenants, one home", () => { // history, so it stays. op: { type: "actor.claim", - sessionKey: "test:usr_isaac_p", + sessionKey: "home:usr_isaac_p", as: "usr_isaac_p", name: "Isaac the Second", }, diff --git a/packages/server/test/prototype-click.test.ts b/packages/server/test/prototype-click.test.ts index ad24b9471..40741f41b 100644 --- a/packages/server/test/prototype-click.test.ts +++ b/packages/server/test/prototype-click.test.ts @@ -72,8 +72,8 @@ beforeEach(async () => { await agent.speakAs(percy, "claude-code:s-1"); const made = await fetch(`${base}/api/ops`, { method: "POST", - headers: { "Content-Type": "application/json", ...agent.headers }, - body: JSON.stringify({ canvasId: null, actor: percy, op: { type: "project.create", canvasId: CANVAS, title: "Acme Prototype" } }), + headers: { "Content-Type": "application/json", ...person.headers }, + body: JSON.stringify({ canvasId: null, actor: priya, op: { type: "project.create", canvasId: CANVAS, title: "Acme Prototype" } }), }); if (!made.ok) throw new Error(await made.text()); await fetch(`${base}${grantsRoute(CANVAS)}`, { diff --git a/packages/server/test/seen.test.ts b/packages/server/test/seen.test.ts index a86cad706..6812c51bd 100644 --- a/packages/server/test/seen.test.ts +++ b/packages/server/test/seen.test.ts @@ -93,7 +93,7 @@ async function seed(badge: TestBadge): Promise { async function laptop(): Promise { const badge = await mintTestBadge(base); - await badge.speakAs(ada, "test:laptop"); + await badge.speakAs(ada, "home:laptop"); await seed(badge); return badge; } @@ -197,8 +197,8 @@ describe("a viewer is never refused their own mark", () => { describe("a person who was two actors", () => { it("keeps the marks made under the id they stopped using", async () => { const badge = await mintTestBadge(base); - await badge.speakAs(wasAda, "test:old"); - await badge.speakAs(ada, "test:new"); + await badge.speakAs(wasAda, "home:old"); + await badge.speakAs(ada, "home:new"); await seed(badge); await mark(badge, wasAda, 2); diff --git a/packages/server/test/view-only.test.ts b/packages/server/test/view-only.test.ts index cd51f5915..493933508 100644 --- a/packages/server/test/view-only.test.ts +++ b/packages/server/test/view-only.test.ts @@ -29,7 +29,8 @@ import type { ServerMessage, WatchLogResponse, } from "@isocan/core"; -import { grantsRoute, VIEW_ONLY } from "@isocan/core"; +import { applyOperation, grantsRoute, invertOperation, VIEW_ONLY } from "@isocan/core"; +import { ensureLinkGrant } from "../src/grants.ts"; import { startDaemon, type Daemon } from "../src/daemon.ts"; import { currentSocketUrl, mintTestBadge, type TestBadge } from "./badge.ts"; @@ -698,3 +699,96 @@ describe("changing what the link admits to", () => { expect(((await seen.json()) as CanvasSnapshotResponse).capability).toBeUndefined(); }); }); + +describe("agents can never own rooms, and legacy agent-owned canvases resolve to their person owner", () => { + it("refuses project.create, space creation, and group creation when the actor is an agent", async () => { + const iona = { id: "usr_iona", name: "Iona 7" }; + const agentBadge = await stranger(); + await agentBadge.speakAs(iona, "antigravity:conv-1"); + + const canvasRes = await op(agentBadge, { + canvasId: null, + actor: iona, + op: { type: "project.create", canvasId: "prj_agent_refused", title: "Should fail" }, + }); + expect(canvasRes.status).toBe(400); + expect(((await canvasRes.json()) as { code?: string }).code).toBe("agent-owner"); + + const spaceRes = await post(agentBadge, "/api/spaces", { name: "Agent Space", actorId: iona.id }); + expect(spaceRes.status).toBe(403); + expect(((await spaceRes.json()) as { code?: string }).code).toBe("agent-owner"); + + const groupRes = await post(agentBadge, "/api/groups", { name: "Agent Group", actorId: iona.id }); + expect(groupRes.status).toBe(403); + expect(((await groupRes.json()) as { code?: string }).code).toBe("agent-owner"); + }); + + it("lets a person who owns a legacy agent creator hold own across badges, sockets, and link changes", async () => { + const iona = { id: "usr_iona", name: "Iona 7" }; + await daemon.desk.attest(owner.badgeId, { + attribute: "email:priya@acme.test", + verifiedVia: "proxy", + at: new Date().toISOString(), + }); + await owner.speakAs(iona, "antigravity:conv-1"); + + // Seed a legacy canvas already on disk whose createdBy is the agent Iona 7. + const birthOp = { type: "project.create" as const, canvasId: CANVAS, title: "Legacy Agent Board" }; + const envelope = { id: "op_legacy_birth", canvasId: null, actor: iona, ts: new Date().toISOString(), op: birthOp }; + const state = applyOperation(null, envelope)!; + await daemon.store.createCanvasDir(CANVAS); + await daemon.store.appendLog(CANVAS, { seq: 1, envelope, inverse: invertOperation(null, birthOp) }); + await daemon.store.saveSnapshot(CANVAS, state, 1); + await ensureLinkGrant(daemon.desk, CANVAS, owner.badgeId); + + // Priya opens the canvas from a separate browser cookie badge claiming Priya + her email. + const browser = await stranger(); + await daemon.desk.attest(browser.badgeId, { + attribute: "email:priya@acme.test", + verifiedVia: "magic-link", + at: new Date().toISOString(), + }); + await browser.speakAs(priya, "web:browser-1"); + + const snapRes = await get(browser, `/api/projects/${CANVAS}/canvas`); + expect(snapRes.status).toBe(200); + expect(((await snapRes.json()) as CanvasSnapshotResponse).capability).toBe("own"); + + const hello = await new Promise((resolve, reject) => { + const ws = new WebSocket(currentSocketUrl(`${base.replace("http:", "ws:")}/ws?canvasId=${CANVAS}`), { + headers: browser.headers, + }); + ws.on("error", reject); + ws.on("message", (data) => { + resolve(JSON.parse(String(data)) as ServerMessage); + ws.close(); + }); + }); + expect(hello.type).toBe("snapshot"); + if (hello.type === "snapshot") expect(hello.capability).toBe("own"); + + // Lowering the link to read-only must keep Priya at own, never sweep her down to read. + const lowered = await post(browser, grantsRoute(CANVAS), { subject: "link", capability: "read", actorId: priya.id }); + expect(lowered.status).toBe(200); + expect(((await (await get(browser, `/api/projects/${CANVAS}/canvas`)).json()) as CanvasSnapshotResponse).capability).toBe("own"); + expect((await rename(browser)).status).toBe(200); + + // Granting Priya's email `own` is not blocked as redundant by namesTheCreator + // (reaches attester check rather than returning bad-grant). + const granted = await post(owner, grantsRoute(CANVAS), { + subject: "email:priya@acme.test", + capability: "own", + actorId: priya.id, + }); + expect(granted.status).toBe(400); + expect(((await granted.json()) as { code?: string }).code).toBe("no-attester"); + + // Turning the link off works from Priya's browser badge. + const link = (await grantsOf(browser)).find((g) => g.subject === "link")!; + const off = await fetch(`${base}${grantsRoute(CANVAS)}/${link.id}?actorId=${priya.id}`, { + method: "DELETE", + headers: browser.headers, + }); + expect(off.status).toBe(200); + }); +}); diff --git a/packages/voice-agent/src/voice-harness.ts b/packages/voice-agent/src/voice-harness.ts index 5a2f4fb94..24990f553 100644 --- a/packages/voice-agent/src/voice-harness.ts +++ b/packages/voice-agent/src/voice-harness.ts @@ -26,7 +26,7 @@ import { agentSessionOf, machineAgentKey } from "./agent-key.ts"; import { readRcAgents, upsertRcAgent } from "./rc-rows.ts"; import { statSync } from "node:fs"; import { keysFile, migrateVoiceKey, removeKey, resolveKeyAsync, writeKey } from "@isocan/core/keystore"; -import { ApiError, connect, matchRef, type CanvasHandle, type ListedItem } from "@isocan/api"; +import { ApiError, connect, matchRef, resolveOwnerActor, type CanvasHandle, type ListedItem } from "@isocan/api"; import { besideBox, CANVAS_GROUPS_REQUIRED, @@ -3587,7 +3587,8 @@ export async function startVoiceServer(options: VoiceServerOptions): Promise<{ } const canvasId = newCanvasId(); try { - await target.canvas.ctx.client.sendOp(null, target.canvas.ctx.actor, { + const owner = await resolveOwnerActor(target.canvas.ctx.client, target.canvas.ctx.home, target.canvas.ctx.actor); + await target.canvas.ctx.client.sendOp(null, owner, { type: "project.create", canvasId, title, @@ -4462,8 +4463,10 @@ export async function startVoiceServer(options: VoiceServerOptions): Promise<{ try { /* Home-scoped, exactly as `isocan canvas create` sends it: the envelope names no canvas, because the canvas does not - exist until this op makes it. */ - const ack = await target.canvas.ctx.client.sendOp(null, target.canvas.ctx.actor, { + exist until this op makes it — owned by the person, not + the agent. */ + const owner = await resolveOwnerActor(target.canvas.ctx.client, target.canvas.ctx.home, target.canvas.ctx.actor); + const ack = await target.canvas.ctx.client.sendOp(null, owner, { type: "project.create", canvasId, title, diff --git a/packages/voice-agent/test/badge.ts b/packages/voice-agent/test/badge.ts index 2e8d4d40c..c1716a06e 100644 --- a/packages/voice-agent/test/badge.ts +++ b/packages/voice-agent/test/badge.ts @@ -57,7 +57,7 @@ export async function mintTestBadge(base: string): Promise { badgeId: door.badgeId, token, headers, - async speakAs(actor, sessionKey = `test:${actor.id}`) { + async speakAs(actor, sessionKey = `home:${actor.id}`) { const claimed = await fetch(`${base}/api/ops`, { method: "POST", headers: { "Content-Type": "application/json", ...headers }, diff --git a/packages/voice-agent/test/voice-harness.test.ts b/packages/voice-agent/test/voice-harness.test.ts index 0af330923..9854d8d42 100644 --- a/packages/voice-agent/test/voice-harness.test.ts +++ b/packages/voice-agent/test/voice-harness.test.ts @@ -2205,7 +2205,7 @@ describe("the projects this session can work on", () => { expect(canvasId).toMatch(/^prj_/); // The home lists it, and its own log holds its birth — the same - // `project.create` `isocan canvas create` sends, sent as this agent. + // `project.create` `isocan canvas create` sends, owned by the person. const canvases = (await (await fetch(`${base}/api/projects`, { headers: badge.headers })).json()) as { id: string; title: string; @@ -2213,7 +2213,7 @@ describe("the projects this session can work on", () => { expect(canvases.find((c) => c.id === canvasId)?.title).toBe("Launch plan"); const born = (await log([canvasId])).find((e) => e.type === "project.create"); expect(born, "a new canvas's log starts with its own birth").toBeDefined(); - expect(born!.actor).not.toBe(seeder.id); + expect(born!.actor).toBe(person.id); // Created, not entered: the session is still on the canvas it was on, // because nothing was switched and the answer says so. @@ -2510,10 +2510,7 @@ describe("the name the enrolment summons", () => { * copies of fifty lines of setup would drift. */ async function enrolledAndRenamed() { - const named = await isocan(["identity", "--name", "Person", "--as", "usr_person", "--session"], { - ISOCAN_SESSION_ID: "person", - ISOCAN_HARNESS: "isocan", - }); + const named = await isocan(["identity", "--name", "Person", "--home"]); expect(named.code, named.stderr).toBe(0); // `--canvas prj_1`: the point-anywhere form, so the enrolment lands in the // room the harness stands in rather than in the one a bare temp cwd would @@ -3944,10 +3941,7 @@ describe("the harness as the rc's adapter", () => { // is what `isocan rc` resolves the adapter from. // The CLI's own badge has to hold the person before it may enrol anyone: // the badge this test mints is not the badge the spawned CLI carries. - const named = await isocan(["identity", "--name", "Person", "--as", "usr_person", "--session"], { - ISOCAN_SESSION_ID: "person", - ISOCAN_HARNESS: "isocan", - }); + const named = await isocan(["identity", "--name", "Person", "--home"]); expect(named.code, named.stderr).toBe(0); const enrolled = await isocan(["rc", "add", "Voice", "--harness", "voice"]); expect(enrolled.code, enrolled.stderr).toBe(0); diff --git a/packages/web/test/badge.ts b/packages/web/test/badge.ts index dfbcad62a..233ba987f 100644 --- a/packages/web/test/badge.ts +++ b/packages/web/test/badge.ts @@ -59,7 +59,7 @@ export async function mintTestBadge(base: string): Promise { badgeId: door.badgeId, token, headers, - async speakAs(actor, sessionKey = `test:${actor.id}`) { + async speakAs(actor, sessionKey = `home:${actor.id}`) { const claimed = await fetch(`${base}/api/ops`, { method: "POST", headers: { "Content-Type": "application/json", ...headers }, diff --git a/packages/web/test/desk.test.ts b/packages/web/test/desk.test.ts index c20b58c6b..458858e60 100644 --- a/packages/web/test/desk.test.ts +++ b/packages/web/test/desk.test.ts @@ -85,7 +85,7 @@ describe("the terminal has the same desk", () => { const desk = cli.slice(cli.indexOf('.command("desk ")'), cli.indexOf('.command("end [note...]")')); expect(desk).toContain("properties: { [DESK_OF_PROP]: sprint.id }"); expect(desk).toContain("g.subject === LINK"); - expect(desk).toContain("revokeGrant(canvasId, link.id)"); + expect(desk).toContain("revokeGrant(canvasId, link.id"); expect(desk).toContain("mintPass(canvasId)"); expect(desk).toContain("canvasUrlWithPass(origin, canvasId, token)"); }); diff --git a/packages/web/test/ownerguard.test.ts b/packages/web/test/ownerguard.test.ts index a8bb8574d..84c62929b 100644 --- a/packages/web/test/ownerguard.test.ts +++ b/packages/web/test/ownerguard.test.ts @@ -33,7 +33,7 @@ const read = (rel: string) => readFileSync(fileURLToPath(new URL(rel, import.met describe("only an owner may change sharing or publication", () => { const dialog = read("../src/components/ShareDialog.tsx"); const http = read("../../server/src/http.ts"); - const ownerCheck = /atLeast\(await heldRung\(desk, snapshot\.project, req\.badge!, actorId \?\? null, await engine\.actorJoins\(\)\), "own"\)/g; + const ownerCheck = /atLeast\(await heldRung\(desk, snapshot\.project, req\.badge!, actorId \?\? null, await engine\.actorJoins\(\)(?:, await engine\.actorKinds\(\))?\), "own"\)/g; it("is refused by the daemon, not merely hidden by the app", () => { // Both writes — the POST that invites or sets the link, and the DELETE diff --git a/scripts/lib/design-lint-eval-runner.mjs b/scripts/lib/design-lint-eval-runner.mjs index bb888bc40..f7120cf88 100644 --- a/scripts/lib/design-lint-eval-runner.mjs +++ b/scripts/lib/design-lint-eval-runner.mjs @@ -155,10 +155,10 @@ export async function createEvalHost(task) { const close = async () => { daemon.app.server.closeAllConnections(); await daemon.close(); await rm(home, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); }; try { const client = new DaemonClient(`http://127.0.0.1:${daemon.app.server.address().port}`, home); - const session = "acme:design-eval"; + const session = "home:design-eval"; await client.claimActor({ type: "actor.claim", sessionKey: session, name: "Acme Evaluation" }); const actor = (await client.actorBindings([session]))[0].actor; - const ctx = { client, actor, home, harness: "acme", birthHome: null, binding: null, homeOf: async () => null, homes: async () => ({ birth: null, links: [], rows: {}, legacy: false, rowFor: () => null }) }; + const ctx = { client, actor, home, harness: null, birthHome: null, binding: null, homeOf: async () => null, homes: async () => ({ birth: null, links: [], rows: {}, legacy: false, rowFor: () => null }) }; const id = core.newCanvasId(); await client.sendOp(null, actor, { type: "project.create", canvasId: id, title: "Acme evaluation", groupMode: "groups" }); const canvas = new CanvasHandle(ctx, (await client.snapshot(id)).project);