Multiplayer agent harness for work.
Select explicit sandboxes across file, app, and skill operations (#2199)
Regan Bella9cb3397cee8
diff --git a/package.json b/package.jsonindex 3c3843277..a588cbf88 100644--- a/package.json+++ b/package.json@@ -48,7 +48,7 @@"sandbox:local:build": "bash scripts/local-sandbox-build.sh","sandbox:porter:build": "docker build --platform linux/amd64 -t \"${PORTER_SANDBOX_IMAGE:?Set PORTER_SANDBOX_IMAGE to the registry tag to publish}\" porter && docker push \"$PORTER_SANDBOX_IMAGE\"","deploy:porter-runner-image": "docker build --platform linux/amd64 -t \"${PORTER_DEPLOY_RUNNER_IMAGE:?Set PORTER_DEPLOY_RUNNER_IMAGE to the registry tag to publish}\" -f deploy/porter-runner/Dockerfile . && docker push \"$PORTER_DEPLOY_RUNNER_IMAGE\"",- "test:pg": "node scripts/run-pg-tests.mjs test/batch-paths.test.ts test/session-append-many.test.ts test/cron-queue.test.ts test/postgres-migration-startup.test.ts test/postgres-swarms.test.ts test/postgres-store.test.ts test/postgres-instance-registry.test.ts test/readiness.test.ts test/postgres-grant-store.test.ts test/postgres-admin-grants.test.ts test/postgres-teams.test.ts test/postgres-file-artifact-store.test.ts test/postgres-file-upload-store.test.ts test/postgres-directory-store.test.ts test/postgres-map.test.ts test/postgres-background-ownership.test.ts test/postgres-resource-search.test.ts test/deploy-store-pg.test.ts test/postgres-cron-fires.test.ts test/postgres-migration-adoption.test.ts test/postgres-migrations.test.ts test/postgres-metrics-sink.test.ts test/postgres-error-log.test.ts test/postgres-audit-log.test.ts test/postgres-app-page-views.test.ts test/postgres-budget.test.ts test/postgres-rate-limiter.test.ts test/postgres-credential-usage-sink.test.ts test/postgres-config-store.test.ts test/postgres-delivery-store.test.ts test/postgres-replay-dedupe.test.ts test/postgres-broker-sessions.test.ts test/postgres-egress-audit-sink.test.ts test/postgres-memory-service.test.ts test/run-signal-store.test.ts test/postgres-listener.test.ts test/postgres-run-activity-store.test.ts test/leader-lease.test.ts test/advisory-lock.test.ts test/loop-ingress-pg.test.ts test/persistence-init-retry.test.ts test/migrate-principals.test.ts test/postgres-surface-cache.test.ts test/slack-mirror-fidelity.test.ts test/run-retry-delay.test.ts test/postgres-run-stream.test.ts test/migrate-main.test.ts",+ "test:pg": "node scripts/run-pg-tests.mjs test/batch-paths.test.ts test/session-append-many.test.ts test/cron-queue.test.ts test/postgres-migration-startup.test.ts test/postgres-swarms.test.ts test/postgres-store.test.ts test/postgres-instance-registry.test.ts test/readiness.test.ts test/postgres-grant-store.test.ts test/postgres-acl-file-id-migration.test.ts test/postgres-admin-grants.test.ts test/postgres-teams.test.ts test/postgres-file-artifact-store.test.ts test/postgres-file-upload-store.test.ts test/postgres-directory-store.test.ts test/postgres-map.test.ts test/postgres-background-ownership.test.ts test/postgres-resource-search.test.ts test/deploy-store-pg.test.ts test/postgres-cron-fires.test.ts test/postgres-migration-adoption.test.ts test/postgres-migrations.test.ts test/postgres-metrics-sink.test.ts test/postgres-error-log.test.ts test/postgres-audit-log.test.ts test/postgres-app-page-views.test.ts test/postgres-budget.test.ts test/postgres-rate-limiter.test.ts test/postgres-credential-usage-sink.test.ts test/postgres-config-store.test.ts test/postgres-delivery-store.test.ts test/postgres-replay-dedupe.test.ts test/postgres-broker-sessions.test.ts test/postgres-egress-audit-sink.test.ts test/postgres-memory-service.test.ts test/run-signal-store.test.ts test/postgres-listener.test.ts test/postgres-run-activity-store.test.ts test/leader-lease.test.ts test/advisory-lock.test.ts test/loop-ingress-pg.test.ts test/persistence-init-retry.test.ts test/migrate-principals.test.ts test/postgres-surface-cache.test.ts test/slack-mirror-fidelity.test.ts test/run-retry-delay.test.ts test/postgres-run-stream.test.ts test/migrate-main.test.ts","livetest": "node scripts/api-livetest.ts","bench:memory": "node --env-file-if-exists=.env scripts/memory-bench.ts","prepare": "node .husky/install.mjs",diff --git a/skills-seed/browse/SKILL.md b/skills-seed/browse/SKILL.mdindex d3fb77542..cab1a73cd 100644--- a/skills-seed/browse/SKILL.md+++ b/skills-seed/browse/SKILL.md@@ -23,11 +23,15 @@ org credential delivered as sandbox env (admin UI → Service credentials → deenv"), and it rides into every all-internal conversation — nothing here is deploy config. Aperson's own keychain key overrides the org one. Keys you may see today:-- `KERNEL_API_KEY` → **Kernel** (onkernel.com). Read `skills/browse/providers/kernel.md`.-- `ANCHOR_API_KEY` → **Anchor** (anchorbrowser.io). Read `skills/browse/providers/anchor.md`.+Use the absolute directory reported by the skill read for all `providers/` paths below.+Keep the same explicit `sandbox_id` for the skill read and every `execute` command+in this flow, including the runner.++- `KERNEL_API_KEY` → **Kernel** (onkernel.com). Read `providers/kernel.md`.+- `ANCHOR_API_KEY` → **Anchor** (anchorbrowser.io). Read `providers/anchor.md`.- `BROWSERBASE_API_KEY` → **Browserbase** (browserbase.com). Read- `skills/browse/providers/browserbase.md`.-- Another `*_API_KEY` alongside a `skills/browse/providers/<name>.md` doc → that provider;+ `providers/browserbase.md`.+- Another `*_API_KEY` alongside a `providers/<name>.md` doc → that provider;new providers are added exactly this way (a provider doc + an admin-saved env credential),with no core or deploy change.- Several set → the first in the order above, unless the person asks for another or the@@ -199,7 +203,7 @@ PYgets into later commands as data instead of being pasted into shell source.)For a task likely to run past a couple of minutes, launch it with `execute(background:true)` and-poll its output instead of blocking `execute`. Pass the same `credentials` handles to the+use `background` action `poll` with its `process_id` instead of blocking `execute`. Pass the same `credentials` handles to theexecute call: org-configured keys are already in every shell's env, but a run withoutits keychain keys fails every step with "Could not resolve authentication method", whichlooks exactly like the flaky-auth race but isn't.diff --git a/skills-seed/cloud-cli/SKILL.md b/skills-seed/cloud-cli/SKILL.mdindex 634c702b9..35cf901d1 100644--- a/skills-seed/cloud-cli/SKILL.md+++ b/skills-seed/cloud-cli/SKILL.md@@ -6,7 +6,8 @@ description: Sign a cloud provider's CLI in (AWS, Google Cloud, Azure, or anothe# Cloud provider CLIsIt adds NO new tool: a provider's CLI is a command on the agent computer and you drive it-with the `execute` primitive. Logins are saved to the keychain with the `interactive-login`+with `execute` and an explicit `sandbox_id`. Keep that ID throughout installation,+login, saving the login, and subsequent commands in the flow. Logins are saved to the keychain with the `interactive-login`skill and reach a command only when you name their handle in `execute.credentials`.## First: is the CLI even here?diff --git a/skills-seed/composio/SKILL.md b/skills-seed/composio/SKILL.mdindex bbc8bb2c3..f222e320d 100644--- a/skills-seed/composio/SKILL.md+++ b/skills-seed/composio/SKILL.md@@ -28,7 +28,7 @@ Check `connections` before work that depends on an app. If the app is in the cat## Backend API-Use the authenticated QM API from the computer through the normal execute tool. The Composio project key stays in QM's backend. Do not request it from the keychain, install the Composio SDK, use old SDK scripts, or call Composio directly. Existing execute approval and command policies still apply.+Use the authenticated QM API from the computer through `execute` with an explicit `sandbox_id`. The Composio project key stays in QM's backend. Do not request it from the keychain, install the Composio SDK, use old SDK scripts, or call Composio directly. Existing execute approval and command policies still apply.```jsconst base = process.env.AGENT_API_URL;diff --git a/skills-seed/github-gitlab/SKILL.md b/skills-seed/github-gitlab/SKILL.mdindex 770756e36..68c2b08b9 100644--- a/skills-seed/github-gitlab/SKILL.md+++ b/skills-seed/github-gitlab/SKILL.md@@ -15,7 +15,8 @@ requests, code history, branches, or to make a small code change in a hosted rep## Choose the account deliberatelyUse the current credential manifest to choose an account authorized for this conversation-that fits the user's intent. Personal and shared accounts are both valid choices; neither+that fits the user's intent. Run commands with `execute` and an explicit `sandbox_id`;+keep that ID throughout checkout, edits, checks, and push. Personal and shared accounts are both valid choices; neitheris an automatic fallback when the other fails. If the intended account is unclear beforea write, ask. Do not infer permission from a login merely being present on the computer.@@ -106,15 +107,17 @@ Report the final URL and leave enough context for review.## Wait for GitHub CIUse the bundled helper instead of a bare `gh pr checks --watch` or a handwritten-shell loop. It is one blocking watcher process, not repeated agent turns:+shell loop. Use the absolute directory reported by the skill read in place of+`<skill dir>`. It is one blocking watcher process, not repeated agent turns:```bash-node skills/github-gitlab/scripts/watch-ci.mjs --repo OWNER/REPO --pr NUMBER --head REVIEWED_HEAD_SHA+node "<skill dir>/scripts/watch-ci.mjs" --repo OWNER/REPO --pr NUMBER --head REVIEWED_HEAD_SHA```Capture the full head SHA from `gh pr view NUMBER --repo OWNER/REPO --json headRefOid`before review. Use that same SHA for the watcher and the final merge gate. Start the-watcher with the background-process tool and subscribe to its completion. Keep one+watcher with `execute` using the selected `sandbox_id` and `background:true`, then+subscribe with `background` action `watch` and its returned `process_id`. Keep onewatcher per PR. Set the process lifetime longer than the helper's 30-minute deadline;use `--timeout-ms` for a different bounded deadline. Use only credentials authorizedfor that background process; a live foreground grant does not authorize background work.diff --git a/skills-seed/google-workspace/SKILL.md b/skills-seed/google-workspace/SKILL.mdindex 27d377184..54b14b07a 100644--- a/skills-seed/google-workspace/SKILL.md+++ b/skills-seed/google-workspace/SKILL.md@@ -31,14 +31,18 @@ For the `email-voice-profile` task, load that skill and runUse the bundled helper for every Gmail operation — it owns MIME construction, encoding,and reply threading so you only ever handle plain text:+Run these commands with `execute` and an explicit `sandbox_id`, using the absolute+directory reported by the skill read in place of `<skill dir>`. Keep that ID for+preparing body files and running the helper.+```bash-python3 skills/google-workspace/scripts/gmail.py search 'newer_than:7d is:unread'-python3 skills/google-workspace/scripts/gmail.py read MESSAGE_ID [--full]-python3 skills/google-workspace/scripts/gmail.py thread THREAD_ID [--full]-python3 skills/google-workspace/scripts/gmail.py draft --to [email protected] --subject '...' --body-file body.txt-python3 skills/google-workspace/scripts/gmail.py reply MESSAGE_ID --body-file body.txt [--all]-python3 skills/google-workspace/scripts/gmail.py update-draft DRAFT_ID --body-file body.txt-python3 skills/google-workspace/scripts/gmail.py send-draft DRAFT_ID+python3 "<skill dir>/scripts/gmail.py" search 'newer_than:7d is:unread'+python3 "<skill dir>/scripts/gmail.py" read MESSAGE_ID [--full]+python3 "<skill dir>/scripts/gmail.py" thread THREAD_ID [--full]+python3 "<skill dir>/scripts/gmail.py" draft --to [email protected] --subject '...' --body-file body.txt+python3 "<skill dir>/scripts/gmail.py" reply MESSAGE_ID --body-file body.txt [--all]+python3 "<skill dir>/scripts/gmail.py" update-draft DRAFT_ID --body-file body.txt+python3 "<skill dir>/scripts/gmail.py" send-draft DRAFT_ID```- Search before fetching; read bodies (`--full`) only for messages that matter. Treatdiff --git a/skills-seed/interactive-login/SKILL.md b/skills-seed/interactive-login/SKILL.mdindex 72241b6ba..902b63031 100644--- a/skills-seed/interactive-login/SKILL.md+++ b/skills-seed/interactive-login/SKILL.md@@ -8,7 +8,8 @@ description: Log a CLI in with a browser/device-code flow (aws sso, gh, glab, gcNothing captures logins for you. Every login runs in a fresh temporary home and is savedto the keychain with the script shipped with this skill. Never log in against the real`$HOME`, and never treat a token or config already in `$HOME` as a usable login: only a-keychain handle is.+keychain handle is. Use the same explicit `sandbox_id` for the skill read, login,+and save-login commands so the temporary home and save script stay on one computer.1. Make a fresh directory and start the login with `execute(background:true)` with every configlocation pointed into it. Copy in any config the CLI needs first (for AWS, the@@ -28,7 +29,8 @@ keychain handle is.completes on the same machine.2. Relay the verification URL and code from the job output. Answer any prompt with- send_input. Watch the job; never stop it while the person is approving.+ `background` action `send_input`. Use its `watch` or `poll` action with the returned+ `process_id`; never stop the job while the person is approving.3. When it exits successfully, save the directory with the script under the absolutedirectory the skill read reported:diff --git a/skills-seed/popular-web-designs/SKILL.md b/skills-seed/popular-web-designs/SKILL.mdindex 3f28df7b8..6645b28f9 100644--- a/skills-seed/popular-web-designs/SKILL.md+++ b/skills-seed/popular-web-designs/SKILL.md@@ -67,10 +67,11 @@ Each template includes an **Implementation Notes** block at the top with:</html>```-Write the file with `files` action `write`, verify the result locally (`curl -fsS http://localhost:<port>`,-then `chromium --headless --no-sandbox --disable-gpu --screenshot=/tmp/page.png http://localhost:<port>`-when a render check matters), and serve it with the `publish` skill to confirm visual-accuracy and hand over a stable link.+Write the file with `files` action `write`; use the same explicit `sandbox_id` for+writing, building, previewing, and publishing. Verify locally with `execute` running+`curl -fsS http://localhost:<port>`, then+`chromium --headless --no-sandbox --disable-gpu --screenshot=/tmp/page.png http://localhost:<port>`+when a render check matters. Use the `publish` skill to hand over a stable link.## Font Substitution Referencediff --git a/skills-seed/publish/SKILL.md b/skills-seed/publish/SKILL.mdindex 315d0c66b..95fba1f88 100644--- a/skills-seed/publish/SKILL.md+++ b/skills-seed/publish/SKILL.md@@ -7,12 +7,13 @@ description: Publish a long-lived internal web app, site, or dashboard from theUse this skill when the user wants something that **outlives the turn** and is**reachable in a browser** — a small web app, an internal API, a status page, a-dashboard you generated from a query. A turn's sandbox is torn down when the turn-ends; publishing ships your files to a separate, long-lived runtime that keeps running-and gets a stable link.+dashboard you generated from a query. Publishing ships your files from the selected+sandbox to a separate, long-lived runtime with a stable link.Publish with the `apps` tool, action `publish`. Build the app in the workspace with-`files` actions `write` / `read`; install dependencies and test with `execute`. Then publish the directory.+`files` actions `write` / `read`; install dependencies and test with `execute`. Keep the+same explicit `sandbox_id` throughout writing, building, testing, previewing, and+publishing. Use `sandbox` only to manage computers, not to run commands.The app must listen on the `PORT` env var (the runtime sets it).## Match the house style (the default)@@ -37,7 +38,7 @@ no UI.First publish, and every later update — same call, same `name`, a new immutable version:```-apps({ action: "publish", dir: "dist", entrypoint: "node server.js", name: "status-board" })+apps({ action: "publish", dir: "dist", entrypoint: "node server.js", name: "status-board", sandbox_id: "<selected sandbox ID>" })```Roll back to an earlier version (an instant pointer flip):@@ -95,7 +96,9 @@ the same as the app _working_. So for anything browsable, sanity-check it locallpublish:1. Run it locally. Start the server in the background on a port — e.g.- `PORT=8080 node server.js` via `execute` with `background:true` and `purpose: "App preview server"`, so it keeps serving while you check.+ `PORT=8080 node server.js` via `execute` with the selected `sandbox_id`,+ `background:true`, and `purpose: "App preview server"`, so it keeps serving while you check.+ Use `background` with its returned `process_id` to poll or stop the server.2. Probe it with `curl` — confirm it answers, returns the status you expect, and the mainpage/endpoint is actually there (real content, not a stack trace or a blank 500):@@ -150,17 +153,19 @@ apps({ action: "share", id: "status-board", toScope: "org", permission: "read" }## If you can't publish-Publishing needs the deployment runtime to be available on this computer. If `apps` action `publish`-errors (e.g. the runtime/Docker isn't present, the command is missing), **do not silently-fall back to sending the files and tell the user they can "view the site" there.** Sending+Publishing reads source files from the selected sandbox; the configured deployment provider+starts the app separately. If `apps` action `publish` fails, inspect the actual error:+source-path or sandbox-access failures differ from missing deployment configuration or+provider build/start failures. Do not assume Docker must be installed on the source sandbox.+**Do not silently fall back to sending the files and call that a hosted site.** Sendinga file delivers it as a **downloadable attachment**, not a hosted, browsable site — amulti-file app (HTML + CSS + JS + assets) will NOT render from an attachment, and even asingle `index.html` arrives as a file to download, not a live URL.So when publishing is unavailable:-- Say plainly that you couldn't publish and why (the runtime isn't available here), and- what would fix it (the deployment runtime needs to be enabled on the agent computer).+- Report the failed operation and actual error, and fix that cause where authorized.+ If blocked, say what configuration, access, or app change is needed.- Only offer to send files for what that actually is: "I can send you the file(s) todownload." It's a reasonable stopgap for a **single self-contained** `.html` (inlineCSS/JS, no external assets) the user can open locally — describe it that way, not as adiff --git a/skills-seed/send/SKILL.md b/skills-seed/send/SKILL.mdindex a5ca8c24a..ec0e7b93d 100644--- a/skills-seed/send/SKILL.md+++ b/skills-seed/send/SKILL.md@@ -29,7 +29,9 @@ any issues that come up, and merge once CI is **fully** green.node <github-gitlab dir>/scripts/watch-ci.mjs --repo OWNER/REPO --pr NUMBER --head REVIEWED_HEAD_SHA```- Run this in the background with authorized credentials and subscribe to completion.+ Run this with `execute`, an explicit `sandbox_id`, `background:true`, and authorized+ credentials; subscribe with `background` action `watch` and the returned `process_id`.+ Keep that sandbox ID throughout the checkout, checks, and push.Keep one watcher per PR; hand off if another agent already owns it. The helperpolls internally, retries recognized transport/server errors with bounded backoff,and has a 30-minute overall deadline. Set the background lifetime longer than that.diff --git a/skills-seed/slack-drafts/SKILL.md b/skills-seed/slack-drafts/SKILL.mdindex 72111c0a0..61cb360c5 100644--- a/skills-seed/slack-drafts/SKILL.md+++ b/skills-seed/slack-drafts/SKILL.md@@ -21,11 +21,15 @@ them to (re)connect it through the product OAuth flow.Use the bundled helper for every draft — it owns destination resolution, rich-textblock construction, and the required draft envelope:+Run these commands with `execute` and an explicit `sandbox_id`, using the absolute+directory reported by the skill read in place of `<skill dir>`. Keep that ID for+preparing body files and running the helper.+```bash-python3 skills/slack-drafts/scripts/slack_drafts.py create --to '#general' --text 'hello'-python3 skills/slack-drafts/scripts/slack_drafts.py create --to '@jane' --text-file body.txt-python3 skills/slack-drafts/scripts/slack_drafts.py create --to C0123ABCDEF --thread-ts 1712345678.000100 --text '...'-python3 skills/slack-drafts/scripts/slack_drafts.py resolve --to '#general'+python3 "<skill dir>/scripts/slack_drafts.py" create --to '#general' --text 'hello'+python3 "<skill dir>/scripts/slack_drafts.py" create --to '@jane' --text-file body.txt+python3 "<skill dir>/scripts/slack_drafts.py" create --to C0123ABCDEF --thread-ts 1712345678.000100 --text '...'+python3 "<skill dir>/scripts/slack_drafts.py" resolve --to '#general'```- `--to` takes a channel/IM ID (`C…`/`G…`/`D…`), a user ID (`U…`/`W…`), `#channel-name`,diff --git a/skills-seed/taste-skill/SKILL.md b/skills-seed/taste-skill/SKILL.mdindex 866221132..c2f9c79d4 100644--- a/skills-seed/taste-skill/SKILL.md+++ b/skills-seed/taste-skill/SKILL.md@@ -36,7 +36,8 @@ anything externally facing or high-fidelity. Two adjustments for this runtime:You have a real computer, not a hosted design canvas. Build the artifact as files in yourworkspace, verify it locally, and when it should outlive the turn ship it with the-`publish` skill.+`publish` skill. Keep the same explicit `sandbox_id` on file, build, preview,+and publish calls; run commands through `execute`, not `sandbox`.- **`files` actions `write` / `read`** — author and inspect workspace files.- **`execute`** — install deps and run build steps.diff --git a/skills-seed/use-shared-credential/SKILL.md b/skills-seed/use-shared-credential/SKILL.mdindex 5e978eff0..448ac257a 100644--- a/skills-seed/use-shared-credential/SKILL.md+++ b/skills-seed/use-shared-credential/SKILL.md@@ -15,7 +15,7 @@ core stamps the secret onto the outbound call at the wire and returns the responThe **Credentials** inventory groups available credentials by owner. Organization rows marked`proxy` give the host and allowed methods/paths. Select the exact `service_<slug>` handle in-`execute.credentials` for the command making the request. Core supplies+`execute.credentials` for the command making the request, with an explicit `sandbox_id`. Core supplies`AGENT_CREDENTIAL_TOKEN` only to that command; its absence before selection does not meanaccess is missing. Use that token, not `AGENT_API_TOKEN`, for broker requests.diff --git a/src/acl/acl-store.ts b/src/acl/acl-store.tsindex 9ca615673..0a28b660c 100644--- a/src/acl/acl-store.ts+++ b/src/acl/acl-store.ts@@ -3,27 +3,14 @@ import { parseScopeId } from "../types.ts";import { parseRef, refPrefix } from "./resource-ref.ts";import { samePerson } from "../directory/person.ts";import type { ResourceKind } from "./resource-ref.ts";+import type { FileArtifact, FileArtifactRef } from "../files/file-artifact-store.ts";const isFileGrant = (g: Grant) => parseRef(g.ref).kind === "file";-function basename(p: string): string {- const parts = p.split("/");- return parts[parts.length - 1] || p;-}-type ScopeEntitlement = (p: Principal, scope: ScopeId, sessionScopeId: ScopeId, orgScopeId: ScopeId) => boolean;export type ScopeManagement = (principalId: string, scopeId: ScopeId, authoredBy?: string) => Promise<boolean>;-function toHandle(g: Grant): GrantedHandle {- return {- handlePath: `shared/${basename(g.ref)}`,- ownerScopeId: g.ownerScopeId,- ownerPath: g.ref,- permission: g.permission,- };-}-function ownerOf(scopeId: ScopeId): string | null {const { kind, ref } = parseScopeId(scopeId);return kind === "personal" ? ref : null;@@ -78,6 +65,7 @@ export interface AclStore {export interface AclStoreOptions {manages?: ScopeManagement;+ resolveFiles?: (refs: readonly FileArtifactRef[]) => Promise<FileArtifact[]>;}export interface GrantPersistence {@@ -146,6 +134,39 @@ export function createAclStore(persist: GrantPersistence = createMemoryGrantPersistence(),opts: AclStoreOptions = {},): AclStore {+ async function resolveGrantedFiles(grants: readonly Grant[]): Promise<Map<string, FileArtifact>> {+ const refs = grants.filter(isFileGrant).map((g) => ({ id: g.ref, ownerScopeId: g.ownerScopeId }));+ const files = refs.length ? await opts.resolveFiles?.(refs) : [];+ return new Map(files?.filter((file) => file.enabled).map((file) => [file.id, file]));+ }++ async function validateFileGrant(g: Grant): Promise<void> {+ if (!isFileGrant(g)) return;+ const file = (await resolveGrantedFiles([g])).get(g.ref);+ if (!file || file.ownerScopeId !== g.ownerScopeId) {+ throw new Error(+ "file grants require an enabled Files record ID owned by the granting scope; put the file in Files first using POST /v1/files/uploads, then share its ID",+ );+ }+ }++ async function handles(grants: Grant[]): Promise<GrantedHandle[]> {+ const files = await resolveGrantedFiles(grants);+ const result: GrantedHandle[] = [];+ for (const grant of grants) {+ const file = files.get(grant.ref);+ if (file && file.ownerScopeId === grant.ownerScopeId) {+ result.push({+ handlePath: `shared/${file.name}`,+ ownerScopeId: file.ownerScopeId,+ fileId: file.id,+ permission: grant.permission,+ });+ }+ }+ return result;+ }+async function canManage(scopeId: ScopeId, principalId: string, authoredBy?: string): Promise<boolean> {const owner = ownerOf(scopeId);if (owner !== null) return samePerson(principalId, owner);@@ -157,6 +178,7 @@ export function createAclStore(if (!(await canManage(g.ownerScopeId, g.grantedBy, authoredBy))) {throw new Error("only a manager of this scope may grant access (no transitive re-share)");}+ await validateFileGrant(g);await persist.put(g);},async revoke(ownerScopeId, ref, granteeScopeId, revokedBy, authoredBy) {@@ -178,25 +200,26 @@ export function createAclStore() {throw new Error("replacement grants must belong to the selected resource");}+ for (const grant of replacement) await validateFileGrant(grant);return persist.replaceForResourceIfCurrent(ownerScopeId, ref, expected, replacement);},async handlesFor(scopeIds) {const set = new Set(scopeIds);- return (await persist.all()).filter((g) => isFileGrant(g) && set.has(g.granteeScopeId)).map(toHandle);+ return handles((await persist.all()).filter((g) => isFileGrant(g) && set.has(g.granteeScopeId)));},async handlesForAudience(audience, sessionScopeId, orgScopeId, entitled) {if (audience.length === 0) return [];const reaches = (p: Principal, g: Grant) =>entitled(p, g.granteeScopeId, sessionScopeId, orgScopeId) ||entitled(p, g.ownerScopeId, sessionScopeId, orgScopeId);- return (await persist.all())- .filter(+ return handles(+ (await persist.all()).filter((g) =>isFileGrant(g) &&audience.some((p) => entitled(p, g.granteeScopeId, sessionScopeId, orgScopeId)) &&audience.every((p) => reaches(p, g)),- )- .map(toHandle);+ ),+ );},async grantsFor(ownerScopeId, ref) {return (await persist.all()).filter((g) => g.ownerScopeId === ownerScopeId && g.ref === ref);diff --git a/src/acl/postgres-grant-store.ts b/src/acl/postgres-grant-store.tsindex 1d9a32b00..0ea26bd2b 100644--- a/src/acl/postgres-grant-store.ts+++ b/src/acl/postgres-grant-store.ts@@ -48,6 +48,38 @@ export function createPostgresGrantStore(connectionString: string): GrantPersistFOR EACH STATEMENT EXECUTE FUNCTION acl_grants_bump_version()`,],},+ {+ id: "acl/grants/0003-file-ids",+ statements: [+ `DO $migrate$+ BEGIN+ LOCK TABLE acl_grants IN SHARE ROW EXCLUSIVE MODE;+ CREATE TEMP TABLE acl_file_grant_ids ON COMMIT DROP AS+ SELECT g.owner_scope_id, g.path, g.grantee_scope_id, g.permission, g.granted_by, NULL::text AS file_id+ FROM acl_grants g+ WHERE g.path NOT LIKE 'skill:%' AND g.path NOT LIKE 'deployment:%'+ AND g.path NOT LIKE 'cron:%' AND g.path NOT LIKE 'service-cred:%';+ IF to_regclass('file_artifacts') IS NOT NULL THEN+ DELETE FROM acl_file_grant_ids t USING file_artifacts f+ WHERE f.id = t.path AND f.owner_scope_id = t.owner_scope_id AND f.enabled;+ UPDATE acl_file_grant_ids t SET file_id = (+ SELECT f.id FROM file_artifacts f+ WHERE f.owner_scope_id = t.owner_scope_id AND f.path = t.path AND f.enabled+ ORDER BY f.created_at DESC, f.id DESC LIMIT 1+ );+ END IF;+ DELETE FROM acl_grants g USING acl_file_grant_ids t+ WHERE g.owner_scope_id = t.owner_scope_id AND g.path = t.path+ AND g.grantee_scope_id = t.grantee_scope_id AND g.permission = t.permission;+ INSERT INTO acl_grants (owner_scope_id, path, grantee_scope_id, permission, granted_by)+ SELECT owner_scope_id, file_id, grantee_scope_id, permission, granted_by+ FROM acl_file_grant_ids WHERE file_id IS NOT NULL+ ORDER BY owner_scope_id, path, grantee_scope_id, permission+ ON CONFLICT (owner_scope_id, path, grantee_scope_id, permission) DO NOTHING;+ END+ $migrate$`,+ ],+ },]);const { q } = db;let cache: { v: string; grants: readonly Grant[] } | null = null;diff --git a/src/acl/resource-ref.ts b/src/acl/resource-ref.tsindex 190dc568b..b7ba3d273 100644--- a/src/acl/resource-ref.ts+++ b/src/acl/resource-ref.ts@@ -13,7 +13,7 @@ const PREFIX: Record<Exclude<ResourceKind, "file">, string> = {"service-cred": "service-cred:",};-export const fileRef = (path: string): ResourceRef => ({ kind: "file", id: path });+export const fileRef = (id: string): ResourceRef => ({ kind: "file", id });export const skillRef = (id: string): ResourceRef => ({ kind: "skill", id });export const deployRef = (id: string): ResourceRef => ({ kind: "deploy", id });export const cronRef = (id: string): ResourceRef => ({ kind: "cron", id });diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.tsindex 4d24e836e..6262aeb29 100644--- a/src/api/agent-api-catalog.ts+++ b/src/api/agent-api-catalog.ts@@ -456,7 +456,7 @@ const FAMILIES: AgentApiFamily[] = [method: "POST",path: "/v1/reach",summary:- "send a teammate a DM, post to a channel, or post to a group DM RIGHT NOW — `text` plus `recipient`, `channel`, or `participants` (the group DM's other members — the group is opened for you if it doesn't exist yet, so never ask someone to create one), optionally with `files` (workspace-relative paths, attached to the message all-or-nothing). EXTREMELY IMPORTANT: a `channel` post broadcasts to everyone there — pick the narrowest audience that can act; a question or errand for one person goes to their DM (`recipient`), NEVER a public channel, unless the person you're helping explicitly named that channel as the destination or the message genuinely concerns the whole room; pass `threadTs` (the parent message's ts) with a `recipient`/`channel`/`participants` post to reply inside that thread instead of top-level; or react to a message instead of posting with `react:{ts,emoji}` plus a `channel`/`participants`; or retract one of your own messages with `delete:{ts}` (no target = this conversation, or name a `channel`/`participants` to delete elsewhere) — find a message's `ts` via /v1/surface-context; pass `unfurlLinks:false` to suppress Slack previews (no schedule; for later/recurring use /v1/crons)",+ "send a teammate a DM, post to a channel, or post to a group DM RIGHT NOW — `text` plus `recipient`, `channel`, or `participants` (the group DM's other members — the group is opened for you if it doesn't exist yet, so never ask someone to create one), optionally with `files` (workspace paths or {file_id: \"stored Files ID\"}, sent all-or-nothing); `sandbox_id` selects the sandbox for paths, omitted means default, ignored for stored IDs. EXTREMELY IMPORTANT: a `channel` post broadcasts to everyone there — pick the narrowest audience that can act; a question or errand for one person goes to their DM (`recipient`), NEVER a public channel, unless the person you're helping explicitly named that channel as the destination or the message genuinely concerns the whole room; pass `threadTs` (the parent message's ts) with a `recipient`/`channel`/`participants` post to reply inside that thread instead of top-level; or react to a message instead of posting with `react:{ts,emoji}` plus a `channel`/`participants`; or retract one of your own messages with `delete:{ts}` (no target = this conversation, or name a `channel`/`participants` to delete elsewhere) — find a message's `ts` via /v1/surface-context; pass `unfurlLinks:false` to suppress Slack previews (no schedule; for later/recurring use /v1/crons)",},],},diff --git a/src/api/app-helpers.ts b/src/api/app-helpers.tsindex b0f41f057..1a8fdf1f7 100644--- a/src/api/app-helpers.ts+++ b/src/api/app-helpers.ts@@ -366,7 +366,7 @@ export function createAppHelpers(deps: AppDeps, app: App) {const handles = await deps.acl.handlesFor(myScopes);const page = await deps.files.listDocuments(myScopes,- handles.map((h) => ({ ownerScopeId: h.ownerScopeId, path: h.ownerPath })),+ handles.map((h) => ({ ownerScopeId: h.ownerScopeId, id: h.fileId })),{...opts,...(inScope ? { createdInScope: inScope } : {}),@@ -486,7 +486,7 @@ export function createAppHelpers(deps: AppDeps, app: App) {if (r.kind === "skill") return (await deps.skills.get(r.id))?.createdBy;if (r.kind === "cron") return (await deps.crons.get(r.id))?.createdBy;if (r.kind === "deploy") return (await deps.deploy.listDeployments()).find((d) => d.id === r.id)?.createdBy;- if (r.kind === "file") return (await deps.files.resolveByOwnerPaths([{ ownerScopeId, path: r.id }]))[0]?.createdBy;+ if (r.kind === "file") return (await deps.files.resolveByIds([{ ownerScopeId, id: r.id }]))[0]?.createdBy;return undefined;}diff --git a/src/api/app-search.ts b/src/api/app-search.tsindex 751f1a8ef..7c2573530 100644--- a/src/api/app-search.ts+++ b/src/api/app-search.ts@@ -48,8 +48,8 @@ function fileBackend(deps: AppDeps, app: App, helpers: AppHelpers): SearchBackendeps.files.listOwnedByScopes(scopes, { limit: 200 }),deps.acl.handlesFor(scopes),]);- const shared = await deps.files.resolveByOwnerPaths(- handles.map((h) => ({ ownerScopeId: h.ownerScopeId, path: h.ownerPath })),+ const shared = await deps.files.resolveByIds(+ handles.map((h) => ({ ownerScopeId: h.ownerScopeId, id: h.fileId })),);return [...owned.files,diff --git a/src/api/app-sessions.ts b/src/api/app-sessions.tsindex b6df58047..2496cf405 100644--- a/src/api/app-sessions.ts+++ b/src/api/app-sessions.ts@@ -377,7 +377,7 @@ export function createSessionMethods(if (createdInScope !== ownerScopeId) {await deps.acl.grant({ownerScopeId,- ref: path,+ ref: artifact.id,granteeScopeId: createdInScope,permission: "read",grantedBy: principalId,@@ -399,7 +399,7 @@ export function createSessionMethods(const myScopes = await currentResourceScopesForViewer(principalId);let allowed = myScopes.includes(art.ownerScopeId);if (!allowed) {- const grants = await deps.acl.grantsFor(art.ownerScopeId, art.path);+ const grants = await deps.acl.grantsFor(art.ownerScopeId, art.id);allowed = grants.some((g) => myScopes.includes(g.granteeScopeId));}if (!allowed) return null;@@ -1139,7 +1139,7 @@ export function createSessionMethods(if (type === "file") {const f = await deps.files.get(idOrName);return f- ? { id: f.id, ownerScopeId: f.ownerScopeId, createdBy: f.createdBy, grantRef: encodeRef(fileRef(f.path)) }+ ? { id: f.id, ownerScopeId: f.ownerScopeId, createdBy: f.createdBy, grantRef: encodeRef(fileRef(f.id)) }: null;}const d = (await deps.deploy.listDeployments()).find((x) => x.id === idOrName || x.name === idOrName);diff --git a/src/api/control-service.ts b/src/api/control-service.tsindex 28fdcfce6..baac6f4b5 100644--- a/src/api/control-service.ts+++ b/src/api/control-service.ts@@ -934,7 +934,15 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Adasync shareArtifact(req, capability): Promise<ShareArtifactResult> {const permission: Permission = req.permission === "write" ? "write" : "read";const home = await app.getArtifactHome(req.type, req.id);- if (!home) return { ok: false, code: "not_found", message: `no ${req.type} "${req.id}"` };+ if (!home)+ return {+ ok: false,+ code: "not_found",+ message:+ req.type === "file"+ ? `no Files record "${req.id}"; put the file in Files first using POST /v1/files/uploads, then share its ID`+ : `no ${req.type} "${req.id}"`,+ };const target = await resolveArtifactTarget(app, req);if (target.kind === "invalid") return { ok: false, code: "bad_request", message: target.message };diff --git a/src/api/routes/reach.ts b/src/api/routes/reach.tsindex 5085444bd..6c44b3345 100644--- a/src/api/routes/reach.ts+++ b/src/api/routes/reach.ts@@ -2,10 +2,15 @@ import { randomUUID } from "node:crypto";import { sendJson } from "../http.ts";import { isObj } from "./shared.ts";import { type ApiCtx, type Route } from "./route.ts";-import { collectNamedOutbound, MAX_OUTBOUND_FILES, type ArtifactRegistration } from "../../core/attachments.ts";-import { hasParentPathSegment } from "../../sandbox/sandbox.ts";+import { collectNamedOutbound, parseOutboundFiles, type ArtifactRegistration } from "../../core/attachments.ts";+import type { SandboxHandle } from "../../sandbox/sandbox.ts";+import {+ accessConversationSandbox,+ SandboxAccessError,+ type SandboxResource,+} from "../../sandbox/sandbox-resources.ts";import { resolveEnvironmentId } from "../../environments/environment-store.ts";-import { errMessage } from "../../util/errors.ts";+import { errMessage, swallowAs } from "../../util/errors.ts";import { scopeId, type OutgoingAttachment } from "../../types.ts";type ReachBody = {@@ -19,23 +24,9 @@ type ReachBody = {react?: unknown;delete?: unknown;files?: unknown;+ sandbox_id?: unknown;};-function parseFiles(v: unknown): { ok: true; files: string[] } | { ok: false; message: string } {- if (v === undefined) return { ok: true, files: [] };- if (!Array.isArray(v) || v.some((p) => typeof p !== "string" || !p.trim())) {- return {- ok: false,- message: 'files must be an array of workspace-relative path strings, e.g. ["work/report.pdf"]',- };- }- if (v.length > MAX_OUTBOUND_FILES) return { ok: false, message: `too many files (max ${MAX_OUTBOUND_FILES})` };- if ((v as string[]).some(hasParentPathSegment)) {- return { ok: false, message: "files must stay inside the workspace — no .. path segments" };- }- return { ok: true, files: v as string[] };-}-function parseReact(v: unknown): { messageTs: string; emoji: string } | undefined {if (!isObj(v)) return undefined;const ts = (v as { ts?: unknown }).ts;@@ -89,9 +80,16 @@ async function reachNow(ctx: ApiCtx): Promise<void> {message: "react and delete are separate actions — send one at a time",});}- const filesParsed = parseFiles(b.files);+ const filesParsed = parseOutboundFiles(b.files);if (!filesParsed.ok) return sendJson(res, 400, { error: "bad_request", message: filesParsed.message });const files = filesParsed.files;+ let requestedSandboxId: string | undefined;+ if (b.sandbox_id !== undefined) {+ if (typeof b.sandbox_id !== "string" || !b.sandbox_id.trim()) {+ return sendJson(res, 400, { error: "bad_request", message: "sandbox_id must be a sandbox id string" });+ }+ if (files.some((f) => typeof f === "string")) requestedSandboxId = b.sandbox_id.trim();+ }if (files.length && (react || del)) {return sendJson(res, 400, {error: "bad_request",@@ -122,7 +120,8 @@ async function reachNow(ctx: ApiCtx): Promise<void> {let attachments: OutgoingAttachment[] | undefined;if (files.length) {const { sandbox, blobTransfer } = deps;- if (!sandbox || !blobTransfer) {+ const needsSandbox = files.some((f) => typeof f === "string");+ if (!blobTransfer || (needsSandbox && !sandbox) || (requestedSandboxId && !deps.sandboxResources)) {return sendJson(res, 501, {error: "not_configured",message: "file attachments aren't available on this server — the sandbox/blob store isn't wired",@@ -166,9 +165,34 @@ async function reachNow(ctx: ApiCtx): Promise<void> {),}: undefined;- const handle = await sandbox.provision([{ scopeId: envScope, mountPath: "", mode: "rw" }]);+ let resource: SandboxResource | undefined;+ if (requestedSandboxId) {+ try {+ resource = await accessConversationSandbox(+ deps.sandboxResources,+ capability.actorId,+ requestedSandboxId,+ (scope) => scope === capability.scopeId || scope === envScope,+ );+ } catch (e) {+ if (!(e instanceof SandboxAccessError)) throw e;+ return sendJson(res, 403, {+ error: "forbidden",+ message: "sandbox_id isn't a computer this conversation can read files from",+ });+ }+ }+ let provisioned: Promise<SandboxHandle> | undefined;+ const handle = () =>+ (provisioned ??= resource+ ? sandbox!.provision([{ scopeId: resource.ownerScopeId, mountPath: "", mode: "rw" }], {+ sandboxId: resource.id,+ })+ : sandbox!.provision([{ scopeId: envScope, mountPath: "", mode: "rw" }]));try {- const r = await collectNamedOutbound(sandbox, handle, files, blobTransfer, register);+ const r = await collectNamedOutbound(sandbox, handle, files, blobTransfer, register, [], (id) =>+ app.openFileForViewer(id, capability.actorId),+ );const bad = [...r.missing.map((p) => `${p} (not found)`),...r.empty.map((p) => `${p} (empty)`),@@ -177,12 +201,16 @@ async function reachNow(ctx: ApiCtx): Promise<void> {if (bad.length) {return sendJson(res, 400, {error: "attach_failed",- message: `couldn't attach: ${bad.join(", ")} — nothing was sent; fix the path(s) and retry`,+ message: `couldn't attach: ${bad.join(", ")} — nothing was sent; fix the file(s) and retry`,});}attachments = r.attachments;} finally {- await sandbox.teardown(handle, { keepWarm: true }).catch(() => {});+ if (provisioned) {+ const used = await provisioned.catch(() => undefined);+ if (used)+ await sandbox!.teardown(used, { keepWarm: true }).catch(swallowAs("reach: sandbox teardown", undefined));+ }}}const result = await app.reachNow({diff --git a/src/core/attachments.ts b/src/core/attachments.tsindex 634942232..41568c7f4 100644--- a/src/core/attachments.ts+++ b/src/core/attachments.ts@@ -1,3 +1,4 @@+import type { Readable } from "node:stream";import { basename } from "node:path";import { randomUUID } from "node:crypto";import type {@@ -9,9 +10,13 @@ import type {SessionEntry,} from "../types.ts";import { hasParentPathSegment, type Sandbox, type SandboxHandle } from "../sandbox/sandbox.ts";-import { MAX_BLOB_BYTES, collectBlob, type BlobTransferStore } from "../persistence/blob-transfer.ts";+import {+ MAX_BLOB_BYTES,+ BlobTooLargeError,+ collectBlob,+ type BlobTransferStore,+} from "../persistence/blob-transfer.ts";import { fileArtifactId, type FileArtifactStore, type FileDirection } from "../files/file-artifact-store.ts";-import { parseRef } from "../acl/resource-ref.ts";import { swallowAs } from "../util/errors.ts";import { hashId } from "../util/crypto.ts";import type { SecurityScreenVerdict } from "../security/security-posture.ts";@@ -210,7 +215,7 @@ export function inboundManifest(metas: AttachmentMeta[], inboxDir = INBOX_DIR, u(m) =>`- ${inboxDir}/${m.name} (${m.mimetype}, ${m.sizeBytes} bytes)${m.author ? ` — shared by ${m.author}` : ""}${unstaged?.has(m.name)- ? ` — saved as file ${m.artifactId}, not yet on a computer (no default sandbox); if you need it on disk, select or create a sandbox with set_default, then download GET $AGENT_API_URL/v1/files/${m.artifactId}/content (header x-agent-capability: $AGENT_API_TOKEN) to a path you choose`+ ? ` — saved as file ${m.artifactId}, not yet on a computer (no default sandbox); send it directly with {file_id: "${m.artifactId}"}; if you need it on disk, choose a sandbox_id for execute and download GET $AGENT_API_URL/v1/files/${m.artifactId}/content (header x-agent-capability: $AGENT_API_TOKEN) to a path you choose`: ""}`,)@@ -262,15 +267,10 @@ export function inboundIssueList(opts: {return issues;}-function isFileHandle(h: GrantedHandle): boolean {- return parseRef(h.ownerPath).kind === "file";-}-export function sharedManifest(handles: readonly GrantedHandle[]): string {const seen = new Set<string>();const lines: string[] = [];for (const h of handles) {- if (!isFileHandle(h)) continue;if (seen.has(h.handlePath)) continue;seen.add(h.handlePath);lines.push(`- ${h.handlePath}${h.permission === "write" ? " (writable)" : ""}`);@@ -283,10 +283,7 @@ export function sharedManifest(handles: readonly GrantedHandle[]): string {shown.push(`…and ${omitted} more (read shared/<name> to fetch)`);}const noun = total === 1 ? "file" : "files";- return (- `${total} ${noun} shared with you — read a path below to fetch that file on demand, ` +- `then attach it to a message to pass it on (name its path in the surface \`post\` action's \`files\`):\n${shown.join("\n")}`- );+ return `${total} ${noun} shared with you — read a path below to fetch that file on demand:\n${shown.join("\n")}`;}export function sharedFilesSystemSection(handles: readonly GrantedHandle[]): string {@@ -418,13 +415,50 @@ export function legacyDeliveryNoteManifest(text: string): string | null {return m ? m[1]! : null;}+export type OutboundFile = string | { file_id: string };++export type OpenStoredFile = (id: string) => Promise<{+ name: string;+ mimetype: string;+ sizeBytes: number;+ stream: Readable;+} | null>;++export function parseOutboundFiles(+ value: unknown,+): { ok: true; files: OutboundFile[] } | { ok: false; message: string } {+ if (value === undefined) return { ok: true, files: [] };+ if (+ !Array.isArray(value) ||+ value.some((file) =>+ typeof file === "string"+ ? !file.trim()+ : !file ||+ typeof file !== "object" ||+ Array.isArray(file) ||+ Object.keys(file).length !== 1 ||+ typeof file.file_id !== "string" ||+ !file.file_id.trim(),+ )+ )+ return { ok: false, message: 'files must be workspace path strings or {file_id: "stored Files ID"} objects' };+ if (value.length > MAX_OUTBOUND_FILES) return { ok: false, message: `too many files (max ${MAX_OUTBOUND_FILES})` };+ if (value.some((file) => typeof file === "string" && hasParentPathSegment(file)))+ return { ok: false, message: "files must stay inside the workspace — no .. path segments" };+ return {+ ok: true,+ files: value.map((file) => (typeof file === "string" ? file.trim() : { file_id: file.file_id.trim() })),+ };+}+export async function collectNamedOutbound(- sandbox: Sandbox,- handle: SandboxHandle,- paths: readonly string[],+ sandbox: Sandbox | undefined,+ handle: SandboxHandle | (() => Promise<SandboxHandle>),+ paths: readonly OutboundFile[],transfer: BlobTransferStore,register?: ArtifactRegistration,reservedNames: readonly string[] = [],+ openStored?: OpenStoredFile,): Promise<{attachments: OutgoingAttachment[];missing: string[];@@ -432,9 +466,8 @@ export async function collectNamedOutbound(oversized: string[];createdArtifactIds: Set<string>;}> {- const invalid = paths.filter(hasParentPathSegment);- if (invalid.length)- return { attachments: [], missing: invalid, empty: [], oversized: [], createdArtifactIds: new Set() };+ const parsed = parseOutboundFiles(paths);+ if (!parsed.ok) throw new Error(parsed.message);const attachments: OutgoingAttachment[] = [];const missing: string[] = [];const empty: string[] = [];@@ -442,56 +475,70 @@ export async function collectNamedOutbound(const usedNames = new Set<string>(reservedNames);const doomed = () => missing.length > 0 || empty.length > 0 || oversized.length > 0;const createdArtifactIds = new Set<string>();- let i = 0;- for (const p of paths) {- const bytes = await sandbox.readFileBytes(handle, p);- if (bytes === null) {- missing.push(p);- continue;- }- const name = uniqueName(safeAttachmentName(basename(p)), usedNames);- usedNames.add(name);- if (bytes.length === 0) {- empty.push(p);- continue;- }- if (bytes.length > MAX_ATTACHMENT_BYTES) {- oversized.push(p);- continue;- }- if (doomed()) continue;- const mimetype = mimeFromName(name);- const { blobId } = await transfer.put(bytes);- const artifact = register ? await registerArtifact(register, "out", i, name, mimetype, bytes) : undefined;- if (artifact?.created) createdArtifactIds.add(artifact.id);- i += 1;- attachments.push({- name,- mimetype,- sizeBytes: bytes.length,- blobId,- ...(artifact ? { artifactId: artifact.id, artifactViewerId: register!.createdBy } : {}),- });- }- if (doomed() && attachments.length) {- await Promise.all(- attachments.map(async (a) => {- await transfer.delete(a.blobId).catch(swallowAs("attachments: rollback blob delete", undefined));- if (register && a.artifactId && createdArtifactIds.has(a.artifactId)) {- await register.store.delete(a.artifactId).catch((e) => {- try {- register.onError?.(e);- } catch (err) {- swallowAs("attachments: rollback onError", undefined)(err);- }- });- }- }),- );+ const rollback = async () => {+ await Promise.all(attachments.map((a) => discardOutbound(a, transfer, register, createdArtifactIds)));attachments.length = 0;createdArtifactIds.clear();+ };+ let target: SandboxHandle | undefined;+ try {+ for (const [i, file] of parsed.files.entries()) {+ const storedId = typeof file === "string" ? undefined : file.file_id;+ const label = typeof file === "string" ? file : file.file_id;+ let bytes: Uint8Array | undefined;+ let stored: Awaited<ReturnType<OpenStoredFile>> = null;+ if (typeof file === "string") {+ if (!sandbox) throw new Error("sandbox file access is not available");+ target ??= typeof handle === "function" ? await handle() : handle;+ bytes = (await sandbox.readFileBytes(target, file)) ?? undefined;+ } else {+ stored = (await openStored?.(file.file_id)) ?? null;+ }+ if (!bytes && !stored) {+ missing.push(label);+ continue;+ }+ const sizeBytes = stored?.sizeBytes ?? bytes!.length;+ if (sizeBytes === 0) empty.push(label);+ if (sizeBytes > MAX_ATTACHMENT_BYTES) oversized.push(label);+ if (doomed()) {+ stored?.stream.destroy();+ continue;+ }+ const name = uniqueName(safeAttachmentName(stored?.name ?? label), usedNames);+ usedNames.add(name);+ const mimetype = stored?.mimetype || mimeFromName(name);+ let blob;+ try {+ blob = await transfer.put(stored?.stream ?? bytes!, { maxBytes: MAX_ATTACHMENT_BYTES });+ } catch (error) {+ if (!(error instanceof BlobTooLargeError)) throw error;+ oversized.push(label);+ continue;+ } finally {+ stored?.stream.destroy();+ }+ const attachment: OutgoingAttachment = { name, mimetype, sizeBytes: blob.sizeBytes, blobId: blob.blobId };+ attachments.push(attachment);+ if (blob.sizeBytes === 0) {+ empty.push(label);+ continue;+ }+ let artifact;+ if (storedId) artifact = { id: storedId, created: false };+ else if (register) artifact = await registerArtifact(register, "out", i, name, mimetype, bytes!);+ if (artifact?.created) createdArtifactIds.add(artifact.id);+ if (artifact) {+ attachment.artifactId = artifact.id;+ if (register) attachment.artifactViewerId = register.createdBy;+ }+ }+ if (doomed()) await rollback();+ return { attachments, missing, empty, oversized, createdArtifactIds };+ } catch (error) {+ await rollback();+ throw error;}- return { attachments, missing, empty, oversized, createdArtifactIds };}export async function discardOutbound(diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.tsindex 787760242..45f77fdef 100644--- a/src/core/orchestrator.ts+++ b/src/core/orchestrator.ts@@ -137,7 +137,6 @@ import { createTranscriptSource } from "../harness/tape-projection.ts";import { defaultPublishAudience } from "../resolution/publish-audience.ts";import {INBOX_DIR,- SHARED_DIR,TURN_FILES_DIR,environmentNote,fileEventPayload,@@ -1114,7 +1113,6 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {memoryPolicy,useMemory,memory: deps.memory,- workspace: deps.workspace,files: deps.files,skills: deps.skills,auditLog: deps.auditLog,@@ -1309,7 +1307,6 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {const turnSessionDir = `${TURN_FILES_DIR}/${hashId([conversation.threadRef], 24)}`;const turnFilesDir = `${turnSessionDir}/${transferId}`;const turnInboxDir = `${turnFilesDir}/${INBOX_DIR}`;- const turnSharedDir = `${turnFilesDir}/${SHARED_DIR}`;if (!external && deps.deploymentLayer?.hints.length) {systemPrompt += `\n\n## Deployment tool hints\n${deps.deploymentLayer.hints.map((hint) => `- ${hint}`).join("\n")}`;@@ -2598,11 +2595,6 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {}): undefined;- const snapshotExcludeDirs = [- ...resolution.layers.filter((l) => l.mode === "ro" && l.mountPath).map((l) => l.mountPath),- TURN_FILES_DIR,- ];-const spine: SpineState = {surfaceOutboundCount: 0,crossConversationPosts: 0,@@ -2641,11 +2633,11 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {seed: input.runId ?? `${session.id}:${Date.now()}`,...(fileGrantees.length? {- onRegistered: async ({ ownerScopeId, path }) => {+ onRegistered: async ({ ownerScopeId, id }) => {for (const granteeScopeId of fileGrantees) {await deps.acl.grant({ownerScopeId,- ref: path,+ ref: id,granteeScopeId,permission: "read",grantedBy: actor.id,@@ -2701,6 +2693,34 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {.then(() => deps.turnStream?.markSurfacePosted(runId)).catch(swallowAs("orchestrator: first-block ack", undefined));};+ let readableHandles: Awaited<ReturnType<typeof deps.acl.handlesForAudience>> | undefined;+ const mayReadArtifact = async (artifact: FileArtifact, fresh = false): Promise<boolean> => {+ if (+ conversation.audience.every((principal) =>+ principalEntitledToScope(principal, artifact.ownerScopeId, scopeId, resolution.orgScopeId),+ )+ )+ return true;+ let handles = fresh ? undefined : readableHandles;+ handles ??= await deps.acl.handlesForAudience(+ conversation.audience,+ scopeId,+ resolution.orgScopeId,+ principalEntitledToScope,+ );+ if (!fresh) readableHandles = handles;+ return handles.some(+ (handle) => handle.ownerScopeId === artifact.ownerScopeId && handle.fileId === artifact.id,+ );+ };+ const provisionOutbound = (sandboxId?: string) =>+ sandboxId !== undefined ? provisionResource(sandboxId) : provision();+ const openStoredOutbound = async (id: string) => {+ const artifact = await deps.files.get(id);+ if (!artifact || !(await mayReadArtifact(artifact, true))) return null;+ const opened = await deps.files.open(id);+ return opened ? { ...artifact, sizeBytes: opened.sizeBytes, stream: opened.stream } : null;+ };const surfaceToolDeps = createSurfaceToolDeps({deps,input,@@ -2712,14 +2732,16 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {defaultDestination,blobTransfer,fileRegistration,- provision,+ provision: provisionOutbound,+ openStored: openStoredOutbound,postProvenance,postKeys,spine,});const attachStaging = createAttachStaging({sandbox: deps.sandbox,- provision,+ provision: provisionOutbound,+ openStored: openStoredOutbound,blobTransfer,fileRegistration,});@@ -2755,7 +2777,6 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {authorizeCommand,grantedHandles: resolution.grantedHandles,context,- sharedMaterializeDir: turnSharedDir,workspace: deps.workspace,deploy: deps.deploy,acl: deps.acl,@@ -2846,9 +2867,6 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {attempt: input.attempt ?? 1,...(backgroundBroker ? { backgroundBroker } : {}),...(monitorBroker ? { monitorBroker } : {}),- ...(scopeProfile.writablePersistence === "resident_disk"- ? { persistWritesToStore: { excludeDirs: snapshotExcludeDirs } }- : {}),onGapWork: (work) => {if (work.phase === "exec") {execMs += Math.max(0, work.end - work.start);@@ -2981,24 +2999,6 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {await deps.harness.turns.resetSession?.(session.id);}const visibleHistory = filterHistory(forModelContext(rawEntries, { includeSecurityTainted: false }));- let readableHandles: Awaited<ReturnType<typeof deps.acl.handlesForAudience>> | undefined;- const mayReadArtifact = async (artifact: FileArtifact): Promise<boolean> => {- if (- conversation.audience.every((principal) =>- principalEntitledToScope(principal, artifact.ownerScopeId, scopeId, resolution.orgScopeId),- )- )- return true;- readableHandles ??= await deps.acl.handlesForAudience(- conversation.audience,- scopeId,- resolution.orgScopeId,- principalEntitledToScope,- );- return readableHandles.some(- (handle) => handle.ownerScopeId === artifact.ownerScopeId && handle.ownerPath === artifact.path,- );- };const rehydrateTape = (messages: readonly unknown[]) => {return rehydrateFoldImages(messages,diff --git a/src/core/orchestrator/attach-tool.ts b/src/core/orchestrator/attach-tool.tsindex 306a9b9d3..c211f9426 100644--- a/src/core/orchestrator/attach-tool.ts+++ b/src/core/orchestrator/attach-tool.ts@@ -1,9 +1,12 @@import type { OutgoingAttachment } from "../../types.ts";-import { hasParentPathSegment, type Sandbox, type SandboxHandle } from "../../sandbox/sandbox.ts";+import { type Sandbox, type SandboxHandle } from "../../sandbox/sandbox.ts";import type { BlobTransferStore } from "../../persistence/blob-transfer.ts";import type { AttachFiles, AttachResult } from "../../tools/primitives.ts";import {collectNamedOutbound,+ parseOutboundFiles,+ type OutboundFile,+ type OpenStoredFile,discardOutbound,MAX_OUTBOUND_FILES,type ArtifactRegistration,@@ -11,9 +14,10 @@ import {export interface AttachToolsContext {sandbox: Sandbox;- provision: () => Promise<SandboxHandle>;+ provision: (sandboxId?: string) => Promise<SandboxHandle>;blobTransfer: BlobTransferStore;fileRegistration: ArtifactRegistration;+ openStored?: OpenStoredFile;}export interface StagedAttachments {@@ -29,28 +33,40 @@ interface StagedEntry {export function createAttachStaging(ctx: AttachToolsContext): StagedAttachments {const staged = new Map<string, StagedEntry>();let calls = 0;- const attach = async (files: readonly string[]): Promise<AttachResult> => {- const paths = [...new Set(files.map((f) => String(f ?? "").trim()).filter(Boolean))];- if (!paths.length) return { ok: false, message: "attach needs at least one workspace file path" };- const invalid = paths.filter(hasParentPathSegment);- if (invalid.length)- return {- ok: false,- message: `couldn't attach: ${invalid.map((p) => `${p} (not found)`).join(", ")} — nothing was staged; fix the path(s) and retry`,- };- const resulting = new Set([...staged.keys(), ...paths]);+ const attach = async (files: readonly OutboundFile[], sandboxId?: string): Promise<AttachResult> => {+ const parsed = parseOutboundFiles(files);+ if (!parsed.ok) return { ok: false, message: parsed.message };+ const keyed = new Map(+ parsed.files.map((file) => [+ typeof file === "string"+ ? JSON.stringify(["path", sandboxId ?? null, file])+ : JSON.stringify(["file", file.file_id]),+ file,+ ]),+ );+ const paths = [...keyed.values()];+ const keys = [...keyed.keys()];+ if (!paths.length) return { ok: false, message: "attach needs at least one file" };+ const resulting = new Set([...staged.keys(), ...keys]);if (resulting.size > MAX_OUTBOUND_FILES)return {ok: false,message: `too many files — a reply carries at most ${MAX_OUTBOUND_FILES}, and ${staged.size} ${staged.size === 1 ? "is" : "are"} already staged`,};- const handle = await ctx.provision();const register = { ...ctx.fileRegistration, seed: `${ctx.fileRegistration.seed}:attach:${calls}` };calls += 1;const keptNames = [...staged.entries()]- .filter(([path]) => !paths.includes(path))+ .filter(([path]) => !keys.includes(path)).map(([, entry]) => entry.attachment.name);- const r = await collectNamedOutbound(ctx.sandbox, handle, paths, ctx.blobTransfer, register, keptNames);+ const r = await collectNamedOutbound(+ ctx.sandbox,+ () => ctx.provision(sandboxId),+ paths,+ ctx.blobTransfer,+ register,+ keptNames,+ ctx.openStored,+ );const bad = [...r.missing.map((p) => `${p} (not found)`),...r.empty.map((p) => `${p} (empty)`),@@ -62,10 +78,20 @@ export function createAttachStaging(ctx: AttachToolsContext): StagedAttachmentsmessage: `couldn't attach: ${bad.join(", ")} — nothing was staged; fix the path(s) and retry`,};for (const [i, attachment] of r.attachments.entries()) {- const path = paths[i]!;+ const path = keys[i]!;const superseded = staged.get(path);staged.set(path, { attachment, created: r.createdArtifactIds });- if (superseded) await discardOutbound(superseded.attachment, ctx.blobTransfer, register, superseded.created);+ if (superseded) {+ const referenced = [...staged.values()].some(+ (entry) => entry.attachment.artifactId === superseded.attachment.artifactId,+ );+ await discardOutbound(+ superseded.attachment,+ ctx.blobTransfer,+ register,+ referenced ? undefined : superseded.created,+ );+ }}return {ok: true,diff --git a/src/core/orchestrator/sandboxes.ts b/src/core/orchestrator/sandboxes.tsindex bf20c5a03..188775ad1 100644--- a/src/core/orchestrator/sandboxes.ts+++ b/src/core/orchestrator/sandboxes.ts@@ -5,7 +5,7 @@ import { intersectEgressPolicies } from "../../resolution/egress-policy.ts";import { isOpenScopeMember } from "../../resolution/sharing-access.ts";import type { GapPhase } from "../../sessions/session-store.ts";import { type SandboxHandle, supportsProcessSessions, SandboxProvisionCleanupError } from "../../sandbox/sandbox.ts";-import type { SandboxAccessPlan } from "../../sandbox/sandbox-resources.ts";+import { accessConversationSandbox, type SandboxAccessPlan } from "../../sandbox/sandbox-resources.ts";import { reconcileProcesses } from "../../processes/reconcile.ts";import { leaseLapsed } from "../../runs/run-store.ts";import { finishProcessCredentials } from "../../credentials/execute-files.ts";@@ -264,8 +264,8 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {const skillsRoot = (r: SkillResolution) =>`${SKILLS_ROOT}/${turnSessionDir.split("/").at(-1)}/${hashId([r.skill!.id, String(r.skill!.version)], 16)}`;const laidTrees = new Set<string>();- const materializeSkillTree = async (handle: SandboxHandle, r: SkillResolution, sandboxId?: string): Promise<void> => {- const treeKey = `${sandboxId ?? "default"}:${skillDir(skillsRoot(r), r)}`;+ const materializeSkillTree = async (handle: SandboxHandle, r: SkillResolution): Promise<void> => {+ const treeKey = `${handle.resourceId ?? handle.id}:${skillDir(skillsRoot(r), r)}`;if (laidTrees.has(treeKey)) return;const start = Date.now();try {@@ -316,10 +316,10 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {? renderSkillBody(resolution, root): rehomeSkillPaths(resolution, asset!, root ?? skillsRoot(resolution));if (!shipsFiles) return { content: render(), sourceScopeId: resolution.skill.scopeId };- const access = sandboxId ? await accessResource(sandboxId) : undefined;+ const access = sandboxId !== undefined ? await accessResource(sandboxId) : undefined;if (access?.crossScope) return { content: render(skillsRoot(resolution)), sourceScopeId: resolution.skill.scopeId };const handle = access ? await provisionResource(access) : await provision();- await materializeSkillTree(handle, resolution, sandboxId);+ await materializeSkillTree(handle, resolution);const root = `${handle.rootDir}/${skillsRoot(resolution)}`;const pack = packRoot(root, resolution);return {@@ -351,9 +351,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {return true;};const accessResource = async (id: string): Promise<SandboxAccessPlan> => {- const resource = await deps.sandboxResources?.access(actor.id, id);- if (!resource || !(await canUseSandboxScope(resource.ownerScopeId)))- throw new Error("sandbox access is no longer authorized in this conversation");+ const resource = await accessConversationSandbox(deps.sandboxResources, actor.id, id, canUseSandboxScope);const crossScope = resource.ownerScopeId !== writableScopeId && resource.ownerScopeId !== scopeId;if (!crossScope) return { resource, crossScope: false, egress: resolution.egress, commandPolicy: null };await deps.config!.refreshSecurity([resource.ownerScopeId]);diff --git a/src/core/orchestrator/surface-tools.ts b/src/core/orchestrator/surface-tools.tsindex c04a3d1d8..f1312dd26 100644--- a/src/core/orchestrator/surface-tools.ts+++ b/src/core/orchestrator/surface-tools.ts@@ -16,7 +16,7 @@ import {withDelete,type ReachResolution,} from "../../reach/reach.ts";-import { hasParentPathSegment, type SandboxHandle } from "../../sandbox/sandbox.ts";+import { type SandboxHandle } from "../../sandbox/sandbox.ts";import type {SurfaceToolDeps,SurfacePostResult,@@ -27,7 +27,13 @@ import type {SurfaceSearchResult,} from "../../tools/primitives.ts";import { collectBlob, MAX_BLOB_BYTES, type BlobTransferStore } from "../../persistence/blob-transfer.ts";-import { collectNamedOutbound, type ArtifactRegistration } from "../attachments.ts";+import {+ collectNamedOutbound,+ parseOutboundFiles,+ type OutboundFile,+ type OpenStoredFile,+ type ArtifactRegistration,+} from "../attachments.ts";import { parseBotLedger, type BotPolicy, type ChannelPolicy } from "../../surface-cache/channel-policy-store.ts";import { isoFromTs } from "../../util/message-tag.ts";import { errMessage } from "../../util/errors.ts";@@ -57,7 +63,8 @@ export interface SurfaceToolsContext {defaultDestination: Destination | undefined;blobTransfer: BlobTransferStore;fileRegistration: ArtifactRegistration;- provision: () => Promise<SandboxHandle>;+ openStored?: OpenStoredFile;+ provision: (sandboxId?: string) => Promise<SandboxHandle>;postProvenance: (deliveryKey: string) => DeliveryProvenance;postKeys: TurnPostKeys;spine: SpineState;@@ -191,17 +198,21 @@ export function createSurfaceToolDeps(ctx: SurfaceToolsContext): SurfaceToolDepsreturn coverageSince;};const resolveFiles = async (- files?: readonly string[],+ files?: readonly OutboundFile[],+ sandboxId?: string,): Promise<{ ok: true; attachments?: OutgoingAttachment[] } | { ok: false; message: string }> => {if (!files?.length) return { ok: true };- const invalid = files.filter(hasParentPathSegment);- if (invalid.length)- return {- ok: false,- message: `couldn't attach: ${invalid.map((p) => `${p} (not found)`).join(", ")} — nothing was sent; fix the path(s) and retry`,- };- const handle = await provision();- const r = await collectNamedOutbound(deps.sandbox, handle, files, blobTransfer, fileRegistration);+ const parsed = parseOutboundFiles(files);+ if (!parsed.ok) return parsed;+ const r = await collectNamedOutbound(+ deps.sandbox,+ () => provision(sandboxId),+ files,+ blobTransfer,+ fileRegistration,+ [],+ ctx.openStored,+ );const bad = [...r.missing.map((p) => `${p} (not found)`),...r.empty.map((p) => `${p} (empty)`),@@ -212,7 +223,7 @@ export function createSurfaceToolDeps(ctx: SurfaceToolsContext): SurfaceToolDepsreturn { ok: true, attachments: r.attachments };};return {- post: async (postText, opts, files) => {+ post: async (postText, opts, files, sandboxId) => {const seq = postKeys.take();let destination = currentDestination;if (opts?.ts && destination.type !== "principal") {@@ -220,7 +231,7 @@ export function createSurfaceToolDeps(ctx: SurfaceToolsContext): SurfaceToolDeps} else if (opts?.broadcast && destination.type !== "principal" && conversation.channelRef) {destination = { ...destination, target: conversation.channelRef };}- const f = await resolveFiles(files);+ const f = await resolveFiles(files, sandboxId);if (!f.ok) return { ok: false, message: f.message };const footer = buildDebugFooter();const run = input.runId ? await deps.runs?.get(input.runId) : null;@@ -237,7 +248,7 @@ export function createSurfaceToolDeps(ctx: SurfaceToolsContext): SurfaceToolDepsconst sent = await enqueue(projectedDestination, postText, seq, f.attachments);return sent.ok && f.attachments?.length ? { ...sent, attachments: postedFileMetas(f.attachments) } : sent;},- reach: async (postText, target, files) => {+ reach: async (postText, target, files, sandboxId) => {const seq = postKeys.take();if (spine.crossConversationPosts >= 5) return { ok: false, message: "outbound limit reached for this turn" };const selectors = [@@ -247,7 +258,7 @@ export function createSurfaceToolDeps(ctx: SurfaceToolsContext): SurfaceToolDeps].filter(Boolean).length;if (selectors !== 1)return { ok: false, message: "reach needs exactly one of: channel, recipient, or participants." };- const f = await resolveFiles(files);+ const f = await resolveFiles(files, sandboxId);if (!f.ok) return { ok: false, message: f.message };const sending = postText.trim().length > 0 || (f.attachments?.length ?? 0) > 0;const d = await resolveDestination(target, { mayOpenGroup: sending });diff --git a/src/files/file-artifact-store.ts b/src/files/file-artifact-store.tsindex a2b5972b0..98564ad7d 100644--- a/src/files/file-artifact-store.ts+++ b/src/files/file-artifact-store.ts@@ -64,7 +64,7 @@ export interface ListOwnedOptions {nameQuery?: string;}-export type FileArtifactRef = Pick<FileArtifact, "ownerScopeId" | "path">;+export type FileArtifactRef = Pick<FileArtifact, "ownerScopeId" | "id">;export class FileArtifactDeletedError extends Error {constructor() {super("file was deleted");@@ -88,7 +88,7 @@ export interface FileArtifactStore {opts?: ListOwnedOptions,): Promise<FilePage>;- resolveByOwnerPaths(refs: readonly FileArtifactRef[]): Promise<FileArtifact[]>;+ resolveByIds(refs: readonly FileArtifactRef[]): Promise<FileArtifact[]>;setEnabled(id: string, enabled: boolean): Promise<void>;@@ -99,20 +99,10 @@ export function fileArtifactId(seed: string, direction: FileDirection, batchIndereturn createHash("sha256").update(`${seed}:${direction}:${batchIndex}`).digest("hex").slice(0, 32);}-/**- * The artifact store's own path namespace. Files that exist only as artifacts- * (viewer uploads, inbound attachments) live at artifacts/<id>/<name>;- * workspace-backed files never do. The namespace is what lets a shared-handle- * read pick the right backing store without a precedence rule.- */export function artifactPath(id: string, name: string): string {return `artifacts/${id}/${name}`;}-export function isArtifactPath(path: string): boolean {- return /^artifacts\/[0-9a-f]{32}\//.test(path);-}-const DEFAULT_LIMIT = 50;const MAX_LIMIT = 200;@@ -149,7 +139,7 @@ export function createMemoryFileArtifactStore(byteStore: DurableByteStore): FilesharedRefs?: readonly FileArtifactRef[],): Promise<FilePage> {const owners = new Set(scopes);- const shared = new Set(sharedRefs?.map((r) => JSON.stringify([r.ownerScopeId, r.path])));+ const shared = new Set(sharedRefs?.map((r) => JSON.stringify([r.ownerScopeId, r.id])));const limit = clampLimit(opts?.limit);const cursor = opts?.cursor ? decodeCursor(opts.cursor) : null;const nameQuery = opts?.nameQuery?.toLowerCase();@@ -157,7 +147,7 @@ export function createMemoryFileArtifactStore(byteStore: DurableByteStore): File.filter((r) =>(owners.has(r.ownerScopeId) && (opts?.includeDisabled || r.enabled)) ||- (r.enabled && shared.has(JSON.stringify([r.ownerScopeId, r.path]))),+ (r.enabled && shared.has(JSON.stringify([r.ownerScopeId, r.id]))),).filter((r) => opts?.createdInScope == null || r.createdInScope === opts.createdInScope).filter((r) => nameQuery == null || r.name.toLowerCase().includes(nameQuery));@@ -246,10 +236,10 @@ export function createMemoryFileArtifactStore(byteStore: DurableByteStore): FilelistDocuments: (scopes, sharedRefs, opts) => listFiles(scopes, opts, sharedRefs),- async resolveByOwnerPaths(refs) {+ async resolveByIds(refs) {if (refs.length === 0) return [];- const want = new Set(refs.map((r) => `${r.ownerScopeId}\0${r.path}`));- return [...rows.values()].filter((r) => r.enabled && want.has(`${r.ownerScopeId}\0${r.path}`));+ const want = new Set(refs.map((r) => `${r.ownerScopeId}\0${r.id}`));+ return [...rows.values()].filter((r) => r.enabled && want.has(`${r.ownerScopeId}\0${r.id}`));},async setEnabled(id, enabled) {diff --git a/src/files/postgres-file-artifact-store.ts b/src/files/postgres-file-artifact-store.tsindex d717887db..88417d28e 100644--- a/src/files/postgres-file-artifact-store.ts+++ b/src/files/postgres-file-artifact-store.ts@@ -95,9 +95,9 @@ export function createPostgresFileArtifactStore(if (sharedRefs !== undefined) {params.push(sharedRefs.map((r) => r.ownerScopeId),- sharedRefs.map((r) => r.path),+ sharedRefs.map((r) => r.id),);- access = `(${access} OR (enabled = TRUE AND (owner_scope_id, path) IN (SELECT * FROM unnest($2::text[], $3::text[]))))`;+ access = `(${access} OR (enabled = TRUE AND (owner_scope_id, id) IN (SELECT * FROM unnest($2::text[], $3::text[]))))`;}const filters = [access];if (!opts?.includeDisabled) filters.push("enabled = TRUE");@@ -209,15 +209,15 @@ export function createPostgresFileArtifactStore(listDocuments: (scopes, sharedRefs, opts) => listFiles(scopes, opts, sharedRefs),- async resolveByOwnerPaths(refs) {+ async resolveByIds(refs) {if (refs.length === 0) return [];const owners = refs.map((r) => r.ownerScopeId as string);- const paths = refs.map((r) => r.path);+ const ids = refs.map((r) => r.id);const rows = await q(`SELECT * FROM file_artifactsWHERE enabled = TRUE- AND (owner_scope_id, path) IN (SELECT * FROM unnest($1::text[], $2::text[]))`,- [owners, paths],+ AND (owner_scope_id, id) IN (SELECT * FROM unnest($1::text[], $2::text[]))`,+ [owners, ids],);return rows.map(rowToArtifact);},diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.tsindex c951738e8..665b0ffcd 100644--- a/src/harness/agent-tools.ts+++ b/src/harness/agent-tools.ts@@ -1,4 +1,5 @@import { adminOperations } from "../tools/admin.ts";+import { MAX_OUTBOUND_FILES, type OutboundFile } from "../core/attachments.ts";import { MaskedExecutionError } from "../security/secret-masking.ts";import type { DocumentInput } from "../core/document-inputs.ts";import { createKeyedQueue } from "../util/async.ts";@@ -694,12 +695,12 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):command: params.command,purpose: params.purpose,...scopeNote,- ...(params.sandbox_id ? { sandbox_id: params.sandbox_id } : {}),+ ...(params.sandbox_id !== undefined ? { sandbox_id: params.sandbox_id } : {}),});try {if (params.sandbox_id === null) throw new Error("a command requires a sandbox ID; null only clears the default");const execOpts = {- ...(params.sandbox_id ? { sandboxId: params.sandbox_id } : {}),+ ...(params.sandbox_id !== undefined ? { sandboxId: params.sandbox_id } : {}),...(params.timeout_seconds !== undefined ? { timeoutSeconds: params.timeout_seconds } : {}),...(route?.scratch ? { scratch: true } : {}),...(route?.ownerAuth ? { ownerAuth: true } : {}),@@ -764,8 +765,22 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):'[error] a scratch box cannot be made durable yet — use scope:"scoped" for work that must survive future turns, or drop `durable`.';const SCOPED_EPHEMERAL_ERROR ='[error] the scoped computer is always durable today — re-run with durable:true (or omit `durable`), or use scope:"scratch" for disposable local working files.';+ const outboundFilesSchema = Type.Array(+ Type.Union([+ Type.String({ minLength: 1 }),+ Type.Object({ file_id: Type.String({ minLength: 1 }) }, { additionalProperties: false }),+ ]),+ { maxItems: MAX_OUTBOUND_FILES, description: 'Workspace paths or {file_id: "stored Files ID"} objects.' },+ );+ const outboundSandboxSchema = Type.Optional(+ Type.String({+ minLength: 1,+ description: "Sandbox for workspace paths; omit for the default. Ignored for stored file IDs.",+ }),+ );+ const sandboxSelector = (description: string) => Type.Optional(Type.String({ minLength: 1, description }));const FILE_SEND_GUIDANCE =- "The files and apps tools use the default sandbox; execute can target sandbox_id. To send a file, write it to a workspace path and name that path to whichever tool sends: the surface `post` action's `files` when you have `post` (the only way there — a file needs a thread), otherwise `attach`, which rides it out with your reply. The tool result tells you what actually went. A background job can't deliver; have it write to the workspace and attach that from a live turn. ";+ "execute, files, skills, and apps take an optional sandbox_id; omit it for the default. Sending accepts workspace paths with an optional sandbox_id, or {file_id: \"stored Files ID\"} without a sandbox. Use the surface `post` action's `files` when you have `post` (the only way there — a file needs a thread), otherwise `attach`, which rides it out with your reply. The tool result tells you what actually went. A background job can't deliver; have it write to the workspace and attach that from a live turn. ";const DURABLE_PARAM_DESC ="Retain working state for later turns within provider recovery limits? Scoped retains working state; scratch lasts for the turn; owner is invocation-only. Publish durable code to git and artifacts to Files.";@@ -1102,7 +1117,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):const { content, sourceScopeId, dir, packDir } = await tc.skill(p.name, {...(p.path ? { path: p.path } : {}),...(p.source ? { source: p.source } : {}),- ...(p.sandbox_id ? { sandboxId: p.sandbox_id } : {}),+ ...(p.sandbox_id !== undefined ? { sandboxId: p.sandbox_id } : {}),...(signal ? { signal } : {}),});signal?.throwIfAborted();@@ -1136,14 +1151,20 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):description: "Read a file from the workspace (scope, then global). Returns its contents.",parameters: Type.Object({path: Type.String({ description: "Relative path within the workspace." }),+ sandbox_id: sandboxSelector("Sandbox to read from; omit for the default. Shared files ignore it."),}),async execute(callId, params) {const tc = ref.current;if (!tc) return text("[error] no active tool context");- await recordCall(callId, { tool: "files", action: "read", path: params.path });+ await recordCall(callId, {+ tool: "files",+ action: "read",+ path: params.path,+ ...(params.sandbox_id !== undefined ? { sandbox_id: params.sandbox_id } : {}),+ });const signal = ref.abortSignal;signal?.throwIfAborted();- const { content, sourceScopeId, shared } = await tc.read(params.path, signal);+ const { content, sourceScopeId, shared } = await tc.read(params.path, signal, params.sandbox_id);signal?.throwIfAborted();return recordResult(callId,@@ -1168,20 +1189,28 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):name: "write",label: "write",description:- "Save file contents in the writable workspace scope, durable across sessions. Use files action share to grant access separately.",+ "Save file contents in the writable workspace scope. To share it, upload it to Files with POST /v1/files/uploads, then use files action share with the returned ID.",parameters: Type.Object({path: Type.String({ description: "Relative path within the workspace." }),data: Type.String({ description: "File contents, including an empty string to empty the file." }),+ sandbox_id: sandboxSelector("Sandbox to write on; omit for the default."),}),async execute(callId, params) {const tc = ref.current;if (!tc) return text("[error] no active tool context");- await recordCall(callId, { tool: "files", action: "write", path: params.path, bytes: params.data.length });+ const sandboxNote = params.sandbox_id !== undefined ? { sandbox_id: params.sandbox_id } : {};+ await recordCall(callId, {+ tool: "files",+ action: "write",+ path: params.path,+ bytes: params.data.length,+ ...sandboxNote,+ });try {- await tc.write(params.path, params.data);+ await tc.write(params.path, params.data, params.sandbox_id);return recordResult(callId,- { tool: "files", action: "write", path: params.path, bytes: params.data.length },+ { tool: "files", action: "write", path: params.path, bytes: params.data.length, ...sandboxNote },text(`wrote ${params.path} (${params.data.length} bytes)`),);} catch (e) {@@ -1262,6 +1291,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):"Sites allowed to embed the app in an iframe, as https origins (https://tools.example.com, or https://*.example.com for any subdomain). Every frame between the app and the browser tab must be listed, so a panel inside another site needs both. [] forbids embedding again. Omitted = leave the current setting alone.",}),),+ sandbox_id: sandboxSelector("Sandbox holding `dir`; omit for the default. The app's owner is unchanged."),}),async execute(callId, params) {const tc = ref.current;@@ -1272,9 +1302,11 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):dir: params.dir,entrypoint: params.entrypoint,name: params.name,+ ...(params.sandbox_id !== undefined ? { sandbox_id: params.sandbox_id } : {}),});try {- const r = await tc.publish(params as PublishInput);+ const { sandbox_id: sandboxId, ...input } = params;+ const r = await tc.publish({ ...(input as PublishInput), ...(sandboxId !== undefined ? { sandboxId } : {}) });const reach = describePublishAudience(r.audience);const alwaysOnNote = r.alwaysOn ? "\nAlways-on: the app is kept warm — no idle cold starts." : "";const embedNote = r.embedAncestors?.length ? `\nEmbeddable by: ${r.embedAncestors.join(", ")}` : "";@@ -3114,73 +3146,14 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):},});- const fileShare = defineTool({- name: "share",- label: "share",- description:- "Grant access to an existing workspace file without changing its contents. The file stays in its current home; recipients see it under shared/.",- parameters: Type.Object(- {- path: Type.Optional(Type.String({ description: "Workspace file path; pair with scope." })),- id: Type.Optional(Type.String({ description: "Existing file artifact ID; pair with toScope." })),- toScope: Type.Optional(Type.String({ description: "Destination scope or teammate name for an artifact ID." })),- scope: Type.Optional(- Type.String({ description: 'Destination: "org", personal:<userId>, channel:<id>, or team:<id>.' }),- ),- permission: Type.Optional(- Type.Union([Type.Literal("read"), Type.Literal("write")], {- description: "read = view (default); write = view/manage.",- }),- ),- },- {- anyOf: [- { required: ["path", "scope"], properties: { id: false, toScope: false } },- { required: ["id", "toScope"], properties: { path: false, scope: false } },- ],- },- ),- async execute(callId, params) {- const tc = ref.current;- if (!tc) return text("[error] no active tool context");- if (params.id !== undefined && params.toScope !== undefined) {- if (!controlTools) return unavailable(callId, "files");- return sharingTool("file").execute(- callId,- { id: params.id, toScope: params.toScope, permission: params.permission },- undefined,- undefined,- undefined as never,- );- }- await recordCall(callId, { tool: "files", action: "share", ...params });- try {- const result = await tc.write(params.path!, undefined, [- { scope: params.scope!, permission: params.permission },- ]);- return recordResult(- callId,- { tool: "files", action: "share", path: params.path, shared: result.shared },- text(- result.shared.map((grant) => `shared ${params.path} with ${grant.scope} (${grant.permission})`).join("; "),- ),- );- } catch (e) {- return recordResult(- callId,- { tool: "files", action: "share", path: params.path, error: errMessage(e) },- text(`[share failed] ${errMessage(e)}`),- true,- );- }- },- });-function sharingTool(type: "file" | "skill" | "deploy" | "cron", move = false): ToolDefinition {const tool = { file: "files", skill: "skills", deploy: "apps", cron: "cron" }[type];const action = move ? "move" : "share";let description ="Grant access to an artifact you own while keeping it in its current home. Only the owner can share; grantees cannot reshare.";+ if (type === "file")+ description =+ "Share an existing Files record by ID. A sandbox path cannot be shared; upload it with POST /v1/files/uploads first.";if (move)description ="Transfer the artifact to another context. Moving an app transfers ownership; existing shares survive. Moving a skill to the org requires an org admin in a user-started turn.";@@ -3327,14 +3300,16 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):`${actions.join("/")}: ${operation.description} Required fields: ${((operation.parameters as { required?: string[] }).required ?? []).filter((key) => key !== "action").join(", ") || "none"}.`,).join("\n\n"),- parameters: Type.Object(properties, { additionalProperties: false }),+ parameters: Type.Object(properties, { additionalProperties: true }),async execute(callId, params, signal, onUpdate, ctx) {const index = groups.findIndex((group) => group.actions.includes(String(params.action)));if (index < 0 || !Check(variants[index]!, params)) {return recordResult(callId,{ tool: name, action: params.action, error: "invalid_arguments" },- text(`[error] Invalid arguments for ${name} action ${String(params.action)}.`),+ text(+ `[error] Invalid arguments for ${name} action ${String(params.action)}. ${groups[index]?.operation.description ?? ""}`,+ ),true,);}@@ -3458,12 +3433,8 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):"post: set true to post at THIS channel's top level instead of in the current thread — a deliberate wider-audience announcement. Default (unset) replies in the thread you're in. Ignored in a DM.",}),),- files: Type.Optional(- Type.Array(Type.String(), {- description:- 'post/reach: workspace-relative file paths to upload WITH your message — images, PDFs, code snippets, whatever. Write the file to an ordinary workspace path (e.g. "work/cover.png") and list that path here; it\'s attached to the message at its destination, like a person attaching a file. Short code can just go in `text` as a ``` block; use a file for anything downloadable.',- }),- ),+ sandbox_id: outboundSandboxSchema,+ files: Type.Optional(outboundFilesSchema),emoji: Type.Optional(Type.String({ description: 'react: emoji name without colons (e.g. "eyes", "tada").' })),ref: Type.Optional(Type.String({@@ -3536,7 +3507,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):text: capText(params.text),...(params.files?.length ? { files: params.files } : {}),});- const r = await tc.post(params.text, opts, params.files);+ const r = await tc.post(params.text, opts, params.files, params.sandbox_id);return recordResult(callId,{@@ -3579,7 +3550,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):bytes: params.text.length,...(params.files?.length ? { files: params.files.length } : {}),});- const r = await tc.reach(params.text, target, params.files);+ const r = await tc.reach(params.text, target, params.files, params.sandbox_id);return recordResult(callId,{@@ -3840,22 +3811,18 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):name: "attach",label: "Attach",description:- "Send file(s) along with this turn's reply. Name workspace-relative paths of files you have " +- "already written; they ride out with the reply as real uploads. Call it again to add more — " +- "re-naming the same path replaces it. The result lists exactly what will be delivered; if a " +- "path is wrong nothing is staged and the result says so, so never claim you sent a file you " +- "have not seen confirmed here.",+ "Send files with this turn's reply, using workspace paths or stored Files IDs. " ++ "Repeated sources replace their staged copy. Any invalid file stages nothing; the result lists what will be delivered.",parameters: Type.Object({- files: Type.Array(Type.String(), {- description: 'Workspace-relative paths of files to deliver with this reply, e.g. ["report.md"].',- }),+ files: outboundFilesSchema,+ sandbox_id: outboundSandboxSchema,}),- async execute(callId, params: { files?: string[] }) {+ async execute(callId, params: { files?: OutboundFile[]; sandbox_id?: string }) {const tc = ref.current;if (!tc) return text("[error] no active tool context");- const files = (params.files ?? []).map((f) => String(f ?? "").trim()).filter(Boolean);- await recordCall(callId, { tool: "attach", files });- const r = await tc.attach(files);+ const files = params.files ?? [];+ await recordCall(callId, { tool: "attach", files, sandbox_id: params.sandbox_id });+ const r = await tc.attach(files, params.sandbox_id);if (!r.ok) return recordResult(callId, { tool: "attach", ok: false }, text(`[not attached] ${r.message}`), true);const list = r.files.map((f) => `${f.name} (${f.sizeBytes} bytes, ${f.mimetype})`).join("; ");const total = r.staged > r.files.length ? ` ${r.staged} file(s) are now staged for this reply.` : "";@@ -3916,11 +3883,12 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):tc: typeof ref.current,paths: readonly string[] | undefined,signal?: AbortSignal,+ sandboxId?: string,): Promise<string[]> {const out: string[] = [];for (const path of (paths ?? []).slice(0, GOAL_EVIDENCE_FILES)) {const content = tc- ? await tc.read(path, signal).then(+ ? await tc.read(path, signal, sandboxId).then((r) => r.content,() => null,)@@ -4046,9 +4014,10 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):description: "Workspace paths of the deliverables; the governor reads them directly.",}),),+ sandbox_id: sandboxSelector("Sandbox holding `files`; omit for the default."),}),async execute(callId, params) {- const p = params as { status?: "complete" | "resume"; note: string; files?: string[] };+ const p = params as { status?: "complete" | "resume"; note: string; files?: string[]; sandbox_id?: string };const status = p.status === "resume" ? "resume" : "complete";await recordCall(callId, {tool: "goal",@@ -4112,7 +4081,10 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):true,);}- const evidence = [p.note ?? "", ...(await goalEvidenceFiles(ref.current, p.files, ref.abortSignal))].join("\n");+ const evidence = [+ p.note ?? "",+ ...(await goalEvidenceFiles(ref.current, p.files, ref.abortSignal, p.sandbox_id)),+ ].join("\n");const verdict = ref.governGoal? await ref.governGoal({@@ -4322,7 +4294,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):read: skill,...(controlTools ? { share: sharingTool("skill"), move: sharingTool("skill", true) } : {}),}),- resourceTool("files", { read, write, share: fileShare }),+ resourceTool("files", { read, write, ...(controlTools ? { share: sharingTool("file") } : {}) }),resourceTool("apps", {publish,...(controlTools ? { share: sharingTool("deploy"), move: sharingTool("deploy", true) } : {}),diff --git a/src/harness/harness-shared.ts b/src/harness/harness-shared.tsindex ebbd016df..0c79c1d20 100644--- a/src/harness/harness-shared.ts+++ b/src/harness/harness-shared.ts@@ -161,9 +161,7 @@ export function nativeChildToolAllowed(name: string, args?: unknown): boolean {const action = args && typeof args === "object" ? (args as Record<string, unknown>).action : undefined;if (name === "apps") return action === "publish";if (action === "read" || action === "write") return true;- return (- action === "share" && typeof (args as Record<string, unknown>).path === "string" && !("id" in (args as object))- );+ return false;}export function bridgedTools(ref: ToolContextRef, options: AgentToolsOptions): BridgedTool[] {diff --git a/src/resolution/context-files.ts b/src/resolution/context-files.tsindex 87580d257..2506cebf0 100644--- a/src/resolution/context-files.ts+++ b/src/resolution/context-files.ts@@ -1,5 +1,4 @@-import { isArtifactPath, type FileArtifactStore } from "../files/file-artifact-store.ts";-import type { WorkspaceStore } from "../workspace/workspace-store.ts";+import type { FileArtifactStore } from "../files/file-artifact-store.ts";import type { GrantedHandle, ScopeId } from "../types.ts";const MAX_SHARED_ARTIFACT_BYTES = 10 * 1024 * 1024;@@ -7,22 +6,21 @@ const MAX_SHARED_ARTIFACT_BYTES = 10 * 1024 * 1024;async function readGrantedArtifactBytes(files: FileArtifactStore | undefined,ownerScopeId: ScopeId,- ownerPath: string,+ fileId: string,): Promise<Buffer | null> {if (!files) return null;- const rows = await files.resolveByOwnerPaths([{ ownerScopeId, path: ownerPath }]);- // Re-assert the tuple: the (owner_scope_id, path) index isn't unique and- // neither implementation orders results.- const row = rows.find((r) => r.ownerScopeId === ownerScopeId && r.path === ownerPath);- if (!row) return null;- const opened = await files.open(row.id);+ const opened = await files.open(fileId);if (!opened) return null;+ if (opened.artifact.ownerScopeId !== ownerScopeId) {+ opened.stream.destroy();+ return null;+ }// The advertised size can be absent on some backends (fails open at 0), so// the collector enforces the cap on actual bytes read.if (opened.sizeBytes > MAX_SHARED_ARTIFACT_BYTES) {opened.stream.destroy();throw new Error(- `shared file ${ownerPath.split("/").pop()} is ${opened.sizeBytes} bytes — larger than the ${MAX_SHARED_ARTIFACT_BYTES}-byte shared-read limit`,+ `shared file ${opened.artifact.name} is ${opened.sizeBytes} bytes — larger than the ${MAX_SHARED_ARTIFACT_BYTES}-byte shared-read limit`,);}const chunks: Buffer[] = [];@@ -33,7 +31,7 @@ async function readGrantedArtifactBytes(if (total > MAX_SHARED_ARTIFACT_BYTES) {opened.stream.destroy();throw new Error(- `shared file ${ownerPath.split("/").pop()} exceeds the ${MAX_SHARED_ARTIFACT_BYTES}-byte shared-read limit`,+ `shared file ${opened.artifact.name} exceeds the ${MAX_SHARED_ARTIFACT_BYTES}-byte shared-read limit`,);}chunks.push(buf);@@ -44,20 +42,16 @@ async function readGrantedArtifactBytes(export async function readContextFile(path: string,handles: readonly GrantedHandle[],- workspace: Pick<WorkspaceStore, "readBytes">,files?: FileArtifactStore,onRead?: (grant: GrantedHandle) => void,): Promise<{ grant: GrantedHandle; bytes: Uint8Array | null } | { error: string } | null> {const matches = handles.filter((grant) => grant.handlePath === path);if (!matches.length) return null;- const distinct = new Set(matches.map((grant) => `${grant.ownerScopeId}\0${grant.ownerPath}`));+ const distinct = new Set(matches.map((grant) => `${grant.ownerScopeId}\0${grant.fileId}`));if (distinct.size > 1)return { error: `ERROR: ambiguous shared handle "${path}" maps to ${distinct.size} different files` };const grant = matches[0]!;- // Artifact and workspace namespaces must not shadow each other with stale snapshots.- const bytes = isArtifactPath(grant.ownerPath)- ? await readGrantedArtifactBytes(files, grant.ownerScopeId, grant.ownerPath)- : await workspace.readBytes(grant.ownerScopeId, grant.ownerPath);+ const bytes = await readGrantedArtifactBytes(files, grant.ownerScopeId, grant.fileId);if (bytes !== null) onRead?.(grant);return { grant, bytes };}diff --git a/src/resolution/sharing-access.ts b/src/resolution/sharing-access.tsindex deda0f7eb..f09d038be 100644--- a/src/resolution/sharing-access.ts+++ b/src/resolution/sharing-access.ts@@ -1,10 +1,7 @@-import { MEMORY_FILE } from "../memory/memory-service.ts";import type { FileArtifactStore } from "../files/file-artifact-store.ts";import type { SessionStore } from "../sessions/session-store.ts";import type { GrantedHandle, Principal, ScopeId, TurnOrigin } from "../types.ts";import { parseScopeId, personalScope } from "../types.ts";-import type { WorkspaceStore } from "../workspace/workspace-store.ts";-import { relative } from "node:path";import type { ScopedConfigStore } from "./config-store.ts";import type { IsCurrentSharedScopeMember } from "./scope-membership.ts";import type { SharingPosture } from "./sharing-posture.ts";@@ -90,34 +87,20 @@ function handlePath(path: string): string {export async function carriedFileHandles(sourceScopes: readonly ScopeId[],- workspace: Pick<WorkspaceStore, "list" | "scopeDir">,files: Pick<FileArtifactStore, "listOwnedByScopes">,): Promise<GrantedHandle[]> {const handles = new Map<string, GrantedHandle>();for (const sourceScope of sourceScopes) {const remaining = MAX_OPEN_FILES - handles.size;if (remaining <= 0) break;- const [workspacePaths, page] = await Promise.all([- workspace.list(sourceScope, { limit: remaining }),- files.listOwnedByScopes([sourceScope], { limit: remaining }),- ]);- const artifacts = page.files.map((file) => file.path);- const workspaceBase = workspace.scopeDir(sourceScope);- const ownedPaths = workspacePaths.map((path) => {- const rel = relative(workspaceBase, path);- return rel.startsWith("..") ? "" : rel;- });- for (const ownerPath of [...ownedPaths, ...artifacts]) {+ const page = await files.listOwnedByScopes([sourceScope], { limit: remaining });+ for (const file of page.files) {if (handles.size >= MAX_OPEN_FILES) break;- const relative = handlePath(ownerPath);- if (relative === MEMORY_FILE) continue;- if (!relative) continue;- const key = `${sourceScope}\0${ownerPath}`;- handles.set(key, {+ handles.set(file.id, {carried: true,- handlePath: `shared/open-${handleSource(sourceScope)}/${relative}`,+ handlePath: `shared/open-${handleSource(sourceScope)}/${file.id}/${handlePath(file.name)}`,ownerScopeId: sourceScope,- ownerPath,+ fileId: file.id,permission: "read",});}diff --git a/src/resolution/turn-context.ts b/src/resolution/turn-context.tsindex 4adcd8702..fc7d0e2bb 100644--- a/src/resolution/turn-context.ts+++ b/src/resolution/turn-context.ts@@ -7,7 +7,6 @@ import { principalEntitledToScope } from "./context-filter.ts";import { swallowAs } from "../util/errors.ts";import { readContextFile } from "./context-files.ts";import type { FileArtifactStore } from "../files/file-artifact-store.ts";-import type { WorkspaceStore } from "../workspace/workspace-store.ts";import type { AuditLog } from "../audit/audit-log.ts";import type { MemoryService } from "../memory/memory-service.ts";import { recallMemoryScopes, writableMemoryScope, type MemoryPolicy } from "../memory/policy.ts";@@ -25,7 +24,6 @@ type ContextInput = Omit<Parameters<typeof sharingSourcesForTurn>[0], "posture">memoryPolicy: MemoryPolicy;useMemory: boolean;memory: MemoryService;- workspace: WorkspaceStore;files: FileArtifactStore;skills?: SkillStore;auditLog?: AuditLog;@@ -69,10 +67,7 @@ export async function resolveTurnContext(input: ContextInput) {currentScopeMembers: input.currentScopeMembers,};const memory = disclosedMemory(input.memory, disclosure);- const handles = [- ...resolution.grantedHandles,- ...(await carriedFileHandles(sharingSources, input.workspace, input.files)),- ];+ const handles = [...resolution.grantedHandles, ...(await carriedFileHandles(sharingSources, input.files))];return {sharingSources,memoryScopeId,@@ -153,8 +148,8 @@ export async function resolveTurnContext(input: ContextInput) {};},readFile: (path: string) =>- readContextFile(path, handles, input.workspace, input.files, (grant) => {- if (grant.carried) recordRead(grant.ownerScopeId, grant.ownerPath);+ readContextFile(path, handles, input.files, (grant) => {+ if (grant.carried) recordRead(grant.ownerScopeId, grant.fileId);}),};}diff --git a/src/sandbox/sandbox-resources.ts b/src/sandbox/sandbox-resources.tsindex 8f4bc0bda..5ff2430b9 100644--- a/src/sandbox/sandbox-resources.ts+++ b/src/sandbox/sandbox-resources.ts@@ -76,6 +76,21 @@ export interface SandboxResources {defaultBackend(): SandboxBackendName;}+export class SandboxAccessError extends Error {}++export async function accessConversationSandbox(+ resources: SandboxResources | undefined,+ actorId: string,+ id: string,+ canUseScope: (scope: ScopeId) => boolean | Promise<boolean>,+): Promise<SandboxResource> {+ if (!id.trim()) throw new SandboxAccessError("sandbox_id must be a non-empty sandbox ID");+ const resource = await resources?.access(actorId, id);+ if (!resource || resource.state === "retired" || !(await canUseScope(resource.ownerScopeId)))+ throw new SandboxAccessError("sandbox access is no longer authorized in this conversation");+ return resource;+}+export function createSandboxResources(opts: {upgrade?: () => Promise<void>;records: DurableMap<SandboxResource>;@@ -108,12 +123,12 @@ export function createSandboxResources(opts: {};const authorize = async (actorId: string, scopeId: ScopeId): Promise<void> => {if (!parseScopeId(scopeId).kind || !(await opts.canUseScope(actorId, scopeId)))- throw new Error("sandbox access requires permission to use its owning scope");+ throw new SandboxAccessError("sandbox access requires permission to use its owning scope");};const get = async (id: string): Promise<SandboxResource> => {await initialize();const record = await opts.records.get(id);- if (!record) throw new Error(`sandbox not found: ${id}`);+ if (!record) throw new SandboxAccessError(`sandbox not found: ${id}`);return record;};const use = async <T>(id: string, action: () => Promise<T>, exclusive = false): Promise<T> => {diff --git a/src/sandbox/sandbox-routing.ts b/src/sandbox/sandbox-routing.tsindex 8068eeb7a..906e72ec7 100644--- a/src/sandbox/sandbox-routing.ts+++ b/src/sandbox/sandbox-routing.ts@@ -105,13 +105,14 @@ export function createSandboxRouter(opts: RoutingSandboxOptions): Sandbox {profile: fallback.profile,async profileFor(scopeId: string, sandboxId?: string): Promise<AgentComputerProfile> {- const resource = sandboxId ? await resources.get(sandboxId) : await resources.resolve(scopeId);+ const resource = sandboxId !== undefined ? await resources.get(sandboxId) : await resources.resolve(scopeId);return resource ? backendFor(resource.backend).profile : fallback.profile;},async provision(layers: WorkspaceLayer[], provOpts?: ProvisionOptions): Promise<SandboxHandle> {const scope = provOpts?.routeScopeId ?? writableScope(layers);- const resource = provOpts?.sandboxId ? await resources.get(provOpts.sandboxId) : await resources.resolve(scope);+ const resource =+ provOpts?.sandboxId !== undefined ? await resources.get(provOpts.sandboxId) : await resources.resolve(scope);const backend = resource?.backend ?? defaultBackend;const sandbox = backendFor(backend);const provision = async (targetLayers: WorkspaceLayer[]) => {diff --git a/src/tools/primitives.ts b/src/tools/primitives.tsindex 11e282585..c4b1f19b9 100644--- a/src/tools/primitives.ts+++ b/src/tools/primitives.ts@@ -13,8 +13,7 @@ import { withAbort, withTimeout } from "../util/async.ts";import type { RuntimeRequest, RuntimeResult } from "../harness/runtime-types.ts";import { readContextFile } from "../resolution/context-files.ts";import { type TurnContext } from "../resolution/turn-context.ts";-import { randomUUID } from "node:crypto";-import type { SandboxAccessPlan, SandboxResources } from "../sandbox/sandbox-resources.ts";+import type { SandboxAccessPlan, SandboxResource, SandboxResources } from "../sandbox/sandbox-resources.ts";import { join } from "node:path";import { interpolateSplitEnv } from "../deployment/deployment-layer.ts";import type { CredentialPathSpec } from "../credentials/resident-paths.ts";@@ -56,9 +55,9 @@ import { publicUrlOf } from "../deploy/deploy-store.ts";import { carriesGitMetadata } from "../deploy/deploy-fs.ts";import type { AclStore } from "../acl/acl-store.ts";import type { AuditLog } from "../audit/audit-log.ts";-import { mimeFromName } from "../core/attachments.ts";-import { swallow, errMessage, withCleanup } from "../util/errors.ts";-import { fileArtifactId, type FileArtifactStore } from "../files/file-artifact-store.ts";+import { TURN_FILES_DIR, type OutboundFile } from "../core/attachments.ts";+import { errMessage, withCleanup } from "../util/errors.ts";+import type { FileArtifactStore } from "../files/file-artifact-store.ts";import type { ScopedConfigStore } from "../resolution/config-store.ts";import { MEMORY_FILE, type MemoryService } from "../memory/memory-service.ts";import type { McpToolService, McpToolDescriptor } from "../mcp/mcp-tool-service.ts";@@ -92,6 +91,7 @@ export interface PublishInput {embedAncestors?: string[];public?: boolean;share?: Array<{ scope: ScopeId; permission: Permission }>;+ sandboxId?: string;}export interface PublishAudienceDescriptor {@@ -161,15 +161,6 @@ export interface SkillResult {packDir?: string;}-interface ShareDirective {- scope: ScopeId | "org";- permission?: Permission;-}--interface WriteResult {- shared: Array<{ scope: ScopeId; permission: Permission }>;-}-interface ReachedProvenance {scopeId: ScopeId;label: string;@@ -196,7 +187,7 @@ interface AttachedFileMeta {export type AttachResult = { ok: true; files: AttachedFileMeta[]; staged: number } | { ok: false; message: string };-export type AttachFiles = (files: readonly string[]) => Promise<AttachResult>;+export type AttachFiles = (files: readonly OutboundFile[], sandboxId?: string) => Promise<AttachResult>;export interface ToolContext extends SurfaceToolDeps {admin?: AdminToolAccess;@@ -224,7 +215,7 @@ export interface ToolContext extends SurfaceToolDeps {): Promise<unknown>;computerStatus(sandboxId?: string): Promise<ComputerStatus>;restartComputer(sandboxId?: string): Promise<void>;- read(path: string, signal?: AbortSignal): Promise<ReadResult>;+ read(path: string, signal?: AbortSignal, sandboxId?: string): Promise<ReadResult>;listSkills(query?: string,offset?: number,@@ -239,7 +230,7 @@ export interface ToolContext extends SurfaceToolDeps {name: string,opts?: { path?: string; sandboxId?: string; source?: string; signal?: AbortSignal },): Promise<SkillResult>;- write(path: string, data?: string, share?: ShareDirective[]): Promise<WriteResult>;+ write(path: string, data: string, sandboxId?: string): Promise<void>;publish(input: PublishInput): Promise<PublishResult>;setDeploymentPublic(id: string, isPublic: boolean): Promise<{ id: string; name?: string; public: boolean }>;createPlayground(input: { title: string; html: string }): Promise<PlaygroundArtifact>;@@ -432,8 +423,18 @@ type SurfaceStandingOrderResult =| { ok: false; message: string };export interface SurfaceToolDeps {- post(text: string, opts?: SurfacePostOpts, files?: readonly string[]): Promise<SurfacePostResult>;- reach(text: string, target: SurfaceReachTarget, files?: readonly string[]): Promise<SurfacePostResult>;+ post(+ text: string,+ opts?: SurfacePostOpts,+ files?: readonly OutboundFile[],+ sandboxId?: string,+ ): Promise<SurfacePostResult>;+ reach(+ text: string,+ target: SurfaceReachTarget,+ files?: readonly OutboundFile[],+ sandboxId?: string,+ ): Promise<SurfacePostResult>;react(input: SurfaceReactInput): Promise<SurfacePostResult>;edit(input: SurfaceEditInput): Promise<SurfacePostResult>;delete(input: SurfaceDeleteInput): Promise<SurfacePostResult>;@@ -488,7 +489,6 @@ export interface ToolContextDeps {authorizeCommand: (command: string, approvalKey?: string, exactApprovalKey?: boolean) => boolean;grantedHandles: GrantedHandle[];context?: TurnContext;- sharedMaterializeDir?: string;sandboxResources?: SandboxResources;invalidateProvision?: () => void;workspace: WorkspaceStore;@@ -528,7 +528,6 @@ export interface ToolContextDeps {attempt?: number;backgroundBroker?: BackgroundExecBroker;monitorBroker?: MonitorBroker;- persistWritesToStore?: { excludeDirs: readonly string[] };onGapWork?: (work: GapWork) => void;control?: ControlService;controlClaims?: CapabilityClaims;@@ -556,14 +555,39 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {}): undefined);const fallbackMounts = deps.layers.filter((l) => l.mode === "ro" && l.mountPath);- const persistExclude = deps.persistWritesToStore?.excludeDirs;- const orgScopeId = deps.layers.find((l) => l.mountPath === "global")?.scopeId ?? null;+ const persistExclude = [...fallbackMounts.map((mount) => mount.mountPath!), TURN_FILES_DIR];const accessSandbox = async (id: string): Promise<SandboxAccessPlan> => {if (!deps.sandboxResources || !deps.accessSandboxResource) throw new Error("sandbox inventory unavailable");+ if (!id.trim()) throw new Error("sandbox_id must name a sandbox; omit it to use the default");return deps.accessSandboxResource(id);};+ const machine = async (+ id: string | undefined,+ ): Promise<{+ handle: SandboxHandle;+ resource?: SandboxResource;+ crossScope: boolean;+ durableRef: (path: string) => string;+ }> => {+ if (id === undefined) {+ const handle = await deps.provision();+ const resource = handle.resourceId ? await deps.sandboxResources?.get(handle.resourceId) : undefined;+ return { handle, ...(resource ? { resource } : {}), crossScope: false, durableRef: (path) => path };+ }+ let access = await accessSandbox(id);+ if (!deps.provisionResource) throw new Error("sandbox inventory unavailable");+ const handle = await deps.provisionResource(access, (current) => {+ access = current;+ });+ const resource = access.resource;+ const fallback = writableScopeId ? await deps.sandboxResources!.resolve(writableScopeId) : null;+ const durableRef =+ fallback?.id === resource.id ? (path: string) => path : (path: string) => `sandbox-files/${resource.id}/${path}`;+ return { handle, resource, crossScope: access.crossScope, durableRef };+ };+const authorizeExecution = (command: string, access?: SandboxAccessPlan, policy = deps.commandPolicy()): void => {const source = evaluateCommandWithLayer(command, policy, deps.layerCommandRules?.() ?? []);if (source.decision === "deny") throw new CommandDenied(command, source.reason ?? "denied by policy");@@ -782,7 +806,7 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {return { ...status, guestResponsive: false, probeError: errMessage(e) };}};- if (sandboxId) {+ if (sandboxId !== undefined) {const resources = deps.sandboxResources;if (!resources || !deps.provisionResource) throw new Error("sandbox inventory unavailable");const access = await accessSandbox(sandboxId);@@ -795,7 +819,7 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {return probe(await deps.sandbox.computerStatus(writableScopeId), deps.provision);},async restartComputer(sandboxId?: string): Promise<void> {- if (sandboxId) {+ if (sandboxId !== undefined) {const resources = deps.sandboxResources;if (!resources) throw new Error("sandbox inventory unavailable");await accessSandbox(sandboxId);@@ -852,7 +876,7 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {}const executionPolicy = deps.commandPolicy;let handle;- if (execOpts?.sandboxId) {+ if (execOpts?.sandboxId !== undefined) {if (!deps.sandboxResources || !deps.provisionResource) throw new Error("sandbox inventory unavailable");const access = await accessSandbox(execOpts.sandboxId);handle = await deps.provisionResource(access, (current) => {@@ -923,7 +947,7 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {});},- async read(path: string, signal?: AbortSignal): Promise<ReadResult> {+ async read(path: string, signal?: AbortSignal, sandboxId?: string): Promise<ReadResult> {signal?.throwIfAborted();if (path === MEMORY_FILE && memory && deps.memoryScopeId) {if (!deps.memoryAccess?.read.includes(deps.memoryScopeId)) {@@ -934,43 +958,27 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {}const sharedFile = deps.context? await withAbort(() => deps.context!.readFile(path), signal)- : await withAbort(() => readContextFile(path, deps.grantedHandles, deps.workspace, deps.files), signal);+ : await withAbort(() => readContextFile(path, deps.grantedHandles, deps.files), signal);if (sharedFile && "error" in sharedFile) return { content: sharedFile.error, sourceScopeId: null };if (sharedFile) {const { grant: granted, bytes } = sharedFile;if (bytes === null) return { content: null, sourceScopeId: granted.ownerScopeId };const asText = tryDecodeUtf8(bytes);if (asText !== null) return { content: asText, sourceScopeId: granted.ownerScopeId, shared: true };- if (granted.carried) {- return {- content:- "Binary files require an explicit share before they can be copied into this conversation's computer.",- sourceScopeId: granted.ownerScopeId,- };- }- const handle = await deps.provision();- const name = granted.handlePath.split(/[\\/]/).pop() ?? granted.handlePath;- const materializedPath = deps.sharedMaterializeDir- ? `${deps.sharedMaterializeDir}/${name}`- : granted.handlePath;- signal?.throwIfAborted();- await deps.sandbox.writeFileBytes(handle, materializedPath, bytes);- signal?.throwIfAborted();return {- content:- `[binary file materialized into the sandbox at ${materializedPath} (${bytes.length} bytes) — ` +- `to send it, attach it to a message: name \`${materializedPath}\` in the surface \`post\` action's \`files\`]`,+ content: `[binary file ${granted.handlePath.split("/").pop()}, Files ID ${granted.fileId}; send it by ID]`,sourceScopeId: granted.ownerScopeId,shared: true,};}if (path.startsWith("shared/open-")) return { content: null, sourceScopeId: null };signal?.throwIfAborted();- const handle = await deps.provision();+ const { handle, resource, crossScope } = await machine(sandboxId);+ const mounts = crossScope ? fallbackMounts.filter((mount) => mount.mountPath === "global") : fallbackMounts;return timed("file_op", async () => {const direct = await withAbort(() => deps.sandbox.readFile(handle, path), signal);- if (direct !== null) return { content: direct, sourceScopeId: writableScopeId };- for (const mount of fallbackMounts) {+ if (direct !== null) return { content: direct, sourceScopeId: resource?.ownerScopeId ?? writableScopeId };+ for (const mount of mounts) {const v = await withAbort(() => deps.sandbox.readFile(handle, join(mount.mountPath, path)), signal);if (v !== null) return { content: v, sourceScopeId: mount.scopeId };}@@ -1013,7 +1021,7 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {): Promise<SkillResult> {opts?.signal?.throwIfAborted();if (!deps.useSkill) return { content: null, sourceScopeId: null };- if (opts?.sandboxId && (!deps.sandboxResources || !deps.provisionResource))+ if (opts?.sandboxId !== undefined && (!deps.sandboxResources || !deps.provisionResource))throw new Error("named sandboxes are not available here");return withAbort(() => deps.useSkill!(name, opts?.path ?? "SKILL.md", opts?.sandboxId, opts?.source),@@ -1021,80 +1029,18 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {);},- async write(path: string, data?: string, share?: ShareDirective[]): Promise<WriteResult> {- const wantShare = share !== undefined && share.length > 0;- if (data === undefined && !wantShare) {- throw new Error("write needs `data` to save content, `share` to grant access, or both");+ async write(path: string, data: string, sandboxId?: string): Promise<void> {+ if (deps.memory && deps.memoryScopeId && isUnderAnyDir(path, ["memory"])) {+ throw new Error("your durable memory isn't a file — use the `memory` tool instead");}- if (data !== undefined && deps.memory && deps.memoryScopeId && isUnderAnyDir(path, ["memory"])) {- throw new Error(- `your durable memory isn't a file — use the \`memory\` tool instead (action "remember" to add facts, "rewrite" to curate the whole notebook)`,- );- }- const handle = await deps.provision();- return once(() =>+ const { handle, resource, crossScope, durableRef } = await machine(sandboxId);+ if (crossScope) throw new Error("files write needs a computer owned by this conversation");+ const ownerScopeId = resource?.ownerScopeId ?? writableScopeId;+ await once(() =>timed("file_op", async () => {- if (data !== undefined) {- await deps.sandbox.writeFile(handle, path, data);- if (writableScopeId && persistExclude && !isUnderAnyDir(path, persistExclude)) {- await deps.workspace.write(writableScopeId, path, data);- }- }- const shared: WriteResult["shared"] = [];- if (wantShare) {- if (!writableScopeId) throw new Error("share needs a writable scope that owns the file");- const bytes = await deps.sandbox.readFileBytes(handle, path);- if (bytes === null) throw new Error(`no such file to share: ${path}`);- await deps.workspace.write(writableScopeId, path, bytes);- const priorRows = deps.files- ? await deps.files.resolveByOwnerPaths([{ ownerScopeId: writableScopeId, path }])- : [];- const priorArtifact = priorRows.find((r) => r.direction === "out") ?? priorRows[0];- const priorAuthor = priorArtifact?.createdBy;- const author = data === undefined ? (priorAuthor ?? deps.createdBy) : deps.createdBy;- if (deps.files) {- try {- const name = path.split(/[\\/]/).pop() || path;- await deps.files.put({- id: priorArtifact?.id ?? fileArtifactId(randomUUID(), "out", 0),- reuseExistingPath: true,- ownerScopeId: writableScopeId,- createdBy: author,- name,- path,- mimetype: mimeFromName(name),- data: bytes,- direction: "out",- createdInScope: writableScopeId,- });- } catch (e) {- swallow("tools: persist of outbound file artifact failed", e);- }- }- for (const s of share!) {- const granteeScopeId = s.scope === "org" ? orgScopeId : s.scope;- if (!granteeScopeId) throw new Error('cannot resolve "org" — no org scope is mounted in this session');- if (parseScopeId(granteeScopeId).kind === null) {- throw new Error(- `invalid share target "${s.scope}" — use a scope id like personal:<id>, channel:<id>, team:<id>, or org:<id> (or "org")`,- );- }- const permission: Permission = s.permission ?? "read";- await deps.acl.grant(- { ownerScopeId: writableScopeId, ref: path, granteeScopeId, permission, grantedBy: deps.createdBy },- author,- );- deps.auditLog?.record({- at: Date.now(),- principalId: deps.createdBy,- action: "file_share",- resource: path,- scopeLabel: granteeScopeId,- });- shared.push({ scope: granteeScopeId, permission });- }- }- return { shared };+ await deps.sandbox.writeFile(handle, path, data);+ if (ownerScopeId && !isUnderAnyDir(path, persistExclude))+ await deps.workspace.write(ownerScopeId, durableRef(path), data);}),);},@@ -1119,9 +1065,9 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {if (effectiveEntrypoint && input.dir && hasParentPathSegment(input.dir)) {throw new Error("publish directory must stay inside the workspace — no .. path segments");}- const handle = await deps.provision();+ if (!effectiveEntrypoint && input.sandboxId !== undefined) await accessSandbox(input.sandboxId);const files: DeployFile[] = effectiveEntrypoint- ? filesUnder(await collectTree(deps.sandbox, handle, input.dir), input.dir)+ ? filesUnder(await collectTree(deps.sandbox, (await machine(input.sandboxId)).handle, input.dir), input.dir): [];if (effectiveEntrypoint && files.length === 0) {throw new Error(`publish: no files found under ${input.dir ?? "."} - nothing to deploy`);@@ -1263,7 +1209,7 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {const requested = await selectCredentials(requestedCredentials, false);const policy = deps.commandPolicy;let handle: SandboxHandle;- if (opts?.sandboxId) {+ if (opts?.sandboxId !== undefined) {if (!deps.sandboxResources || !deps.provisionResource) throw new Error("sandbox inventory unavailable");const access = await accessSandbox(opts.sandboxId);handle = await deps.provisionResource(access, (current) => {@@ -1431,14 +1377,14 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {(r) => r.ok,),- post: (text, opts, files) =>+ post: (text, opts, files, sandboxId) =>surfaceOp(- (s) => s.post(text, opts, files),+ (s) => s.post(text, opts, files, sandboxId),(r) => r.ok,),- reach: (text, target, files) =>+ reach: (text, target, files, sandboxId) =>surfaceOp(- (s) => s.reach(text, target, files),+ (s) => s.reach(text, target, files, sandboxId),(r) => r.ok,),react: (input) =>@@ -1464,8 +1410,10 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {getStandingOrder: () => surfaceOp((s) => s.getStandingOrder()),setStandingOrder: (orders, bots, ambientEnabled, expectedOrders) =>surfaceOp((s) => s.setStandingOrder(orders, bots, ambientEnabled, expectedOrders)),- attach: (files) =>- deps.attach ? deps.attach(files) : Promise.resolve({ ok: false as const, message: ATTACH_UNAVAILABLE_MESSAGE }),+ attach: (files, sandboxId) =>+ deps.attach+ ? deps.attach(files, sandboxId)+ : Promise.resolve({ ok: false as const, message: ATTACH_UNAVAILABLE_MESSAGE }),};}diff --git a/src/types.ts b/src/types.tsindex b72e221d2..eb959e3eb 100644--- a/src/types.ts+++ b/src/types.ts@@ -182,7 +182,7 @@ export interface GrantedHandle {carried?: true;handlePath: string;ownerScopeId: ScopeId;- ownerPath: string;+ fileId: string;permission: Permission;}diff --git a/src/wiring.ts b/src/wiring.tsindex 50ab31113..7a420442a 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -614,6 +614,7 @@ export function buildApp(const acl = createAclStore(config.databaseUrl ? createPostgresGrantStore(config.databaseUrl) : undefined, {manages: (principalId, scopeId, authoredBy) =>membership.managesArtifactHome!(scopeId, authoredBy ?? "", principalId),+ resolveFiles: (refs) => files.resolveByIds(refs),});const pgArtifactMap = config.databaseUrl ? createPostgresMapFactory(config.databaseUrl) : null;const artifactMap = <T>(table: string, indexedFields?: readonly Extract<keyof T, string>[]): DurableMap<T> =>diff --git a/test/acl-file-grants.test.ts b/test/acl-file-grants.test.tsnew file mode 100644index 000000000..c7920bbe7--- /dev/null+++ b/test/acl-file-grants.test.ts@@ -0,0 +1,117 @@+import assert from "node:assert/strict";+import test from "node:test";+import { createAclStore, type GrantPersistence } from "../src/acl/acl-store.ts";+import { createMemoryDurableByteStore } from "../src/files/durable-byte-store.ts";+import { createMemoryFileArtifactStore, type FileArtifactRef } from "../src/files/file-artifact-store.ts";+import { principalEntitledToScope } from "../src/resolution/context-filter.ts";+import type { Grant, Principal } from "../src/types.ts";++const owner = "personal:alice";+const recipient = "personal:bob";+const org = "org:default-org";+const bob: Principal = { id: "bob", type: "internal", teamIds: [] };+const grant: Grant = {+ ownerScopeId: owner,+ ref: "F1",+ granteeScopeId: recipient,+ grantedBy: "alice",+ permission: "read",+};++async function fixture() {+ const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());+ await files.put({+ id: "F1",+ ownerScopeId: owner,+ createdBy: "alice",+ name: "report.md",+ path: "reports/report.md",+ mimetype: "text/markdown",+ data: Buffer.from("hello"),+ direction: "out",+ });+ return { files, acl: createAclStore(undefined, { resolveFiles: (refs) => files.resolveByIds(refs) }) };+}++test("file grants require a real, enabled Files ID owned by the granting scope", async () => {+ const { files, acl } = await fixture();+ for (const ref of ["reports/report.md", "report.md", "artifacts/F1/report.md", "missing"]) {+ await assert.rejects(acl.grant({ ...grant, ref }), /put the file in Files first using POST \/v1\/files\/uploads/);+ }+ await assert.rejects(+ acl.grant({ ...grant, ownerScopeId: recipient, grantedBy: "bob" }),+ /owned by the granting scope/,+ );+ await files.setEnabled("F1", false);+ await assert.rejects(acl.grant(grant), /enabled Files record ID/);+ assert.deepEqual(await acl.list(), []);+ await files.setEnabled("F1", true);+ await acl.grant(grant);+ assert.deepEqual(await acl.list(), [grant]);+});++test("missing Files resolver fails closed for grants and replacement grants", async () => {+ const acl = createAclStore();+ await assert.rejects(acl.grant(grant), /Files record ID/);+ await assert.rejects(acl.replaceGrantsIfCurrent(owner, "F1", [], [grant], "alice"), /Files record ID/);+ assert.deepEqual(await acl.list(), []);+});++test("conditional replacement validates file grants before changing persisted access", async () => {+ const { files, acl } = await fixture();+ await acl.grant(grant);+ const replacement: Grant = { ...grant, permission: "write" };+ await files.setEnabled("F1", false);+ await assert.rejects(+ acl.replaceGrantsIfCurrent(owner, "F1", [grant], [replacement], "alice"),+ /enabled Files record ID/,+ );+ assert.deepEqual(await acl.list(), [grant]);+ await files.setEnabled("F1", true);+ assert.equal(await acl.replaceGrantsIfCurrent(owner, "F1", [grant], [replacement], "alice"), true);+ assert.deepEqual(await acl.list(), [replacement]);+ await files.delete("F1");+ assert.equal(await acl.replaceGrantsIfCurrent(owner, "F1", [replacement], [], "alice"), true);+});++test("shared handles use the Files name and ID and disappear when the file is disabled or deleted", async () => {+ const { files, acl } = await fixture();+ await acl.grant(grant);+ const expected = [{ handlePath: "shared/report.md", fileId: "F1", ownerScopeId: owner, permission: "read" }];+ assert.deepEqual(await acl.handlesFor([recipient]), expected);+ assert.deepEqual(await acl.handlesForAudience([bob], recipient, org, principalEntitledToScope), expected);+ assert.deepEqual(await acl.handlesForAudience([], recipient, org, principalEntitledToScope), []);+ assert.deepEqual(+ await acl.handlesForAudience(+ [bob, { id: "outsider", type: "internal", teamIds: [] }],+ "channel:C1",+ org,+ principalEntitledToScope,+ ),+ [],+ );+ for (const remove of [() => files.setEnabled("F1", false), () => files.delete("F1")]) {+ await remove();+ assert.deepEqual(await acl.handlesFor([recipient]), []);+ assert.deepEqual(await acl.handlesForAudience([bob], recipient, org, principalEntitledToScope), []);+ }+});++test("legacy paths, missing Files records and wrong-owner references never produce handles", async () => {+ const { files } = await fixture();+ const persist: GrantPersistence = {+ all: async () => [+ { ...grant, ref: "reports/report.md" },+ { ...grant, ref: "missing" },+ { ...grant, ownerScopeId: org },+ ],+ put: async () => assert.fail("read-only fixture"),+ remove: async () => assert.fail("read-only fixture"),+ replaceForResourceIfCurrent: async () => assert.fail("read-only fixture"),+ };+ for (const opts of [{}, { resolveFiles: (refs: readonly FileArtifactRef[]) => files.resolveByIds(refs) }]) {+ const acl = createAclStore(persist, opts);+ assert.deepEqual(await acl.handlesFor([recipient]), []);+ assert.deepEqual(await acl.handlesForAudience([bob], recipient, org, principalEntitledToScope), []);+ }+});diff --git a/test/acl-resource-prefix.test.ts b/test/acl-resource-prefix.test.tsindex 90397b8ff..a33822043 100644--- a/test/acl-resource-prefix.test.ts+++ b/test/acl-resource-prefix.test.ts@@ -1,5 +1,7 @@import { test } from "node:test";import assert from "node:assert/strict";+import { createMemoryFileArtifactStore } from "../src/files/file-artifact-store.ts";+import { createMemoryDurableByteStore } from "../src/files/durable-byte-store.ts";import { createAclStore } from "../src/acl/acl-store.ts";import { cronRef, deployRef, encodeRef, parseRef, serviceCredRef, skillRef } from "../src/acl/resource-ref.ts";import { principalEntitledToScope } from "../src/resolution/context-filter.ts";@@ -190,11 +192,22 @@ test("the prefix filters: a deployment grant is never returned for the service-c});test("file handles exclude non-file grants — a skill/cron/deploy grant never becomes a bogus shared/ file", async () => {- const acl = createAclStore();+ const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());+ await files.put({+ id: "F1",+ ownerScopeId: ORG,+ createdBy: "admin",+ name: "doc.md",+ path: "artifacts/F1/doc.md",+ mimetype: "text/markdown",+ data: Buffer.from("hello"),+ direction: "out",+ });+ const acl = createAclStore(undefined, { resolveFiles: (refs) => files.resolveByIds(refs) });const grantee = scopeId("channel", "C");await acl.grant({ownerScopeId: ORG,- ref: "artifacts/F1/doc.md",+ ref: "F1",granteeScopeId: grantee,permission: "read",grantedBy: "admin",@@ -210,14 +223,14 @@ test("file handles exclude non-file grants — a skill/cron/deploy grant never b}const handles = await acl.handlesFor([grantee]);assert.deepEqual(- handles.map((h) => h.ownerPath),- ["artifacts/F1/doc.md"],+ handles.map((h) => h.fileId),+ ["F1"],"only the file grant materializes as a handle",);const audienceHandles = await acl.handlesForAudience([P("U1")], grantee, ORG, principalEntitledToScope);assert.deepEqual(- audienceHandles.map((h) => h.ownerPath),- ["artifacts/F1/doc.md"],+ audienceHandles.map((h) => h.fileId),+ ["F1"],"audience handles exclude skill/cron/deploy/service-cred grants",);});diff --git a/test/acl-revoke-authz.test.ts b/test/acl-revoke-authz.test.tsindex a76cf6b68..679f3bf36 100644--- a/test/acl-revoke-authz.test.ts+++ b/test/acl-revoke-authz.test.ts@@ -6,6 +6,8 @@ import { mkdtempSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import type { AddressInfo } from "node:net";+import { createMemoryFileArtifactStore, type FileArtifactStore } from "../src/files/file-artifact-store.ts";+import { createMemoryDurableByteStore } from "../src/files/durable-byte-store.ts";import { createAclStore } from "../src/acl/acl-store.ts";import { createInsecureTestServer } from "../src/api/server.ts";import { buildApp } from "../src/wiring.ts";@@ -17,31 +19,51 @@ const carol = scopeId("personal", "U2");const org = scopeId("org", "default-org");const grant = (over: Partial<Grant> = {}): Grant => ({ownerScopeId: owner,- ref: "redline.md",+ ref: "F1",granteeScopeId: carol,permission: "read",grantedBy: "U1",...over,});+async function putFile(files: FileArtifactStore, ownerScopeId: string) {+ await files.put({+ id: "F1",+ ownerScopeId,+ createdBy: "U1",+ name: "redline.md",+ path: "artifacts/F1/redline.md",+ mimetype: "text/markdown",+ data: Buffer.from("hello"),+ direction: "out",+ });+}++async function fileAcl(ownerScopeId: string) {+ const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());+ await putFile(files, ownerScopeId);+ return createAclStore(undefined, { resolveFiles: (refs) => files.resolveByIds(refs) });+}+test("revoke has the same owner check as grant: a non-owner cannot revoke a personal-scope grant", async () => {- const acl = createAclStore();+ const acl = await fileAcl(owner);await acl.grant(grant());- await assert.rejects(acl.revoke(owner, "redline.md", carol, "U2"), /only a manager/);- assert.equal((await acl.grantsFor(owner, "redline.md")).length, 1, "the grant survives the rejected revoke");- await acl.revoke(owner, "redline.md", carol, "U1");- assert.equal((await acl.grantsFor(owner, "redline.md")).length, 0, "the owner can revoke");+ await assert.rejects(acl.revoke(owner, "F1", carol, "U2"), /only a manager/);+ assert.equal((await acl.grantsFor(owner, "F1")).length, 1, "the grant survives the rejected revoke");+ await acl.revoke(owner, "F1", carol, "U1");+ assert.equal((await acl.grantsFor(owner, "F1")).length, 0, "the owner can revoke");});test("org-owned grants have no single owner, so revoke is not owner-gated (same as grant)", async () => {- const acl = createAclStore();+ const acl = await fileAcl(org);await acl.grant(grant({ ownerScopeId: org, grantedBy: "admin" }));- await acl.revoke(org, "redline.md", carol, "someone-else");- assert.equal((await acl.grantsFor(org, "redline.md")).length, 0);+ await acl.revoke(org, "F1", carol, "someone-else");+ assert.equal((await acl.grantsFor(org, "F1")).length, 0);});test("POST /v1/grants/revoke requires revokedBy and rejects a non-owner", async () => {const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "revoke-")) }));+ await putFile(built.files, owner);const server = createInsecureTestServer(built.app);server.listen(0);const base = `http://localhost:${(server.address() as AddressInfo).port}`;@@ -50,27 +72,27 @@ test("POST /v1/grants/revoke requires revokedBy and rejects a non-owner", asynctry {assert.equal((await post("/v1/grants", grant())).status, 200);- const missing = await post("/v1/grants/revoke", { ownerScopeId: owner, ref: "redline.md", granteeScopeId: carol });+ const missing = await post("/v1/grants/revoke", { ownerScopeId: owner, ref: "F1", granteeScopeId: carol });assert.equal(missing.status, 400, "revokedBy is required");const forged = await post("/v1/grants/revoke", {ownerScopeId: owner,- ref: "redline.md",+ ref: "F1",granteeScopeId: carol,revokedBy: "U2",});assert.equal(forged.status, 400);assert.equal(((await forged.json()) as { error: string }).error, "revoke_failed");- assert.equal((await built.acl.grantsFor(owner, "redline.md")).length, 1, "the grant survives");+ assert.equal((await built.acl.grantsFor(owner, "F1")).length, 1, "the grant survives");const legit = await post("/v1/grants/revoke", {ownerScopeId: owner,- ref: "redline.md",+ ref: "F1",granteeScopeId: carol,revokedBy: "U1",});assert.equal(legit.status, 200);- assert.equal((await built.acl.grantsFor(owner, "redline.md")).length, 0);+ assert.equal((await built.acl.grantsFor(owner, "F1")).length, 0);} finally {await new Promise<void>((r) => server.close(() => r()));}diff --git a/test/agent-tools.test.ts b/test/agent-tools.test.tsindex 975ee7f09..cf6a84e6b 100644--- a/test/agent-tools.test.ts+++ b/test/agent-tools.test.ts@@ -20,7 +20,11 @@ function fakeToolContext(sink?: { lastExecOpts?: Parameters<ToolContext["executeasync attach(files) {return {ok: true,- files: files.map((name) => ({ name, mimetype: "text/plain", sizeBytes: 1 })),+ files: files.map((name) => ({+ name: typeof name === "string" ? name : name.file_id,+ mimetype: "text/plain",+ sizeBytes: 1,+ })),staged: files.length,};},@@ -39,14 +43,7 @@ function fakeToolContext(sink?: { lastExecOpts?: Parameters<ToolContext["execute? { content: "data", sourceScopeId: "personal:U1" }: { content: null, sourceScopeId: null };},- async write(_path, _data, share) {- return {- shared: (share ?? []).map((s) => ({- scope: s.scope === "org" ? "org:default-org" : s.scope,- permission: s.permission ?? "read",- })),- };- },+ async write() {},async publish(input) {return {id: "dep-1",@@ -397,7 +394,7 @@ test("each agent tool emits a tool_call then a tool_result", async () => {await call(execute, { command: "echo hi", purpose: "Run test command" });await call(read, { action: "read", path: "a.txt" });await call(write, { action: "write", path: "out.txt", data: "xyz" });- await call(write, { action: "share", path: "out.txt", scope: "org" });+ await call(write, { action: "share", id: "file-id", toScope: "org" });assert.deepEqual(emitted.map((e) => `${e.type}:${e.payload.tool}`),@@ -415,7 +412,7 @@ test("each agent tool emits a tool_call then a tool_result", async () => {assert.equal(emitted[1]!.payload.code, 0);assert.equal(emitted[3]!.payload.found, true);assert.equal(emitted[5]!.payload.bytes, 3);- assert.equal(emitted[7]!.payload.shared[0].scope, "org:default-org");+ assert.equal(emitted[7]!.payload.verb, "share");assert.equal(emitted.every((e) => e.scopeLabel === "personal:U1"),true,@@ -1379,7 +1376,7 @@ test("each action dispatches to exactly its matching tool-context method", async} as unknown as ToolContext;const slack = surfaceTool({ current: tc, scopeLabel: "channel:C1" });- await call(slack, { action: "post", text: "hi" });+ await call(slack, { action: "post", text: "hi", files: [{ file_id: "saved" }], sandbox_id: "box" });await call(slack, { action: "react", ts: "1.1", emoji: "eyes" });await call(slack, { action: "edit", ref: "1.1", text: "y" });await call(slack, { action: "delete", ref: "1.1" });@@ -1388,14 +1385,14 @@ test("each action dispatches to exactly its matching tool-context method", asyncawait call(slack, { action: "search", query: "q", source: "slack" });await call(slack, { action: "read_members" });await call(slack, { action: "read_file", ref: "aaaa" });- await call(slack, { action: "reach", text: "hi", channel: "eng" });+ await call(slack, { action: "reach", text: "hi", channel: "eng", files: ["report.md"], sandbox_id: "box" });assert.deepEqual(calls.map((c) => c[0]),["post", "react", "edit", "delete", "readThread", "whatsNew", "search", "readMembers", "readFile", "reach"],);- assert.deepEqual(calls[0]![1], ["hi", {}, undefined]);- assert.deepEqual(calls[9]![1], ["hi", { channel: "eng" }, undefined]);+ assert.deepEqual(calls[0]![1], ["hi", {}, [{ file_id: "saved" }], "box"]);+ assert.deepEqual(calls[9]![1], ["hi", { channel: "eng" }, ["report.md"], "box"]);assert.deepEqual(calls[1]![1], [{ ts: "1.1", emoji: "eyes" }]);assert.deepEqual(calls[2]![1], [{ ref: "1.1", text: "y" }]);assert.deepEqual(calls[3]![1], [{ ref: "1.1" }]);@@ -3638,7 +3635,7 @@ test("resource catalog exposes one home per operation and leaves MCP tools intac["files", { action: "read", path: "a" }, { action: "read", path: "a", data: "oops" }],["files",- { action: "share", path: "a", scope: "org" },+ { action: "share", id: "file-id", toScope: "org" },{ action: "write", path: "a", data: "x", share: [{ scope: "org" }] },],[@@ -3669,7 +3666,6 @@ test("resource actions preserve sharing targets, transfer semantics and file con...fakeToolContext(),async write(...args: Parameters<ToolContext["write"]>) {writes.push(args);- return { shared: [{ scope: "org:test", permission: "read" as const }] };},async setDeploymentPublic(id: string, isPublic: boolean) {publicChanges.push({ id, isPublic });@@ -3683,12 +3679,18 @@ test("resource actions preserve sharing targets, transfer semantics and file conconst tools = createAgentTools({ current: tc }, { controlTools: true });const files = tools.find((tool) => tool.name === "files")!;await call(files, { action: "write", path: "notes", data: "" });- await call(files, { action: "share", path: "notes", scope: "org" });- assert.deepEqual(writes, [- ["notes", ""],- ["notes", undefined, [{ scope: "org", permission: undefined }]],- ]);+ const pathShare = { action: "share", path: "notes", scope: "org", sandbox_id: "sb1" };+ assert.ok(Check(files.parameters, pathShare));+ const rejected = await call(files, pathShare);+ assert.match(textOut(rejected), /upload it with POST \/v1\/files\/uploads first/);+ assert.deepEqual(writes, [["notes", "", undefined]]);+ const invalidAppShare = { action: "share", id: "app", toScope: "org", unknown: true };+ const apps = tools.find((tool) => tool.name === "apps")!;+ assert.ok(Check(apps.parameters, invalidAppShare));+ assert.match(textOut(await call(apps, invalidAppShare)), /Invalid arguments/);+ assert.deepEqual(shares, []);for (const [name, type, action] of [+ ["files", "file", "share"],["apps", "deploy", "share"],["apps", "deploy", "move"],["skills", "skill", "share"],diff --git a/test/claude-harness.test.ts b/test/claude-harness.test.tsindex 5ad44917a..3cdb34740 100644--- a/test/claude-harness.test.ts+++ b/test/claude-harness.test.ts@@ -180,7 +180,7 @@ test("resource tools register with the actual Claude SDK and preserve flat argumtest("native children retain publication and file work without gaining artifact transfers", async () => {const { nativeChildToolAllowed } = await import("../src/harness/harness-shared.ts");assert.equal(nativeChildToolAllowed("apps", { action: "publish" }), true);- assert.equal(nativeChildToolAllowed("files", { action: "share", path: "notes", scope: "org" }), true);+ assert.equal(nativeChildToolAllowed("files", { action: "share", path: "notes", scope: "org" }), false);for (const [name, args] of [["apps", { action: "move" }],["apps", { action: "share" }],diff --git a/test/core-search.test.ts b/test/core-search.test.tsindex 3ed11b41c..48e3d9973 100644--- a/test/core-search.test.ts+++ b/test/core-search.test.ts@@ -180,7 +180,7 @@ test("file search retains common artifact identities when viewers own differentcreatedBy: author.id,createdInScope: project,name: "pelican.txt",- path: id,+ path: artifactPath(id, "pelican.txt"),mimetype: "text/plain",data: Buffer.from("pelican launch"),direction: "in",@@ -221,7 +221,7 @@ test("file search still reaches shared artifacts outside the first document pageconst id = "shared-search-" + n;await built.files.put({id,- path: id,+ path: artifactPath(id, "pelican.txt"),ownerScopeId,createdBy: "[email protected]",name: "note.txt",diff --git a/test/file-artifact-store.test.ts b/test/file-artifact-store.test.tsindex e33d54f24..3890be5a8 100644--- a/test/file-artifact-store.test.ts+++ b/test/file-artifact-store.test.ts@@ -1,4 +1,4 @@-import { assertDocumentListing } from "./support/file-document-listing.ts";+import { assertDocumentListing, assertSharedRecordIdentity } from "./support/file-document-listing.ts";import { test } from "node:test";import assert from "node:assert/strict";import { mkdtemp, readdir, rm } from "node:fs/promises";@@ -180,23 +180,19 @@ test("listOwnedByScopes: nameQuery matches names case-insensitively across the wassert.equal((await store.listOwnedByScopes([owner], { nameQuery: "missing" })).files.length, 0);});-test("resolveByOwnerPaths returns the SHARED set by (owner, path); disabled excluded", async () => {+test("resolveByIds returns the SHARED set by (owner, id); disabled excluded", async () => {const store = createMemoryFileArtifactStore(createMemoryDurableByteStore());await store.put(put({ id: "a", path: "p/a", data: Buffer.from("a") }));await store.put(put({ id: "b", path: "p/b", data: Buffer.from("b") }));- const hit = await store.resolveByOwnerPaths([{ ownerScopeId: owner, path: "p/a" }]);+ const hit = await store.resolveByIds([{ ownerScopeId: owner, id: "a" }]);assert.deepEqual(hit.map((f) => f.id),["a"],);await store.setEnabled("a", false);- assert.equal(- (await store.resolveByOwnerPaths([{ ownerScopeId: owner, path: "p/a" }])).length,- 0,- "disabled excluded",- );+ assert.equal((await store.resolveByIds([{ ownerScopeId: owner, id: "a" }])).length, 0, "disabled excluded");assert.equal(await store.get("a"), null, "get hides disabled by default");assert.ok(await store.get("a", { includeDisabled: true }), "get can surface disabled");});@@ -243,3 +239,7 @@ test("local stream failure removes partial bytes and publishes nothing", async (await rm(dir, { recursive: true, force: true });}});++test("shared file refs authorize only the exact record ID", async () => {+ await assertSharedRecordIdentity(createMemoryFileArtifactStore(createMemoryDurableByteStore()));+});diff --git a/test/file-channel-share.test.ts b/test/file-channel-share.test.tsindex e4f5e06e4..77463f453 100644--- a/test/file-channel-share.test.ts+++ b/test/file-channel-share.test.ts@@ -48,9 +48,9 @@ function registration(seed: "run-1",...(grantees.length? {- onRegistered: async ({ ownerScopeId, path }) => {+ onRegistered: async ({ ownerScopeId, id }) => {for (const granteeScopeId of grantees) {- await acl.grant({ ownerScopeId, ref: path, granteeScopeId, permission: "read", grantedBy: initiator });+ await acl.grant({ ownerScopeId, ref: id, granteeScopeId, permission: "read", grantedBy: initiator });}},}@@ -64,7 +64,7 @@ function makeApp(files: FileArtifactStore, acl: ReturnType<typeof createAclStoretest("a file delivered in a PUBLIC channel is auto-shared (read) with the org — visible to other members", async () => {const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());- const acl = createAclStore();+ const acl = createAclStore(undefined, { resolveFiles: (refs) => files.resolveByIds(refs) });await collectNamedOutbound(memSandbox({ "flag.png": PNG }),HANDLE,@@ -87,7 +87,7 @@ test("a file delivered in a PUBLIC channel is auto-shared (read) with the orgtest("a file delivered in a DM stays owner-only — no auto-share", async () => {const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());- const acl = createAclStore();+ const acl = createAclStore(undefined, { resolveFiles: (refs) => files.resolveByIds(refs) });await collectNamedOutbound(memSandbox({ "note.txt": Buffer.from("private") }),HANDLE,diff --git a/test/file-share.test.ts b/test/file-share.test.tsindex fc21ac372..1a78a67f7 100644--- a/test/file-share.test.ts+++ b/test/file-share.test.ts@@ -7,239 +7,134 @@ import { carriedFileHandles } from "../src/resolution/sharing-access.ts";import { createToolContext } from "../src/tools/primitives.ts";import { createLocalWorkspaceStore } from "../src/workspace/workspace-store.ts";import { createAclStore } from "../src/acl/acl-store.ts";-import { artifactPath, createMemoryFileArtifactStore, fileArtifactId } from "../src/files/file-artifact-store.ts";+import { createMemoryFileArtifactStore, fileArtifactId } from "../src/files/file-artifact-store.ts";import { createMemoryDurableByteStore } from "../src/files/durable-byte-store.ts";-import { createAuditLog } from "../src/audit/audit-log.ts";import { principalEntitledToScope } from "../src/resolution/context-filter.ts";-import { scopeId, type Principal, type WorkspaceLayer } from "../src/types.ts";-import type { Sandbox, SandboxHandle } from "../src/sandbox/sandbox.ts";+import { scopeId, type Principal } from "../src/types.ts";+import type { Sandbox } from "../src/sandbox/sandbox.ts";+import { createAttachStaging } from "../src/core/orchestrator/attach-tool.ts";+import { createMemoryBlobTransferStore, collectBlob } from "../src/persistence/blob-transfer.ts";const person = (id: string, teamIds?: string[]): Principal => ({id,type: "internal",...(teamIds ? { teamIds } : {}),});--const ws = () => createLocalWorkspaceStore(mkdtempSync(join(tmpdir(), "fshare-")));--const sameBytes = (a: Uint8Array | null | undefined, b: Uint8Array) => assert.deepEqual([...(a ?? [])], [...b]);-const JPEG = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0xff]);+const owner = scopeId("personal", "U1");+const grantee = scopeId("personal", "U2");-function memSandbox(seed: Record<string, Uint8Array> = {}): { sandbox: Sandbox; files: Map<string, Uint8Array> } {- const files = new Map<string, Uint8Array>(Object.entries(seed));- const sandbox = {- async writeFile(_h: SandboxHandle, rel: string, data: string) {- files.set(rel, new TextEncoder().encode(data));- },- async readFile(_h: SandboxHandle, rel: string) {- const b = files.get(rel);- return b ? new TextDecoder().decode(b) : null;- },- async writeFileBytes(_h: SandboxHandle, rel: string, data: Uint8Array) {- files.set(rel, data);- },- async readFileBytes(_h: SandboxHandle, rel: string) {- return files.get(rel) ?? null;- },- } as unknown as Sandbox;- return { sandbox, files };+function fixture() {+ const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());+ return { files, acl: createAclStore(undefined, { resolveFiles: (refs) => files.resolveByIds(refs) }) };}-function toolCtx(opts: {- scope: string;- workspace: ReturnType<typeof createLocalWorkspaceStore>;- sandbox: Sandbox;- acl: ReturnType<typeof createAclStore>;- auditLog?: ReturnType<typeof createAuditLog>;- layers?: WorkspaceLayer[];- grantedHandles?: Awaited<ReturnType<ReturnType<typeof createAclStore>["handlesFor"]>>;- sharedMaterializeDir?: string;- createdBy?: string;-}) {- return createToolContext({- sandbox: opts.sandbox,- provision: async () => ({ id: "h", rootDir: "/workspace" }) as SandboxHandle,- layers: opts.layers ?? [{ scopeId: opts.scope, mountPath: "", mode: "rw" }],- commandPolicy: () => ({}) as never,- authorizeCommand: () => false,- grantedHandles: opts.grantedHandles ?? [],- ...(opts.sharedMaterializeDir ? { sharedMaterializeDir: opts.sharedMaterializeDir } : {}),- workspace: opts.workspace,- deploy: {} as never,- acl: opts.acl,- ...(opts.auditLog ? { auditLog: opts.auditLog } : {}),- createdBy: opts.createdBy ?? opts.scope.split(":")[1] ?? opts.scope,- });+async function put(+ files: ReturnType<typeof createMemoryFileArtifactStore>,+ ownerScopeId: string,+ name: string,+ data: Uint8Array,+) {+ const id = fileArtifactId(`${ownerScopeId}:${name}`, "in", 0);+ return (+ await files.put({+ id,+ ownerScopeId,+ createdBy: "U1",+ name,+ path: name,+ mimetype: name.endsWith(".jpg") ? "image/jpeg" : "text/plain",+ data,+ direction: "in",+ })+ ).artifact;}-test("write shares an existing file to a person; the grantee reads it back byte-for-byte", async () => {- const workspace = ws();- const acl = createAclStore();- const auditLog = createAuditLog();- const owner = scopeId("personal", "U1");- const carol = scopeId("personal", "U2");-- const r = await toolCtx({- scope: owner,- workspace,- sandbox: memSandbox({ "orange.jpg": JPEG }).sandbox,- acl,- auditLog,- }).write("orange.jpg", undefined, [{ scope: carol, permission: "read" }]);-- assert.deepEqual(r.shared, [{ scope: carol, permission: "read" }]);- assert.equal((await acl.list()).length, 1);- assert.deepEqual((await acl.list())[0], {- ownerScopeId: owner,- ref: "orange.jpg",- granteeScopeId: carol,- permission: "read",- grantedBy: "U1",+for (const carried of [false, true]) {+ test(`${carried ? "carried" : "explicitly shared"} Files records read inline or return a sendable binary ID without a computer`, async () => {+ const { files, acl } = fixture();+ const image = await put(files, owner, "orange.jpg", JPEG);+ const text = await put(files, owner, "notes.txt", Buffer.from("the plan"));+ for (const file of [image, text])+ await acl.grant({+ ownerScopeId: owner,+ ref: file.id,+ granteeScopeId: grantee,+ permission: "read",+ grantedBy: "U1",+ });+ const handles = carried ? await carriedFileHandles([owner], files) : await acl.handlesFor([grantee]);+ const noComputer = async (): Promise<never> => {+ throw new Error("must not provision a computer");+ };+ const ctx = createToolContext({+ sandbox: {} as Sandbox,+ provision: noComputer,+ layers: [{ scopeId: grantee, mountPath: "", mode: "rw" }],+ commandPolicy: () => ({}) as never,+ authorizeCommand: () => false,+ grantedHandles: handles,+ workspace: createLocalWorkspaceStore(mkdtempSync(join(tmpdir(), "fshare-"))),+ files,+ deploy: {} as never,+ acl,+ createdBy: "U2",+ });+ const textHandle = handles.find((handle) => handle.fileId === text.id)!;+ assert.deepEqual(await ctx.read(textHandle.handlePath), {+ content: "the plan",+ sourceScopeId: owner,+ shared: true,+ });+ const imageHandle = handles.find((handle) => handle.fileId === image.id)!;+ assert.deepEqual(await ctx.read(imageHandle.handlePath), {+ content: `[binary file orange.jpg, Files ID ${image.id}; send it by ID]`,+ sourceScopeId: owner,+ shared: true,+ });+ const transfer = createMemoryBlobTransferStore();+ const staging = createAttachStaging({+ sandbox: {} as Sandbox,+ provision: noComputer,+ blobTransfer: transfer,+ fileRegistration: { store: files, ownerScopeId: grantee, createdBy: "U2", seed: "send" },+ openStored: async (id) => {+ if (!handles.some((handle) => handle.fileId === id)) return null;+ const file = await files.get(id);+ const opened = await files.open(id);+ return file && opened ? { ...opened, name: file.name, mimetype: file.mimetype } : null;+ },+ });+ assert.equal((await staging.attach([{ file_id: image.id }])).ok, true);+ const sent = await transfer.open(staging.staged()[0]!.blobId);+ assert.deepEqual(await collectBlob(sent!.stream), Buffer.from(JPEG));});- assert.equal(- (await auditLog.events()).some(- (e) => e.action === "file_share" && e.resource === "orange.jpg" && e.scopeLabel === carol,- ),- true,- );- sameBytes(await workspace.readBytes(owner, "orange.jpg"), JPEG);-- const carolBox = memSandbox();- const got = await toolCtx({- scope: carol,- workspace,- sandbox: carolBox.sandbox,- acl,- grantedHandles: await acl.handlesFor([carol]),- }).read("shared/orange.jpg");-- assert.match(got.content ?? "", /materialized.*shared\/orange\.jpg/);- assert.equal(got.sourceScopeId, owner);- sameBytes(carolBox.files.get("shared/orange.jpg"), JPEG);-});--test("a binary shared file materializes in the current turn's private directory", async () => {- const workspace = ws();- const acl = createAclStore();- const owner = scopeId("personal", "U1");- const grantee = scopeId("personal", "U2");- await workspace.write(owner, "orange.jpg", JPEG);- await acl.grant({- ownerScopeId: owner,- ref: "orange.jpg",- granteeScopeId: grantee,- permission: "read",- grantedBy: "U1",- });-- const box = memSandbox();- const got = await toolCtx({- scope: grantee,- workspace,- sandbox: box.sandbox,- acl,- grantedHandles: await acl.handlesFor([grantee]),- sharedMaterializeDir: "shared/turn-1",- }).read("shared/orange.jpg");-- assert.match(got.content ?? "", /shared\/turn-1\/orange\.jpg/);- sameBytes(box.files.get("shared/turn-1/orange.jpg"), JPEG);- assert.equal(box.files.has("shared/orange.jpg"), false);- const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());- const openHandle = (await carriedFileHandles([owner], workspace, files))[0]!;- const carriedBox = memSandbox();- const blocked = await toolCtx({- scope: grantee,- workspace,- sandbox: carriedBox.sandbox,- acl,- grantedHandles: [openHandle],- }).read(openHandle.handlePath);- assert.match(blocked.content ?? "", /Binary files require an explicit share/);- assert.equal(carriedBox.files.size, 0);- await workspace.write(owner, "notes.txt", "untrusted source text");- const textHandle = (await carriedFileHandles([owner], workspace, files)).find((h) => h.ownerPath === "notes.txt")!;- const text = await toolCtx({- scope: grantee,- workspace,- sandbox: carriedBox.sandbox,- acl,- grantedHandles: [textHandle],- }).read(textHandle.handlePath);- assert.equal(text.shared, true);-});--test("the screenshot scenario: shared to the org in a DM, delivered from a channel session", async () => {- const workspace = ws();- const acl = createAclStore();- const org = scopeId("org", "default-org");- const alice = scopeId("personal", "U1");-- const dmLayers: WorkspaceLayer[] = [- { scopeId: org, mountPath: "global", mode: "ro" },- { scopeId: alice, mountPath: "", mode: "rw" },- ];- const r = await toolCtx({- scope: alice,- workspace,- sandbox: memSandbox({ "orange.jpg": JPEG }).sandbox,- acl,- layers: dmLayers,- }).write("orange.jpg", undefined, [{ scope: "org", permission: "read" }]);- assert.deepEqual(r.shared, [{ scope: org, permission: "read" }], '"org" resolves to the session org scope');-- const channel = scopeId("channel", "C1");- const handles = await acl.handlesFor([channel, org]);- assert.equal(handles.length, 1, "the org-granted file is reachable from the channel session");-- const channelBox = memSandbox();- const got = await toolCtx({- scope: channel,- workspace,- sandbox: channelBox.sandbox,- acl,- grantedHandles: handles,- }).read("shared/orange.jpg");- sameBytes(channelBox.files.get("shared/orange.jpg"), JPEG);- assert.equal(got.sourceScopeId, alice, "the file keeps its owner (Alice) — sharing never moves ownership");-});--test("write can save AND share in one call; a text grant returns inline content", async () => {- const workspace = ws();- const acl = createAclStore();- const owner = scopeId("personal", "U1");- const grantee = scopeId("personal", "U2");+}- const r = await toolCtx({ scope: owner, workspace, sandbox: memSandbox().sandbox, acl }).write(- "notes.md",- "the plan",- [{ scope: grantee, permission: "read" }],+test("workspace paths cannot be granted even when a Files record has that path", async () => {+ const { files, acl } = fixture();+ const file = await put(files, owner, "notes.txt", Buffer.from("the plan"));+ await assert.rejects(+ acl.grant({ ownerScopeId: owner, ref: file.path, granteeScopeId: grantee, permission: "read", grantedBy: "U1" }),+ /Files record ID/,);- assert.deepEqual(r.shared, [{ scope: grantee, permission: "read" }]);- assert.equal(await workspace.read(owner, "notes.md"), "the plan", "the contents were saved durably");-- const box = memSandbox();- const got = await toolCtx({- scope: grantee,- workspace,- sandbox: box.sandbox,- acl,- grantedHandles: await acl.handlesFor([grantee]),- }).read("shared/notes.md");- assert.equal(got.content, "the plan");- assert.equal(box.files.has("shared/notes.md"), false, "text reads stay inline — no sandbox materialization");+ assert.deepEqual(await acl.list(), []);+ await acl.grant({ ownerScopeId: owner, ref: file.id, granteeScopeId: grantee, permission: "read", grantedBy: "U1" });+ assert.deepEqual(await acl.handlesFor([grantee]), [+ { handlePath: "shared/notes.txt", ownerScopeId: owner, fileId: file.id, permission: "read" },+ ]);});test("a person-grant resolves in a shared room of {owner, grantee} — but never leaks to an unentitled member", async () => {- const acl = createAclStore();+ const { files, acl } = fixture();const alice = scopeId("personal", "U1");const carol = scopeId("personal", "U2");const org = scopeId("org", "default-org");const channel = scopeId("channel", "C1");+ const image = await put(files, alice, "orange.jpg", JPEG);await acl.grant({ownerScopeId: alice,- ref: "orange.jpg",+ ref: image.id,granteeScopeId: carol,permission: "read",grantedBy: "U1",@@ -265,14 +160,16 @@ test("a person-grant resolves in a shared room of {owner, grantee} — but never});test("an org grant surfaces for the whole audience; a team grant only when every member is in the team", async () => {- const acl = createAclStore();+ const { files, acl } = fixture();const alice = scopeId("personal", "U1");const org = scopeId("org", "default-org");const channel = scopeId("channel", "C1");- await acl.grant({ ownerScopeId: alice, ref: "poster.png", granteeScopeId: org, permission: "read", grantedBy: "U1" });+ const poster = await put(files, alice, "poster.png", JPEG);+ const playbook = await put(files, alice, "playbook.md", Buffer.from("plan"));+ await acl.grant({ ownerScopeId: alice, ref: poster.id, granteeScopeId: org, permission: "read", grantedBy: "U1" });await acl.grant({ownerScopeId: alice,- ref: "playbook.md",+ ref: playbook.id,granteeScopeId: scopeId("team", "T1"),permission: "read",grantedBy: "U1",@@ -294,119 +191,3 @@ test("an org grant surfaces for the whole audience; a team grant only when every);assert.deepEqual(allInTeam.map((h) => h.handlePath).sort(), ["shared/playbook.md", "shared/poster.png"]);});--test("write without data or share is rejected; sharing a missing file / from a read-only session errors", async () => {- const workspace = ws();- const acl = createAclStore();- const owner = scopeId("personal", "U1");-- await assert.rejects(- () => toolCtx({ scope: owner, workspace, sandbox: memSandbox().sandbox, acl }).write("x.md"),- /needs `data`.*`share`/,- );- await assert.rejects(- () =>- toolCtx({ scope: owner, workspace, sandbox: memSandbox().sandbox, acl }).write("ghost.png", undefined, [- { scope: owner },- ]),- /no such file to share: ghost\.png/,- );- await assert.rejects(- () =>- toolCtx({- scope: owner,- workspace,- sandbox: memSandbox({ "x.png": JPEG }).sandbox,- acl,- layers: [{ scopeId: scopeId("org", "default-org"), mountPath: "global", mode: "ro" }],- }).write("x.png", undefined, [{ scope: "org" }]),- /writable scope/,- );-});--test("a viewer-uploaded artifact (artifacts/<id>/<name>) is readable through its shared handle (public #94)", async () => {- const workspace = ws();- const acl = createAclStore();- const owner = scopeId("personal", "U1");- const grantee = scopeId("personal", "U2");- const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());- const id = fileArtifactId("upload:U1:test:1:x", "in", 0);- const path = artifactPath(id, "notes.txt");- await files.put({- id,- ownerScopeId: owner,- createdBy: "U1",- name: "notes.txt",- path,- mimetype: "text/plain",- data: Buffer.from("hello from the upload"),- direction: "in",- createdInScope: grantee,- });- await acl.grant({ ownerScopeId: owner, ref: path, granteeScopeId: grantee, permission: "read", grantedBy: "U1" });-- const handles = await acl.handlesForAudience([person("U2")], grantee, "org:o", principalEntitledToScope);- assert.equal(handles.length, 1, "the grant materializes as a handle");-- const ctx = createToolContext({- sandbox: memSandbox().sandbox,- provision: async () => ({ id: "h", rootDir: "/workspace" }) as SandboxHandle,- layers: [{ scopeId: grantee, mountPath: "", mode: "rw" }],- commandPolicy: () => ({}) as never,- authorizeCommand: () => false,- grantedHandles: handles,- workspace,- files,- deploy: {} as never,- acl,- createdBy: "U2",- });- const got = await ctx.read(handles[0]!.handlePath);- assert.equal(got.content, "hello from the upload");- assert.equal(got.sourceScopeId, owner);-});--test("a workspace-backed share is never served from a stale artifact snapshot", async () => {- const workspace = ws();- const acl = createAclStore();- const owner = scopeId("personal", "U1");- const grantee = scopeId("personal", "U2");- const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());- // artifact snapshot holds version 1 under the real workspace path- await files.put({- id: fileArtifactId("share:U1:doc.txt", "out", 0),- ownerScopeId: owner,- createdBy: "U1",- name: "doc.txt",- path: "doc.txt",- mimetype: "text/plain",- data: Buffer.from("version 1"),- direction: "out",- createdInScope: owner,- });- // workspace holds version 2- await workspace.write(owner, "doc.txt", "version 2");- await acl.grant({- ownerScopeId: owner,- ref: "doc.txt",- granteeScopeId: grantee,- permission: "read",- grantedBy: "U1",- });- const handles = await acl.handlesForAudience([person("U2")], grantee, "org:o", principalEntitledToScope);- const ctx = createToolContext({- sandbox: memSandbox().sandbox,- provision: async () => ({ id: "h", rootDir: "/workspace" }) as SandboxHandle,- layers: [{ scopeId: grantee, mountPath: "", mode: "rw" }],- commandPolicy: () => ({}) as never,- authorizeCommand: () => false,- grantedHandles: handles,- workspace,- files,- deploy: {} as never,- acl,- createdBy: "U2",- });- const got = await ctx.read(handles[0]!.handlePath);- assert.equal(got.content, "version 2", "the live workspace copy wins for workspace-namespace paths");-});diff --git a/test/file-sharing.test.ts b/test/file-sharing.test.tsindex 637651959..40feadbcb 100644--- a/test/file-sharing.test.ts+++ b/test/file-sharing.test.ts@@ -156,9 +156,9 @@ test("inboundManifest leaves a file unattributed when its author is unknown (mixtest("sharedManifest lists shared/<name> handles, flags writable, dedups, and reads nothing", () => {const handles: GrantedHandle[] = [- { handlePath: "shared/report.txt", ownerScopeId: "personal:U2", ownerPath: "report.txt", permission: "read" },- { handlePath: "shared/budget.xlsx", ownerScopeId: "personal:U3", ownerPath: "budget.xlsx", permission: "write" },- { handlePath: "shared/report.txt", ownerScopeId: "personal:U4", ownerPath: "report.txt", permission: "read" },+ { handlePath: "shared/report.txt", ownerScopeId: "personal:U2", fileId: "1".repeat(32), permission: "read" },+ { handlePath: "shared/budget.xlsx", ownerScopeId: "personal:U3", fileId: "2".repeat(32), permission: "write" },+ { handlePath: "shared/report.txt", ownerScopeId: "personal:U4", fileId: "1".repeat(32), permission: "read" },];const m = sharedManifest(handles);assert.match(m, /shared\/report\.txt/);@@ -168,52 +168,12 @@ test("sharedManifest lists shared/<name> handles, flags writable, dedups, and reassert.equal(sharedManifest([]), "");});-test("sharedManifest excludes non-file grants (credentials, deployments, skills, crons) — they have their own resolvers", () => {- const handles: GrantedHandle[] = [- { handlePath: "shared/report.txt", ownerScopeId: "personal:U2", ownerPath: "report.txt", permission: "read" },- {- handlePath: "shared/service-cred:openai",- ownerScopeId: "org:default-org",- ownerPath: "service-cred:openai",- permission: "read",- },- {- handlePath: "shared/deployment:abc-123",- ownerScopeId: "personal:U2",- ownerPath: "deployment:abc-123",- permission: "read",- },- { handlePath: "shared/skill:s-1", ownerScopeId: "channel:C1", ownerPath: "skill:s-1", permission: "read" },- { handlePath: "shared/cron:k-1", ownerScopeId: "personal:U2", ownerPath: "cron:k-1", permission: "read" },- ];- const m = sharedManifest(handles);- assert.match(m, /shared\/report\.txt/);- assert.doesNotMatch(m, /service-cred/, "credentials are broker-only, not fetchable files");- assert.doesNotMatch(m, /deployment:/, "deployments are a reach target, not a file");- assert.doesNotMatch(m, /skill:/, "a shared skill is reached through the skill resolver, not as a file");- assert.doesNotMatch(m, /cron:/, "a shared cron isn't a fetchable file");- assert.match(m, /^1 file shared with you/, "count reflects only real files");-});--test("sharedManifest renders nothing when every grant is a non-file kind", () => {- const handles: GrantedHandle[] = [- {- handlePath: "shared/service-cred:openai",- ownerScopeId: "org:default-org",- ownerPath: "service-cred:openai",- permission: "read",- },- ];- assert.equal(sharedManifest(handles), "");- assert.equal(sharedFilesSystemSection(handles), "");-});-test("sharedManifest caps the listing at MAX_SHARED_FILES_LISTED with a '…and N more' tail", () => {const total = MAX_SHARED_FILES_LISTED + 7;const handles: GrantedHandle[] = Array.from({ length: total }, (_, i) => ({handlePath: `shared/file-${i}.txt`,ownerScopeId: "personal:U2",- ownerPath: `file-${i}.txt`,+ fileId: i.toString(16).padStart(32, "0"),permission: "read" as const,}));const m = sharedManifest(handles);@@ -232,7 +192,7 @@ test("sharedManifest at exactly the cap lists every file with no '…and N more'const handles: GrantedHandle[] = Array.from({ length: MAX_SHARED_FILES_LISTED }, (_, i) => ({handlePath: `shared/f${i}.txt`,ownerScopeId: "personal:U2",- ownerPath: `f${i}.txt`,+ fileId: i.toString(16).padStart(32, "0"),permission: "read" as const,}));const m = sharedManifest(handles);@@ -242,7 +202,7 @@ test("sharedManifest at exactly the cap lists every file with no '…and N more'test("sharedFilesSystemSection wraps the listing in a ## heading, '' when nothing is shared", () => {const handles: GrantedHandle[] = [- { handlePath: "shared/report.txt", ownerScopeId: "personal:U2", ownerPath: "report.txt", permission: "read" },+ { handlePath: "shared/report.txt", ownerScopeId: "personal:U2", fileId: "1".repeat(32), permission: "read" },];const s = sharedFilesSystemSection(handles);assert.match(s, /^## Files shared with you\n/);@@ -515,7 +475,7 @@ test("attaching a missing, empty, or traversing path stages nothing and says whiassert.match(empty.message, /blank\.txt \(empty\)/);const traversal = await staging.attach(["../../etc/passwd"]);assert.ok(!traversal.ok);- assert.match(traversal.message, /not found/);+ assert.match(traversal.message, /no \.\. path segments/);assert.equal(staging.staged().length, 0, "a failed call stages nothing at all");});diff --git a/test/file-store-population.test.ts b/test/file-store-population.test.tsindex bd3243ccf..4b641d95a 100644--- a/test/file-store-population.test.ts+++ b/test/file-store-population.test.ts@@ -1,15 +1,9 @@import { test } from "node:test";import assert from "node:assert/strict";import { collectNamedOutbound, materializeInbound, type ArtifactRegistration } from "../src/core/attachments.ts";-import { createToolContext } from "../src/tools/primitives.ts";import { createMemoryFileArtifactStore, type FileArtifactStore } from "../src/files/file-artifact-store.ts";import { createMemoryDurableByteStore } from "../src/files/durable-byte-store.ts";import { createMemoryBlobTransferStore } from "../src/persistence/blob-transfer.ts";-import { createLocalWorkspaceStore } from "../src/workspace/workspace-store.ts";-import { createAclStore } from "../src/acl/acl-store.ts";-import { mkdtempSync } from "node:fs";-import { tmpdir } from "node:os";-import { join } from "node:path";import { scopeId } from "../src/types.ts";import type { Sandbox, SandboxHandle } from "../src/sandbox/sandbox.ts";@@ -164,73 +158,3 @@ test("materializeInbound omits artifactId when registration fails or is absent",assert.equal(failed.metas[0]!.artifactId, undefined, "no artifactId is fabricated on a store fault");assert.equal(errors.length, 1);});--test("write+share registers an artifact keyed on the SAME (owner, path) as the grant", async () => {- const store = createMemoryFileArtifactStore(createMemoryDurableByteStore());- const acl = createAclStore();- const workspace = createLocalWorkspaceStore(mkdtempSync(join(tmpdir(), "popshare-")));- const grantee = scopeId("personal", "U2");- const { sandbox } = memSandbox({ "redline.md": "v1 redline" });-- const ctx = createToolContext({- sandbox,- provision: async () => HANDLE,- layers: [{ scopeId: owner, mountPath: "", mode: "rw" }],- commandPolicy: () => ({}) as never,- authorizeCommand: () => false,- grantedHandles: [],- workspace,- deploy: {} as never,- acl,- files: store,- createdBy: "U1",- persistWritesToStore: { excludeDirs: ["inbox"] },- });-- await ctx.write("redline.md", undefined, [{ scope: grantee, permission: "read" }]);-- assert.equal((await acl.grantsFor(owner, "redline.md")).length, 1);- const shared = await store.resolveByOwnerPaths([{ ownerScopeId: owner, path: "redline.md" }]);- assert.equal(shared.length, 1);- assert.equal(shared[0]!.name, "redline.md");- assert.deepEqual(await drain(store, shared[0]!.id), Buffer.from("v1 redline"));-});--test("intentional write+share after deletion creates a fresh visible artifact generation", async () => {- const store = createMemoryFileArtifactStore(createMemoryDurableByteStore());- const acl = createAclStore();- const workspace = createLocalWorkspaceStore(mkdtempSync(join(tmpdir(), "republish-")));- const grantee = scopeId("personal", "U2");- const { sandbox } = memSandbox();- const ctx = createToolContext({- sandbox,- provision: async () => HANDLE,- layers: [{ scopeId: owner, mountPath: "", mode: "rw" }],- commandPolicy: () => ({}) as never,- authorizeCommand: () => false,- grantedHandles: [],- workspace,- deploy: {} as never,- acl,- files: store,- createdBy: "U1",- persistWritesToStore: { excludeDirs: ["inbox"] },- });- const share = [{ scope: grantee, permission: "read" as const }];- await Promise.all([- ctx.write("report.txt", "first generation", share),- ctx.write("report.txt", "first generation", share),- ]);- assert.equal((await store.resolveByOwnerPaths([{ ownerScopeId: owner, path: "report.txt" }])).length, 1);- const first = (await store.resolveByOwnerPaths([{ ownerScopeId: owner, path: "report.txt" }]))[0]!;- await ctx.write("report.txt", undefined, share);- assert.equal((await store.resolveByOwnerPaths([{ ownerScopeId: owner, path: "report.txt" }])).length, 1);- await store.delete(first.id);- await ctx.write("report.txt", "new generation", share);- const current = await store.resolveByOwnerPaths([{ ownerScopeId: owner, path: "report.txt" }]);- assert.equal(current.length, 1);- assert.notEqual(current[0]!.id, first.id);- assert.deepEqual(await drain(store, current[0]!.id), Buffer.from("new generation"));- assert.equal(await store.get(first.id, { includeDisabled: true }), null);- await assert.rejects(store.publish({ ...first, blobKey: first.blobKey! }), /deleted/);-});diff --git a/test/files-http.test.ts b/test/files-http.test.tsindex f6c8ae3c1..fcf6e374b 100644--- a/test/files-http.test.ts+++ b/test/files-http.test.ts@@ -62,7 +62,7 @@ async function drain(stream: NodeJS.ReadableStream): Promise<Buffer> {test("owner sees their own file in owned[] and can open its bytes", async () => {const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());- const app = makeApp(files, createAclStore());+ const app = makeApp(files, createAclStore(undefined, { resolveFiles: (refs) => files.resolveByIds(refs) }));const id = fileArtifactId("run-1", "out", 0);await files.put({id,@@ -88,7 +88,7 @@ test("owner sees their own file in owned[] and can open its bytes", async () =>test("a grantee sees a shared file in shared[] and can open it; the owner doesn't double-list it", async () => {const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());- const acl = createAclStore();+ const acl = createAclStore(undefined, { resolveFiles: (refs) => files.resolveByIds(refs) });const app = makeApp(files, acl);const owner = scopeId("personal", "U1");const id = fileArtifactId("share", "out", 0);@@ -104,7 +104,7 @@ test("a grantee sees a shared file in shared[] and can open it; the owner doesn'});await acl.grant({ownerScopeId: owner,- ref: "redline.md",+ ref: id,granteeScopeId: scopeId("personal", "U2"),permission: "read",grantedBy: "U1",@@ -123,7 +123,7 @@ test("a grantee sees a shared file in shared[] and can open it; the owner doesn'test("a stranger sees nothing and cannot open the file (404 = null)", async () => {const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());- const app = makeApp(files, createAclStore());+ const app = makeApp(files, createAclStore(undefined, { resolveFiles: (refs) => files.resolveByIds(refs) }));const id = fileArtifactId("run-1", "out", 0);await files.put({id,@@ -144,7 +144,7 @@ test("a stranger sees nothing and cannot open the file (404 = null)", async () =test("an org grant surfaces the file to any org member", async () => {const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());- const acl = createAclStore();+ const acl = createAclStore(undefined, { resolveFiles: (refs) => files.resolveByIds(refs) });const app = makeApp(files, acl);const owner = scopeId("personal", "U1");const id = fileArtifactId("orgshare", "out", 0);@@ -160,7 +160,7 @@ test("an org grant surfaces the file to any org member", async () => {});await acl.grant({ownerScopeId: owner,- ref: "poster.png",+ ref: id,granteeScopeId: scopeId("org", ORG),permission: "read",grantedBy: "U1",@@ -194,14 +194,14 @@ test("openFileForViewer returns null when the bytes are gone (a backfilled histoget: async () => row,open: async () => null,} as unknown as FileArtifactStore;- const app = makeApp(files, createAclStore());+ const app = makeApp(files, createAclStore(undefined, { resolveFiles: (refs) => files.resolveByIds(refs) }));assert.equal(await app.openFileForViewer(id, "U1"), null, "owner is authorized but the bytes are unavailable → 404");});test("uploadFileForViewer stores a personal inbound file", async () => {const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());- const app = makeUploadApp(files, createAclStore());+ const app = makeUploadApp(files, createAclStore(undefined, { resolveFiles: (refs) => files.resolveByIds(refs) }));const file = await app.uploadFileForViewer("U1", {name: "../notes.txt",@@ -223,7 +223,7 @@ test("uploadFileForViewer stores a personal inbound file", async () => {test("uploadFileForViewer to a shared context is visible to another context member", async () => {const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());- const acl = createAclStore();+ const acl = createAclStore(undefined, { resolveFiles: (refs) => files.resolveByIds(refs) });const app = makeUploadApp(files, acl);const file = await app.uploadFileForViewer("U1", {@@ -234,7 +234,7 @@ test("uploadFileForViewer to a shared context is visible to another context memb});assert.ok(file);assert.equal(file!.createdInScope, channel);- const grants = await acl.grantsFor(scopeId("personal", "U1"), `artifacts/${file!.id}/brief.pdf`);+ const grants = await acl.grantsFor(scopeId("personal", "U1"), file!.id);assert.equal(grants.some((g) => g.granteeScopeId === channel),true,@@ -250,7 +250,7 @@ test("uploadFileForViewer to a shared context is visible to another context membtest("scoped file listing pages within the requested context", async () => {const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());- const app = makeUploadApp(files, createAclStore());+ const app = makeUploadApp(files, createAclStore(undefined, { resolveFiles: (refs) => files.resolveByIds(refs) }));await app.uploadFileForViewer("U1", {name: "personal.txt",mimetype: "text/plain",@@ -273,7 +273,7 @@ test("scoped file listing pages within the requested context", async () => {test("project files collapse across contributors and turns before paging owned and shared documents", async () => {const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());- const acl = createAclStore();+ const acl = createAclStore(undefined, { resolveFiles: (refs) => files.resolveByIds(refs) });const app = makeUploadApp(files, acl);const ledger: string[] = [];for (const [turn, author, documents] of [@@ -297,7 +297,7 @@ test("project files collapse across contributors and turns before paging owned acreatedInScope: channel,createdAt: turn * 100,});- await acl.grant({ ownerScopeId, ref: path, granteeScopeId: channel, permission: "read", grantedBy: author });+ await acl.grant({ ownerScopeId, ref: id, granteeScopeId: channel, permission: "read", grantedBy: author });ledger.push(id);}}@@ -326,7 +326,7 @@ test("project files collapse across contributors and turns before paging owned afor (const authors of [["U1"], ["U2"], ["U1", "U2"]]) {test("scope resources drain file pages for " + authors.join(" and "), async () => {const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());- const acl = createAclStore();+ const acl = createAclStore(undefined, { resolveFiles: (refs) => files.resolveByIds(refs) });const app = makeUploadApp(files, acl);for (let n = 0; n < 55; n++) {for (const [index, author] of authors.entries()) {@@ -345,7 +345,7 @@ for (const authors of [["U1"], ["U2"], ["U1", "U2"]]) {createdInScope: channel,createdAt: n * 2 + index,});- await acl.grant({ ownerScopeId, ref: path, granteeScopeId: channel, permission: "read", grantedBy: author });+ await acl.grant({ ownerScopeId, ref: id, granteeScopeId: channel, permission: "read", grantedBy: author });}}const resources = await app.listScopeResources("U1", channel);@@ -355,3 +355,43 @@ for (const authors of [["U1"], ["U2"], ["U1", "U2"]]) {assert.equal(resources?.files.filter((file) => file.ownerScopeId === scopeId("personal", author)).length, 55);});}++test("file grants name one Files record, not its path or another generation", async () => {+ const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());+ const acl = createAclStore(undefined, { resolveFiles: (refs) => files.resolveByIds(refs) });+ const app = makeUploadApp(files, acl);+ const ownerScopeId = scopeId("personal", "U1");+ const input = {+ ownerScopeId,+ createdBy: "U1",+ name: "report.txt",+ path: "report.txt",+ mimetype: "text/plain",+ direction: "out" as const,+ };+ const original = (await files.put({ ...input, id: "original", data: Buffer.from("old") })).artifact;+ const replacement = (await files.put({ ...input, id: "replacement", data: Buffer.from("new") })).artifact;+ const grant = {+ ownerScopeId,+ granteeScopeId: scopeId("personal", "U2"),+ permission: "read" as const,+ grantedBy: "U1",+ };+ for (const ref of [input.path, "artifacts/original/report.txt", "nonexistent"])+ await assert.rejects(app.grant({ ...grant, ref }), /put the file in Files first using POST \/v1\/files\/uploads/);+ assert.deepEqual(await acl.list(), []);+ await app.grant({ ...grant, ref: original.id });+ const metadata = await app.getArtifactHome("file", original.id);+ assert.equal(metadata?.grantRef, original.id);+ assert.deepEqual(+ (await app.listFilesForViewer("U2")).shared.map((file) => file.id),+ [original.id],+ );+ const opened = await app.openFileForViewer(original.id, "U2");+ assert.ok(opened);+ assert.equal((await drain(opened.stream)).toString(), "old");+ assert.equal(await app.openFileForViewer(replacement.id, "U2"), null);+ await files.delete(original.id);+ assert.deepEqual((await app.listFilesForViewer("U2")).shared, []);+ assert.equal(await app.openFileForViewer(replacement.id, "U2"), null);+});diff --git a/test/memory-file-routing.test.ts b/test/memory-file-routing.test.tsindex 49ed957ef..220d5f8ff 100644--- a/test/memory-file-routing.test.ts+++ b/test/memory-file-routing.test.ts@@ -63,7 +63,6 @@ function harness(opts: { memoryStart?: string; recall?: boolean } = {}) {memory,memoryScopeId: personal,memoryAccess: { write: personal, read: opts.recall === false ? [] : [personal] },- persistWritesToStore: { excludeDirs: [] },});return { ctx, wsWrites, sandboxFiles, getDurable: () => durable };}diff --git a/test/orchestrator.test.ts b/test/orchestrator.test.tsindex 086d72e56..9496021ba 100644--- a/test/orchestrator.test.ts+++ b/test/orchestrator.test.ts@@ -1894,7 +1894,7 @@ test("a file posted in a GROUP conversation is granted read to the conversation);assert.notEqual(t.status, "error");const handles = await acl.handlesFor([scopeId("group", "G9")]);- const fileHandle = handles.find((h) => h.ownerPath.endsWith("/flag.png"));+ const fileHandle = handles.find((h) => h.handlePath === "shared/flag.png");assert.ok(fileHandle, "the posted file is granted to the conversation scope");assert.equal(fileHandle!.ownerScopeId, scopeId("personal", "U1"));});@@ -1925,7 +1925,7 @@ test("a file posted in a GROUP conversation is granted read to the conversation);assert.notEqual(t.status, "error");const handles = await acl.handlesFor([scopeId("group", "G9")]);- const fileHandle = handles.find((h) => h.ownerPath.endsWith("/flag.png"));+ const fileHandle = handles.find((h) => h.handlePath === "shared/flag.png");assert.ok(fileHandle, "the posted file is granted to the conversation scope");assert.equal(fileHandle!.ownerScopeId, scopeId("personal", "U1"));});@@ -1934,9 +1934,19 @@ test("a file shared with the session is LISTED in the cached system prompt — wconst built = freshApp();const { app, acl } = built;const boxes = spyProvisioning(built.sandbox);- acl.grant({+ await built.files.put({+ id: "budget-file",ownerScopeId: scopeId("personal", "U2"),- ref: "budget.csv",+ createdBy: "U2",+ name: "budget.csv",+ path: "budget.csv",+ mimetype: "text/csv",+ data: Buffer.from("amount\n10"),+ direction: "out",+ });+ await acl.grant({+ ownerScopeId: scopeId("personal", "U2"),+ ref: "budget-file",granteeScopeId: scopeId("personal", "U1"),permission: "read",grantedBy: "U2",diff --git a/test/postgres-acl-file-id-migration.test.ts b/test/postgres-acl-file-id-migration.test.tsnew file mode 100644index 000000000..5f3d1cf03--- /dev/null+++ b/test/postgres-acl-file-id-migration.test.ts@@ -0,0 +1,84 @@+import { test, after } from "node:test";+import assert from "node:assert/strict";+import { randomBytes } from "node:crypto";+import { createPostgresGrantStore } from "../src/acl/postgres-grant-store.ts";+import { createPostgresFileArtifactStore } from "../src/files/postgres-file-artifact-store.ts";+import { createMemoryDurableByteStore } from "../src/files/durable-byte-store.ts";+import { migrateRegisteredPgSchemas } from "../src/persistence/pg-pool.ts";++const BASE = process.env.DATABASE_URL;+const skip = BASE ? false : "set DATABASE_URL (a Postgres) to run the ACL file-ID migration test";+const schema = `acl_file_ids_${randomBytes(4).toString("hex")}`;++after(async () => {+ if (!BASE) return;+ const pg = (await import("pg")).default;+ const admin = new pg.Pool({ connectionString: BASE });+ await admin.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`);+ await admin.end();+});++test("file grants move from owner paths to enabled Files record IDs", { skip }, async () => {+ const pg = (await import("pg")).default;+ const admin = new pg.Pool({ connectionString: BASE });+ await admin.query(`CREATE SCHEMA ${schema}`);+ const url = new URL(BASE!);+ url.searchParams.set("options", `-c search_path=${schema}`);+ const db = url.toString();+ const grants = createPostgresGrantStore(db);+ createPostgresFileArtifactStore(db, createMemoryDurableByteStore());+ await migrateRegisteredPgSchemas(db);+ const pool = new pg.Pool({ connectionString: db });+ try {+ await pool.query("DELETE FROM qm_schema_migrations WHERE id = 'acl/grants/0003-file-ids'");+ const file = (id: string, owner: string, path: string, createdAt: number, enabled = true) =>+ pool.query(+ `INSERT INTO file_artifacts (id, owner_scope_id, path, name, mimetype, size_bytes, direction, created_by, created_at, updated_at, enabled)+ VALUES ($1, $2, $3, 'a.md', 'text/markdown', 1, 'out', 'U1', $4, $4, $5)`,+ [id, owner, path, createdAt, enabled],+ );+ await file("old", "personal:U1", "reports/a.md", 1);+ await file("new", "personal:U1", "reports/a.md", 2);+ await file("gone", "personal:U1", "reports/a.md", 3, false);+ await file("theirs", "personal:U9", "reports/b.md", 1);+ await file("kept", "personal:U1", "reports/c.md", 1);+ const rows: [string, string, string, string][] = [+ ["reports/a.md", "personal:U2", "read", "path-grantor"],+ ["reports/a.md", "personal:U3", "read", "path-grantor"],+ ["new", "personal:U3", "read", "id-grantor"],+ ["reports/b.md", "personal:U2", "read", "U1"],+ ["reports/missing.md", "personal:U2", "read", "U1"],+ ["gone", "personal:U2", "read", "U1"],+ ["theirs", "personal:U2", "read", "U1"],+ ["kept", "personal:U2", "write", "U1"],+ ["skill:s1", "personal:U2", "use", "U1"],+ ["deployment:d1", "personal:U2", "read", "U1"],+ ["cron:c1", "personal:U2", "manage", "U1"],+ ["service-cred:github", "personal:U2", "use", "U1"],+ ];+ for (const [path, grantee, permission, by] of rows) {+ await pool.query(+ "INSERT INTO acl_grants (owner_scope_id, path, grantee_scope_id, permission, granted_by) VALUES ('personal:U1', $1, $2, $3, $4)",+ [path, grantee, permission, by],+ );+ }++ await migrateRegisteredPgSchemas(db);++ assert.deepEqual(+ (await grants.all()).map((g) => [g.ref, g.granteeScopeId, g.permission, g.grantedBy]),+ [+ ["cron:c1", "personal:U2", "manage", "U1"],+ ["deployment:d1", "personal:U2", "read", "U1"],+ ["kept", "personal:U2", "write", "U1"],+ ["new", "personal:U2", "read", "path-grantor"],+ ["new", "personal:U3", "read", "id-grantor"],+ ["service-cred:github", "personal:U2", "use", "U1"],+ ["skill:s1", "personal:U2", "use", "U1"],+ ],+ );+ } finally {+ await pool.end();+ await admin.end();+ }+});diff --git a/test/postgres-file-artifact-store.test.ts b/test/postgres-file-artifact-store.test.tsindex e442f0369..04edd33e8 100644--- a/test/postgres-file-artifact-store.test.ts+++ b/test/postgres-file-artifact-store.test.ts@@ -1,4 +1,4 @@-import { assertDocumentListing } from "./support/file-document-listing.ts";+import { assertDocumentListing, assertSharedRecordIdentity } from "./support/file-document-listing.ts";import { test, beforeEach } from "node:test";import assert from "node:assert/strict";import { createMemoryDurableByteStore } from "../src/files/durable-byte-store.ts";@@ -150,17 +150,17 @@ test("pg scoped file pages have a matching enabled recency index", { skip }, asy}});-test("pg resolveByOwnerPaths returns the shared set; disabled excluded", { skip }, async () => {+test("pg resolveByIds returns the shared set; disabled excluded", { skip }, async () => {const store = createPostgresFileArtifactStore(URL!, createMemoryDurableByteStore());await store.put(put({ id: "r1", path: "p/r1", data: Buffer.from("1") }));await store.put(put({ id: "r2", path: "p/r2", data: Buffer.from("2") }));assert.deepEqual(- (await store.resolveByOwnerPaths([{ ownerScopeId: owner, path: "p/r1" }])).map((f) => f.id),+ (await store.resolveByIds([{ ownerScopeId: owner, id: "r1" }])).map((f) => f.id),["r1"],);await store.setEnabled("r1", false);- assert.equal((await store.resolveByOwnerPaths([{ ownerScopeId: owner, path: "p/r1" }])).length, 0);+ assert.equal((await store.resolveByIds([{ ownerScopeId: owner, id: "r1" }])).length, 0);});test("pg open round-trips bytes; delete removes the ROW only", { skip }, async () => {@@ -252,5 +252,9 @@ test("pg concurrent first shares reuse one path generation and republish after dconst current = await second.put({ ...input, id: "share-three", data: Buffer.from("new content") });assert.equal(current.created, true);assert.equal(current.artifact.id, "share-three");- assert.equal((await first.resolveByOwnerPaths([{ ownerScopeId: owner, path: input.path }])).length, 1);+ assert.equal((await first.resolveByIds([{ ownerScopeId: owner, id: current.artifact.id }])).length, 1);+});++test("shared file refs authorize only the exact record ID", { skip }, async () => {+ await assertSharedRecordIdentity(createPostgresFileArtifactStore(URL!, createMemoryDurableByteStore()));});diff --git a/test/postgres-grant-store.test.ts b/test/postgres-grant-store.test.tsindex b281a7d06..c5f941b1e 100644--- a/test/postgres-grant-store.test.ts+++ b/test/postgres-grant-store.test.ts@@ -1,6 +1,8 @@import { test, before } from "node:test";import assert from "node:assert/strict";import { createPostgresGrantStore } from "../src/acl/postgres-grant-store.ts";+import { createMemoryFileArtifactStore } from "../src/files/file-artifact-store.ts";+import { createMemoryDurableByteStore } from "../src/files/durable-byte-store.ts";import { createAclStore } from "../src/acl/acl-store.ts";import { principalEntitledToScope } from "../src/resolution/context-filter.ts";import { scopeId, type Grant, type Principal } from "../src/types.ts";@@ -182,13 +184,29 @@ test("pg-backed AclStore: owner-only grant, dedup, permission-agnostic revoke, handle surfacing",{ skip },async () => {- const acl = createAclStore(createPostgresGrantStore(URL!));-- await assert.rejects(acl.grant(grant({ ref: "owner-only.md", grantedBy: "U2" })), /only a manager/);-- await acl.grant(grant({ ref: "owner-only.md" }));- await acl.grant(grant({ ref: "owner-only.md" }));- assert.equal((await acl.grantsFor(owner, "owner-only.md")).length, 1);+ const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());+ for (const [id, name] of [+ ["owner-only", "owner-only.md"],+ ["poster", "poster.png"],+ ]) {+ await files.put({+ id: id!,+ ownerScopeId: owner,+ createdBy: "U1",+ name: name!,+ path: name!,+ mimetype: "application/octet-stream",+ data: Buffer.from("file"),+ direction: "out",+ });+ }+ const acl = createAclStore(createPostgresGrantStore(URL!), { resolveFiles: (refs) => files.resolveByIds(refs) });++ await assert.rejects(acl.grant(grant({ ref: "owner-only", grantedBy: "U2" })), /only a manager/);++ await acl.grant(grant({ ref: "owner-only" }));+ await acl.grant(grant({ ref: "owner-only" }));+ assert.equal((await acl.grantsFor(owner, "owner-only")).length, 1);const handles = await acl.handlesFor([carol]);assert.equal(@@ -196,7 +214,7 @@ test(true,);- await acl.grant(grant({ ref: "poster.png", granteeScopeId: org }));+ await acl.grant(grant({ ref: "poster", granteeScopeId: org }));const surfaced = await acl.handlesForAudience([person("U1"), person("U2")],scopeId("channel", "C1"),@@ -208,13 +226,9 @@ test(true,);- await acl.grant(grant({ ref: "owner-only.md", permission: "write" }));- assert.equal((await acl.grantsFor(owner, "owner-only.md")).length, 2);- await acl.revoke(owner, "owner-only.md", carol, "U1");- assert.equal(- (await acl.grantsFor(owner, "owner-only.md")).length,- 0,- "revoke drops every permission for the triple",- );+ await acl.grant(grant({ ref: "owner-only", permission: "write" }));+ assert.equal((await acl.grantsFor(owner, "owner-only")).length, 2);+ await acl.revoke(owner, "owner-only", carol, "U1");+ assert.equal((await acl.grantsFor(owner, "owner-only")).length, 0, "revoke drops every permission for the triple");},);diff --git a/test/prompt-inventory-order.test.ts b/test/prompt-inventory-order.test.tsindex 40c8be4b1..3682a4eb9 100644--- a/test/prompt-inventory-order.test.ts+++ b/test/prompt-inventory-order.test.ts@@ -38,7 +38,7 @@ test("prompt inventories keep identical bytes across permutations, including capids.map((id) => ({handlePath: `shared/${id}`,ownerScopeId: "personal:U1",- ownerPath: `${id}.txt`,+ fileId: id,permission: "read",})),sharedManifest,diff --git a/test/reach-files.test.ts b/test/reach-files.test.tsindex 48572039a..e5511e973 100644--- a/test/reach-files.test.ts+++ b/test/reach-files.test.ts@@ -19,8 +19,10 @@ const SECRET = "reach-files-secret".repeat(3);describe("POST /v1/reach with files", () => {let server: Server;let bare: Server;+ let noSandbox: Server;let base: string;let bareBase: string;+ let noSandboxBase: string;let built: BuiltApp;const capDm = async (actorId: string) =>@@ -59,8 +61,17 @@ describe("POST /v1/reach with files", () => {files: built.files,environments: built.environments,auditLog: built.auditLog,+ sandboxResources: built.sandboxResources,});bare = createServer(built.app, { signingSecret: SECRET });+ noSandbox = createServer(built.app, {+ signingSecret: SECRET,+ blobTransfer: built.blobTransfer,+ files: built.files,+ environments: built.environments,+ });+ await new Promise<void>((resolve) => noSandbox.listen(0, resolve));+ noSandboxBase = `http://localhost:${(noSandbox.address() as AddressInfo).port}`;await new Promise<void>((resolve) => server.listen(0, resolve));await new Promise<void>((resolve) => bare.listen(0, resolve));base = `http://localhost:${(server.address() as AddressInfo).port}`;@@ -70,6 +81,170 @@ describe("POST /v1/reach with files", () => {after(async () => {await new Promise<void>((resolve) => server.close(() => resolve()));await new Promise<void>((resolve) => bare.close(() => resolve()));+ await new Promise<void>((resolve) => noSandbox.close(() => resolve()));+ });++ const storeFile = async (owner: string, name: string, data: string) => {+ const id = `file-${owner}-${name}-${Math.random().toString(36).slice(2)}`;+ await built.files.put({+ id,+ ownerScopeId: scopeId("personal", owner),+ createdBy: owner,+ name,+ path: `artifacts/${id}/${name}`,+ mimetype: "text/plain",+ data: Buffer.from(data),+ direction: "out",+ });+ return id;+ };++ const secondSandbox = async (actorId: string) => {+ const scope = scopeId("personal", actorId);+ const resources = built.sandboxResources.forTurn({ actorId, scopeId: scope, isCurrent: async () => true });+ return resources.create(actorId, scope, resources.defaultBackend());+ };++ const readDelivered = async (deliveryId: string) => {+ const d = (await built.app.pendingDeliveries("principal")).find((x) => x.id === deliveryId);+ assert.ok(d?.attachments?.length);+ const out: string[] = [];+ for (const a of d!.attachments!) {+ const opened = await built.blobTransfer.open(a.blobId);+ const chunks: Buffer[] = [];+ for await (const c of opened!.stream) chunks.push(c as Buffer);+ out.push(`${a.name}:${Buffer.concat(chunks).toString()}`);+ }+ return out;+ };++ it("attaches a stored Files ID the sender can view", async () => {+ const id = await storeFile("U-carol", "stored.txt", "from Files\n");+ const res = await post(+ base,+ "/v1/reach",+ { text: "stored", recipient: "Alice", files: [{ file_id: id }] },+ { "x-agent-capability": await capDm("U-carol") },+ );+ assert.equal(res.status, 200);+ assert.deepEqual(await readDelivered(((await res.json()) as any).deliveryId), ["stored.txt:from Files\n"]);+ });++ it("refuses a stored Files ID the sender cannot view, without revealing it", async () => {+ const id = await storeFile("U-alice", "private.txt", "alice only\n");+ const res = await post(+ base,+ "/v1/reach",+ { text: "steal", recipient: "Alice", files: [{ file_id: id }] },+ { "x-agent-capability": await capDm("U-carol") },+ );+ assert.equal(res.status, 400);+ const body = (await res.json()) as any;+ assert.equal(body.error, "attach_failed");+ assert.doesNotMatch(body.message, /alice only/);+ });++ it("sends stored Files IDs on a server with no sandbox, but refuses workspace paths there", async () => {+ const id = await storeFile("U-carol", "nobox.txt", "no box\n");+ const ok = await post(+ noSandboxBase,+ "/v1/reach",+ { text: "stored only", recipient: "Alice", files: [{ file_id: id }], sandbox_id: "ignored" },+ { "x-agent-capability": await capDm("U-carol") },+ );+ assert.equal(ok.status, 200);+ assert.deepEqual(await readDelivered(((await ok.json()) as any).deliveryId), ["nobox.txt:no box\n"]);+ const refused = await post(+ noSandboxBase,+ "/v1/reach",+ { text: "path", recipient: "Alice", files: [{ file_id: id }, "reports/report.md"] },+ { "x-agent-capability": await capDm("U-carol") },+ );+ assert.equal(refused.status, 501);+ });++ it("rolls back a staged stored file when a later workspace path in the batch is missing", async () => {+ const id = await storeFile("U-carol", "staged.txt", "staged\n");+ await built.blobTransfer.sweep(0);+ const before = (await built.files.listOwnedByScopes([scopeId("personal", "U-carol")])).files.length;+ const res = await post(+ base,+ "/v1/reach",+ { text: "mixed", recipient: "Alice", files: [{ file_id: id }, "reports/absent.md"] },+ { "x-agent-capability": await capDm("U-carol") },+ );+ assert.equal(res.status, 400);+ assert.match(((await res.json()) as any).message, /reports\/absent\.md \(not found\)/);+ assert.equal(await built.blobTransfer.sweep(0), 0, "no orphaned transfer blob");+ assert.equal(+ (await built.files.listOwnedByScopes([scopeId("personal", "U-carol")])).files.length,+ before,+ "no orphaned outbound artifact",+ );+ });++ it("reads workspace paths from an explicitly named sandbox_id instead of the default", async () => {+ const extra = await secondSandbox("U-carol");+ const handle = await built.sandbox.provision(+ [{ scopeId: scopeId("personal", "U-carol"), mountPath: "", mode: "rw" }],+ { sandboxId: extra.id },+ );+ await built.sandbox.writeFile(handle, "only-here.md", "second box\n");+ await built.sandbox.teardown(handle, { keepWarm: true });+ const viaDefault = await post(+ base,+ "/v1/reach",+ { text: "default", recipient: "Alice", files: ["only-here.md"] },+ { "x-agent-capability": await capDm("U-carol") },+ );+ assert.equal(viaDefault.status, 400, "the default box doesn't have it");+ const res = await post(+ base,+ "/v1/reach",+ { text: "named", recipient: "Alice", files: ["only-here.md"], sandbox_id: extra.id },+ { "x-agent-capability": await capDm("U-carol") },+ );+ assert.equal(res.status, 200);+ assert.deepEqual(await readDelivered(((await res.json()) as any).deliveryId), ["only-here.md:second box\n"]);+ });++ it("refuses an unauthorized, unknown, or retired sandbox_id instead of falling back to the default", async () => {+ await seedFile("U-carol", "reports/fallback.md", "default box\n");+ const alices = await secondSandbox("U-alice");+ const retired = await secondSandbox("U-carol");+ await built.sandboxResources.retire("U-carol", retired.id);+ for (const sandbox_id of [alices.id, "no-such-sandbox", retired.id]) {+ const res = await post(+ base,+ "/v1/reach",+ { text: "x", recipient: "Alice", files: ["reports/fallback.md"], sandbox_id },+ { "x-agent-capability": await capDm("U-carol") },+ );+ assert.equal(res.status, 403, sandbox_id);+ assert.equal(((await res.json()) as any).error, "forbidden");+ }+ const access = built.sandboxResources.access;+ built.sandboxResources.access = async () => {+ throw new Error("record store unavailable");+ };+ try {+ const failed = await post(+ base,+ "/v1/reach",+ { text: "x", recipient: "Alice", files: ["reports/fallback.md"], sandbox_id: alices.id },+ { "x-agent-capability": await capDm("U-carol") },+ );+ assert.equal(failed.status, 500, "a store failure is not reported as an access denial");+ } finally {+ built.sandboxResources.access = access;+ }+ const malformed = await post(+ base,+ "/v1/reach",+ { text: "x", recipient: "Alice", files: ["reports/fallback.md"], sandbox_id: 7 },+ { "x-agent-capability": await capDm("U-carol") },+ );+ assert.equal(malformed.status, 400);});it("composes named workspace files into the delivery as attachments (the silent-drop bug)", async () => {@@ -171,7 +346,7 @@ describe("POST /v1/reach with files", () => {{ "x-agent-capability": await capDm("U-carol") },);assert.equal(res.status, 400);- assert.match(((await res.json()) as any).message, /files must be an array/);+ assert.match(((await res.json()) as any).message, /files must be/);const res2 = await post(base,"/v1/reach",diff --git a/test/read-cancellation.test.ts b/test/read-cancellation.test.tsindex 0cda452ad..197f3200e 100644--- a/test/read-cancellation.test.ts+++ b/test/read-cancellation.test.ts@@ -1,3 +1,4 @@+import { Readable } from "node:stream";import { test } from "node:test";import assert from "node:assert/strict";import { setTimeout as sleep } from "node:timers/promises";@@ -66,70 +67,35 @@ test("already cancelled reads never start IO", async () => {assert.equal(reads(), 0);});-test("cancel during a shared read does not materialize late binary data", async () => {- const pending = Promise.withResolvers<Uint8Array | null>();+test("cancel during a shared artifact read settles without touching a sandbox", async () => {+ const pending = Promise.withResolvers<Buffer>();const started = Promise.withResolvers<void>();- let writes = 0;- const { tc } = setup({- grantedHandles: [- {- handlePath: "shared/file.bin",- ownerPath: "file.bin",- ownerScopeId: scopeId("personal", "U2"),- permission: "read",- },- ],- workspace: {- readBytes: async () => {- started.resolve();- return pending.promise;- },- } as unknown as ToolContextDeps["workspace"],- sandbox: {- writeFileBytes: async () => {- writes++;- },- } as unknown as Sandbox,+ const ownerScopeId = scopeId("personal", "U2");+ const { tc, reads } = setup({+ grantedHandles: [{ handlePath: "shared/file.bin", fileId: "file-id", ownerScopeId, permission: "read" }],+ files: {+ get: async () => ({ id: "file-id", name: "file.bin", ownerScopeId }),+ open: async () => ({+ artifact: { id: "file-id", name: "file.bin", ownerScopeId },+ sizeBytes: 3,+ stream: Readable.from(+ (async function* () {+ started.resolve();+ yield await pending.promise;+ })(),+ ),+ }),+ } as unknown as ToolContextDeps["files"],+ provision: async () => {+ throw new Error("must not provision");+ },});const controller = new AbortController();const result = tc.read("shared/file.bin", controller.signal);await started.promise;controller.abort();await assert.rejects(result, { name: "AbortError" });- pending.resolve(new Uint8Array([255, 254, 0]));+ pending.resolve(Buffer.from([255, 254, 0]));await sleep(0);- assert.equal(writes, 0);-});--test("cancellation drains an in-flight materialization instead of abandoning writes", async () => {- const writing = Promise.withResolvers<void>();- const finish = Promise.withResolvers<void>();- const { tc } = setup({- grantedHandles: [- {- handlePath: "shared/file.bin",- ownerPath: "file.bin",- ownerScopeId: scopeId("personal", "U2"),- permission: "read",- },- ],- workspace: { readBytes: async () => new Uint8Array([255, 254, 0]) } as unknown as ToolContextDeps["workspace"],- sandbox: {- writeFileBytes: async () => {- writing.resolve();- await finish.promise;- },- } as unknown as Sandbox,- });- const controller = new AbortController();- let settled = false;- const result = tc.read("shared/file.bin", controller.signal).finally(() => {- settled = true;- });- await writing.promise;- controller.abort();- await sleep(10);- assert.equal(settled, false);- finish.resolve();- await assert.rejects(result, { name: "AbortError" });+ assert.equal(reads(), 0);});diff --git a/test/sandbox-resources.test.ts b/test/sandbox-resources.test.tsindex 7e833397b..f656fcd9a 100644--- a/test/sandbox-resources.test.ts+++ b/test/sandbox-resources.test.ts@@ -136,6 +136,11 @@ test("explicit sandbox profiles follow selected storage rather than the parent'sconst worker = await resources.create("alice", "personal:alice", "modal", "Worker");assert.equal((await router.profileFor!("personal:alice")).backend, "local");assert.equal((await router.profileFor!("personal:alice", worker.id)).backend, "modal");+ await assert.rejects(router.profileFor!("personal:alice", ""), /sandbox not found/);+ await assert.rejects(+ router.provision([{ scopeId: "personal:alice", mode: "rw", mountPath: "" }], { sandboxId: "" }),+ /sandbox not found/,+ );assert.equal((await router.profileFor!("personal:alice")).backend, "local");});diff --git a/test/scope-resources-authz.test.ts b/test/scope-resources-authz.test.tsindex d94fcbd7d..2d4ed9fb1 100644--- a/test/scope-resources-authz.test.ts+++ b/test/scope-resources-authz.test.ts@@ -20,7 +20,7 @@ function makeDeps() {const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());const crons = createCronStore();const webhooks = createWebhookStore();- const acl = createAclStore();+ const acl = createAclStore(undefined, { resolveFiles: (refs) => files.resolveByIds(refs) });const identity = {classify: (id: string) => ({ id, type: "internal" }),isInternal: (p: { type: string }) => p.type === "internal",@@ -56,7 +56,7 @@ async function setup(): Promise<{ app: App; deps: ReturnType<typeof makeDeps> }>});await deps.acl.grant({ownerScopeId: scopeId("personal", "U2"),- ref: "report.pdf",+ ref: "f-channel",granteeScopeId: orgScope,permission: "read",grantedBy: "U2",@@ -281,7 +281,7 @@ test("every file a context lists is one the viewer is authorized to open", asyncassert.ok(art, "the listed file exists");const myScopes = [scopeId("personal", U1), orgScope];const ownedByViewer = myScopes.includes(art!.ownerScopeId);- const grants = await deps.acl.grantsFor(art!.ownerScopeId, art!.path);+ const grants = await deps.acl.grantsFor(art!.ownerScopeId, art!.id);const sharedToViewer = grants.some((g) => myScopes.includes(g.granteeScopeId));assert.ok(ownedByViewer || sharedToViewer, `${f.name} is openable by U1 (owned or ACL-granted)`);}diff --git a/test/selected-sandbox-files.test.ts b/test/selected-sandbox-files.test.tsnew file mode 100644index 000000000..5d9af5d2a--- /dev/null+++ b/test/selected-sandbox-files.test.ts@@ -0,0 +1,148 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { createToolContext, type ToolContextDeps } from "../src/tools/primitives.ts";+import { scopeId, type WorkspaceLayer } from "../src/types.ts";+import type { Sandbox, SandboxHandle } from "../src/sandbox/sandbox.ts";+import type { SandboxAccessPlan } from "../src/sandbox/sandbox-resources.ts";++const conversation = scopeId("channel", "C1");+const other = scopeId("channel", "C2");+const defaultBox: SandboxHandle = { id: "default", rootDir: "/workspace" };+const selectedBox: SandboxHandle = { id: "selected", rootDir: "/workspace" };++function plan(id: string, ownerScopeId: string, crossScope = false): SandboxAccessPlan {+ return {+ resource: { id, ownerScopeId, backingScopeId: `sandbox-${id}` },+ crossScope,+ } as unknown as SandboxAccessPlan;+}++function harness(opts: { access?: SandboxAccessPlan; extra?: Partial<ToolContextDeps> } = {}) {+ const disks = new Map<string, Map<string, string>>([+ ["default", new Map([["notes.md", "default copy"]])],+ [+ "selected",+ new Map([+ ["notes.md", "selected copy"],+ ["app/server.js", "listen()"],+ ]),+ ],+ ]);+ const stored: Array<{ scope: string; path: string }> = [];+ const deployed: Array<Record<string, unknown>> = [];+ let defaultProvisions = 0;+ const layers: WorkspaceLayer[] = [{ scopeId: conversation, mountPath: "", mode: "rw" }];+ const sandbox = {+ profile: { backend: "modal" },+ readFile: async (h: SandboxHandle, path: string) => disks.get(h.id)?.get(path) ?? null,+ readFileBytes: async (h: SandboxHandle, path: string) => {+ const v = disks.get(h.id)?.get(path);+ return v === undefined ? null : new TextEncoder().encode(v);+ },+ writeFile: async (h: SandboxHandle, path: string, data: string) => {+ disks.get(h.id)!.set(path, data);+ },+ listDir: async (h: SandboxHandle) => [...disks.get(h.id)!.keys()].filter((p) => p.startsWith("app/")),+ } as unknown as Sandbox;+ const ctx = createToolContext({+ sandbox,+ provision: async () => {+ defaultProvisions += 1;+ return defaultBox;+ },+ sandboxResources: { resolve: async () => ({ id: "default" }) } as never,+ accessSandboxResource: async (id) => {+ if (!opts.access || opts.access.resource.id !== id) throw new Error(`sandbox not found: ${id}`);+ return opts.access;+ },+ provisionResource: async (input, authorize) => {+ authorize?.(input as SandboxAccessPlan);+ return selectedBox;+ },+ layers,+ commandPolicy: () => ({ mode: "denylist", rules: [] }),+ authorizeCommand: () => false,+ grantedHandles: [],+ workspace: {+ write: async (scope: string, path: string) => {+ stored.push({ scope, path });+ },+ } as never,+ files: {} as never,+ acl: {} as never,+ deploy: {+ getDeployment: async () => ({ entrypoint: "node server.js" }),+ deployOrUpdate: async (input: Record<string, unknown>) => {+ deployed.push(input);+ return { id: "d1", name: "site", currentVersion: 2, createdInScope: input.createdInScope };+ },+ deploymentGrantees: async () => [],+ } as never,+ createdBy: "U1",+ ...opts.extra,+ });+ return { ctx, disks, stored, deployed, provisions: () => defaultProvisions };+}++test("a selected sandbox read never falls back to the default computer", async () => {+ const h = harness({ access: plan("sb1", conversation) });+ assert.deepEqual(await h.ctx.read("notes.md", undefined, "sb1"), {+ content: "selected copy",+ sourceScopeId: conversation,+ });+ await assert.rejects(h.ctx.read("notes.md", undefined, "missing"), /sandbox not found: missing/);+ await assert.rejects(h.ctx.read("notes.md", undefined, ""), /must name a sandbox/);+ assert.equal(h.provisions(), 0);+});++test("a selected write persists to that computer's backing store, not the conversation default", async () => {+ const h = harness({ access: plan("sb1", conversation) });+ await h.ctx.write("notes.md", "edited", "sb1");+ assert.equal(h.disks.get("selected")!.get("notes.md"), "edited");+ assert.equal(h.disks.get("default")!.get("notes.md"), "default copy");+ assert.deepEqual(h.stored, [{ scope: conversation, path: "sandbox-files/sb1/notes.md" }]);+ assert.equal(h.provisions(), 0);+});++test("another conversation's computer can be read but not written", async () => {+ const h = harness({ access: plan("sb2", other, true) });+ assert.equal((await h.ctx.read("notes.md", undefined, "sb2")).sourceScopeId, other);+ await assert.rejects(h.ctx.write("notes.md", "x", "sb2"), /owned by this conversation/);+ assert.equal(h.disks.get("selected")!.get("notes.md"), "selected copy");+ assert.deepEqual(h.stored, []);+});++test("publish reads files from the selected sandbox while the app stays owned by its creator", async () => {+ const h = harness({ access: plan("sb2", other, true) });+ await h.ctx.publish({ dir: "app", entrypoint: "node server.js", name: "site", sandboxId: "sb2" });+ assert.equal(h.provisions(), 0);+ const [deploy] = h.deployed;+ assert.equal(deploy!.ownerScopeId, scopeId("personal", "U1"));+ assert.equal(deploy!.createdInScope, conversation);+ assert.deepEqual(+ (deploy!.files as Array<{ path: string }>).map((f) => f.path),+ ["server.js"],+ );+});++test("metadata-only publish needs no computer but still rejects an unknown sandbox", async () => {+ const h = harness();+ await h.ctx.publish({ name: "site", rollbackTo: 1 });+ assert.equal(h.provisions(), 0);+ await assert.rejects(h.ctx.publish({ name: "site", rollbackTo: 1, sandboxId: "missing" }), /sandbox not found/);+ assert.equal(h.deployed.length, 1);+});++test("naming the default sandbox explicitly persists exactly like omitting it", async () => {+ const access = plan("sb1", conversation);+ const h = harness({+ access,+ extra: {+ provision: async () => ({ ...selectedBox, resourceId: "sb1" }),+ sandboxResources: { get: async () => access.resource, resolve: async () => access.resource } as never,+ },+ });+ await h.ctx.write("notes.md", "implicit");+ await h.ctx.write("notes.md", "explicit", "sb1");+ assert.deepEqual(new Set(h.stored.map((e) => `${e.scope} ${e.path}`)), new Set([`${conversation} notes.md`]));+});diff --git a/test/share-verb.test.ts b/test/share-verb.test.tsindex 2a4bcbb7e..a7a8ac971 100644--- a/test/share-verb.test.ts+++ b/test/share-verb.test.ts@@ -13,6 +13,8 @@ import type { ApiCtx } from "../src/api/routes/route.ts";import { createSkillStore } from "../src/skills/skill-store.ts";import { splitToScope } from "../src/api/artifact-share.ts";import { createAclStore } from "../src/acl/acl-store.ts";+import { createMemoryFileArtifactStore, type FileArtifactStore } from "../src/files/file-artifact-store.ts";+import { createMemoryDurableByteStore } from "../src/files/durable-byte-store.ts";import type { ManagesArtifactHome } from "../src/resolution/scope-membership.ts";const ORG = "default-org";@@ -26,6 +28,7 @@ interface FakeState {recipients: Record<string, RecipientResolution>;privateChannels: Set<string>;acl: ReturnType<typeof createAclStore>;+ files: FileArtifactStore;}function fakeManages(state: FakeState): ManagesArtifactHome {@@ -94,6 +97,7 @@ const cap = (actorId: string, scope?: ScopeId, liveActor = true): CapabilityClai}) as CapabilityClaims;function baseState(over: Partial<FakeState> = {}): FakeState {+ const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());const state: FakeState = {artifacts: {},scopesByPrincipal: {},@@ -102,7 +106,11 @@ function baseState(over: Partial<FakeState> = {}): FakeState {admins: new Set(),recipients: {},privateChannels: new Set(),- acl: createAclStore(undefined, { manages: (p, s, a) => manages(s, a ?? "", p) }),+ files,+ acl: createAclStore(undefined, {+ manages: (p, s, a) => manages(s, a ?? "", p),+ resolveFiles: (refs) => files.resolveByIds(refs),+ }),...over,};const manages = fakeManages(state);@@ -113,15 +121,15 @@ async function grantsOf(state: FakeState): Promise<Grant[]> {return [...(await state.acl.list())];}-function ownerState(): FakeState {+async function ownerState(): Promise<FakeState> {const home = (type: ArtifactType, id: string): ArtifactHome & { type: ArtifactType } => ({type,id,ownerScopeId: scopeId("personal", "U1"),createdBy: "U1",- grantRef: type === "file" ? `artifacts/${id}/doc.md` : `${type === "deploy" ? "deployment" : type}:${id}`,+ grantRef: type === "file" ? id : `${type === "deploy" ? "deployment" : type}:${id}`,});- return baseState({+ const state = baseState({artifacts: {"file:F1": home("file", "F1"),"skill:S1": home("skill", "S1"),@@ -134,11 +142,22 @@ function ownerState(): FakeState {},recipients: { carol: { kind: "one", member: { principalId: "U-carol", displayName: "Carol", type: "internal" } } },});+ await state.files.put({+ id: "F1",+ ownerScopeId: scopeId("personal", "U1"),+ createdBy: "U1",+ name: "doc.md",+ path: "artifacts/F1/doc.md",+ mimetype: "text/markdown",+ data: Buffer.from("hello"),+ direction: "out",+ });+ return state;}test("share adds a grant for EVERY artifact type — one verb, one store, uniform across file/skill/deploy/cron", async () => {for (const type of ["file", "skill", "deploy", "cron"] as const) {- const state = ownerState();+ const state = await ownerState();const svc = createControlService(fakeApp(state));const id = { file: "F1", skill: "S1", deploy: "D1", cron: "K1" }[type];const r = await svc.shareArtifact({ type, id, scope: scopeId("channel", "C1") }, cap("U1"));@@ -151,14 +170,13 @@ test("share adds a grant for EVERY artifact type — one verb, one store, uniforassert.equal(g.granteeScopeId, scopeId("channel", "C1"));assert.equal(g.grantedBy, "U1");assert.equal(g.permission, "read");- const expectedPath =- type === "file" ? `artifacts/${id}/doc.md` : `${type === "deploy" ? "deployment" : type}:${id}`;- assert.equal(g.ref, expectedPath, `${type}: keyed on the consumer's path`);+ const expectedPath = type === "file" ? id : `${type === "deploy" ? "deployment" : type}:${id}`;+ assert.equal(g.ref, expectedPath, `${type}: keyed on the artifact ID`);}});test("share resolves a teammate by name → a frictionless person grant (the person-follows model, §3)", async () => {- const state = ownerState();+ const state = await ownerState();const svc = createControlService(fakeApp(state));const r = await svc.shareArtifact({ type: "file", id: "F1", recipient: "carol" }, cap("U1"));assert.ok(r.ok, JSON.stringify(r));@@ -168,7 +186,7 @@ test("share resolves a teammate by name → a frictionless person grant (the per});test("share into a scope you belong to is frictionless; permission:write is honored", async () => {- const state = ownerState();+ const state = await ownerState();const svc = createControlService(fakeApp(state));const r = await svc.shareArtifact({ type: "deploy", id: "D1", scope: scopeId("channel", "C1"), permission: "write" },@@ -180,7 +198,7 @@ test("share into a scope you belong to is frictionless; permission:write is hono});test("move changes the home scope (skills); the creator is untouched; no grant is written", async () => {- const state = ownerState();+ const state = await ownerState();const svc = createControlService(fakeApp(state));const r = await svc.shareArtifact({ type: "skill", id: "S1", scope: scopeId("channel", "C1"), move: true },@@ -193,7 +211,7 @@ test("move changes the home scope (skills); the creator is untouched; no grant i});test("move into a teammate's personal scope is refused — a move re-homes only into a context you belong to", async () => {- const state = ownerState();+ const state = await ownerState();const svc = createControlService(fakeApp(state));const r = await svc.shareArtifact({ type: "skill", id: "S1", recipient: "carol", move: true }, cap("U1"));assert.equal(r.ok, false);@@ -202,7 +220,7 @@ test("move into a teammate's personal scope is refused — a move re-homes only});test("moving a DEPLOY to a teammate's personal scope is an ownership transfer — allowed for a live actor", async () => {- const state = ownerState();+ const state = await ownerState();const svc = createControlService(fakeApp(state));const r = await svc.shareArtifact({ type: "deploy", id: "D1", recipient: "carol", move: true }, cap("U1"));assert.ok(r.ok, JSON.stringify(r));@@ -212,7 +230,7 @@ test("moving a DEPLOY to a teammate's personal scope is an ownership transfer});test("a deploy ownership transfer to a person takes a LIVE actor — an autonomous trigger is refused", async () => {- const state = ownerState();+ const state = await ownerState();const svc = createControlService(fakeApp(state));const r = await svc.shareArtifact({ type: "deploy", id: "D1", recipient: "carol", move: true },@@ -224,7 +242,7 @@ test("a deploy ownership transfer to a person takes a LIVE actor — an autonomo});test("moving a deploy into a channel you belong to re-homes it there (group ownership)", async () => {- const state = ownerState();+ const state = await ownerState();const svc = createControlService(fakeApp(state));const r = await svc.shareArtifact({ type: "deploy", id: "D1", scope: scopeId("channel", "C1"), move: true },@@ -236,7 +254,7 @@ test("moving a deploy into a channel you belong to re-homes it there (group owne});test("move is refused for a type whose home isn't movable (file) — directed to share", async () => {- const state = ownerState();+ const state = await ownerState();const svc = createControlService(fakeApp(state));const r = await svc.shareArtifact({ type: "file", id: "F1", scope: scopeId("channel", "C1"), move: true }, cap("U1"));assert.equal(r.ok, false);@@ -247,7 +265,7 @@ test("move is refused for a type whose home isn't movable (file) — directed to});test("ceding a skill to the ORG is admin-gated — a non-admin share to org is forbidden, never a silent grant", async () => {- const state = ownerState();+ const state = await ownerState();const svc = createControlService(fakeApp(state));const r = await svc.shareArtifact({ type: "skill", id: "S1", scope: "org" }, cap("U1"));assert.equal(r.ok, false);@@ -256,7 +274,7 @@ test("ceding a skill to the ORG is admin-gated — a non-admin share to org is f});test("an org admin CAN cede a skill to the org — share to org promotes", async () => {- const state = ownerState();+ const state = await ownerState();state.admins.add("U1");const svc = createControlService(fakeApp(state));const r = await svc.shareArtifact({ type: "skill", id: "S1", scope: "org" }, cap("U1"));@@ -269,7 +287,7 @@ test("an org admin CAN cede a skill to the org — share to org promotes", async});test("an org admin can promote a TEAMMATE'S skill org-wide — admin-ness, not ownership, is the authority", async () => {- const state = ownerState();+ const state = await ownerState();state.admins.add("U9");const svc = createControlService(fakeApp(state));const r = await svc.shareArtifact({ type: "skill", id: "S1", scope: "org" }, cap("U9"));@@ -278,7 +296,7 @@ test("an org admin can promote a TEAMMATE'S skill org-wide — admin-ness, not o});test("an autonomous trigger (no liveActor) cannot cede a skill to the org, even as an admin", async () => {- const state = ownerState();+ const state = await ownerState();state.admins.add("U1");const svc = createControlService(fakeApp(state));const r = await svc.shareArtifact({ type: "skill", id: "S1", scope: "org" }, cap("U1", undefined, false));@@ -288,7 +306,7 @@ test("an autonomous trigger (no liveActor) cannot cede a skill to the org, even});test("ceding a skill to the org via MOVE is also refused for a non-admin (admin gate, not a frictionless move)", async () => {- const state = ownerState();+ const state = await ownerState();const svc = createControlService(fakeApp(state));const r = await svc.shareArtifact({ type: "skill", id: "S1", scope: "org", move: true }, cap("U1"));assert.equal(r.ok, false);@@ -296,7 +314,7 @@ test("ceding a skill to the org via MOVE is also refused for a non-admin (admin});test("a non-member can't share into a scope they're not in (forbidden)", async () => {- const state = ownerState();+ const state = await ownerState();const svc = createControlService(fakeApp(state));const r = await svc.shareArtifact({ type: "file", id: "F1", scope: scopeId("channel", "C9") }, cap("U1"));assert.equal(r.ok, false);@@ -305,7 +323,7 @@ test("a non-member can't share into a scope they're not in (forbidden)", async (});test("only the owner may share a personal-homed artifact — a non-creator is forbidden (no transitive re-share)", async () => {- const state = ownerState();+ const state = await ownerState();state.scopesByPrincipal["U2"] = [scopeId("personal", "U2"), scopeId("org", ORG), scopeId("channel", "C1")];const svc = createControlService(fakeApp(state));const r = await svc.shareArtifact({ type: "file", id: "F1", scope: scopeId("channel", "C1") }, cap("U2"));@@ -314,7 +332,7 @@ test("only the owner may share a personal-homed artifact — a non-creator is fo});test("a member of a shared home (private channel/group) can share it even if they didn't create it (PR2 manage parity)", async () => {- const state = ownerState();+ const state = await ownerState();state.privateChannels.add("C1");state.artifacts["skill:CS"] = {type: "skill",@@ -341,7 +359,7 @@ test("a member of a shared home (private channel/group) can share it even if the});test("an author who LEFT a private channel can no longer share its artifact (parity with canManageSkill — membership, not authorship)", async () => {- const state = ownerState();+ const state = await ownerState();state.privateChannels.add("C1");state.artifacts["skill:CS"] = {type: "skill",@@ -367,7 +385,7 @@ test("an author who LEFT a private channel can no longer share its artifact (par});test("a PUBLIC-channel artifact's author can share it end to end — both authz gates agree (#986 regression)", async () => {- const state = ownerState();+ const state = await ownerState();state.artifacts["cron:PK"] = {type: "cron",id: "PK",@@ -385,7 +403,7 @@ test("a PUBLIC-channel artifact's author can share it end to end — both authz});test("a non-owner non-member CANNOT share a PUBLIC-channel artifact — the author door is author-only", async () => {- const state = ownerState();+ const state = await ownerState();state.artifacts["cron:PK"] = {type: "cron",id: "PK",@@ -406,7 +424,7 @@ test("a non-owner non-member CANNOT share a PUBLIC-channel artifact — the auth});test("a non-member of a shared home cannot share it (membership-gated, not just creator-gated)", async () => {- const state = ownerState();+ const state = await ownerState();state.artifacts["skill:CS"] = {type: "skill",id: "CS",@@ -422,11 +440,17 @@ test("a non-member of a shared home cannot share it (membership-gated, not just});test("an unknown artifact is a not_found; a bad scope id is a bad_request; an unknown teammate is recipient_not_found", async () => {- const state = ownerState();+ const state = await ownerState();const svc = createControlService(fakeApp(state));const missing = await svc.shareArtifact({ type: "file", id: "ghost", scope: "org" }, cap("U1"));assert.equal(missing.ok, false);- if (!missing.ok) assert.equal(missing.code, "not_found");+ if (!missing.ok) {+ assert.equal(missing.code, "not_found");+ assert.match(missing.message, /POST \/v1\/files\/uploads/);+ }+ const path = await svc.shareArtifact({ type: "file", id: "artifacts/F1/doc.md", scope: "org" }, cap("U1"));+ assert.equal(path.ok, false);+ if (!path.ok) assert.match(path.message, /POST \/v1\/files\/uploads/);const badScope = await svc.shareArtifact({ type: "file", id: "F1", scope: "not-a-scope" }, cap("U1"));assert.equal(badScope.ok, false);@@ -438,7 +462,7 @@ test("an unknown artifact is a not_found; a bad scope id is a bad_request; an un});test("sharing a non-skill to the org is a plain visibility grant (org is everyone's floor — no review)", async () => {- const state = ownerState();+ const state = await ownerState();const svc = createControlService(fakeApp(state));const r = await svc.shareArtifact({ type: "deploy", id: "D1", scope: "org" }, cap("U1"));assert.ok(r.ok);@@ -447,7 +471,7 @@ test("sharing a non-skill to the org is a plain visibility grant (org is everyon});test("sharing into a TEAM the actor belongs to is frictionless (team is a my_scopes context, §3)", async () => {- const state = ownerState();+ const state = await ownerState();state.scopesByPrincipal["U1"] = [scopeId("personal", "U1"), scopeId("org", ORG), scopeId("team", "T1")];const svc = createControlService(fakeApp(state));const r = await svc.shareArtifact({ type: "file", id: "F1", scope: scopeId("team", "T1") }, cap("U1"));@@ -456,7 +480,7 @@ test("sharing into a TEAM the actor belongs to is frictionless (team is a my_sco});test("sharing into a team the actor is NOT on is forbidden", async () => {- const state = ownerState();+ const state = await ownerState();const svc = createControlService(fakeApp(state));const r = await svc.shareArtifact({ type: "file", id: "F1", scope: scopeId("team", "T9") }, cap("U1"));assert.equal(r.ok, false);@@ -464,7 +488,7 @@ test("sharing into a team the actor is NOT on is forbidden", async () => {});test("a move records the acting principal in the audit, not the artifact's creator", async () => {- const state = ownerState();+ const state = await ownerState();state.privateChannels.add("C1");state.artifacts["skill:CM"] = {type: "skill",@@ -489,7 +513,7 @@ test("a move records the acting principal in the audit, not the artifact's creat});test("an automated trigger (no liveActor) cannot MOVE a skill out of its shared home — the move-verb sibling of the shared-skill mutation guard", async () => {- const state = ownerState();+ const state = await ownerState();state.privateChannels.add("C1");state.artifacts["skill:CM"] = {type: "skill",@@ -524,7 +548,7 @@ test("an automated trigger (no liveActor) cannot MOVE a skill out of its shared});test("a trigger (no liveActor) cannot MOVE a personal skill INTO a shared scope either — a move that authors a group-wide skill is guarded like create", async () => {- const state = ownerState();+ const state = await ownerState();state.scopesByPrincipal["U1"] = [scopeId("personal", "U1"), scopeId("org", ORG), scopeId("channel", "C1")];const svc = createControlService(fakeApp(state));const trigger = cap("U1", scopeId("personal", "U1"), false);@@ -560,7 +584,7 @@ function callShareRoute(state: FakeState, capability: CapabilityClaims | null, b}test("POST /v1/share: a single toScope (scope id) → 200 grant; a name → directory-resolved", async () => {- const byScope = await callShareRoute(ownerState(), cap("U1"), {+ const byScope = await callShareRoute(await ownerState(), cap("U1"), {type: "file",id: "F1",toScope: scopeId("channel", "C1"),@@ -569,13 +593,13 @@ test("POST /v1/share: a single toScope (scope id) → 200 grant; a name → direassert.equal(byScope.body.verb, "share");assert.equal(byScope.body.target.scope, scopeId("channel", "C1"));- const byName = await callShareRoute(ownerState(), cap("U1"), { type: "file", id: "F1", toScope: "carol" });+ const byName = await callShareRoute(await ownerState(), cap("U1"), { type: "file", id: "F1", toScope: "carol" });assert.equal(byName.status, 200);assert.equal(byName.body.target.label, "Carol");});test("POST /v1/share: no capability → 403; bad type/missing fields → 400; non-admin org cede → 403", async () => {- const state = ownerState();+ const state = await ownerState();assert.equal((await callShareRoute(state, null, { type: "file", id: "F1", toScope: "org" })).status, 403);assert.equal((await callShareRoute(state, cap("U1"), { type: "bogus", id: "F1", toScope: "org" })).status, 400);assert.equal((await callShareRoute(state, cap("U1"), { type: "file", toScope: "org" })).status, 400);diff --git a/test/sharing-context-e2e.test.ts b/test/sharing-context-e2e.test.tsindex 829c6e8eb..426db8fe7 100644--- a/test/sharing-context-e2e.test.ts+++ b/test/sharing-context-e2e.test.ts@@ -1,3 +1,4 @@+import { randomUUID } from "node:crypto";import { credentialHandle } from "../src/credentials/keychain.ts";import "./support/auto-fake-sprites.ts";import { test, type TestContext } from "node:test";@@ -78,7 +79,27 @@ async function fixture(t: TestContext, config: Partial<Config> = {}) {members = members.filter((m) => m !== id);await roster();};- return { ...built, turn, skill, remove };+ const fileIds = new Map<string, string>();+ const file = async (ownerScopeId: string, name: string, data: string | Buffer) => {+ for (const existing of (await built.files.listOwnedByScopes([ownerScopeId])).files) {+ if (existing.name === name) await built.files.setEnabled(existing.id, false);+ }+ const id = randomUUID();+ fileIds.set(`${ownerScopeId}/${name}`, id);+ await built.files.put({+ id,+ ownerScopeId,+ createdBy: ownerScopeId === "channel:C1" ? "U1" : ownerScopeId.slice("personal:".length),+ name,+ path: name,+ mimetype: "application/octet-stream",+ data: Buffer.from(data),+ direction: "out",+ });+ };+ const filePath = (ownerScopeId: string, name: string) =>+ `shared/open-${ownerScopeId.replace(":", "-")}/${fileIds.get(`${ownerScopeId}/${name}`)}/${name}`;+ return { ...built, turn, skill, remove, file, filePath };}test("sharing e2e: personal files and memories follow the speaker, opt-out, and automation boundaries", async (t) => {@@ -87,33 +108,35 @@ test("sharing e2e: personal files and memories follow the speaker, opt-out, and["U1", "ALICE_PAYLOAD"],["U2", "BOB_PAYLOAD"],]) {- await b.workspace.write(`personal:${id}`, "notes.txt", marker!);+ await b.file(`personal:${id}`, "notes.txt", marker!);await b.memory.capture(`personal:${id}`, [`OWN_MEMORY_${id}`], Date.now(), id!);}- assert.equal(await b.turn("!read shared/open-personal-U1/notes.txt", true), "ALICE_PAYLOAD");+ assert.equal(await b.turn(`!read ${b.filePath("personal:U1", "notes.txt")}`, true), "ALICE_PAYLOAD");assert.doesNotMatch(await b.turn("!memorysearch OWN_MEMORY", true), /OWN_MEMORY_U1/);assert.doesNotMatch(await b.turn("!sysprompt", true), /OWN_MEMORY_U2|open-personal-U2/);- assert.match(await b.turn("!read shared/open-personal-U1/notes.txt", true, "U2"), /no file/);- assert.equal(await b.turn("!read shared/open-personal-U2/notes.txt", true, "U2"), "BOB_PAYLOAD");+ assert.match(await b.turn(`!read ${b.filePath("personal:U1", "notes.txt")}`, true, "U2"), /no file/);+ assert.equal(await b.turn(`!read ${b.filePath("personal:U2", "notes.txt")}`, true, "U2"), "BOB_PAYLOAD");assert.equal(- await b.turn("!read shared/open-personal-U2/notes.txt", true, "U2", { origin: { kind: "ambient", live: true } }),+ await b.turn(`!read ${b.filePath("personal:U2", "notes.txt")}`, true, "U2", {+ origin: { kind: "ambient", live: true },+ }),"BOB_PAYLOAD",);await b.config.setSharingPosture("personal:U1", "isolated");- await b.workspace.write("personal:U1", "notes.txt", "NEW_PRIVATE_PAYLOAD");- assert.match(await b.turn("!read shared/open-personal-U1/notes.txt", true), /no file/);+ await b.file("personal:U1", "notes.txt", "NEW_PRIVATE_PAYLOAD");+ assert.match(await b.turn(`!read ${b.filePath("personal:U1", "notes.txt")}`, true), /no file/);assert.doesNotMatch(await b.turn("!memorysearch OWN_MEMORY", true), /OWN_MEMORY_U1/);await b.config.clearSharingPosture("personal:U1");- assert.equal(await b.turn("!read shared/open-personal-U1/notes.txt", true), "NEW_PRIVATE_PAYLOAD");+ assert.equal(await b.turn(`!read ${b.filePath("personal:U1", "notes.txt")}`, true), "NEW_PRIVATE_PAYLOAD");assert.match(- await b.turn("!read shared/open-personal-U1/notes.txt", true, "U1", { origin: { kind: "automation" } }),+ await b.turn(`!read ${b.filePath("personal:U1", "notes.txt")}`, true, "U1", { origin: { kind: "automation" } }),/no file/,);});test("sharing e2e: a delegated turn shares its live parent's access under current sharing permission", async (t) => {const b = await fixture(t, { apiBaseUrl: "https://core.example.com", signingSecret: "test-ingress-secret" });- await b.workspace.write("personal:U1", "notes.txt", "DELEGATED_PERSONAL_FILE");+ await b.file("personal:U1", "notes.txt", "DELEGATED_PERSONAL_FILE");await b.turn("inspect my personal notes", true);const parent = await b.runs.latestForThread("C1:shared-test");assert.ok(parent);@@ -162,7 +185,7 @@ test("sharing e2e: a delegated turn shares its live parent's access under currenawait sleep(25);}};- const read = "!read shared/open-personal-U1/notes.txt";+ const read = `!read ${b.filePath("personal:U1", "notes.txt")}`;assert.equal(await childTurn(read), "DELEGATED_PERSONAL_FILE");assert.equal(await childTurn("!run echo delegated"), "delegated");assert.ok(token);@@ -179,18 +202,18 @@ test("sharing e2e: a delegated turn shares its live parent's access under currentest("sharing e2e: room file and memory access is revoked on the next DM turn", async (t) => {const b = await fixture(t);- await b.workspace.write("channel:C1", "plan.txt", "ROOM_FILE");+ await b.file("channel:C1", "plan.txt", "ROOM_FILE");await b.memory.capture("channel:C1", ["ROOM_MEMORY"], Date.now(), "U1");await b.turn("hello", true);- assert.equal(await b.turn("!read shared/open-channel-C1/plan.txt"), "ROOM_FILE");+ assert.equal(await b.turn(`!read ${b.filePath("channel:C1", "plan.txt")}`), "ROOM_FILE");assert.match(await b.turn("!memorysearch ROOM_MEMORY"), /ROOM_MEMORY/);await b.config.setSharingPosture("channel:C1", "isolated");- assert.match(await b.turn("!read shared/open-channel-C1/plan.txt"), /no file/);+ assert.match(await b.turn(`!read ${b.filePath("channel:C1", "plan.txt")}`), /no file/);assert.doesNotMatch(await b.turn("!memorysearch ROOM_MEMORY"), /ROOM_MEMORY/);await b.config.clearSharingPosture("channel:C1");- assert.equal(await b.turn("!read shared/open-channel-C1/plan.txt"), "ROOM_FILE");+ assert.equal(await b.turn(`!read ${b.filePath("channel:C1", "plan.txt")}`), "ROOM_FILE");await b.remove("U1");- assert.match(await b.turn("!read shared/open-channel-C1/plan.txt"), /no file/);+ assert.match(await b.turn(`!read ${b.filePath("channel:C1", "plan.txt")}`), /no file/);assert.doesNotMatch(await b.turn("!memorysearch ROOM_MEMORY"), /ROOM_MEMORY/);assert.doesNotMatch(await b.turn("!sysprompt"), /ROOM_MEMORY|open-channel-C1/);});@@ -263,12 +286,12 @@ test("sharing e2e: local skill name wins, then exposes the carried fallback whentest("sharing e2e: writes and memory capture remain local while reading carried context", async (t) => {const b = await fixture(t, { memoryCapture: "writable" });- await b.workspace.write("personal:U1", "notes.txt", "SOURCE_UNCHANGED");+ await b.file("personal:U1", "notes.txt", "SOURCE_UNCHANGED");await b.memory.capture("personal:U1", ["PERSONAL_SOURCE_MEMORY"], Date.now(), "U1");- assert.equal(await b.turn("!read shared/open-personal-U1/notes.txt", true), "SOURCE_UNCHANGED");+ assert.equal(await b.turn(`!read ${b.filePath("personal:U1", "notes.txt")}`, true), "SOURCE_UNCHANGED");assert.match(await b.turn("!write notes.txt ROOM_WRITE", true), /wrote/);assert.match(await b.turn("!memoryremember ROOM_CAPTURE_ONLY", true), /remembered 1/);- assert.equal(await b.workspace.read("personal:U1", "notes.txt"), "SOURCE_UNCHANGED");+ assert.equal(await b.turn(`!read ${b.filePath("personal:U1", "notes.txt")}`, true), "SOURCE_UNCHANGED");assert.equal(await b.workspace.read("channel:C1", "notes.txt"), "ROOM_WRITE");assert.match(await b.memory.read("channel:C1"), /ROOM_CAPTURE_ONLY/);assert.doesNotMatch(await b.memory.read("personal:U1"), /ROOM_CAPTURE_ONLY/);@@ -292,27 +315,39 @@ test("sharing e2e: binary carry never materializes bytes and text artifacts usedirection: "out",});await b.workspace.write("personal:U1", path, "STALE_WORKSPACE_SNAPSHOT");- assert.equal(await b.turn(`!read shared/open-personal-U1/${path}`, true), "CURRENT_ARTIFACT");- await b.workspace.write("personal:U1", "binary.dat", Buffer.from([0xff, 0xfe, 0, 1]));+ assert.equal(await b.turn(`!read shared/open-personal-U1/${id}/report.txt`, true), "CURRENT_ARTIFACT");+ await b.file("personal:U1", "binary.dat", Buffer.from([0xff, 0xfe, 0, 1]));assert.match(- await b.turn("!read shared/open-personal-U1/binary.dat", true),- /Binary files require an explicit share/,+ await b.turn(`!read ${b.filePath("personal:U1", "binary.dat")}`, true),+ /binary file binary.dat, Files ID .+; send it by ID/,);assert.equal(- await b.turn("!run python3 -c \"import os; print(os.path.exists('shared/open-personal-U1/binary.dat'))\"", true),+ await b.turn(+ `!run python3 -c "import os; print(os.path.exists('${b.filePath("personal:U1", "binary.dat")}'))"`,+ true,+ ),"False",);await b.config.setSharingPosture("personal:U1", "isolated");- assert.match(await b.turn(`!read shared/open-personal-U1/${path}`, true), /no file/);+ assert.match(await b.turn(`!read shared/open-personal-U1/${id}/report.txt`, true), /no file/);});test("sharing e2e: explicit text-file grants survive Isolated and revoke without stale reads", async (t) => {const b = await fixture(t);- await b.workspace.write("personal:U2", "shared-note.txt", "EXPLICIT_TEXT");+ await b.files.put({+ id: "shared-note",+ ownerScopeId: "personal:U2",+ createdBy: "U2",+ name: "shared-note.txt",+ path: "shared-note.txt",+ mimetype: "text/plain",+ data: Buffer.from("EXPLICIT_TEXT"),+ direction: "out",+ });await b.acl.grant({ownerScopeId: "personal:U2",- ref: "shared-note.txt",+ ref: "shared-note",granteeScopeId: "personal:U1",permission: "read",grantedBy: "U2",@@ -322,7 +357,7 @@ test("sharing e2e: explicit text-file grants survive Isolated and revoke withoutawait b.config.setSharingPosture("org:default-org", "isolated");assert.equal(await b.turn("!read shared/shared-note.txt"), "EXPLICIT_TEXT");assert.match(await b.turn("!read shared/shared-note.txt", true), /no file/);- await b.acl.revoke("personal:U2", "shared-note.txt", "personal:U1", "U2", "U2");+ await b.acl.revoke("personal:U2", "shared-note", "personal:U1", "U2", "U2");assert.match(await b.turn("!read shared/shared-note.txt"), /no file/);});@@ -337,12 +372,12 @@ test("sharing e2e: unavailable connector skills cannot be read or executed", asyfor (const memoryRecall of ["off", "writable"] as const) {test(`sharing e2e: memory ${memoryRecall} does not disable carried files or skills`, async (t) => {const b = await fixture(t, { memoryRecall });- await b.workspace.write("personal:U1", "notes.txt", "FILE_WITH_MEMORY_RESTRICTED");+ await b.file("personal:U1", "notes.txt", "FILE_WITH_MEMORY_RESTRICTED");await b.memory.capture("personal:U1", ["NO_CARRIED_MEMORY"], Date.now(), "U1");await b.skill("personal:U1", "independent-helper", "SKILL_WITH_MEMORY_RESTRICTED");assert.doesNotMatch(await b.turn("!sysprompt", true), /NO_CARRIED_MEMORY/);assert.doesNotMatch(await b.turn("!memorysearch NO_CARRIED_MEMORY", true), /NO_CARRIED_MEMORY/);- assert.equal(await b.turn("!read shared/open-personal-U1/notes.txt", true), "FILE_WITH_MEMORY_RESTRICTED");+ assert.equal(await b.turn(`!read ${b.filePath("personal:U1", "notes.txt")}`, true), "FILE_WITH_MEMORY_RESTRICTED");assert.equal(await b.turn("!skill-run independent-helper python3 {dir}/scripts/value.py", true),"SKILL_WITH_MEMORY_RESTRICTED",diff --git a/test/sharing-posture.test.ts b/test/sharing-posture.test.tsindex 5315f55f4..6374571ea 100644--- a/test/sharing-posture.test.ts+++ b/test/sharing-posture.test.ts@@ -1,3 +1,4 @@+import { readContextFile } from "../src/resolution/context-files.ts";import assert from "node:assert/strict";import test from "node:test";import { composeSharingPosture, parseSharingPosture, type SharingPosture } from "../src/resolution/sharing-posture.ts";@@ -10,12 +11,8 @@ import {import { createMemoryConfigStore, type PersistedSharingPosture } from "../src/resolution/config-store.ts";import { createMemoryMap } from "../src/persistence/durable-map.ts";import { scopeId, type Principal, type Session } from "../src/types.ts";-import { createLocalWorkspaceStore } from "../src/workspace/workspace-store.ts";import { createMemoryFileArtifactStore } from "../src/files/file-artifact-store.ts";import { createMemoryDurableByteStore } from "../src/files/durable-byte-store.ts";-import { join } from "node:path";-import { mkdtemp } from "node:fs/promises";-import { tmpdir } from "node:os";import { createIsCurrentSharedScopeMember } from "../src/resolution/scope-membership.ts";test("sharing posture is isolated by default and isolated wins composition", () => {@@ -190,13 +187,9 @@ test("DM carry is recent, bounded, non-transitive, source-vetoed, and revoked by});test("carried file handles expose only selected source scopes read-only without mounting them", async () => {- const root = await mkdtemp(join(tmpdir(), "sharing-handles-"));- const workspace = createLocalWorkspaceStore(root);const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());const personal = scopeId("personal", "U1");const teammate = scopeId("personal", "U2");- await workspace.write(personal, "notes/private.txt", "mine");- await workspace.write(teammate, "teammate-secret.txt", "theirs");await files.put({id: "1".repeat(32),ownerScopeId: personal,@@ -207,13 +200,20 @@ test("carried file handles expose only selected source scopes read-only withoutdata: Buffer.from("artifact"),direction: "in",});- const handles = await carriedFileHandles([personal], workspace, files);+ await files.put({+ id: "3".repeat(32),+ ownerScopeId: teammate,+ createdBy: "U2",+ name: "secret.txt",+ path: "secret.txt",+ mimetype: "text/plain",+ data: Buffer.from("theirs"),+ direction: "in",+ });+ const handles = await carriedFileHandles([personal], files);assert.deepEqual(- handles.map((handle) => [handle.ownerScopeId, handle.ownerPath, handle.permission]),- [- [personal, "notes/private.txt", "read"],- [personal, `artifacts/${"1".repeat(32)}/artifact.txt`, "read"],- ],+ handles.map((handle) => [handle.ownerScopeId, handle.fileId, handle.permission]),+ [[personal, "1".repeat(32), "read"]],);assert.equal(handles.some((handle) => handle.ownerScopeId === teammate),@@ -224,17 +224,21 @@ test("carried file handles expose only selected source scopes read-only withoutid: secondArtifactId,ownerScopeId: personal,createdBy: "U1",- name: "second-artifact.txt",- path: `artifacts/${secondArtifactId}/second-artifact.txt`,+ name: "artifact.txt",+ path: `artifacts/${secondArtifactId}/artifact.txt`,mimetype: "text/plain",data: Buffer.from("second artifact"),direction: "in",});- const pagedHandles = await carriedFileHandles([personal], workspace, {- listOwnedByScopes: (scopes, opts) => files.listOwnedByScopes(scopes, { ...opts, limit: 1 }),- });+ const handlesAgain = await carriedFileHandles([personal], files);+ assert.equal(new Set(handlesAgain.map((handle) => handle.handlePath)).size, 2);+ for (const handle of handlesAgain) {+ const read = await readContextFile(handle.handlePath, handlesAgain, files);+ assert.ok(read && "bytes" in read);+ assert.equal(read.bytes?.toString(), handle.fileId === secondArtifactId ? "second artifact" : "artifact");+ }assert.equal(- pagedHandles.some((handle) => handle.ownerPath === `artifacts/${secondArtifactId}/second-artifact.txt`),+ handlesAgain.some((handle) => handle.fileId === secondArtifactId),true,);});@@ -273,35 +277,22 @@ test("Open examines a bounded candidate window even when every membership is revassert.equal(checks, 100);});-test("Open file enumeration is globally capped and excludes the memory notebook", async () => {- const root = await mkdtemp(join(tmpdir(), "sharing-cap-"));- const workspace = createLocalWorkspaceStore(root);- const personal = scopeId("personal", "U1");- await workspace.write(personal, "memory/MEMORY.md", "PRIVATE_NOTE");- for (let i = 0; i < 210; i++) await workspace.write(personal, `file-${i}.txt`, "file");- const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());- const handles = await carriedFileHandles([personal], workspace, files);- assert.ok(handles.length <= 200);- assert.equal(- handles.some((handle) => handle.ownerPath === "memory/MEMORY.md"),- false,- );- assert.ok((await workspace.list(personal, { limit: 3 })).length <= 3);-});--test("Open excludes memory notebook aliases with Windows separators", async () => {- const personal = scopeId("personal", "U1");- const root = await mkdtemp(join(tmpdir(), "sharing-memory-alias-"));- const workspace = createLocalWorkspaceStore(root);+test("Open file enumeration is globally capped across selected scopes", async () => {const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());- await workspace.write(personal, "memory/MEMORY.md", "PRIVATE");- const handles = await carriedFileHandles(- [personal],- {- scopeDir: workspace.scopeDir,- list: async () => [join(workspace.scopeDir(personal), "memory\\MEMORY.md")],- },- files,- );- assert.deepEqual(handles, []);+ const scopes = [scopeId("personal", "U1"), scopeId("channel", "C1")];+ for (let i = 0; i < 210; i++) {+ await files.put({+ id: i.toString(16).padStart(32, "0"),+ ownerScopeId: scopes[i % 2]!,+ createdBy: "U1",+ name: `file-${i}.txt`,+ path: `file-${i}.txt`,+ mimetype: "text/plain",+ data: Buffer.from("file"),+ direction: "in",+ });+ }+ const handles = await carriedFileHandles(scopes, files);+ assert.equal(handles.length, 200);+ assert.equal(new Set(handles.map((handle) => handle.ownerScopeId)).size, 2);});diff --git a/test/skills-source-read.test.ts b/test/skills-source-read.test.tsindex 1b76d7a0b..d0950e708 100644--- a/test/skills-source-read.test.ts+++ b/test/skills-source-read.test.ts@@ -114,6 +114,7 @@ test("published source follows scope shadowing and preserves sandbox-authored wotest("a body read avoids sandbox work and a file request materializes that skill under the skills root", async () => {const { createTurnSandboxes } = await import("../src/core/orchestrator/sandboxes.ts");+ const { SandboxAccessError } = await import("../src/sandbox/sandbox-resources.ts");type TurnSandboxContext = import("../src/core/orchestrator/sandboxes.ts").TurnSandboxContext;type SkillResolution = import("../src/skills/skill-store.ts").SkillResolution;const files = new Map<string, string>();@@ -141,12 +142,17 @@ test("a body read avoids sandbox work and a file request materializes that skillconst turn = createTurnSandboxes({deps: {skills: { recordUse: async () => {} },- sandboxResources: { access: async () => ({ id: "resource-1", ownerScopeId: "personal:U1" }) },+ sandboxResources: {+ access: async (_actor: string, id: string) => {+ if (id !== "resource-1" && id !== "box") throw new SandboxAccessError("sandbox not found");+ return { id, ownerScopeId: "personal:U1" };+ },+ },sandbox: {provision: async (_layers: unknown, options?: { sandboxId?: string }) => {sandboxIds.push(options?.sandboxId);provisions++;- return handle;+ return { ...handle, id: options?.sandboxId ?? handle.id };},listDir: async () => [],removeDir: async () => {},@@ -176,6 +182,9 @@ test("a body read avoids sandbox work and a file request materializes that skilldelete bodyOnly.skill!.pack;visible.push(bodyOnly);assert.deepEqual(await turn.useSkill("body-only", "SKILL.md"), { content: "BODY", sourceScopeId: "personal:U1" });+ await assert.rejects(turn.useSkill("source-helper", "SKILL.md", ""), /non-empty/);+ await assert.rejects(turn.useSkill("source-helper", "SKILL.md", "missing"), /sandbox not found/);+ assert.equal(provisions, 0);await turn.provision();assert.equal(provisions, 1);assert.equal(files.size, 0);@@ -191,6 +200,8 @@ test("a body read avoids sandbox work and a file request materializes that skillfiles.set(`${root}/source-helper/references/example.txt`, "local edit");assert.equal((await turn.useSkill("source-helper", "SKILL.md")).dir, loaded.dir);assert.equal(files.get(`${root}/source-helper/references/example.txt`), "local edit");+ await turn.useSkill("source-helper", "SKILL.md", "box");+ assert.equal(files.get(`${root}/source-helper/references/example.txt`), "local edit");resolution.skill!.pack = { packId: "pack", commit: "c", upstreamName: "source-helper" };resolution.screenedBundles = [{ packId: "pack", commit: "c", hash: "pack-hash", files: [{ path: "lib.txt", content: "PACK_RESOURCE" }] },@@ -201,7 +212,7 @@ test("a body read avoids sandbox work and a file request materializes that skillconst onResource = await turn.useSkill("source-helper", "SKILL.md", "resource-1");assert.equal(onResource.dir, loaded.dir);assert.equal(onResource.packDir, `/workspace/${root}/.packs/pack`);- assert.deepEqual(sandboxIds, [undefined, "resource-1"]);+ assert.deepEqual(sandboxIds, [undefined, "box", "resource-1"]);assert.equal(files.get(`${root}/.packs/pack/lib.txt`), "PACK_RESOURCE");assert.equal([...files.keys()].some((path) => path.includes("/unrelated/")),diff --git a/test/support/file-document-listing.ts b/test/support/file-document-listing.tsindex 2c97c4221..4698062c6 100644--- a/test/support/file-document-listing.ts+++ b/test/support/file-document-listing.ts@@ -30,7 +30,7 @@ export async function assertDocumentListing(store: FileArtifactStore): Promise<vconst disabled = (await put("disabled", "same", 0)).artifact;await store.setEnabled(disabled.id, false);await put("other-scope", "same", 5, { createdInScope: elsewhere });- const refs = [shared, second].map(({ ownerScopeId, path }) => ({ ownerScopeId, path }));+ const refs = [shared, second].map(({ ownerScopeId, id }) => ({ ownerScopeId, id }));assert.deepEqual((await store.listDocuments([], [], { limit: 1 })).files, []);assert.deepEqual((await store.listDocuments([], refs, { createdInScope: project })).files.map((f) => f.id),@@ -43,15 +43,11 @@ export async function assertDocumentListing(store: FileArtifactStore): Promise<v);assert.ok(first.nextCursor);await put("second-later-copy", "different", 100, { ownerScopeId: teammate });- const next = await store.listDocuments(- [mine],- [...refs, { ownerScopeId: teammate, path: "artifacts/second-later-copy/report.txt" }],- {- createdInScope: project,- limit: 1,- cursor: first.nextCursor,- },- );+ const next = await store.listDocuments([mine], [...refs, { ownerScopeId: teammate, id: "second-later-copy" }], {+ createdInScope: project,+ limit: 1,+ cursor: first.nextCursor,+ });assert.deepEqual(next.files.map((f) => f.id),["owned"],@@ -65,7 +61,7 @@ export async function assertDocumentListing(store: FileArtifactStore): Promise<v"raw artifact listing keeps the per-turn ledger",);assert.deepEqual(- (await store.resolveByOwnerPaths([shared, hidden])).map((f) => f.id).sort(),+ (await store.resolveByIds([shared, hidden])).map((f) => f.id).sort(),["hidden", "shared"],"exact handle lookups do not collapse",);@@ -93,3 +89,33 @@ export async function assertDocumentListing(store: FileArtifactStore): Promise<v);assert.equal(scoped.nextCursor, undefined);}++export async function assertSharedRecordIdentity(store: FileArtifactStore): Promise<void> {+ const ownerScopeId = scopeId("personal", "record-owner");+ const input = {+ ownerScopeId,+ createdBy: "record-owner",+ path: "report.txt",+ name: "report.txt",+ mimetype: "text/plain",+ direction: "out" as const,+ };+ await store.put({ ...input, id: "record-first", data: Buffer.from("first") });+ await store.put({ ...input, id: "record-second", data: Buffer.from("second") });+ const refs = [{ ownerScopeId, id: "record-first" }];+ assert.deepEqual(+ (await store.resolveByIds(refs)).map((file) => file.id),+ ["record-first"],+ );+ assert.deepEqual(+ (await store.listDocuments([], refs)).files.map((file) => file.id),+ ["record-first"],+ );+ assert.deepEqual(+ await store.resolveByIds([{ ownerScopeId: scopeId("personal", "stranger"), id: "record-first" }]),+ [],+ );+ await store.delete("record-first");+ assert.deepEqual(await store.resolveByIds(refs), []);+ assert.deepEqual((await store.listDocuments([], refs)).files, []);+}diff --git a/test/surface-post-files.test.ts b/test/surface-post-files.test.tsindex eccad9d36..02c6b6d21 100644--- a/test/surface-post-files.test.ts+++ b/test/surface-post-files.test.ts@@ -1,6 +1,13 @@+import { Readable } from "node:stream";+import { createAttachStaging } from "../src/core/orchestrator/attach-tool.ts";import { test } from "node:test";import assert from "node:assert/strict";-import { collectNamedOutbound, type ArtifactRegistration } from "../src/core/attachments.ts";+import {+ collectNamedOutbound,+ parseOutboundFiles,+ MAX_ATTACHMENT_BYTES,+ type ArtifactRegistration,+} from "../src/core/attachments.ts";import { createSurfaceToolDeps, type SurfaceToolsContext } from "../src/core/orchestrator/surface-tools.ts";import { turnPostKeys } from "../src/core/orchestrator/turn-helpers.ts";import { createMemoryBlobTransferStore } from "../src/persistence/blob-transfer.ts";@@ -44,9 +51,7 @@ test("collectNamedOutbound: rejects parent traversal before reading outside thereturn bytes("secret");},} as unknown as Sandbox;- const r = await collectNamedOutbound(sandbox, handle, paths, transfer);- assert.deepEqual(r.missing, invalid);- assert.deepEqual(r.attachments, []);+ await assert.rejects(collectNamedOutbound(sandbox, handle, paths, transfer), /no \.\. path segments/);assert.deepEqual(reads, []);assert.equal(await transfer.sweep(0), 0);});@@ -220,3 +225,155 @@ test("surface post returns the sent attachments' metadata (so surfaces can rendeassert.ok(a.artifactId, "artifact id present so the web surface can serve the bytes");assert.ok(!("blobId" in a), "internal blob handle is not leaked to surfaces");});++test("stored files retain metadata and need no sandbox, including replacement and failed batches", async () => {+ const store = createMemoryFileArtifactStore(createMemoryDurableByteStore());+ const transfer = createMemoryBlobTransferStore();+ await store.put({+ id: "saved",+ ownerScopeId: "personal:U1",+ createdBy: "U1",+ name: "report.custom",+ path: "report.custom",+ mimetype: "text/custom",+ data: bytes("saved data"),+ direction: "out",+ });+ const staging = createAttachStaging({+ sandbox: undefined as unknown as Sandbox,+ provision: async () => {+ throw new Error("no default sandbox");+ },+ blobTransfer: transfer,+ fileRegistration: { store, ownerScopeId: "personal:U1", createdBy: "U1", seed: "new" },+ openStored: async (id) => {+ const opened = await store.open(id);+ return opened ? { ...opened.artifact, stream: opened.stream } : null;+ },+ });+ assert.equal((await staging.attach([{ file_id: "saved" }])).ok, true);+ const first = staging.staged()[0]!;+ assert.equal(first.artifactId, "saved");+ assert.equal(first.mimetype, "text/custom");+ assert.equal(first.name, "report.custom");+ assert.equal((await staging.attach([{ file_id: "saved" }])).ok, true);+ assert.equal(await transfer.open(first.blobId), null);+ assert.equal(staging.staged().length, 1);+ assert.equal((await staging.attach([{ file_id: "saved" }, { file_id: "denied" }])).ok, false);+ assert.equal(staging.staged().length, 1);+ assert.ok(await store.get("saved"), "rollback never deletes the source artifact");+});++test("workspace staging selects the requested sandbox and never falls back on rejected IDs", async () => {+ const selected: Array<string | undefined> = [];+ const transfer = createMemoryBlobTransferStore();+ const staging = createAttachStaging({+ sandbox: {+ async readFileBytes(box: SandboxHandle) {+ return bytes(box.id);+ },+ } as unknown as Sandbox,+ provision: async (id) => {+ selected.push(id);+ if (id === "denied") throw new Error("unauthorized");+ return { ...handle, id: id ?? "default" };+ },+ blobTransfer: transfer,+ fileRegistration: {+ store: createMemoryFileArtifactStore(createMemoryDurableByteStore()),+ ownerScopeId: "personal:U1",+ createdBy: "U1",+ seed: "selector",+ },+ });+ await staging.attach(["report.txt"], "one");+ await staging.attach(["report.txt"], "two");+ assert.equal(staging.staged().length, 2, "the same path on different computers is not a replacement");+ await assert.rejects(staging.attach(["report.txt"], "denied"), /unauthorized/);+ assert.deepEqual(selected, ["one", "two", "denied"]);+});++test("stored file validation rejects malformed inputs, excessive counts and oversized streams", async () => {+ for (const input of [+ [{}],+ [{ file_id: "" }],+ [{ file_id: "id", path: "ambiguous" }],+ [12],+ Array(21).fill({ file_id: "id" }),+ ])+ assert.equal(parseOutboundFiles(input).ok, false);+ let opened = 0;+ const transfer = createMemoryBlobTransferStore();+ const result = await collectNamedOutbound(+ undefined,+ async () => {+ throw new Error("sandbox not needed");+ },+ [{ file_id: "large" }],+ transfer,+ undefined,+ [],+ async () => {+ opened++;+ return {+ name: "large.zip",+ mimetype: "application/zip",+ sizeBytes: MAX_ATTACHMENT_BYTES + 1,+ stream: Readable.from(["not read"]),+ };+ },+ );+ assert.equal(opened, 1);+ assert.deepEqual(result.oversized, ["large"]);+ assert.deepEqual(result.attachments, []);+ assert.equal(await transfer.sweep(0), 0);+});++test("a stored stream failure rolls back earlier workspace staging", async () => {+ const store = createMemoryFileArtifactStore(createMemoryDurableByteStore());+ const transfer = createMemoryBlobTransferStore();+ await assert.rejects(+ collectNamedOutbound(+ fakeSandbox({ "report.txt": bytes("hello") }),+ handle,+ ["report.txt", { file_id: "broken" }],+ transfer,+ { store, ownerScopeId: "personal:U1", createdBy: "U1", seed: "rollback" },+ [],+ async () => ({+ name: "broken.txt",+ mimetype: "text/plain",+ sizeBytes: 1,+ stream: Readable.from(+ (async function* () {+ yield "partial";+ throw new Error("read failed");+ })(),+ ),+ }),+ ),+ /read failed/,+ );+ assert.equal(await transfer.sweep(0), 0);+ assert.equal((await store.listOwnedByScopes(["personal:U1"])).files.length, 0);+});++test("replacing a path preserves its artifact when staged again by ID", async () => {+ const store = createMemoryFileArtifactStore(createMemoryDurableByteStore());+ const staging = createAttachStaging({+ sandbox: fakeSandbox({ "report.txt": bytes("report") }),+ provision: async () => handle,+ blobTransfer: createMemoryBlobTransferStore(),+ fileRegistration: { store, ownerScopeId: "personal:U1", createdBy: "U1", seed: "reference" },+ openStored: async (id) => {+ const opened = await store.open(id);+ return opened ? { ...opened.artifact, stream: opened.stream } : null;+ },+ });+ await staging.attach(["report.txt"]);+ const id = staging.staged()[0]!.artifactId!;+ await staging.attach([{ file_id: id }]);+ await staging.attach(["report.txt"]);+ assert.equal(staging.staged().length, 2);+ assert.ok(await store.open(id), "the staged file ID remains readable");+});diff --git a/test/system-prompt-order.test.ts b/test/system-prompt-order.test.tsindex 625a65926..2042901ae 100644--- a/test/system-prompt-order.test.ts+++ b/test/system-prompt-order.test.ts@@ -30,7 +30,7 @@ import type { Sandbox } from "../src/sandbox/sandbox.ts";import type { ConnectorStatusCache } from "../src/credentials/connector-status.ts";import type { ConnectorTokenStore } from "../src/credentials/keychain.ts";import { createSkillStore, type SkillStore } from "../src/skills/skill-store.ts";-import { scopeId, type Conversation, type Principal, type TurnRequest } from "../src/types.ts";+import { scopeId, type Conversation, type Principal, type ScopeId, type TurnRequest } from "../src/types.ts";import type { ManagedGroupDirectory } from "../src/resolution/scope-membership.ts";import type { IsCurrentSharedScopeMember } from "../src/resolution/scope-membership.ts";@@ -218,20 +218,23 @@ test("Open carries only the live actor's personal reads into a shared turn and aconst personal = scopeId("personal", actor.id);const teammatePersonal = scopeId("personal", teammate.id);const channelScope = scopeId("channel", "C1");- await workspace.write(personal, "private.txt", "ACTOR_PRIVATE_FILE");- await workspace.write(teammatePersonal, "teammate.txt", "TEAMMATE_PRIVATE_FILE");- await workspace.write(personal, "private.bin", new Uint8Array([255, 254, 0, 1]));- const artifactId = "2".repeat(32);- await files.put({- id: artifactId,- ownerScopeId: personal,- createdBy: actor.id,- name: "private-artifact.txt",- path: `artifacts/${artifactId}/private-artifact.txt`,- mimetype: "text/plain",- data: Buffer.from("ACTOR_PRIVATE_ARTIFACT"),- direction: "in",- });+ const put = (id: string, ownerScopeId: ScopeId, name: string, mimetype: string, data: Uint8Array | string) =>+ files.put({+ id,+ ownerScopeId,+ createdBy: actor.id,+ name,+ path: name,+ mimetype,+ data: Buffer.from(data),+ direction: "in",+ });+ const privateId = "1".repeat(32);+ const teammateId = "3".repeat(32);+ const binaryId = "4".repeat(32);+ await put(privateId, personal, "private.txt", "text/plain", "ACTOR_PRIVATE_FILE");+ await put(teammateId, teammatePersonal, "teammate.txt", "text/plain", "TEAMMATE_PRIVATE_FILE");+ await put(binaryId, personal, "private.bin", "application/octet-stream", new Uint8Array([255, 254, 0, 1]));const channel = (thread: string, text: string, origin: OrchestratorInput["origin"]): OrchestratorInput => ({surface: "test",actor,@@ -251,29 +254,22 @@ test("Open carries only the live actor's personal reads into a shared turn and aawait config.setSharingPosture(scopeId("org", ORG), "open");const open = await orchestrator.handleTurn(- channel("C1:open", "!read shared/open-personal-U1/private.txt", { kind: "human" }),+ channel("C1:open", `!read shared/open-personal-U1/${privateId}/private.txt`, { kind: "human" }),);assert.equal(open.reply, "ACTOR_PRIVATE_FILE");const binary = await orchestrator.handleTurn(- channel("C1:binary", "!read shared/open-personal-U1/private.bin", { kind: "human" }),+ channel("C1:binary", `!read shared/open-personal-U1/${binaryId}/private.bin`, { kind: "human" }),);- assert.match(binary.reply ?? "", /Binary files require an explicit share/);- const artifact = await orchestrator.handleTurn(- channel("C1:artifact", `!read shared/open-personal-U1/artifacts/${artifactId}/private-artifact.txt`, {- kind: "human",- }),- );- assert.equal(artifact.reply, "ACTOR_PRIVATE_ARTIFACT");+ assert.match(binary.reply ?? "", new RegExp(`Files ID ${binaryId}`));const teammateRead = await orchestrator.handleTurn(channel("C1:teammate", "!sysprompt", { kind: "human" }));- assert.doesNotMatch(teammateRead.reply ?? "", /shared\/open-personal-U2\/teammate\.txt/);- await workspace.write(personal, "private.txt", "NEW_PRIVATE_CONTENT");+ assert.doesNotMatch(teammateRead.reply ?? "", /shared\/open-personal-U2\//);const nextActor = await orchestrator.handleTurn({- ...channel("C1:open", "!read shared/open-personal-U1/private.txt", { kind: "human" }),+ ...channel("C1:open", `!read shared/open-personal-U1/${privateId}/private.txt`, { kind: "human" }),actor: teammate,});- assert.doesNotMatch(nextActor.reply ?? "", /NEW_PRIVATE_CONTENT/);+ assert.doesNotMatch(nextActor.reply ?? "", /ACTOR_PRIVATE_FILE/);const nextActorOwn = await orchestrator.handleTurn({- ...channel("C1:open", "!read shared/open-personal-U2/teammate.txt", { kind: "human" }),+ ...channel("C1:open", `!read shared/open-personal-U2/${teammateId}/teammate.txt`, { kind: "human" }),actor: teammate,});assert.equal(nextActorOwn.reply, "TEAMMATE_PRIVATE_FILE");@@ -378,7 +374,7 @@ test("Open advertises the source and audits a carried skill read without grantintest("Open keeps unclassified personal memory out of rooms, loads room memory in DMs, and capture stays in the room", async () => {let member = true;- const { orchestrator, config, memory, workspace } = buildOrchestrator({+ const { orchestrator, config, memory, files } = buildOrchestrator({sandbox: readSandbox(),isCurrentSharedScopeMember: async (principalId, sourceScope) =>member && principalId === actor.id && sourceScope === scopeId("channel", "C1"),@@ -420,9 +416,19 @@ test("Open keeps unclassified personal memory out of rooms, loads room memory in}),);assert.match(search.reply ?? "", /\[channel:C1\].*ROOM_ONLY_MEMORY/);- await workspace.write(channelScope, "decision.txt", "ROOM_DECISION_FILE");+ const decisionId = "5".repeat(32);+ await files.put({+ id: decisionId,+ ownerScopeId: channelScope,+ createdBy: actor.id,+ name: "decision.txt",+ path: "decision.txt",+ mimetype: "text/plain",+ data: Buffer.from("ROOM_DECISION_FILE"),+ direction: "in",+ });const sharedFile = await orchestrator.handleTurn(- dm("dm:U1:room-file", "!read shared/open-channel-C1/decision.txt", { origin: { kind: "human" } }),+ dm("dm:U1:room-file", `!read shared/open-channel-C1/${decisionId}/decision.txt`, { origin: { kind: "human" } }),);assert.equal(sharedFile.reply, "ROOM_DECISION_FILE");@@ -443,7 +449,7 @@ test("Open keeps unclassified personal memory out of rooms, loads room memory in);assert.doesNotMatch(revoked.reply ?? "", /ROOM_ONLY_MEMORY/);const revokedFile = await orchestrator.handleTurn(- dm("dm:U1:room-file", "!read shared/open-channel-C1/decision.txt", { origin: { kind: "human" } }),+ dm("dm:U1:room-file", `!read shared/open-channel-C1/${decisionId}/decision.txt`, { origin: { kind: "human" } }),);assert.doesNotMatch(revokedFile.reply ?? "", /ROOM_DECISION_FILE/);diff --git a/test/turn-context.test.ts b/test/turn-context.test.tsindex 11abd772b..4c2b2a39b 100644--- a/test/turn-context.test.ts+++ b/test/turn-context.test.ts@@ -29,7 +29,7 @@ async function fixture() {sharingPosture: "open",grantedHandles: [],} as unknown as Resolution;- const acl = createAclStore();+ const acl = createAclStore(undefined, { resolveFiles: (refs) => files.resolveByIds(refs) });const input: Parameters<typeof resolveTurnContext>[0] = {actor: { id: "alice", type: "internal" },audience: [{ id: "alice", type: "internal" }],@@ -43,14 +43,22 @@ async function fixture() {resolution,memoryPolicy: { recall: "visible", capture: "writable" },useMemory: true,- workspace,memory,files,auditLog,};await memory.replace("personal:alice", "# Memory\n\n- LOCAL_FACT");await memory.replace("channel:eng", `# Memory\n\n- SHARED_FACT\n- ${"long fact ".repeat(1500)}\n- LAST_FACT`);- await workspace.write("channel:eng", "plan.txt", "PLAN_CONTENT");+ await files.put({+ id: "1".repeat(32),+ ownerScopeId: "channel:eng",+ createdBy: "alice",+ name: "plan.txt",+ path: "plan.txt",+ mimetype: "text/plain",+ data: Buffer.from("PLAN_CONTENT"),+ direction: "in",+ });return {input,acl,@@ -81,7 +89,7 @@ test("one context loads full source-labelled notebooks and shares authority withassert.equal(await context.readFile("shared/open-channel-other/plan.txt"), null);const events = await auditLog.events();assert.ok(events.some((e) => e.resource === "memory" && e.detail?.includes("channel:eng")));- assert.ok(events.some((e) => e.resource === "plan.txt" && e.detail?.includes("channel:eng")));+ assert.ok(events.some((e) => e.resource === "1".repeat(32) && e.detail?.includes("channel:eng")));});for (const mode of [@@ -157,8 +165,8 @@ test("skill discovery uses the same included scopes and audience-filtered explictest("ambiguous file aliases fail closed in the shared reader", async () => {const { input } = await fixture();input.resolution.grantedHandles = [- { handlePath: "shared/plan.txt", ownerScopeId: "personal:alice", ownerPath: "one.txt", permission: "read" },- { handlePath: "shared/plan.txt", ownerScopeId: "personal:alice", ownerPath: "two.txt", permission: "read" },+ { handlePath: "shared/plan.txt", ownerScopeId: "personal:alice", fileId: "1".repeat(32), permission: "read" },+ { handlePath: "shared/plan.txt", ownerScopeId: "personal:alice", fileId: "2".repeat(32), permission: "read" },];const result = await (await resolveTurnContext(input)).readFile("shared/plan.txt");assert.ok(result && "error" in result);