Multiplayer agent harness for work.
Add isolated and open sharing settings (#1048)
Joshua France1366726eb946
diff --git a/.env.example b/.env.exampleindex 7fb0a747f..1017c901d 100644--- a/.env.example+++ b/.env.example@@ -9,6 +9,7 @@ HARNESS=pi# (defaults to ~/.codex/auth.json when HARNESS=codex). Not allowed in production.CODEX_AUTH_FILE=HARNESS_SECURITY_POSTURE=auto+HARNESS_SHARING_POSTURE=isolated#ANTHROPIC_API_KEY=sk-ant-...#OPENAI_API_KEY=sk-...diff --git a/README.md b/README.mdindex 4977984e0..8dc500c6d 100644--- a/README.md+++ b/README.md@@ -32,7 +32,7 @@ isn't tied to any single vendor.work with it collaboratively in Slack channels and projects.- **Slack and web.** The same identity and configuration carries between Slack and theweb app.-- **Admin control.** Set org-level configuration, a security posture, and which+- **Admin control.** Set org-level configuration, security and sharing postures, and whichharnesses and models are available.- **Web apps.** Spin up custom internal apps and publish them to the right people.- **Shared skills.** Skills are scope-owned and shareable by grant, with admin-gated@@ -110,6 +110,27 @@ can only tighten:The predeclared command policy — approval rules and hard denials for things likerecursive deletes or destructive SQL — applies in every posture, Dangerous included.+Sharing posture is independent:++- **Isolated** (default) — resources stay in their scope unless explicitly shared.+- **Open** — on a live authenticated internal human turn, the speaker's opted-in personal+ files, artifacts, skills, and memory may be read in an opted-in shared room. In the+ speaker's DM, files and skills from up to 25 recent shared contexts where they are still+ a member are available. Included memories are loaded into the prompt in full with source-scope+ labels and are also searchable; relevance ranking is not applied.+ The candidate window is limited to 100 recent sessions and file discovery to 200 files.+ Binary files still require explicit sharing before entering another conversation's computer.+ Cross-context memory search is available only through the active turn's memory tool;+ reusable sandbox API tokens retain their original memory scope.++The organization value is a ceiling, and personal and room scopes can opt out; Isolated+wins. “Follow organization” removes a personal or room override. Disabled memory recall+and writable-only recall still apply. Open does not mount a personal workspace into a room, carry credentials or message+history, widen writes, run in automation or ambient turns, cross organizations, add a+teammate's entitlement, or weaken screening, command approvals, or egress. It can still+reveal private information in a shared reply, so cross-context reads are provenance-labelled+and audited.+[`SECURITY.md`](./SECURITY.md) has the threat model, the operator assumptions, and theknown limitations.diff --git a/SECURITY.md b/SECURITY.mdindex 923cf4ae9..bb3574749 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -83,6 +83,21 @@ plaintext credentials while a process is using them. An approval means a humanaccepted the displayed action under the information available at that time, not thatthe resulting behavior is safe.+Sharing posture defaults to Isolated. Open is a deliberate disclosure tradeoff for live,+authenticated internal human turns: core may expose the speaker's opted-in personal files,+artifacts, skills, and memory to an opted-in shared conversation, and may expose files and+skills from up to 25 recent shared contexts in that speaker's DM after rechecking current+membership. Included memories are loaded in full with source-scope labels and searchable through the active+turn's memory tool; they are not added to reusable sandbox API tokens. Candidate discovery+is limited to 100 recent sessions and 200 files, and binary files require explicit sharing+before being copied into a different conversation's computer. Organization, personal, room, and source-room policy compose fail-closed, with+Isolated winning. These reads are labelled and audited, but model output is not a disclosure+control. Open does not change transcript audience filtering, writes or memory capture,+credential materialization, automation or ambient turns, tenant boundaries, another+person's entitlement, command approvals, content screening, or egress. In Auto, carried+skills and their bundled files must pass screening before prompt inclusion or materialization;+flagged, oversized, or unavailable screening leaves the carried skill inaccessible.+### Deliberately portal-only actionsThree actions are intentionally excluded from the agent self-API, even though the@@ -112,6 +127,11 @@ these, not through them.common dangerous forms, but obfuscation, encoding, or writing and then executing ascript can evade it. It is a speed bump against mistakes and injection, not asandbox boundary.+- **Open sharing relies on model discretion after authorization.** Server-side policy,+ identity, membership, source bounds, and read-only capability checks determine which+ resources can enter a turn, but they cannot ensure the model keeps relevant private data+ out of a shared reply. Audit supports investigation after access; it does not prevent+ disclosure.- **Browser actions sit outside some core gates.** Actions inside the browser runnerdo not re-enter command policy or human-in-the-loop approval. They rely ontask-level consent and the runner's spend checks. Browser traffic exits through thediff --git a/plugins/admin/public/index.html b/plugins/admin/public/index.htmlindex 3ab9d6cf3..a72c7dc15 100644--- a/plugins/admin/public/index.html+++ b/plugins/admin/public/index.html@@ -5205,6 +5205,10 @@<span class="k">Autonomy</span><span class="v">Loading</span><span class="detail">Security posture</span></div>+ <div class="governance-status" id="governance-status-sharing">+ <span class="k">Sharing</span><span class="v">Loading</span+ ><span class="detail">Cross-context reads</span>+ </div><div class="governance-status" id="governance-status-egress"><span class="k">Network</span><span class="v">Loading</span><span class="detail">Outbound enforcement</span>@@ -5456,6 +5460,54 @@<h2>Data boundaries</h2><p>What can leave a scope, which audiences can see it, and how deployment authority is carried.</p></div>+ <section class="card sv-governance setting-row hidden" id="card-sharing-posture">+ <div class="head">+ <h2>Sharing posture</h2>+ <p>+ The organization is a ceiling. Personal and room scopes can opt out, and Isolated always wins.+ </p>+ </div>+ <div class="body">+ <p id="sharing-posture-effective"></p>+ <select id="sharing-posture" data-choice-state hidden>+ <option value="isolated">Isolated</option>+ <option value="open">Open</option>+ </select>+ <div class="choice-stack">+ <label class="posture-choice"+ ><input+ type="radio"+ name="sharing-posture-choice"+ value="isolated"+ data-choice-for="sharing-posture"+ /><span+ ><strong>Isolated</strong+ ><small>Resources stay in their own scope unless explicitly shared.</small></span+ ></label+ >+ <label class="posture-choice"+ ><input+ type="radio"+ name="sharing-posture-choice"+ value="open"+ data-choice-for="sharing-posture"+ /><span+ ><strong>Open</strong+ ><small+ >QM can use your saved memories, files, and skills across conversations when you ask it for+ help. In a group conversation, this could risk revealing private information to+ others.</small+ ></span+ ></label+ >+ </div>+ </div>+ <div class="foot">+ <button class="primary" data-save="sharing-posture">Apply</button>+ <button type="button" id="sharing-posture-inherit" hidden>Follow organization</button>+ <span class="status" id="st-sharing-posture"></span>+ </div>+ </section><section class="card sv-governance" id="card-egress"><div class="head"><h2>Egress policy</h2>@@ -6290,6 +6342,7 @@[$("card-security-posture"),$("card-auto-flagger"),+ $("card-sharing-posture"),governanceAmbient,$("card-external-slack"),$("card-command-policy"),@@ -7760,6 +7813,13 @@if (posture === "dangerous") postureTone = "danger";else if (posture === "auto") postureTone = "warn";setGovernanceStatus("governance-status-posture", titleCase(posture), "Effective security posture", postureTone);+ const sharingPosture = data.sharingPosture || "isolated";+ setGovernanceStatus(+ "governance-status-sharing",+ titleCase(sharingPosture),+ "Effective sharing posture",+ sharingPosture === "open" ? "danger" : "ok",+ );const allowCount = (data.egress?.allowedHosts || []).length;const denyCount = (data.egress?.deniedHosts || []).length;const enforcement = data.egressEnforcement || {@@ -7921,6 +7981,9 @@syncAutoFlaggerModels();$("auto-flagger-rubric").value = current.rubric;}+ const showSharingPosture = "sharingPosture" in (r.data || {});+ $("card-sharing-posture").classList.toggle("hidden", !showSharingPosture);+ if (showSharingPosture) renderSharingPosture(r.data);const showGrantModes = "approvalGrantModes" in (r.data || {});$("card-approval-grant-modes").classList.toggle("hidden", !showGrantModes);if (showGrantModes) {@@ -10559,6 +10622,7 @@rubric: $("auto-flagger-rubric").value,}),+ "sharing-posture": () => ({ posture: $("sharing-posture").value }),"approval-grant-modes": () => ({session: $("approval-grant-session").checked,always: $("approval-grant-always").checked,@@ -10591,6 +10655,7 @@const SAVE_ST = {"security-posture": "st-security-posture","auto-flagger": "st-auto-flagger",+ "sharing-posture": "st-sharing-posture","approval-grant-modes": "st-approval-grant-modes","command-policy": "st-policy",soul: "st-soul",@@ -10697,6 +10762,24 @@danger: dangerous,});}+ if (key === "sharing-posture") {+ const before = JSON.parse(sectionSnapshots.get(key) || "{}").posture || "isolated";+ const open = body.posture === "open";+ return reviewGovernanceChange({+ title: open ? "Enable Open sharing?" : "Return to Isolated sharing?",+ subtitle: "This applies to future live human turns in the selected scope.",+ facts: [+ ["Scope", governanceScopeName()],+ ["Current", titleCase(before)],+ ["Proposed", titleCase(body.posture)],+ ],+ warning: open+ ? "Open can reveal a speaker's private information in shared replies. It does not carry credentials, history, writes, automation, or another person's resources. Organization, personal, and room policy must all allow it."+ : "Cross-context resources will again require explicit shares or grants.",+ confirmLabel: open ? "Enable Open" : "Use Isolated",+ danger: open,+ });+ }if (key === "external-slack-participants") {const before = !!JSON.parse(sectionSnapshots.get(key) || "{}").on;return reviewGovernanceChange({@@ -10716,6 +10799,43 @@}return Promise.resolve(true);}+ function renderSharingPosture(data) {+ const effective = data.sharingPosture || "isolated";+ $("sharing-posture").value = effective;+ $("sharing-posture-inherit").hidden = scope.startsWith("org:") || data.sharingPostureOverride == null;+ $("sharing-posture-effective").textContent =+ (data.sharingPostureOverride == null+ ? scope.startsWith("org:")+ ? "Default"+ : "Following organization"+ : "Configured: " + titleCase(data.sharingPostureOverride)) ++ " · Effective: " ++ titleCase(effective);+ document+ .querySelectorAll('[data-choice-for="sharing-posture"]')+ .forEach((input) => (input.checked = input.value === effective));+ }+ $("sharing-posture-inherit").onclick = async () => {+ const requestedScope = scope;+ if (+ !(await reviewGovernanceChange({+ title: "Follow organization sharing?",+ subtitle: "Remove this scope's sharing override.",+ facts: [["Scope", governanceScopeName()]],+ warning:+ "The organization's sharing setting will apply. A personal or room Isolated override still takes precedence.",+ confirmLabel: "Follow organization",+ })) ||+ requestedScope !== scope+ )+ return;+ const result = await api("PUT", "/api/scopes/" + encodeURIComponent(requestedScope) + "/sharing-posture", {+ inherit: true,+ });+ if (requestedScope !== scope) return;+ if (result.ok) await loadScope();+ setStatus("st-sharing-posture", result.ok ? "Saved" : "Could not reset sharing.", result.ok ? "ok" : "err");+ };let governanceSaveSeq = 0;$("auto-flagger-test").onclick = async () => {const requestedScope = scope;@@ -10788,7 +10908,7 @@}if (btn.dataset.saveRequest === saveRequest) delete btn.dataset.saveRequest;if (r.ok) {- if (key === "security-posture" || key === "ambient-policy") {+ if (key === "security-posture" || key === "sharing-posture" || key === "ambient-policy") {const fresh = await api("GET", "/api/scopes/" + encodeURIComponent(scope));if (!fresh.ok) {updateSectionDirty(key);@@ -10797,6 +10917,7 @@}renderGovernanceOverview(fresh.data);if (key === "security-posture") $("security-posture").value = fresh.data.securityPosture || "auto";+ else if (key === "sharing-posture") renderSharingPosture(fresh.data);else renderAmbientPolicy(fresh.data.ambientPolicy);captureSection(key);} else if (key === "branding") {@@ -15211,6 +15332,7 @@: "default",],["Security posture", cfg.securityPosture || "auto"],+ ["Sharing posture", cfg.sharingPosture || "isolated"],["Egress overrides", allowN || denyN ? allowN + " allow · " + denyN + " deny" : "none"],["Base model", cfg.baseModel || "org default"],["Connectors linked", String((cfg.connectors || []).length)],diff --git a/plugins/admin/test/auto-flagger.test.ts b/plugins/admin/test/auto-flagger.test.tsindex 7fc5294cc..60773623f 100644--- a/plugins/admin/test/auto-flagger.test.ts+++ b/plugins/admin/test/auto-flagger.test.ts@@ -129,7 +129,10 @@ test("the card is org-only and follows the current governance layout", () => {vm.runInContext(`{${loadSource}}`, context);assert.ok(elements["card-auto-flagger"].classes.has("hidden"));}- assert.match(html, /\$\("card-security-posture"\),\s*\$\("card-auto-flagger"\),\s*governanceAmbient/);+ assert.match(+ html,+ /\$\("card-security-posture"\),\s*\$\("card-auto-flagger"\),\s*\$\("card-sharing-posture"\),\s*governanceAmbient/,+ );});test("test sends an unsaved draft and comparison window without saving it", async () => {diff --git a/plugins/admin/test/default-view.test.ts b/plugins/admin/test/default-view.test.tsindex 21a12ffb0..7a282c9fb 100644--- a/plugins/admin/test/default-view.test.ts+++ b/plugins/admin/test/default-view.test.ts@@ -168,7 +168,7 @@ test("transcript filters hide diagnostics without hiding folded delivery evidenctest("governance posture saves refresh only the saved card", () => {const reloads = html.match(/const SAVE_RELOADS = new Set\(\[[^\n]+/)?.[0] ?? "";assert.doesNotMatch(reloads, /security-posture|ambient-policy/);- assert.match(html, /if \(key === "security-posture" \|\| key === "ambient-policy"\)/);+ assert.match(html, /if \(key === "security-posture" \|\| key === "sharing-posture" \|\| key === "ambient-policy"\)/);});test("compact ambient reply policy tracks the value after each save", () => {@@ -196,6 +196,7 @@ test("governance retains scoped effective-state data behind the compact referenc}assert.match(html, /function renderGovernanceOverview\(data\)/);assert.match(html, /Effective security posture/);+ assert.match(html, /Effective sharing posture/);assert.match(html, /Resolved at organization scope/);assert.match(html,@@ -213,6 +214,7 @@ test("control-plane pages use the shared web UI canvas without redundant page in);assert.match(html, /--cta: oklch\(0\.27 0\.062 250\)/);assert.match(html, /data-choice-for="security-posture"/);+ assert.match(html, /data-choice-for="sharing-posture"/);assert.match(html, /data-checkbox-for="external-slack-participants"/);assert.match(html, /governanceAmbient\.id = "card-governance-org-ambient"/);assert.match(html, /id="sc-editor"/);@@ -231,6 +233,7 @@ test("control-plane pages use the shared web UI canvas without redundant page intest("governance renders simple settings as compact rows with contextual actions", () => {for (const id of ["card-security-posture",+ "card-sharing-posture","card-external-slack","card-base-model","card-people-directory",@@ -273,6 +276,7 @@ test("compact governance rows preserve policy detail and collapse before they ovtest("governance reviews high-impact changes in product and preserves drafts", () => {assert.match(html, /<dialog class="review-dialog" id="governance-review"/);assert.match(html, /key === "security-posture"/);+ assert.match(html, /key === "sharing-posture"/);assert.match(html, /key === "external-slack-participants"/);assert.match(html, /Review the immutable change below/);assert.match(html, /function hasGovernanceDraft\(\)/);@@ -433,6 +437,7 @@ test("the hidden utility hides an element whose component rule is declared latertest("admin parity views expose the requested card groups and real navigation actions", () => {for (const text of ["Security posture",+ "Sharing posture","Command policy","Ambient reply policy","Egress policy",@@ -536,3 +541,13 @@ test("governance follows the neutral web UI interaction palette", () => {/\.posture-choice:has\(input:checked\) \{\s*border-color: var\(--border\);\s*background: var\(--subtle\)/,);});++test("Open sharing explains the benefit and privacy risk in plain language", () => {+ const card = html.slice(html.indexOf('id="card-sharing-posture"'), html.indexOf('id="card-egress"'));+ assert.match(+ card,+ /QM can use your saved memories, files, and skills across conversations when you ask it for\s+help/,+ );+ assert.match(card, /In a group conversation, this could risk revealing private information to\s+others/);+ assert.doesNotMatch(card, /live internal speaker|entitled resources|opted-in contexts/);+});diff --git a/src/api/routes/admin-resources.ts b/src/api/routes/admin-resources.tsindex c09737035..1b9552a7b 100644--- a/src/api/routes/admin-resources.ts+++ b/src/api/routes/admin-resources.ts@@ -46,6 +46,7 @@ import type { ApprovalGrantModes } from "../../types.ts";import { parseEgressPolicy } from "../../resolution/egress-policy.ts";import { DEVICE_FLOW_CUTOVER_MODES, type DeviceFlowCutoverMode } from "../../credentials/device-flow-cutover.ts";import { FEATURE_NAMES, type FeatureName } from "../../feature-flags.ts";+import { parseSharingPosture, SHARING_POSTURES, type SharingPosture } from "../../resolution/sharing-posture.ts";export interface AutoFlaggerDraft {harnessId: HarnessId;@@ -174,6 +175,27 @@ export const ADMIN_RESOURCES: readonly AdminResource[] = [(deps, scope, posture) => deps.config!.setSecurityPosture(scope, posture),),},+ {+ id: "sharing-posture",+ kind: "enum",+ target: "any",+ label:+ "Cross-context read posture. The organization is a ceiling; personal and room scopes may opt out. Isolated wins.",+ readKey: "sharingPosture",+ enumValues: SHARING_POSTURES,+ get: (deps, scope) => deps.config!.getSharingPostureDurable(scope),+ apply: generic<SharingPosture | null>(+ (body) => {+ if ((body as { inherit?: unknown }).inherit === true) return { value: null };+ const posture = parseSharingPosture((body as { posture?: unknown }).posture);+ return posture+ ? { value: posture }+ : { error: `sharing-posture requires { posture: ${SHARING_POSTURES.join(" | ")} }` };+ },+ (deps, scope, posture) =>+ posture === null ? deps.config!.clearSharingPosture(scope) : deps.config!.setSharingPosture(scope, posture),+ ),+ },{id: "auto-flagger",kind: "custom",diff --git a/src/api/routes/admin/scope-config.ts b/src/api/routes/admin/scope-config.tsindex 7ab0ae478..5182fe045 100644--- a/src/api/routes/admin/scope-config.ts+++ b/src/api/routes/admin/scope-config.ts@@ -270,6 +270,7 @@ export async function getScopeConfig(ctx: ApiCtx): Promise<void> {for (const r of ADMIN_RESOURCES) {if (r.readKey && r.get) values[r.readKey] = await r.get(deps, targetScope);}+ values.sharingPostureOverride = await deps.config.getSharingPostureOwnDurable(targetScope);const scopeProfile = (await deps.sandbox?.profileFor?.(targetScope)) ?? deps.sandbox?.profile;const declaredEgress =scopeProfile?.egressEnforcement ?? deps.egressDeclaredEnforcement ?? deps.egressEnforcement ?? "none";diff --git a/src/config.ts b/src/config.tsindex 62dbd0263..04ef977d2 100644--- a/src/config.ts+++ b/src/config.ts@@ -19,6 +19,7 @@ import type { OrgBranding } from "./resolution/config-store.ts";import { validateCoreSecretEnv } from "./deployment/secret-schema.ts";import { DEFAULT_CAPTURE_QUIET_MS } from "./memory/strategies/per-turn.ts";import { parseSecurityPosture, type SecurityPosture } from "./security/security-posture.ts";+import { parseSharingPosture, type SharingPosture } from "./resolution/sharing-posture.ts";import { slackPluginConfigFromEnv, type SlackPluginConfig } from "./slack/config.ts";import { codexAuthFileForEnv, readCodexOAuthAuthFile } from "./harness/codex-auth-file.ts";import {@@ -47,6 +48,7 @@ export interface Config {harness: "mock" | "pi" | "opencode" | "codex" | "claude";securityPosture: SecurityPosture;sandboxResourcesEnabled: boolean;+ sharingPosture: SharingPosture;sandboxBackend: "aws" | "local" | "sprites" | "smolmachines" | "e2b" | "modal" | "porter" | "agent37";sandboxSecondaryBackend?: "aws" | "local" | "sprites" | "smolmachines" | "e2b" | "modal" | "porter" | "agent37";deployProvider: "docker" | "aws" | "fly" | "porter";@@ -897,6 +899,15 @@ function securityPostureEnvStrict(value: string | undefined): SecurityPosture {);}+function sharingPostureEnvStrict(value: string | undefined): SharingPosture {+ if (value === undefined || value.trim() === "") return "isolated";+ const posture = parseSharingPosture(value);+ if (posture) return posture;+ throw new Error(+ `HARNESS_SHARING_POSTURE=${JSON.stringify(value)} is not recognized — use isolated or open, or unset it.`,+ );+}+function securityScreenBackendEnvStrict(value: string | undefined): Config["securityScreenBackend"] {if (value === undefined || value.trim() === "") return "model";const backend = value.trim().toLowerCase();@@ -1206,6 +1217,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {...(env.DATABASE_CA_CERT_FILE ? { databaseCaCertFile: env.DATABASE_CA_CERT_FILE } : {}),harness,securityPosture: securityPostureEnvStrict(env.HARNESS_SECURITY_POSTURE),+ sharingPosture: sharingPostureEnvStrict(env.HARNESS_SHARING_POSTURE),securityScreenBackend,...(securityScreenBackend === "proxy"? {diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.tsindex f1033b712..2da468296 100644--- a/src/core/orchestrator.ts+++ b/src/core/orchestrator.ts@@ -24,6 +24,8 @@ import { renderGatewayContext } from "./gateway-context.ts";import { deriveTurnOutcome, approvalBlocksInput } from "./turn-outcome.ts";import { applyPromptVars, loadProtocolFile, type PromptVars } from "../resolution/prompt-vars.ts";import { cleanBrandingLabel, resolveBranding } from "../resolution/branding.ts";+import { resolveTurnContext } from "../resolution/turn-context.ts";+import { renderSharingPosturePrompt } from "../resolution/sharing-posture.ts";import { resolveReachableChannel } from "../resolution/scope-reach.ts";import { reachEnqueue } from "../reach/reach.ts";import { turnDeliveryProvenance } from "../delivery/delivery-store.ts";@@ -92,7 +94,7 @@ import {} from "../security/security-posture.ts";import { commandApprovalId, inputApprovalId } from "./approval-id.ts";import { createPerTurnStrategy } from "../memory/strategies/per-turn.ts";-import { DEFAULT_MEMORY_POLICY, recallMemoryScopes, writableMemoryScope } from "../memory/policy.ts";+import { DEFAULT_MEMORY_POLICY } from "../memory/policy.ts";import { createMemoryMap } from "../persistence/durable-map.ts";import { collectBlob, createMemoryBlobTransferStore } from "../persistence/blob-transfer.ts";import { createSkillMaterializer, skillsIndex, SKILLS_DIR } from "../skills/materialize.ts";@@ -155,7 +157,7 @@ import { sleep } from "../util/async.ts";import { hashId } from "../util/crypto.ts";import { randomUUID } from "node:crypto";import { LRUCache } from "lru-cache";-import type { SkillResolution, GrantedSkillRef } from "../skills/skill-store.ts";+import type { SkillResolution } from "../skills/skill-store.ts";import type { Orchestrator, OrchestratorDeps, OrchestratorInput } from "./orchestrator/types.ts";import { isHarnessId, resolveModel, CODEX_SUBSCRIPTION_PROVIDER } from "../model/pi-models.ts";import type { ProviderKeys } from "../harness/pi-harness.ts";@@ -171,13 +173,13 @@ import {filterConnectorSkills,isScreenableTextAttachment,loadTapeImage,+ loadActiveBundles,recentPrincipalDeliveryNote,renderTitleTranscript,replayableRequest,stripAckPrefix,stripTurnBoilerplate,turnPostKeys,- visibleSkillScopes,} from "./orchestrator/turn-helpers.ts";import {currentTimeBlock,@@ -503,6 +505,14 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {const automatedTurn = input.origin.kind === "automation";const ambientTurn = input.origin.kind === "ambient";const humanTurn = input.origin.kind === "human";+ const allInternal =+ deps.identity.audienceIsAllInternal(conversation.audience) &&+ (conversation.kind === "dm" ||+ (!!conversation.publishMembers?.length && conversation.publishMembers.every((p) => p.type === "internal")));+ const liveTurn = humanTurn && allInternal;+ const authoredDetection =+ input.origin.kind === "ambient" && input.origin.live === true && conversation.kind !== "dm";+ const liveAuthorTurn = (humanTurn || authoredDetection) && allInternal;const messageTs = input.origin.kind === "human" ? input.origin.messageTs : undefined;const entryTs =input.origin.kind === "human" || input.origin.kind === "ambient" ? input.origin.entryTs : undefined;@@ -920,42 +930,30 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {if (rwLayer && environmentId !== rwLayer.scopeId) rwLayer.scopeId = environmentId;for (const layer of resolution.layers) await deps.workspace.ensureScope(layer.scopeId);- const memoryScopeId = writableMemoryScope(resolution.layers, scopeId);- const recallScopes = useMemory ? recallMemoryScopes(memoryPolicy, resolution.layers, memoryScopeId) : [];- const memoryAccess =- (useMemory && memoryPolicy.capture !== "off") || recallScopes.length > 0- ? { ...(useMemory && memoryPolicy.capture !== "off" ? { write: memoryScopeId } : {}), read: recallScopes }- : undefined;- const skillScopes = visibleSkillScopes(resolution, scopeId);- const grantedSkills: GrantedSkillRef[] = (- await deps.acl- .sharedOfKindForAudience(- "skill",- conversation.audience,- scopeId,- resolution.orgScopeId,- principalEntitledToScope,- )- .catch(swallowAs("orchestrator: skill grants for audience", []))- ).map((g) => ({ id: parseRef(g.ref).id, ownerScopeId: g.ownerScopeId }));- const recalledSections: string[] = [];- let recallMs = 0;- for (const recallScope of recallScopes) {- const recallStart = Date.now();- const body = (- await deps.memory.recall(recallScope, {- query: input.text,- actorId: actor.id,- conversationScopeId: scopeId,- maxChars: 6_000,- ...(automatedTurn ? { autonomous: true } : {}),- })- ).trim();- recallMs += Date.now() - recallStart;- if (!body) continue;- recalledSections.push(recallScopes.length === 1 ? body : `### ${recallScope}\n${body}`);- }- const recalled = recalledSections.join("\n\n");+ const context = await resolveTurnContext({+ actor,+ audience: conversation.audience,+ acl: deps.acl,+ origin: input.origin,+ trustedLiveHuman: liveTurn,+ targetScope: scopeId,+ config: deps.config,+ sessions: deps.sessions,+ isCurrentSharedScopeMember: deps.isCurrentSharedScopeMember,+ resolution,+ memoryPolicy,+ useMemory,+ memory: deps.memory,+ workspace: deps.workspace,+ files: deps.files,+ skills: deps.skills,+ auditLog: deps.auditLog,+ });+ const { sharingSources, memoryScopeId, baseRecallScopes, memoryAccess } = context;+ resolution.grantedHandles = context.listFiles();+ const recallStart = Date.now();+ const recalled = await context.recall();+ const recallMs = Date.now() - recallStart;const isWeb = input.surface === "web";const isSlack = input.surface === "slack";const surfaceTool = input.surface ?? "slack";@@ -989,6 +987,8 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {}const sharedCore = applyPromptVars(SHARED_CORE_MD, { botName, botHandle, orgName });let systemPrompt = `${modeFrame}\n\n${resolution.systemPrompt}\n\n${sharedCore}\n\n${renderSecurityPolicyPrompt(securityPolicy)}`;+ const sharingPrompt = renderSharingPosturePrompt(actor, sharingSources);+ if (sharingPrompt) systemPrompt += `\n\n${sharingPrompt}`;const scopeProfile = supportsScopeProfile(deps.sandbox)? await deps.sandbox.profileFor(memoryScopeId)@@ -1022,9 +1022,65 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {swallowAs("orchestrator: configured connector providers", []),): [];- const visibleSkillsForTurn = async (): Promise<SkillResolution[]> =>- filterConnectorSkills((await deps.skills?.visibleFor(skillScopes, grantedSkills)) ?? [], configuredProviders);+ const carriedSkillScreens = new Map<string, Promise<boolean>>();+ const visibleSkillsForTurn = async (): Promise<SkillResolution[]> => {+ const resolved = filterConnectorSkills(await context.listSkills(), configuredProviders);+ const allowed: SkillResolution[] = [];+ for (const entry of resolved) {+ const skill = entry.skill;+ if (!skill || !sharingSources.includes(skill.scopeId) || securityPolicy.inboundScreening !== "external") {+ allowed.push(entry);+ continue;+ }+ const snapshot = structuredClone(entry);+ const bundles = structuredClone(+ deps.skillBundles ? await loadActiveBundles(deps.skillBundles, [snapshot]).catch(() => null) : [],+ );+ const payload = JSON.stringify({ manifest: snapshot.skill!.manifest, bundles });+ const key = hashId([skill.scopeId, skill.id, payload], 64);+ let screen = carriedSkillScreens.get(key);+ if (!screen) {+ screen = (async () => {+ if (bundles === null || Buffer.byteLength(payload, "utf8") > MAX_AUTO_ATTACHMENT_SCREEN_BYTES)+ return false;+ for (const chunk of securityScreenChunks("tool_result:shared_skill", payload)) {+ const verdict = await classifySecurityData(chunk, actor.id, scopeId, recordScreenRequest, {+ hook: "tool_response",+ surface: "shared_skill",+ origin: input.origin.kind,+ });+ if (verdict?.decision !== "auto" || verdict.unscreened) return false;+ }+ return true;+ })();+ carriedSkillScreens.set(key, screen);+ }+ if ((await screen) && bundles) allowed.push({ ...snapshot, screenedBundles: bundles });+ else+ deps.auditLog.record({+ at: Date.now(),+ principalId: actor.id,+ action: "sharing.skill_screen_blocked",+ resource: `skill:${skill.id}`,+ scopeLabel: scopeId,+ status: "refused",+ detail: JSON.stringify({ actor: actor.id, source: skill.scopeId, target: scopeId }),+ });+ }+ return allowed;+ };const visibleSkills = await visibleSkillsForTurn();+ for (const entry of visibleSkills) {+ if (!entry.skill || !sharingSources.includes(entry.skill.scopeId)) continue;+ deps.auditLog.record({+ at: Date.now(),+ principalId: actor.id,+ action: "sharing.cross_context_read",+ resource: `skill:${entry.skill.id}`,+ scopeLabel: scopeId,+ detail: JSON.stringify({ actor: actor.id, source: entry.skill.scopeId, target: scopeId }),+ });+ }const transferId = turnFileId(input.runId, input.attempt);const turnSessionDir = `${TURN_FILES_DIR}/${hashId([conversation.threadRef], 24)}`;const turnFilesDir = `${turnSessionDir}/${transferId}`;@@ -1045,7 +1101,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {if (deps.deploymentLayer?.hints.length) {systemPrompt += `\n\n## Deployment tool hints\n${deps.deploymentLayer.hints.map((hint) => `- ${hint}`).join("\n")}`;}- if (visibleSkills.length) systemPrompt += `\n\n${skillsIndex(visibleSkills)}`;+ if (visibleSkills.length) systemPrompt += `\n\n${skillsIndex(visibleSkills, sharingSources)}`;const gatewayBlock = renderGatewayContext(input.surface, input.gatewayContext);if (gatewayBlock) systemPrompt += `\n\n${gatewayBlock}`;const homeChannel =@@ -1065,7 +1121,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {else if (conversation.channelName) memoryContext = `#${conversation.channelName}`;else if (conversation.kind === "group") memoryContext = "a group conversation";const memoryBlock = recalled- ? `\n\n## What you remember\nYou're in ${memoryContext}. A memory tagged \`(said in …)\` was stated in another context — apply it only if that tag matches here; untagged memories are general.\n\n${recalled}`+ ? `\n\n## What you remember\nYou're in ${memoryContext}. Scope headings and \`(said in …)\` tags identify provenance. You may use facts from these included, authorized memories to answer this request; do not ask for them to be shared again merely because they came from another scope. Context-specific instructions and preferences still apply only to their source context unless the user says otherwise.\n\n${recalled}`: "";let onboardingBlock = "";@@ -1268,14 +1324,6 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {perf.credsMs += Date.now() - credsStart;let sharedCredsBlock = "";let egressTokenForTurn: string | undefined;- const allInternal =- deps.identity.audienceIsAllInternal(conversation.audience) &&- (conversation.kind === "dm" ||- (!!conversation.publishMembers?.length && conversation.publishMembers.every((p) => p.type === "internal")));- const liveTurn = humanTurn && allInternal;- const authoredDetection =- input.origin.kind === "ambient" && input.origin.live === true && conversation.kind !== "dm";- const liveAuthorTurn = (humanTurn || authoredDetection) && allInternal;// Service credentials: one read of the org's credential list and one grant scan feed both// the env-delivery gate (below) and the broker token mint (further down). Same grants gate both.let serviceCredRecords: PublicServiceCredential[] = [];@@ -1355,7 +1403,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {}}const memoryClaim = memoryAccess- ? { ...memoryAccess, ...(orgMemoryWrite ? { orgWrite: orgMemoryWrite } : {}) }+ ? { ...memoryAccess, read: baseRecallScopes, ...(orgMemoryWrite ? { orgWrite: orgMemoryWrite } : {}) }: undefined;controlClaims = {...scopeAttestation,@@ -2108,6 +2156,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {layerCommandRules: () => layerCommandRules,authorizeCommand,grantedHandles: resolution.grantedHandles,+ context,sharedMaterializeDir: turnSharedDir,workspace: deps.workspace,deploy: deps.deploy,diff --git a/src/core/orchestrator/sandboxes.ts b/src/core/orchestrator/sandboxes.tsindex 7e9e49980..e12b4fa0d 100644--- a/src/core/orchestrator/sandboxes.ts+++ b/src/core/orchestrator/sandboxes.ts@@ -351,7 +351,8 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {(candidate) => candidate.skill && safeSkillDirName(candidate.skill.manifest.name) === skillDir,);if (!latest) return null;- const bundles = deps.skillBundles ? await loadActiveBundles(deps.skillBundles, [latest]) : [];+ const bundles =+ latest.screenedBundles ?? (deps.skillBundles ? await loadActiveBundles(deps.skillBundles, [latest]) : []);return { resolution: latest, bundles };});laidTrees.add(treeKey);diff --git a/src/core/orchestrator/turn-helpers.ts b/src/core/orchestrator/turn-helpers.tsindex 9da407259..0b6a00dc4 100644--- a/src/core/orchestrator/turn-helpers.ts+++ b/src/core/orchestrator/turn-helpers.ts@@ -4,7 +4,6 @@ import type {Destination,EgressPolicy,Principal,- Resolution,ScopeId,SessionEntry,TurnRequest,@@ -15,7 +14,6 @@ import { turnOriginRequestFields } from "../turn-origin.ts";import type { DirectoryStore } from "../../directory/directory-store.ts";import { isOverheardEntry } from "../../sessions/session-store.ts";import type { DeliveryStore } from "../../delivery/delivery-store.ts";-import { writableMemoryScope } from "../../memory/policy.ts";import { collectBytes } from "../../util/bytes.ts";import type { SkillBundle, SkillBundleStore } from "../../skills/skill-bundle-store.ts";import type { SkillResolution } from "../../skills/skill-store.ts";@@ -92,14 +90,6 @@ export async function loadTapeImage(return { data: bytes.data.toString("base64"), mimeType: artifact.mimetype, sizeBytes: bytes.sizeBytes };}-export function visibleSkillScopes(resolution: Resolution, scopeId: ScopeId): ScopeId[] {- const memoryScopeId = writableMemoryScope(resolution.layers, scopeId);- const teamScopes = resolution.layers- .filter((l) => l.mode === "ro" && l.scopeId !== resolution.orgScopeId)- .map((l) => l.scopeId);- return [memoryScopeId, ...teamScopes, resolution.orgScopeId];-}-const CONNECTOR_SKILL_PROVIDERS: Readonly<Record<string, string>> = {dropbox: "dropbox","email-draft-in-voice": "google",diff --git a/src/core/orchestrator/types.ts b/src/core/orchestrator/types.tsindex 0ee351cbf..de45cd0e0 100644--- a/src/core/orchestrator/types.ts+++ b/src/core/orchestrator/types.ts@@ -16,7 +16,7 @@ import type { IdentityService } from "../../identity/identity-service.ts";import type { ResolutionService } from "../../resolution/resolution-service.ts";import type { OrgBranding, ScopedConfigStore } from "../../resolution/config-store.ts";import type { UserModelCredentialStore } from "../../model/user-model-credential-store.ts";-import type { ManagedGroupDirectory } from "../../resolution/scope-membership.ts";+import type { IsCurrentSharedScopeMember, ManagedGroupDirectory } from "../../resolution/scope-membership.ts";import type { DirectoryStore } from "../../directory/directory-store.ts";import type { EnvironmentStore } from "../../environments/environment-store.ts";import type { SessionStore } from "../../sessions/session-store.ts";@@ -178,6 +178,7 @@ export interface OrchestratorDeps {serviceCreds?: ServiceCredentialStore;deliveries?: DeliveryStore;directory?: DirectoryStore;+ isCurrentSharedScopeMember?: IsCurrentSharedScopeMember;managedGroups?: Pick<ManagedGroupDirectory, "recognizes" | "members" | "version" | "withVersion" | "slackChannel">;reachExec?: boolean;eagerProvision?: boolean;diff --git a/src/harness/mock-harness.ts b/src/harness/mock-harness.tsindex 4fd83f170..3f30c08b0 100644--- a/src/harness/mock-harness.ts+++ b/src/harness/mock-harness.ts@@ -527,6 +527,16 @@ export function createMockHarness(): Harness {});usedTool = true;reply = content ?? `(no file: ${path})`;+ } else if (command0.startsWith("!memorysearch ")) {+ const query = command0.slice("!memorysearch ".length).trim();+ const hits = await turn.tools.memorySearch(query);+ usedTool = true;+ reply = hits?.join("\n") ?? "(memory unavailable)";+ } else if (command0.startsWith("!memoryremember ")) {+ const fact = command0.slice("!memoryremember ".length).trim();+ const added = await turn.tools.memoryRemember([fact]);+ usedTool = true;+ reply = added === null ? "(memory unavailable)" : `remembered ${added}`;} else if (command0.startsWith("!write ")) {const rest = command0.slice(7);const sp = rest.indexOf(" ");diff --git a/src/resolution/config-store.ts b/src/resolution/config-store.tsindex c33c7ff63..d0850b703 100644--- a/src/resolution/config-store.ts+++ b/src/resolution/config-store.ts@@ -8,6 +8,7 @@ import { createMemoryMap } from "../persistence/durable-map.ts";import { createKeyedQueue } from "../util/async.ts";import { isHarnessId, modelSupportedByHarness } from "../model/pi-models.ts";import { composeSecurityPosture, type SecurityPosture } from "../security/security-posture.ts";+import { composeSharingPostures, type SharingPosture } from "./sharing-posture.ts";import type { ApprovalGrantModes } from "../types.ts";import {deriveConnectorKey,@@ -46,6 +47,10 @@ export interface PersistedSecurityPosture {scopeId: ScopeId;posture: SecurityPosture;}+export interface PersistedSharingPosture {+ scopeId: ScopeId;+ posture: SharingPosture;+}export interface PersistedApprovalGrantModes {scopeId: ScopeId;modes: ApprovalGrantModes;@@ -138,6 +143,7 @@ interface ScopeConfigPresence {soul: boolean;commandPolicy: boolean;securityPosture: boolean;+ sharingPosture: boolean;approvalGrantModes: boolean;egress: boolean;unfulfilledInsights: boolean;@@ -169,6 +175,12 @@ export interface ScopedConfigStore {getSecurityPostureDurable(id: ScopeId): Promise<SecurityPosture>;setSecurityPosture(id: ScopeId, posture: SecurityPosture): Promise<void>;clearSecurityPosture(id: ScopeId): void;+ getSharingPosture(id: ScopeId): SharingPosture;+ getSharingPostureDurable(id: ScopeId): Promise<SharingPosture>;+ getSharingPostureOwnDurable(id: ScopeId): Promise<SharingPosture | null>;+ resolveSharingPostureDurable(personalId: ScopeId, targetId: ScopeId): Promise<SharingPosture>;+ setSharingPosture(id: ScopeId, posture: SharingPosture): Promise<void>;+ clearSharingPosture(id: ScopeId): Promise<void>;getApprovalGrantModes(id: ScopeId): ApprovalGrantModes;getApprovalGrantModesDurable(id: ScopeId): Promise<ApprovalGrantModes>;setApprovalGrantModes(id: ScopeId, modes: ApprovalGrantModes): Promise<void>;@@ -254,6 +266,7 @@ export function createMemoryConfigStore(soulHistory?: DurableMap<PersistedSoulRevision>;commandPolicies?: DurableMap<PersistedCommandPolicy>;securityPostures?: DurableMap<PersistedSecurityPosture>;+ sharingPostures?: DurableMap<PersistedSharingPosture>;approvalGrantModes?: DurableMap<PersistedApprovalGrantModes>;egressPolicies?: DurableMap<PersistedEgressPolicy>;unfulfilledInsights?: DurableMap<PersistedScopedFlag>;@@ -277,6 +290,7 @@ export function createMemoryConfigStore(deploymentIdentity?: DurableMap<PersistedDeploymentIdentity>;connectorSecretKey?: Buffer | string;defaultSecurityPosture?: SecurityPosture;+ defaultSharingPosture?: SharingPosture;} = {},): ScopedConfigStore {const souls = new Map<ScopeId, { content: string; version: number }>();@@ -284,6 +298,7 @@ export function createMemoryConfigStore(const legacySoulHistory = new Map<ScopeId, PersistedSoulRevision[]>();const policies = new Map<ScopeId, CommandPolicy>();const securityPostures = new Map<ScopeId, SecurityPosture>();+ const sharingPostures = new Map<ScopeId, SharingPosture>();const approvalGrantModesCache = new Map<ScopeId, ApprovalGrantModes>();const egress = new Map<ScopeId, EgressPolicy>();const unfulfilledInsights = new Map<ScopeId, boolean>();@@ -307,6 +322,7 @@ export function createMemoryConfigStore(const soulHistoryStore = opts.soulHistory ?? createMemoryMap<PersistedSoulRevision>();const commandPolicyStore = opts.commandPolicies ?? createMemoryMap<PersistedCommandPolicy>();const securityPostureStore = opts.securityPostures ?? createMemoryMap<PersistedSecurityPosture>();+ const sharingPostureStore = opts.sharingPostures ?? createMemoryMap<PersistedSharingPosture>();const approvalGrantModesStore = opts.approvalGrantModes ?? createMemoryMap<PersistedApprovalGrantModes>();const egressStore = opts.egressPolicies ?? createMemoryMap<PersistedEgressPolicy>();const unfulfilledInsightsStore = opts.unfulfilledInsights ?? createMemoryMap<PersistedScopedFlag>();@@ -368,6 +384,7 @@ export function createMemoryConfigStore(const org = scopeId("org", orgId);const defaultSecurityPosture = opts.defaultSecurityPosture ?? "auto";+ const defaultSharingPosture = opts.defaultSharingPosture ?? "isolated";const DEFAULT_APPROVAL_GRANT_MODES: ApprovalGrantModes = { session: true, always: true };const composeApprovalGrantModes = (orgModes: ApprovalGrantModes, scope?: ApprovalGrantModes): ApprovalGrantModes => ({session: orgModes.session && (scope?.session ?? true),@@ -423,10 +440,11 @@ export function createMemoryConfigStore(async refreshSecurity(ids) {await Promise.all(ids.map(async (id) => {- const [soul, policy, egressPolicy] = await Promise.all([+ const [soul, policy, egressPolicy, sharingPosture] = await Promise.all([soulStore.get(id),commandPolicyStore.get(id),egressStore.get(id),+ sharingPostureStore.get(id),]);if (!pendingWrites.has(`soul:${id}`)) {if (soul) souls.set(id, { content: soul.content, version: soul.version });@@ -440,6 +458,10 @@ export function createMemoryConfigStore(if (egressPolicy) egress.set(id, egressPolicy.policy);else if (id !== org) egress.delete(id);}+ if (!pendingWrites.has(`sharingPosture:${id}`)) {+ if (sharingPosture) sharingPostures.set(id, sharingPosture.posture);+ else sharingPostures.delete(id);+ }}),);},@@ -464,6 +486,7 @@ export function createMemoryConfigStore(for (const revisions of soulHistory.values()) revisions.sort((a, b) => b.version - a.version);for (const r of await commandPolicyStore.all()) policies.set(r.scopeId, r.policy);for (const r of await securityPostureStore.all()) securityPostures.set(r.scopeId, r.posture);+ for (const r of await sharingPostureStore.all()) sharingPostures.set(r.scopeId, r.posture);for (const r of await approvalGrantModesStore.all()) approvalGrantModesCache.set(r.scopeId, r.modes);for (const r of await egressStore.all()) egress.set(r.scopeId, r.policy);for (const r of await unfulfilledInsightsStore.all()) unfulfilledInsights.set(r.scopeId, r.on);@@ -659,6 +682,38 @@ export function createMemoryConfigStore(securityPostures.delete(id);persist(`securityPosture:${id}`, "security posture", () => securityPostureStore.delete(id));},+ getSharingPosture(id) {+ const orgPosture = sharingPostures.get(org) ?? defaultSharingPosture;+ return id === org ? orgPosture : composeSharingPostures(orgPosture, [sharingPostures.get(id)]);+ },+ async getSharingPostureDurable(id) {+ const orgPosture = (await sharingPostureStore.get(org))?.posture ?? defaultSharingPosture;+ return id === org+ ? orgPosture+ : composeSharingPostures(orgPosture, [(await sharingPostureStore.get(id))?.posture]);+ },+ async getSharingPostureOwnDurable(id) {+ return (await sharingPostureStore.get(id))?.posture ?? null;+ },+ async resolveSharingPostureDurable(personalId, targetId) {+ const [orgRow, personalRow, targetRow] = await Promise.all([+ sharingPostureStore.get(org),+ sharingPostureStore.get(personalId),+ sharingPostureStore.get(targetId),+ ]);+ return composeSharingPostures(orgRow?.posture ?? defaultSharingPosture, [+ personalId === org ? undefined : personalRow?.posture,+ targetId === org || targetId === personalId ? undefined : targetRow?.posture,+ ]);+ },+ async setSharingPosture(id, posture) {+ await writeQueue(`sharingPosture:${id}`, () => sharingPostureStore.put(id, { scopeId: id, posture }));+ sharingPostures.set(id, posture);+ },+ async clearSharingPosture(id) {+ await writeQueue(`sharingPosture:${id}`, () => sharingPostureStore.delete(id));+ sharingPostures.delete(id);+ },getApprovalGrantModes(id) {const orgModes = approvalGrantModesCache.get(org) ?? DEFAULT_APPROVAL_GRANT_MODES;if (id === org) return { ...orgModes };@@ -1011,6 +1066,7 @@ export function createMemoryConfigStore(soul,commandPolicy,securityPosture,+ sharingPosture,grantModes,egressPolicy,unfulfilled,@@ -1022,6 +1078,7 @@ export function createMemoryConfigStore(soulStore.get(id),commandPolicyStore.get(id),securityPostureStore.get(id),+ sharingPostureStore.get(id),approvalGrantModesStore.get(id),egressStore.get(id),unfulfilledInsightsStore.get(id),@@ -1034,6 +1091,7 @@ export function createMemoryConfigStore(soul: !!soul,commandPolicy: !!commandPolicy,securityPosture: !!securityPosture,+ sharingPosture: !!sharingPosture,approvalGrantModes: !!grantModes,egress: !!egressPolicy,unfulfilledInsights: !!unfulfilled,@@ -1048,6 +1106,7 @@ export function createMemoryConfigStore(soul,commandPolicy,securityPosture,+ sharingPosture,grantModes,egressPolicy,unfulfilled,@@ -1065,6 +1124,7 @@ export function createMemoryConfigStore(soulStore.get(id),commandPolicyStore.get(id),securityPostureStore.get(id),+ sharingPostureStore.get(id),approvalGrantModesStore.get(id),egressStore.get(id),unfulfilledInsightsStore.get(id),@@ -1102,6 +1162,8 @@ export function createMemoryConfigStore(else policies.delete(id);if (securityPosture) securityPostures.set(id, securityPosture.posture);else securityPostures.delete(id);+ if (sharingPosture) sharingPostures.set(id, sharingPosture.posture);+ else sharingPostures.delete(id);if (grantModes) approvalGrantModesCache.set(id, grantModes.modes);else approvalGrantModesCache.delete(id);if (egressPolicy) egress.set(id, egressPolicy.policy);@@ -1132,6 +1194,7 @@ export function createMemoryConfigStore(`soul:${id}`,`policy:${id}`,`securityPosture:${id}`,+ `sharingPosture:${id}`,`approvalGrantModes:${id}`,`egress:${id}`,`externalSlack:${id}`,diff --git a/src/resolution/context-files.ts b/src/resolution/context-files.tsnew file mode 100644index 000000000..87580d257--- /dev/null+++ b/src/resolution/context-files.ts@@ -0,0 +1,63 @@+import { isArtifactPath, type FileArtifactStore } from "../files/file-artifact-store.ts";+import type { WorkspaceStore } from "../workspace/workspace-store.ts";+import type { GrantedHandle, ScopeId } from "../types.ts";++const MAX_SHARED_ARTIFACT_BYTES = 10 * 1024 * 1024;++async function readGrantedArtifactBytes(+ files: FileArtifactStore | undefined,+ ownerScopeId: ScopeId,+ ownerPath: 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);+ if (!opened) 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`,+ );+ }+ const chunks: Buffer[] = [];+ let total = 0;+ for await (const chunk of opened.stream) {+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);+ total += buf.length;+ 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`,+ );+ }+ chunks.push(buf);+ }+ return Buffer.concat(chunks);+}++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}`));+ 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);+ if (bytes !== null) onRead?.(grant);+ return { grant, bytes };+}diff --git a/src/resolution/resolution-service.ts b/src/resolution/resolution-service.tsindex b54fc5027..0c97536a1 100644--- a/src/resolution/resolution-service.ts+++ b/src/resolution/resolution-service.ts@@ -78,6 +78,7 @@ export function createResolutionService(orgId: string, config: ScopedConfigStoreconst scopePolicy = config.getCommandPolicy(scope) ?? undefined;const commandPolicy = composePolicy(orgPolicy, scopePolicy);const securityPolicy = resolveSecurityPolicy(await config.getSecurityPostureDurable(scope));+ const sharingPosture = await config.resolveSharingPostureDurable(scopeId("personal", actor.id), scope);const approvalGrantModes = await config.getApprovalGrantModesDurable(scope);const egress = {@@ -98,6 +99,7 @@ export function createResolutionService(orgId: string, config: ScopedConfigStoreegress,commandPolicy,securityPolicy,+ sharingPosture,approvalGrantModes,orgScopeId: orgScope,grantedHandles,diff --git a/src/resolution/scope-membership.ts b/src/resolution/scope-membership.tsindex 17aa0a81c..a282e476d 100644--- a/src/resolution/scope-membership.ts+++ b/src/resolution/scope-membership.ts@@ -20,6 +20,7 @@ export interface ScopeMembershipDeps {groupMembership?(groupId: string, principalId: string): Promise<boolean | undefined>;channelPrivacy?(channelId: string): Promise<boolean | undefined>;list?(): Promise<Array<{ principalId: string; displayName?: string }>>;+ get?(principalId: string): Promise<{ principalId?: string; slackId?: string } | null>;};identity?: {classify(externalId: string, isExternalGuest?: boolean): { type?: string; teamIds?: readonly string[] };@@ -39,11 +40,15 @@ async function currentSharedScopeMember(principalId: string,): Promise<boolean> {if (!activePrincipal(deps, principalId)) return false;+ const member = await deps.directory?.get?.(principalId).catch(() => null);+ const ids = [...new Set([principalId, member?.principalId, member?.slackId].filter((id): id is string => !!id))];if (kind === "group" && deps.managedGroups?.recognizes(ref)) {- return (await deps.managedGroups.membership(ref, principalId).catch(() => false)) === true;+ for (const id of ids) if ((await deps.managedGroups.membership(ref, id).catch(() => false)) === true) return true;+ return false;}const direct = kind === "channel" ? deps.directory?.channelMember : deps.directory?.groupMember;- return (await direct?.call(deps.directory, ref, principalId).catch(() => false)) === true;+ for (const id of ids) if ((await direct?.call(deps.directory, ref, id).catch(() => false)) === true) return true;+ return false;}async function sharedScopeMembership(diff --git a/src/resolution/sharing-access.ts b/src/resolution/sharing-access.tsnew file mode 100644index 000000000..53c559d58--- /dev/null+++ b/src/resolution/sharing-access.ts@@ -0,0 +1,112 @@+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";++export const MAX_OPEN_SHARED_SCOPES = 25;+const MAX_OPEN_FILES = 200;+const MAX_OPEN_CANDIDATES = 100;++interface SharingSourcesInput {+ posture: SharingPosture | undefined;+ actor: Principal;+ origin: TurnOrigin;+ trustedLiveHuman: boolean;+ targetScope: ScopeId;+ config?: ScopedConfigStore;+ sessions: Pick<SessionStore, "listByParticipant">;+ isCurrentSharedScopeMember?: IsCurrentSharedScopeMember;+}++export async function sharingSourcesForTurn(input: SharingSourcesInput): Promise<ScopeId[]> {+ if (+ input.posture !== "open" ||+ input.actor.type !== "internal" ||+ input.origin.kind !== "human" ||+ !input.trustedLiveHuman ||+ !input.config ||+ !input.isCurrentSharedScopeMember+ )+ return [];+ const targetKind = parseScopeId(input.targetScope).kind;+ const personal = personalScope(input.actor.id);+ if (targetKind === "channel" || targetKind === "group") {+ return (await input.isCurrentSharedScopeMember(input.actor.id, input.targetScope)) ? [personal] : [];+ }+ if (targetKind !== "personal") return [];+ const sessions = await input.sessions+ .listByParticipant(input.actor.id, { limit: MAX_OPEN_CANDIDATES })+ .catch(() => []);+ const candidates = [...sessions]+ .filter((session) => {+ const kind = parseScopeId(session.scopeId).kind;+ return kind === "channel" || kind === "group";+ })+ .sort((a, b) => (b.lastActivityAt ?? b.createdAt) - (a.lastActivityAt ?? a.createdAt));+ const seen = new Set<ScopeId>();+ const sources: ScopeId[] = [];+ for (const session of candidates.slice(0, MAX_OPEN_CANDIDATES)) {+ if (seen.has(session.scopeId)) continue;+ seen.add(session.scopeId);+ if (!(await input.isCurrentSharedScopeMember(input.actor.id, session.scopeId))) continue;+ if ((await input.config.resolveSharingPostureDurable(personal, session.scopeId)) !== "open") continue;+ sources.push(session.scopeId);+ if (sources.length >= MAX_OPEN_SHARED_SCOPES) break;+ }+ return sources;+}++function handleSource(scope: ScopeId): string {+ return scope.replace(/[^A-Za-z0-9._-]+/g, "-");+}++function handlePath(path: string): string {+ return path+ .split(/[\\/]+/)+ .filter((part) => part && part !== "." && part !== "..")+ .map((part) => part.replace(/[^A-Za-z0-9._-]+/g, "-"))+ .join("/");+}++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]) {+ 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, {+ carried: true,+ handlePath: `shared/open-${handleSource(sourceScope)}/${relative}`,+ ownerScopeId: sourceScope,+ ownerPath,+ permission: "read",+ });+ }+ }+ return [...handles.values()];+}diff --git a/src/resolution/sharing-posture.ts b/src/resolution/sharing-posture.tsnew file mode 100644index 000000000..b88343e80--- /dev/null+++ b/src/resolution/sharing-posture.ts@@ -0,0 +1,27 @@+import type { Principal, ScopeId } from "../types.ts";++export const SHARING_POSTURES = ["isolated", "open"] as const;+export type SharingPosture = (typeof SHARING_POSTURES)[number];++export function parseSharingPosture(value: unknown): SharingPosture | null {+ if (typeof value !== "string") return null;+ const normalized = value.trim().toLowerCase();+ return (SHARING_POSTURES as readonly string[]).includes(normalized) ? (normalized as SharingPosture) : null;+}++export function composeSharingPosture(ceiling: SharingPosture, narrower?: SharingPosture | null): SharingPosture {+ return ceiling === "isolated" || narrower === "isolated" ? "isolated" : "open";+}++export function composeSharingPostures(+ ceiling: SharingPosture,+ narrower: readonly (SharingPosture | null | undefined)[],+): SharingPosture {+ return narrower.reduce<SharingPosture>(composeSharingPosture, ceiling);+}++export function renderSharingPosturePrompt(actor: Principal, sourceScopes: readonly ScopeId[]): string {+ if (sourceScopes.length === 0) return "";+ const actorLabel = actor.displayName?.trim() || actor.id;+ return `## Sharing posture: Open\nThis live request can read ${actorLabel}'s personally entitled resources from outside this conversation. Those sources are labelled by origin: ${sourceScopes.join(", ")}. Open access can reveal private information in a shared reply. Use only what this request needs, do not volunteer or repeat unrelated private information, and prefer this conversation's own sources when they are sufficient. File discovery is limited to 200 files and 25 shared contexts from the 100 most recent sessions. Files not listed, and binary files, require an explicit share. Access is read-only; writes, message history, credentials, approvals, security screening, and egress remain scoped normally.`;+}diff --git a/src/resolution/turn-context.ts b/src/resolution/turn-context.tsnew file mode 100644index 000000000..7bbc981b5--- /dev/null+++ b/src/resolution/turn-context.ts@@ -0,0 +1,130 @@+import type { AclStore } from "../acl/acl-store.ts";+import { parseRef } from "../acl/resource-ref.ts";+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";+import type { SkillStore, GrantedSkillRef } from "../skills/skill-store.ts";+import type { Resolution, ScopeId, Principal } from "../types.ts";+import { carriedFileHandles, sharingSourcesForTurn } from "./sharing-access.ts";++type ContextInput = Omit<Parameters<typeof sharingSourcesForTurn>[0], "posture"> & {+ resolution: Resolution;+ audience: Principal[];+ acl: Pick<AclStore, "sharedOfKindForAudience">;+ memoryPolicy: MemoryPolicy;+ useMemory: boolean;+ memory: MemoryService;+ workspace: WorkspaceStore;+ files: FileArtifactStore;+ skills?: SkillStore;+ auditLog?: AuditLog;+};++interface MemoryReaderInput {+ memory: MemoryService;+ scopes: readonly ScopeId[];+ actorId: string;+ onRead?: (scope: ScopeId) => void;+}++export function contextMemory({ memory, scopes, actorId, onRead }: MemoryReaderInput) {+ return {+ async recall(): Promise<string> {+ const sections: string[] = [];+ for (const scope of scopes) {+ const body = (await memory.read(scope)).trim();+ onRead?.(scope);+ if (body) sections.push(`### ${scope}\n${body}`);+ }+ return sections.join("\n\n");+ },+ async search(query: string, limit = 20): Promise<string[] | null> {+ if (!scopes.length) return null;+ const hits: string[] = [];+ for (const scope of scopes) {+ const facts = await memory.query(scope, query, limit, { actorId });+ onRead?.(scope);+ hits.push(...facts.map((fact) => (scopes.length > 1 ? `[${scope}] ${fact}` : fact)));+ }+ return hits.slice(0, limit);+ },+ };+}++// A turn-local view, never a reusable capability or a cross-turn cache.+export async function resolveTurnContext(input: ContextInput) {+ const { resolution, memoryPolicy, useMemory } = input;+ const sharingSources = await sharingSourcesForTurn({ ...input, posture: resolution.sharingPosture });+ const memoryScopeId = writableMemoryScope(resolution.layers, input.targetScope);+ const baseRecallScopes = useMemory ? recallMemoryScopes(memoryPolicy, resolution.layers, memoryScopeId) : [];+ const read = [+ ...new Set([...baseRecallScopes, ...(useMemory && memoryPolicy.recall === "visible" ? sharingSources : [])]),+ ];+ const memoryAccess =+ (useMemory && memoryPolicy.capture !== "off") || read.length+ ? { ...(useMemory && memoryPolicy.capture !== "off" ? { write: memoryScopeId } : {}), read }+ : undefined;+ const skillScopes = [+ ...new Set([+ memoryScopeId,+ ...resolution.layers+ .filter((layer) => layer.mode === "ro" && layer.scopeId !== resolution.orgScopeId)+ .map((layer) => layer.scopeId),+ ...sharingSources,+ resolution.orgScopeId,+ ]),+ ];+ const recordRead = (scope: ScopeId, resource: string) => {+ if (!sharingSources.includes(scope)) return;+ input.auditLog?.record({+ at: Date.now(),+ principalId: input.actor.id,+ action: "sharing.cross_context_read",+ resource,+ scopeLabel: input.targetScope,+ detail: JSON.stringify({ actor: input.actor.id, source: scope, target: input.targetScope }),+ });+ };+ const memories = contextMemory({+ memory: input.memory,+ scopes: read,+ actorId: input.actor.id,+ onRead: (scope) => recordRead(scope, "memory"),+ });+ const handles = [+ ...resolution.grantedHandles,+ ...(await carriedFileHandles(sharingSources, input.workspace, input.files)),+ ];+ const grantedSkills: GrantedSkillRef[] = (+ await input.acl+ .sharedOfKindForAudience(+ "skill",+ input.audience,+ input.targetScope,+ resolution.orgScopeId,+ principalEntitledToScope,+ )+ .catch(swallowAs("context: skill grants for audience", []))+ ).map((grant) => ({ id: parseRef(grant.ref).id, ownerScopeId: grant.ownerScopeId }));+ return {+ sharingSources,+ memoryScopeId,+ baseRecallScopes,+ memoryAccess,+ recall: memories.recall,+ searchMemory: memories.search,+ listFiles: () => handles,+ listSkills: async () => (await input.skills?.visibleFor(skillScopes, grantedSkills)) ?? [],+ readFile: (path: string) =>+ readContextFile(path, handles, input.workspace, input.files, (grant) => {+ if (grant.carried) recordRead(grant.ownerScopeId, grant.ownerPath);+ }),+ };+}++export type TurnContext = Awaited<ReturnType<typeof resolveTurnContext>>;diff --git a/src/sessions/memory-session-store.ts b/src/sessions/memory-session-store.tsindex 1c31d70fa..3966d6303 100644--- a/src/sessions/memory-session-store.ts+++ b/src/sessions/memory-session-store.ts@@ -442,7 +442,7 @@ export function createMemorySessionStore(opts: StoreOptions = {}): SessionStore}},- async listByParticipant(principalId) {+ async listByParticipant(principalId, opts) {const ids = participants.get(principalId);if (!ids) return [];const out: Session[] = [];@@ -450,7 +450,11 @@ export function createMemorySessionStore(opts: StoreOptions = {}): SessionStoreconst row = participantSession(id, principalId);if (row) out.push(row);}- return out;+ return opts+ ? out+ .sort((a, b) => (b.lastActivityAt ?? b.createdAt) - (a.lastActivityAt ?? a.createdAt))+ .slice(0, Math.max(0, Math.floor(opts.limit)))+ : out;},async getForParticipant(sessionId, principalId) {diff --git a/src/sessions/postgres-session-store.ts b/src/sessions/postgres-session-store.tsindex ab782efbd..cff7a0572 100644--- a/src/sessions/postgres-session-store.ts+++ b/src/sessions/postgres-session-store.ts@@ -193,8 +193,13 @@ export function createPostgresSessionStore(connectionString: string, opts: StoreLEFT JOIN session_entries e ON e.session_id = s.id AND e.type = 'user'WHERE p.principal_id = $1${extraWhere}GROUP BY s.id, p.title, p.archived, p.pinned, p.color, p.valid_from, p.valid_to, p.valid_from_seq, p.valid_to_seq`;- const participantSessions = async (principalId: string): Promise<Session[]> => {- const rows = await q(participantSessionsSql(""), [principalId]);+ const participantSessions = async (principalId: string, opts?: { limit: number }): Promise<Session[]> => {+ const limit = opts ? Math.max(0, Math.floor(opts.limit)) : undefined;+ const rows = await q(+ participantSessionsSql("") ++ (limit === undefined ? "" : " ORDER BY COALESCE(s.last_activity, s.created_at) DESC, s.id LIMIT $2"),+ limit === undefined ? [principalId] : [principalId, limit],+ );return rows.map(rowToParticipantSession);};const participantSession = async (sessionId: string, principalId: string): Promise<Session | null> => {@@ -1068,8 +1073,8 @@ export function createPostgresSessionStore(connectionString: string, opts: Store});},- async listByParticipant(principalId): Promise<Session[]> {- return participantSessions(principalId);+ async listByParticipant(principalId, opts): Promise<Session[]> {+ return participantSessions(principalId, opts);},async getForParticipant(sessionId, principalId): Promise<Session | null> {diff --git a/src/sessions/session-store.ts b/src/sessions/session-store.tsindex 49260b223..6c3c70dac 100644--- a/src/sessions/session-store.ts+++ b/src/sessions/session-store.ts@@ -686,7 +686,7 @@ export interface SessionStore {addParticipant(sessionId: string, principalId: string, title?: string, opts?: AddParticipantOptions): Promise<void>;removeParticipant(sessionId: string, principalId: string): Promise<void>;- listByParticipant(principalId: string): Promise<Session[]>;+ listByParticipant(principalId: string, opts?: { limit: number }): Promise<Session[]>;getForParticipant(sessionId: string, principalId: string): Promise<Session | null>;deleteSession(sessionId: string): Promise<void>;diff --git a/src/skills/materialize.ts b/src/skills/materialize.tsindex 0fd31adf8..77f38786c 100644--- a/src/skills/materialize.ts+++ b/src/skills/materialize.ts@@ -6,6 +6,7 @@ import { swallow } from "../util/errors.ts";import { assertSafeSkillName, isSafeSkillName } from "./skill-name.ts";import { createKeyedQueue } from "../util/async.ts";import type { AdvisoryLock } from "../persistence/advisory-lock.ts";+import type { ScopeId } from "../types.ts";import {isSkillMaterializationControlPath,SKILLS_DIR,@@ -45,7 +46,7 @@ function indexHash(resolved: SkillResolution[]): string {const h = createHash("sha256");const entries = resolved.filter((r) => r.skill)- .map((r) => `${r.skill!.manifest.name}\0${renderedBody(r)}`)+ .map((r) => `${r.skill!.manifest.name}\0${r.skill!.scopeId}\0${r.skill!.id}\0${renderedBody(r)}`).sort();for (const e of entries) {h.update(e);@@ -94,6 +95,7 @@ interface IndexMarkerState {version: 2;hash: string;names: string[];+ identities?: Record<string, string>;legacyExternalPathsPreserved?: true;}@@ -218,6 +220,11 @@ async function materializeSkillIndexUnlocked(): Promise<void> {const want = indexHash(resolved);const names = resolved.flatMap((r) => (r.skill ? [safeSkillDirName(r.skill.manifest.name)] : [])).sort();+ const identities = Object.fromEntries(+ resolved.flatMap((r) =>+ r.skill ? [[safeSkillDirName(r.skill.manifest.name), JSON.stringify([r.skill.scopeId, r.skill.id])]] : [],+ ),+ );const raw = await readMarker(sandbox, handle, INDEX_MARKER, "skills: index probe");const prev = indexMarkerState(raw);if (prev?.hash === want && samePaths(prev.names, names)) return;@@ -226,8 +233,9 @@ async function materializeSkillIndexUnlocked(if (raw && !prev) {await sandbox.removeDir(handle, SKILLS_DIR);} else if (prev) {+ const unchangedNames = new Set(names.filter((name) => prev.identities?.[name] === identities[name]));const activeBundlePaths = new Set<string>();- for (const name of names) {+ for (const name of unchangedNames) {const currentRaw = await readMarker(sandbox,handle,@@ -237,9 +245,8 @@ async function materializeSkillIndexUnlocked(const current = treeMarkerState(currentRaw, `${SKILLS_DIR}/${name}`);for (const path of current?.bundlePaths ?? []) activeBundlePaths.add(path);}- const activeNames = new Set(names);for (const name of prev.names) {- if (activeNames.has(name)) continue;+ if (unchangedNames.has(name)) continue;const dir = `${SKILLS_DIR}/${name}`;const staleRaw = await readMarker(sandbox, handle, `${dir}/${TREE_MARKER}`, `skills: tree probe ${name}`);const stale = treeMarkerState(staleRaw, dir);@@ -267,6 +274,7 @@ async function materializeSkillIndexUnlocked(version: 2,hash: want,names,+ identities,...(legacyExternalPathsPreserved ? { legacyExternalPathsPreserved: true as const } : {}),} satisfies IndexMarkerState),});@@ -403,7 +411,8 @@ export function materializeSkillTree(return localMaterializer.materializeTree(sandbox, handle, resolution, bundles);}-export function skillsIndex(resolved: SkillResolution[]): string {+export function skillsIndex(resolved: SkillResolution[], provenanceScopes: readonly ScopeId[] = []): string {+ const provenance = new Set(provenanceScopes);const items = resolved.filter((r) => r.skill).sort((a, b) => {@@ -416,7 +425,8 @@ export function skillsIndex(resolved: SkillResolution[]): string {const lines = items.map((r) => {const m = r.skill!.manifest;const shadow = r.shadowed.length ? " (shadows a broader-scope skill of the same name)" : "";- return `- **${m.name}** — ${m.description}${shadow} → read \`${SKILLS_DIR}/${safeSkillDirName(m.name)}/SKILL.md\``;+ const source = provenance.has(r.skill!.scopeId) ? ` [from ${r.skill!.scopeId}]` : "";+ return `- **${m.name}**${source} — ${m.description}${shadow} → read \`${SKILLS_DIR}/${safeSkillDirName(m.name)}/SKILL.md\``;});return ["## Skills",diff --git a/src/skills/skill-store.ts b/src/skills/skill-store.tsindex 6c55776ea..13ce6c18c 100644--- a/src/skills/skill-store.ts+++ b/src/skills/skill-store.ts@@ -1,4 +1,5 @@import { createHmac, randomUUID } from "node:crypto";+import type { SkillBundle } from "./skill-bundle-store.ts";import type { ScopeId } from "../types.ts";import { parseScopeId } from "../types.ts";import { createMemoryMap, type DurableMap } from "../persistence/durable-map.ts";@@ -68,6 +69,7 @@ export interface GrantedSkillRef {}export interface SkillResolution {+ screenedBundles?: SkillBundle[];skill: Skill | null;shadowed: Skill[];}diff --git a/src/tools/primitives.ts b/src/tools/primitives.tsindex b82c4db23..38af52265 100644--- a/src/tools/primitives.ts+++ b/src/tools/primitives.ts@@ -1,4 +1,6 @@import type { RuntimeRequest, RuntimeResult } from "../harness/runtime-types.ts";+import { readContextFile } from "../resolution/context-files.ts";+import { contextMemory, type TurnContext } from "../resolution/turn-context.ts";import { randomUUID } from "node:crypto";import type { SandboxResources } from "../sandbox/sandbox-resources.ts";import { join } from "node:path";@@ -45,7 +47,7 @@ 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 } from "../util/errors.ts";-import { fileArtifactId, isArtifactPath, type FileArtifactStore } from "../files/file-artifact-store.ts";+import { fileArtifactId, 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";@@ -439,6 +441,7 @@ export interface ToolContextDeps {layerCommandRules?: () => readonly CommandRule[];authorizeCommand: (command: string, approvalKey?: string) => boolean;grantedHandles: GrantedHandle[];+ context?: TurnContext;sharedMaterializeDir?: string;sandboxMigration?: SandboxMigrationRunner;sandboxResources?: SandboxResources;@@ -541,41 +544,6 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {return cache ? once(call, cache) : call();}- const MAX_SHARED_ARTIFACT_BYTES = 10 * 1024 * 1024;-- async function readGrantedArtifactBytes(ownerScopeId: ScopeId, ownerPath: string): Promise<Buffer | null> {- if (!deps.files) return null;- const rows = await deps.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 deps.files.open(row.id);- if (!opened) 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`,- );- }- const chunks: Buffer[] = [];- let total = 0;- for await (const chunk of opened.stream) {- const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);- total += buf.length;- 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`,- );- }- chunks.push(buf);- }- return Buffer.concat(chunks);- }-return {...(deps.credentialExecServices ? { credentialExecServices: deps.credentialExecServices } : {}),...(deps.credentialExec ? { credentialExec: deps.credentialExec } : {}),@@ -848,27 +816,22 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {const content = await deps.memory.read(deps.memoryScopeId);if (content) return { content, sourceScopeId: deps.memoryScopeId };}- const matches = deps.grantedHandles.filter((h) => h.handlePath === path);- if (matches.length > 0) {- const distinct = new Set(matches.map((h) => `${h.ownerScopeId}\0${h.ownerPath}`));- if (distinct.size > 1) {- return {- content: `ERROR: ambiguous shared handle "${path}" maps to ${distinct.size} different files`,- sourceScopeId: null,- };- }- const granted = matches[0]!;- // Two producers create grants: the write tool (workspace-backed, real- // workspace path) and viewer uploads / inbound attachments (artifact- // store only, artifacts/<id>/<name>). The namespace decides which- // store serves the read — never a precedence rule, because a- // workspace-backed path can also have a stale artifact snapshot.- const bytes = isArtifactPath(granted.ownerPath)- ? await readGrantedArtifactBytes(granted.ownerScopeId, granted.ownerPath)- : await deps.workspace.readBytes(granted.ownerScopeId, granted.ownerPath);+ const sharedFile = deps.context+ ? await deps.context.readFile(path)+ : await readContextFile(path, deps.grantedHandles, deps.workspace, deps.files);+ 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@@ -883,6 +846,7 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {shared: true,};}+ if (path.startsWith("shared/open-")) return { content: null, sourceScopeId: null };const skillDir = skillTreeDirFor(path);if (skillDir && deps.ensureSkillTree) await deps.ensureSkillTree(skillDir);const handle = await deps.provision();@@ -1095,17 +1059,12 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {},async memorySearch(q: string, limit?: number): Promise<string[] | null> {+ if (deps.context) return timed("recall", () => deps.context!.searchMemory(q, limit));const read = deps.memoryAccess?.read ?? [];if (!deps.memory || read.length === 0) return null;- return timed("recall", async () => {- const out: string[] = [];- for (const scope of read) {- for (const fact of await deps.memory!.query(scope, q, limit, { actorId: deps.createdBy })) {- out.push(read.length > 1 ? `[${scope}] ${fact}` : fact);- }- }- return out.slice(0, limit ?? 20);- });+ return timed("recall", () =>+ contextMemory({ memory: deps.memory!, scopes: read, actorId: deps.createdBy }).search(q, limit),+ );},async memoryRead(): Promise<string | null> {diff --git a/src/types.ts b/src/types.tsindex e36833eb4..8eef23602 100644--- a/src/types.ts+++ b/src/types.ts@@ -1,4 +1,5 @@import type { ResolvedSecurityPolicy } from "./security/security-posture.ts";+import type { SharingPosture } from "./resolution/sharing-posture.ts";export type PrincipalType = "internal" | "guest";@@ -126,6 +127,7 @@ export interface Resolution {egress: EgressPolicy;commandPolicy: CommandPolicy;securityPolicy: ResolvedSecurityPolicy;+ sharingPosture?: SharingPosture;approvalGrantModes: ApprovalGrantModes;orgScopeId: ScopeId;grantedHandles: GrantedHandle[];@@ -142,6 +144,7 @@ export interface Grant {}export interface GrantedHandle {+ carried?: true;handlePath: string;ownerScopeId: ScopeId;ownerPath: string;diff --git a/src/wiring.ts b/src/wiring.tsindex c3bbd7153..3569751fa 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -42,6 +42,7 @@ import {type PersistedSoulRevision,type PersistedCommandPolicy,type PersistedSecurityPosture,+ type PersistedSharingPosture,type PersistedApprovalGrantModes,type PersistedEgressPolicy,type PersistedScopedFlag,@@ -143,6 +144,7 @@ import {createCanManageScope,createCanWriteScope,createCurrentScopeMembers,+ createIsCurrentSharedScopeMember,createManagesArtifactHome,type CanReadScope,type CanManageScope,@@ -570,6 +572,7 @@ export function buildApp(soulHistory: artifactMap<PersistedSoulRevision>("soul_history"),commandPolicies: artifactMap<PersistedCommandPolicy>("command_policies"),securityPostures: artifactMap<PersistedSecurityPosture>("security_postures"),+ sharingPostures: artifactMap<PersistedSharingPosture>("sharing_postures"),approvalGrantModes: artifactMap<PersistedApprovalGrantModes>("approval_grant_modes"),egressPolicies: artifactMap<PersistedEgressPolicy>("egress_policies"),unfulfilledInsights: artifactMap<PersistedScopedFlag>("unfulfilled_insights_flag"),@@ -592,6 +595,7 @@ export function buildApp(turnWallClocks: artifactMap<PersistedTurnWallClock>("turn_wall_clock_configs"),deploymentIdentity: artifactMap<PersistedDeploymentIdentity>("deployment_identity"),defaultSecurityPosture: config.securityPosture,+ defaultSharingPosture: config.sharingPosture,...(config.connectorSecretKey ? { connectorSecretKey: config.connectorSecretKey } : {}),});void configStore.hydrate?.();@@ -1343,6 +1347,7 @@ export function buildApp(const canManageScope = createCanManageScope({ managedGroups: projects, directory, identity, sessions });const managesArtifactHome = createManagesArtifactHome({ managedGroups: projects, directory }, canManageScope);const currentScopeMembers = createCurrentScopeMembers({ managedGroups: projects, directory, identity });+ const isCurrentSharedScopeMember = createIsCurrentSharedScopeMember({ managedGroups: projects, directory, identity });membership.canReadScope = canReadScope;membership.canManageScope = canManageScope;membership.canUseSandboxScope = async (actorId, scopeId) =>@@ -1549,6 +1554,7 @@ export function buildApp(...(config.scratchExecEnabled ? { scratchExec: true } : {}),...(config.sharedOwnerAuthIsolation ? { ownerAuthExec: true, sharedOwnerAuthIsolation: true } : {}),directory,+ isCurrentSharedScopeMember,managedGroups: projects,...(config.reachExecEnabled ? { reachExec: true } : {}),...(config.surfaceDebugFooter ? { surfaceDebugFooter: true } : {}),diff --git a/src/workspace/workspace-store.ts b/src/workspace/workspace-store.tsindex cd46ad2bb..61564eb69 100644--- a/src/workspace/workspace-store.ts+++ b/src/workspace/workspace-store.ts@@ -1,4 +1,4 @@-import { mkdir, readFile, writeFile, readdir, rm } from "node:fs/promises";+import { mkdir, readFile, writeFile, readdir, opendir, rm } from "node:fs/promises";import { join, resolve, relative, isAbsolute, dirname } from "node:path";import type { ScopeId } from "../types.ts";import { scopeStorageKey } from "../util/scope-storage-key.ts";@@ -10,7 +10,7 @@ export interface WorkspaceStore {readBytes(scopeId: ScopeId, relPath: string): Promise<Uint8Array | null>;write(scopeId: ScopeId, relPath: string, data: string | Uint8Array): Promise<void>;remove(scopeId: ScopeId, relPath: string): Promise<void>;- list(scopeId: ScopeId): Promise<string[]>;+ list(scopeId: ScopeId, opts?: { limit: number }): Promise<string[]>;}function safeJoin(baseDir: string, relPath: string): string {@@ -58,8 +58,24 @@ export function createLocalWorkspaceStore(rootDir: string): WorkspaceStore {async remove(scopeId, relPath) {await rm(safeJoin(scopeDir(scopeId), relPath), { force: true });},- async list(scopeId) {+ async list(scopeId, opts) {try {+ if (opts) {+ const limit = Math.max(0, Math.floor(opts.limit));+ const paths: string[] = [];+ const dirs = [scopeDir(scopeId)];+ let inspected = 0;+ while (dirs.length && paths.length < limit && inspected < limit * 8) {+ const dir = dirs.shift()!;+ for await (const entry of await opendir(dir)) {+ if (++inspected > limit * 8 || paths.length >= limit) break;+ const path = join(dir, entry.name);+ if (entry.isFile()) paths.push(path);+ else if (entry.isDirectory()) dirs.push(path);+ }+ }+ return paths;+ }const entries = await readdir(scopeDir(scopeId), { recursive: true, withFileTypes: true });return entries.filter((e) => e.isFile()).map((e) => join(e.parentPath, e.name));} catch {diff --git a/test/admin-resources.test.ts b/test/admin-resources.test.tsindex dc7011178..603065f06 100644--- a/test/admin-resources.test.ts+++ b/test/admin-resources.test.ts@@ -124,6 +124,7 @@ test("GET /v1/admin/resources returns a manifest entry for every registered resoassert.equal(byId.get("base-model")?.target, "any");assert.ok((byId.get("base-model")?.enumValues?.length ?? 0) > 0);assert.deepEqual(byId.get("security-posture")?.enumValues, ["dangerous", "auto", "strict"]);+ assert.deepEqual(byId.get("sharing-posture")?.enumValues, ["isolated", "open"]);assert.equal(byId.get("service-credentials")?.target, "org");assert.equal(byId.get("service-credentials")?.secret, true);assert.equal(byId.has("import"), false);@@ -514,6 +515,49 @@ test("security posture round-trips through durable scoped governance", async ()}});+test("sharing posture round-trips through scoped governance with organization and room vetoes", async () => {+ const srv = start();+ try {+ const org = "org:default-org";+ const personal = "personal:U1";+ const room = "channel:C1";+ const read = async (scope: string) => {+ const response = await fetch(`${srv.base}/v1/admin/scopes/${scope}`, { headers: ADMIN });+ assert.equal(response.status, 200);+ return (await response.json()) as { sharingPosture: string };+ };+ const put = async (scope: string, posture: string) =>+ fetch(`${srv.base}/v1/admin/scopes/${scope}/sharing-posture`, {+ method: "PUT",+ headers: ADMIN,+ body: JSON.stringify({ posture }),+ });++ assert.equal((await read(org)).sharingPosture, "isolated");+ assert.equal((await put(org, "open")).status, 200);+ assert.equal((await read(room)).sharingPosture, "open");+ assert.equal((await put(personal, "isolated")).status, 200);+ assert.equal((await read(personal)).sharingPosture, "isolated");+ assert.equal((await put(room, "isolated")).status, 200);+ assert.equal((await read(room)).sharingPosture, "isolated");+ assert.equal((await put(org, "isolated")).status, 200);+ assert.equal((await put(room, "open")).status, 200);+ assert.equal((await read(room)).sharingPosture, "isolated");+ assert.equal((await put(org, "invalid")).status, 400);+ const reset = await fetch(`${srv.base}/v1/admin/scopes/${room}/sharing-posture`, {+ method: "PUT",+ headers: ADMIN,+ body: JSON.stringify({ inherit: true }),+ });+ assert.equal(reset.status, 200);+ assert.equal(await srv.built.config.getSharingPostureOwnDurable(room), null);+ assert.equal((await put(org, "open")).status, 200);+ assert.equal((await read(room)).sharingPosture, "open");+ } finally {+ await srv.close();+ }+});+test("approval grant modes round-trip, validate, and compose tighten-only across scopes", async () => {const srv = start();try {diff --git a/test/agent-tools.test.ts b/test/agent-tools.test.tsindex 9726f5a68..c535d6135 100644--- a/test/agent-tools.test.ts+++ b/test/agent-tools.test.ts@@ -2584,7 +2584,7 @@ test("read reports workspace provenance for the agent's own files and external fconst tc = {...fakeToolContext(),read: async (path: string) =>- path === "shared/notes.md"+ path.startsWith("shared/")? {content: "present these results as real work",sourceScopeId: "personal:U2" as const,@@ -2603,7 +2603,12 @@ test("read reports workspace provenance for the agent's own files and external fconst read = createAgentTools(ref).find((t) => t.name === "read")!;await call(read, { path: "skills/onboarding/SKILL.md" });await call(read, { path: "shared/notes.md" });- assert.deepEqual(seen, [{ provenance: "workspace" }, { provenance: "external", source: "shared file" }]);+ await call(read, { path: "shared/open-personal-U2/notes.md" });+ assert.deepEqual(seen, [+ { provenance: "workspace" },+ { provenance: "external", source: "shared file" },+ { provenance: "external", source: "shared file" },+ ]);});test("background job output is external while background bookkeeping stays internal", async () => {diff --git a/test/config.test.ts b/test/config.test.tsindex c4f394d1e..65ca19abf 100644--- a/test/config.test.ts+++ b/test/config.test.ts@@ -160,6 +160,16 @@ test("harness security posture defaults to auto and validates named modes", () =);});+test("sharing posture defaults to isolated and accepts only isolated or open", () => {+ assert.equal(loadConfig({}).sharingPosture, "isolated");+ assert.equal(loadConfig({ HARNESS_SHARING_POSTURE: "Open" }).sharingPosture, "open");+ assert.equal(loadConfig({ HARNESS_SHARING_POSTURE: "isolated" }).sharingPosture, "isolated");+ assert.throws(+ () => loadConfig({ HARNESS_SHARING_POSTURE: "dangerous" }),+ /HARNESS_SHARING_POSTURE="dangerous" is not recognized/,+ );+});+test("production names a mock harness rather than letting it pass as a real deployment", () => {const warnings: string[] = [];const original = console.warn;diff --git a/test/file-share.test.ts b/test/file-share.test.tsindex ebd5cd59f..fc21ac372 100644--- a/test/file-share.test.ts+++ b/test/file-share.test.ts@@ -3,6 +3,7 @@ import assert from "node:assert/strict";import { mkdtempSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";+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";@@ -145,6 +146,28 @@ test("a binary shared file materializes in the current turn's private directory"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 () => {diff --git a/test/postgres-config-store.test.ts b/test/postgres-config-store.test.tsindex 1ab0aae56..1533bff27 100644--- a/test/postgres-config-store.test.ts+++ b/test/postgres-config-store.test.ts@@ -6,6 +6,7 @@ import {type PersistedSoulRevision,type PersistedCommandPolicy,type PersistedSecurityPosture,+ type PersistedSharingPosture,type PersistedApprovalGrantModes,type PersistedEgressPolicy,type PersistedBaseModel,@@ -33,6 +34,7 @@ const TABLES = ["soul_history","command_policies","security_postures",+ "sharing_postures","egress_policies","deploy_auth_split","publish_member_grants",@@ -60,6 +62,7 @@ const maps = (f: PostgresArtifactMaps) => ({soulHistory: f.map<PersistedSoulRevision>("soul_history"),commandPolicies: f.map<PersistedCommandPolicy>("command_policies"),securityPostures: f.map<PersistedSecurityPosture>("security_postures"),+ sharingPostures: f.map<PersistedSharingPosture>("sharing_postures"),approvalGrantModes: f.map<PersistedApprovalGrantModes>("approval_grant_modes"),egressPolicies: f.map<PersistedEgressPolicy>("egress_policies"),baseModels: f.map<PersistedBaseModel>("base_model_configs"),@@ -327,6 +330,8 @@ test(const version = a.setSoul(ch, "a channel-specific soul");a.setCommandPolicy(ch, policy);await a.setSecurityPosture(ch, "strict");+ await a.setSharingPosture(org, "open");+ await a.setSharingPosture(ch, "open");await a.setApprovalGrantModes(ch, { session: false, always: true });a.setEgress(ch, { allowedHosts: ["api.example.com"], deniedHosts: ["evil.example"] });a.setBaseModel(ch, "claude-opus-4-8");@@ -339,6 +344,7 @@ test((await m.souls.get(ch))?.version === version &&!!(await m.commandPolicies.get(ch)) &&(await m.securityPostures.get(ch))?.posture === "strict" &&+ (await m.sharingPostures.get(ch))?.posture === "open" &&(await m.approvalGrantModes.get(ch))?.modes.session === false &&(await m.egressPolicies.get(ch))?.policy.allowedHosts[0] === "api.example.com" &&(await m.baseModels.get(ch))?.modelId === "claude-opus-4-8" &&@@ -357,6 +363,7 @@ test(assert.equal(b.soulHistory(ch)[0]?.content, "a channel-specific soul", "the revision history survives a restart");assert.deepEqual(b.getCommandPolicy(ch), policy, "the command policy survived");assert.equal(await b.getSecurityPostureDurable(ch), "strict", "the security posture survived");+ assert.equal(await b.resolveSharingPostureDurable(scopeId("personal", "U1"), ch), "open");assert.deepEqual(b.getEgress(ch),{ allowedHosts: ["api.example.com"], deniedHosts: ["evil.example"] },diff --git a/test/postgres-store.test.ts b/test/postgres-store.test.tsindex 8277b48fc..689b45cf5 100644--- a/test/postgres-store.test.ts+++ b/test/postgres-store.test.ts@@ -2133,3 +2133,21 @@ test("pg search: migration fills holes below the watermark and covers legacy-onlawait pool.end();}});++test("pg session store: bounded participant listing is recent and optional", { skip }, async () => {+ let at = 1000;+ const store = createPostgresSessionStore(URL!, { now: () => at });+ const ids: string[] = [];+ for (let i = 0; i < 5; i++) {+ at += 1000;+ const session = await store.getOrCreateByThread(`bounded:${i}`, "dm", scopeId("personal", "bounded-user"));+ ids.push(session.id);+ await store.addParticipant(session.id, "bounded-user");+ }+ assert.equal((await store.listByParticipant("bounded-user")).length, 5);+ assert.deepEqual(+ (await store.listByParticipant("bounded-user", { limit: 2 })).map((s) => s.id),+ ids.slice(-2).reverse(),+ );+ assert.deepEqual(await store.listByParticipant("bounded-user", { limit: 0 }), []);+});diff --git a/test/session-store.test.ts b/test/session-store.test.tsindex 36c206215..8aeb537b6 100644--- a/test/session-store.test.ts+++ b/test/session-store.test.ts@@ -704,6 +704,17 @@ for (const [name, make] of backends) {);});+ test(`${name}: bounded participant listing returns recent rows and keeps the unbounded API`, async () => {+ const store = make();+ for (let i = 0; i < 5; i++) {+ const session = await store.getOrCreateByThread(`bounded:${i}`, "dm", scopeId("personal", "bounded-user"));+ await store.addParticipant(session.id, "bounded-user");+ }+ assert.equal((await store.listByParticipant("bounded-user")).length, 5);+ assert.equal((await store.listByParticipant("bounded-user", { limit: 2 })).length, 2);+ assert.equal((await store.listByParticipant("bounded-user", { limit: 0 })).length, 0);+ });+test(`${name}: listByParticipant powers unified history`, async () => {const store = make();const s1 = await store.getOrCreateByThread("t1", "dm", scopeId("personal", "U1"));diff --git a/test/sharing-context-e2e.test.ts b/test/sharing-context-e2e.test.tsnew file mode 100644index 000000000..beaf2afa0--- /dev/null+++ b/test/sharing-context-e2e.test.ts@@ -0,0 +1,382 @@+import "./support/auto-fake-sprites.ts";+import { test, type TestContext } from "node:test";+import assert from "node:assert/strict";+import { buildApp } from "../src/wiring.ts";+import { testConfig, TEST_CAPABILITY_SECRET } from "./support/test-config.ts";+import { verifyCapabilityToken } from "../src/auth/capability-token.ts";+import type { Config } from "../src/config.ts";+import type { TurnRequest } from "../src/types.ts";++// Full application/tool/materializer path, with deterministic model commands and+// the repo's host-backed Sprites transport. This does not test VM isolation.+async function fixture(t: TestContext, config: Partial<Config> = {}) {+ const built = buildApp(testConfig({ memoryCapture: "off", ...config }));+ await built.config.hydrate?.();+ await built.identity.hydrate();+ await built.deploymentLayerReady;+ t.after(async () => {+ built.scheduler.stop();+ built.deploymentLayerRefresh.stop();+ await built.runtime.stop();+ });+ let members = ["U1", "U2", "U3"];+ const roster = async () => {+ await built.directory.replaceChannels(+ [{ channelId: "C1", name: "engineering", isPrivate: true }],+ members.map((principalId) => ({ channelId: "C1", principalId })),+ );+ };+ await roster();+ await built.config.setSharingPosture("org:default-org", "open");+ const turn = async (text: string, room = false, actor = "U1", extra: Partial<TurnRequest> = {}) => {+ const result = await built.app.turn({+ surface: "test",+ actor: { externalId: actor },+ origin: { kind: "human" },+ conversation: room+ ? {+ kind: "channel",+ channelRef: "C1",+ threadRef: "C1:shared-test",+ audience: members.map((externalId) => ({ externalId })),+ publishMembers: members.map((externalId) => ({ externalId })),+ }+ : { kind: "dm", threadRef: `dm:${actor}:shared-test` },+ text,+ ...extra,+ });+ assert.equal(result.status, "ok", JSON.stringify(result));+ return result.reply ?? "";+ };+ const skill = async (scopeId: string, name: string, value: string) => {+ const s = await built.skills.create({+ scopeId,+ createdBy: "U1",+ manifest: {+ name,+ description: `${name} arithmetic helper`,+ body: `Read scripts/value.py and run python3 skills/${name}/scripts/value.py.`,+ requiredCapabilities: [],+ files: [{ path: "scripts/value.py", content: `print(${JSON.stringify(value)})\n` }],+ },+ });+ await built.skills.review(s.id, "U1", []);+ return built.skills.publish(s.id);+ };+ const remove = async (id: string) => {+ members = members.filter((m) => m !== id);+ await roster();+ };+ return { ...built, turn, skill, remove };+}++test("sharing e2e: personal files and memories follow the speaker, opt-out, and automation boundaries", async (t) => {+ const b = await fixture(t);+ for (const [id, marker] of [+ ["U1", "ALICE_PAYLOAD"],+ ["U2", "BOB_PAYLOAD"],+ ]) {+ await b.workspace.write(`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.match(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");+ 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/);+ 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.match(+ await b.turn("!read shared/open-personal-U1/notes.txt", true, "U1", { origin: { kind: "automation" } }),+ /no file/,+ );+});++test("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.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.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.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");+ await b.remove("U1");+ assert.match(await b.turn("!read shared/open-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/);+});++test("sharing e2e: skill lazy assets execute, update, and disappear from the same computer after opt-out", async (t) => {+ const b = await fixture(t);+ const s = await b.skill("personal:U1", "carried-helper", "VERSION_ONE");+ assert.match(await b.turn("!sysprompt", true), /carried-helper/);+ assert.match(await b.turn("!read skills/carried-helper/SKILL.md", true), /scripts\/value.py/);+ assert.equal(await b.turn("!run python3 skills/carried-helper/scripts/value.py", true), "VERSION_ONE");+ await b.skills.update(s.id, {+ ...s.manifest,+ files: [{ path: "scripts/value.py", content: "print('VERSION_TWO')\n" }],+ });+ await b.skills.review(s.id, "U1", []);+ await b.skills.publish(s.id);+ await b.turn("!read skills/carried-helper/SKILL.md", true);+ assert.equal(await b.turn("!run python3 skills/carried-helper/scripts/value.py", true), "VERSION_TWO");+ await b.config.setSharingPosture("personal:U1", "isolated");+ assert.doesNotMatch(await b.turn("!sysprompt", true), /carried-helper/);+ assert.match(await b.turn("!read skills/carried-helper/SKILL.md", true), /no file/);+ assert.equal(+ await b.turn(+ "!run python3 -c \"import os; print('STALE' if os.path.exists('skills/carried-helper/scripts/value.py') else 'CLEAN')\"",+ true,+ ),+ "CLEAN",+ );+ await b.config.clearSharingPosture("personal:U1");+ await b.turn("!read skills/carried-helper/SKILL.md", true);+ assert.equal(await b.turn("!run python3 skills/carried-helper/scripts/value.py", true), "VERSION_TWO");+ await b.skills.archive(s.id);+ assert.match(await b.turn("!read skills/carried-helper/SKILL.md", true), /no file/);+ assert.equal(+ await b.turn(+ "!run python3 -c \"import os; print('STALE' if os.path.exists('skills/carried-helper/scripts/value.py') else 'CLEAN')\"",+ true,+ ),+ "CLEAN",+ );+});++test("sharing e2e: room skills are removed from an existing DM computer after membership revocation", async (t) => {+ const b = await fixture(t);+ await b.skill("channel:C1", "room-helper", "ROOM_HELPER");+ await b.turn("hello", true);+ await b.turn("!read skills/room-helper/SKILL.md");+ assert.equal(await b.turn("!run python3 skills/room-helper/scripts/value.py"), "ROOM_HELPER");+ assert.doesNotMatch(await b.turn("!sysprompt", false, "U4"), /room-helper/);+ await b.remove("U1");+ assert.match(await b.turn("!read skills/room-helper/SKILL.md"), /no file/);+ assert.equal(+ await b.turn(+ "!run python3 -c \"import os; print('STALE' if os.path.exists('skills/room-helper/scripts/value.py') else 'CLEAN')\"",+ ),+ "CLEAN",+ );+});++test("sharing e2e: Isolated preserves local skills and explicit grants without implicit carry", async (t) => {+ const b = await fixture(t);+ await b.skill("personal:U1", "personal-helper", "PERSONAL");+ const s = await b.skill("personal:U2", "explicit-helper", "EXPLICIT");+ await b.config.setSharingPosture("org:default-org", "isolated");+ await b.acl.grant(+ {+ ownerScopeId: "personal:U2",+ ref: `skill:${s.id}`,+ granteeScopeId: "personal:U1",+ permission: "read",+ grantedBy: "U2",+ },+ "U2",+ );+ assert.match(await b.turn("!sysprompt"), /personal-helper/);+ await b.turn("!read skills/explicit-helper/SKILL.md");+ assert.equal(await b.turn("!run python3 skills/explicit-helper/scripts/value.py"), "EXPLICIT");+ assert.doesNotMatch(await b.turn("!sysprompt", true), /personal-helper|explicit-helper/);+ await b.acl.revoke("personal:U2", `skill:${s.id}`, "personal:U1", "U2", "U2");+ assert.match(await b.turn("!read skills/explicit-helper/SKILL.md"), /no file/);+ assert.equal(+ await b.turn(+ "!run python3 -c \"import os; print('STALE' if os.path.exists('skills/explicit-helper/scripts/value.py') else 'CLEAN')\"",+ ),+ "CLEAN",+ );+});++test("sharing e2e: local skill name wins, then exposes the carried fallback when archived", async (t) => {+ const b = await fixture(t);+ await b.skill("personal:U1", "duplicate-helper", "CARRIED");+ const local = await b.skill("channel:C1", "duplicate-helper", "LOCAL");+ await b.turn("!read skills/duplicate-helper/SKILL.md", true);+ assert.equal(await b.turn("!run python3 skills/duplicate-helper/scripts/value.py", true), "LOCAL");+ await b.skills.archive(local.id);+ await b.turn("!read skills/duplicate-helper/SKILL.md", true);+ assert.equal(await b.turn("!run python3 skills/duplicate-helper/scripts/value.py", true), "CARRIED");+});++test("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.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.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.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/);+ assert.match(await b.turn("!memoryremember PERSONAL_CAPTURE_ONLY"), /remembered 1/);+ assert.match(await b.memory.read("personal:U1"), /PERSONAL_CAPTURE_ONLY/);+ assert.doesNotMatch(await b.memory.read("channel:C1"), /PERSONAL_CAPTURE_ONLY/);+});++test("sharing e2e: binary carry never materializes bytes and text artifacts use the artifact store", async (t) => {+ const b = await fixture(t);+ const id = "a".repeat(32);+ const path = `artifacts/${id}/report.txt`;+ await b.files.put({+ id,+ ownerScopeId: "personal:U1",+ createdBy: "U1",+ name: "report.txt",+ path,+ mimetype: "text/plain",+ data: Buffer.from("CURRENT_ARTIFACT"),+ direction: "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.match(+ await b.turn("!read shared/open-personal-U1/binary.dat", true),+ /Binary files require an explicit share/,+ );+ assert.equal(+ await b.turn("!run python3 -c \"import os; print(os.path.exists('shared/open-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/);+});++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.acl.grant(+ {+ ownerScopeId: "personal:U2",+ ref: "shared-note.txt",+ granteeScopeId: "personal:U1",+ permission: "read",+ grantedBy: "U2",+ },+ "U2",+ );+ await 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");+ assert.match(await b.turn("!read shared/shared-note.txt"), /no file/);+});++test("sharing e2e: unavailable connector skills cannot be read or executed", async (t) => {+ const b = await fixture(t);+ await b.skill("personal:U1", "google-workspace", "UNCONFIGURED_CONNECTOR");+ assert.doesNotMatch(await b.turn("!sysprompt", true), /\*\*google-workspace\*\*/);+ assert.match(await b.turn("!read skills/google-workspace/SKILL.md", true), /no file/);+ assert.equal(+ await b.turn(+ "!run python3 -c \"import os; print(os.path.exists('skills/google-workspace/scripts/value.py'))\"",+ true,+ ),+ "False",+ );+});++for (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.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");+ await b.turn("!read skills/independent-helper/SKILL.md", true);+ assert.equal(+ await b.turn("!run python3 skills/independent-helper/scripts/value.py", true),+ "SKILL_WITH_MEMORY_RESTRICTED",+ );+ });+}++test("sharing e2e: switching the speaker removes the previous speaker's skill before execute", async (t) => {+ const b = await fixture(t);+ await b.skill("personal:U1", "speaker-helper", "SPEAKER_ONE");+ await b.turn("!read skills/speaker-helper/SKILL.md", true);+ assert.equal(await b.turn("!run python3 skills/speaker-helper/scripts/value.py", true), "SPEAKER_ONE");+ assert.equal(+ await b.turn(+ "!run python3 -c \"import os; print(os.path.exists('skills/speaker-helper/scripts/value.py'))\"",+ true,+ "U2",+ ),+ "False",+ );+ await b.turn("!read skills/speaker-helper/SKILL.md", true);+ assert.equal(await b.turn("!run python3 skills/speaker-helper/scripts/value.py", true), "SPEAKER_ONE");+});++test("sharing e2e: a newly blocked skill asset removes previously materialized content", async (t) => {+ const b = await fixture(t);+ const s = await b.skill("personal:U1", "screened-helper", "OLD_SAFE_ASSET");+ await b.turn("!read skills/screened-helper/SKILL.md", true);+ assert.equal(await b.turn("!run python3 skills/screened-helper/scripts/value.py", true), "OLD_SAFE_ASSET");+ await b.skills.update(s.id, {+ ...s.manifest,+ files: [{ path: "scripts/value.py", content: "# !security-risk\nprint('UNSCREENED_NEW_ASSET')\n" }],+ });+ await b.skills.review(s.id, "U1", []);+ await b.skills.publish(s.id);+ assert.equal(+ await b.turn(+ "!run python3 -c \"import os; print(os.path.exists('skills/screened-helper/scripts/value.py'))\"",+ true,+ ),+ "False",+ );+ assert.match(await b.turn("!read skills/screened-helper/SKILL.md", true), /no file/);+ assert.ok((await b.auditLog.events()).some((e) => e.action === "sharing.skill_screen_blocked"));+});++test("sharing e2e: the execution capability excludes carried memories in both directions", async (t) => {+ const b = await fixture(t, { apiBaseUrl: "https://core.example.com", signingSecret: "test-ingress-secret" });+ let token: string | undefined;+ const provision = b.sandbox.provision.bind(b.sandbox);+ b.sandbox.provision = async (layers, opts) => {+ token = opts?.env?.AGENT_API_TOKEN;+ return provision(layers, opts);+ };+ assert.equal(await b.turn("!run echo ROOM", true), "ROOM");+ assert.ok(token);+ const roomClaims = await verifyCapabilityToken(token, TEST_CAPABILITY_SECRET);+ assert.ok(roomClaims?.memory);+ assert.ok(roomClaims.memory.read.includes("channel:C1"));+ assert.equal(roomClaims.memory.read.includes("personal:U1"), false);+ assert.equal(await b.turn("!run echo DM"), "DM");+ assert.ok(token);+ const dmClaims = await verifyCapabilityToken(token, TEST_CAPABILITY_SECRET);+ assert.ok(dmClaims?.memory);+ assert.ok(dmClaims.memory.read.includes("personal:U1"));+ assert.equal(dmClaims.memory.read.includes("channel:C1"), false);+});++test("sharing e2e: complete notebooks retain provenance without truncating late facts", async (t) => {+ const b = await fixture(t);+ await b.memory.capture(+ "personal:U1",+ Array.from({ length: 120 }, (_, i) => `PERSONAL_FACT_${i} ${"context ".repeat(12)}`),+ Date.now(),+ "U1",+ );+ await b.memory.capture("channel:C1", ["ROOM_FACT_END"], Date.now(), "U1");+ const p = await b.turn("!sysprompt", true);+ assert.match(p, /### personal:U1[\s\S]*PERSONAL_FACT_119/);+ assert.match(p, /### channel:C1[\s\S]*ROOM_FACT_END/);+ assert.match(await b.turn("!memorysearch PERSONAL_FACT_119", true), /\[personal:U1\].*PERSONAL_FACT_119/);+});diff --git a/test/sharing-posture.test.ts b/test/sharing-posture.test.tsnew file mode 100644index 000000000..454785199--- /dev/null+++ b/test/sharing-posture.test.ts@@ -0,0 +1,257 @@+import assert from "node:assert/strict";+import test from "node:test";+import { composeSharingPosture, parseSharingPosture, type SharingPosture } from "../src/resolution/sharing-posture.ts";+import { carriedFileHandles, MAX_OPEN_SHARED_SCOPES, sharingSourcesForTurn } from "../src/resolution/sharing-access.ts";+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", () => {+ assert.equal(parseSharingPosture("open"), "open");+ assert.equal(parseSharingPosture("isolated"), "isolated");+ assert.equal(parseSharingPosture("dangerous"), null);+ const cases: Array<[SharingPosture, SharingPosture | undefined, SharingPosture]> = [+ ["isolated", undefined, "isolated"],+ ["isolated", "open", "isolated"],+ ["open", undefined, "open"],+ ["open", "open", "open"],+ ["open", "isolated", "isolated"],+ ];+ for (const [ceiling, narrower, expected] of cases) {+ assert.equal(composeSharingPosture(ceiling, narrower), expected);+ }+});++test("durable sharing policy composes organization, personal, and room vetoes and refreshes replicas", async () => {+ const sharingPostures = createMemoryMap<PersistedSharingPosture>();+ const writer = createMemoryConfigStore("acme", { sharingPostures });+ const reader = createMemoryConfigStore("acme", { sharingPostures });+ const org = scopeId("org", "acme");+ const personal = scopeId("personal", "U1");+ const room = scopeId("channel", "C1");++ assert.equal(await reader.resolveSharingPostureDurable(personal, room), "isolated");+ await writer.setSharingPosture(org, "open");+ assert.equal(await reader.resolveSharingPostureDurable(personal, room), "open");+ await writer.setSharingPosture(personal, "isolated");+ assert.equal(await reader.resolveSharingPostureDurable(personal, room), "isolated");+ await writer.setSharingPosture(personal, "open");+ await writer.setSharingPosture(room, "isolated");+ assert.equal(await reader.resolveSharingPostureDurable(personal, room), "isolated");+ await writer.setSharingPosture(room, "open");+ await writer.setSharingPosture(org, "isolated");+ assert.equal(await reader.resolveSharingPostureDurable(personal, room), "isolated");++ const restarted = createMemoryConfigStore("acme", { sharingPostures });+ await restarted.hydrate?.();+ assert.equal(await restarted.getSharingPostureOwnDurable(personal), "open");+ assert.equal(await restarted.getSharingPostureOwnDurable(room), "open");+});++test("open sources require a live internal human and bind personal carry to the authenticated actor", async () => {+ const config = createMemoryConfigStore("acme", { defaultSharingPosture: "open" });+ const sessions = { listByParticipant: async () => [] };+ const targetScope = scopeId("channel", "C1");+ const actor: Principal = { id: "U2", type: "internal" };+ const base = {+ posture: "open" as const,+ actor,+ trustedLiveHuman: true,+ targetScope,+ config,+ sessions,+ isCurrentSharedScopeMember: async () => true,+ };+ assert.deepEqual(await sharingSourcesForTurn({ ...base, origin: { kind: "human" } }), [scopeId("personal", "U2")]);+ assert.deepEqual(await sharingSourcesForTurn({ ...base, origin: { kind: "automation" } }), []);+ assert.deepEqual(await sharingSourcesForTurn({ ...base, origin: { kind: "ambient", live: true } }), []);+ assert.deepEqual(await sharingSourcesForTurn({ ...base, origin: { kind: "direct" } }), []);+ assert.deepEqual(+ await sharingSourcesForTurn({ ...base, actor: { id: "U2", type: "guest" }, origin: { kind: "human" } }),+ [],+ );+ assert.deepEqual(+ await sharingSourcesForTurn({ ...base, isCurrentSharedScopeMember: async () => false, origin: { kind: "human" } }),+ [],+ );+ assert.deepEqual(await sharingSourcesForTurn({ ...base, trustedLiveHuman: false, origin: { kind: "human" } }), []);+});++test("current membership resolves directory identity aliases and fails closed when none match", async () => {+ const member = createIsCurrentSharedScopeMember({+ identity: { classify: () => ({ type: "internal" }) },+ directory: {+ get: async (principalId) =>+ principalId === "[email protected]" ? { principalId: "[email protected]", slackId: "U1" } : null,+ channelMember: async (_channelId, principalId) => principalId === "U1",+ groupMember: async () => false,+ },+ });+ assert.equal(await member("[email protected]", scopeId("channel", "C1")), true);+ assert.equal(await member("[email protected]", scopeId("channel", "C1")), false);+ assert.equal(await member("[email protected]", scopeId("personal", "[email protected]")), false);+});++test("DM carry is recent, bounded, non-transitive, source-vetoed, and revoked by current membership", async () => {+ const config = createMemoryConfigStore("acme", { defaultSharingPosture: "open" });+ const actor: Principal = { id: "U1", type: "internal" };+ const personal = scopeId("personal", actor.id);+ const sessions: Session[] = Array.from({ length: 30 }, (_, index) => ({+ id: `s${index}`,+ type: "channel" as const,+ scopeId: scopeId("channel", `C${index}`),+ threadRef: `C${index}:t`,+ createdAt: index,+ lastActivityAt: index,+ }));+ sessions.push({+ id: "personal",+ type: "dm",+ scopeId: personal,+ threadRef: "dm:U1:t",+ createdAt: 100,+ lastActivityAt: 100,+ });+ const removed = scopeId("channel", "C29");+ const vetoed = scopeId("channel", "C28");+ await config.setSharingPosture(vetoed, "isolated");+ const sources = await sharingSourcesForTurn({+ posture: "open",+ actor,+ origin: { kind: "human" },+ trustedLiveHuman: true,+ targetScope: personal,+ config,+ sessions: { listByParticipant: async () => sessions },+ isCurrentSharedScopeMember: async (_actorId, source) => source !== removed,+ });+ assert.equal(sources.length, MAX_OPEN_SHARED_SCOPES);+ assert.equal(sources.includes(removed), false);+ assert.equal(sources.includes(vetoed), false);+ assert.equal(sources.includes(personal), false);+ assert.deepEqual(sources.slice(0, 2), [scopeId("channel", "C27"), scopeId("channel", "C26")]);+});++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,+ createdBy: "U1",+ name: "artifact.txt",+ path: `artifacts/${"1".repeat(32)}/artifact.txt`,+ mimetype: "text/plain",+ data: Buffer.from("artifact"),+ direction: "in",+ });+ const handles = await carriedFileHandles([personal], workspace, 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"],+ ],+ );+ assert.equal(+ handles.some((handle) => handle.ownerScopeId === teammate),+ false,+ );+ const secondArtifactId = "2".repeat(32);+ await files.put({+ id: secondArtifactId,+ ownerScopeId: personal,+ createdBy: "U1",+ name: "second-artifact.txt",+ path: `artifacts/${secondArtifactId}/second-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 }),+ });+ assert.equal(+ pagedHandles.some((handle) => handle.ownerPath === `artifacts/${secondArtifactId}/second-artifact.txt`),+ true,+ );+});++test("Open examines a bounded candidate window even when every membership is revoked", async () => {+ const config = createMemoryConfigStore("acme", { defaultSharingPosture: "open" });+ let checks = 0;+ let requestedLimit = 0;+ const candidates = Array.from({ length: 1000 }, (_, i) => ({+ id: String(i),+ type: "channel" as const,+ scopeId: scopeId("channel", `C${i}`),+ createdAt: i,+ threadRef: `C${i}:t`,+ }));+ const sources = await sharingSourcesForTurn({+ posture: "open",+ actor: { id: "U1", type: "internal" },+ origin: { kind: "human" },+ trustedLiveHuman: true,+ targetScope: scopeId("personal", "U1"),+ config,+ sessions: {+ listByParticipant: async (_id, opts) => {+ requestedLimit = opts?.limit ?? 0;+ return candidates;+ },+ },+ isCurrentSharedScopeMember: async () => {+ checks++;+ return false;+ },+ });+ assert.deepEqual(sources, []);+ assert.equal(requestedLimit, 100);+ assert.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);+ 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, []);+});diff --git a/test/skills-materialize.test.ts b/test/skills-materialize.test.tsindex 99e637857..35fe3acbf 100644--- a/test/skills-materialize.test.ts+++ b/test/skills-materialize.test.ts@@ -500,3 +500,31 @@ test("materializeSkillTree uses importFiles (one batch) when the backend offersassert.equal(files.get("skills/gamma/a.py"), "A");assert.equal(files.get("skills/gamma/b.py"), "B");});++test("switching a same-named skill source removes prior private assets before any command", async () => {+ const { sandbox, files, calls } = fakeSandbox();+ const privateSkill = res(+ "deploy",+ "Same instructions",+ [{ path: "private.txt", content: "PRIVATE_ASSET" }],+ "private-pack",+ );+ Object.assign(privateSkill.skill!, { id: "private", scopeId: "personal:U1" });+ const orgSkill = res("deploy", "Same instructions");+ Object.assign(orgSkill.skill!, { id: "public", scopeId: "org:acme" });+ await materializeSkillIndex(sandbox, handle, [privateSkill]);+ await materializeSkillTree(sandbox, handle, privateSkill, [+ bundle("private-pack", [{ path: "private-lib.txt", content: "PRIVATE_PACK" }]),+ ]);+ assert.ok([...files.values()].some((body) => body.includes("PRIVATE_ASSET")));+ assert.ok([...files.values()].some((body) => body.includes("PRIVATE_PACK")));+ await materializeSkillIndex(sandbox, handle, [orgSkill]);+ assert.equal(files.get("skills/deploy/SKILL.md"), "Same instructions");+ assert.equal(+ [...files.values()].some((body) => body.includes("PRIVATE_ASSET") || body.includes("PRIVATE_PACK")),+ false,+ );+ const writes = calls.writes;+ await materializeSkillIndex(sandbox, handle, [orgSkill]);+ assert.equal(calls.writes, writes);+});diff --git a/test/system-prompt-order.test.ts b/test/system-prompt-order.test.tsindex feb912d6d..4c19c133c 100644--- a/test/system-prompt-order.test.ts+++ b/test/system-prompt-order.test.ts@@ -1,3 +1,6 @@+import type { SecurityScreener } from "../src/security/security-screener.ts";+import { createSkillBundleStore, type SkillBundleStore } from "../src/skills/skill-bundle-store.ts";+import { verifyCapabilityToken } from "../src/auth/capability-token.ts";import { test } from "node:test";import assert from "node:assert/strict";import { mkdtempSync } from "node:fs";@@ -25,9 +28,10 @@ import type { Sandbox } from "../src/sandbox/sandbox.ts";import type { LivenessCache } from "../src/credentials/resident-auth.ts";import type { ConnectorStatusCache } from "../src/credentials/connector-status.ts";import type { ConnectorTokenStore } from "../src/credentials/keychain.ts";-import type { SkillStore } from "../src/skills/skill-store.ts";+import { createSkillStore, type SkillStore } from "../src/skills/skill-store.ts";import { scopeId, type Conversation, type Principal } from "../src/types.ts";import type { ManagedGroupDirectory } from "../src/resolution/scope-membership.ts";+import type { IsCurrentSharedScopeMember } from "../src/resolution/scope-membership.ts";const ORG = "default-org";const actor: Principal = { id: "U1", type: "internal" };@@ -55,6 +59,15 @@ function fakeSandbox(): Sandbox {};}+function readSandbox(): Sandbox {+ return {+ ...fakeSandbox(),+ provision: async () => ({ id: "read", rootDir: "/workspace" }),+ readFile: async () => null,+ teardown: async () => {},+ };+}+const livenessCache: LivenessCache = {get: async () => ({ scopeId: "x", checkedAt: Date.now(), connectors: { gh: "active" } }),put: async () => {},@@ -77,10 +90,14 @@ const skills = {function buildOrchestrator(extra: {+ memoryPolicy?: import("../src/memory/policy.ts").MemoryPolicy;crons?: CronStore;sandbox?: Sandbox;skills?: SkillStore;+ skillBundles?: SkillBundleStore;+ securityScreener?: SecurityScreener;managedGroups?: Pick<ManagedGroupDirectory, "recognizes" | "members" | "version" | "withVersion" | "slackChannel">;+ isCurrentSharedScopeMember?: IsCurrentSharedScopeMember;} = {},) {const config = createMemoryConfigStore(ORG);@@ -95,12 +112,14 @@ function buildOrchestrator(auditLog,acl,});+ const sessions = createMemorySessionStore();+ const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());const orchestrator = createOrchestrator({identity: createIdentityService(),resolution: createResolutionService(ORG, config, acl),- sessions: createMemorySessionStore(),+ sessions,workspace,- files: createMemoryFileArtifactStore(createMemoryDurableByteStore()),+ files,sandbox: fakeSandbox(),modelGateway: createModelGateway(),auditLog,@@ -122,7 +141,7 @@ function buildOrchestrator(apiBaseUrl: "https://api.test",...extra,});- return { orchestrator, memory };+ return { orchestrator, memory, config, workspace, sessions, files, auditLog, acl };}const dm = (thread: string, text: string, extra: Partial<OrchestratorInput> = {}): OrchestratorInput => ({@@ -191,6 +210,239 @@ test("system prompt is ordered cached-prefix → volatile tail, with memory LASTassert.match(prompt, /\$AGENT_API_URL/);});+test("Open carries only the live actor's personal reads into a shared turn and audits actual access", async () => {+ const teammate: Principal = { id: "U2", type: "internal" };+ const { orchestrator, config, workspace, files, auditLog } = buildOrchestrator({+ sandbox: readSandbox(),+ isCurrentSharedScopeMember: async (_principalId, sourceScope) => sourceScope === scopeId("channel", "C1"),+ });+ const 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 channel = (thread: string, text: string, origin: OrchestratorInput["origin"]): OrchestratorInput => ({+ surface: "test",+ actor,+ conversation: {+ kind: "channel",+ threadRef: thread,+ channelRef: "C1",+ audience: [actor, teammate],+ publishMembers: [actor, teammate],+ },+ text,+ origin,+ });++ const isolated = await orchestrator.handleTurn(channel("C1:isolated", "!sysprompt", { kind: "human" }));+ assert.doesNotMatch(isolated.reply ?? "", /shared\/open-personal-U1\/private\.txt/);++ await config.setSharingPosture(scopeId("org", ORG), "open");+ const open = await orchestrator.handleTurn(+ channel("C1:open", "!read shared/open-personal-U1/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" }),+ );+ 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");+ 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");+ const nextActor = await orchestrator.handleTurn({+ ...channel("C1:open", "!read shared/open-personal-U1/private.txt", { kind: "human" }),+ actor: teammate,+ });+ assert.doesNotMatch(nextActor.reply ?? "", /NEW_PRIVATE_CONTENT/);+ const nextActorOwn = await orchestrator.handleTurn({+ ...channel("C1:open", "!read shared/open-personal-U2/teammate.txt", { kind: "human" }),+ actor: teammate,+ });+ assert.equal(nextActorOwn.reply, "TEAMMATE_PRIVATE_FILE");++ const automated = await orchestrator.handleTurn(channel("C1:automation", "!sysprompt", { kind: "automation" }));+ assert.doesNotMatch(automated.reply ?? "", /shared\/open-personal-U1\/private\.txt/);+ const incompleteRoster = await orchestrator.handleTurn({+ ...channel("C1:incomplete", "!sysprompt", { kind: "human" }),+ conversation: {+ kind: "channel",+ threadRef: "C1:incomplete",+ channelRef: "C1",+ audience: [actor, teammate],+ },+ });+ assert.doesNotMatch(incompleteRoster.reply ?? "", /shared\/open-personal-U1\/private\.txt/);+ await config.setExternalSlackParticipants(scopeId("org", ORG), true);+ const external = await orchestrator.handleTurn({+ surface: "slack",+ actor,+ conversation: {+ kind: "channel",+ threadRef: "C1:external",+ channelRef: "C1",+ audience: [actor, { id: "[email protected]", type: "guest" }],+ },+ text: "!sysprompt",+ origin: { kind: "human" },+ });+ assert.equal(external.status, "ok");+ assert.doesNotMatch(external.reply ?? "", /shared\/open-personal-U1\/private\.txt/);+ assert.equal((await workspace.list(channelScope)).includes("private.txt"), false);+ const carryAudit = (await auditLog.events()).find((event) => event.action === "sharing.cross_context_read");+ assert.equal(carryAudit?.principalId, actor.id);+ assert.deepEqual(JSON.parse(carryAudit?.detail ?? "{}"), {+ actor: actor.id,+ source: personal,+ target: channelScope,+ });+});++test("Open labels and audits a carried personal skill without granting it to the room", async () => {+ const personal = scopeId("personal", actor.id);+ const skills = createSkillStore();+ const skill = await skills.create({+ scopeId: personal,+ createdBy: actor.id,+ manifest: {+ name: "private-method",+ description: "Use a private working method",+ body: "Keep the method private.",+ requiredCapabilities: [],+ },+ });+ await skills.review(skill.id, actor.id, []);+ await skills.publish(skill.id);+ const { orchestrator, config, auditLog, acl } = buildOrchestrator({+ skills,+ isCurrentSharedScopeMember: async () => true,+ });+ await config.setSharingPosture(scopeId("org", ORG), "open");+ const result = await orchestrator.handleTurn({+ surface: "test",+ actor,+ conversation: {+ kind: "channel",+ threadRef: "C1:skill",+ channelRef: "C1",+ audience: [actor],+ publishMembers: [actor],+ },+ text: "!sysprompt",+ origin: { kind: "human" },+ });+ assert.match(result.reply ?? "", /\*\*private-method\*\* \[from personal:U1\]/);+ const event = (await auditLog.events()).find(+ (candidate) => candidate.action === "sharing.cross_context_read" && candidate.resource === `skill:${skill.id}`,+ );+ assert.deepEqual(JSON.parse(event?.detail ?? "{}"), {+ actor: actor.id,+ source: personal,+ target: scopeId("channel", "C1"),+ });+ assert.deepEqual(await acl.list(), []);+});++test("Open loads included memories in both directions with provenance and capture stays in the room", async () => {+ let member = true;+ const { orchestrator, config, memory, workspace } = buildOrchestrator({+ sandbox: readSandbox(),+ isCurrentSharedScopeMember: async (principalId, sourceScope) =>+ member && principalId === actor.id && sourceScope === scopeId("channel", "C1"),+ });+ const personal = scopeId("personal", actor.id);+ const channelScope = scopeId("channel", "C1");+ await config.setSharingPosture(scopeId("org", ORG), "open");+ await memory.capture(personal, ["PERSONAL_OPEN_MEMORY"], Date.now(), actor.id);+ const channelConversation: Conversation = {+ kind: "channel",+ threadRef: "C1:memory",+ channelRef: "C1",+ audience: [actor],+ publishMembers: [actor],+ };+ const prompt = await orchestrator.handleTurn({+ surface: "test",+ actor,+ conversation: channelConversation,+ text: "!sysprompt",+ origin: { kind: "human" },+ });+ assert.match(prompt.reply ?? "", /Sharing posture: Open/);+ assert.match(prompt.reply ?? "", /can reveal private information in a shared reply/);+ assert.match(prompt.reply ?? "", /### personal:U1[\s\S]*PERSONAL_OPEN_MEMORY/);++ await orchestrator.handleTurn({+ surface: "test",+ actor,+ conversation: { ...channelConversation, threadRef: "C1:capture" },+ text: "!memoryremember ROOM_ONLY_MEMORY",+ origin: { kind: "human" },+ });+ assert.match(await memory.read(channelScope), /ROOM_ONLY_MEMORY/);+ assert.doesNotMatch(await memory.read(personal), /ROOM_ONLY_MEMORY/);++ const search = await orchestrator.handleTurn(+ dm("dm:U1:open-search", "!memorysearch ROOM_ONLY_MEMORY", {+ origin: { kind: "human" },+ }),+ );+ assert.match(search.reply ?? "", /\[channel:C1\].*ROOM_ONLY_MEMORY/);+ await workspace.write(channelScope, "decision.txt", "ROOM_DECISION_FILE");+ const sharedFile = await orchestrator.handleTurn(+ dm("dm:U1:room-file", "!read shared/open-channel-C1/decision.txt", { origin: { kind: "human" } }),+ );+ assert.equal(sharedFile.reply, "ROOM_DECISION_FILE");++ const dmPrompt = await orchestrator.handleTurn(+ dm("dm:U1:search-only", "!sysprompt", {+ origin: { kind: "human" },+ }),+ );+ assert.match(dmPrompt.reply ?? "", /### channel:C1[\s\S]*ROOM_ONLY_MEMORY/);+ assert.match(dmPrompt.reply ?? "", /included, authorized memories/);+ assert.doesNotMatch(dmPrompt.reply ?? "", /apply it only if that tag matches here/);++ member = false;+ const revoked = await orchestrator.handleTurn(+ dm("dm:U1:revoked", "!memorysearch ROOM_ONLY_MEMORY", {+ origin: { kind: "human" },+ }),+ );+ 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" } }),+ );+ assert.doesNotMatch(revokedFile.reply ?? "", /ROOM_DECISION_FILE/);++ member = true;+ await config.setSharingPosture(channelScope, "isolated");+ const vetoed = await orchestrator.handleTurn(+ dm("dm:U1:vetoed", "!memorysearch ROOM_ONLY_MEMORY", {+ origin: { kind: "human" },+ }),+ );+ assert.doesNotMatch(vetoed.reply ?? "", /ROOM_ONLY_MEMORY/);+});+test("the system prompt is byte-identical across two turns a minute apart; the clock rides the environment note", async (t) => {t.mock.timers.enable({ apis: ["Date"], now: Date.now() });const { orchestrator: orch } = buildOrchestrator();@@ -358,3 +610,247 @@ test("a project session names its linked Slack home channel; unlinked projects gassert.equal(unlinked.status, "ok");assert.ok(!(unlinked.reply ?? "").includes("## Project home channel"));});++for (const mode of ["off", "writable", "skip"] as const) {+ test(`Open respects memory ${mode}`, async () => {+ const { orchestrator, config, memory } = buildOrchestrator({+ sandbox: readSandbox(),+ memoryPolicy: { recall: mode === "skip" ? "visible" : mode, capture: "off" },+ isCurrentSharedScopeMember: async () => true,+ });+ await config.setSharingPosture(scopeId("org", ORG), "open");+ await memory.capture(scopeId("personal", actor.id), ["DO_NOT_RECALL_PRIVATE_NOTE"], Date.now(), actor.id);+ for (const text of [+ "!sysprompt",+ "!memorysearch DO_NOT_RECALL_PRIVATE_NOTE",+ "!read shared/open-personal-U1/memory/MEMORY.md",+ ]) {+ const result = await orchestrator.handleTurn({+ surface: "test",+ actor,+ conversation: {+ kind: "channel",+ channelRef: "C1",+ threadRef: `C1:disabled:${mode}:${text}`,+ audience: [actor],+ publishMembers: [actor],+ },+ origin: { kind: "human" },+ text,+ ...(mode === "skip" ? { skipMemory: true } : {}),+ });+ assert.doesNotMatch(result.reply ?? "", /DO_NOT_RECALL_PRIVATE_NOTE/);+ }+ });+}++test("Open source memory is never exported into a reusable sandbox bearer token", async () => {+ let env: Record<string, string> | undefined;+ const box: Sandbox = {+ ...readSandbox(),+ provision: async (_layers, opts) => {+ env = opts?.env;+ return { id: "open-token", rootDir: "/workspace" };+ },+ run: async () => ({ stdout: "ok", stderr: "", code: 0, timedOut: false }),+ writeFile: async () => {},+ writeFileBytes: async () => {},+ listDir: async () => [],+ removeDir: async () => {},+ };+ const { orchestrator, config, memory } = buildOrchestrator({+ sandbox: box,+ isCurrentSharedScopeMember: async () => true,+ });+ const personal = scopeId("personal", actor.id);+ const room = scopeId("channel", "C1");+ await config.setSharingPosture(scopeId("org", ORG), "open");+ await memory.capture(personal, ["OPEN_TOKEN_PRIVATE"], Date.now(), actor.id);+ const result = await orchestrator.handleTurn({+ surface: "test",+ actor,+ origin: { kind: "human" },+ conversation: {+ kind: "channel",+ channelRef: "C1",+ threadRef: "C1:token",+ audience: [actor],+ publishMembers: [actor],+ },+ text: "!run echo ok",+ });+ assert.equal(result.status, "ok", result.reason);+ assert.ok(env?.AGENT_API_TOKEN);+ const claims = await verifyCapabilityToken(env.AGENT_API_TOKEN, "test-signing-secret");+ assert.ok(claims);+ assert.ok(claims.memory?.read.includes(room));+ assert.equal(claims.memory?.read.includes(personal), false);+ await memory.capture(room, ["ROOM_TOKEN_PRIVATE"], Date.now(), actor.id);+ const dmResult = await orchestrator.handleTurn(dm("dm:U1:open-token", "!run echo ok", { origin: { kind: "human" } }));+ assert.equal(dmResult.status, "ok", dmResult.reason);+ const dmClaims = await verifyCapabilityToken(env.AGENT_API_TOKEN, "test-signing-secret");+ assert.ok(dmClaims?.memory?.read.includes(personal));+ assert.equal(dmClaims?.memory?.read.includes(room), false);+});++for (const location of [+ "description",+ "body",+ "asset",+ "bundle",+ "unavailable",+ "multibyte",+ "bundle-error",+] as const) {+ test(`Open screens carried skill ${location} before exposing its index or materialized content`, async () => {+ const skills = createSkillStore();+ const bundles = createSkillBundleStore();+ const owner = scopeId("personal", actor.id);+ const room = scopeId("channel", "C1");+ let marker = "!security-risk";+ if (location === "unavailable") marker = "!security-screen-unavailable";+ if (location === "multibyte") marker = "字".repeat(7000);+ const create = async (scope: string, name: string) => {+ const carried = scope === owner;+ const skill = await skills.create({+ scopeId: scope,+ createdBy: actor.id,+ manifest: {+ name,+ description: carried && location === "description" ? marker : "A useful method",+ body: carried && ["body", "unavailable", "multibyte"].includes(location) ? marker : "Do useful work.",+ requiredCapabilities: [],+ files: carried && location === "asset" ? [{ path: "helper.sh", content: marker }] : [],+ },+ ...(carried && ["bundle", "bundle-error"].includes(location)+ ? { pack: { packId: "test-pack", commit: "1", upstreamName: name } }+ : {}),+ });+ await skills.review(skill.id, actor.id, []);+ await skills.publish(skill.id);+ };+ await create(owner, "carried-method");+ await create(room, "local-method");+ await bundles.put({+ packId: "test-pack",+ commit: "1",+ hash: "bundle-hash",+ files: [{ path: "shared-helper.sh", content: marker }],+ });+ if (location === "bundle-error")+ bundles.get = async () => {+ throw new Error("bundle temporarily unavailable");+ };+ const disk = new Map<string, string>();+ const sandbox: Sandbox = {+ ...readSandbox(),+ readFile: async (_handle, path) => disk.get(path) ?? null,+ writeFile: async (_handle, path, body) => {+ disk.set(path, body);+ },+ writeFileBytes: async (_handle, path, bytes) => {+ disk.set(path, Buffer.from(bytes).toString("utf8"));+ },+ removeDir: async (_handle, path) => {+ for (const key of disk.keys()) if (key === path || key.startsWith(`${path}/`)) disk.delete(key);+ },+ listDir: async () => [],+ };+ const { orchestrator, config } = buildOrchestrator({+ skills,+ skillBundles: bundles,+ sandbox,+ isCurrentSharedScopeMember: async () => true,+ });+ await config.setSharingPosture(scopeId("org", ORG), "open");+ const result = await orchestrator.handleTurn({+ surface: "test",+ actor,+ origin: { kind: "human" },+ conversation: {+ kind: "channel",+ channelRef: "C1",+ threadRef: `C1:screen-${location}`,+ audience: [actor],+ publishMembers: [actor],+ },+ text: "!sysprompt",+ });+ assert.equal(result.status, "ok", result.reason);+ assert.doesNotMatch(result.reply ?? "", /carried-method/);+ assert.match(result.reply ?? "", /local-method/);+ const read = await orchestrator.handleTurn({+ surface: "test",+ actor,+ origin: { kind: "human" },+ conversation: {+ kind: "channel",+ channelRef: "C1",+ threadRef: `C1:read-screen-${location}`,+ audience: [actor],+ publishMembers: [actor],+ },+ text: "!read skills/carried-method/SKILL.md",+ });+ assert.equal(read.status, "ok", read.reason);+ assert.doesNotMatch(read.reply ?? "", /!security-risk|!security-screen-unavailable/);+ assert.equal(disk.has("skills/carried-method/SKILL.md"), false);+ assert.ok(disk.has("skills/local-method/SKILL.md"));+ });+}++test("Open uses the exact skill snapshot that passed screening despite an in-flight source update", async () => {+ const skills = createSkillStore();+ const owner = scopeId("personal", actor.id);+ const skill = await skills.create({+ scopeId: owner,+ createdBy: actor.id,+ manifest: {+ name: "snapshot-method",+ description: "SAFE_DESCRIPTION",+ body: "SAFE_BODY",+ requiredCapabilities: [],+ },+ });+ await skills.review(skill.id, actor.id, []);+ await skills.publish(skill.id);+ let updated = false;+ const securityScreener: SecurityScreener = {+ provider: "test",+ shadow: false,+ classify: async ({ payload }) => {+ if (!updated && payload.includes("SAFE_DESCRIPTION")) {+ updated = true;+ await skills.update(skill.id, {+ ...skill.manifest,+ description: "UNSCREENED_UPDATE !security-risk",+ body: "UNSCREENED_BODY !security-risk",+ });+ }+ return { verdict: { decision: payload.includes("!security-risk") ? "strict" : "auto" }, score: 0, threshold: 1 };+ },+ };+ const { orchestrator, config } = buildOrchestrator({+ skills,+ securityScreener,+ isCurrentSharedScopeMember: async () => true,+ });+ await config.setSharingPosture(scopeId("org", ORG), "open");+ const result = await orchestrator.handleTurn({+ surface: "test",+ actor,+ origin: { kind: "human" },+ conversation: {+ kind: "channel",+ channelRef: "C1",+ threadRef: "C1:skill-snapshot",+ audience: [actor],+ publishMembers: [actor],+ },+ text: "!sysprompt",+ });+ assert.equal(result.status, "ok", result.reason);+ assert.equal(updated, true);+ assert.match(result.reply ?? "", /SAFE_DESCRIPTION/);+ assert.doesNotMatch(result.reply ?? "", /UNSCREENED_UPDATE|UNSCREENED_BODY/);+});diff --git a/test/turn-context.test.ts b/test/turn-context.test.tsnew file mode 100644index 000000000..c34fcf726--- /dev/null+++ b/test/turn-context.test.ts@@ -0,0 +1,166 @@+import { createAclStore } from "../src/acl/acl-store.ts";+import assert from "node:assert/strict";+import test from "node:test";+import { mkdtempSync } from "node:fs";+import { join } from "node:path";+import { tmpdir } from "node:os";+import { resolveTurnContext } from "../src/resolution/turn-context.ts";+import { createLocalWorkspaceStore } from "../src/workspace/workspace-store.ts";+import { createMemoryService } from "../src/memory/memory-service.ts";+import { createMemoryConfigStore } from "../src/resolution/config-store.ts";+import { createMemoryFileArtifactStore } 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 type { Resolution, Session } from "../src/types.ts";++async function fixture() {+ const workspace = createLocalWorkspaceStore(mkdtempSync(join(tmpdir(), "turn-context-")));+ const memory = createMemoryService(workspace);+ const config = createMemoryConfigStore("test", { defaultSharingPosture: "open" });+ const files = createMemoryFileArtifactStore(createMemoryDurableByteStore());+ const auditLog = createAuditLog();+ let member = true;+ const resolution = {+ layers: [+ { scopeId: "personal:alice", mode: "rw", mountPath: "" },+ { scopeId: "org:test", mode: "ro", mountPath: "global" },+ ],+ orgScopeId: "org:test",+ sharingPosture: "open",+ grantedHandles: [],+ } as unknown as Resolution;+ const acl = createAclStore();+ const input: Parameters<typeof resolveTurnContext>[0] = {+ actor: { id: "alice", type: "internal" },+ audience: [{ id: "alice", type: "internal" }],+ acl,+ targetScope: "personal:alice",+ origin: { kind: "human" },+ trustedLiveHuman: true,+ sessions: { listByParticipant: async () => [{ scopeId: "channel:eng", createdAt: 1 }] as Session[] },+ isCurrentSharedScopeMember: async (actor, scope) => member && actor === "alice" && scope === "channel:eng",+ config,+ 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");+ return {+ input,+ acl,+ memory,+ config,+ auditLog,+ removeMember: () => {+ member = false;+ },+ };+}++test("one context loads full source-labelled notebooks and shares authority with search and files", async () => {+ const { input, auditLog } = await fixture();+ const context = await resolveTurnContext(input);+ const recalled = await context.recall();+ assert.match(recalled, /### personal:alice[\s\S]*LOCAL_FACT/);+ assert.match(recalled, /### channel:eng[\s\S]*SHARED_FACT[\s\S]*LAST_FACT/);+ assert.ok(recalled.length > 12000, "no relevance or per-notebook recall truncation");+ assert.deepEqual(await context.searchMemory("LAST_FACT"), ["[channel:eng] LAST_FACT"]);+ assert.deepEqual(context.memoryAccess?.read, ["personal:alice", "org:test", "channel:eng"]);+ assert.deepEqual(context.baseRecallScopes, ["personal:alice", "org:test"], "reusable tokens exclude carried sources");+ assert.equal(context.memoryAccess?.write, "personal:alice");+ const handle = context.listFiles().find((h) => h.ownerScopeId === "channel:eng")!;+ const result = await context.readFile(handle.handlePath);+ assert.ok(result && "bytes" in result);+ assert.equal(Buffer.from(result.bytes!).toString(), "PLAN_CONTENT");+ assert.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")));+});++for (const mode of [+ "isolated",+ "source-veto",+ "removed",+ "speaker-switch",+ "automation",+ "memory-off",+ "memory-writable",+ "memory-skip",+] as const) {+ test(`context ${mode} excludes source memories consistently`, async () => {+ const { input, config, removeMember } = await fixture();+ if (mode === "isolated") input.resolution.sharingPosture = "isolated";+ if (mode === "source-veto") await config.setSharingPosture("channel:eng", "isolated");+ if (mode === "removed") removeMember();+ if (mode === "speaker-switch") input.actor = { id: "bob", type: "internal" };+ if (mode === "automation") input.trustedLiveHuman = false;+ if (mode === "memory-off") input.memoryPolicy.recall = "off";+ if (mode === "memory-writable") input.memoryPolicy.recall = "writable";+ if (mode === "memory-skip") input.useMemory = false;+ const context = await resolveTurnContext(input);+ assert.doesNotMatch(await context.recall(), /SHARED_FACT|LAST_FACT/);+ assert.deepEqual((await context.searchMemory("LAST_FACT")) ?? [], []);+ if (!mode.startsWith("memory-")) {+ assert.deepEqual(context.listFiles(), []);+ assert.equal(await context.readFile("shared/open-channel-eng/plan.txt"), null);+ }+ });+}++test("fresh turn re-resolves membership after an earlier successful read", async () => {+ const { input, removeMember } = await fixture();+ assert.match(await (await resolveTurnContext(input)).recall(), /SHARED_FACT/);+ removeMember();+ const next = await resolveTurnContext(input);+ assert.doesNotMatch(await next.recall(), /SHARED_FACT/);+ assert.equal(await next.readFile("shared/open-channel-eng/plan.txt"), null);+});++test("skill discovery uses the same included scopes and audience-filtered explicit grants", async () => {+ const { input, acl, removeMember } = await fixture();+ await acl.grant(+ {+ ownerScopeId: "personal:owner",+ ref: "skill:explicit",+ granteeScopeId: "personal:alice",+ permission: "read",+ grantedBy: "owner",+ },+ "owner",+ );+ const seen: Array<{ scopes: readonly string[]; grants: unknown }> = [];+ input.skills = {+ visibleFor: async (scopes, grants) => {+ seen.push({ scopes: [...scopes], grants });+ return [];+ },+ } as Pick<NonNullable<typeof input.skills>, "visibleFor"> as NonNullable<typeof input.skills>;+ await (await resolveTurnContext(input)).listSkills();+ assert.deepEqual(seen[0], {+ scopes: ["personal:alice", "channel:eng", "org:test"],+ grants: [{ id: "explicit", ownerScopeId: "personal:owner" }],+ });+ input.audience.push({ id: "bob", type: "internal" });+ input.targetScope = "channel:other";+ removeMember();+ await (await resolveTurnContext(input)).listSkills();+ assert.deepEqual(seen[1], { scopes: ["personal:alice", "org:test"], grants: [] });+});++test("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" },+ ];+ const result = await (await resolveTurnContext(input)).readFile("shared/plan.txt");+ assert.ok(result && "error" in result);+ assert.match(result.error, /ambiguous shared handle/);+});