The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Isolate unreleased companion and memory subsystems from core (#684)
Dee5f421456ef3f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex f9377afa4..e7d80029e 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -238,6 +238,34 @@ jobs:node scripts/test-process-images-bundled.mjsnpx vitest run src/lib/nativeProcessImages.spec.ts src/lib/processImages.spec.ts src/lib/processImages.real.spec.ts --maxWorkers=1+ # The optional product has its own dependencies, bundle and suites. CLI-only CI+ # deliberately checks core without installing or building this package.+ companion-subsystems:+ if: ${{ (inputs.scope || 'full') == 'full' }}+ runs-on: ubuntu-latest+ timeout-minutes: 10+ defaults:+ run:+ working-directory: companions+ steps:+ - uses: actions/checkout@v7+ - uses: actions/setup-node@v7+ with:+ node-version: ${{ env.CLI_NODE_VERSION }}+ cache: npm+ cache-dependency-path: |+ cli/package-lock.json+ companions/package-lock.json+ # Shared source helpers retain their own dependency resolution during typecheck.+ - run: npm ci --prefix ../cli --ignore-scripts+ - run: npm ci+ - run: npm run typecheck+ - run: npm run build+ - run: npm run test:bundle+ # CPU-budget fuzz runs alone, separate from subprocess-heavy fixture tests.+ - run: npx vitest run src/shared/guard.fuzz.spec.ts --maxWorkers=1+ - run: npm test -- --exclude src/shared/guard.fuzz.spec.ts --maxWorkers=3+# Typecheck and contract checks run alongside the default suite's four shards.cli-contracts:if: ${{ contains(fromJSON('["full","cli"]'), inputs.scope || 'full') }}@@ -304,12 +332,6 @@ jobs:- name: Native helper build-input and portable bundle contractsrun: node --test scripts/test-process-image-bundle.mjs- # The guard fuzz suite measures a wall-clock CPU budget. Sibling workers running- # subprocess fixtures can deschedule it past that bound on a shared runner.- # Keep it outside the default-suite shards, with the same assertions and deadline.- - name: Guard fuzz and bounded hostile-input time- run: npx vitest run src/pair/learn/guard.fuzz.spec.ts-- name: Concurrent registry discovery, hooks and durable close intentsrun: node scripts/registry-observation-e2e.mjs "$RUNNER_TEMP/registry-observation-e2e"@@ -347,9 +369,9 @@ jobs:# existing worker cap/isolation: subprocess fixtures still need spare CPUs.# Opt-in real-engine suites retain their existing explicit skips.- name: Discover the complete default-suite inventory- run: npx vitest list --config vitest.ci.config.ts --filesOnly --exclude src/pair/learn/guard.fuzz.spec.ts --json="$RUNNER_TEMP/inventory-${{ matrix.shard }}.json"+ run: npx vitest list --config vitest.ci.config.ts --filesOnly --json="$RUNNER_TEMP/inventory-${{ matrix.shard }}.json"- name: Run default-suite shard- run: npx vitest run --config vitest.ci.config.ts --exclude src/pair/learn/guard.fuzz.spec.ts --shard=${{ matrix.shard }}/4 --reporter=default --reporter=json --outputFile.json="$RUNNER_TEMP/result-${{ matrix.shard }}.json"+ run: npx vitest run --config vitest.ci.config.ts --shard=${{ matrix.shard }}/4 --reporter=default --reporter=json --outputFile.json="$RUNNER_TEMP/result-${{ matrix.shard }}.json"- name: Preserve inventory and test resultsif: ${{ !cancelled() }}uses: actions/upload-artifact@v4diff --git a/cli/build-bundle.mjs b/cli/build-bundle.mjsindex 430f5d7d6..893e3b532 100644--- a/cli/build-bundle.mjs+++ b/cli/build-bundle.mjs@@ -14,8 +14,6 @@ import * as esbuild from 'esbuild'import { readFileSync, copyFileSync, rmSync } from 'fs'import { readDshRegistry } from './scripts/lib/dshRegistry.mjs'import { readBuiltinBundle, readHarnessMonitorBundle, readModelManagerBundle } from './scripts/lib/modelManagerBundle.mjs'-import { plateWorkerSource } from './scripts/lib/plateWorker.mjs'-import { memoryWorkerSource } from './scripts/lib/memoryWorker.mjs'import { readProcessImageBundle } from './scripts/lib/processImageBundle.mjs'import { fileURLToPath } from 'node:url'const modelManagerBundle = JSON.stringify(readModelManagerBundle(fileURLToPath(new URL('../store/agents/autonomous-grid', import.meta.url))))@@ -28,10 +26,6 @@ const version =// The bundled registry (the store/ folders and store/registry at the repo root) — see src/dsh/registry.ts.const dshRegistry = JSON.stringify(readDshRegistry(new URL('../store', import.meta.url)))-// The plate worker, bundled on its own (src/pair/plateService.ts): harnessd starts it from this string,-// since the release is this one file.-const plateWorker = await plateWorkerSource({ minify: true })-const memoryWorker = await memoryWorkerSource({ minify: true })const processImages = readProcessImageBundle({path: process.env.HARNESS_PROCESS_IMAGES_ARTIFACT,required: process.env.HARNESS_REQUIRE_PROCESS_IMAGES === '1',@@ -54,8 +48,6 @@ await esbuild.build({__MODEL_MANAGER_BUNDLE__: JSON.stringify(modelManagerBundle),__DEVICES_BUNDLE__: JSON.stringify(devicesBundle),__HARNESS_MONITOR_BUNDLE__: JSON.stringify(harnessMonitorBundle),- __PLATE_WORKER__: JSON.stringify(plateWorker),- __MEMORY_WORKER__: JSON.stringify(memoryWorker),__DARWIN_PROCESS_IMAGES__: processImages ? JSON.stringify(processImages) : 'undefined',},// The copyright line is MIT's one condition — it has to travel with the copy the user actuallydiff --git a/cli/build.mjs b/cli/build.mjsindex 7b206d767..cb7ab29d1 100644--- a/cli/build.mjs+++ b/cli/build.mjs@@ -3,8 +3,6 @@ import { readdirSync, statSync, readFileSync } from 'fs'import { join } from 'path'import { readDshRegistry } from './scripts/lib/dshRegistry.mjs'import { readBuiltinBundle, readHarnessMonitorBundle, readModelManagerBundle } from './scripts/lib/modelManagerBundle.mjs'-import { plateWorkerSource } from './scripts/lib/plateWorker.mjs'-import { memoryWorkerSource } from './scripts/lib/memoryWorker.mjs'import { fileURLToPath } from 'node:url'const modelManagerBundle = JSON.stringify(readModelManagerBundle(fileURLToPath(new URL('../store/agents/autonomous-grid', import.meta.url))))const devicesBundle = JSON.stringify(readBuiltinBundle(fileURLToPath(new URL('../store/agents/devices', import.meta.url)), ['harness.json', 'AGENTS.md', 'LICENSE', 'template']))@@ -15,9 +13,6 @@ const harnessMonitorBundle = JSON.stringify(readHarnessMonitorBundle(fileURLToPaconst version = JSON.parse(readFileSync('package.json', 'utf8')).version// The bundled registry (the store/ folders and store/registry at the repo root) — see src/dsh/registry.ts.const dshRegistry = JSON.stringify(readDshRegistry(join('..', 'store')))-// The plate worker, bundled on its own (src/pair/plateService.ts): harnessd starts it from this string.-const plateWorker = await plateWorkerSource()-const memoryWorker = await memoryWorkerSource()function getAllTsFiles(dir, fileList = []) {const files = readdirSync(dir)@@ -52,8 +47,6 @@ try {__MODEL_MANAGER_BUNDLE__: JSON.stringify(modelManagerBundle),__DEVICES_BUNDLE__: JSON.stringify(devicesBundle),__HARNESS_MONITOR_BUNDLE__: JSON.stringify(harnessMonitorBundle),- __PLATE_WORKER__: JSON.stringify(plateWorker),- __MEMORY_WORKER__: JSON.stringify(memoryWorker),},logLevel: 'info',})diff --git a/cli/ci-test-durations.json b/cli/ci-test-durations.jsonindex 7c6c14671..6b25422a1 100644--- a/cli/ci-test-durations.json+++ b/cli/ci-test-durations.json@@ -55,17 +55,7 @@"src/localWsServer.spec.ts": 2700,"src/loginForceRace.spec.ts": 3300,"src/machinesCommand.spec.ts": 5800,- "src/memory/capture.spec.ts": 1500,- "src/memory/claudeInference.spec.ts": 1200,- "src/memory/notebook.spec.ts": 1300,- "src/memory/opencodeCapture.spec.ts": 1800,- "src/memory/opencodeInference.spec.ts": 1500,- "src/memory/retention.spec.ts": 1100,- "src/memory/runtime.spec.ts": 1100,- "src/memory/store.spec.ts": 2000,"src/orchestrator/service.spec.ts": 2700,- "src/pair/classify.fuzz.spec.ts": 2300,- "src/pair/plateService.spec.ts": 2800,"src/remoteCommand.spec.ts": 1400,"src/scripts/install.spec.ts": 10100,"src/teams/remote.spec.ts": 20500,diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjsindex 2b441a8ca..e27492380 100644--- a/cli/hook/notify.mjs+++ b/cli/hook/notify.mjs@@ -1561,8 +1561,7 @@ async function main() {}// SessionStart or UserPromptSubmit (the catch hook) → register the session. Registration is- // idempotent, so re-registering on every prompt is cheap. The daemon verifies the process before- // supplying the collection persona or optional, scope-checked coding memory.+ // idempotent, so re-registering on every prompt is cheap. The adapter verifies the process.// Command Code fires SessionStart BEFORE it writes the transcript, and the daemon validates the path// (realpath) — sending one that isn't on disk yet gets the whole registration rejected. Announce// without it; the session is registered again with the real path on the first Stop. Scoped to@@ -1589,23 +1588,10 @@ async function main() {model: modelName(input.model),cliVersion: input.cli_version || input.cursor_version || input.version,}- const ok = await post(port, '/api/hook/session-start', body, (response) => {- if (event !== 'UserPromptSubmit' || (engine !== 'claude' && engine !== 'codex')) return- if (typeof response.additionalContext !== 'string' || !response.additionalContext || response.additionalContext.length > 8_000) return- hookOutput = JSON.stringify({ hookSpecificOutput: {- hookEventName: 'UserPromptSubmit', additionalContext: response.additionalContext,- } })- if (typeof response.memoryReceiptId === 'string' && /^[a-f0-9-]{36}$/.test(response.memoryReceiptId)) {- acknowledgeMemoryOutput = () => post(port, '/api/hook/memory-emitted', {- engine, sessionId: body.sessionId, ...terminalHookFields(tmuxPane), memoryReceiptId: response.memoryReceiptId,- })- }- })+ const ok = await post(port, '/api/hook/session-start', body)if (!ok) await fallbackRegister(input, engine, tmuxPane)}-let hookOutput = null-let acknowledgeMemoryOutput = nullmain().catch(() => {}).finally(() => {@@ -1617,11 +1603,6 @@ main()// — there `decision` is required, and `{}` reads as a denial (measured: every tool call of the turn// came back "Tool call denied by pre-tool hook").// Copilot parses stdout as JSON too; `{}` is the documented no-op for every event installed here.- if (hookOutput) process.stdout.write(`${hookOutput}\n`, (error) => {- // This proves only the pipe write. It does not prove native ingestion, model use or usefulness.- if (error || !acknowledgeMemoryOutput || remainingBudget() <= 0) { process.exit(0); return }- Promise.resolve(acknowledgeMemoryOutput()).catch(() => {}).finally(() => process.exit(0))- })- else if (e === 'cursor' || e === 'hermes' || e === 'agy' || e === 'copilot') process.stdout.write('{}\n', () => process.exit(0))+ if (e === 'cursor' || e === 'hermes' || e === 'agy' || e === 'copilot') process.stdout.write('{}\n', () => process.exit(0))else process.exit(0)})diff --git a/cli/scripts/lib/plateWorker.mjs b/cli/scripts/lib/plateWorker.mjsdeleted file mode 100644index 392c41bd9..000000000--- a/cli/scripts/lib/plateWorker.mjs+++ /dev/null@@ -1,21 +0,0 @@-import * as esbuild from 'esbuild'-import { fileURLToPath } from 'node:url'--// The plate worker (src/pair/plateWorker.ts) as one self-contained CommonJS script: the shader, every-// model and the roll bundled in. Both builds define it as `__PLATE_WORKER__`, and harnessd starts it with-// `new Worker(source, { eval: true })` — the release ships a single cli.js, so the worker cannot be a-// file of its own beside it.-export async function plateWorkerSource({ minify = false } = {}) {- const result = await esbuild.build({- entryPoints: [fileURLToPath(new URL('../../src/pair/plateWorker.ts', import.meta.url))],- bundle: true,- write: false,- platform: 'node',- format: 'cjs',- target: 'node20',- minify,- legalComments: 'none',- logLevel: 'silent',- })- return result.outputFiles[0].text-}diff --git a/cli/src/backendSocket.optionalFeatures.spec.ts b/cli/src/backendSocket.optionalFeatures.spec.tsnew file mode 100644index 000000000..00c5955ca--- /dev/null+++ b/cli/src/backendSocket.optionalFeatures.spec.ts@@ -0,0 +1,74 @@+import { afterEach, expect, it, vi } from 'vitest'+import { BackendSocket } from './backendSocket.js'+import { PAIR_REQUESTS, PLATE_REQUEST, rpcResultType } from './lib/e2ee/applicationFrames.js'++afterEach(() => vi.restoreAllMocks())++it.each(['memory', 'recall_memory', 'status', 'list_harnesses'])(+ 'refuses retired optional %s requests without starting any feature service', async verb => {+ const socket = new BackendSocket('fixture')+ const frames: Array<{ type?: unknown; payload?: any }> = []+ vi.spyOn(socket, 'sendTo').mockImplementation((_to, frame) => { frames.push(frame) })+ socket.registerLocalClient('local:feature', { sendFrame: () => true, sendBinary: () => true }, { tool: true })+ try {+ socket.handleLocalFrame('local:feature', { type: 'pair', payload: {+ requestId: 'retired', verb, action: 'configure_experiment', enabled: true,+ } })+ await vi.waitFor(() => expect(frames).toContainEqual({ type: 'pair_result', payload: {+ requestId: 'retired', error: 'UNSUPPORTED',+ } }))+ } finally {+ await socket.unregisterLocalClient('local:feature')+ await socket.stop()+ }+ },+)++const retiredRequests = ['pair', ...PAIR_REQUESTS, PLATE_REQUEST]++it.each(retiredRequests)('preserves the local transport boundary for %s', async type => {+ const socket = new BackendSocket('fixture')+ const frames: unknown[] = []+ socket.registerLocalClient('local:window', {+ sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true,+ })+ try {+ socket.handleLocalFrame('local:window', { type, payload: { requestId: 'retired' } })+ await vi.waitFor(() => expect(frames).toContainEqual({ type: rpcResultType(type), payload: {+ requestId: 'retired', error: type === 'pair' ? 'UNSUPPORTED' : 'REMOTE_ONLY',+ } }))+ } finally {+ await socket.unregisterLocalClient('local:window')+ await socket.stop()+ }+})++it.each(retiredRequests)('keeps the encrypted, targeted refusal for relayed %s', async type => {+ const socket = new BackendSocket('fixture')+ const internal = socket as any+ vi.spyOn(internal.e2ee, 'hasSession').mockReturnValue(true)+ vi.spyOn(internal.e2ee, 'sessionRole').mockReturnValue('web')+ vi.spyOn(internal.e2ee, 'unwrapDown').mockReturnValue({ type, payload: { requestId: 'retired' } })+ const wrap = vi.spyOn(internal.e2ee, 'wrapRpcReply').mockReturnValue({+ type: rpcResultType(type), payload: { __e2e: 'sealed' },+ })+ const broadcast = vi.spyOn(socket, 'send')+ try {+ await internal.dispatchDown({ type, payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }, 'remote:owner', 'relay')+ expect(wrap).toHaveBeenCalledWith('remote:owner', rpcResultType(type), 'retired', {+ error: type === 'pair' ? 'LOCAL_ONLY' : 'UNSUPPORTED',+ })+ expect(broadcast).not.toHaveBeenCalled()+ } finally { await socket.stop() }+})++it.each(retiredRequests)('still refuses plaintext relayed %s before optional dispatch', async type => {+ const socket = new BackendSocket('fixture')+ const frames: unknown[] = []+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ vi.spyOn(socket, 'sendTo').mockImplementation((_to, frame) => { frames.push(frame) })+ try {+ await (socket as any).dispatchDown({ type, payload: { requestId: 'retired' } }, 'remote:untrusted', 'relay')+ expect(frames).toEqual([{ type: rpcResultType(type), payload: { requestId: 'retired', error: 'E2EE_REQUIRED' } }])+ } finally { await socket.stop() }+})diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 55b564d23..e87b91e82 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -132,7 +132,6 @@ import {} from './lib/terminalBinary.js'import { b64d, fingerprint, isWrapped } from './lib/e2ee/core.js'import { encryptRpcResult, PAIR_REQUESTS, PLATE_REQUEST, rpcResultType } from './lib/e2ee/applicationFrames.js'-import type { PairEvent, PairService } from './pair/protocol.js'import { tmuxPaneInfo } from './lib/tmux.js'import { DEVICE_RECENT_SAFE_FRAME_BYTES, fitRecentReplyPayloadForDevice } from './lib/deviceRecentTrim.js'import { shouldReplayCommander } from './lib/commanderReplay.js'@@ -792,17 +791,6 @@ export class BackendSocket {/** Receives `theme_set` — the desktop's pane colours, to become this machine's tmux* `window-style` (lib/hostTheme.ts). Wired by cli.ts; null answers with UNSUPPORTED. */hostThemeSink: ((theme: HostTheme) => void) | null = null- /**- * The pair brain's sensor (pair/sensor.ts): answers the sealed `pair_*` RPCs another machine's brain- * sends, and the loopback-only `pair` request. Null answers UNSUPPORTED, like an older daemon.- */- pairService: PairService | null = null- /** The owning machine's reads and writes for the pair (pair/owner.ts). Null: those answer UNSUPPORTED. */- pairOwner: { handle: (type: string, payload: Record<string, unknown>, from: { connId: string; label?: string | null }) => Promise<Record<string, unknown>> } | null = null- /** The control interface (pair/control.ts) behind the loopback `pair` request: the verbs it answers. */- pairControl: { verbs: ReadonlySet<string>; local: (payload: Record<string, unknown>, connId: string) => Promise<Record<string, unknown>> } | null = null- /** The account's zoo changed (a `zoo_changed` from the backend) — cli.ts re-reads which daemon is paired. */- onZooChanged: ((revision: number) => void) | null = null/** The account's device key log grew (lib/e2ee/deviceLogSyncer.ts): re-read it from this machine's head. */onDeviceKeysChanged: (() => void) | null = null/** This machine's key was taken out of the account's device key log (`machine_revoked` says so). */@@ -814,17 +802,6 @@ export class BackendSocket {onLinkUp: (() => void) | null = null/** Appends to the device key log waiting for the backend's answer, by requestId. */private readonly devlogAppends = new Map<string, (payload: Record<string, unknown> | null) => void>()- /**- * Whether daemons run at all (lib/daemonsSwitch.ts). Off, the loopback `pair` request (`harness pair`, the- * MCP server) is answered DAEMONS_OFF before any verb runs, except the verified owner's local coding- * memory opt-in setting. That setting does not read memory or start a companion. Null: always on.- */- daemonsOn: (() => boolean) | null = null- /**- * An individual's art (pair/plateService.ts), for the phone's sealed `pair_plate_get` → `pair_plate`. Null- * answers UNSUPPORTED, like an older daemon. The service answers DAEMONS_OFF itself while daemons are off.- */- plateService: { get: (payload: Record<string, unknown>) => Promise<Record<string, unknown>> } | null = nullruntimeProfileProvider: ((session: RegisteredSession) => string | null) | null = nullonRuntimeProfileUpdate: ((sessionId: string, selectedModel: string) => Promise<void>) | null = null/** Web↔adapter E2EE: group-encrypts user events, runs the CPace pairing, holds per-conn sessions. */@@ -1445,7 +1422,6 @@ export class BackendSocket {if (!this.toolClients.delete(connId)) this.onLocalClient?.(connId, false)this.rowStateWindows.delete(connId)this.viewerForwarder.closeConnection(connId)- this.pairService?.unwatch(connId)this.interactiveViewers.closeConnection(connId); this.ownerCommands.closeConnection(connId)// The window left before any link could hear it attach: nothing happened, as far as the backend// is concerned, and a later link must not be told otherwise.@@ -1699,75 +1675,6 @@ export class BackendSocket {this.send({ type: resultType, payload: { requestId, ...payload } })}- /**- * The pair brain's requests (daemons/BRAIN.md):- * - `pair_watch` / `pair_journal` from another machine's brain, answered by the sensor;- * - `pair_list`, `pair_read` and the writes (`pair_answer`, `pair_send`, `pair_stop`, `pair_start`,- * `pair_pause`, `pair_resume`), answered by the owning machine's PairOwner (pair/owner.ts), which- * re-checks the floor and journals every action;- * - the loopback-only `pair`: the control interface's verbs (pair/control.ts) when it is wired, the- * sensor's own read verbs otherwise.- * An older daemon answers every one of them UNSUPPORTED, which a brain already handles.- */- private handlePair(connId: string, type: string, payload: Record<string, unknown>, local: boolean,- reply: (t: string, rid: unknown, p: Record<string, unknown>) => void): void {- const requestId = payload.requestId- const service = this.pairService- const detached = (work: Promise<Record<string, unknown>>): void => {- void work.then((result) => reply(type, requestId, result)).catch(() => reply(type, requestId, { error: 'PAIR_FAILED' }))- }- if (type === 'pair') {- if (!local) { reply(type, requestId, { error: 'LOCAL_ONLY', detail: 'Ask the pair brain on this computer.' }); return }- const verb = typeof payload.verb === 'string' ? payload.verb : ''- const control = this.pairControl- // The owner must be able to clear the saved opt-in without turning companions on. Only these- // two settings actions reach MemoryControl, which checks their full schema and verifies the OS- // caller. Ordinary library, recall and agent tools remain inert while the master switch is off.- const memorySetting = control?.verbs.has('memory') && verb === 'memory' &&- (payload.action === 'experiment' || payload.action === 'configure_experiment')- if (this.daemonsOn && !this.daemonsOn() && !memorySetting) { reply(type, requestId, { error: 'DAEMONS_OFF', detail: 'Daemons are off for this account or on this computer.' }); return }- if (control && control.verbs.has(verb)) { detached(control.local(payload, connId)); return }- if (!service) { reply(type, requestId, { error: 'UNSUPPORTED' }); return }- detached(service.local(payload))- return- }- // The machine-to-machine requests come from ANOTHER machine, sealed. This computer's own processes use- // `pair` (a tool) or the window's daemon_* frames; a loopback `pair_*` would be a local process- // claiming to be a remote brain — and the owner treats a remote request as one (daemons/BRAIN.md).- if (local) { reply(type, requestId, { error: 'REMOTE_ONLY', detail: 'pair_* requests come from another machine.' }); return }- if (!service) { reply(type, requestId, { error: 'UNSUPPORTED' }); return }- if (!service.enabled()) { reply(type, requestId, { error: 'PAIR_OFF' }); return }- if (type === 'pair_watch') {- if (payload.off === true) { service.unwatch(connId); reply(type, requestId, { ok: true }); return }- const snapshot = service.watch(connId, (event) => this.sendPairEvent(connId, event))- reply(type, requestId, { snapshot })- return- }- if (type === 'pair_journal') { reply(type, requestId, { ...service.journal(payload) }); return }- const owner = this.pairOwner- if (!owner) {- reply(type, requestId, type === 'pair_read' ? service.read(payload) : { error: 'UNSUPPORTED' })- return- }- // Detached: an answer keys a dialog and a pause saves a conversation, both seconds of work that must- // not hold the watch's pushes behind them on this connection.- detached(owner.handle(type, payload, { connId, label: this.e2ee.sessionLabel(connId) }))- }-- /** One `pair_event` to one watcher: plaintext over loopback, sealed pairwise (`wrapTarget`) otherwise.- * Through the same ordered queue as the watch's reply, and only while the link is up — a push for a- * connection the backend has forgotten is dropped there anyway. False = stop pushing to it. */- private sendPairEvent(connId: string, event: PairEvent): boolean {- const payload = event as unknown as Record<string, unknown>- const local = this.localClients.get(connId)- if (local) return local.sendFrame({ type: 'pair_event', payload })- if (!this.isConnected()) return false- const frame = this.e2ee.wrapTarget(connId, 'pair_event', payload)- if (!frame) return false- this.sendTo(connId, frame)- return true- }-private async dispatchDown(frame: Frame, connId: string, transport: DownTransport = 'relay'): Promise<void> {const type = frame.type as string | undefinedif (!type) return@@ -1900,7 +1807,6 @@ export class BackendSocket {this.autonomousDeviceRelay?.drop(connId)this.e2ee.dropSession(connId)this.viewerForwarder.closeConnection(connId)- this.pairService?.unwatch(connId)this.interactiveViewers.closeConnection(connId); this.ownerCommands.closeConnection(connId)await this.terminalP2p.closeConnection(connId, 'client_disconnected', false)this.p2pPendingOpens.delete(connId)@@ -1951,7 +1857,6 @@ export class BackendSocket {if (type === 'zoo_changed') {const revision = (typeof frame.payload === 'object' && frame.payload !== null ? (frame.payload as { revision?: unknown }).revision : undefined)this.sendLocal({ type: 'zoo_changed', payload: { revision: typeof revision === 'number' ? revision : 0 } })- this.onZooChanged?.(typeof revision === 'number' ? revision : 0)return}@@ -2068,21 +1973,12 @@ export class BackendSocket {return}- // The pair brain (daemons/BRAIN.md). `pair_*` come from another machine's brain and reach here only- // sealed — the default-deny above already refused them in the clear. `pair` is this computer's own.- if (PAIR_REQUESTS.has(type) || type === 'pair') {- this.handlePair(connId, type, payload, local, reply)- return- }- // An individual's art for the phone, sealed (the default-deny above refused it in the clear). A window- // on this computer asks `daemon_plate_get` over the Unix socket instead; the same request over loopback- // would let a TCP client past that, so it is refused like a loopback `pair_*`.- if (type === PLATE_REQUEST) {- if (local) { reply(type, requestId, { error: 'REMOTE_ONLY', detail: 'On this computer, ask daemon_plate_get over the daemon\'s socket.' }); return }- const plates = this.plateService- if (!plates) { reply(type, requestId, { error: 'UNSUPPORTED' }); return }- // Detached: a plate not drawn yet takes seconds, and this connection's other requests must not wait.- void plates.get(payload).then((result) => reply(type, requestId, result)).catch(() => reply(type, requestId, { error: 'RENDER_FAILED' }))+ // Retired optional-feature requests remain reserved. Never reinterpret one as an+ // ordinary command or weaken its existing encryption / local transport boundary.+ if (PAIR_REQUESTS.has(type) || type === 'pair' || type === PLATE_REQUEST) {+ const error = type === 'pair' && !local ? 'LOCAL_ONLY'+ : type !== 'pair' && local ? 'REMOTE_ONLY' : 'UNSUPPORTED'+ reply(type, requestId, { error })return}diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.tsindex a2108d606..d80ad5006 100644--- a/cli/src/cable/cableHost.ts+++ b/cli/src/cable/cableHost.ts@@ -1,4 +1,3 @@-import type { CompanionIdentity, CompanionMilestone } from './companionIdentity.js'// Everything the cable session needs from the rest of the daemon, in one place.//// The session owns the protocol and nothing else; this owns the answers. Keeping them apart is what lets@@ -37,9 +36,6 @@ export interface RecentTurn {}export interface CableHostWiring {- companion?: () => string | null- companionIdentity?: () => CompanionIdentity | null- companionMilestone?: () => CompanionMilestone | null/** Exact live terminal footer for a local agent; absent when no footer is visible. */activityText?: (agentId: string) => Promise<string | null>/** The person's own last questions to a LOCAL agent, newest first. */@@ -319,10 +315,6 @@ export class DaemonCableHost implements CableHost {return locale.startsWith('vi') ? 'vi' : 'en'}- companion(): string | null { return this.wiring.companion?.() ?? null }- companionIdentity(): CompanionIdentity | null { return this.wiring.companionIdentity?.() ?? null }- companionMilestone(): CompanionMilestone | null { return this.wiring.companionMilestone?.() ?? null }-/** This computer's own agents, in the order every other surface reads them in. */private localAgents(): CableAgent[] {// `advertised()`, not `list()` — the SAME set `agents_list` answers the web and the desktop app with. Theydiff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.tsindex ee0888f52..54b81aa5c 100644--- a/cli/src/cable/cableSession.spec.ts+++ b/cli/src/cable/cableSession.spec.ts@@ -134,101 +134,15 @@ describe('cable session', () => {voiceLang: 'en', followCompanion: true, companion: null as string | null,}- it('follows all ten paired species, deduplicates acknowledgements and restores the saved skin', async () => {- let paired: string | null = 'tim'- const { session, port } = await connect(makeHost({ companion: () => paired }))- try {- port.say({ t: 'hello', product: 'harness', mac: 'aa:bb', fw: 'companions', settings: companionSettings })- await vi.waitFor(() => expect(port.sent).toContainEqual({ t: 'companion.set', id: 'tim' }))- for (const id of ['tim', 'gnu', 'lynx', 'mutt', 'yak', 'gopher', 'bug', 'tux', 'auk', 'beastie']) {- paired = id- await session['syncCompanion']()- expect(port.sent.filter(m => m.t === 'companion.set').at(-1)).toEqual({ t: 'companion.set', id })- port.say({ t: 'settings.state', ok: true, settings: { ...companionSettings, companion: id } })- await settle()- const count = port.sent.length- await session['syncCompanion']()- expect(port.sent).toHaveLength(count)- }- paired = null // unpair, sign out or disable Focus-bar creature- await session['syncCompanion']()- expect(port.sent.at(-1)).toEqual({ t: 'companion.set', id: null })- expect(port.types()).not.toContain('settings.set') // brightness and saved Focus skin survive- } finally { await session.stop() }- })-- it('syncs individual changes and sends fresh celebrations once without replay on hello', async () => {- let identity = {id:'tim',uid:'tim_1',seed:42,name:'Pip',version:'0.1' as '0.1'|'1.0',colour:2,mark:1}- let event: import('./companionIdentity.js').CompanionMilestone | null = null- const {session,port}=await connect(makeHost({companion:()=>identity.id, companionIdentity:()=>identity, companionMilestone:()=>event}))- const settings={...companionSettings,companionProtocol:2,companionDetails:null as unknown}- try {- port.say({t:'hello',product:'harness',mac:'aa:bb',settings})- await vi.waitFor(()=>expect(port.sent).toContainEqual({t:'companion.set',id:'tim',identity}))- port.say({t:'settings.state',settings:{...settings,companion:'tim',companionDetails:identity}})- identity={...identity,name:'Dot',version:'1.0',colour:3,mark:2}- await session['syncCompanion']()- expect(port.sent.filter(m=>m.t==='companion.set').at(-1)).toEqual({t:'companion.set',id:'tim',identity})- port.say({t:'settings.state',settings:{...settings,companion:'tim',companionDetails:identity}})- event={token:'tim_1:grow:1.0',kind:'grow',at:Date.now(),companion:identity}- await session['syncCompanion'](); await session['syncCompanion']()- expect(port.sent.filter(m=>m.t==='companion.celebrate')).toHaveLength(1)- port.say({t:'hello',product:'harness',mac:'aa:bb',settings})- await session['syncCompanion']()- expect(port.sent.filter(m=>m.t==='companion.celebrate')).toHaveLength(1)- event={...event,token:'old-event',at:Date.now()-9_000}- await session['syncCompanion']()- expect(port.sent.filter(m=>m.t==='companion.celebrate')).toHaveLength(1)- port.say({t:'settings.state',settings:{...settings,quiet:true}})- event={...event,token:'quiet-event',at:Date.now()}- await session['syncCompanion']()- port.say({t:'settings.state',settings:{...settings,quiet:false}})- await session['syncCompanion']()- expect(port.sent.filter(m=>m.t==='companion.celebrate')).toHaveLength(1)- } finally { await session.stop() }- })-- it('honours follow-off, refuses unknown species and never sends companion commands to old firmware', async () => {- let paired = 'gnu'- const { session, port } = await connect(makeHost({ companion: () => paired }))- try {- port.say({ t: 'hello', product: 'harness', mac: 'aa:bb', settings: { ...companionSettings, followCompanion: false } })- await settle(); await session['syncCompanion']()- expect(port.types()).not.toContain('companion.set')- paired = 'unknown'- port.say({ t: 'settings.state', settings: companionSettings })- await settle(); await session['syncCompanion']()- expect(port.types()).not.toContain('companion.set')- paired = 'gnu'- await session['syncCompanion']()- expect(port.sent.at(-1)).toEqual({ t: 'companion.set', id: 'gnu' })- port.sent.length = 0- port.say({ t: 'hello', product: 'harness', mac: 'other', fw: 'old' })- await settle(); await session['syncCompanion']()- expect(port.types()).not.toContain('companion.set')- } finally { await session.stop() }- })-- it('bounds unacknowledged retries, sends a newer choice immediately and restores after reboot', async () => {- let paired = 'tim'- const { session, port } = await connect(makeHost({ companion: () => paired }))+ it('preserves dial settings and sends no automatic companion presentation', async () => {+ const { session, port } = await connect()try {- port.say({ t: 'hello', product: 'harness', mac: 'aa:bb', settings: companionSettings })- await vi.waitFor(() => expect(port.types()).toContain('companion.set'))- port.sent.length = 0- await session['syncCompanion']()- expect(port.sent).toHaveLength(0)- paired = 'gnu'- await session['syncCompanion']()- expect(port.sent).toEqual([{ t: 'companion.set', id: 'gnu' }])- session['companionAttempt']!.at -= 5_001- await session['syncCompanion']()- expect(port.sent.filter(m => m.t === 'companion.set')).toHaveLength(2)- port.say({ t: 'settings.state', settings: { ...companionSettings, companion: 'gnu' } })- await settle(); await session['syncCompanion']()- port.sent.length = 0- port.say({ t: 'hello', product: 'harness', mac: 'aa:bb', settings: companionSettings })- await vi.waitFor(() => expect(port.sent).toContainEqual({ t: 'companion.set', id: 'gnu' }))+ port.say({ t: 'hello', product: 'harness', mac: 'aa:bb', proto: 3, settings: companionSettings })+ await vi.waitFor(() => expect(port.types()).toContain('agents.end'))+ await session.focusAgent('a1')+ await settle()+ expect(port.types().filter(type => type.startsWith('companion.'))).toEqual([])+ expect(port.types()).not.toContain('settings.set')} finally { await session.stop() }})diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.tsindex f293352f1..de95fdd42 100644--- a/cli/src/cable/cableSession.ts+++ b/cli/src/cable/cableSession.ts@@ -1,4 +1,4 @@-import { readCompanionIdentity, sameCompanion, type CompanionIdentity, type CompanionMilestone } from './companionIdentity.js'+import { readCompanionIdentity, type CompanionIdentity } from './companionProtocol.js'// The message layer: what the daemon and the dial SAY to each other, on top of the bytes serial.ts moves.//// Written twice — here and in devices/harness-device/firmware/main/cable_client.c — with no shared code, because one half@@ -233,10 +233,6 @@ export interface RouteDecision {* and a network to prove that `hello` gets a `welcome`.*/export interface CableHost {- /** Account/guest paired species while the creature experiment is on; otherwise null. */- companion?(): string | null- companionIdentity?(): CompanionIdentity | null- companionMilestone?(): CompanionMilestone | null/** The computer at the other end of the cable — its identity, not "the" machine's. */localMachine(): { id: string; name: string }/** Every machine the owner has, local row included. Never rejects: `source` explains a short list. */@@ -497,8 +493,6 @@ export class CableSession {private greetedHw: string | undefined/** What the device last SAID its settings are. Never what this computer last asked for. */private greetedSettings: DeviceSettings | undefined- private companionEventSeen: string | null | undefined- private companionAttempt: { id: string | null; at: number } | undefinedprivate greetedFw: string | null = nullprivate lastRx = 0private stopped = false@@ -689,7 +683,6 @@ export class CableSession {// restarted greets the dial before its registry has finished loading, so the one thing it ever said// was "no agents". The dial removed both tiles and sat empty while the daemon knew about two.if (this.greetedMac !== null) {- await this.syncCompanion()// Machines FIRST. The dial paints its Overview eyebrow from the machine list, so an agent list that// lands first shows a nameless "Machine" for a frame.if (Date.now() - this.machinesAt >= MACHINES_POLL_MS) {@@ -789,8 +782,6 @@ export class CableSession {this.decoder.reset()this.greetedMac = nullthis.greetedFw = null- this.companionAttempt = undefined- this.companionEventSeen = undefinedthis.appFocusGeneration += 1this.drivingAppFocus = falsethis.expectedAppFocusEcho = ''@@ -966,7 +957,6 @@ export class CableSession {// a flash slot before it answers, so a cadence of retries would spend erase cycles on the user's// hardware every fifteen seconds, and nothing about the next greeting changes what went wrong.await this.maybeOfferFirmware(str('fw') ?? '')- await this.syncCompanion()return}case 'pong':@@ -1694,32 +1684,6 @@ export class CableSession {return sent}- /** A transient identity, independent of the device's saved skin and preferences. */- private async syncCompanion(): Promise<void> {- const settings = this.greetedSettings- if (!this.greetedMac || typeof settings?.followCompanion !== 'boolean') return- const requested = settings.followCompanion ? this.host.companion?.() : null- const id = requested && ['tim', 'gnu', 'lynx', 'mutt', 'yak', 'gopher', 'bug', 'tux', 'auk', 'beastie'].includes(requested)- ? requested : null- const identity = id ? this.host.companionIdentity?.() ?? null : null- const detailed = settings.companionProtocol === 2 && !!identity- const key = detailed ? JSON.stringify(identity) : id- const now = Date.now()- const same = settings.companion === id && (!detailed || sameCompanion(settings.companionDetails, identity))- if (same) this.companionAttempt = undefined- else if (this.companionAttempt?.id !== key || now - this.companionAttempt.at >= 5_000) {- this.companionAttempt = {id:key,at:now}- if (await this.send({t:'companion.set',id,...(detailed?{identity}: {})})) this.log(`cable: companion → ${id ?? 'saved skin'}${detailed?` (${identity!.name}, ${identity!.version})`:''}`)- }- const event = this.host.companionMilestone?.() ?? null- if (this.companionEventSeen === undefined) { this.companionEventSeen=event?.token ?? null; return }- if (event && event.token !== this.companionEventSeen) {- this.companionEventSeen=event.token- if (settings.companionProtocol===2 && settings.followCompanion && !settings.quiet && now>=event.at && now-event.at<=8_000)- await this.send({t:'companion.celebrate',kind:event.kind,token:event.token,identity:event.companion})- }- }-private async send(msg: Message): Promise<boolean> {if (!this.link?.isOpen) return falsetry {diff --git a/cli/src/cable/companionProtocol.spec.ts b/cli/src/cable/companionProtocol.spec.tsnew file mode 100644index 000000000..81302c2bd--- /dev/null+++ b/cli/src/cable/companionProtocol.spec.ts@@ -0,0 +1,28 @@+import { expect, it } from 'vitest'+import { COMPANION_SPECIES, readCompanionIdentity } from './companionProtocol.js'++const valid = { id: 'tim', uid: 'tim-1', seed: 1, name: 'Tim', version: '0.1', colour: -1, mark: 0 }++it.each(COMPANION_SPECIES)('retains valid existing %s wire identities without companion services', id => {+ expect(readCompanionIdentity({ ...valid, id, unrelated: 'ignored' })).toEqual({ ...valid, id })+})++it.each([null, undefined, false, 1, 'tim', [], {}])('refuses a malformed identity %j', value => {+ expect(readCompanionIdentity(value)).toBeNull()+})++it.each([+ ['id', 1], ['id', 'unknown'], ['uid', 1], ['uid', ''], ['uid', 'x'.repeat(65)], ['uid', '../outside'],+ ['name', 1], ['name', ''], ['name', 'x'.repeat(25)], ['name', 'Tim\n'],+ ['version', '9.0'], ['version', null], ['seed', 0.5], ['seed', -1], ['seed', 0x100000000],+ ['colour', 0.5], ['colour', -2], ['colour', 6], ['mark', 0.5], ['mark', -1], ['mark', 5],+] as const)('refuses invalid %s = %j', (field, value) => {+ expect(readCompanionIdentity({ ...valid, [field]: value })).toBeNull()+})++it('accepts the complete existing numeric and text boundary ranges', () => {+ for (const identity of [+ { ...valid, seed: 0, version: '1.0', colour: 0 },+ { ...valid, seed: 0xffffffff, version: '2.0', colour: 5, mark: 4, uid: 'x'.repeat(64), name: 'x'.repeat(24) },+ ]) expect(readCompanionIdentity(identity)).toEqual(identity)+})diff --git a/cli/src/cable/companionProtocol.ts b/cli/src/cable/companionProtocol.tsnew file mode 100644index 000000000..9b2c18f9b--- /dev/null+++ b/cli/src/cable/companionProtocol.ts@@ -0,0 +1,23 @@+/** Existing device wire data only. No collection state, rendering or background work. */+export const COMPANION_SPECIES = ['tim', 'gnu', 'lynx', 'mutt', 'yak', 'gopher', 'bug', 'tux', 'auk', 'beastie'] as const+export interface CompanionIdentity {+ id: string+ uid: string+ seed: number+ name: string+ version: '0.1' | '1.0' | '2.0'+ colour: number+ mark: number+}+export function readCompanionIdentity(value: unknown): CompanionIdentity | null {+ if (!value || typeof value !== 'object') return null+ const d = value as Record<string, unknown>+ if (typeof d.id !== 'string' || !COMPANION_SPECIES.includes(d.id as typeof COMPANION_SPECIES[number]) ||+ typeof d.uid !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(d.uid) ||+ typeof d.name !== 'string' || !/^[\x20-\x7e]{1,24}$/.test(d.name) ||+ !['0.1','1.0','2.0'].includes(d.version as string) ||+ !Number.isInteger(d.seed) || (d.seed as number)<0 || (d.seed as number)>0xffffffff ||+ !Number.isInteger(d.colour) || (d.colour as number)<-1 || (d.colour as number)>5 ||+ !Number.isInteger(d.mark) || (d.mark as number)<0 || (d.mark as number)>4) return null+ return {id:d.id,uid:d.uid,name:d.name,version:d.version as CompanionIdentity['version'],seed:d.seed as number,colour:d.colour as number,mark:d.mark as number}+}diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 38f91b71f..8e62ab0bd 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -1,6 +1,5 @@#!/usr/bin/env nodeimport './config/loadEnv.js'-import { CompanionZoo, readCompanionIdentity, type CompanionIdentity } from './cable/companionIdentity.js'import { MODEL_MANAGER_ID, ensureBundledCoreHarnesses } from './dsh/builtins.js'import { runDevicesCommand } from './devices/client.js'import { createDeviceStore, deviceStoreAgents } from './lib/autonomous-device/storeRuntime.js'@@ -68,9 +67,6 @@ import { flashCommand } from './lib/flash.js'import { readOrMintComputerId } from './lib/computerIdentity.js'import { awaitLoginCallback, extractCallbackParams, LOGIN_TIMEOUT_MESSAGE } from './lib/loginCallback.js'import { AUTH_DIR, AuthSessionError, AuthSessionManager, clearAuthSession, ensureSignInEpoch, knownSsoClientId, newSignInEpoch, readAuthSession, signInOf, ssoClientIdFor, writeAuthSession, type AuthSession } from './lib/authSession.js'-import { LocalPresence, PAIR_HARNESS_DSH, ZooTurnCounter, ZooTurnReporter } from './lib/zooTurns.js'-import { ZooLessonReporter } from './lib/zooLessons.js'-import { DAEMONS_OFF, DAEMONS_OFF_DETAIL, DaemonsSwitch, localKillSwitch, zooPassthrough, type ZooRead } from './lib/daemonsSwitch.js'import { handOffToGrid } from './lib/gridHandoff.js'import { qrSignIn } from './lib/qrSignIn.js'import { pickSignInMethod, signInMethodFlag, signInProviderName, withSignInProvider, type SignInMethod, type SignInProvider } from './lib/signInMethodPicker.js'@@ -87,48 +83,9 @@ import { forgetGridModels, gridAnnotation, keystrokePrewarm, observeMachineList,import { gridAvailable, managedGridPath } from './lib/gridExec.js'import { ENGINE_CLI_COMMANDS, ENGINES, PROCESS_ENGINES, engineBin, enginePathOverride } from './lib/engineBin.js'import { isTerminalEngine, type AgentEngine } from './engines/types.js'-import { PairJournal } from './pair/journal.js'-import { PairSensor } from './pair/sensor.js'-import { PairBrain } from './pair/brain.js'-import { PairFleet, relayPairLinkOpener } from './pair/fleet.js'-import { PairTriage } from './pair/triage.js'-import { PairVoice, isRosterDaemon } from './pair/voice.js'-import { PairOwner, type OwnerSubject } from './pair/owner.js'-import { PairControl, StartedHarnesses } from './pair/control.js'-import { PairToken } from './pair/token.js'-import { pairCommand as pairControlCommand, pairRequest, pairVerb, type PairClientDeps } from './pair/client.js'-import { serveMcp } from './pair/mcp.js'import { DEFAULT_HARNESS_PERMISSION, freshHarnessEnvironment } from './lib/harnessDefaults.js'-import { PairHarness, type PairEngine } from './pair/pairHarness.js'-import { CompanionIntelligence } from './pair/intelligence.js'-import { CodingMemoryRuntime } from './memory/runtime.js'-import { OpenCodeMemoryBinding } from './memory/opencodeBinding.js'-import { MemoryExperimentSettings } from './memory/experiment.js'-import { MemoryControl } from './memory/control.js'-import { isOwnerProcess } from './memory/ownerProcess.js'-import { hasMemoryForegroundActivity, MemorySessionRoster } from './memory/hostSessions.js'-import { companionMemoryInference } from './memory/companion.js'-import { CompanionStartupProfile } from './pair/startupProfile.js'-import { ConversationReview } from './pair/learn/conversationReview.js'-import { individualName, pairedIndividual } from './pair/individuals.js'-import { PlateService } from './pair/plateService.js'-import { inProjects, PairConfigFile, pairConfigPath, ruleRunner, type PairConfig } from './pair/rules.js'-import { LessonSignals } from './pair/learn/signals.js'-import { LessonDistiller } from './pair/learn/distill.js'-import { LessonStore } from './pair/learn/store.js'-import { PairLearner, joinProposals } from './pair/learn/propose.js'-import { ShownLines } from './pair/shown.js'-import { PairGate, pairingFrom } from './pair/gate.js'-import { runtimeLessons } from './pair/learn/publish.js'-import { ApprovalNonces, lessonKeyVerdict, loopbackPeerPid, verifyPerson } from './pair/learn/approval.js'-import { LessonBorrower } from './pair/learn/borrow.js'-import { LessonCurator } from './pair/learn/curate.js'-import { LessonExporter } from './pair/learn/export.js'-import { LessonUsage } from './pair/learn/usage.js'import { probeEngines } from './lib/engineProbe.js'-import { ensureBuiltinPair } from './dsh/builtins.js'-import { DEFAULT_AUTONOMY, isAutonomy, type Autonomy } from './pair/floor.js'-import { createHash, randomUUID } from 'node:crypto'+import { randomUUID } from 'node:crypto'import { engineInstallRecipe } from './lib/engineInstall.js'import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell, dropPermissionFlagIfUnsupported, namedAgentArgs, permissionModeApproves, permissionModeFlags, refusePermissionFlagIfUnsupported, supportsFirstPrompt, supportsNamedAgent } from './lib/engineLaunch.js'import { workspaceMissing } from './lib/workspaceCheck.js'@@ -492,8 +449,6 @@ ${apiUsage}Browser end-to-end encryption:harness autonomous-device <command> pair/status/list/revoke an Autonomous deviceharness pair <code> pair a BROWSER (code shown on the machine page)- harness pair <verb> your paired daemon's control interface: status, list_harnesses,- read_harness, brief, mcp, … (harness pair status --help)harness pairings list paired clientsharness unpair <#|fp> unpair one browser (by list number or fingerprint)harness unpair --all unpair every browser@@ -1936,115 +1891,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {// NB: hooks are installed AFTER the hook server binds (below), with the port it actually got — the// server may fall back to a free port if env.PORT is taken, and the hooks must point at the real one.- // THE DAEMONS SWITCH (lib/daemonsSwitch.ts, daemons/README.md "Off switches"). Every daemon deploy ships- // dark: until the account's zoo answers 200 — or, signed out, a guest window says its person consented —- // nothing daemon-related runs here: no sensor or journal, no brain, no learning, no pair harness, no zoo- // reports, no timers, and one backend request, the probe. HARNESS_DAEMONS=0 in this environment or- // "daemons": false in pair.jsonc keeps all of it off whatever the server says. What it switches is bound- // further down (onDaemonsChanged, onZooRead), and it starts once all of that is wired.- let onDaemonsChanged: (on: boolean) => void = () => {}- let onZooRead: (read: ZooRead) => void = () => {}- // Provenance stays local to the exact response object; no account identifier is added to a wire body.- const memoryZooOwners = new WeakMap<ZooRead, string>()- const memoryOwnerBindings = new WeakMap<ZooRead, Promise<string | null>>()- const daemonsKilled = localKillSwitch({ file: pairConfigPath() })- const daemons = new DaemonsSwitch({- read: () => proxyBackend('GET', '/api/zoo'),- signedIn: () => readAuthSession() !== null,- killed: daemonsKilled,- onChange: (on) => onDaemonsChanged(on),- onRead: (read) => onZooRead(read),- })- /** The hook server's `/api/zoo` passthrough for windows: DAEMONS_OFF when killed here, else the backend's answer. */- const zooProxy = zooPassthrough({ proxy: (method, path, body) => proxyBackend(method, path, body), killed: daemonsKilled, observe: (read) => daemons.observe(read) })- // THE PAIR SENSOR (pair/sensor.ts, daemons/BRAIN.md). Every daemon runs one for its own harnesses:- // no model, just turns, questions and recaps, journaled for whichever computer you sit down at. Off- // until daemons are on and the account's zoo has a paired daemon — see onZooRead, bound once the backend- // proxy exists. `onPairToggled` is bound the same way, to things declared further down.- let onPairToggled: (on: boolean) => void = () => {}- /** The thinking half (pair/brain.ts), built once the relay pool exists. */- let pairBrain: PairBrain | null = null- /**- * What the person confirmed at a window (pair/gate.ts, daemons/BRAIN.md "Security"): the zoo's autonomy- * and pair.jsonc are requests; a level above `suggest`, and rules, take effect only after their yes.- */- const pairGate = new PairGate({ file: join(env.ADAPTER_DATA_DIR, 'pair', 'confirmed.json'), onEvent: (event) => pairBrain?.onGate(event) }, DEFAULT_AUTONOMY)- /** How much the daemon may do on its own right now (pair/floor.ts): the level the gate let through. */- const pairAutonomy = (): Autonomy => pairGate.autonomy()- /** HARNESSD_PAIR_TOKEN (pair/token.ts): rotated at every launch of the pair harness. */- const pairToken = new PairToken(join(env.ADAPTER_DATA_DIR, 'pair', 'token'))- /** `talk` / `daemon_talk`: the person's words to the pair harness — bound once it can be started. */- let pairTalk: (text: string, companionUid?: string) => Promise<Record<string, unknown>> = async () => ({ ok: false, error: 'UNSUPPORTED' })- /** A turn started or ended on the pair harness: it is in use (its idle pause waits). Bound with it. */- let pairHarnessActivity: (agentId: string) => void = () => {}- let companionPromptContext: (agentId: string) => string | null = () => null- let companionProfileChanged: () => void = () => {}- let openCodeMemoryBinding: OpenCodeMemoryBinding | null = null- // Local account opt-in, exposed in Settings → Experimental. The old env flag is a migration default.- const memoryExperiment = new MemoryExperimentSettings(join(env.ADAPTER_DATA_DIR, 'coding-memory-settings'), process.env.HARNESS_CODING_MEMORY === '1')- const guestMemoryProfile = createHash('sha256').update(JSON.stringify(['harness-memory-guest-v1', computerId()])).digest('hex')- const memoryProfile = (): string | null => {- const current = readAuthSession()- return current ? current.memoryOwner?.key ?? null : guestMemoryProfile- }- const codingMemoryPreview = () => memoryExperiment.enabled(memoryProfile())- let applyCodingMemorySetting: () => Promise<void> = async () => {}- let codingMemory: CodingMemoryRuntime | null = null- let memoryPause = Promise.resolve()- let refreshMemoryIdentity: () => Promise<void> = async () => {}- let isCollectionAgent: (agentId: string) => boolean = () => false- /** The person's pair.jsonc (pair/rules.ts): the model opt-in, learning's opt-ins, and the rules act-within-rules runs here. */- const pairConfig = new PairConfigFile(pairConfigPath())- /** pair.jsonc as the person confirmed it (pair/gate.ts): a new or changed file waits for their yes. */- const pairRulesConfig = (): PairConfig => pairGate.rules(pairConfig.load())- /** A question opened on this machine: answer it by rule if the dial and a rule say so. Bound with the owner. */- let pairRules: (agentId: string, requestId: string) => void = () => {}- /** The pair harness is the daemon's own: its turns are nobody's news (no notification, no count). */- const isPairHarnessSession = (sessionId: string): boolean => registry.bySession(sessionId)?.dsh === PAIR_HARNESS_DSH- const pairSensor = new PairSensor({- machineId: () => backendRef?.machineId ?? session?.machineId ?? computerId(),- journal: new PairJournal({ dir: join(env.ADAPTER_DATA_DIR, 'pair') }),- describe: (agentId) => {- const s = registry.resolve(agentId)- if (!s) return null- return {- name: projectDisplayName(s),- engine: s.engine,- excluded: isTerminalEngine(s.engine) ? 'terminal' : s.dsh === PAIR_HARNESS_DSH ? 'pair' : null,- cwd: s.cwd ?? null,- }- },- onEnabledChanged: (on) => onPairToggled(on),- })- // LEARNING (pair/learn, daemons/LEARNING.md): the lessons folder, and what this machine notices in its own- // harnesses' events while pairing is on. The learner that distills and proposes is bound with the brain.- const lessonStore = new LessonStore({ root: env.HARNESS_LESSONS_DIR, now: Date.now })- let pairLearner: PairLearner | null = null- // When each lesson was last read by a session (pair/learn/usage.ts): always on, it only reads events.- const lessonUsage = new LessonUsage({ store: lessonStore, now: Date.now })- const lessonSignals = new LessonSignals({- now: Date.now,- machine: () => terminalHintMachineName(),- file: join(env.ADAPTER_DATA_DIR, 'pair', 'learn', 'signals.json'),- home: homedir(),- onSignal: (signal) => pairLearner?.signal(signal),- })- /** The approved lesson skills a harness session in `workspace` loads (the Store runtime path). Never throws.- * None while daemons are off: a launch is exactly what it was before them. */- const lessonsFor = (workspace: string) => {- if (!daemons.on()) return null- try { return runtimeLessons(lessonStore, workspace) } catch { return null }- }const syncSession = createSessionSync({terminalAvailable: (agentId) => registry.terminalAvailable(agentId),project: (s) => projectFrame(s, runtimeProfiles.selectedModel(s)),send: (frame) => backendRef?.send(frame),sendCommander: (frame) => backendRef?.sendCommander(frame),- onUnavailable: (agentId) => {- pairSensor.removed(agentId)- lessonSignals.forget(agentId)- },- onFailed: (agentId, detail) => pairSensor.failed(agentId, detail),warn: (err) => console.error('[cli] announceSession failed:', err instanceof Error ? err.message : err),})const announceRename = (s: RegisteredSession, opts: { device?: boolean } = {}): void => {@@ -2203,10 +2054,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {let appFormWindow: { machineId: string; connId: string } | undefinedlet appVoiceFocus: { machineId: string; agentId: string; connId: string } | undefinedlet backendRef: BackendSocket | undefined- let fullReconcile: (announceDevice?: boolean) => Promise<void> = async () => {}/** Assigned below, once the grid reconcile exists. A backend (re)connect is the signal that the* control plane is reachable again, which is precisely what an earlier attempt may have lacked. */- let onBackendConnected: () => void = () => {}+ let fullReconcile: (announceDevice?: boolean) => Promise<void> = async () => {}const auth = new AuthSessionManager(backendHttpBase())// The account's machine id when this computer is signed in; its own durable computer id when it is@@ -2232,7 +2082,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {void fullReconcile(true).catch((err) => {console.error('[runtime-profile] connect reconcile failed:', err instanceof Error ? err.message : err)})- onBackendConnected()}, computerId(), autonomousEnv)backendRef = backendbackend.viewerTargetProvider = (agentId) => dshViewers.forwardingUrl(agentId)@@ -2284,9 +2133,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Offline, for every list read: is there a `grid` here holding a sign-in? What decides whether the// picker offers local and shared models or a Set up row.backend.gridSetUp = () => gridAvailable() && signedInGridEmail() !== null- // Re-read the zoo on every reconnect as well, while daemons are on: a `zoo_changed` sent while the link- // was down is lost. Off, a reconnect asks nothing (lib/daemonsSwitch.ts).- onBackendConnected = () => { daemons.connected() }/*** Is ANY device surface watching this machine?@@ -2327,9 +2173,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {const deviceIsWatching = (): boolean => backend.hasCommander() || cableWatchingLocal() || backend.autonomousDeviceConnected()/** Anyone who can DRAW a question: a device, a cabled dial, or a desktop window on this computer. */- // ...or the pair brain, while pairing is on: it watches every harness on every machine, so a question- // on a computer nobody is sitting at must still be read for the computer somebody is.- const someoneCanAnswer = (): boolean => deviceIsWatching() || backend.hasLocalClient() || pairSensor.enabled()+ const someoneCanAnswer = (): boolean => deviceIsWatching() || backend.hasLocalClient()const terminalStreams = new TerminalStreamManager({terminals,resolveAgent: (agentId) => registry.resolve(agentId),@@ -2952,8 +2796,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {// before its answer arrived — as `question_response_result`.return questions.answer(payload)}- /** The transcript's open tool calls for a session (CommanderMirror.openTools), bound once the mirror exists. */- let openToolsOf: (sessionId: string) => Array<{ name: string; input: unknown }> = () => []// What is still being asked, by session — handed to a window that connects later (openQuestions below).const openQuestions = new Map<string, Record<string, unknown>>()backend.monitorActivityProvider = sessionId => openQuestions.has(sessionId)@@ -2987,10 +2829,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {// today: a remote machine's watcher is gated on ITS OWN audience, which a window attached over// here is not part of either way.backend.sendLocal(asked)- // With the WHOLE dialog: the pair's floor reads every line of the command, not the clipped title —- // and the transcript's open tool calls, so it reads the exact command rather than its wrapped paint.- pairSensor.question(agentIdFor(sessionId), requestId, shaped, detail ? { ...detail, tools: openToolsOf(sessionId) } : detail)- pairRules(agentIdFor(sessionId), requestId)openQuestions.set(sessionId, asked)console.log(`[question] ${sid(sessionId)} asking the user · "${preview(shaped[0]?.q ?? '')}" · req=${requestId}`)},@@ -3011,7 +2849,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {// one already answered. This is the mechanism behind "answer anywhere": the dial is cabled to// this very computer, so the dial and this window are always the same machine's audience.backend.sendLocal(closed)- pairSensor.questionGone(agentIdFor(sessionId), requestId)openQuestions.delete(sessionId)console.log(`[question] ${sid(sessionId)} answered elsewhere · closing on every client · req=${requestId}`)},@@ -3073,8 +2910,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {agentIdFor: (sessionId) => registry.bySession(sessionId)?.agentId,// An Orchestrator specialist's turn end, or the Director's while specialists are still out, is not// announced: the person asked to hear from the main agent once, not from every sub-agent.- // The pair harness's turns are silent on the dial too, like a sub-agent's.- isSubagent: (sessionId: string) => isSubagentSession(sessionId) || isPairHarnessSession(sessionId),+ isSubagent: (sessionId: string) => isSubagentSession(sessionId),// A claude sub-agent still at work is one whose transcript is still growing:// `<session>/subagents/agent-<id>.jsonl` beside the parent's (the same file enrichSubagentStats// reads). Written in the last SUBAGENT_IDLE_MS = alive; the held turn end waits for it.@@ -3108,11 +2944,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {},dataDir: env.ADAPTER_DATA_DIR,recapForce: env.RECAP_FORCE,- // Pairing needs a recap per turn for the brief, device or not (SUMMARY_MODE=local makes it free).- alwaysGenerate: () => env.RECAP_WITHOUT_DEVICE || pairSensor.enabled(),- onSummary: (sessionId, summary) => pairSensor.recap(registry.bySession(sessionId)?.agentId ?? sessionId, summary.recap),+ alwaysGenerate: () => env.RECAP_WITHOUT_DEVICE,})- openToolsOf = (sessionId) => mirror.openTools(sessionId)// Recaps are STORED under the engine session id — that is what lets `--resume` bring the last recap// back under a brand-new agent — but they are ASKED FOR by agent id, which is the only id the device// and the voice router know. Resolve across the two, or every tile restores empty.@@ -3251,7 +3084,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {runtimeProfiles.onChanged = (sessionId) => {const session = registry.resolve(sessionId)if (session) syncSession(session)- companionProfileChanged()}// A timer is an opportunity to inspect work, not proof that work is happening.@@ -3285,43 +3117,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {heartbeats.set(sessionId, timer)}- // Turns that count toward the zoo's eggs and the paired daemon's bond (lib/zooTurns.ts): a turn a- // person started, seen live, in a session that is not a sub-agent, a terminal or the pair harness.- // Reported once a minute as `zoo.turn` through the same signed-in path as /api/zoo; a guest's turns- // are the desktop client's to count, so nothing is counted while signed out. Each carries its minutes- // and whether it finished while the person was away from this computer (no active local window or- // `hn` for 30 minutes: zooPresence, fed below beside the pair brain), which is what earns night eggs.- const zooPresence = new LocalPresence()- const zooTurnCounter = new ZooTurnCounter({- eligible: (sessionId) => {- const session = registry.bySession(sessionId)- return !!session && !isTerminalEngine(session.engine) && session.dsh !== PAIR_HARNESS_DSH && !isSubagentSession(sessionId)- },- away: () => zooPresence.away(),- })- // Both only while daemons are on; a 404 on their POST is a server with daemons off, which the switch learns.- const postZooOps = async (body: unknown): Promise<ZooRead> => {- const answer = await proxyBackend('POST', '/api/zoo/ops', body)- daemons.observe(answer)- return answer- }- const zooTurnReporter = new ZooTurnReporter({- post: (body) => postZooOps(body),- signedIn: () => readAuthSession() !== null,- enabled: () => daemons.on(),- machineId: () => backend.machineId,- })- // Bond for a lesson the person approved (lib/zooLessons.ts, the learner's `credit`): `zoo.lesson` through the- // same signed-in path. A guest's approval is only journaled (`learned`).- const zooLessonReporter = new ZooLessonReporter({- post: (body) => postZooOps(body),- signedIn: () => readAuthSession() !== null,- enabled: () => daemons.on(),- })-emitSessionEvents = (sessionId: string, events: ReturnType<CursorNormalizer['ingest']>, opts?: { resumed?: boolean; replay?: boolean }): void => {if (!events.length || !registry.bySession(sessionId)?.active) return- if (hasMemoryForegroundActivity(events, opts) && !isSubagentSession(sessionId)) codingMemory?.activity()const usageSession = registry.bySession(sessionId)if (usageSession?.engine === 'opencode') agentTokenUsage.changed(usageSession)for (const [eventIndex, event] of events.entries()) {@@ -3347,20 +3144,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {// it always did.if (event.type === 'turn_ended') {if (opts?.resumed || opts?.replay) frame.replay = true- // The pair harness is the daemon talking to you, not work finishing: no app notifies on it.- if (isSubagentSession(sessionId) || isPairHarnessSession(sessionId)) frame.subagent = true+ if (isSubagentSession(sessionId)) frame.subagent = true}- if (event.type === 'turn_started' || event.type === 'turn_ended') pairHarnessActivity(agentId)backend.send(frame)if (event.type === 'turn_started' || event.type === 'turn_ended') sessionSearch?.touch(sessionId)- // The pair sensor reads the same two flags the apps do: a replay is a baseline, a sub-agent is nobody's news.- if (event.type === 'turn_started') {- pairSensor.turnStarted(agentId, { replay: !!(opts?.resumed || opts?.replay), subagent: isSubagentSession(sessionId) })- } else if (event.type === 'turn_ended') {- pairSensor.turnEnded(agentId, { replay: frame.replay === true, subagent: frame.subagent === true, aborted: event.payload.aborted === true })- }if (event.type === 'turn_started') {- if (daemons.on()) zooTurnCounter.started(sessionId, { replay: !!(opts?.resumed || opts?.replay) })turnStartedAt.set(sessionId, Date.now())console.log(`[turn] ${sid(sessionId)} started · engine=${registry.bySession(sessionId)?.engine ?? 'claude'} · bytes=${Buffer.byteLength(event.payload.userMessage, 'utf8')}`)input.onTurnStarted(agentIdFor(sessionId), event.payload.userMessage)@@ -3374,8 +3162,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {// and marking it pre-turn is how a restarted daemon never announced a question Codex had open.if (!opts?.resumed) questionWatcher.noteTurnStart(sessionId)} else if (event.type === 'turn_ended') {- const counted = zooTurnCounter.ended(sessionId, { replay: !!(opts?.resumed || opts?.replay), aborted: event.payload.aborted === true })- if (counted) zooTurnReporter.count(counted)const startedAt = turnStartedAt.get(sessionId)turnStartedAt.delete(sessionId)// Say when a turn was KILLED. The log previously showed an interrupt as a fresh `[turn] started@@ -3400,22 +3186,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// to the device and self-cancels once mirror.heartbeat() reports idle (summary done).}}- // Real work and the person's collection conversation can teach lessons. Archived- // pair chats, sub-agents and replay stay excluded. Tool-free background reviews- // never register as agents, so they cannot feed their own results back in here.- const learnFrom = registry.bySession(sessionId)- if (!codingMemoryPreview() && learnFrom && pairSensor.enabled() && !isTerminalEngine(learnFrom.engine) && !isSubagentSession(sessionId) &&- (!isPairHarnessSession(sessionId) || isCollectionAgent(learnFrom.agentId))) {- lessonSignals.ingest({ agentId: learnFrom.agentId, sessionId, engine: learnFrom.engine, cwd: learnFrom.cwd ?? null }, events,- { replay: !!(opts?.resumed || opts?.replay) })- }- // A session reading a lesson is its use (the curator's clock), pairing or not — daemons on — never a- // replay or a terminal.- if (learnFrom && daemons.on() && !isTerminalEngine(learnFrom.engine)) {- lessonUsage.ingest({ cwd: learnFrom.cwd ?? null }, events, { replay: !!(opts?.resumed || opts?.replay) })- }mirror.ingest(events, sessionId, { replay: !!(opts?.resumed || opts?.replay) })- if (codingMemoryPreview() && daemons.on() && !opts?.resumed && !opts?.replay) void codingMemory?.tick()// Subscribed devices only (lib/autonomous-device/stream.ts). A transcript re-read is history, not live.if (!opts?.replay) autonomousDeviceService?.stream(agentIdFor(sessionId), events)}@@ -3466,7 +3237,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {syncRecapPool()turnStates.delete(sessionId)turnStartedAt.delete(sessionId)- zooTurnCounter.forget(sessionId)codexNormalizers.delete(sessionId)cursorNormalizers.delete(sessionId)opencodeReaders.get(sessionId)?.stop()@@ -4013,95 +3783,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {}const json = await res.json().catch(() => ({})) as Record<string, unknown>const result = { status: res.status, body: json }- if (latest?.accessToken === accessToken && latest.memoryOwner) memoryZooOwners.set(result, latest.memoryOwner.key)- if (method === 'GET' && path === '/api/auth/me' && res.status === 200 && json?.success === true) {- const userId = (json.data as { user?: { id?: unknown } } | undefined)?.user?.id- if (typeof userId === 'string') {- const binding = auth.bindMemoryOwner(userId, accessToken, latest?.autonomousEnv ?? env.AUTONOMOUS_ENV).catch(() => null)- memoryOwnerBindings.set(result, binding)- }- }return result}- // PAIRING IS ON only while daemons are on (lib/daemonsSwitch.ts) and the account's zoo has a paired daemon- // (daemons/README.md, "The zoo"). The zoo is account state, read through the same proxy the window uses —- // the switch's probe is that read — and re-read on `zoo_changed` and on every reconnect. Signed out there- // is no account zoo: a guest's window keeps its own and says which daemon is paired in `daemon_presence`- // (pair/brain.ts), which is what `guestPair` holds. A backend that cannot be reached keeps the last answer- // rather than switching pairing off on a blip.- // `pair` is the paired individual's SPECIES (its voice and lore; the zoo names the individual by uid) and- // `name` what the person calls it, `pip the tim` (pair/individuals.ts).- // INDIVIDUAL ART (pair/plateService.ts): each individual's plates, drawn here in a worker thread with the- // generated models, kept under the data folder, served to windows (`daemon_plate_get`, Unix socket) and- // phones (`pair_plate_get`, sealed). Idle, and nothing on disk touched, while daemons are off.- const plates = new PlateService({ dir: join(env.ADAPTER_DATA_DIR, 'pair', 'plates') })- const companionZoo = new CompanionZoo()- let zooPair: { known: boolean; pair: string | null; name: string | null; autonomy: Autonomy; consent: boolean; consentAt: string | null } = { known: false, pair: null, name: null, autonomy: DEFAULT_AUTONOMY, consent: false, consentAt: null }- let zooMemoryOwner: string | null = null- let guestPair: string | null = null- let guestCompanion: CompanionIdentity | null = null- let guestAutonomy: Autonomy | null = null- let guestConsent = false- let refreshPairPackage: () => void = () => {}- // The autonomy dial rides with the pair: the account's zoo, or a guest window's own (daemon_presence).- // Nothing is watched until the person said yes on the first-day consent screen (zoo `consent.watching`,- // or a guest window's `consent`): until then the sensor stays off and the dial stays at watch.- const applyPair = (): void => {- // Daemons off: nothing is paired, and the dial is left as it was (nothing reads it).- if (!daemons.on()) { pairSensor.setPair(null); return }- const pairing = pairingFrom(zooPair, { pair: guestPair, autonomy: guestAutonomy, consent: guestConsent }, DEFAULT_AUTONOMY)- // A request: a step above `suggest` waits for the person's yes at a window (pair/gate.ts), and a yes- // holds only under the consent (`epoch`) it was given in.- pairGate.setRequested(pairing.autonomy, { keepConfirmed: !pairing.consented, epoch: pairing.epoch })- // A guest window names only a species; the account's zoo names the individual too.- pairSensor.setPair(pairing.pair, zooPair.known && pairing.pair === zooPair.pair ? zooPair.name : null)- refreshPairPackage()- // Pairing on or off already refreshed the brain (onPairToggled); another daemon paired, or the dial moved,- // reaches the windows attached here now. The brain sends only what they were not already sent.- pairBrain?.refresh()- }- onZooRead = (result) => {- if (result.status === 200) {- zooMemoryOwner = memoryZooOwners.get(result) ?? null- const zoo = (result.body.data as { zoo?: { autonomy?: unknown; consent?: { watching?: unknown; at?: unknown } | null } } | undefined)?.zoo- companionZoo.observe(zoo, Date.now(), (result.body.data as { revision?: number } | undefined)?.revision)- // The zoo holds individuals and `paired` names one by uid; the brain speaks as its species.- const paired = pairedIndividual(zoo)- const pair = paired && isRosterDaemon(paired.id) ? paired : null- const at = zoo?.consent?.at- zooPair = {- known: true, pair: pair?.id ?? null, name: pair ? individualName(pair) : null,- autonomy: isAutonomy(zoo?.autonomy) ? zoo.autonomy : DEFAULT_AUTONOMY,- consent: zoo?.consent?.watching === true, consentAt: typeof at === 'string' && at.length <= 64 ? at : null,- }- // A uid not seen before is a hatch: its art is drawn now, before a window asks (idle while daemons are off).- plates.observeZoo(zoo)- } else if (result.status === 401) {- zooMemoryOwner = null- companionZoo.reset()- zooPair = { known: false, pair: null, name: null, autonomy: DEFAULT_AUTONOMY, consent: false, consentAt: null }- }- applyPair()- void refreshMemoryIdentity()- void codingMemory?.tick()- }- // Only a server with the zoo on sends it: the switch asks at once, whatever it had cached.- backend.onZooChanged = () => daemons.zooChanged()- backend.pairService = pairSensor- // The phone's sealed `pair_plate_get` (a window's `daemon_plate_get` is bound with the local socket).- backend.plateService = { get: (payload) => plates.get(payload) as Promise<Record<string, unknown>> }- // `harness pair` and the MCP server: DAEMONS_OFF while off, before any verb runs.- backend.daemonsOn = () => daemons.on()- // An open question the watcher already announced before pairing came on is announced again, so the- // sensor hears it too (clients dedupe a repeated push by requestId).- onPairToggled = (on) => {- if (on) questionWatcher.reset()- pairBrain?.refresh()- void refreshMemoryIdentity()- void codingMemory?.tick()- }-// Built HERE rather than beside the cable stack that also uses it (further down), because the hook// server starts long before that point and agent restore can sit between the two. A cache bound late// is a cache that is still null exactly when a cold boot during an outage needs it most.@@ -4209,25 +3893,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {const { server: hookServer, port: hookPort, localSocket } = await startHookServer(daemonPort(), {- onPromptContext: async (agentId, prompt) => {- const persona = companionPromptContext(agentId)- const recalled = await codingMemory?.preparePromptRecall(agentId, { query: prompt })- return { additionalContext: [persona, recalled?.packet.text].filter(Boolean).join('\n\n'),- ...(recalled?.receipt ? { memoryReceiptId: recalled.receipt.id } : {}) }- },- onMemoryContextEmitted: async (agentId, receiptId) => await codingMemory?.promptRecallEmitted(agentId, receiptId) ?? false,- onMemoryContext: async (agentId, prompt, adapter) => {- const recalled = await codingMemory?.preparePromptRecall(agentId, { query: prompt }, adapter)- return recalled?.packet.text ? { additionalContext: recalled.packet.text,- ...(recalled.receipt ? { memoryReceiptId: recalled.receipt.id } : {}) } : null- },- onOpenCodeMemoryRuntime: (agent, input) => {- if (!agent.processIdentity) return { observe: false }- const result = openCodeMemoryBinding?.receive({ agentId: agent.agentId, sessionId: agent.sessionId,- processKey: processIdentityKey('opencode', agent.processIdentity) }, input) ?? { observe: false }- if (result.observe) codingMemory?.activity()- return result- },onCommandBar: commandBarService,onAutonomousDeviceRequest: async (method, target, body) => {if (!autonomousDeviceService) return { status: 503, body: { error: { code: 'UNAVAILABLE', message: 'Autonomous device service is starting' } } }@@ -4564,8 +4229,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {// logout restarts the daemon, and the window between the file changing and the restart landing// is exactly when the app asks — the answer it needs is the file's.signedIn: readAuthSession() !== null,- // Whether this daemon runs its daemons (lib/daemonsSwitch.ts): the server's answer and the kill switch.- daemons: (({ on, server, killed }) => ({ on, server, killed: killed !== null }))(daemons.state()),version: VERSION,localWs: {path: LOCAL_WS_PATH,@@ -4608,7 +4271,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {...(tmuxBackend ? [{ backend: 'tmux', instance: 'default', state: 'configured' }] : []),],dormantAgents: registry.list().filter((session) => !session.active).length,- ...(codingMemoryPreview() ? { codingMemory: codingMemory?.status() ?? { state: 'off' } } : {}),dataDir: tildify(env.ADAPTER_DATA_DIR),port: daemonPort(),},@@ -4647,13 +4309,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {onDeskOps: (body) => proxyBackend('POST', '/api/desk/ops', body),onExperimentalRead: () => proxyBackend('GET', '/api/experimental-settings'),onExperimentalWrite: (body) => proxyBackend('PATCH', '/api/experimental-settings', body),- // The account's zoo — see backend routes/zoo.ts. Same shape as the desk: read and ops proxied,- // everyone else's changes heard as `zoo_changed`. The backend requires the account's creature- // opt-in. Signed out, proxyBackend answers 401 NOT_SIGNED_IN.- // Killed on this computer (lib/daemonsSwitch.ts): a 404 DAEMONS_OFF without asking, which a window reads- // exactly as the server's own 404 — daemons hidden. Otherwise verbatim, and the switch learns from it.- onZooRead: () => zooProxy.read(),- onZooOps: (body) => zooProxy.ops(body),onStore: (method, path, body) => proxyBackend(method, path, body),}, { socketPath: localSocketPath(env.ADAPTER_DATA_DIR, env.PORT), allowPortFallback: true })try { saveDaemonPort(env.ADAPTER_DATA_DIR, env.PORT, hookPort) } catch (error) {@@ -4808,479 +4463,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {void ensureSignInEpoch().catch(() => null).then(() => devLogSyncer?.register())setInterval(() => { void devLogSyncer?.refresh() }, 10 * 60_000).unref()}- // THE PAIR BRAIN (pair/brain.ts, daemons/BRAIN.md): thinks only while a window or `hn` is attached to- // THIS daemon — the computer you are at. Other linked machines are read over background relay sessions- // (never the window's own) with sealed `pair_*`. Everything it says goes out through sendLocal.- const pairFleet = new PairFleet({- local: {- machineId: () => backend.machineId,- name: () => terminalHintMachineName(),- snapshot: () => pairSensor.snapshot(),- subscribe: (listener) => pairSensor.subscribe(listener),- journal: (payload) => pairSensor.journal(payload),- },- machines: () => machineListCache.list().machines- .filter((m) => !m.local)- .map((m) => ({ machineId: m.machineId, name: m.name, linked: relayPeers.get(m.machineId) !== null, online: m.state !== 'offline' })),- open: relayPairLinkOpener({- acquire: (machineId, sink, onClosed) => relayPool.acquireIsolated(machineId, readAuthSession()?.autonomousEnv ?? env.AUTONOMOUS_ENV,- { type: 'machine_select', payload: { machineId } }, sink, onClosed),- newId: () => randomUUID(),- }),- onChange: (change) => pairBrain?.onFleetChange(change),- })- // THE OWNING MACHINE'S HALF of every pair write (pair/owner.ts): a key pressed here, the pair harness's- // tool call, a rule, or another machine's brain over sealed pair_* — all go through the same floor, and- // every action is journaled. `agent_delete` is Stop/Pause (the conversation is kept); nothing here can- // delete, restart, fork or bypass.- const pairSubject = (s: RegisteredSession, status: OwnerSubject['status']): OwnerSubject => ({- agentId: s.agentId, name: projectDisplayName(s), engine: s.engine, status,- untouchable: isTerminalEngine(s.engine) ? 'terminal' : s.dsh === PAIR_HARNESS_DSH ? 'pair' : null,- cwd: s.cwd ?? null, dsh: s.dsh ?? null,- })- const pairOwner = new PairOwner({- sensor: pairSensor,- autonomy: () => pairAutonomy(),- subject: (agentId) => {- const live = registry.resolve(agentId)- if (live && registry.terminalAvailable(live.agentId)) return pairSubject(live, 'live')- const stopped = stoppedAgents.get(agentId)- return stopped ? pairSubject(stopped, 'stopped') : null- },- subjects: () => {- const live = registry.advertised()- return [...live.map((s) => pairSubject(s, 'live')), ...stoppedAgents.available(live).map((s) => pairSubject(s, 'stopped'))]- },- recent: (agentId) => ({- recaps: (backend.recentProvider?.(agentId, 3) ?? []).map((r) => r?.recap || r?.text || '').filter(Boolean),- asks: backend.recentAsksProvider?.(agentId, 3) ?? [],- }),- // Keyed by the question's own text; AskQuestionController checks the dialog on screen is still- // `requestId` before a single key goes in, and answers STALE_QUESTION otherwise.- keyAnswer: ({ agentId, requestId, question, option }) => questions.answer({ agentId, requestId, answers: { [question || 'answer']: option } })- .then((result) => result.ok ? { ok: true as const } : { ok: false as const, error: result.error, detail: result.detail }),- message: (agentId, text, deliveryId) => {- if (!backend.onMessage) throw new Error('message handler not wired')- // The daemon's own words are never the person correcting an agent (pair/learn/signals.ts).- lessonSignals.daemonSent(agentId, text)- backend.onMessage(agentId, text, deliveryId)- },- cancel: (agentId) => backend.onCancel?.(agentId),- // Mode `ask`, bypass off, always: the daemon never starts anything that approves itself.- create: async ({ engine, cwd, prompt, name }) => {- if (!backend.onCreateAgent) return { ok: false, error: 'UNSUPPORTED' }- if (!ENGINES.includes(engine as AgentEngine)) return { ok: false, error: 'INVALID_ENGINE' }- const created = await backend.onCreateAgent({- engine: engine as AgentEngine, cwd, bypassPermission: false, permissionMode: 'ask',- grid: null, codexHome: null, dsh: null, prompt, name, agent: null,- })- return created.ok ? { ok: true, agentId: created.session.agentId } : created- },- stop: async (agentId) => {- if (!backend.onDeleteAgent) throw Object.assign(new Error('stop is not wired'), { code: 'UNSUPPORTED' })- await backend.onDeleteAgent(agentId)- },- resume: async (agentId) => {- if (!backend.onResumeAgent) return { ok: false, error: 'UNSUPPORTED' }- const resumed = await backend.onResumeAgent(agentId)- return resumed.ok ? { ok: true } : resumed- },- newId: () => randomUUID(),- })- backend.pairOwner = pairOwner- // AUTONOMY act-within-rules (pair/rules.ts): this machine's rules answer this machine's questions, through- // the same owner floor as a key — journaled by `rule`, reported afterwards by whichever brain is watching.- const runRules = ruleRunner({- active: () => pairSensor.enabled() && pairAutonomy() === 'act-within-rules',- config: () => pairRulesConfig(),- question: (agentId) => pairSensor.harness(agentId)?.question ?? null,- subject: (agentId) => {- const s = registry.resolve(agentId)- return s ? { name: projectDisplayName(s), engine: s.engine, cwd: s.cwd ?? null } : null- },- answer: (input, by, why) => pairOwner.answer(input, by, why),- log: (line) => console.log(line),- })- pairRules = (agentId, requestId) => { void runRules(agentId, requestId).catch(() => {}) }- // Which window was shown which line (pair/shown.ts): every pair frame that carries a keyed id goes out- // through these, so a key counts only from a window that received its line and said it drew it.- const pairShown = new ShownLines(Date.now)- const pairSendLocal = pairShown.sender((frame) => backend.sendLocal(frame), () => backend.localClientIds())- const pairSendLocalTo = pairShown.senderTo((connId, frame) => backend.sendLocalTo(connId, frame))- const pairVoice = new PairVoice({ sendLocal: pairSendLocal, now: Date.now })- // THE CONTROL INTERFACE (pair/control.ts): the pair harness's tools, behind the loopback `pair` request —- // `harness pair <verb>` and the harnessd MCP server. Writes need the pair harness's token and pass the- // autonomy dial; then this machine's PairOwner, or another machine's over the fleet's sealed link.- // PERSON-ONLY lesson actions (pair/learn/approval.ts): the process asking, found by its loopback port, must- // not descend from a harness pane (or from this daemon); a verified caller gets a one-time nonce.- const lessonNonces = new ApprovalNonces(Date.now)- const verifyLessonCaller = (connId: string) => verifyPerson(connId, {- peerPort: (id) => localWsServer.peerPort(id),- localPort: () => hookPort,- peerPid: (peer, local) => loopbackPeerPid(peer, local),- processes: () => processRows(),- harnessPanePids: async () => { const inventory = await listTmuxPanes(); return inventory.ok ? inventory.panes.map((pane) => pane.rootPid) : null },- })- const memoryControl = new MemoryControl({ runtime: () => codingMemoryPreview() ? codingMemory : null,- experiment: { owner: memoryProfile, read: owner => memoryExperiment.read(owner), write: async (owner, enabled, expected) => {- const choice = memoryExperiment.write(owner, enabled, expected)- await applyCodingMemorySetting()- return choice- } }, verify: async connId => {- const verdict = await verifyLessonCaller(connId)- if (!verdict.ok) return verdict- if (!await isOwnerProcess(verdict.pid)) return { ok: false, error: 'UNVERIFIED', detail: 'The memory library requires a verified process belonging to this computer’s owner.' }- return verdict- } })- const pairControl = new PairControl({- owner: pairOwner,- fleet: pairFleet,- local: {- machineId: () => backend.machineId,- name: () => terminalHintMachineName(),- journal: (payload) => pairSensor.journal(payload),- harnesses: () => pairSensor.snapshot().harnesses,- },- pairing: { enabled: () => pairSensor.enabled(), pairedDaemon: () => pairSensor.pairedDaemon(),- pairedUid: () => zooPair.known ? companionZoo.identity?.uid ?? null : guestCompanion?.uid ?? null },- autonomy: () => pairAutonomy(),- tokenMatches: (candidate) => pairToken.matches(candidate),- voice: pairVoice,- present: () => !!pairBrain?.isActive && pairBrain.present(),- started: new StartedHarnesses(join(env.ADAPTER_DATA_DIR, 'pair', 'started.json')),- changed: () => pairBrain?.stateChanged(),- lessons: async (payload) => pairLearner ? pairLearner.local(payload) : { ok: false, error: 'UNSUPPORTED' },- lessonReview: async (connId, id) => pairBrain?.reviewLesson(connId, id) ?? { ok: false, error: 'UNSUPPORTED' },- memory: (payload, connId) => memoryControl.local(payload, connId),- recallMemory: async payload => {- const agentId = pairHarness.agentId()- if (!codingMemory || !agentId) return { ok: false, error: 'UNSUPPORTED' }- return codingMemory.recallCollection(agentId, payload)- },- person: { verify: verifyLessonCaller, nonces: lessonNonces },- now: Date.now,- newId: () => randomUUID(),- })- backend.pairControl = pairControl- // THE PAIR HARNESS (pair/pairHarness.ts): the daemon as a conversation, started or resumed when you talk- // to it, stopped when idle unless coding memory still uses it. Automatic approvals, scoped harnessd- // MCP, a fresh token every launch.- const pairHarness = new PairHarness({- pairedDaemon: () => pairSensor.pairedDaemon(),- pairedName: () => pairSensor.pairedName(),- pairedUid: () => zooPair.known ? companionZoo.identity?.uid ?? null : guestCompanion?.uid ?? null,- collectionUids: () => zooPair.known ? companionZoo.uids : guestCompanion ? [guestCompanion.uid] : [],- engine: async (preferred) => {- preferred ??= 'opencode' // New collections share the product default.- const found = await probeEngines([preferred]).catch(() => [])- return found.some(e => e.engine === preferred && e.installed) ? preferred : null- },- // The launcher when this daemon is the installed release it runs; otherwise exactly this process.- mcpCommand: () => {- const launcher = join(env.HARNESS_BIN_DIR, 'harness')- const script = process.argv[1] ? resolve(process.argv[1]) : ''- return script === join(env.ADAPTER_CLI_DIR, 'cli.js') && existsSync(launcher) ? [launcher] : [process.execPath, ...process.execArgv, script]- },- token: pairToken,- workspace: join(env.ADAPTER_DATA_DIR, 'pair', 'workspace'),- stateFile: join(env.ADAPTER_DATA_DIR, 'pair', 'harness.json'),- install: (files) => ensureBuiltinPair(PAIR_HARNESS_DSH, files),- find: () => {- const live = registry.advertised()- return [- ...live.filter((s) => s.dsh === PAIR_HARNESS_DSH).map((s) => ({ agentId: s.agentId, status: 'live' as const, engine: s.engine as PairEngine, cwd: s.cwd, hasConversation: !!s.sessionId })),- ...stoppedAgents.available(live).filter((s) => s.dsh === PAIR_HARNESS_DSH).map((s) => ({ agentId: s.agentId, status: 'stopped' as const, engine: s.engine as PairEngine, cwd: s.cwd, hasConversation: !!s.sessionId })),- ]- },- create: async ({ engine, cwd, prompt, name }) => {- if (!backend.onCreateAgent) return { ok: false, error: 'UNSUPPORTED' }- const created = await backend.onCreateAgent({- engine, cwd, bypassPermission: true, permissionMode: DEFAULT_HARNESS_PERMISSION, grid: null, codexHome: null,- dsh: PAIR_HARNESS_DSH, prompt, name, agent: null,- })- return created.ok ? { ok: true, agentId: created.session.agentId } : created- },- resume: async (agentId) => {- if (!backend.onResumeAgent) return { ok: false, error: 'UNSUPPORTED' }- const resumed = await backend.onResumeAgent(agentId)- return resumed.ok ? { ok: true } : resumed- },- stop: async (agentId) => {- const current = registry.byAgent(agentId)- if (!current) return- if (!backend.closeAgentService) throw new Error('Safe close is unavailable.')- const result = await backend.closeAgentService.request({ agentId, sessionId: current.sessionId,- createdAt: new Date(current.registeredAt).toISOString(), mode: 'now' })- if (!result.closed) throw new Error(result.detail ?? 'Could not save and stop the companion.')- },- send: (agentId, text) => backend.onMessage?.(agentId, text, randomUUID()),- working: (agentId) => {- const sessionId = registry.resolve(agentId)?.sessionId- return !!sessionId && mirror.isBusy(sessionId)- },- backgroundInUse: (agentId): boolean => agentId === pairHarness.agentId() && !!codingMemory?.needsCompanion(),- now: Date.now,- })- pairTalk = (text, uid) => pairHarness.talk(text, uid)- refreshPairPackage = () => {- try { pairHarness.refreshPackage() }- catch (error) { console.warn('[core-harnesses] Could not refresh Companions:', error instanceof Error ? error.message : String(error)) }- }- refreshPairPackage()- isCollectionAgent = (agentId) => agentId === pairHarness.agentId()- companionPromptContext = (agentId) => daemons.on() ? pairHarness.context(agentId) : null- pairHarnessActivity = (agentId) => { if (daemons.on()) pairHarness.activity(agentId) }- const companionStartupProfile = new CompanionStartupProfile({- current: () => {- if (!daemons.on() || !pairSensor.pairedDaemon()) return null- const session = registry.advertised().find(s => s.agentId === pairHarness.agentId())- return session?.dsh === PAIR_HARNESS_DSH ? session : null- },- capture: (id) => captureTerminal(id, 60),- })- const companionIntelligence = new CompanionIntelligence({- enabled: () => daemons.on() && !!pairSensor.pairedDaemon(),- current: () => {- const agentId = pairHarness.agentId()- if (!agentId) return null- const live = registry.advertised().find(s => s.agentId === agentId)- const session = live ?? stoppedAgents.get(agentId)- if (!session || session.dsh !== PAIR_HARNESS_DSH) return null- const nativeProcessKey = live?.processIdentity ? processIdentityKey(session.engine, live.processIdentity) : null- return { agentId, sessionId: session.sessionId, engine: session.engine,- profile: runtimeProfiles.selectedModel(session), stopped: !live,- startup: live ? companionStartupProfile.selected(session) : null,- nativeProcessKey,- accountKey: session.engine === 'opencode' && nativeProcessKey ? openCodeMemoryBinding?.identity({- agentId, sessionId: session.sessionId, processKey: nativeProcessKey,- }) ?? null : undefined,- codexHome: session.codexHome, customProvider: !!(session.grid || session.gridLaunch || session.gateway) }- },- openCodeSnapshot: runtime => runtime.sessionId && runtime.nativeProcessKey ? openCodeMemoryBinding?.read({- agentId: runtime.agentId, sessionId: runtime.sessionId, processKey: runtime.nativeProcessKey,- }) ?? null : null,- directory: join(env.ADAPTER_DATA_DIR, 'pair', 'reasoning'),- stateFile: join(env.ADAPTER_DATA_DIR, 'pair', 'intelligence.json'),- })- openCodeMemoryBinding = new OpenCodeMemoryBinding({ current: () => {- const ownerKey = codingMemory?.ownerKey(), status = codingMemory?.status()- if (!daemons.on() || !codingMemoryPreview() || !ownerKey || status?.state !== 'ready' || !status.preferences?.learn) return null- const session = registry.advertised().find(s => s.agentId === pairHarness.agentId())- if (!session || !session.active || session.dsh !== PAIR_HARNESS_DSH || session.engine !== 'opencode'- || !session.sessionId || !session.processIdentity) return null- return { ownerKey, agentId: session.agentId, sessionId: session.sessionId,- processKey: processIdentityKey('opencode', session.processIdentity),- model: parseRuntimeProfile(runtimeProfiles.selectedModel(session))?.model ?? null }- } })- companionProfileChanged = () => { companionIntelligence.status(); pairBrain?.stateChanged() }- {- const roster = new MemorySessionRoster(homedir(), Date.now, { opencode: OPENCODE_DB })- codingMemory = new CodingMemoryRuntime({- directory: join(env.ADAPTER_DATA_DIR, 'coding-memory'),- context: () => {- const current = readAuthSession()- const profileId = current ? current.memoryOwner?.key ?? null : guestMemoryProfile- return { experimental: daemons.on() && codingMemoryPreview(), profileId,- watching: !!pairSensor.pairedDaemon() && (current- ? !!profileId && zooMemoryOwner === profileId && zooPair.consent : guestConsent) }- },- sessions: () => roster.refresh(registry.advertised(), id => mirror.isBusy(id), isSubagentSession, pairHarness.agentId()),- inference: companionMemoryInference(companionIntelligence, agentId => {- const session = registry.advertised().find(candidate => candidate.agentId === agentId)- return !!session?.sessionId && mirror.isBusy(session.sessionId)- }),- })- let refreshing: Promise<void> | null = null- let lastAttempt = -Infinity- refreshMemoryIdentity = () => {- const current = readAuthSession()- if (!daemons.on() || !current || (current.memoryOwner?.key && zooMemoryOwner === current.memoryOwner.key)) return Promise.resolve()- if (refreshing) return refreshing- if (Date.now() - lastAttempt < 30_000) return Promise.resolve()- lastAttempt = Date.now()- refreshing = (async () => {- if (!current.memoryOwner) {- const response = await proxyBackend('GET', '/api/auth/me')- await memoryOwnerBindings.get(response)- }- // Re-read watching consent under the newly bound owner. An old account's cached zoo cannot- // authorize capture for the new account, even if both accounts use the same companion avatar.- const latest = readAuthSession()- if (daemons.on() && latest?.memoryOwner && zooMemoryOwner !== latest.memoryOwner.key) daemons.zooChanged()- await codingMemory?.tick()- })().catch(() => {}).finally(() => { refreshing = null })- return refreshing- }- }- // The collection's DSH supplies learning and triage with its observed model. The- // experiment and watching consent still gate everything; there is no second model switch.- const lessonProjects = (): string[] =>- [...new Set([...registry.advertised(), ...stoppedAgents.available(registry.advertised())].map((s) => s.cwd).filter((cwd): cwd is string => !!cwd))]- const lessonDistiller = new LessonDistiller({ oneshot: companionIntelligence.run, modelEnabled: () => companionIntelligence.ready(), now: Date.now, home: homedir() })- const conversationReview = new ConversationReview({- directory: join(env.ADAPTER_DATA_DIR, 'pair', 'learn'),- scope: () => daemons.on() && pairSensor.pairedDaemon() ? pairHarness.learningScope() : null,- pairedDaemon: () => pairSensor.pairedDaemon(), intelligence: () => companionIntelligence.status(),- turns: (from, to) => sessionSearch?.recentConversations(from, to) ?? null,- cwd: (id) => registry.resolve(id)?.cwd ?? stoppedAgents.get(id)?.cwd ?? null,- machine: () => terminalHintMachineName(), distiller: lessonDistiller, store: lessonStore, now: Date.now,- home: homedir(), changed: () => pairBrain?.stateChanged(),- })- pairLearner = new PairLearner({- store: lessonStore,- distiller: lessonDistiller,- history: conversationReview,- intelligence: () => companionIntelligence.status(),- queueFile: () => {- const id = pairHarness.learningScope()- return id ? join(env.ADAPTER_DATA_DIR, 'pair', 'learn', `queue-${id}.json`) : null- },- pairedDaemon: () => pairSensor.pairedDaemon(),- autonomy: () => pairAutonomy(),- voice: pairVoice,- sendLocal: pairSendLocal,- present: () => !!pairBrain?.isActive && pairBrain.present(),- focused: (agentId) => pairBrain?.isFocused(backend.machineId, agentId) ?? false,- busy: () => pairSensor.snapshot().harnesses.some((h) => h.working),- projects: lessonProjects,- // Notes into AGENTS.md only for a project the person opted in; every other project's go to .harness/lessons.md.- agentsMd: (dir) => inProjects(dir, pairRulesConfig().learn.agentsMd),- learned: ({ daemon, lesson }) => { pairSensor.learned({ daemon, name: lesson.name, agentId: lesson.from[0]?.agentId, engine: lesson.from[0]?.engine }) },- // Bond for the daemon that found it: `zoo.lesson`, signed in only (a guest's is the journal entry above).- credit: (daemon, lesson) => { zooLessonReporter.credit(lesson.id, daemon) },- // L2 (daemons/LEARNING.md). Borrow: opt-in, read-only, from the engines' own stores.- borrowEnabled: () => pairRulesConfig().learn.borrow,- borrower: new LessonBorrower({- store: lessonStore,- sources: { hermesHome: env.HERMES_HOME, claudeProjectsDir: env.CLAUDE_PROJECTS_DIR, codexHome: env.CODEX_HOME },- projects: lessonProjects, machine: () => terminalHintMachineName(), now: Date.now, home: homedir(), log: (line) => console.log(line),- }),- // Check: usage, and the daily curator (stale at 30 days unused, archived at 90).- usage: lessonUsage,- curator: new LessonCurator({- store: lessonStore, usage: lessonUsage, now: Date.now,- busy: () => pairSensor.snapshot().harnesses.some((h) => h.working),- archived: (record) => { pairLearner?.withdrawn(record) },- log: (line) => console.log(line),- }),- // Export: opt-in, only files Harness wrote are ever touched.- exportTo: () => pairRulesConfig().learn.export,- exporter: new LessonExporter({- store: lessonStore,- dirs: {- agents: join(homedir(), '.agents', 'skills'),- claude: join(process.env.CLAUDE_CONFIG_DIR || dirname(env.CLAUDE_PROJECTS_DIR), 'skills'),- },- destinations: () => pairRulesConfig().learn.export,- }),- machineId: () => backend.machineId,- changed: () => pairBrain?.stateChanged(),- home: homedir(),- now: Date.now,- log: (line) => console.log(line),- })- pairBrain = new PairBrain({- pairing: { enabled: () => pairSensor.enabled(), pairedDaemon: () => pairSensor.pairedDaemon() },- fleet: pairFleet,- // Template first, then this collection's selected model when it is ready.- triage: new PairTriage({ oneshot: companionIntelligence.run, modelEnabled: () => companionIntelligence.ready(), now: Date.now, budgetMs: 30_000 }),- companionHarness: () => ({ ...companionIntelligence.status(), agentId: pairHarness.agentId(), engine: pairHarness.engine() }),- voice: pairVoice,- proposals: joinProposals(pairControl, pairLearner),- autonomy: () => pairAutonomy(),- sendLocal: pairSendLocal,- sendLocalTo: pairSendLocalTo,- shown: pairShown,- gate: pairGate,- // A key sent on to another machine is journaled here too, with the window it came from.- relayed: (fields) => { pairSensor.relayed(fields) },- // A lesson's key (pair/learn/approval.ts): never a tool client, never a process inside a harness pane.- lessonKey: (connId) => lessonKeyVerdict(connId, { isTool: (conn) => backend.isToolClient(conn), verify: verifyLessonCaller }),- lessonReview: (id) => pairLearner!.review(id),- // A key pressed on a line about THIS machine's harness: the owner's floor, then the dialog's own- // requestId, checked as the keys go in (STALE_QUESTION, nothing typed, when it changed).- answer: (input) => pairOwner.answer(input, 'key'),- onGuestPair: (daemonId, identity) => {- guestPair = isRosterDaemon(daemonId) ? daemonId : null- const parsed = readCompanionIdentity(identity)- guestCompanion = parsed?.id === guestPair ? parsed : null- applyPair()- },- onGuestAutonomy: (level) => { guestAutonomy = isAutonomy(level) ? level : null; applyPair() },- onGuestConsent: (watching) => { guestConsent = watching; applyPair() },- onActiveChanged: (active) => setVoiceRouterDeviceConnected(backend.hasCommander() || active),- talk: (text, uid) => pairTalk(text, uid),- open: async (uid, engine) => {- const previousEngine = pairHarness.engine()- const result = await pairHarness.open(uid, engine)- if (result.ok) {- if (engine && engine !== previousEngine) {- companionIntelligence.cancel()- conversationReview.engineChanged()- }- pairBrain?.stateChanged()- return { ...result, engine: pairHarness.engine() }- }- return result- },- now: Date.now,- })- // DAEMONS ON AND OFF (lib/daemonsSwitch.ts): the only timers the pair keeps whatever happens — the learner's- // tick and the pair.jsonc re-read — run only while daemons are on. Off takes everything back to idle: no- // pairing (the sensor, brain and learner stop with it), nothing waiting to be reported, the pair harness- // paused if it was live (its conversation kept).- let learnTick: ReturnType<typeof setInterval> | null = null- let pairConfigTick: ReturnType<typeof setInterval> | null = null- applyCodingMemorySetting = async () => {- openCodeMemoryBinding?.clear()- pairLearner?.cancelReviews()- conversationReview.stop()- memoryPause = memoryPause.then(() => codingMemory?.pause()).catch(() => {})- await memoryPause- if (daemons.on() && codingMemoryPreview()) {- codingMemory?.start()- await refreshMemoryIdentity()- }- }- onDaemonsChanged = (on) => {- plates.setOn(on)- if (on) {- // pair.jsonc is read when something needs it, and on this tick: a "daemons": false in it switches- // everything off within the tick (before the rest of the file is read), and any other change asks for- // the person's yes soon.- pairRulesConfig()- {- learnTick ??= setInterval(() => { if (!codingMemoryPreview()) void pairLearner?.tick().catch((err) => console.warn(`[learn] tick failed: ${err instanceof Error ? err.message : err}`)) }, 60_000)- learnTick.unref?.()- }- void memoryPause.then(() => { if (daemons.on() && codingMemoryPreview()) codingMemory?.start() })- void refreshMemoryIdentity()- pairConfigTick ??= setInterval(() => { daemons.recheck(); if (daemons.on()) { pairRulesConfig(); void refreshMemoryIdentity() } }, 30_000)- pairConfigTick.unref?.()- } else {- openCodeMemoryBinding?.clear()- memoryPause = memoryPause.then(() => codingMemory?.pause()).catch(() => {})- if (learnTick) { clearInterval(learnTick); learnTick = null }- if (pairConfigTick) { clearInterval(pairConfigTick); pairConfigTick = null }- zooTurnCounter.clear()- zooTurnReporter.clear()- zooLessonReporter.clear()- void pairHarness.off().catch(() => {})- conversationReview.stop()- pairLearner?.cancelReviews()- companionIntelligence.cancel()- companionZoo.reset(); guestCompanion = null- }- applyPair()- pairBrain?.refresh()- }- backend.onLocalClient = (connId, attached) => {- if (attached) { zooPresence.attached(connId); pairBrain?.clientAttached(connId) }- else { zooPresence.detached(connId); pairBrain?.clientDetached(connId) }- }- for (const connId of backend.localClientIds()) { zooPresence.attached(connId); pairBrain.clientAttached(connId) }- // Everything the switch turns on is wired: the one probe (or, signed out, nothing until a guest window asks).- daemons.start()// Spoken tasks go to the WINDOW to be routed, not to the copy of the router in this process.//// Built here because both ends need it: the local socket hands it the window's replies, and the cable@@ -5553,46 +4735,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {return sent},onVoiceRouteReply: (voiceId, reply) => windowRouter.reply(voiceId, reply),- // A key from a window: it counts only if this window was shown the line (pair/shown.ts, BRAIN.md Security),- // and a lesson's only if it is the person's too (the brain's `lessonKey`).- // While daemons are off (lib/daemonsSwitch.ts) every one of these is answered DAEMONS_OFF — a result the- // window reads as "hide daemons", never an error that breaks it — and nothing else happens.- onDaemonAct: (connId, payload, reply) => {- const off = !daemons.on() ? DAEMONS_OFF : !pairBrain ? 'UNSUPPORTED' : null- if (off) { reply({ type: 'daemon_act_result', payload: { requestId: payload.requestId, id: payload.id, ok: false, error: off, ...(off === DAEMONS_OFF ? { detail: DAEMONS_OFF_DETAIL } : {}) } }); return }- void pairBrain!.onKey(connId, payload, (frame) => { reply(frame) })- },- onDaemonShown: (connId, payload) => { if (daemons.on()) pairBrain?.onShown(connId, payload) },- // The person's yes (or no) to a setting the gate holds back, from a window that showed it.- onDaemonConfirm: (connId, payload, reply) => {- const off = !daemons.on() ? DAEMONS_OFF : !pairBrain ? 'UNSUPPORTED' : null- if (off) { reply({ type: 'daemon_confirm_result', payload: { requestId: payload.requestId, kind: payload.kind, nonce: payload.nonce, ok: false, error: off, ...(off === DAEMONS_OFF ? { detail: DAEMONS_OFF_DETAIL } : {}) } }); return }- pairBrain!.onConfirm(connId, payload, (frame) => { reply(frame) })- },- // The person talking to their daemon, from a window: forwarded to the pair harness (which starts or- // wakes for it), rate-limited, with what it costs.- onDaemonTalk: (connId, payload, reply) => {- const off = !daemons.on() ? DAEMONS_OFF : !pairBrain ? 'UNSUPPORTED' : null- if (off) { reply({ type: 'daemon_talk_result', payload: { requestId: payload.requestId, ok: false, error: off, ...(off === DAEMONS_OFF ? { detail: DAEMONS_OFF_DETAIL } : {}) } }); return }- void pairBrain!.onTalk(connId, payload, (frame) => { reply(frame) })- },- onDaemonOpen: (connId, payload, reply) => {- const off = !daemons.on() ? DAEMONS_OFF : !pairBrain ? 'UNSUPPORTED' : null- if (off) { reply({ type: 'daemon_open_result', payload: { requestId: payload.requestId, ok: false, error: off, ...(off === DAEMONS_OFF ? { detail: DAEMONS_OFF_DETAIL } : {}) } }); return }- void pairBrain!.onOpen(connId, payload, (frame) => { reply(frame) })- },- // Presence: whether the person is here (the zoo's away turns) always; the rest only while daemons are- // on. Signed out, a window bound to this machine saying its guest zoo has the person's consent is what- // turns them on (guests keep working as before, but only when a window asks).- // An individual's art, for any client on the socket: DAEMONS_OFF while off (the service says so).- onDaemonPlate: (_connId, payload, reply) => {- void plates.get(payload).then((answer) => { reply({ type: 'daemon_plate', payload: { requestId: payload.requestId, ...answer } }) })- },- onDaemonPresence: (connId, payload, meta) => {- zooPresence.presence(connId, payload)- if (meta.ui && 'consent' in payload) daemons.guestConsent(payload.consent === true)- if (daemons.on()) pairBrain?.onPresence(connId, payload, meta)- },machineId: backend.machineId,backend,relayPool,@@ -5775,7 +4917,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {console.warn(`[dsh] ${id} is not installed on this machine · cannot restore its harness context`)return null}- return prepareHarnessLaunch(installed, workspace, engine, runtimeKey, { privateGrid: backend.gridName() }, null, lessonsFor(workspace))+ return prepareHarnessLaunch(installed, workspace, engine, runtimeKey, { privateGrid: backend.gridName() }, null)},}// Whatever the source (the row itself, or a grid override the desktop just sent), the agent's DSH,@@ -6045,7 +5187,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {const PANE_POLLED_ENGINES = new Set(['devin', 'cursor', 'grok', 'agy', 'opencode', 'kilo'])const PANE_POLL_MS = 15_000setInterval(() => {- void companionStartupProfile.refresh().then(() => companionProfileChanged()).catch(() => undefined)for (const session of registry.list()) {if (!PANE_POLLED_ENGINES.has(session.engine)) continuevoid captureTerminal(session.agentId, 60)@@ -6071,8 +5212,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {backend.onCommanderJoin = () => { setSummaryPoolDeviceConnected(deviceIsWatching()); mirror.replayAll(); questionWatcher.reset() } // re-announce an open questionbackend.onCommanderPresenceChanged = (connected) => {setSummaryPoolDeviceConnected(connected || backend.autonomousDeviceConnected())- // Warm the voice-router worker while a device is connected — or while the pair brain may need it.- setVoiceRouterDeviceConnected(connected || pairBrain?.isActive === true)+ // Warm the voice-router worker while a device is connected.+ setVoiceRouterDeviceConnected(connected)}// Web cancel (C-c) interrupts the turn — claude writes no end_turn line to close it, so stop the@@ -6392,7 +5533,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {console.warn(`[agent] create ${dsh} refused · ${detail}`)return { ok: false, error: 'DSH_MATERIALIZE_FAILED', detail }}- const prepared = harnessLaunchOrRefusal(() => prepareHarnessLaunch(installed, cwd, engine, label, dshAccount, null, lessonsFor(cwd)))+ const prepared = harnessLaunchOrRefusal(() => prepareHarnessLaunch(installed, cwd, engine, label, dshAccount, null))if (!prepared.ok) return prepareddshEnv = prepared.launch.envdshArgs = prepared.launch.args@@ -6578,7 +5719,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {const cwd = source.cwdconst sourceKey = forkRuntimeKey({ cwd, agentId: source.agentId, dshRuntime: source.dshRuntime })const prepared = harnessLaunchOrRefusal(() => prepareHarnessLaunch(installed, cwd, engine, label,- { privateGrid: backend.gridName() }, sourceKey, lessonsFor(cwd)))+ { privateGrid: backend.gridName() }, sourceKey))if (!prepared.ok) return prepareddshEnv = prepared.launch.envdshArgs = prepared.launch.args@@ -7206,7 +6347,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {daemonBoot.updater?.stop()daemonBoot.tuiUpdater?.stop()agentReconciler.stop()- await codingMemory?.close()clearInterval(logTrimTimer)clearInterval(runtimeReconcileTimer)clearInterval(paneTitleSyncTimer)@@ -7319,7 +6459,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {daemonBoot.updater?.stop()daemonBoot.tuiUpdater?.stop()agentReconciler.stop()- await codingMemory?.close()clearInterval(logTrimTimer)clearInterval(runtimeReconcileTimer)clearInterval(paneTitleSyncTimer)@@ -7343,11 +6482,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {await dshViewers.stopAll()await dshVerdicts.stop()autonomousDeviceDirect?.stop()- // The last minute's turns, best effort: an update restart should not lose them, nor wait on them.- daemons.stop()- zooTurnReporter.stop()- zooLessonReporter.stop()- await Promise.race([Promise.all([zooTurnReporter.flush(), zooLessonReporter.flush()]), new Promise((resolve) => setTimeout(resolve, 2000).unref())])await backend.stop()try { if (readPid() === process.pid) rmSync(PID_FILE, { force: true }) } catch { /* ignore */ }process.exit(0)@@ -7440,11 +6574,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {let devicesStatusRevision = 0const cableHost = new DaemonCableHost({- // Zoo selection is visual identity; it does not require consent to watch terminal activity.- // Guest identity is only a fallback while signed out, never another account's cached choice.- companion: () => daemons.on() ? (zooPair.known ? zooPair.pair : readAuthSession() ? null : guestPair) : null,- companionIdentity: () => daemons.on() ? (zooPair.known ? companionZoo.identity : readAuthSession() ? null : guestCompanion) : null,- companionMilestone: () => daemons.on() ? companionZoo.milestone : null,activityText: async (agentId) => {const session = registry.resolve(agentId)if (!session || (session.engine !== 'claude' && session.engine !== 'codex')) return null@@ -7970,7 +7099,6 @@ async function daemonCall(method: 'GET' | 'POST', path: string, body?: unknown):async function pairCommand(code: string | undefined): Promise<void> {if (!code) {console.error('Usage: harness pair <code> (the code is shown on the browser or device)')- console.error(' harness pair <verb> your daemon\'s control interface (harness pair status --help)')process.exit(1)}const { res, json } = await daemonCall('POST', '/api/pair', { code })@@ -9003,46 +8131,9 @@ switch (cmd) {connect: (url) => new NewCommandSocket(url),}).then(code => { process.exitCode = code }).catch(onError)break- case 'pair': {- // `harness pair <code>` pairs a browser; `harness pair <verb>` is the daemon's control interface- // (pair/client.ts). No pairing code is ever one of the verbs.- const verb = pairVerb(args[0])- if (!verb) { pairCommand(args[0]).catch(onError); break }- const pairClient: PairClientDeps = {- port: daemonPort(),- machineId: async () => process.env.HARNESSD_MACHINE_ID || (await runningDaemonStatus())?.machineId || null,- connect: (url) => new NewCommandSocket(url),- env: process.env,- }- if (verb === 'mcp') {- // stdout is the protocol: anything else printed there would corrupt it.- console.log = (...line: unknown[]) => console.error(...line)- const at = rest.findIndex((word) => word === '--token-file' || word.startsWith('--token-file='))- const tokenFile = at < 0 ? null : rest[at]!.includes('=') ? rest[at]!.slice('--token-file='.length) : rest[at + 1] ?? null- serveMcp({ input: process.stdin, output: process.stdout, version: VERSION, call: (payload) => pairRequest({ ...pairClient, tokenFile }, payload),- log: (line) => console.error(line) })- .then(() => { process.exitCode = 0 }).catch(onError)- break- }- // `lessons approve` asks the person at this terminal; with no terminal (an agent's shell tool) it refuses.- const confirm = process.stdin.isTTY && process.stderr.isTTY- ? (question: string) => new Promise<boolean>((resolve) => {- const rl = createInterface({ input: process.stdin, output: process.stderr })- rl.question(question, (answer) => { rl.close(); resolve(/^y(es)?$/i.test(answer.trim())) })- })- : null- // Which tmux session this shell is in: a harness pane never approves a lesson (the daemon checks again).- const paneSession = (): Promise<string | null> => {- const pane = process.env.TMUX_PANE- if (!pane || !process.env.TMUX) return Promise.resolve(null)- return new Promise((resolve) => {- execFileCb('tmux', ['display-message', '-p', '-t', pane, '#{session_name}'], { timeout: 2_000 }, (err, stdout) => resolve(err ? null : String(stdout).trim() || null))- })- }- pairControlCommand(rest, { ...pairClient, confirm, paneSession, output: (line) => process.stdout.write(`${line}\n`), error: (line) => console.error(line) })- .then((code) => { process.exitCode = code }).catch(onError)+ case 'pair':+ pairCommand(args[0]).catch(onError)break- }case 'browser-link':case 'e2ee-link':// Browser setup links served the retired web client. Said plainly rather than falling to "unknowndiff --git a/cli/src/config/env.ts b/cli/src/config/env.tsindex f374a6ac4..00d4706cd 100644--- a/cli/src/config/env.ts+++ b/cli/src/config/env.ts@@ -411,10 +411,6 @@ const envSchema = z.object({// Where the `harness` launcher lives. Same name (and default) `scripts/install-cli.sh` uses, so a// sandboxed install and this process agree on which launcher they are talking about.HARNESS_BIN_DIR: z.string().default(adapterBinDir),- // The lessons your daemons learned (pair/learn, daemons/LEARNING.md): a git-backed folder outside any- // repo, created on the first lesson, never before.- HARNESS_LESSONS_DIR: z.string().default(join(adapterRootDir, 'lessons')),-// ── the dial on the USB cable ──────────────────────────────────────────────────────────────────// Set 'true' to leave the serial port alone entirely. The port is exclusive, so this is what a// developer flips before running esptool or a serial monitor against the dial.diff --git a/cli/src/config/envIsolation.spec.ts b/cli/src/config/envIsolation.spec.tsindex 54254a5d4..758802207 100644--- a/cli/src/config/envIsolation.spec.ts+++ b/cli/src/config/envIsolation.spec.ts@@ -24,8 +24,6 @@ describe('test environment isolation', () => {expect(env.ADAPTER_RUNTIME_DIR.startsWith(productRoot)).toBe(false)})it('keeps the lessons folder off the developer\'s ~/.harness, so no spec writes a lesson there', () => {- expect(env.HARNESS_LESSONS_DIR.startsWith(productRoot)).toBe(false)- expect(env.HARNESS_LESSONS_DIR).toBe(join(env.ADAPTER_DATA_DIR, 'lessons'))})it('keeps account reads and refreshes in the test-owned auth directory', () => {expect(AUTH_DIR).toBe(join(env.ADAPTER_DATA_DIR, 'auth'))diff --git a/cli/src/coreIsolation.spec.ts b/cli/src/coreIsolation.spec.tsnew file mode 100644index 000000000..1e6c1657d--- /dev/null+++ b/cli/src/coreIsolation.spec.ts@@ -0,0 +1,24 @@+import { fileURLToPath } from 'node:url'+import { readFileSync } from 'node:fs'+import { build } from 'esbuild'+import { expect, it } from 'vitest'++it('builds the ordinary CLI without either optional feature implementation', async () => {+ const result = await build({+ absWorkingDir: fileURLToPath(new URL('..', import.meta.url)),+ entryPoints: ['src/cli.ts'], bundle: true, write: false,+ platform: 'node', format: 'esm', metafile: true,+ external: ['bufferutil', 'utf-8-validate'], logLevel: 'silent',+ })+ expect(Object.keys(result.metafile!.inputs).filter(path =>+ /(?:^|\/)companions\/|src\/(?:pair|memory)\//.test(path))).toEqual([])+ for (const name of ['build.mjs', 'build-bundle.mjs']) {+ const source = readFileSync(new URL(`../${name}`, import.meta.url), 'utf8')+ expect(source).not.toMatch(/(?:memory|plate)WorkerSource|__(?:MEMORY|PLATE)_WORKER__/)+ }+})++it('keeps the default native hook free of companion context and memory receipts', () => {+ const source = readFileSync(new URL('../hook/notify.mjs', import.meta.url), 'utf8')+ expect(source).not.toMatch(/memory-emitted|memoryReceiptId|additionalContext|acknowledgeMemoryOutput/)+})diff --git a/cli/src/devices/client.ts b/cli/src/devices/client.tsindex 05fd20efa..9233deeb0 100644--- a/cli/src/devices/client.ts+++ b/cli/src/devices/client.ts@@ -1,12 +1,12 @@/** Devices DSH tools use the same owned-machine bridge as Desktop. No serial or credential access. */import { randomUUID } from 'node:crypto'-import type { PairSocket } from '../pair/client.js'+import type { ClientSocket } from '../lib/clientSocket.js'import { deviceSettingsPatchSchema } from '../lib/harnessDevices.js'export interface DevicesClientDeps {port: numbermachineId(): Promise<string | null>- connect(url: string): PairSocket+ connect(url: string): ClientSocketfetch?: typeof fetchrequest?: (machineId: string, type: string, payload?: Record<string, unknown>) => Promise<Record<string, unknown>>delay?: (ms: number) => Promise<void>diff --git a/cli/src/dsh/builtins.ts b/cli/src/dsh/builtins.tsindex 9b0c12b4b..fc7d0eda8 100644--- a/cli/src/dsh/builtins.ts+++ b/cli/src/dsh/builtins.ts@@ -56,18 +56,9 @@ export function ensureBundledCoreHarnesses(log: (line: string) => void = consolereturn ready}-/** The pair harness (pair/pairHarness.ts): generated on this machine, never listed in the Store or the picker. */-export const PAIR_BUILTIN_SOURCE = 'builtin:pair'--/** Install the pair harness's generated package. True once it is installed at this revision. */-export function ensureBuiltinPair(id: string, files: BundledFiles): boolean {- if (!files['harness.json']) return false- return installBuiltin({ id, source: PAIR_BUILTIN_SOURCE, folder: 'pair', files, what: 'pair harness' })-}-/** Built-ins opened through their own product entry points, absent from the public picker. */export function isHiddenBuiltin(record: { source?: string | null }): boolean {- return record.source === PAIR_BUILTIN_SOURCE || record.source === DEVICES_BUILTIN_SOURCE+ return record.source === 'builtin:pair' || record.source === DEVICES_BUILTIN_SOURCE}/** Materialize `files` under `.bundled/<folder>/<revision>` and point the index at it. Idempotent per revision. */diff --git a/cli/src/dsh/runtime.ts b/cli/src/dsh/runtime.tsindex 5901de5f1..a596af628 100644--- a/cli/src/dsh/runtime.ts+++ b/cli/src/dsh/runtime.ts@@ -12,7 +12,6 @@ import { installedDsh, type InstalledDsh } from './installed.js'import { dshAccountEnv, dshLaunch, type DshAccount, type DshLaunch } from './launch.js'import { compatibleHarnessEngines } from './compatibility.js'import { skillDirsIn } from './materialize.js'-import { installLessons, type RuntimeLessons } from '../pair/learn/publish.js'const Snapshot = z.object({version: z.literal(1),@@ -168,13 +167,8 @@ export function harnessLaunchOrRefusal(prepare: () => DshLaunch):}}-/**- * `lessons`: the approved lesson skills this session loads (pair/learn/publish.ts runtimeLessons). They are- * copied, read-only, to `<runtime>/lessons` and indexed in CONTEXT.md, one line each — the Store runtime path is how a- * lesson reaches every engine without a byte in an engine's own folders. Never fails a launch.- */export function prepareHarnessLaunch(dsh: InstalledDsh, workspace: string, engine: AgentEngine,- key: string, account: DshAccount = {}, sourceKey?: string | null, lessons?: RuntimeLessons | null): DshLaunch {+ key: string, account: DshAccount = {}, sourceKey?: string | null): DshLaunch {const adapter = harnessAdapter(engine)if (dsh.manifest.kind === 'viewer') throw new Error(`${dsh.id} is a viewer, not a harness`)const ws = realpathSync(workspace)@@ -212,7 +206,6 @@ export function prepareHarnessLaunch(dsh: InstalledDsh, workspace: string, engin}migrateHarnessInstructions(ws, dsh)installBootstrap(ws, engine)- const lessonIndex = installLessons(dir, lessons)const env: Record<string, string> = { ...data.env, ...dshAccountEnv(account), HARNESS_CONTEXT_FILE: join(dir, 'CONTEXT.md'), HARNESS_SKILLS_DIR: skillsDir }// Spec-1 packages used their default engine's discovery paths in env. Translate the path, not// arbitrary engine names or source paths inside an upstream installation.@@ -232,7 +225,6 @@ export function prepareHarnessLaunch(dsh: InstalledDsh, workspace: string, engin'', '## Harness skills',...data.skills.map(skill => `- ${skill.name}: ${JSON.stringify(join(skillsDir, skill.name, 'SKILL.md'))}`),'',- ...lessonIndex,].join('\n')writeManagedFile(env.HARNESS_CONTEXT_FILE!, context)if (!existsSync(file)) writeManagedFile(file, `${JSON.stringify(data, null, 2)}\n`)diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.tsindex 97ca9f2fb..e7e16e5cc 100644--- a/cli/src/hookNotify.spec.ts+++ b/cli/src/hookNotify.spec.ts@@ -130,6 +130,8 @@ function runHook(opts: RunHookOpts): Promise<string> {async function collect(response: Record<string, unknown> = {}): Promise<{ port: number; requests: Array<{ url: string; body: Record<string, unknown> }> }> {const requests: Array<{ url: string; body: Record<string, unknown> }> = []const server = createServer((req, res) => {+ // Local service discovery may probe a test port. Only hook POSTs belong to this fixture.+ if (req.method !== 'POST') { res.writeHead(405).end(); return }let raw = ''req.on('data', (chunk) => { raw += chunk.toString() })req.on('end', () => {@@ -148,18 +150,15 @@ async function collect(response: Record<string, unknown> = {}): Promise<{ port:}describe('hook notify terminal scope', () => {- it.each(['claude', 'codex'] as const)('acknowledges an emitted %s memory packet without copying the prompt or claim into the receipt', async engine => {+ it.each(['claude', 'codex'] as const)('ignores a stale %s memory response and only reports ordinary session registration', async engine => {const additionalContext = 'Historical coding memory: keep review changes small.'const memoryReceiptId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'const { port, requests } = await collect({ ok: true, additionalContext, memoryReceiptId })const recordings = JSON.parse(readFileSync(new URL('./lib/__fixtures__/swarm-prompt-hooks.json', import.meta.url), 'utf8'))const input = recordings[engine].inputconst stdout = await runHook({ port, engine, tmuxPane: '%42', input })- expect(JSON.parse(stdout)).toEqual({ hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext } })- expect(requests.map(request => request.url)).toEqual(['/api/hook/session-start', '/api/hook/memory-emitted'])- expect(requests[1].body).toMatchObject({ engine, sessionId: input.session_id, memoryReceiptId })- expect(requests[1].body).not.toHaveProperty('prompt')- expect(requests[1].body).not.toHaveProperty('additionalContext')+ expect(stdout).toBe('')+ expect(requests.map(request => request.url)).toEqual(['/api/hook/session-start'])})it('never acknowledges a receipt without emitted user-turn context', async () => {@@ -169,13 +168,13 @@ describe('hook notify terminal scope', () => {expect(requests.map(request => request.url)).toEqual(['/api/hook/session-start'])})- it.each(['claude', 'codex'] as const)('adds daemon-verified companion context to the actual %s user turn', async engine => {+ it.each(['claude', 'codex'] as const)('does not inject companion context returned by an older adapter into a %s user turn', async engine => {const additionalContext = 'Companions collection context: selected GNU; retain this conversation.'const { port, requests } = await collect({ ok: true, additionalContext })const recordings = JSON.parse(readFileSync(new URL('./lib/__fixtures__/swarm-prompt-hooks.json', import.meta.url), 'utf8'))const input = recordings[engine].inputconst stdout = await runHook({ port, engine, tmuxPane: '%42', input })- expect(JSON.parse(stdout)).toEqual({ hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext } })+ expect(stdout).toBe('')expect(requests[0]?.body.prompt).toBe(input.prompt)expect(await runHook({ port, engine, tmuxPane: '%42', input: { ...input, hook_event_name: 'SessionStart' } })).toBe('')})@@ -243,6 +242,7 @@ describe('hook notify terminal scope', () => {const cursorHome = join(dir, 'cursor')const requests: Array<{ url: string; body: Record<string, unknown> }> = []const server = createServer((req, res) => {+ if (req.method !== 'POST') { res.writeHead(405).end(); return }let raw = ''req.on('data', (chunk) => { raw += chunk.toString() })req.on('end', () => {@@ -378,6 +378,7 @@ describe('hook notify terminal scope', () => {it('forwards tmux events regardless of legacy MACHINE_ID', async () => {const requests: Array<{ url: string; body: Record<string, unknown> }> = []const server = createServer((req, res) => {+ if (req.method !== 'POST') { res.writeHead(405).end(); return }let raw = ''req.on('data', (chunk) => { raw += chunk.toString() })req.on('end', () => {@@ -401,6 +402,7 @@ describe('hook notify terminal scope', () => {it('drops standalone SessionEnd but forwards tmux SessionEnd', async () => {const requests: Array<{ url: string; body: Record<string, unknown> }> = []const server = createServer((req, res) => {+ if (req.method !== 'POST') { res.writeHead(405).end(); return }let raw = ''req.on('data', (chunk) => { raw += chunk.toString() })req.on('end', () => {@@ -1133,7 +1135,6 @@ describe('hook notify Command Code re-registration', () => {cwd: '/tmp/demo',title: 'Greeting',})- expect(requests[1].body).toMatchObject({ sessionId: '53955d6d' })})it('omits a transcript path that does not exist yet', async () => {diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.tsindex 293795607..db262ee58 100644--- a/cli/src/hookServer.spec.ts+++ b/cli/src/hookServer.spec.ts@@ -63,167 +63,6 @@ async function start(overrides: Partial<HookServerHandlers> = {}) {}describe('process-owned hook server', () => {- it.each(['claude', 'codex', 'opencode'] as const)('serves shared memory only to the live bound %s adapter', async engine => {- const entry = { engine, agentId: 'coding-agent', sessionId: 'native',- processIdentity: { pid: 42, executable: engine, startMarker: 'same-process' } } as RegisteredSession- const resolveHookAgent = vi.fn(async () => entry as RegisteredSession | null)- const onMemoryContext = vi.fn(() => ({ additionalContext: 'Historical coding context',- memoryReceiptId: '77777777-7777-4777-8777-777777777777' }))- const registration = vi.spyOn(registry, 'register')- try {- const { base, headers } = await start({ resolveHookAgent, onMemoryContext })- const body = { engine, sessionId: 'native', callerPid: 42, tmuxPane: '%41', cliVersion: 'test-version', prompt: 'Review parser\nchanges.' }- const submit = (value: unknown = body, authenticated = true) => fetch(`${base}/api/hook/memory-context`, {- method: 'POST', headers: authenticated ? headers : {}, body: JSON.stringify(value) })- expect((await submit(body, false)).status).toBe(401)- expect((await submit({ ...body, sessionId: 'other-session' })).status).toBe(403)- for (const changes of [{ callerPid: undefined }, { cliVersion: undefined }, { prompt: ' ' },- { prompt: 'x'.repeat(4001) }, { projectId: 'caller-selected' }, { engine: 'terminal' }]) {- expect((await submit({ ...body, ...changes })).status).toBe(400)- }- expect(onMemoryContext).not.toHaveBeenCalled()- expect(await (await submit()).json()).toEqual({ ok: true, additionalContext: 'Historical coding context',- memoryReceiptId: '77777777-7777-4777-8777-777777777777' })- expect(onMemoryContext).toHaveBeenCalledExactlyOnceWith('coding-agent', 'Review parser\nchanges.', { engine, cliVersion: 'test-version' })- expect(registration).not.toHaveBeenCalled()- resolveHookAgent.mockResolvedValue(null)- expect((await submit()).status).toBe(403)- } finally { registration.mockRestore() }- })-- it('never falls back to pane-only ownership for memory reads or OpenCode acknowledgements', async () => {- const onMemoryContext = vi.fn(), onMemoryContextEmitted = vi.fn(async () => true)- const lookup = vi.spyOn(registry, 'byPaneEngine').mockReturnValue({ engine: 'opencode', sessionId: 'native' } as RegisteredSession)- try {- const { base, headers } = await start({ onMemoryContext, onMemoryContextEmitted })- const body = { engine: 'opencode', sessionId: 'native', callerPid: 42, tmuxPane: '%41', cliVersion: '1.18.34', prompt: 'Review parser.' }- for (const route of ['memory-context', 'memory-emitted']) {- const response = await fetch(`${base}/api/hook/${route}`, { method: 'POST', headers,- body: JSON.stringify({ ...body, memoryReceiptId: '77777777-7777-4777-8777-777777777777' }) })- expect(response.status).toBe(403)- }- expect(lookup).not.toHaveBeenCalled()- expect(onMemoryContext).not.toHaveBeenCalled()- expect(onMemoryContextEmitted).not.toHaveBeenCalled()- } finally { lookup.mockRestore() }- })-- it('bounds a stalled adapter read without sending late context', async () => {- const entry = { engine: 'opencode', agentId: 'coding-agent', sessionId: 'native',- processIdentity: { pid: 42, executable: 'opencode', startMarker: 'same-process' } } as RegisteredSession- const { base, headers } = await start({ resolveHookAgent: async () => entry,- onMemoryContext: async () => new Promise(() => {}) })- const result = await fetch(`${base}/api/hook/memory-context`, { method: 'POST', headers,- body: JSON.stringify({ engine: 'opencode', sessionId: 'native', callerPid: 42, tmuxPane: '%41', cliVersion: '1.18.34', prompt: 'Review parser.' }) })- expect(await result.json()).toEqual({ ok: true })- })-- it('accepts private OpenCode runtime observations only from the verified live session', async () => {- const entry = { engine: 'opencode', agentId: 'companion', sessionId: 'native',- processIdentity: { pid: 42, executable: 'opencode', startMarker: 'same-process' } } as RegisteredSession- const resolveHookAgent = vi.fn(async () => entry as RegisteredSession | null)- const onOpenCodeMemoryRuntime = vi.fn(() => ({ observe: true, recorded: true }))- const registration = vi.spyOn(registry, 'register')- try {- const { base, headers, handlers } = await start({ resolveHookAgent, onOpenCodeMemoryRuntime })- const body = { engine: 'opencode', sessionId: 'native', tmuxPane: '%41', callerPid: 42,- input: { kind: 'observe', snapshot: { private: 'synthetic-secret' } } }- const submit = (value: unknown = body, authenticated = true) => fetch(`${base}/api/hook/opencode-memory-runtime`, {- method: 'POST', headers: authenticated ? headers : { 'content-type': 'application/json' }, body: JSON.stringify(value) })- expect((await submit(body, false)).status).toBe(401)- expect((await submit({ ...body, sessionId: 'previous-session' })).status).toBe(403)- expect((await submit({ ...body, engine: 'codex' })).status).toBe(400)- expect((await submit({ ...body, callerPid: undefined })).status).toBe(400)- expect((await submit({ ...body, input: { blob: 'x'.repeat(51_000) } })).status).toBe(400)- expect(onOpenCodeMemoryRuntime).not.toHaveBeenCalled()- const accepted = await submit()- expect(await accepted.json()).toEqual({ observe: true, recorded: true })- expect(onOpenCodeMemoryRuntime).toHaveBeenCalledExactlyOnceWith(entry, body.input)- expect(registration).not.toHaveBeenCalled()- expect(handlers.onRegistered).not.toHaveBeenCalled()- resolveHookAgent.mockResolvedValue(null)- expect((await submit()).status).toBe(403)- } finally { registration.mockRestore() }- })-- it('does not accept private runtime data through discovery fallback without ancestry verification', async () => {- const callback = vi.fn()- const { base, headers } = await start({ onOpenCodeMemoryRuntime: callback })- const result = await fetch(`${base}/api/hook/opencode-memory-runtime`, { method: 'POST', headers,- body: JSON.stringify({ engine: 'opencode', sessionId: 'native', tmuxPane: '%41', callerPid: 42, input: { kind: 'probe' } }) })- expect(result.status).toBe(403)- expect(callback).not.toHaveBeenCalled()- })-- it('attributes prompt text only after resolving the actual engine process', async () => {- const entry = { engine: 'claude', agentId: 'agent-scope', sessionId: 'session-scope', runtimes: [{ backend: 'tmux', paneId: '%41' }] } as RegisteredSession- const onPromptSubmitted = vi.fn()- const onPromptContext = vi.fn(() => 'Companions collection context')- const resolveHookAgent = vi.fn(async () => null as RegisteredSession | null)- const registration = vi.spyOn(registry, 'register').mockReturnValue({ entry, isNew: false, evicted: null, rebound: null, orphaned: null })- try {- const { base, headers } = await start({ onPromptSubmitted, onPromptContext, resolveHookAgent })- const submit = () => fetch(`${base}/api/hook/session-start`, { method: 'POST', headers, body: JSON.stringify({- engine: 'claude', sessionId: entry.sessionId, tmuxPane: '%41', hookEvent: 'UserPromptSubmit', prompt: 'ask a peer\nfor evidence',- }) })- await submit()- expect(onPromptSubmitted).not.toHaveBeenCalled()- expect(onPromptContext).not.toHaveBeenCalled()- resolveHookAgent.mockResolvedValue(entry)- expect(await (await submit()).json()).toEqual({ ok: true, additionalContext: 'Companions collection context' })- expect(onPromptContext).toHaveBeenCalledExactlyOnceWith('agent-scope', 'ask a peer\nfor evidence')- expect(onPromptSubmitted).toHaveBeenCalledExactlyOnceWith('agent-scope', 'ask a peer\nfor evidence')- } finally { registration.mockRestore() }- })- it.each(['claude', 'codex'] as const)('awaits bounded optional memory on a verified %s user prompt only', async engine => {- const entry = { engine, agentId: 'memory_agent', sessionId: 'memory_session', runtimes: [{ backend: 'tmux', paneId: '%41' }] } as RegisteredSession- const registration = vi.spyOn(registry, 'register').mockReturnValue({ entry, isNew: false, evicted: null, rebound: null, orphaned: null })- const context = { additionalContext: 'Historical coding memory', memoryReceiptId: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' }- const onPromptContext = vi.fn(async () => context)- try {- const { base, headers } = await start({ resolveHookAgent: async () => entry, onPromptContext })- const submit = async (hookEvent: string) => (await fetch(`${base}/api/hook/session-start`, { method: 'POST', headers,- body: JSON.stringify({ engine, sessionId: entry.sessionId, tmuxPane: '%41', hookEvent, prompt: 'Fix the coding bug.' }) })).json()- expect(await submit('SessionStart')).toEqual({ ok: true })- expect(onPromptContext).not.toHaveBeenCalled()- expect(await submit('UserPromptSubmit')).toEqual({ ok: true, ...context })- } finally { registration.mockRestore() }- })-- it.each(['failed', 'hung', 'oversized'] as const)('continues the prompt when optional recall is %s', async mode => {- const entry = { engine: 'claude', agentId: 'memory_agent', sessionId: 'memory_session' } as RegisteredSession- const registration = vi.spyOn(registry, 'register').mockReturnValue({ entry, isNew: false, evicted: null, rebound: null, orphaned: null })- const onPromptContext = async (): Promise<string> => {- if (mode === 'failed') throw new Error('Private provider error must not be returned.')- if (mode === 'hung') return new Promise(() => {})- return '🪴'.repeat(2_100)- }- try {- const { base, headers } = await start({ resolveHookAgent: async () => entry, onPromptContext })- const started = performance.now()- const response = await fetch(`${base}/api/hook/session-start`, { method: 'POST', headers,- body: JSON.stringify({ engine: 'claude', sessionId: entry.sessionId, tmuxPane: '%41', hookEvent: 'UserPromptSubmit' }) })- expect(await response.json()).toEqual({ ok: true })- expect(performance.now() - started).toBeLessThan(1_000)- } finally { registration.mockRestore() }- })-- it.each(['codex', 'opencode'] as const)('accepts emitted receipts only from a %s hook bound to the same live native session', async engine => {- const entry = { engine, agentId: 'memory_agent', sessionId: 'memory_session',- processIdentity: { pid: 42, executable: engine, startMarker: 'same-process' } } as RegisteredSession- const resolveHookAgent = vi.fn(async () => entry)- const onMemoryContextEmitted = vi.fn(async () => true)- const { base, headers } = await start({ resolveHookAgent, onMemoryContextEmitted })- const body = { engine, callerPid: 42, sessionId: entry.sessionId, tmuxPane: '%41', memoryReceiptId: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' }- const submit = (value = body, authenticated = true) => fetch(`${base}/api/hook/memory-emitted`, {- method: 'POST', headers: authenticated ? headers : { 'content-type': 'application/json' }, body: JSON.stringify(value) })- expect((await submit(body, false)).status).toBe(401)- expect((await submit({ ...body, sessionId: 'old_session' })).status).toBe(403)- expect((await submit({ ...body, memoryReceiptId: 'fabricated' })).status).toBe(400)- expect(onMemoryContextEmitted).not.toHaveBeenCalled()- expect(await (await submit()).json()).toEqual({ ok: true, recorded: true, delivery: 'unverified' })- expect(onMemoryContextEmitted).toHaveBeenCalledExactlyOnceWith(entry.agentId, body.memoryReceiptId)- })it('runs targeted resolution and rejects a hook without a matching pane engine process', async () => {const resolveHookAgent = vi.fn(async () => null)@@ -432,59 +271,18 @@ describe('account Experimental settings proxy', () => {})})-describe('the zoo proxy', () => {- it('reads the zoo ungated and writes its ops only with the local header, body passed through', async () => {- const zoo = { daemons: [], eggs: [], pair: null, habits: [], firstEgg: false, pity: 0, easter: [] }- const ops = vi.fn(async (body: unknown) => ({ status: 200, body: { success: true, data: { revision: 2, zoo, hatched: [], echo: body } } }))- const deskRead = vi.fn()- const { base } = await start({- onZooRead: async () => ({ status: 200, body: { success: true, data: { revision: 1, zoo } } }),- onZooOps: ops,- onDeskRead: deskRead,- })- const read = await fetch(`${base}/api/zoo`)- expect(await read.json()).toEqual({ success: true, data: { revision: 1, zoo } })- expect(deskRead).not.toHaveBeenCalled() // its own document: a zoo read never reads the desk-- const refused = await fetch(`${base}/api/zoo/ops`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{"ops":[]}' })- expect(refused.status).toBe(403)- expect(ops).not.toHaveBeenCalled()-- const body = { ops: [{ op: 'zoo.habit', key: 'turn' }] }- const written = await fetch(`${base}/api/zoo/ops`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-adapter-local': '1' }, body: JSON.stringify(body) })- expect(((await written.json()) as { data: unknown }).data).toMatchObject({ revision: 2, hatched: [], echo: body })- expect(ops).toHaveBeenCalledWith(body)-- const bad = await fetch(`${base}/api/zoo/ops`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-adapter-local': '1' }, body: '{nope' })- expect(bad.status).toBe(400)- })-- it('passes a signed-out answer through as it came, the way the desk does', async () => {- const signedOut = { status: 401, body: { success: false, error: { code: 'NOT_SIGNED_IN', message: 'Not signed in' } } }- const { base } = await start({ onZooRead: async () => signedOut, onZooOps: async () => signedOut })- const read = await fetch(`${base}/api/zoo`)- expect(read.status).toBe(401)- expect(await read.json()).toEqual(signedOut.body)- const write = await fetch(`${base}/api/zoo/ops`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-adapter-local': '1' }, body: '{"ops":[{"op":"zoo.habit","key":"turn"}]}' })- expect(write.status).toBe(401)- })-- it('passes a daemons-off answer through as it came: the window hides daemons on the 404', async () => {- const off = { status: 404, body: { success: false, error: { code: 'DAEMONS_OFF', message: 'Daemons are off for this account or on this computer.' } } }- const { base } = await start({ onZooRead: async () => off, onZooOps: async () => off })- const read = await fetch(`${base}/api/zoo`)- expect(read.status).toBe(404)- expect(await read.json()).toEqual(off.body)- const write = await fetch(`${base}/api/zoo/ops`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-adapter-local': '1' }, body: '{"ops":[{"op":"zoo.habit","key":"turn"}]}' })- expect(write.status).toBe(404)- expect(await write.json()).toEqual(off.body)- })-- it('answers 503 on a daemon built without the zoo', async () => {- const { base } = await start()- expect((await fetch(`${base}/api/zoo`)).status).toBe(503)- expect((await fetch(`${base}/api/zoo/ops`, { method: 'POST', headers: { 'x-adapter-local': '1' }, body: '{}' })).status).toBe(503)- })+describe('optional feature routes are absent from core', () => {+ it.each(['/api/zoo', '/api/zoo/ops', '/api/hook/memory-context', '/api/hook/memory-emitted', '/api/hook/opencode-memory-runtime'])(+ 'does not handle %s or consult account metadata', async path => {+ const me = vi.fn(async () => ({ status: 200, body: {} }))+ const { base } = await start({ onAuthMe: me })+ const response = await fetch(`${base}${path}`, {+ method: path === '/api/zoo' ? 'GET' : 'POST', headers: { 'x-adapter-local': '1' }, body: path === '/api/zoo' ? undefined : '{}',+ })+ expect(response.status).toBe(404)+ expect(me).not.toHaveBeenCalled()+ },+ )})describe('the Harness Store proxy', () => {diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.tsindex 2928a960e..dc38ab115 100644--- a/cli/src/hookServer.ts+++ b/cli/src/hookServer.ts@@ -55,33 +55,7 @@ export interface PairOutcome {body: Record<string, unknown>}-export interface NativePromptContext { additionalContext: string; memoryReceiptId?: string }-type PromptContext = NativePromptContext | string | null--/** Optional recall must never hang an engine's prompt or expose a failed lookup as a hook failure. */-async function boundedPromptContext(read: () => PromptContext | Promise<PromptContext>): Promise<NativePromptContext | null> {- let timer: NodeJS.Timeout | undefined- try {- const result = await Promise.race([Promise.resolve().then(read),- new Promise<null>(resolve => { timer = setTimeout(() => resolve(null), 225) })])- const context = typeof result === 'string' ? { additionalContext: result } : result- if (!context || typeof context.additionalContext !== 'string' || !context.additionalContext- || Buffer.byteLength(context.additionalContext) > 8_000) return null- return { additionalContext: context.additionalContext,- ...(typeof context.memoryReceiptId === 'string' && /^[a-f0-9-]{36}$/.test(context.memoryReceiptId)- ? { memoryReceiptId: context.memoryReceiptId } : {}) }- } catch { return null } finally { if (timer) clearTimeout(timer) }-}-export interface HookServerHandlers {- /** Context for a verified process-owned agent, only on its real user turn. */- onPromptContext?: (agentId: string, prompt: string) => PromptContext | Promise<PromptContext>- /** Shared recall for a live, process-verified native adapter. Scope always comes from the host. */- onMemoryContext?: (agentId: string, prompt: string, adapter: { engine: AgentEngine; cliVersion: string }) => PromptContext | Promise<PromptContext>- /** Called only for the same process-owned native session after its hook writes context to stdout. */- onMemoryContextEmitted?: (agentId: string, receiptId: string) => Promise<boolean>- /** Private, process-verified OpenCode request metadata. Never enters the session registry or clients. */- onOpenCodeMemoryRuntime?: (agent: RegisteredSession, input: unknown) => Record<string, unknown>onCommandBar?: Pick<CommandBarService, 'status' | 'decide'>onAutonomousDeviceRequest?: (method: string, target: string, body?: unknown) => Promise<{ status: number; body: unknown }>@@ -179,11 +153,6 @@ export interface HookServerHandlers {/** The account's Experimental switches, proxied with the daemon's own identity. */onExperimentalRead?: () => Promise<PairOutcome>onExperimentalWrite?: (body: unknown) => Promise<PairOutcome>- /** GET /api/zoo — the account's daemons and eggs (daemons/README.md); proxied like the desk. */- onZooRead?: () => Promise<PairOutcome>- /** POST /api/zoo/ops — habits, hatches, pair and nickname, applied on the backend (its routes/zoo.ts),- * which alone draws; a local write, so CSRF-guarded like the desk's ops. */- onZooOps?: (body: unknown) => Promise<PairOutcome>/** /api/store/* — proxy the Harness Store's ratings and reviews to backend the same way: reads* ungated like the machine list, writes (PUT/DELETE) CSRF-guarded like a rename. See storeProxy.ts. */onStore?: StoreHandler@@ -195,7 +164,7 @@ const MAX_HOOK_BODY_BYTES = 256 * 1024const HOOK_BODY_FIELDS = new Set(['engine', 'launcherId', 'sessionId', 'transcriptPath', 'cwd', 'source', 'tmuxPane', 'title', 'model','cliVersion', 'runtimeHints', 'callerPid', 'hookEvent', 'pluginVersion', 'reason', 'status', 'toolUseId',- 'toolName', 'input', 'prompt', 'memoryReceiptId',+ 'toolName', 'input', 'prompt',])function optionalBoundedString(value: unknown, max: number): boolean {@@ -229,7 +198,6 @@ function validHookBody(value: unknown): value is BoundHookBody {|| !optionalBoundedString(body.status, 100)|| !optionalBoundedString(body.toolUseId, 200)|| !optionalBoundedString(body.toolName, 200)- || !optionalBoundedString(body.memoryReceiptId, 36)|| !optionalBoundedJson(body.input, 128 * 1024)) return falseif (body.callerPid !== undefined&& (!Number.isSafeInteger(body.callerPid) || (body.callerPid as number) <= 0)) return false@@ -286,7 +254,6 @@ function normalizedRuntimeHints(body: RegisterInput): HookTerminalHint[] {}type BoundHookBody = RegisterInput & {- memoryReceiptId?: stringprompt?: stringsessionId?: stringreason?: string@@ -592,60 +559,10 @@ export function startHookServer(}console.log(`[hooks] ${sid(result.entry.sessionId)} ${body.hookEvent ?? 'session-start'} · engine=${result.entry.engine} · isNew=${result.isNew}`)handlers.onRegistered(result.entry, { isNew: result.isNew, evicted: result.evicted, rebound: result.rebound, orphaned: result.orphaned, hookEvent: body.hookEvent })- const context = body.hookEvent === 'UserPromptSubmit' && (engine === 'claude' || engine === 'codex') && handlers.onPromptContext- ? await boundedPromptContext(() => handlers.onPromptContext!(result.entry.agentId, body.prompt ?? '')) : null- json(200, { ok: true, ...context })+ json(200, { ok: true })return}- if (req.method === 'POST' && url === '/api/hook/opencode-memory-runtime') {- if (!hookOk) { json(401, { error: 'UNAUTHORIZED' }); return }- let body: BoundHookBody- try {- const parsed: unknown = JSON.parse(await readBody(req))- if (!validHookBody(parsed) || parsed.engine !== 'opencode' || !parsed.callerPid- || !optionalBoundedJson(parsed.input, 50_000)) { json(400, { error: 'invalid hook body' }); return }- body = parsed- } catch { json(400, { error: 'bad json' }); return }- // Unlike discovery fallback, credentials always require the host's live ancestry resolver.- const agent = handlers.resolveHookAgent ? await verifiedBoundMutation(body, handlers) : null- if (!agent?.processIdentity) { json(403, { error: 'UNBOUND_HOOK' }); return }- json(200, handlers.onOpenCodeMemoryRuntime?.(agent, body.input) ?? { observe: false }); return- }-- if (req.method === 'POST' && url === '/api/hook/memory-context') {- if (!hookOk) { json(401, { error: 'UNAUTHORIZED' }); return }- let body: BoundHookBody- try {- const parsed: unknown = JSON.parse(await readBody(req))- if (!validHookBody(parsed) || !['claude', 'codex', 'opencode'].includes(parsed.engine ?? '')- || !parsed.callerPid || !parsed.cliVersion || typeof parsed.prompt !== 'string'- || !parsed.prompt.trim() || parsed.prompt.length > 4_000) { json(400, { error: 'invalid hook body' }); return }- body = parsed- } catch { json(400, { error: 'bad json' }); return }- const agent = handlers.resolveHookAgent ? await verifiedBoundMutation(body, handlers) : null- if (!agent?.processIdentity) { json(403, { error: 'UNBOUND_HOOK' }); return }- const context = handlers.onMemoryContext ? await boundedPromptContext(() => handlers.onMemoryContext!(- agent.agentId, body.prompt!, { engine: agent.engine, cliVersion: body.cliVersion! })) : null- json(200, { ok: true, ...context }); return- }-- if (req.method === 'POST' && url === '/api/hook/memory-emitted') {- if (!hookOk) { json(401, { error: 'UNAUTHORIZED' }); return }- let body: BoundHookBody- try {- const parsed: unknown = JSON.parse(await readBody(req))- if (!validHookBody(parsed) || !/^[a-f0-9-]{36}$/.test(parsed.memoryReceiptId ?? '')- || !['claude', 'codex', 'opencode'].includes(parsed.engine ?? '')- || (parsed.engine === 'opencode' && !parsed.callerPid)) { json(400, { error: 'invalid hook body' }); return }- body = parsed- } catch { json(400, { error: 'bad json' }); return }- const agent = body.engine === 'opencode' && !handlers.resolveHookAgent ? null : await verifiedBoundMutation(body, handlers)- if (!agent || (body.engine === 'opencode' && !agent.processIdentity)) { json(403, { error: 'UNBOUND_HOOK' }); return }- const recorded = await handlers.onMemoryContextEmitted?.(agent.agentId, body.memoryReceiptId!).catch(() => false) ?? false- json(200, { ok: true, recorded, delivery: 'unverified' }); return- }-if (req.method === 'POST' && url === '/api/hook/session-end') {if (!hookOk) { json(401, { error: 'UNAUTHORIZED' }); return }let body: BoundHookBody@@ -890,20 +807,6 @@ export function startHookServer(try { body = JSON.parse(await readBody(req)) } catch { json(400, { error: { code: 'BAD_REQUEST', message: 'Invalid JSON body' } }); return }await proxied(() => handlers.onExperimentalWrite!(body)); return}- if (req.method === 'GET' && url === '/api/zoo') {- if (!handlers.onZooRead) { json(503, { error: 'UNAVAILABLE' }); return }- await proxied(handlers.onZooRead); return- }- if (req.method === 'POST' && url === '/api/zoo/ops') {- // Any local process that sets the header can send an op here, `zoo.autonomy` and `zoo.consent`- // included: the account's dial is only a REQUEST to each daemon, which acts above `suggest` only- // after the person confirms it at a window (pair/gate.ts, daemons/BRAIN.md "Security").- if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }- if (!handlers.onZooOps) { json(503, { error: 'UNAVAILABLE' }); return }- let body: unknown- try { body = JSON.parse(await readBody(req)) } catch { json(400, { error: { code: 'BAD_REQUEST', message: 'Invalid JSON body' } }); return }- await proxied(() => handlers.onZooOps!(body)); return- }if (req.method === 'GET' && url === '/api/auth/me') {const me = handlers.onAuthMeif (!me) { json(503, { error: 'UNAVAILABLE' }); return }diff --git a/cli/src/lib/agentHandoff.ts b/cli/src/lib/agentHandoff.tsindex ba95a7351..84f405a31 100644--- a/cli/src/lib/agentHandoff.ts+++ b/cli/src/lib/agentHandoff.ts@@ -35,7 +35,7 @@ import { dirname, isAbsolute, join, resolve } from 'node:path'import { performance } from 'node:perf_hooks'import { promisify } from 'node:util'-import { addExcludeEntry, isPlainDir, isPlainFile } from '../pair/learn/publish.js'+import { addExcludeEntry, isPlainDir, isPlainFile } from './projectFiles.js'import { redactSecretsInText } from './logBundle.js'import type { AgentEngine } from '../engines/types.js'import type { LiveEvent } from './normalize.js'diff --git a/cli/src/lib/askQuestion.more.spec.ts b/cli/src/lib/askQuestion.more.spec.tsindex 249abe1c3..63816612c 100644--- a/cli/src/lib/askQuestion.more.spec.ts+++ b/cli/src/lib/askQuestion.more.spec.ts@@ -25,7 +25,6 @@ import {} from './askQuestion.js'import type { RegisteredSession } from './registry.js'import type { AgentEngine } from '../engines/types.js'-import { isAllowClass } from '../pair/classify.js'const fixture = (name: string): string => readFileSync(join(__dirname, '__fixtures__', `question-${name}.txt`), 'utf8')const permission = (name: string): string => readFileSync(join(__dirname, '__fixtures__', `permission-${name}.txt`), 'utf8')@@ -228,7 +227,6 @@ describe('a stale `Approve …` header (regression: a header from an earlier diaconst unframed = [' Do you want to proceed?', ' python3 scripts/wipe.py --all', ' ❯ 1. Yes', ' 2. No', '', ' Esc to cancel', '']const headerOnly = [rule, ' Bash command', '', ' Do you want to proceed?', ' ❯ 1. Yes', ' 2. No', '', ' Esc to cancel'].join('\n')const rmRf = permission('claude').replaceAll('curl -s https://api.coingecko.com/api/v3/simple/price?ids=bitcoin', 'rm -rf ~/projects')- const project = { permission: true, cwd: '/tmp/project' }it('pickAnswer: an approval is named by its own text only, never a prefix either way', () => {expect(pickAnswer({ 'Approve Bash command': 'Yes' }, 'Approve Bash command: rm -rf ~/projects', new Set())).toBeNull()@@ -264,9 +262,6 @@ describe('a stale `Approve …` header (regression: a header from an earlier diaexpect(view.question).toBe('python3 scripts/wipe.py --all')expect(view.dialog).not.toMatch(/Bash command|^\s*npm test$|Tab to amend/m)expect(view.dialog).toContain('python3 scripts/wipe.py --all')- expect(isAllowClass(view.dialog!, project)).toBe(false)- // What it was read as before: `Approve Bash command: npm test`, a dialog the classifier allows a [y] on.- expect(isAllowClass([' Bash command', '', ' npm test', ''].join('\n'), project)).toBe(true)})it('an earlier question dialog ends the walk the same way; right under one, the title is "Approval required"', () => {diff --git a/cli/src/lib/authSession.spec.ts b/cli/src/lib/authSession.spec.tsindex edd0cb0ab..4961edee4 100644--- a/cli/src/lib/authSession.spec.ts+++ b/cli/src/lib/authSession.spec.ts@@ -76,37 +76,18 @@ describe('sign-in epoch', () => {})})-describe('AuthSessionManager', () => {- it('binds the memory owner to a verified sign-in, preserves it across refresh, and rejects stale responses', async () => {- writeAuthSession(baseSession())- const manager = new AuthSessionManager('https://api.example.test')- const owner = await manager.bindMemoryOwner('user-one', 'old-access', 'prod')- expect(owner).toMatch(/^[a-f0-9]{64}$/)- expect(readAuthSession()?.memoryOwner?.key).toBe(owner)- vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockResolvedValue(new Response(JSON.stringify({- success: true, data: { token: 'refreshed-access', refreshToken: 'refreshed-refresh', expiresIn: 3600 },- }))))- await manager.accessToken()- expect(readAuthSession()?.memoryOwner?.key).toBe(owner)- expect(await manager.bindMemoryOwner('another-user', 'old-access', 'prod')).toBeNull()- expect(readAuthSession()?.memoryOwner?.key).toBe(owner)- const signedIn = readAuthSession()!- writeAuthSession({ ...signedIn, accessToken: 'different-login' })- expect(readAuthSession()?.memoryOwner).toBeUndefined()- expect(await manager.bindMemoryOwner('user-two', 'different-login', 'prod')).not.toBe(owner)- })+it('reads a legacy session without interpreting optional metadata or rewriting the sign-in', async () => {+ const saved = { ...baseSession(), memoryOwner: { profileId: 'legacy-preview', owner: 'fixture' },+ futureMetadata: { value: 'preserved-on-disk' } }+ await writeFile(AUTH_SESSION_FILE, JSON.stringify(saved), { mode: 0o600 })+ const bytes = await readFile(AUTH_SESSION_FILE, 'utf8')+ expect(readAuthSession()).toMatchObject({ accessToken: saved.accessToken, refreshToken: saved.refreshToken,+ computerId: saved.computerId, machineId: saved.machineId })+ expect(readAuthSession()).not.toHaveProperty('memoryOwner')+ expect(await readFile(AUTH_SESSION_FILE, 'utf8')).toBe(bytes)+})- it('does not reuse the same memory owner across server environments or after sign-out', async () => {- writeAuthSession(baseSession())- const manager = new AuthSessionManager('https://api.example.test')- const owner = await manager.bindMemoryOwner('user-one', 'old-access', 'prod')- writeAuthSession({ ...readAuthSession()!, autonomousEnv: 'stag' })- expect(readAuthSession()?.memoryOwner).toBeUndefined()- expect(await manager.bindMemoryOwner('user-one', 'old-access', 'prod')).toBeNull()- expect(await manager.bindMemoryOwner('user-one', 'old-access', 'stag')).not.toBe(owner)- clearAuthSession()- expect(await manager.bindMemoryOwner('user-one', 'old-access', 'stag')).toBeNull()- })+describe('AuthSessionManager', () => {it('coalesces concurrent expired-token refreshes into one request and persists the rotated tokens', async () => {writeAuthSession(baseSession())diff --git a/cli/src/lib/authSession.ts b/cli/src/lib/authSession.tsindex 206ad8706..06fa4ef3f 100644--- a/cli/src/lib/authSession.ts+++ b/cli/src/lib/authSession.ts@@ -1,7 +1,7 @@import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'fs'import { homedir } from 'os'import { join } from 'path'-import { createHash, randomBytes } from 'node:crypto'+import { randomBytes } from 'node:crypto'export interface AuthSession {version: 1@@ -18,8 +18,6 @@ export interface AuthSession {* A refresh has to name the same one. Absent is the backend's configured client. */clientId?: SsoClientIdupdatedAt: number- /** Opaque local knowledge owner, learned from authenticated /auth/me, bound to this sign-in. */- memoryOwner?: { key: string; binding: string }/** Which sign-in by hand this session is: minted here when the person signs in, never anything the* backend sends — the device key log keeps its marks per sign-in (deviceLogSyncer `signIn`). */signInEpoch?: string@@ -71,9 +69,6 @@ function parse(raw: string): AuthSession | null {...(value.method === 'qr' || value.method === 'sso' ? { method: value.method } : {}),...(knownSsoClientId(value.clientId) ? { clientId: knownSsoClientId(value.clientId) } : {}),updatedAt: typeof value.updatedAt === 'number' ? value.updatedAt : 0,- ...(value.memoryOwner && /^[a-f0-9]{64}$/.test(value.memoryOwner.key)- && value.memoryOwner.binding === memoryOwnerBinding(value.accessToken, value.autonomousEnv)- ? { memoryOwner: value.memoryOwner } : {}),...(typeof value.signInEpoch === 'string' && value.signInEpoch ? { signInEpoch: value.signInEpoch } : {}),}} catch { return null }@@ -109,10 +104,6 @@ export function signInOf(epoch: string | undefined | null): { epoch: string; adoreturn { epoch, adopted: epoch.startsWith(ADOPTED_SIGN_IN), at: at ? Number(at[1]) : null }}-function memoryOwnerBinding(token: string, environment: AuthSession['autonomousEnv']): string {- return createHash('sha256').update(JSON.stringify(['memory-owner-binding-v1', environment, token])).digest('hex')-}-export function readAuthSession(): AuthSession | null {try { return parse(readFileSync(AUTH_SESSION_FILE, 'utf8')) } catch { return null }}@@ -295,8 +286,6 @@ export class AuthSessionManager {...(refreshed.refreshToken ? { refreshToken: refreshed.refreshToken } : {}),...(refreshed.expiresIn ? { expiresAt: Date.now() + refreshed.expiresIn * 1000 } : {}),updatedAt: Date.now(),- ...(latest.memoryOwner ? { memoryOwner: { key: latest.memoryOwner.key,- binding: memoryOwnerBinding(refreshed.token, latest.autonomousEnv) } } : {}),}writeAuthSession(next)return next.accessToken@@ -314,17 +303,4 @@ export class AuthSessionManager {if (!current || current.machineId === machineId) returnwriteAuthSession({ ...current, machineId, updatedAt: Date.now() })}-- /** A host-observed authenticated response, never an identity supplied by an agent or viewer. */- async bindMemoryOwner(ownerId: string, expectedToken: string, environment: AuthSession['autonomousEnv']): Promise<string | null> {- if (!ownerId || ownerId.length > 200 || /[\x00-\x1f\x7f]/.test(ownerId)) return null- return withLock(async () => {- const latest = readAuthSession()- if (!latest || latest.accessToken !== expectedToken || latest.autonomousEnv !== environment) return null- const key = createHash('sha256').update(JSON.stringify(['harness-memory-profile-v1', environment, ownerId])).digest('hex')- if (latest.memoryOwner?.key !== key) writeAuthSession({ ...latest,- memoryOwner: { key, binding: memoryOwnerBinding(latest.accessToken, latest.autonomousEnv) } })- return key- })- }}diff --git a/cli/src/lib/clientSocket.ts b/cli/src/lib/clientSocket.tsnew file mode 100644index 000000000..242bace6e--- /dev/null+++ b/cli/src/lib/clientSocket.ts@@ -0,0 +1,9 @@+/** Minimal transport used by command clients. No feature implementation belongs here. */+export interface ClientSocket {+ send(data: string): void+ close(): void+ on(event: 'open', listener: () => void): unknown+ on(event: 'message', listener: (data: { toString(): string }) => void): unknown+ on(event: 'close', listener: (code: number, reason: { toString(): string }) => void): unknown+ on(event: 'error', listener: (error: Error) => void): unknown+}diff --git a/cli/src/lib/commander.spec.ts b/cli/src/lib/commander.spec.tsindex f6f0a6d87..92d9c676d 100644--- a/cli/src/lib/commander.spec.ts+++ b/cli/src/lib/commander.spec.ts@@ -388,14 +388,12 @@ describe('CommanderMirror recap events', () => {expect(mirror.recent('session-off', 1)).toHaveLength(0)})- it('alwaysGenerate may be a switch read per turn (the pair brain), and onSummary sees each stored recap', async () => {- let pairing = false- const summaries: Array<[string, { recap: string; body: string }]> = []+ it('reads the alwaysGenerate setting for each turn', async () => {+ let enabled = falseconst mirror = new CommanderMirror({send: () => {}, sendWeb: () => {},hasDevice: () => false,- alwaysGenerate: () => pairing,- onSummary: (sessionId, summary) => summaries.push([sessionId, summary]),+ alwaysGenerate: () => enabled,summarize: async () => 'Fixed the flaky test\n\nPinned the clock in billing.spec.ts.',dataDir,})@@ -404,15 +402,15 @@ describe('CommanderMirror recap events', () => {{ type: 'text_delta', payload: { content: 'done' } },{ type: 'turn_ended', payload: {} },] as LiveEvent[]- mirror.ingest(turn, 'session-pair')+ mirror.ingest(turn, 'session-setting')await vi.runAllTimersAsync()await Promise.resolve()- expect(summaries).toHaveLength(0)- pairing = true- mirror.ingest(turn, 'session-pair')+ expect(mirror.recent('session-setting', 1)).toHaveLength(0)+ enabled = true+ mirror.ingest(turn, 'session-setting')await vi.runAllTimersAsync()await Promise.resolve()- expect(summaries).toEqual([['session-pair', { recap: 'Fixed the flaky test', body: 'Pinned the clock in billing.spec.ts.' }]])+ expect(mirror.recent('session-setting', 1)).toMatchObject([{ recap: 'Fixed the flaky test', text: 'Pinned the clock in billing.spec.ts.' }])})it('runs the recap once when a turn closes twice (Stop hook + watcher race)', async () => {@@ -785,20 +783,3 @@ describe('CommanderMirror keeps the complete final answer beside the clipped oneexpect(Buffer.from(full, 'utf8').toString('utf8')).toBe(full)})})--describe('CommanderMirror keeps the open tool calls for the pair\'s floor', () => {- it('a call is open from its tool_start to its tool_end, and a turn boundary clears them all', () => {- const dir = mkdtempSync(join(tmpdir(), 'adapter-commander-tools-'))- const mirror = new CommanderMirror({ send: () => {}, sendWeb: () => {}, hasDevice: () => false, summarize: async () => null, dataDir: dir })- mirror.ingest([- { type: 'turn_started', payload: { userMessage: 'test it' } },- { type: 'tool_start', payload: { id: 't1', tool: 'Bash', input: { command: 'npm test', description: 'Run the tests' } } },- { type: 'tool_start', payload: { id: 't2', tool: 'Read', input: { file_path: '/w/a.ts' } } },- { type: 'tool_end', payload: { id: 't2', tool: 'Read', output: '', isError: false, summary: '' } },- ] as LiveEvent[], 's1')- expect(mirror.openTools('s1')).toEqual([{ name: 'Bash', input: { command: 'npm test', description: 'Run the tests' } }])- mirror.ingest([{ type: 'turn_ended', payload: {} }] as LiveEvent[], 's1')- expect(mirror.openTools('s1')).toEqual([])- rmSync(dir, { recursive: true, force: true })- })-})diff --git a/cli/src/lib/commander.ts b/cli/src/lib/commander.tsindex a835af804..52c6129fd 100644--- a/cli/src/lib/commander.ts+++ b/cli/src/lib/commander.ts@@ -84,10 +84,8 @@ export interface CommanderMirrorOpts {subagentActive?: (sessionId: string, agentId: string) => booleandataDir: stringrecapForce?: boolean- /** A function when it can change while the daemon runs — the pair brain switches it on with pairing. */+ /** A function when the setting can change while the daemon runs. */alwaysGenerate?: boolean | (() => boolean)- /** Every recap that is stored, as it is stored — the pair sensor journals it (pair/sensor.ts). */- onSummary?: (sessionId: string, summary: { recap: string; body: string }) => void}interface SessionState {@@ -376,35 +374,11 @@ export class CommanderMirror {;(isError ? console.error : console.log)(`[recap] ${line}`)}- /**- * Tool calls started and not yet answered, per session, exactly as the transcript has them: the pair's- * floor (pair/classify.ts) reads a permission prompt from the call it is about, not from its wrapped paint.- */- private readonly toolCalls = new Map<string, Map<string, { name: string; input: unknown }>>()-- /** The session's open tool calls (started, no result yet), oldest first. */- openTools(sessionId: string): Array<{ name: string; input: unknown }> {- return [...(this.toolCalls.get(sessionId)?.values() ?? [])]- }-- private trackTool(sessionId: string, e: LiveEvent): void {- if (e.type === 'turn_started' || e.type === 'turn_ended') { this.toolCalls.delete(sessionId); return }- if (e.type === 'tool_start') {- let open = this.toolCalls.get(sessionId)- if (!open) { open = new Map(); this.toolCalls.set(sessionId, open) }- open.set(String(e.payload.id), { name: String(e.payload.tool || ''), input: e.payload.input })- if (open.size > 32) open.delete(open.keys().next().value as string)- } else if (e.type === 'tool_end') {- this.toolCalls.get(sessionId)?.delete(String(e.payload.id))- }- }-/** Fold one session's LiveEvents into device commander_event frames (live cards + async recap). */ingest(events: LiveEvent[], sessionId: string, options?: { replay?: boolean }): void {const st = this.stateFor(sessionId)if (!options?.replay && st.turnOpen) this.notifications.continued(sessionId)for (const e of events) {- this.trackTool(sessionId, e)switch (e.type) {case 'turn_started':this.notifications.started(sessionId, options?.replay)@@ -770,7 +744,6 @@ export class CommanderMirror {const { recap, body } = splitSummary(summary)const notification = this.notifications.completed(sessionId, body || recap,(this.opts.isSubagent?.(sessionId) ?? false) || st.abandoned)- try { this.opts.onSummary?.(sessionId, { recap, body }) } catch { /* an observer never costs the recap */ }this.trace(sessionId, `${sid} done in ${ms}ms · recap="${recap}" · bodyLen=${body.length}`)this.emit(sessionId, { kind: 'done', text: 'done' })// One decision feeds both clients. A silent recap still updates the@@ -961,7 +934,6 @@ export class CommanderMirror {// The state object is about to be dropped; a held turn-end timer would fire against a dead session.if (st) this.clearEndTimers(st)this.states.delete(sessionId)- this.toolCalls.delete(sessionId)// NB: intentionally do NOT delete this.summaries[sessionId] — reuse it on the next resume.this.emit(sessionId, { kind: 'done', text: 'done' })}diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.tsindex fc5da6eab..0427cd962 100644--- a/cli/src/lib/hooks.ts+++ b/cli/src/lib/hooks.ts@@ -15,8 +15,6 @@ import { VERSION } from '../version.js'import { hermesConfigHomes } from '../engines/hermes/home.js'import { opencodeMajorVersion } from '../engines/opencode/version.js'import { managedNodePath } from './nodeRuntime.js'-import { opencodeMemoryPluginSource } from './opencodeMemoryPlugin.js'-import { opencodeRecallPluginSource } from './opencodeRecallPlugin.js'const SETTINGS_PATH = join(homedir(), '.claude', 'settings.json')const GROK_HOOKS_PATH = join(env.GROK_HOME, 'hooks', 'harness.json')@@ -451,12 +449,7 @@ export const MachineRegister = async ({ directory, worktree, project, client })})} catch {}}-${engine === 'opencode' ? opencodeMemoryPluginSource(port) : ''}-${engine === 'opencode' ? opencodeRecallPluginSource(port) : ''}return {- ${engine === 'opencode' ? `"chat.message": async (input, output) => { await memoryMessage(input, output); await recallMessage(input, output) },- "chat.params": memoryParams, "experimental.chat.messages.transform": recallTransform,- "experimental.session.compacting": recallCompacting, "experimental.compaction.autocontinue": recallAutoContinue,` : ''}event: async ({ event }) => {if (!event) returnif (event.type === "session.created" || event.type === "session.updated") {diff --git a/cli/src/lib/projectFiles.spec.ts b/cli/src/lib/projectFiles.spec.tsnew file mode 100644index 000000000..450ae6b50--- /dev/null+++ b/cli/src/lib/projectFiles.spec.ts@@ -0,0 +1,52 @@+import { afterEach, expect, it } from 'vitest'+import { mkdtempSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { tmpdir } from 'node:os'+import { addExcludeEntry, isLink, isPlainDir, isPlainFile } from './projectFiles.js'++const roots: string[] = []+const fixture = () => { const root = mkdtempSync(join(tmpdir(), 'project-files-')); roots.push(root); return root }+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })+const entry = { pattern: '**/.harness/handoff/', comment: 'Private handoff files' }++it('distinguishes files, directories, missing paths and live/dangling symlinks', () => {+ const root = fixture(), file = join(root, 'file'), missing = join(root, 'missing')+ writeFileSync(file, '')+ symlinkSync(file, join(root, 'file-link'))+ symlinkSync(root, join(root, 'dir-link'))+ symlinkSync(missing, join(root, 'dangling'))+ expect(isPlainFile(file)).toBe(true)+ expect(isPlainDir(root)).toBe(true)+ expect(isPlainFile(root)).toBe(false)+ expect(isPlainDir(file)).toBe(false)+ for (const path of [missing, join(root, 'file-link'), join(root, 'dir-link'), join(root, 'dangling')]) {+ expect(isPlainFile(path)).toBe(false)+ expect(isPlainDir(path)).toBe(false)+ expect(isLink(path)).toBe(path !== missing)+ }+ expect(isLink(file)).toBe(false)+})++it.each(['', 'existing', 'existing\n', ` ${entry.pattern} \n`])('preserves existing exclude contents %j and adds at most one entry', text => {+ const root = fixture(), file = join(root, 'exclude')+ writeFileSync(file, text)+ expect(addExcludeEntry(file, entry)).toBe(file)+ const result = readFileSync(file, 'utf8')+ expect(result.startsWith(text)).toBe(true)+ expect(result.split('\n').filter(line => line.trim() === entry.pattern)).toHaveLength(1)+ expect(addExcludeEntry(file, entry)).toBe(file)+ expect(readFileSync(file, 'utf8')).toBe(result)+})++it('creates a missing parent and refuses linked files or parents without changing their targets', () => {+ const root = fixture(), file = join(root, 'info', 'exclude')+ expect(addExcludeEntry(file, entry)).toBe(file)+ const original = readFileSync(file, 'utf8')+ symlinkSync(file, join(root, 'linked-file'))+ symlinkSync(join(root, 'info'), join(root, 'linked-info'))+ expect(addExcludeEntry(join(root, 'linked-file'), { pattern: 'other', comment: '' })).toBeNull()+ expect(addExcludeEntry(join(root, 'linked-info', 'exclude'), { pattern: 'other', comment: '' })).toBeNull()+ expect(readFileSync(file, 'utf8')).toBe(original)+ mkdirSync(join(root, 'directory-exclude'))+ expect(() => addExcludeEntry(join(root, 'directory-exclude'), entry)).toThrow()+})diff --git a/cli/src/lib/projectFiles.ts b/cli/src/lib/projectFiles.tsnew file mode 100644index 000000000..9ee4bb63c--- /dev/null+++ b/cli/src/lib/projectFiles.ts@@ -0,0 +1,25 @@+/** Plain project-file helpers shared by core handoffs and optional publishers. */+import { appendFileSync, existsSync, lstatSync, mkdirSync, readFileSync } from 'node:fs'+import { join } from 'node:path'++export function isPlainFile(path: string): boolean {+ try { const stat = lstatSync(path); return stat.isFile() && !stat.isSymbolicLink() } catch { return false }+}++export function isPlainDir(path: string): boolean {+ try { const stat = lstatSync(path); return stat.isDirectory() && !stat.isSymbolicLink() } catch { return false }+}++export function isLink(path: string): boolean {+ try { return lstatSync(path).isSymbolicLink() } catch { return false }+}++/** Add one exclude entry without following a linked file or parent directory. */+export function addExcludeEntry(file: string, entry: { pattern: string; comment: string }): string | null {+ if (isLink(file) || isLink(join(file, '..'))) return null+ const text = existsSync(file) ? readFileSync(file, 'utf8') : ''+ if (text.split('\n').some((line) => line.trim() === entry.pattern)) return file+ mkdirSync(join(file, '..'), { recursive: true })+ appendFileSync(file, `${text && !text.endsWith('\n') ? '\n' : ''}# ${entry.comment}\n${entry.pattern}\n`)+ return file+}diff --git a/cli/src/lib/sessionSync.ts b/cli/src/lib/sessionSync.tsindex 80903defc..b83d9be8f 100644--- a/cli/src/lib/sessionSync.ts+++ b/cli/src/lib/sessionSync.ts@@ -7,8 +7,8 @@ export interface SessionSyncDeps {project(session: RegisteredSession): Promise<AgentFrame>send(frame: { type: string; payload: Record<string, unknown> }): voidsendCommander(frame: { type: string; payload: Record<string, unknown> }): void- onUnavailable(agentId: string): void- onFailed(agentId: string, detail: string): void+ onUnavailable?(agentId: string): void+ onFailed?(agentId: string, detail: string): voidwarn(error: unknown): void}@@ -19,7 +19,7 @@ export function createSessionSync(deps: SessionSyncDeps) {// removes the old dial row explicitly while keeping the shell available to the app.const device = opts.device !== false && !isTerminalEngine(session.engine)if (!deps.terminalAvailable(session.agentId)) {- deps.onUnavailable(session.agentId)+ deps.onUnavailable?.(session.agentId)// load() clears terminal verification at every daemon start. Metadata can sync before// discovery restores it, so an app deletion here would permanently remove a live pane// from the shared desk. Only confirmed removal/retirement may send that deletion.@@ -27,7 +27,7 @@ export function createSessionSync(deps: SessionSyncDeps) {if (device) deps.sendCommander({ type: 'agent_deleted', payload: { agentId: session.agentId } })return}- if (session.launch?.state === 'failed') deps.onFailed(session.agentId, session.launch.detail ?? session.launch.error)+ if (session.launch?.state === 'failed') deps.onFailed?.(session.agentId, session.launch.detail ?? session.launch.error)try {const agent = await deps.project(session)const frame = { type: 'agent_synced', payload: { agent } }diff --git a/cli/src/localWsServer.spec.ts b/cli/src/localWsServer.spec.tsindex b290d4e5b..9c002b715 100644--- a/cli/src/localWsServer.spec.ts+++ b/cli/src/localWsServer.spec.ts@@ -834,116 +834,6 @@ describe('local CLI WebSocket', () => {return { unix: `ws+unix://${socketPath}:/api/local-ws`, tcp, open, cleanup }}- it('takes the pair brain\'s frames only over its own socket, and keys, talk and confirmations only from a window', async () => {- const backend = new FakeBackend()- const relayed: Frame[] = []- const relayPool = {- acquire: async (_machineId: string, _env: string, _select: Frame, sink: LocalClientSink) => {- sink.sendFrame({ type: 'connected', payload: { machineId: 'other-machine', e2ee: false } })- return { send: async (frame: Frame) => { relayed.push(frame) }, sendBinary: async () => {}, detach: () => {} }- },- acquireIsolated: async () => { throw new Error('unused') },- invalidate: () => {},- }- const got: Array<[string, Record<string, unknown>]> = []- const presence: Array<{ payload: Record<string, unknown>; ui: boolean }> = []- const w = await unixWorld(backend, {- autonomousEnv: 'test',- relayPool: relayPool as unknown as NonNullable<Parameters<typeof attachLocalWsServer>[1]['relayPool']>,- onDaemonAct: (_connId, payload, reply) => { got.push(['act', payload]); reply({ type: 'daemon_act_result', payload: { requestId: payload.requestId, ok: true } }) },- onDaemonTalk: (_connId, payload, reply) => { got.push(['talk', payload]); reply({ type: 'daemon_talk_result', payload: { requestId: payload.requestId, ok: true } }) },- onDaemonOpen: (_connId, payload, reply) => { got.push(['open', payload]); reply({ type: 'daemon_open_result', payload: { requestId: payload.requestId, ok: true } }) },- onDaemonConfirm: (_connId, payload, reply) => { got.push(['confirm', payload]); reply({ type: 'daemon_confirm_result', payload: { requestId: payload.requestId, ok: true } }) },- onDaemonShown: (_connId, payload) => { got.push(['shown', payload]) },- onDaemonPresence: (_connId, payload, meta) => { presence.push({ payload, ui: meta.ui }) },- })- try {- // A window on this machine, over the socket: every one of them reaches the brain.- const ws = await w.open(w.unix, { machineId })- ws.send(JSON.stringify({ type: 'daemon_presence', payload: { active: true, awayMs: 0 } }))- ws.send(JSON.stringify({ type: 'daemon_shown', payload: { id: 'need:x' } }))- let result = onceMessage(ws)- ws.send(JSON.stringify({ type: 'daemon_act', payload: { requestId: 'r1', id: 'need:x', choice: 'n' } }))- expect(await result).toEqual({ type: 'daemon_act_result', payload: { requestId: 'r1', ok: true } })- result = onceMessage(ws)- ws.send(JSON.stringify({ type: 'daemon_talk', payload: { requestId: 't1', text: 'what needs me?' } }))- expect(await result).toEqual({ type: 'daemon_talk_result', payload: { requestId: 't1', ok: true } })- result = onceMessage(ws)- ws.send(JSON.stringify({ type: 'daemon_confirm', payload: { requestId: 'c1', kind: 'autonomy', nonce: 'n1', accept: true } }))- expect(await result).toEqual({ type: 'daemon_confirm_result', payload: { requestId: 'c1', ok: true } })- result = onceMessage(ws)- ws.send(JSON.stringify({ type: 'daemon_open', payload: { requestId: 'o1', companionUid: 'tim-one' } }))- expect(await result).toEqual({ type: 'daemon_open_result', payload: { requestId: 'o1', ok: true } })- expect(got.map(([kind]) => kind)).toEqual(['shown', 'act', 'talk', 'confirm', 'open'])- expect(presence).toEqual([{ payload: { active: true, awayMs: 0 }, ui: true }])- ws.close()-- // Over TCP — any user's process can reach it — none of them, and nothing is passed on.- const tcp = await w.open(w.tcp, { machineId })- tcp.send(JSON.stringify({ type: 'daemon_presence', payload: { active: false } }))- tcp.send(JSON.stringify({ type: 'daemon_shown', payload: { id: 'need:x' } }))- result = onceMessage(tcp)- tcp.send(JSON.stringify({ type: 'daemon_act', payload: { requestId: 'r2', id: 'need:x', choice: 'y' } }))- expect(await result).toMatchObject({ type: 'daemon_act_result', payload: { requestId: 'r2', id: 'need:x', ok: false, error: 'LOCAL_SOCKET_REQUIRED' } })- result = onceMessage(tcp)- tcp.send(JSON.stringify({ type: 'daemon_confirm', payload: { requestId: 'c2', kind: 'rules', nonce: 'n2' } }))- expect(await result).toMatchObject({ type: 'daemon_confirm_result', payload: { requestId: 'c2', kind: 'rules', nonce: 'n2', ok: false, error: 'LOCAL_SOCKET_REQUIRED' } })- result = onceMessage(tcp)- tcp.send(JSON.stringify({ type: 'daemon_open', payload: { requestId: 'blocked-open', companionUid: 'tim-one' } }))- expect(await result).toMatchObject({ type: 'daemon_open_result', payload: { ok: false, error: 'LOCAL_SOCKET_REQUIRED' } })- tcp.close()-- // A tool (`harness pair`, the MCP server) is not a window, even over the socket.- const tool = await w.open(w.unix, { machineId, tool: true })- result = onceMessage(tool)- tool.send(JSON.stringify({ type: 'daemon_talk', payload: { requestId: 't3', text: 'hi' } }))- expect(await result).toMatchObject({ type: 'daemon_talk_result', payload: { requestId: 't3', ok: false, error: 'UI_ONLY' } })- result = onceMessage(tool)- tool.send(JSON.stringify({ type: 'daemon_open', payload: { requestId: 'blocked-open', companionUid: 'tim-one' } }))- expect(await result).toMatchObject({ type: 'daemon_open_result', payload: { ok: false, error: 'UI_ONLY' } })- tool.close()-- // A relayed machine's socket: its presence is a fact about this desk; a key on it is not a window's.- const relay = await w.open(w.unix, { machineId: 'other-machine' })- relay.send(JSON.stringify({ type: 'daemon_presence', payload: { active: true } }))- result = onceMessage(relay)- relay.send(JSON.stringify({ type: 'daemon_act', payload: { requestId: 'r4', id: 'need:x', choice: 'y' } }))- expect(await result).toMatchObject({ type: 'daemon_act_result', payload: { requestId: 'r4', ok: false, error: 'UI_ONLY' } })- result = onceMessage(relay)- relay.send(JSON.stringify({ type: 'daemon_open', payload: { requestId: 'blocked-open', companionUid: 'tim-one' } }))- expect(await result).toMatchObject({ type: 'daemon_open_result', payload: { ok: false, error: 'UI_ONLY' } })- relay.close()-- expect(got.map(([kind]) => kind)).toEqual(['shown', 'act', 'talk', 'confirm', 'open'])- expect(presence.map((p) => p.ui)).toEqual([true, false])- // Neither this daemon's dispatcher (whose send() uploads) nor the relayed machine ever saw one.- expect(backend.frames).toEqual([])- expect(relayed).toEqual([])- } finally {- await w.cleanup()- }- })-- it('serves individual art on the private socket and refuses it on TCP', async () => {- const backend = new FakeBackend()- const called = vi.fn((_connId, payload, reply) => reply({ type: 'daemon_plate', payload: { requestId: payload.requestId, frames: [{ rows: 'o', mats: '.' }] } }))- const w = await unixWorld(backend, { onDaemonPlate: called })- try {- const socket = await w.open(w.unix, { machineId })- let result = onceMessage(socket)- socket.send(JSON.stringify({ type: 'daemon_plate_get', payload: { requestId: 'art' } }))- expect(await result).toMatchObject({ type: 'daemon_plate', payload: { requestId: 'art', frames: [{ rows: 'o', mats: '.' }] } })- const tcp = await w.open(w.tcp, { machineId })- result = onceMessage(tcp)- tcp.send(JSON.stringify({ type: 'daemon_plate_get', payload: { requestId: 'tcp' } }))- expect(await result).toMatchObject({ type: 'daemon_plate', payload: { requestId: 'tcp', error: 'LOCAL_SOCKET_REQUIRED' } })- expect(called).toHaveBeenCalledOnce()- expect(backend.frames).toEqual([])- socket.close()- tcp.close()- } finally { await w.cleanup() }- })-it('answers daemon_act UNSUPPORTED when there is no pair brain, rather than passing it on', async () => {const backend = new FakeBackend()const w = await unixWorld(backend)diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.tsindex 4ad5371cf..eb1e39c2a 100644--- a/cli/src/localWsServer.ts+++ b/cli/src/localWsServer.ts@@ -16,7 +16,10 @@ import {type TerminalBinaryClear,} from './lib/terminalBinary.js'import { RelayConnectError, type RelaySession, type RemoteRelayPool } from './lib/remoteRelay.js'-import { DAEMON_IN_TYPES, DAEMON_PLATE, DAEMON_PLATE_GET } from './pair/protocol.js'+// Reserved retired feature frames: transport refusals only, no optional implementation.+const DAEMON_IN_TYPES = new Set(['daemon_act', 'daemon_presence', 'daemon_talk', 'daemon_open', 'daemon_shown', 'daemon_confirm'])+const DAEMON_PLATE_GET = 'daemon_plate_get'+const DAEMON_PLATE = 'daemon_plate'export const LOCAL_WS_PATH = '/api/local-ws'export const LOCAL_WS_PROTOCOL_VERSION = 1@@ -118,39 +121,11 @@ export interface LocalWsServerOptions {* separate frame rather than a flag on the answer.*/onVoiceRouteReply?: (voiceId: string, reply: WindowVoiceReply) => void- /**- * The pair brain's frames from a window (pair/brain.ts, daemons/BRAIN.md "Security"): `daemon_act` (a key- * pressed on a daemon's line), `daemon_shown` (the window drew a line), `daemon_confirm` (the person said- * yes to a setting), `daemon_talk` (words to the pair harness) and `daemon_presence` (here, or away).- * Consumed like `app_focus` and never travel on. They are taken ONLY over the daemon's own Unix socket —- * never TCP (LOCAL_SOCKET_REQUIRED) — and all but presence only from a UI connection: a window bound to- * this machine, not a tool (`harness pair`, the MCP server) and not a relayed machine (UI_ONLY). Absent- * (no brain), a request answers UNSUPPORTED and the rest is dropped.- */- onDaemonAct?: (connId: string, payload: Record<string, unknown>, reply: (frame: Frame) => boolean) => void- /** `meta.ui`: a window bound to this machine (else a relayed machine's socket: its desk facts only). */- onDaemonPresence?: (connId: string, payload: Record<string, unknown>, meta: { ui: boolean }) => void- /** `daemon_talk { requestId, text }`: the person's words to their daemon (the pair harness) → `daemon_talk_result`. */- onDaemonTalk?: (connId: string, payload: Record<string, unknown>, reply: (frame: Frame) => boolean) => void- onDaemonOpen?: (connId: string, payload: Record<string, unknown>, reply: (frame: Frame) => boolean) => void- /** `daemon_shown { id }`: this window has displayed that line, detail and all. */- onDaemonShown?: (connId: string, payload: Record<string, unknown>) => void- /** `daemon_confirm { requestId, kind, nonce, accept }` → `daemon_confirm_result`. */- onDaemonConfirm?: (connId: string, payload: Record<string, unknown>, reply: (frame: Frame) => boolean) => void- /**- * `daemon_plate_get { requestId, uid, id, seed, size, version, mood }` → `daemon_plate` (pair/plateService.ts):- * an individual's art. Over the Unix socket only (LOCAL_SOCKET_REQUIRED on TCP), from any client there —- * it moves nothing. Answered here, never forwarded to a relayed machine: any computer draws any individual.- * Absent: `daemon_plate { requestId, error: 'UNSUPPORTED' }`.- */- onDaemonPlate?: (connId: string, payload: Record<string, unknown>, reply: (frame: Frame) => boolean) => voidonSelectionReply?: (connId: string, machineId: string, payload: Record<string, unknown>) => voidonVisitReply?: (connId: string, machineId: string, payload: Record<string, unknown>) => voidonFormReply?: (connId: string, machineId: string, payload: Record<string, unknown>) => void}-/** The pair brain's frames from a window (pair/protocol.ts DAEMON_IN_TYPES). */-const DAEMON_IN = DAEMON_IN_TYPES/** The reply each request among them gets. */const DAEMON_RESULT: Record<string, string> = { daemon_act: 'daemon_act_result', daemon_talk: 'daemon_talk_result', daemon_open: 'daemon_open_result', daemon_confirm: 'daemon_confirm_result' }@@ -195,11 +170,6 @@ export interface RouteAnswer {export interface LocalWsServer {close: () => Promise<void>- /**- * The caller's end of a loopback TCP connection: its port, so the daemon can find the process asking- * (pair/learn/approval.ts). Null over the daemon's Unix socket, or once the connection is gone.- */- peerPort: (connId: string) => number | null/** Exact local socket, including sockets viewing a remote machine; never relayed. */sendToWindow: (connId: string, frame: Frame) => boolean}@@ -342,14 +312,11 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerOconst servers = [server, ...(options.localSocketServer ? [options.localSocketServer] : [])]for (const each of servers) each.on('upgrade', onUpgrade)- const peers = new Map<string, number | null>()wss.on('connection', (ws, req: http.IncomingMessage) => {const connId = `local:${randomUUID()}`// Over the daemon's own Unix socket (0600, in a 0700 folder): this user's process, not any user's.const trusted = isTrustedLocal(req)- // The caller's loopback TCP port, so the daemon can find the process asking (pair/learn/approval.ts).- peers.set(connId, trusted ? null : req.socket.remotePort ?? null)- /** Introduced itself as a tool (`machine_select { tool: true }`): `harness pair`, the MCP server. */+ /** Introduced itself as a tool (`machine_select { tool: true }`), rather than a window. */let tool = falselet selected = false// Which machine THIS connection is bound to. The app opens one local socket per machine, so it is@@ -664,11 +631,10 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerOsink.sendFrame({ type: DAEMON_PLATE, payload: { requestId: payload.requestId, error, ...(detail ? { detail } : {}) } })}if (!trusted) { refuse('LOCAL_SOCKET_REQUIRED', 'The daemon takes these only over its own socket, never TCP.'); return }- if (!options.onDaemonPlate) { refuse('UNSUPPORTED'); return }- options.onDaemonPlate(connId, payload, (frame) => sink.sendFrame(frame))+ refuse('UNSUPPORTED')return}- if (!isBinary && parsed && typeof parsed.type === 'string' && DAEMON_IN.has(parsed.type)) {+ if (!isBinary && parsed && typeof parsed.type === 'string' && DAEMON_IN_TYPES.has(parsed.type)) {const type: string = parsed.typeconst payload = (parsed.payload && typeof parsed.payload === 'object' && !Array.isArray(parsed.payload)? parsed.payload : {}) as Record<string, unknown>@@ -685,12 +651,8 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerOif (!trusted) { answer({ ok: false, error: 'LOCAL_SOCKET_REQUIRED', detail: 'The daemon takes these only over its own socket, never TCP.' }); return }if (tool) { answer({ ok: false, error: 'UI_ONLY', detail: 'A tool is not a window: keys, talk and confirmations come from a window.' }); return }const ui = !relay && boundMachineId === options.machineId- if (type === 'daemon_presence') { options.onDaemonPresence?.(connId, payload, { ui }); return }- if (!ui) { answer({ ok: false, error: 'UI_ONLY', detail: 'Keys, talk and confirmations come from a window on this machine\'s own socket.' }); return }- const reply = (frame: Frame): boolean => sink.sendFrame(frame)- if (type === 'daemon_shown') { options.onDaemonShown?.(connId, payload); return }- const handler = type === 'daemon_act' ? options.onDaemonAct : type === 'daemon_talk' ? options.onDaemonTalk : type === 'daemon_open' ? options.onDaemonOpen : options.onDaemonConfirm- if (handler) { handler(connId, payload, reply); return }+ if (type === 'daemon_presence' || type === 'daemon_shown') return+ if (!ui) { answer({ ok: false, error: 'UI_ONLY' }); return }answer({ ok: false, error: 'UNSUPPORTED' })return}@@ -765,7 +727,6 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerO})const cleanup = (): void => {- peers.delete(connId)heartbeat.stop()const wasWindow = windowSinks.delete(connId)explicitFocusClients.delete(connId)@@ -785,7 +746,6 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerO})return {- peerPort: (connId) => peers.get(connId) ?? null,sendToWindow: (connId, frame) => windowSinks.get(connId)?.sendFrame(frame) ?? false,close: async () => {for (const each of servers) each.off('upgrade', onUpgrade)diff --git a/cli/src/pair/frames.spec.ts b/cli/src/pair/frames.spec.tsdeleted file mode 100644index a50fda646..000000000--- a/cli/src/pair/frames.spec.ts+++ /dev/null@@ -1,299 +0,0 @@-/**- * P0 — the pair brain's contract and sealing (daemons/BRAIN.md).- *- * The frames between two machines' daemons carry question text and recaps, and one of them keys an- * answer into a pane. Every one is sealed pairwise; the relay reads the outer type and nothing else, and- * nothing it writes in the clear is believed. Driven against the REAL E2eeManager and RelaySessionCrypto,- * so a type missing from applicationFrames.ts fails here rather than travelling plaintext.- */-import { afterEach, describe, expect, it, vi } from 'vitest'-import * as C from '../lib/e2ee/core.js'-import { RelaySessionCrypto } from '../lib/e2ee/relayClient.js'-import {- admitRelayedPairFrame, encryptDownFrame, encryptRpcResult, PAIR_PUSHES, PAIR_REQUESTS, PAIR_RESULTS, PLATE_REQUEST, PLATE_RESULT,-} from '../lib/e2ee/applicationFrames.js'-import { BackendSocket } from '../backendSocket.js'-import type { PairEvent, PairService, PairSnapshot } from './protocol.js'--type Frame = Record<string, unknown>--/** A paired peer (another machine's brain) with a live session on `socket`'s daemon. */-function pairedPeer(socket: BackendSocket, connId: string) {- const e2ee = socket.e2ee as unknown as { store: { addPaired: (pub: string, label: string, at: number, role: 'web') => void; getIdentity: () => C.Identity } }- const identity = C.newIdentity()- e2ee.store.addPaired(C.b64e(identity.pub), 'peer brain', Date.now(), 'web')- const sent: Array<{ connId: string; frame: Frame }> = []- vi.spyOn(socket, 'sendTo').mockImplementation((to: string, frame: Frame) => { sent.push({ connId: to, frame }) })- const crypto = new RelaySessionCrypto({ machineId: socket.machineId, selfIdentity: identity, peerPub: e2ee.store.getIdentity().pub })- socket.e2ee.handleFrame(connId, crypto.helloFrame())- const welcome = sent.pop()!- expect(welcome.frame.type).toBe('e2e_welcome')- expect(crypto.handleWelcome(welcome.frame.payload as Frame)).toBe(true)- return { crypto, sent }-}--const SNAPSHOT: PairSnapshot = {- machineId: 'machine-a', epoch: 'e1', seq: 3, rev: 7,- harnesses: [{ agentId: 'a1', name: 'api', engine: 'claude', working: true, failing: null, lastDoneAt: null, recap: null,- question: { requestId: 'q_1', text: 'Run the migration?', options: ['Yes', 'No'], multi: false, deny: false, allow: false, permission: false, since: 1 } }],-}--function fakeService(overrides: Partial<PairService> = {}): PairService & { pushes: Map<string, (e: PairEvent) => boolean> } {- const pushes = new Map<string, (e: PairEvent) => boolean>()- return {- pushes,- enabled: () => true,- watch: (connId, push) => { pushes.set(connId, push); return SNAPSHOT },- unwatch: (connId) => { pushes.delete(connId) },- journal: () => ({ epoch: 'e1', seq: 3, entries: [] }),- read: (payload) => ({ agentId: payload.agentId, recap: 'shipped the fix' }),- local: async (payload) => ({ verb: payload.verb, ok: true }),- ...overrides,- }-}--afterEach(() => vi.restoreAllMocks())--describe('pair frames are sealed application frames', () => {- it('seals individual-art requests and replies to their requesting connection', async () => {- const socket = new BackendSocket('token')- const { crypto, sent } = pairedPeer(socket, 'phone')- const payload = { uid: 'a'.repeat(24), id: 'tim', seed: 13, size: 'portrait', version: '0.1', mood: 'idle' }- const answer = { uid: payload.uid, size: 'portrait', version: '0.1', mood: 'idle', frames: [{ rows: 'o', mats: '.' }], frameMs: 170 }- socket.plateService = { get: vi.fn(async () => answer) }- const dispatch = (socket as unknown as { dispatchDown: (f: Frame, c: string, t?: string) => Promise<void> }).dispatchDown.bind(socket)- try {- expect(encryptDownFrame(PLATE_REQUEST)).toBe(true)- expect(encryptRpcResult(PLATE_RESULT)).toBe(true)- expect(admitRelayedPairFrame({ type: PLATE_RESULT, payload: answer })).toBe(false)- await dispatch({ type: PLATE_REQUEST, payload: { requestId: 'plain', ...payload } }, 'phone')- expect(socket.plateService.get).not.toHaveBeenCalled()- expect(crypto.unwrapIncoming(sent.shift()!.frame)).toMatchObject({ type: PLATE_RESULT, payload: { error: 'E2EE_REQUIRED' } })- await dispatch(crypto.wrapOutgoing({ type: PLATE_REQUEST, payload: { requestId: 'sealed', ...payload } }), 'phone')- await vi.waitFor(() => expect(sent.length).toBe(1))- const reply = sent.shift()!- expect(reply.connId).toBe('phone')- expect(reply.frame.type).toBe(PLATE_RESULT)- expect(reply.frame.payload).not.toHaveProperty('frames')- expect(crypto.unwrapIncoming(reply.frame)?.payload).toEqual({ requestId: 'sealed', ...answer })- await dispatch({ type: PLATE_REQUEST, payload: { requestId: 'tcp', ...payload } }, 'local', 'local')- expect(socket.plateService.get).toHaveBeenCalledTimes(1)- } finally { await socket.stop() }- })-- it('registers every request, result and push, and nothing else under pair_', () => {- expect([...PAIR_REQUESTS].sort()).toEqual(['pair_answer', 'pair_journal', 'pair_list', 'pair_pause', 'pair_read',- 'pair_resume', 'pair_send', 'pair_start', 'pair_stop', 'pair_watch'])- expect([...PAIR_PUSHES]).toEqual(['pair_event'])- for (const type of PAIR_REQUESTS) {- expect(encryptDownFrame(type)).toBe(true)- expect(encryptRpcResult(`${type}_result`)).toBe(true)- expect(PAIR_RESULTS.has(`${type}_result`)).toBe(true)- }- // The loopback `pair` is never sealed going down (it never leaves this computer) but its reply is,- // should a relayed one ever be answered LOCAL_ONLY.- expect(encryptDownFrame('pair')).toBe(false)- expect(encryptRpcResult('pair_result')).toBe(true)- })-- it('seals every pair request end to end; the relay sees only the type', async () => {- const socket = new BackendSocket('token')- const { crypto } = pairedPeer(socket, 'peer-1')- for (const type of PAIR_REQUESTS) {- const request = { requestId: `${type}-1`, agentId: 'a1', question: 'Run the migration?' }- const sealed = crypto.wrapOutgoing({ type, payload: request })- expect(JSON.stringify(sealed)).not.toContain('migration')- expect(sealed.payload).not.toHaveProperty('agentId')- expect(socket.e2ee.unwrapDown('peer-1', sealed)?.payload).toEqual(request)- }- await socket.stop()- })-- it('pair_event pushed with wrapTarget opens on the watching machine, and only there', async () => {- const socket = new BackendSocket('token')- const { crypto } = pairedPeer(socket, 'peer-1')- const event: PairEvent = { machineId: 'machine-a', rev: 8, agentId: 'a1', harness: SNAPSHOT.harnesses[0] }- const sealed = socket.e2ee.wrapTarget('peer-1', 'pair_event', event as unknown as Frame)!- expect(JSON.stringify(sealed)).not.toContain('migration')- expect(admitRelayedPairFrame(sealed)).toBe(true)- expect(crypto.unwrapIncoming(sealed)?.payload).toEqual(event)- // A connection with no session gets nothing at all rather than a plaintext push.- expect(socket.e2ee.wrapTarget('stranger', 'pair_event', event as unknown as Frame)).toBeNull()- await socket.stop()- })-- it('the watching machine believes no pair frame the relay wrote in the clear or under the group key', () => {- expect(admitRelayedPairFrame({ type: 'pair_event', payload: { machineId: 'm', harness: {} } })).toBe(false)- expect(admitRelayedPairFrame({ type: 'pair_watch_result', payload: { requestId: 'r', snapshot: SNAPSHOT } })).toBe(false)- expect(admitRelayedPairFrame({ type: 'pair_event', payload: { __e2e: { v: 1, k: 'g', n: 1, ct: 'x' } } })).toBe(false)- expect(admitRelayedPairFrame({ type: 'pair_event', payload: null })).toBe(false)- // An older daemon's bare refusal is the one plaintext pair frame heard: it names the machine as too old.- expect(admitRelayedPairFrame({ type: 'pair_watch_result', payload: { requestId: 'r', error: 'UNSUPPORTED' } })).toBe(true)- expect(admitRelayedPairFrame({ type: 'pair_event', payload: { requestId: 'r', error: 'UNSUPPORTED' } })).toBe(false)- })-})--describe('the daemon answering another machine\'s brain', () => {- function harness(service: PairService | null = fakeService()) {- const socket = new BackendSocket('token')- socket.pairService = service- const internals = socket as unknown as { dispatchDown: (f: Frame, c: string, t?: string) => Promise<void> }- return { socket, dispatch: (f: Frame, connId: string, transport: 'relay' | 'local' = 'relay') => internals.dispatchDown(f, connId, transport) }- }-- it.each([...PAIR_REQUESTS])('refuses a plaintext %s from the relay with E2EE_REQUIRED, and never reaches the sensor', async (type) => {- const service = fakeService()- const watch = vi.spyOn(service, 'watch')- const read = vi.spyOn(service, 'read')- const { socket, dispatch } = harness(service)- const replies: Frame[] = []- vi.spyOn(socket, 'sendTo').mockImplementation((_c: string, f: Frame) => { replies.push(f) })- await dispatch({ type, payload: { requestId: 'r1', agentId: 'a1' } }, 'web-1')- expect(watch).not.toHaveBeenCalled()- expect(read).not.toHaveBeenCalled()- expect(replies).toEqual([{ type: `${type}_result`, payload: { requestId: 'r1', error: 'E2EE_REQUIRED' } }])- await socket.stop()- })-- it('a sealed pair_watch answers the snapshot sealed, then pushes sealed pair_event to that watcher alone', async () => {- const service = fakeService()- const { socket, dispatch } = harness(service)- const { crypto, sent } = pairedPeer(socket, 'peer-1')- vi.spyOn(socket, 'isConnected').mockReturnValue(true)- await dispatch(crypto.wrapOutgoing({ type: 'pair_watch', payload: { requestId: 'w1' } }), 'peer-1')- const result = sent.shift()!- expect(result.connId).toBe('peer-1')- expect(JSON.stringify(result.frame)).not.toContain('migration')- expect(crypto.unwrapIncoming(result.frame)?.payload).toEqual({ requestId: 'w1', snapshot: SNAPSHOT })-- const push = service.pushes.get('peer-1')!- expect(push({ machineId: 'machine-a', rev: 9, agentId: 'a1', harness: null, removed: true })).toBe(true)- const pushed = sent.shift()!- expect(pushed).toMatchObject({ connId: 'peer-1', frame: { type: 'pair_event' } })- expect(crypto.unwrapIncoming(pushed.frame)?.payload).toMatchObject({ rev: 9, removed: true })-- // The watcher went away: its session is gone, so the next push says stop instead of going out plain.- await dispatch({ type: '__client_disconnected', payload: {} }, 'peer-1')- expect(service.pushes.has('peer-1')).toBe(false)- expect(push({ machineId: 'machine-a', rev: 10, agentId: 'a1', harness: null })).toBe(false)- await socket.stop()- })-- it('the writes and pair_list/pair_read go to the owning machine\'s floor, sealed both ways', async () => {- const { socket, dispatch } = harness()- const handled: Array<[string, Frame]> = []- socket.pairOwner = { handle: async (type, payload) => { handled.push([type, payload]); return type === 'pair_answer' ? { error: 'STALE_QUESTION', detail: 'changed' } : { ok: true } } }- const { crypto, sent } = pairedPeer(socket, 'peer-1')- await dispatch(crypto.wrapOutgoing({ type: 'pair_answer', payload: { requestId: 'r1', agentId: 'a1', expectRequestId: 'q1', choice: 'Yes', by: 'key' } }), 'peer-1')- await vi.waitFor(() => expect(sent.length).toBe(1))- const reply = sent.shift()!- expect(JSON.stringify(reply.frame)).not.toContain('STALE_QUESTION')- expect(crypto.unwrapIncoming(reply.frame)?.payload).toEqual({ requestId: 'r1', error: 'STALE_QUESTION', detail: 'changed' })- for (const type of ['pair_send', 'pair_stop', 'pair_start', 'pair_pause', 'pair_resume', 'pair_list', 'pair_read']) {- await dispatch(crypto.wrapOutgoing({ type, payload: { requestId: type, agentId: 'a1' } }), 'peer-1')- await vi.waitFor(() => expect(sent.length).toBe(1))- expect(crypto.unwrapIncoming(sent.shift()!.frame)?.payload).toEqual({ requestId: type, ok: true })- }- expect(handled.map(([type]) => type)).toEqual(['pair_answer', 'pair_send', 'pair_stop', 'pair_start', 'pair_pause', 'pair_resume', 'pair_list', 'pair_read'])- expect(handled[0][1]).toMatchObject({ agentId: 'a1', expectRequestId: 'q1', choice: 'Yes', by: 'key' })- await socket.stop()- })-- it('tells the owner where a request came from; a loopback pair_* is a local process posing as a machine, refused', async () => {- const { socket, dispatch } = harness()- const from: unknown[] = []- socket.pairOwner = { handle: async (_type, _payload, origin) => { from.push(origin); return { ok: true } } }- const { crypto, sent } = pairedPeer(socket, 'peer-1')- await dispatch(crypto.wrapOutgoing({ type: 'pair_answer', payload: { requestId: 'r1', agentId: 'a1', expectRequestId: 'q1', choice: 'Yes' } }), 'peer-1')- await vi.waitFor(() => expect(sent.length).toBe(1))- expect(from).toEqual([{ connId: 'peer-1', label: 'peer brain' }])- sent.length = 0- socket.registerLocalClient('local:script', { sendFrame: () => true, sendBinary: () => true })- for (const type of ['pair_answer', 'pair_send', 'pair_watch', 'pair_read']) {- await dispatch({ type, payload: { requestId: type, agentId: 'a1', expectRequestId: 'q1', choice: 'Yes', by: 'key' } }, 'local:script', 'local')- }- await vi.waitFor(() => expect(sent.length).toBe(4))- expect(sent.map((r) => [r.connId, (r.frame.payload as Frame).error])).toEqual([['local:script', 'REMOTE_ONLY'], ['local:script', 'REMOTE_ONLY'], ['local:script', 'REMOTE_ONLY'], ['local:script', 'REMOTE_ONLY']])- expect(from).toHaveLength(1)- await socket.unregisterLocalClient('local:script')- await socket.stop()- })-- it('pair_journal and pair_read answer sealed; the writes are UNSUPPORTED with no owner, like an older daemon', async () => {- const { socket, dispatch } = harness()- const { crypto, sent } = pairedPeer(socket, 'peer-1')- for (const [type, expected] of [- ['pair_journal', { epoch: 'e1', seq: 3, entries: [] }],- ['pair_read', { agentId: 'a1', recap: 'shipped the fix' }],- ['pair_answer', { error: 'UNSUPPORTED' }],- ['pair_pause', { error: 'UNSUPPORTED' }],- ] as const) {- await dispatch(crypto.wrapOutgoing({ type, payload: { requestId: type, agentId: 'a1', choice: 'Yes' } }), 'peer-1')- const reply = sent.shift()!- expect(reply.frame.type).toBe(`${type}_result`)- expect(crypto.unwrapIncoming(reply.frame)?.payload).toEqual({ requestId: type, ...expected })- }- await socket.stop()- })-- it('answers like an older daemon with no sensor, and PAIR_OFF while pairing is off', async () => {- for (const [service, error] of [[null, 'UNSUPPORTED'], [fakeService({ enabled: () => false }), 'PAIR_OFF']] as const) {- const { socket, dispatch } = harness(service)- const { crypto, sent } = pairedPeer(socket, 'peer-1')- await dispatch(crypto.wrapOutgoing({ type: 'pair_watch', payload: { requestId: 'w' } }), 'peer-1')- expect(crypto.unwrapIncoming(sent.shift()!.frame)?.payload).toEqual({ requestId: 'w', error })- await socket.stop()- }- })-- it('the `pair` request is local-only: a relayed one, even sealed, is refused without reaching the sensor', async () => {- const service = fakeService()- const local = vi.spyOn(service, 'local')- const { socket, dispatch } = harness(service)- const { crypto, sent } = pairedPeer(socket, 'peer-1')- // A client never seals `pair` (it is not a machine-to-machine type), so seal one by hand: a paired- // peer that goes out of its way to must still be refused.- const keys = crypto as unknown as { c2s: Uint8Array; c2sCounter: number }- const sealedPair = { type: 'pair', payload: C.wrapPayload(keys.c2s, 'p', keys.c2sCounter++, 'pair', undefined, { requestId: 'p1', verb: 'list' }) }- await dispatch(sealedPair, 'peer-1')- await dispatch({ type: 'pair', payload: { requestId: 'p2', verb: 'list' } }, 'peer-1')- expect(local).not.toHaveBeenCalled()- // Sealed or not, the relayed reply is a refusal, sealed to that connection — never a broadcast.- const refusals = sent.map(({ frame }) => crypto.unwrapIncoming(frame)?.payload)- expect(refusals).toContainEqual({ requestId: 'p1', error: 'LOCAL_ONLY', detail: 'Ask the pair brain on this computer.' })- expect(refusals).toContainEqual({ requestId: 'p2', error: 'E2EE_REQUIRED' })-- socket.registerLocalClient('local:window', { sendFrame: () => true, sendBinary: () => true })- socket.handleLocalFrame('local:window', { type: 'pair', payload: { requestId: 'p3', verb: 'list' } })- await vi.waitFor(() => expect(sent).toContainEqual({ connId: 'local:window', frame: { type: 'pair_result', payload: { requestId: 'p3', verb: 'list', ok: true } } }))- expect(local).toHaveBeenCalledTimes(1)- await socket.unregisterLocalClient('local:window')- await socket.stop()- })-- it('the `pair` request answers DAEMONS_OFF while daemons are off, before the control interface or the sensor', async () => {- const service = fakeService()- const local = vi.spyOn(service, 'local')- const { socket } = harness(service)- const control = vi.fn(async (payload: Record<string, unknown>) => ({ ok: true, verb: payload.verb }))- socket.pairControl = { verbs: new Set(['list_harnesses', 'lessons']), local: control }- let on = false- socket.daemonsOn = () => on- const sent: Array<{ connId: string; frame: Frame }> = []- vi.spyOn(socket, 'sendTo').mockImplementation((to: string, frame: Frame) => { sent.push({ connId: to, frame }) })- socket.registerLocalClient('local:tool', { sendFrame: () => true, sendBinary: () => true }, { tool: true })- for (const [requestId, verb] of [['p1', 'status'], ['p2', 'list_harnesses'], ['p3', 'lessons']]) {- socket.handleLocalFrame('local:tool', { type: 'pair', payload: { requestId, verb } })- }- await vi.waitFor(() => expect(sent).toHaveLength(3))- for (const { frame } of sent) expect((frame.payload as Frame).error).toBe('DAEMONS_OFF')- expect(local).not.toHaveBeenCalled()- expect(control).not.toHaveBeenCalled()- // On again: the verbs run as they always did.- on = true- socket.handleLocalFrame('local:tool', { type: 'pair', payload: { requestId: 'p4', verb: 'list_harnesses' } })- await vi.waitFor(() => expect(sent).toContainEqual({ connId: 'local:tool', frame: { type: 'pair_result', payload: { requestId: 'p4', ok: true, verb: 'list_harnesses' } } }))- await socket.unregisterLocalClient('local:tool')- await socket.stop()- })-})diff --git a/cli/vitest.setup.ts b/cli/vitest.setup.tsindex 8638d56ce..50097f6cf 100644--- a/cli/vitest.setup.ts+++ b/cli/vitest.setup.ts@@ -31,8 +31,6 @@ process.env.ZDOTDIR = process.env.ADAPTER_DATA_DIR// discover, refresh, or replace the developer's real Harness account session.process.env.HARNESS_AUTH_DIR = join(process.env.ADAPTER_DATA_DIR, 'auth')process.env.DSH_DIR = join(process.env.ADAPTER_DATA_DIR, 'dsh')-// The lessons folder defaults to ~/.harness/lessons: a spec must never write a lesson there.-process.env.HARNESS_LESSONS_DIR = join(process.env.ADAPTER_DATA_DIR, 'lessons')// The Store catalog is fetched from GitHub by dsh_list; a test must never depend on what that branch// holds today (a published catalog turned a fixture registry of two into the live shelf of 23).// Loopback port 9 refuses at once, so the live catalog falls back to the registry each test stubs.diff --git a/companions/README.md b/companions/README.mdnew file mode 100644index 000000000..2d3eb64a4--- /dev/null+++ b/companions/README.md@@ -0,0 +1,78 @@+# Optional Companions and Memory++This private package holds two subsystems extracted from the core Harness CLI.+It currently builds as libraries. It does not start itself, install hooks, open a+conversation, or connect the experimental desktop viewer. The core CLI can build+and run without installing this package.++| Directory | Owns |+| --- | --- |+| `src/companion` | Characters, collection state, growth, artwork, presentation and companion interaction. |+| `src/memory` | Coding observations, evidence, durable knowledge, review, recall, native inference adapters and the earlier shared-lesson store. |+| `src/application` | Explicit composition between the selected companion model and Memory; conversation review and lesson publication. |+| `src/shared` | Policy and bounded inference contracts used by both subsystems. |++Memory does not import Companions or the application layer. Companions may import+only Memory's public contract in `src/memory/api.ts`. The application layer joins+them. Import-boundary tests enforce that direction. Build checks reject imports+of core startup, configuration, authentication and running services. Some pure+helpers and types still come from CLI source at build time; the built artifacts+contain those helpers and do not import the installed CLI.++The package exports `@openharness/companions/companion`, `/memory` and+`/application`. Memory storage and artwork rendering run in their own bounded+workers when explicitly invoked. Core no longer embeds those workers, constructs+the feature services, adds recall to native hooks, or keeps a companion terminal+alive for learning.++## Build and test++Use the repository's pinned Node 22 runtime. From this directory:++```sh+npm ci --prefix ../cli --ignore-scripts+npm ci --ignore-scripts+npm run typecheck+npm run build+npm run test:bundle+npm test -- --maxWorkers=3+```++The CLI dependencies support typechecking the retained shared source helpers.+The package lock uses the same toolchain versions as the CLI. The bundle test+copies the built artifacts into a disposable folder with no core service or+source tree. It checks disabled-state inactivity, synthetic memory persistence,+recall scope and worker failure handling. It makes no model calls.++The retained `scripts/memory-*` evaluation and native probe scripts document the+previous integration. Several still expect its retired core endpoints or CLI+commands. They are not certification for this package's future integration and+are not run by its build or default test command.++## Remaining integration++Before enabling the companion experience again, the application layer needs:++- Startup and shutdown outside the core process, with explicit opt-in and stop.+- Verified user, project, session and selected-model inputs through supported+ client APIs, including revocation when consent or identity changes.+- Native recall delivery owned by the add-on, without changing core hook output+ or accepting unverified caller identities.+- Desktop, CLI/MCP and device clients connected to the optional application.+ Device presentation must respect ordinary status, notifications and questions.+- A real sourced-memory check across conversations, including companion switching+ without losing the collection conversation or the user's knowledge.++Core rejects the old optional requests as unsupported, preserving their existing+local-only and encryption restrictions. Browser pairing via `harness pair <code>`+remains a core command; the former companion `harness pair <verb>` commands are+disconnected. Brightness and ordinary device settings remain core transport.++The extraction retains storage formats and development-data paths. It does not+copy, delete or rewrite saved memories, consent, collection state or conversations.+An application host must supply verified scope before opening those stores; the+libraries do not constitute that authorization boundary by themselves.++See the [extraction plan](../docs/plans/2026-10-03-memory-companion-isolation.md)+for the complete acceptance criteria. A passing package suite does not mean the+companion-memory MVP is working in the app.diff --git a/companions/build.mjs b/companions/build.mjsnew file mode 100644index 000000000..44f9c26ec--- /dev/null+++ b/companions/build.mjs@@ -0,0 +1,25 @@+import { build } from 'esbuild'+import { mkdir, writeFile } from 'node:fs/promises'+import { fileURLToPath } from 'node:url'+import { memoryWorkerSource } from './scripts/lib/memoryWorker.mjs'+import { plateWorkerSource } from './scripts/lib/plateWorker.mjs'+import { assertOptionalBundle } from './scripts/lib/boundary.mjs'++const root = fileURLToPath(new URL('.', import.meta.url))+const [memory, plate] = await Promise.all([memoryWorkerSource(), plateWorkerSource()])+const entries = [+ ['companion', 'src/companion/api.ts', { __PLATE_WORKER__: JSON.stringify(plate) }],+ ['memory', 'src/memory/index.ts', { __MEMORY_WORKER__: JSON.stringify(memory) }],+ ['application', 'src/application/index.ts', {}],+]+await mkdir(new URL('./dist/', import.meta.url), { recursive: true })+for (const [name, entry, define] of entries) {+ const result = await build({ absWorkingDir: root, entryPoints: [entry], outfile: `dist/${name}.js`,+ bundle: true, platform: 'node', format: 'esm', target: 'node22', define, metafile: true,+ // Dependencies are installed with this package, not taken from the installed Harness CLI.+ packages: 'external', logLevel: 'silent',+ })+ assertOptionalBundle(result.metafile)+ await writeFile(new URL(`./dist/${name}.meta.json`, import.meta.url), JSON.stringify(result.metafile, null, 2))+}+console.log('Built optional companion, memory and application entry points.')diff --git a/companions/package-lock.json b/companions/package-lock.jsonnew file mode 100644index 000000000..4eb56c9e2--- /dev/null+++ b/companions/package-lock.json@@ -0,0 +1,2333 @@+{+ "name": "@openharness/companions",+ "version": "0.0.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "@openharness/companions",+ "version": "0.0.0",+ "dependencies": {+ "ws": "8.21.0",+ "zod": "4.4.3"+ },+ "devDependencies": {+ "@types/node": "20.19.43",+ "@types/ws": "8.18.1",+ "esbuild": "0.27.7",+ "tsx": "4.23.0",+ "typescript": "5.9.3",+ "vitest": "4.1.10",+ "vite": "8.1.4"+ },+ "engines": {+ "node": ">=22.13"+ }+ },+ "node_modules/@emnapi/core": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz",+ "integrity": "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/wasi-threads": "1.2.2",+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@emnapi/runtime": {+ "version": "1.11.1",+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.1.tgz",+ "integrity": "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@emnapi/wasi-threads": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz",+ "integrity": "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz",+ "integrity": "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.7.tgz",+ "integrity": "sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.7.tgz",+ "integrity": "sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.7.tgz",+ "integrity": "sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.7.tgz",+ "integrity": "sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.7.tgz",+ "integrity": "sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.7.tgz",+ "integrity": "sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.7.tgz",+ "integrity": "sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.7.tgz",+ "integrity": "sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.7.tgz",+ "integrity": "sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.7.tgz",+ "integrity": "sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.7.tgz",+ "integrity": "sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.7.tgz",+ "integrity": "sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==",+ "cpu": [+ "mips64el"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.7.tgz",+ "integrity": "sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.7.tgz",+ "integrity": "sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.7.tgz",+ "integrity": "sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.7.tgz",+ "integrity": "sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.7.tgz",+ "integrity": "sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.7.tgz",+ "integrity": "sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.7.tgz",+ "integrity": "sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.7.tgz",+ "integrity": "sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openharmony-arm64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.7.tgz",+ "integrity": "sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.7.tgz",+ "integrity": "sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.7.tgz",+ "integrity": "sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.7.tgz",+ "integrity": "sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.7.tgz",+ "integrity": "sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@jridgewell/sourcemap-codec": {+ "version": "1.5.5",+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@napi-rs/wasm-runtime": {+ "version": "1.1.6",+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz",+ "integrity": "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@tybys/wasm-util": "^0.10.3"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ },+ "peerDependencies": {+ "@emnapi/core": "^1.7.1",+ "@emnapi/runtime": "^1.7.1"+ }+ },+ "node_modules/@oxc-project/types": {+ "version": "0.139.0",+ "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.139.0.tgz",+ "integrity": "sha512-r9gHphtCs+1M7J0pw6Sn/hh/Wpa/iQrOOkrNAlVLF/gHq+/CJmHIWKKUUhdWjcD6CIa8idarspCsASiXCXvFUw==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/Boshen"+ }+ },+ "node_modules/@rolldown/binding-android-arm64": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.1.5.tgz",+ "integrity": "sha512-lZg8fqIv2v7FF237bwMgzGZEJvGL79/s5knJ/i6FmsGF4XXlzccZ4jb+TrFIxtSSxFtIpdsgrPZeMk1I9AFcyQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-darwin-arm64": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.1.5.tgz",+ "integrity": "sha512-51Bnx9pNiMRKSUNtBfySkNJ9vMU9Hh3I1ozDd6gyPPYzaXCfnptUcEZxXGYFn+ul2dtcMUiqGR1Yai2K10uoTw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-darwin-x64": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.1.5.tgz",+ "integrity": "sha512-Tm+gbfC0aHu1tBA/JvKQh32S0K6YgCHkiAF4/W6xX0K0RmNuc94VeK419dJoE65R5aRxmo+noZQSWrAMF6yb6g==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-freebsd-x64": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.1.5.tgz",+ "integrity": "sha512-JMzDKCCXq93YccG5gz3hvOs1oXRKAf0XYpfOS88e+wZrC8Iugj6j68867vrYZkvpDDpKn/KoKORThmchMpF6TA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-arm-gnueabihf": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.1.5.tgz",+ "integrity": "sha512-uML21j2K5TfPGutKxub+M+nLjZIrWjXQ5Grx4lCe/nimTj9B4L63zHpjXLl4y0L3mcm2htEQIb06oCG/szerNw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-arm64-gnu": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.1.5.tgz",+ "integrity": "sha512-navSiuTMogvnQoZoM/v+l3ZWo50/NTwSHSzheABx/RCnmUPaKwq9qSo4Br2OYRs21+Fz8uFqITZM3H4opOB0/Q==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-arm64-musl": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.1.5.tgz",+ "integrity": "sha512-lAryqH7IteztmCXQXk0etKj4wBQ7Gx5S6LjKhsgp9zb8I5bsuvU/2llH1hDQcjsFeqIsovMVN339/8pUDDBXxA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-ppc64-gnu": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.1.5.tgz",+ "integrity": "sha512-fsK/sNBnxzBlL4O1JNrZakVQxPspqpED5dLtNsZS9oOKmtSpdNIzxH2kkol5HYTWJN47sE20ztMJPxfZ89qGOg==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-s390x-gnu": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.1.5.tgz",+ "integrity": "sha512-gLYb4BIadlfTOYT5gO503n8zQjXflgzpD0FcyKh0Mzx3rqCZKnHoJWV9xe1KXUJ5lx2JfcSHr/mhzS0PC/McAA==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-x64-gnu": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.1.5.tgz",+ "integrity": "sha512-FjcpEKUyJygHgs1o50VYNvkt5+7Le/VEdYt0AkRpkL33MnyQfwr8l5mXwMmfmTbyMPr5vJLC+8/Gd9gXnwU1QQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-linux-x64-musl": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.1.5.tgz",+ "integrity": "sha512-Me+PfPI2TMeOQk0gYWfLQZtTktrmzbr8cDboqX83XKc7UrgAi55gF+2dUkWdxd19n55Essp2yeca+O9N5rBxHg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-openharmony-arm64": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.1.5.tgz",+ "integrity": "sha512-yc5WrLzXks6zCQfn9Oxr8pORKyl/pF+QjHmW/Qx3qu0oyrrNC+y2JLTU1E2rcWYAmzlnqngWXHQjy51VzW70Vw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-wasm32-wasi": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.1.5.tgz",+ "integrity": "sha512-VbQGPX2b4r48TAMIM2cjgluIM1HYutm4pcTEJsle7iEP7sB1dFqtPLBVbdLAZCxy1txCcPxf4QFf4v8uvltPqA==",+ "cpu": [+ "wasm32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/core": "1.11.1",+ "@emnapi/runtime": "1.11.1",+ "@napi-rs/wasm-runtime": "^1.1.6"+ },+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-win32-arm64-msvc": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.1.5.tgz",+ "integrity": "sha512-gHv82k63z4qpV5+Q1y/12KrK0ltWBukVDI8nZcbT7Tt/ZlOIVwppazneq0F93oDxTo3IgAMEDIoQh3E2n6mVsw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/binding-win32-x64-msvc": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.1.5.tgz",+ "integrity": "sha512-tTZuDBPw85tEN5PQi1pnEBzDy0Z49HtScLAbD5t6hyeU92A95pRWaSMw1GZZi/RwgSgUIl0xrSlXIT/9QzvYSA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@rolldown/pluginutils": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",+ "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@standard-schema/spec": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",+ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@tybys/wasm-util": {+ "version": "0.10.3",+ "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz",+ "integrity": "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@types/chai": {+ "version": "5.2.3",+ "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",+ "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/deep-eql": "*",+ "assertion-error": "^2.0.1"+ }+ },+ "node_modules/@types/deep-eql": {+ "version": "4.0.2",+ "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",+ "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/estree": {+ "version": "1.0.9",+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/node": {+ "version": "20.19.43",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz",+ "integrity": "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "undici-types": "~6.21.0"+ }+ },+ "node_modules/@types/ws": {+ "version": "8.18.1",+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",+ "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/@vitest/expect": {+ "version": "4.1.10",+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.10.tgz",+ "integrity": "sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@standard-schema/spec": "^1.1.0",+ "@types/chai": "^5.2.2",+ "@vitest/spy": "4.1.10",+ "@vitest/utils": "4.1.10",+ "chai": "^6.2.2",+ "tinyrainbow": "^3.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/mocker": {+ "version": "4.1.10",+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.10.tgz",+ "integrity": "sha512-v0xaezt+DKEmKfaxg133ldzADrwLGd7Ze1MfQQTYfvs8OqZIwbxyxaYURivwV7sWy5fqn3rH5uOrSp07bp44Ow==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/spy": "4.1.10",+ "estree-walker": "^3.0.3",+ "magic-string": "^0.30.21"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ },+ "peerDependencies": {+ "msw": "^2.4.9",+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"+ },+ "peerDependenciesMeta": {+ "msw": {+ "optional": true+ },+ "vite": {+ "optional": true+ }+ }+ },+ "node_modules/@vitest/pretty-format": {+ "version": "4.1.10",+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.10.tgz",+ "integrity": "sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tinyrainbow": "^3.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/runner": {+ "version": "4.1.10",+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.10.tgz",+ "integrity": "sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/utils": "4.1.10",+ "pathe": "^2.0.3"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/snapshot": {+ "version": "4.1.10",+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.10.tgz",+ "integrity": "sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/pretty-format": "4.1.10",+ "@vitest/utils": "4.1.10",+ "magic-string": "^0.30.21",+ "pathe": "^2.0.3"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/spy": {+ "version": "4.1.10",+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.10.tgz",+ "integrity": "sha512-PLf/Ugvoq5wO/b4rwYCR1h2PSIdXz7wnkQFMiUpLdtM7l6pqVFcQIBEHyT1+l+cj7mNwAfZHzqXqDyjvOuwbDw==",+ "dev": true,+ "license": "MIT",+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/@vitest/utils": {+ "version": "4.1.10",+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.10.tgz",+ "integrity": "sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/pretty-format": "4.1.10",+ "convert-source-map": "^2.0.0",+ "tinyrainbow": "^3.1.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ }+ },+ "node_modules/assertion-error": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/chai": {+ "version": "6.2.2",+ "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",+ "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/convert-source-map": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",+ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/detect-libc": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/es-module-lexer": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.0.tgz",+ "integrity": "sha512-KLdwQm2NvGLDkQDCGvmiQrhkd0JbMzXthwQAUgWjQuQdBLFa3eiBP5arXZyA+f8x+x7OXgud6bq2rxjGtHV2tw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/esbuild": {+ "version": "0.27.7",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.7.tgz",+ "integrity": "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.27.7",+ "@esbuild/android-arm": "0.27.7",+ "@esbuild/android-arm64": "0.27.7",+ "@esbuild/android-x64": "0.27.7",+ "@esbuild/darwin-arm64": "0.27.7",+ "@esbuild/darwin-x64": "0.27.7",+ "@esbuild/freebsd-arm64": "0.27.7",+ "@esbuild/freebsd-x64": "0.27.7",+ "@esbuild/linux-arm": "0.27.7",+ "@esbuild/linux-arm64": "0.27.7",+ "@esbuild/linux-ia32": "0.27.7",+ "@esbuild/linux-loong64": "0.27.7",+ "@esbuild/linux-mips64el": "0.27.7",+ "@esbuild/linux-ppc64": "0.27.7",+ "@esbuild/linux-riscv64": "0.27.7",+ "@esbuild/linux-s390x": "0.27.7",+ "@esbuild/linux-x64": "0.27.7",+ "@esbuild/netbsd-arm64": "0.27.7",+ "@esbuild/netbsd-x64": "0.27.7",+ "@esbuild/openbsd-arm64": "0.27.7",+ "@esbuild/openbsd-x64": "0.27.7",+ "@esbuild/openharmony-arm64": "0.27.7",+ "@esbuild/sunos-x64": "0.27.7",+ "@esbuild/win32-arm64": "0.27.7",+ "@esbuild/win32-ia32": "0.27.7",+ "@esbuild/win32-x64": "0.27.7"+ }+ },+ "node_modules/estree-walker": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/estree": "^1.0.0"+ }+ },+ "node_modules/expect-type": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",+ "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=12.0.0"+ }+ },+ "node_modules/fdir": {+ "version": "6.5.0",+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12.0.0"+ },+ "peerDependencies": {+ "picomatch": "^3 || ^4"+ },+ "peerDependenciesMeta": {+ "picomatch": {+ "optional": true+ }+ }+ },+ "node_modules/fsevents": {+ "version": "2.3.3",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/lightningcss": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",+ "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==",+ "dev": true,+ "license": "MPL-2.0",+ "dependencies": {+ "detect-libc": "^2.0.3"+ },+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ },+ "optionalDependencies": {+ "lightningcss-android-arm64": "1.32.0",+ "lightningcss-darwin-arm64": "1.32.0",+ "lightningcss-darwin-x64": "1.32.0",+ "lightningcss-freebsd-x64": "1.32.0",+ "lightningcss-linux-arm-gnueabihf": "1.32.0",+ "lightningcss-linux-arm64-gnu": "1.32.0",+ "lightningcss-linux-arm64-musl": "1.32.0",+ "lightningcss-linux-x64-gnu": "1.32.0",+ "lightningcss-linux-x64-musl": "1.32.0",+ "lightningcss-win32-arm64-msvc": "1.32.0",+ "lightningcss-win32-x64-msvc": "1.32.0"+ }+ },+ "node_modules/lightningcss-android-arm64": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz",+ "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-darwin-arm64": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz",+ "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-darwin-x64": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz",+ "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-freebsd-x64": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz",+ "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-arm-gnueabihf": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz",+ "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-arm64-gnu": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz",+ "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-arm64-musl": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz",+ "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-x64-gnu": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz",+ "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-linux-x64-musl": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz",+ "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-win32-arm64-msvc": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz",+ "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/lightningcss-win32-x64-msvc": {+ "version": "1.32.0",+ "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz",+ "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MPL-2.0",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">= 12.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/parcel"+ }+ },+ "node_modules/magic-string": {+ "version": "0.30.21",+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@jridgewell/sourcemap-codec": "^1.5.5"+ }+ },+ "node_modules/nanoid": {+ "version": "3.3.15",+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.15.tgz",+ "integrity": "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "bin": {+ "nanoid": "bin/nanoid.cjs"+ },+ "engines": {+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"+ }+ },+ "node_modules/obug": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.3.tgz",+ "integrity": "sha512-9miFgM2OFba7hB+pRgvtV84pYTBaoTHohvmIgiRt6dRIzbwEOIaNaP+dIlGs2fNFoB0SeISs0Jz5WFVRid6Xyg==",+ "dev": true,+ "funding": [+ "https://github.com/sponsors/sxzz",+ "https://opencollective.com/debug"+ ],+ "license": "MIT",+ "engines": {+ "node": ">=12.20.0"+ }+ },+ "node_modules/pathe": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/picocolors": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/picomatch": {+ "version": "4.0.5",+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz",+ "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/jonschlinkert"+ }+ },+ "node_modules/postcss": {+ "version": "8.5.16",+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.16.tgz",+ "integrity": "sha512-vuwillviilfKZsg0VGj5R/YwwcHx4SLsIOI/7K6mQkWx+l5cUHTjj5g0AasTBcyXsbfTgrwsUNmVUb5xVwyPwg==",+ "dev": true,+ "funding": [+ {+ "type": "opencollective",+ "url": "https://opencollective.com/postcss/"+ },+ {+ "type": "tidelift",+ "url": "https://tidelift.com/funding/github/npm/postcss"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/ai"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "nanoid": "^3.3.12",+ "picocolors": "^1.1.1",+ "source-map-js": "^1.2.1"+ },+ "engines": {+ "node": "^10 || ^12 || >=14"+ }+ },+ "node_modules/rolldown": {+ "version": "1.1.5",+ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.1.5.tgz",+ "integrity": "sha512-t9z29cJjXf/vxQ8dyhCSpt6H6aSwHTk8cT5I3iy6SMXuFpk5mB6PL6XfC8PCwrPTx93udwKUm9HRteAlTGBLiA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@oxc-project/types": "=0.139.0",+ "@rolldown/pluginutils": "^1.0.0"+ },+ "bin": {+ "rolldown": "bin/cli.mjs"+ },+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ },+ "optionalDependencies": {+ "@rolldown/binding-android-arm64": "1.1.5",+ "@rolldown/binding-darwin-arm64": "1.1.5",+ "@rolldown/binding-darwin-x64": "1.1.5",+ "@rolldown/binding-freebsd-x64": "1.1.5",+ "@rolldown/binding-linux-arm-gnueabihf": "1.1.5",+ "@rolldown/binding-linux-arm64-gnu": "1.1.5",+ "@rolldown/binding-linux-arm64-musl": "1.1.5",+ "@rolldown/binding-linux-ppc64-gnu": "1.1.5",+ "@rolldown/binding-linux-s390x-gnu": "1.1.5",+ "@rolldown/binding-linux-x64-gnu": "1.1.5",+ "@rolldown/binding-linux-x64-musl": "1.1.5",+ "@rolldown/binding-openharmony-arm64": "1.1.5",+ "@rolldown/binding-wasm32-wasi": "1.1.5",+ "@rolldown/binding-win32-arm64-msvc": "1.1.5",+ "@rolldown/binding-win32-x64-msvc": "1.1.5"+ }+ },+ "node_modules/siginfo": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",+ "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",+ "dev": true,+ "license": "ISC"+ },+ "node_modules/source-map-js": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",+ "dev": true,+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/stackback": {+ "version": "0.0.2",+ "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",+ "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/std-env": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz",+ "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tinybench": {+ "version": "2.9.0",+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",+ "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/tinyexec": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.2.4.tgz",+ "integrity": "sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tinyglobby": {+ "version": "0.2.17",+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "fdir": "^6.5.0",+ "picomatch": "^4.0.4"+ },+ "engines": {+ "node": ">=12.0.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/SuperchupuDev"+ }+ },+ "node_modules/tinyrainbow": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz",+ "integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=14.0.0"+ }+ },+ "node_modules/tslib": {+ "version": "2.8.1",+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",+ "license": "0BSD"+ },+ "node_modules/tsx": {+ "version": "4.23.0",+ "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.0.tgz",+ "integrity": "sha512-eUdUIaCr963q2h5u3+QwvYp0+eqPvn+egeqZUm0hwERCqqx1E3kK5ehbGCvqSE5MQAULr67ww0cA3jKc3YkM1w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "esbuild": "~0.28.0"+ },+ "bin": {+ "tsx": "dist/cli.mjs"+ },+ "engines": {+ "node": ">=18.0.0"+ },+ "optionalDependencies": {+ "fsevents": "~2.3.3"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/aix-ppc64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",+ "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/android-arm": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",+ "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/android-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",+ "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/android-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",+ "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/darwin-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",+ "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/darwin-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",+ "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/freebsd-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",+ "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/freebsd-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",+ "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/linux-arm": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",+ "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/linux-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",+ "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/linux-ia32": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",+ "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/linux-loong64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",+ "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/linux-mips64el": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",+ "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",+ "cpu": [+ "mips64el"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/linux-ppc64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",+ "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/linux-riscv64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",+ "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/linux-s390x": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",+ "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/linux-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",+ "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/netbsd-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",+ "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/netbsd-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",+ "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/openbsd-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",+ "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/openbsd-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",+ "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/openharmony-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",+ "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/sunos-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",+ "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/win32-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",+ "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/win32-ia32": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",+ "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/@esbuild/win32-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",+ "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/tsx/node_modules/esbuild": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",+ "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",+ "dev": true,+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.28.1",+ "@esbuild/android-arm": "0.28.1",+ "@esbuild/android-arm64": "0.28.1",+ "@esbuild/android-x64": "0.28.1",+ "@esbuild/darwin-arm64": "0.28.1",+ "@esbuild/darwin-x64": "0.28.1",+ "@esbuild/freebsd-arm64": "0.28.1",+ "@esbuild/freebsd-x64": "0.28.1",+ "@esbuild/linux-arm": "0.28.1",+ "@esbuild/linux-arm64": "0.28.1",+ "@esbuild/linux-ia32": "0.28.1",+ "@esbuild/linux-loong64": "0.28.1",+ "@esbuild/linux-mips64el": "0.28.1",+ "@esbuild/linux-ppc64": "0.28.1",+ "@esbuild/linux-riscv64": "0.28.1",+ "@esbuild/linux-s390x": "0.28.1",+ "@esbuild/linux-x64": "0.28.1",+ "@esbuild/netbsd-arm64": "0.28.1",+ "@esbuild/netbsd-x64": "0.28.1",+ "@esbuild/openbsd-arm64": "0.28.1",+ "@esbuild/openbsd-x64": "0.28.1",+ "@esbuild/openharmony-arm64": "0.28.1",+ "@esbuild/sunos-x64": "0.28.1",+ "@esbuild/win32-arm64": "0.28.1",+ "@esbuild/win32-ia32": "0.28.1",+ "@esbuild/win32-x64": "0.28.1"+ }+ },+ "node_modules/typescript": {+ "version": "5.9.3",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/undici-types": {+ "version": "6.21.0",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/vite": {+ "version": "8.1.4",+ "resolved": "https://registry.npmjs.org/vite/-/vite-8.1.4.tgz",+ "integrity": "sha512-bTT9PsdWO+MQMNG9ZXIP/qM9wGh37DFxTV/sPq9cFpHr3w4jkgef032PkAL9jAqhk3Nz8NQw3O8n6/xFkqO4QQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "lightningcss": "^1.32.0",+ "picomatch": "^4.0.5",+ "postcss": "^8.5.16",+ "rolldown": "~1.1.4",+ "tinyglobby": "^0.2.17"+ },+ "bin": {+ "vite": "bin/vite.js"+ },+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ },+ "funding": {+ "url": "https://github.com/vitejs/vite?sponsor=1"+ },+ "optionalDependencies": {+ "fsevents": "~2.3.3"+ },+ "peerDependencies": {+ "@types/node": "^20.19.0 || >=22.12.0",+ "@vitejs/devtools": "^0.3.0",+ "esbuild": "^0.27.0 || ^0.28.0",+ "jiti": ">=1.21.0",+ "less": "^4.0.0",+ "sass": "^1.70.0",+ "sass-embedded": "^1.70.0",+ "stylus": ">=0.54.8",+ "sugarss": "^5.0.0",+ "terser": "^5.16.0",+ "tsx": "^4.8.1",+ "yaml": "^2.4.2"+ },+ "peerDependenciesMeta": {+ "@types/node": {+ "optional": true+ },+ "@vitejs/devtools": {+ "optional": true+ },+ "esbuild": {+ "optional": true+ },+ "jiti": {+ "optional": true+ },+ "less": {+ "optional": true+ },+ "sass": {+ "optional": true+ },+ "sass-embedded": {+ "optional": true+ },+ "stylus": {+ "optional": true+ },+ "sugarss": {+ "optional": true+ },+ "terser": {+ "optional": true+ },+ "tsx": {+ "optional": true+ },+ "yaml": {+ "optional": true+ }+ }+ },+ "node_modules/vitest": {+ "version": "4.1.10",+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.10.tgz",+ "integrity": "sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@vitest/expect": "4.1.10",+ "@vitest/mocker": "4.1.10",+ "@vitest/pretty-format": "4.1.10",+ "@vitest/runner": "4.1.10",+ "@vitest/snapshot": "4.1.10",+ "@vitest/spy": "4.1.10",+ "@vitest/utils": "4.1.10",+ "es-module-lexer": "^2.0.0",+ "expect-type": "^1.3.0",+ "magic-string": "^0.30.21",+ "obug": "^2.1.1",+ "pathe": "^2.0.3",+ "picomatch": "^4.0.3",+ "std-env": "^4.0.0-rc.1",+ "tinybench": "^2.9.0",+ "tinyexec": "^1.0.2",+ "tinyglobby": "^0.2.15",+ "tinyrainbow": "^3.1.0",+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0",+ "why-is-node-running": "^2.3.0"+ },+ "bin": {+ "vitest": "vitest.mjs"+ },+ "engines": {+ "node": "^20.0.0 || ^22.0.0 || >=24.0.0"+ },+ "funding": {+ "url": "https://opencollective.com/vitest"+ },+ "peerDependencies": {+ "@edge-runtime/vm": "*",+ "@opentelemetry/api": "^1.9.0",+ "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",+ "@vitest/browser-playwright": "4.1.10",+ "@vitest/browser-preview": "4.1.10",+ "@vitest/browser-webdriverio": "4.1.10",+ "@vitest/coverage-istanbul": "4.1.10",+ "@vitest/coverage-v8": "4.1.10",+ "@vitest/ui": "4.1.10",+ "happy-dom": "*",+ "jsdom": "*",+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"+ },+ "peerDependenciesMeta": {+ "@edge-runtime/vm": {+ "optional": true+ },+ "@opentelemetry/api": {+ "optional": true+ },+ "@types/node": {+ "optional": true+ },+ "@vitest/browser-playwright": {+ "optional": true+ },+ "@vitest/browser-preview": {+ "optional": true+ },+ "@vitest/browser-webdriverio": {+ "optional": true+ },+ "@vitest/coverage-istanbul": {+ "optional": true+ },+ "@vitest/coverage-v8": {+ "optional": true+ },+ "@vitest/ui": {+ "optional": true+ },+ "happy-dom": {+ "optional": true+ },+ "jsdom": {+ "optional": true+ },+ "vite": {+ "optional": false+ }+ }+ },+ "node_modules/why-is-node-running": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",+ "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "siginfo": "^2.0.0",+ "stackback": "0.0.2"+ },+ "bin": {+ "why-is-node-running": "cli.js"+ },+ "engines": {+ "node": ">=8"+ }+ },+ "node_modules/ws": {+ "version": "8.21.0",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",+ "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ },+ "node_modules/zod": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz",+ "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ }+ }+}diff --git a/companions/package.json b/companions/package.jsonnew file mode 100644index 000000000..7d1b2eccb--- /dev/null+++ b/companions/package.json@@ -0,0 +1,43 @@+{+ "name": "@openharness/companions",+ "version": "0.0.0",+ "private": true,+ "type": "module",+ "description": "Optional companion experience with isolated companion and coding-memory subsystems.",+ "scripts": {+ "build": "node build.mjs",+ "typecheck": "tsc --noEmit",+ "test": "vitest run",+ "test:bundle": "node --test scripts/test-bundle.mjs"+ },+ "dependencies": {+ "ws": "8.21.0",+ "zod": "4.4.3"+ },+ "devDependencies": {+ "@types/node": "20.19.43",+ "@types/ws": "8.18.1",+ "esbuild": "0.27.7",+ "tsx": "4.23.0",+ "typescript": "5.9.3",+ "vitest": "4.1.10",+ "vite": "8.1.4"+ },+ "engines": {+ "node": ">=22.13"+ },+ "exports": {+ "./companion": {+ "types": "./src/companion/api.ts",+ "import": "./dist/companion.js"+ },+ "./memory": {+ "types": "./src/memory/index.ts",+ "import": "./dist/memory.js"+ },+ "./application": {+ "types": "./src/application/index.ts",+ "import": "./dist/application.js"+ }+ }+}diff --git a/companions/scripts/lib/boundary.mjs b/companions/scripts/lib/boundary.mjsnew file mode 100644index 000000000..6063c6a3b--- /dev/null+++ b/companions/scripts/lib/boundary.mjs@@ -0,0 +1,6 @@+/** Applies to public entry points and embedded workers; neither may boot a core service. */+export function assertOptionalBundle(metafile) {+ const forbidden = Object.keys(metafile.inputs).filter(path =>+ /(?:^|\/)cli\/src\/(?:config\/|(?:cli|backendSocket|localWsServer|hookServer)\.ts$|lib\/(?:registry|authSession|oneshot)\.ts$)/.test(path.replaceAll('\\', '/')))+ if (forbidden.length) throw new Error(`Optional package imported a core service: ${forbidden.join(', ')}`)+}diff --git a/cli/scripts/lib/memoryWorker.mjs b/companions/scripts/lib/memoryWorker.mjssimilarity index 72%rename from cli/scripts/lib/memoryWorker.mjsrename to companions/scripts/lib/memoryWorker.mjsindex 8b6014fb5..384fe6bd4 100644--- a/cli/scripts/lib/memoryWorker.mjs+++ b/companions/scripts/lib/memoryWorker.mjs@@ -1,11 +1,13 @@import * as esbuild from 'esbuild'import { fileURLToPath } from 'node:url'+import { assertOptionalBundle } from './boundary.mjs'export async function memoryWorkerSource({ minify = false } = {}) {const result = await esbuild.build({entryPoints: [fileURLToPath(new URL('../../src/memory/worker.ts', import.meta.url))],bundle: true, write: false, platform: 'node', format: 'cjs', target: 'node20', minify,- legalComments: 'none', logLevel: 'silent',+ legalComments: 'none', logLevel: 'silent', metafile: true,})+ assertOptionalBundle(result.metafile)return result.outputFiles[0].text}diff --git a/companions/scripts/lib/plateWorker.mjs b/companions/scripts/lib/plateWorker.mjsnew file mode 100644index 000000000..8a97d0322--- /dev/null+++ b/companions/scripts/lib/plateWorker.mjs@@ -0,0 +1,21 @@+import * as esbuild from 'esbuild'+import { fileURLToPath } from 'node:url'+import { assertOptionalBundle } from './boundary.mjs'++// Render work belongs to the optional package and runs in its bounded worker.+export async function plateWorkerSource({ minify = false } = {}) {+ const result = await esbuild.build({+ entryPoints: [fileURLToPath(new URL('../../src/companion/plateWorker.ts', import.meta.url))],+ bundle: true,+ write: false,+ platform: 'node',+ format: 'cjs',+ target: 'node20',+ minify,+ legalComments: 'none',+ logLevel: 'silent',+ metafile: true,+ })+ assertOptionalBundle(result.metafile)+ return result.outputFiles[0].text+}diff --git a/cli/scripts/memory-benchmark.ts b/companions/scripts/memory-benchmark.tssimilarity index 100%rename from cli/scripts/memory-benchmark.tsrename to companions/scripts/memory-benchmark.tsdiff --git a/cli/scripts/memory-extraction-eval.ts b/companions/scripts/memory-extraction-eval.tssimilarity index 100%rename from cli/scripts/memory-extraction-eval.tsrename to companions/scripts/memory-extraction-eval.tsdiff --git a/cli/scripts/memory-native-claude-inference-probe.mjs b/companions/scripts/memory-native-claude-inference-probe.mjssimilarity index 100%rename from cli/scripts/memory-native-claude-inference-probe.mjsrename to companions/scripts/memory-native-claude-inference-probe.mjsdiff --git a/cli/scripts/memory-native-claude-lifecycle-probe.mjs b/companions/scripts/memory-native-claude-lifecycle-probe.mjssimilarity index 97%rename from cli/scripts/memory-native-claude-lifecycle-probe.mjsrename to companions/scripts/memory-native-claude-lifecycle-probe.mjsindex 7cb3bb890..5cf9af237 100644--- a/cli/scripts/memory-native-claude-lifecycle-probe.mjs+++ b/companions/scripts/memory-native-claude-lifecycle-probe.mjs@@ -1,4 +1,4 @@-// Manual native check: node cli/scripts/memory-native-claude-lifecycle-probe.mjs+// Manual native check: node companions/scripts/memory-native-claude-lifecycle-probe.mjs// Uses disposable native configuration, fake credentials and localhost responses only.// Checks the next user prompt after resume/manual compaction/model change, not automatic// mid-turn compaction, account changes, real host authorization or model usefulness.@@ -11,7 +11,7 @@ import { randomUUID } from 'node:crypto'import { fileURLToPath } from 'node:url'const fixture = await mkdtemp(join(tmpdir(), 'native-memory-lifecycle-'))-const hookFile = fileURLToPath(new URL('../hook/notify.mjs', import.meta.url))+const hookFile = fileURLToPath(new URL('../../cli/hook/notify.mjs', import.meta.url))const sessionId = randomUUID()const marker = 'memory_lifecycle_72ab9'const receiptId = randomUUID()diff --git a/cli/scripts/memory-native-codex-certification.mjs b/companions/scripts/memory-native-codex-certification.mjssimilarity index 100%rename from cli/scripts/memory-native-codex-certification.mjsrename to companions/scripts/memory-native-codex-certification.mjsdiff --git a/cli/scripts/memory-native-codex-lifecycle-probe.mjs b/companions/scripts/memory-native-codex-lifecycle-probe.mjssimilarity index 97%rename from cli/scripts/memory-native-codex-lifecycle-probe.mjsrename to companions/scripts/memory-native-codex-lifecycle-probe.mjsindex e49342812..6fb71eb53 100644--- a/cli/scripts/memory-native-codex-lifecycle-probe.mjs+++ b/companions/scripts/memory-native-codex-lifecycle-probe.mjs@@ -1,5 +1,5 @@// Manual native check (PTY required):-// node cli/scripts/memory-native-codex-lifecycle-probe.mjs --output <new-report.json>+// node companions/scripts/memory-native-codex-lifecycle-probe.mjs --output <new-report.json>// Review and trust only this disposable folder and its exact synthetic hooks through// the native UI. Never bypass native trust or use an existing native home.// First launch: send a synthetic coding prompt; /compact; send another prompt; /quit.@@ -98,7 +98,7 @@ try {for (const name of ['home','codex','data','work']) await mkdir(join(fixture,name), { mode:0o700 })await writeFile(join(fixture,'data','hook-credential'), `${'a'.repeat(43)}\n`, { mode:0o600 })const quote = value => `'${value.replace(/'/g, `'\\''`)}'`- const command = [process.execPath,fileURLToPath(new URL('../hook/notify.mjs', import.meta.url)),'--port',String(adapter.address().port),'--data-dir',join(fixture,'data'),+ const command = [process.execPath,fileURLToPath(new URL('../../cli/hook/notify.mjs', import.meta.url)),'--port',String(adapter.address().port),'--data-dir',join(fixture,'data'),'--engine',engine,'--codex-home',join(fixture,'codex')].map(quote).join(' ')const config = { hooks: Object.fromEntries(['SessionStart','UserPromptSubmit','PreCompact','PostCompact'].map(event=>[event,[{hooks:[{type:'command',command,timeout:3}]}]])) }await writeFile(join(fixture,'codex','hooks.json'),JSON.stringify(config))diff --git a/cli/scripts/memory-native-hook-probe.mjs b/companions/scripts/memory-native-hook-probe.mjssimilarity index 96%rename from cli/scripts/memory-native-hook-probe.mjsrename to companions/scripts/memory-native-hook-probe.mjsindex 57ef821fb..708c12ec0 100644--- a/cli/scripts/memory-native-hook-probe.mjs+++ b/companions/scripts/memory-native-hook-probe.mjs@@ -1,4 +1,4 @@-// Manual native transport probe: node cli/scripts/memory-native-hook-probe.mjs [--codex] [--interactive] [--context-file synthetic.json]+// Manual native transport probe: node companions/scripts/memory-native-hook-probe.mjs [--codex] [--interactive] [--context-file synthetic.json]// Isolated synthetic configuration and fake credentials; model/adapter endpoints are loopback-only.// Native trust prompts are preserved. Do not bypass them or reuse a real user's config for this test.// This checks transport with a mock model, not extraction fidelity, task quality or every native lifecycle.@@ -76,7 +76,7 @@ try {for (const name of ['home','config','codex','data','work']) await mkdir(join(fixture,name), { mode:0o700 })await writeFile(join(fixture,'data','hook-credential'), `${'a'.repeat(43)}\n`, { mode:0o600 })const quote = value => `'${value.replace(/'/g, `'\\''`)}'`- const command = [process.execPath,fileURLToPath(new URL('../hook/notify.mjs', import.meta.url)),'--port',String(adapter.address().port),'--data-dir',join(fixture,'data'),+ const command = [process.execPath,fileURLToPath(new URL('../../cli/hook/notify.mjs', import.meta.url)),'--port',String(adapter.address().port),'--data-dir',join(fixture,'data'),'--engine',engine,'--codex-home',join(fixture,'codex')].map(quote).join(' ')const config = { hooks: { UserPromptSubmit:[{hooks:[{type:'command',command,timeout:3}]}] } }const settings = join(fixture,'config','settings.json')diff --git a/cli/scripts/memory-native-opencode-binding-probe.mjs b/companions/scripts/memory-native-opencode-binding-probe.mjssimilarity index 98%rename from cli/scripts/memory-native-opencode-binding-probe.mjsrename to companions/scripts/memory-native-opencode-binding-probe.mjsindex e948158f5..381f61d6a 100644--- a/cli/scripts/memory-native-opencode-binding-probe.mjs+++ b/companions/scripts/memory-native-opencode-binding-probe.mjs@@ -1,4 +1,4 @@-// Manual integration check: node cli/scripts/memory-native-opencode-binding-probe.mjs+// Manual integration check: node companions/scripts/memory-native-opencode-binding-probe.mjs// A live disposable OpenCode server observes foreground selection, then the actual companion// intelligence extracts with that binding. All credentials and model responses are synthetic.import assert from 'node:assert/strict'@@ -55,7 +55,7 @@ try {await build({ stdin: { contents: [`export { opencodeMemoryPluginSource } from ${JSON.stringify(join(cli, 'src/lib/opencodeMemoryPlugin.ts'))};`,`export { OpenCodeMemoryBinding } from ${JSON.stringify(join(cli, 'src/memory/opencodeBinding.ts'))};`,- `export { CompanionIntelligence } from ${JSON.stringify(join(cli, 'src/pair/intelligence.ts'))};`,+ `export { CompanionIntelligence } from ${JSON.stringify(join(cli, 'src/application/intelligence.ts'))};`,].join('\n'), resolveDir: cli }, outfile: bundle, bundle: true, platform: 'node', format: 'esm', target: 'node22',banner: { js: "import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);" },})diff --git a/cli/scripts/memory-native-opencode-inference-probe.mjs b/companions/scripts/memory-native-opencode-inference-probe.mjssimilarity index 98%rename from cli/scripts/memory-native-opencode-inference-probe.mjsrename to companions/scripts/memory-native-opencode-inference-probe.mjsindex 8edb2b28a..d16308529 100644--- a/cli/scripts/memory-native-opencode-inference-probe.mjs+++ b/companions/scripts/memory-native-opencode-inference-probe.mjs@@ -1,4 +1,4 @@-// Manual native transport check: node cli/scripts/memory-native-opencode-inference-probe.mjs+// Manual native transport check: node companions/scripts/memory-native-opencode-inference-probe.mjs// Disposable storage, synthetic credentials and localhost responses only. No real inference.import assert from 'node:assert/strict'import { createServer } from 'node:http'diff --git a/cli/scripts/memory-native-opencode-recall-probe.mjs b/companions/scripts/memory-native-opencode-recall-probe.mjssimilarity index 100%rename from cli/scripts/memory-native-opencode-recall-probe.mjsrename to companions/scripts/memory-native-opencode-recall-probe.mjsdiff --git a/cli/scripts/memory-native-opencode-source-probe.mjs b/companions/scripts/memory-native-opencode-source-probe.mjssimilarity index 99%rename from cli/scripts/memory-native-opencode-source-probe.mjsrename to companions/scripts/memory-native-opencode-source-probe.mjsindex be5699677..17291b5e8 100644--- a/cli/scripts/memory-native-opencode-source-probe.mjs+++ b/companions/scripts/memory-native-opencode-source-probe.mjs@@ -1,5 +1,5 @@// Real OpenCode 1.18.34, disposable HOME/database, synthetic localhost model only.-// Run: node cli/scripts/memory-native-opencode-source-probe.mjs+// Run: node companions/scripts/memory-native-opencode-source-probe.mjsimport assert from 'node:assert/strict'import { execFileSync, spawn } from 'node:child_process'import { createServer } from 'node:http'diff --git a/cli/scripts/memory-quality-review.ts b/companions/scripts/memory-quality-review.tssimilarity index 100%rename from cli/scripts/memory-quality-review.tsrename to companions/scripts/memory-quality-review.tsdiff --git a/companions/scripts/test-bundle.mjs b/companions/scripts/test-bundle.mjsnew file mode 100644index 000000000..9f4168dcd--- /dev/null+++ b/companions/scripts/test-bundle.mjs@@ -0,0 +1,75 @@+import assert from 'node:assert/strict'+import { cp, mkdtemp, mkdir, readFile, readdir, rm, symlink } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { fileURLToPath, pathToFileURL } from 'node:url'+import { test } from 'node:test'++test('the optional artifacts work with their source tree and core service absent', { timeout: 20_000 }, async () => {+ const fixture = await mkdtemp(join(tmpdir(), 'companion-bundle-'))+ const clients = []+ try {+ const artifacts = join(fixture, 'package')+ await cp(new URL('../dist/', import.meta.url), artifacts, { recursive: true })+ await symlink(fileURLToPath(new URL('../node_modules/', import.meta.url)), join(artifacts, 'node_modules'), 'dir')+ // No source files, CLI entry point, service, sockets or provider credentials in this fixture.+ const { MemoryClient, CodingMemoryRuntime } = await import(pathToFileURL(join(artifacts, 'memory.js')))+ const { CompanionZoo } = await import(pathToFileURL(join(artifacts, 'companion.js')))+ assert.equal(typeof CompanionZoo, 'function')+ await import(pathToFileURL(join(artifacts, 'application.js')))+ const state = join(fixture, 'state')+ await mkdir(state)+ let inspected = 0+ const disabled = new CodingMemoryRuntime({ directory: state,+ context: () => ({ experimental: false, watching: false, profileId: 'fixture' }),+ sessions: () => { inspected++; return [] },+ inference: { target: async () => { throw new Error('disabled model inspected') },+ run: async () => { throw new Error('disabled model called') } },+ })+ disabled.start()+ await disabled.tick()+ await disabled.close()+ assert.equal(inspected, 0)+ assert.deepEqual(await readdir(state), [])++ const open = () => {+ const client = new MemoryClient({ directory: state, profileId: 'fixture' })+ clients.push(client)+ return client+ }+ const first = open()+ await first.request('registerProject', ['project'])+ await first.request('setControls', [{ learn: true, recall: true }])+ const event = { id: 'fixture-source', profileId: 'fixture', projectId: 'project', engine: 'claude',+ sessionId: 'synthetic-session', nativeEventId: 'fixture-source', role: 'user', eligibility: 'coding',+ observedAt: Date.now(), rootIds: ['fixture-source'], text: 'I prefer small coding changes.' }+ await first.request('ingest', [event])+ const access = { profileId: 'fixture', projectIds: ['project'], includeProfile: false }+ const { record } = await first.request('propose', [{+ kind: 'working_preference', facet: 'changes', assertionType: 'stated_preference',+ scope: { profileId: 'fixture', projectId: 'project' }, claim: event.text, rationale: null,+ futureAction: 'Keep coding changes small.', applicability: {}, exceptions: [], retrievalCues: ['coding', 'changes'],+ evidenceClass: 'user_stated', evidence: [{ sourceEventId: event.id, quote: event.text, paths: ['/claim', '/futureAction', '/applicability', '/validity'] }],+ conflictKey: 'change-size', validity: { validFrom: null, validUntil: null, recheckWhen: [] },+ }, access])+ await first.close()+ const second = open()+ assert.equal((await second.request('read', [record.id, access])).claim, event.text)+ const recalled = await second.recall({ query: 'coding changes' }, access, 2_000)+ assert.equal(recalled.items.length, 1)+ assert.equal((await second.recall({ query: 'coding' }, { ...access, profileId: 'other' })).status, 'denied')+ const broken = new MemoryClient({ directory: join(fixture, 'broken'), profileId: 'fixture',+ source: 'throw new Error("synthetic worker failure")' })+ clients.push(broken)+ assert.equal((await broken.recall({ query: 'coding' }, access)).status, 'unavailable')+ assert.equal((await second.recall({ query: 'coding changes' }, access)).items.length, 1)++ const memoryGraph = JSON.parse(await readFile(join(artifacts, 'memory.meta.json'), 'utf8'))+ assert(!Object.keys(memoryGraph.inputs).some(path => path.startsWith('src/companion/') || path.startsWith('src/application/')))+ const companionGraph = JSON.parse(await readFile(join(artifacts, 'companion.meta.json'), 'utf8'))+ assert(!Object.keys(companionGraph.inputs).some(path => /src\/memory\/(runtime|store|client|worker)\.ts$/.test(path)))+ } finally {+ await Promise.all(clients.map(client => client.close()))+ await rm(fixture, { recursive: true, force: true })+ }+})diff --git a/companions/src/application/index.ts b/companions/src/application/index.tsnew file mode 100644index 000000000..059c78be2--- /dev/null+++ b/companions/src/application/index.ts@@ -0,0 +1,3 @@+/** Composition belongs to the optional package, never to the Harness CLI entry point. */+export { CompanionIntelligence, type CompanionRuntime, type IntelligenceStatus } from './intelligence.js'+export { companionMemoryInference } from './memoryInference.js'diff --git a/cli/src/pair/intelligence.spec.ts b/companions/src/application/intelligence.spec.tssimilarity index 99%rename from cli/src/pair/intelligence.spec.tsrename to companions/src/application/intelligence.spec.tsindex 45dc02802..535025339 100644--- a/cli/src/pair/intelligence.spec.ts+++ b/companions/src/application/intelligence.spec.ts@@ -3,8 +3,8 @@ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { CompanionIntelligence, type CompanionRuntime } from './intelligence.js'-import { encodeRuntimeProfile } from '../lib/runtimeProfile.js'-import type { OneShotOptions } from '../lib/oneshot.js'+import { encodeRuntimeProfile } from '../../../cli/src/lib/runtimeProfile.js'+import type { OneShotOptions } from '../../../cli/src/lib/oneshot.js'import { openCodeSnapshotIdentity, type OpenCodeMemorySnapshot, type OpenCodeMemoryInferenceOptions } from '../memory/opencodeInference.js'import { MemoryError } from '../memory/types.js'diff --git a/cli/src/pair/intelligence.ts b/companions/src/application/intelligence.tssimilarity index 96%rename from cli/src/pair/intelligence.tsrename to companions/src/application/intelligence.tsindex 4132479d2..328d3f85c 100644--- a/cli/src/pair/intelligence.ts+++ b/companions/src/application/intelligence.ts@@ -2,10 +2,10 @@import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'import { dirname } from 'node:path'import { createHash } from 'node:crypto'-import { encodeRuntimeProfile, parseRuntimeProfile, type RuntimeProfile } from '../lib/runtimeProfile.js'-import { runClaudeOneShot, runCodexOneShot, type OneShotOptions } from '../lib/oneshot.js'-import type { PairOneShot } from './triage.js'-import type { StartupProfile } from './startupProfile.js'+import { encodeRuntimeProfile, parseRuntimeProfile, type RuntimeProfile } from './modelProfile.js'+import type { OneShotOptions } from '../../../cli/src/lib/oneshot.js'+import type { PairOneShot } from '../companion/triage.js'+import type { StartupProfile } from '../companion/startupProfile.js'import { runCodexMemoryInference } from '../memory/inference.js'import { runClaudeMemoryInference } from '../memory/claudeInference.js'import { memoryAccountIdentity } from '../memory/account.js'@@ -103,8 +103,8 @@ export class CompanionIntelligence {if (current.status.state !== 'ready' || current.status.contextKey !== selected.status.contextKey) throw new MemoryError('inference_context_changed')} } : {}),}- const run = this.deps.run ?? ((engine, options) => engine === 'claude' ? extraction ? runClaudeMemoryInference(options) : runClaudeOneShot(options)- : extraction ? runCodexMemoryInference(options) : runCodexOneShot(options))+ const run = this.deps.run ?? ((engine, options) => engine === 'claude'+ ? runClaudeMemoryInference(options) : runCodexMemoryInference(options))const result = engine === 'opencode'? await (this.deps.runOpenCode ?? runOpenCodeMemoryInference)({ ...options,expectedSnapshot: openCodeSnapshotIdentity(target.openCodeSnapshot!),diff --git a/cli/src/pair/learn/conversationReview.spec.ts b/companions/src/application/lessons/conversationReview.spec.tssimilarity index 97%rename from cli/src/pair/learn/conversationReview.spec.tsrename to companions/src/application/lessons/conversationReview.spec.tsindex 1f9d1e862..685978f38 100644--- a/cli/src/pair/learn/conversationReview.spec.ts+++ b/companions/src/application/lessons/conversationReview.spec.ts@@ -3,10 +3,10 @@ import { mkdtempSync, readFileSync, rmSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { ConversationReview } from './conversationReview.js'-import { LessonStore } from './store.js'-import { LessonDistiller, type DistillWhy } from './distill.js'-import type { RecentConversationTurn } from '../../lib/sessionSearch/store.js'-import { projectHash } from './types.js'+import { LessonStore } from '../../memory/lessons/store.js'+import { LessonDistiller, type DistillWhy } from '../../memory/lessons/distill.js'+import type { RecentConversationTurn } from '../../../../cli/src/lib/sessionSearch/store.js'+import { projectHash } from '../../memory/lessons/types.js'let dir: stringconst NOW = Date.parse('2026-09-30T15:00:00Z'), HOUR = 3_600_000diff --git a/cli/src/pair/learn/conversationReview.ts b/companions/src/application/lessons/conversationReview.tssimilarity index 97%rename from cli/src/pair/learn/conversationReview.tsrename to companions/src/application/lessons/conversationReview.tsindex 53b4cd9b2..e5c9184a4 100644--- a/cli/src/pair/learn/conversationReview.ts+++ b/companions/src/application/lessons/conversationReview.ts@@ -1,12 +1,12 @@/** Explicit, bounded review of dated local conversations. Every result is a pending lesson. */import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'import { join } from 'node:path'-import type { RecentConversationTurn } from '../../lib/sessionSearch/store.js'-import type { IntelligenceStatus } from '../intelligence.js'-import { guardLesson, parseDistilled, type LessonDistiller } from './distill.js'-import { redact, untrusted } from './guard.js'-import type { LessonStore } from './store.js'-import { contentHash, projectHash, projectName, type Signal } from './types.js'+import type { RecentConversationTurn } from '../../../../cli/src/lib/sessionSearch/store.js'+import type { IntelligenceStatus } from '../../companion/intelligencePort.js'+import { guardLesson, parseDistilled, type LessonDistiller } from '../../memory/lessons/distill.js'+import { redact, untrusted } from '../../shared/guard.js'+import type { LessonStore } from '../../memory/lessons/store.js'+import { contentHash, projectHash, projectName, type Signal } from '../../memory/lessons/types.js'const HOUR = 60 * 60_000const BATCH_CHARS = 20_000diff --git a/cli/src/pair/learn/l2.spec.ts b/companions/src/application/lessons/l2.spec.tssimilarity index 93%rename from cli/src/pair/learn/l2.spec.tsrename to companions/src/application/lessons/l2.spec.tsindex 3a18a4cf0..d6d65b69e 100644--- a/cli/src/pair/learn/l2.spec.ts+++ b/companions/src/application/lessons/l2.spec.ts@@ -7,18 +7,18 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, utimesSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { dirname, join } from 'node:path'-import { LessonBorrower, BORROW_EVERY_MS } from './borrow.js'-import { LessonCurator } from './curate.js'-import { LessonDistiller } from './distill.js'-import { LessonExporter } from './export.js'+import { LessonBorrower, BORROW_EVERY_MS } from '../../memory/lessons/borrow.js'+import { LessonCurator } from '../../memory/lessons/curate.js'+import { LessonDistiller } from '../../memory/lessons/distill.js'+import { LessonExporter } from '../../memory/lessons/export.js'import { PairLearner } from './propose.js'-import { installLessons, runtimeLessons } from './publish.js'-import { LessonStore } from './store.js'-import { LessonUsage } from './usage.js'-import { projectHash, type Signal } from './types.js'-import { PairVoice } from '../voice.js'-import type { DaemonSay } from '../protocol.js'-import type { ExportDestination } from '../rules.js'+import { installLessons, runtimeLessons } from '../../memory/lessons/publish.js'+import { LessonStore } from '../../memory/lessons/store.js'+import { LessonUsage } from '../../memory/lessons/usage.js'+import { projectHash, type Signal } from '../../memory/lessons/types.js'+import { PairVoice } from '../../companion/voice.js'+import type { DaemonSay } from '../../companion/protocol.js'+import type { ExportDestination } from '../../companion/rules.js'const DAY = 24 * 60 * 60_000let dir: stringdiff --git a/cli/src/pair/learn/propose.more.spec.ts b/companions/src/application/lessons/propose.more.spec.tssimilarity index 97%rename from cli/src/pair/learn/propose.more.spec.tsrename to companions/src/application/lessons/propose.more.spec.tsindex 8a0dddf5b..5e85a4d20 100644--- a/cli/src/pair/learn/propose.more.spec.ts+++ b/companions/src/application/lessons/propose.more.spec.ts@@ -9,17 +9,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { BORROW_EVERY_MS, type BorrowPass } from './borrow.js'-import type { CuratorPass } from './curate.js'-import type { Distilled } from './distill.js'-import type { ExportStep } from './export.js'+import { BORROW_EVERY_MS, type BorrowPass } from '../../memory/lessons/borrow.js'+import type { CuratorPass } from '../../memory/lessons/curate.js'+import type { Distilled } from '../../memory/lessons/distill.js'+import type { ExportStep } from '../../memory/lessons/export.js'import { DISTILL_EVERY_MS, PairLearner, joinProposals, type LearnerDeps } from './propose.js'-import { LESSONS_BEGIN, notesPath } from './publish.js'-import { LessonStore, NO_GIT_NOTE, type LessonRecord } from './store.js'-import { projectHash, type Lesson, type Provenance, type Signal } from './types.js'-import type { LessonUsage } from './usage.js'-import { DIALOG_MAX, type DaemonSay } from '../protocol.js'-import type { ExportDestination } from '../rules.js'+import { LESSONS_BEGIN, notesPath } from '../../memory/lessons/publish.js'+import { LessonStore, NO_GIT_NOTE, type LessonRecord } from '../../memory/lessons/store.js'+import { projectHash, type Lesson, type Provenance, type Signal } from '../../memory/lessons/types.js'+import type { LessonUsage } from '../../memory/lessons/usage.js'+import { DIALOG_MAX, type DaemonSay } from '../../companion/protocol.js'+import type { ExportDestination } from '../../companion/rules.js'let dir: stringlet ws: stringdiff --git a/cli/src/pair/learn/propose.spec.ts b/companions/src/application/lessons/propose.spec.tssimilarity index 97%rename from cli/src/pair/learn/propose.spec.tsrename to companions/src/application/lessons/propose.spec.tsindex bb5c1d6cb..4f2c94266 100644--- a/cli/src/pair/learn/propose.spec.ts+++ b/companions/src/application/lessons/propose.spec.ts@@ -8,21 +8,21 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { LessonDistiller } from './distill.js'-import { LessonStore, type LessonRecord } from './store.js'+import { LessonDistiller } from '../../memory/lessons/distill.js'+import { LessonStore, type LessonRecord } from '../../memory/lessons/store.js'import { PairLearner, joinProposals, LESSON_ASK_TTL_MS, LESSON_PROPOSAL_GAP_MS, LESSON_REPROPOSE_MS, DISTILL_EVERY_MS, SIGNAL_MAX_WAIT_MS, type LearnerDeps } from './propose.js'-import { LESSONS_BEGIN, notesPath } from './publish.js'-import { projectHash, type Signal } from './types.js'-import { PairVoice, DISPLAY_MS } from '../voice.js'-import { PairBrain } from '../brain.js'-import { PairControl, type ControlDeps } from '../control.js'-import { PairToken } from '../token.js'-import { ApprovalNonces, type CallerVerdict } from './approval.js'-import { pairCommand, parsePairArgs, PairUsageError, type PairSocket } from '../client.js'-import type { PairFleet } from '../fleet.js'-import type { PairTriage } from '../triage.js'-import type { Autonomy } from '../floor.js'-import type { DaemonSay } from '../protocol.js'+import { LESSONS_BEGIN, notesPath } from '../../memory/lessons/publish.js'+import { projectHash, type Signal } from '../../memory/lessons/types.js'+import { PairVoice, DISPLAY_MS } from '../../companion/voice.js'+import { PairBrain } from '../../companion/brain.js'+import { PairControl, type ControlDeps } from '../../companion/control.js'+import { PairToken } from '../../companion/token.js'+import { ApprovalNonces, type CallerVerdict } from '../../shared/approval.js'+import { pairCommand, parsePairArgs, PairUsageError, type PairSocket } from '../../companion/client.js'+import type { PairFleet } from '../../companion/fleet.js'+import type { PairTriage } from '../../companion/triage.js'+import type { Autonomy } from '../../companion/floor.js'+import type { DaemonSay } from '../../companion/protocol.js'type Frame = Record<string, unknown>diff --git a/cli/src/pair/learn/propose.ts b/companions/src/application/lessons/propose.tssimilarity index 97%rename from cli/src/pair/learn/propose.tsrename to companions/src/application/lessons/propose.tsindex 735b7ac19..1983d8bc8 100644--- a/cli/src/pair/learn/propose.ts+++ b/companions/src/application/lessons/propose.ts@@ -21,21 +21,21 @@* L2 rides the same tick: borrowing (borrow.ts, opt-in) adds candidates to the same queue of proposals, the* curator (curate.ts) marks and archives what goes unused, and export (export.ts, opt-in) follows every change.*/-import type { Autonomy } from '../floor.js'+import type { Autonomy } from '../../companion/floor.js'import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'import { dirname } from 'node:path'-import type { IntelligenceStatus } from '../intelligence.js'-import { DISPLAY_MS, keysPrefix } from '../voice.js'-import { DIALOG_MAX, statusText, str, type DaemonAction, type DaemonMood, type DaemonSay } from '../protocol.js'-import { lessonLineId } from './approval.js'-import { BORROW_EVERY_MS, type BorrowPass } from './borrow.js'-import type { CuratorPass } from './curate.js'-import type { Distilled } from './distill.js'-import type { ExportStep } from './export.js'-import { findProject, publishNote, unpublishNote, withdrawSkill } from './publish.js'-import { NO_GIT_NOTE, type LessonRecord, type LessonStore } from './store.js'-import { contentHash, type Signal } from './types.js'-import type { LessonUsage } from './usage.js'+import type { IntelligenceStatus } from '../../companion/intelligencePort.js'+import { DISPLAY_MS, keysPrefix } from '../../companion/voice.js'+import { DIALOG_MAX, statusText, str, type DaemonAction, type DaemonMood, type DaemonSay } from '../../companion/protocol.js'+import { lessonLineId } from '../../shared/approval.js'+import { BORROW_EVERY_MS, type BorrowPass } from '../../memory/lessons/borrow.js'+import type { CuratorPass } from '../../memory/lessons/curate.js'+import type { Distilled } from '../../memory/lessons/distill.js'+import type { ExportStep } from '../../memory/lessons/export.js'+import { findProject, publishNote, unpublishNote, withdrawSkill } from '../../memory/lessons/publish.js'+import { NO_GIT_NOTE, type LessonRecord, type LessonStore } from '../../memory/lessons/store.js'+import { contentHash, type Signal } from '../../memory/lessons/types.js'+import type { LessonUsage } from '../../memory/lessons/usage.js'export const LESSON_PROPOSAL_GAP_MS = 60 * 60_000export const LESSON_REPROPOSE_MS = 24 * 60 * 60_000diff --git a/companions/src/application/lessons/runtime.ts b/companions/src/application/lessons/runtime.tsnew file mode 100644index 000000000..e65e41827--- /dev/null+++ b/companions/src/application/lessons/runtime.ts@@ -0,0 +1,9 @@+/** Explicit publication into an already prepared optional DSH context. No core lifecycle imports. */+import { appendFileSync } from 'node:fs'+import { dirname } from 'node:path'+import { installLessons, type RuntimeLessons } from '../../memory/lessons/publish.js'++export function publishRuntimeLessons(contextFile: string, lessons?: RuntimeLessons | null): void {+ const lines = installLessons(dirname(contextFile), lessons)+ if (lines.length) appendFileSync(contextFile, `\n${lines.join('\n')}\n`)+}diff --git a/cli/src/memory/companion.spec.ts b/companions/src/application/memoryInference.spec.tssimilarity index 94%rename from cli/src/memory/companion.spec.tsrename to companions/src/application/memoryInference.spec.tsindex 378ca4d0f..1db1338c4 100644--- a/cli/src/memory/companion.spec.ts+++ b/companions/src/application/memoryInference.spec.ts@@ -2,13 +2,13 @@ import { expect, it, vi } from 'vitest'import { mkdtempSync, rmSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { companionMemoryInference } from './companion.js'-import { CompanionIntelligence, type CompanionRuntime } from '../pair/intelligence.js'-import { CodingMemoryStore } from './store.js'-import { MemoryLearner } from './learner.js'-import { QUEUE_OPERATIONS, type MemoryPort, type Operation, type Arguments, type Result } from './operations.js'-import { MemoryError } from './types.js'-import type { InferenceWaitReason } from './inferenceStatus.js'+import { companionMemoryInference } from './memoryInference.js'+import { CompanionIntelligence, type CompanionRuntime } from './intelligence.js'+import { CodingMemoryStore } from '../memory/store.js'+import { MemoryLearner } from '../memory/learner.js'+import { QUEUE_OPERATIONS, type MemoryPort, type Operation, type Arguments, type Result } from '../memory/operations.js'+import { MemoryError } from '../memory/types.js'+import type { InferenceWaitReason } from '../memory/inferenceStatus.js'it('waits for a certified selected Codex runtime and preserves foreground priority', async () => {const intelligence = { extractionStatus: async () => ({ state: 'ready' as const, agentId: 'companion', engine: 'codex', contextKey: 'selected' }),diff --git a/cli/src/memory/companion.ts b/companions/src/application/memoryInference.tssimilarity index 80%rename from cli/src/memory/companion.tsrename to companions/src/application/memoryInference.tsindex 47cdb6a90..4ca64efff 100644--- a/cli/src/memory/companion.ts+++ b/companions/src/application/memoryInference.ts@@ -1,10 +1,10 @@/** Bind background learning to the collection's observed native runtime. */-import type { CompanionIntelligence } from '../pair/intelligence.js'-import { codexMemoryCapability } from './inference.js'-import { claudeMemoryCapability } from './claudeInference.js'-import { opencodeMemoryCapability } from './opencodeInference.js'-import type { MemoryInference } from './learner.js'-import { inferenceWaitReason } from './inferenceStatus.js'+import type { CompanionIntelligence } from './intelligence.js'+import { codexMemoryCapability } from '../memory/inference.js'+import { claudeMemoryCapability } from '../memory/claudeInference.js'+import { opencodeMemoryCapability } from '../memory/opencodeInference.js'+import type { MemoryInference } from '../memory/learner.js'+import { inferenceWaitReason } from '../memory/inferenceStatus.js'export function companionMemoryInference(intelligence: Pick<CompanionIntelligence, 'extractionStatus' | 'extract'>,foregroundBusy: (companionAgentId: string) => boolean,diff --git a/companions/src/application/modelProfile.spec.ts b/companions/src/application/modelProfile.spec.tsnew file mode 100644index 000000000..f919bc847--- /dev/null+++ b/companions/src/application/modelProfile.spec.ts@@ -0,0 +1,19 @@+import { expect, it } from 'vitest'+import { encodeRuntimeProfile as encodeCore, parseRuntimeProfile as parseCore } from '../../../cli/src/lib/runtimeProfile.js'+import { encodeRuntimeProfile, parseRuntimeProfile } from './modelProfile.js'++it.each(['claude', 'codex', 'opencode'] as const)('reads the existing %s public model ID without its runtime manager', engine => {+ for (const effort of ['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra', 'ultracode']) {+ const input = { sessionId: 'agent:with spaces', engine, model: 'provider/model@variant', effort }+ const id = encodeCore(input)+ expect(encodeRuntimeProfile(input)).toBe(id)+ expect(parseRuntimeProfile(id)).toEqual(parseCore(id))+ }+})++it.each([null, '', 'runtime-v2:a:claude:opus@high', 'runtime-v1:a:claude:%zz@high',+ 'runtime-v1:a:claude:opus@unknown', 'runtime-v1:a:unknown:opus@high'])(+ 'does not select a model from an unsupported or malformed ID %s', value => {+ expect(parseRuntimeProfile(value)).toBeNull()+ },+)diff --git a/companions/src/application/modelProfile.ts b/companions/src/application/modelProfile.tsnew file mode 100644index 000000000..6066ff00e--- /dev/null+++ b/companions/src/application/modelProfile.ts@@ -0,0 +1,24 @@+/** Read the existing runtime-v1 model ID without loading the CLI's runtime manager or config. */+export interface RuntimeProfile {+ id: string+ sessionId: string+ engine: 'claude' | 'codex' | 'opencode'+ model: string+ effort: string+}+const EFFORTS = new Set(['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra', 'ultracode'])++export function encodeRuntimeProfile(profile: Omit<RuntimeProfile, 'id'>): string {+ return `runtime-v1:${encodeURIComponent(profile.sessionId)}:${profile.engine}:${encodeURIComponent(profile.model)}@${profile.effort}`+}++export function parseRuntimeProfile(value: unknown): RuntimeProfile | null {+ if (typeof value !== 'string') return null+ const match = /^runtime-v1:([^:]+):(claude|codex|opencode):([^@]+)@([a-z0-9_-]+)$/i.exec(value)+ if (!match) return null+ try {+ const sessionId = decodeURIComponent(match[1]), model = decodeURIComponent(match[3]), effort = match[4].toLowerCase()+ if (!sessionId || !model || !EFFORTS.has(effort)) return null+ return { id: value, sessionId, engine: match[2].toLowerCase() as RuntimeProfile['engine'], model, effort }+ } catch { return null }+}diff --git a/companions/src/boundaries.spec.ts b/companions/src/boundaries.spec.tsnew file mode 100644index 000000000..1245b82c8--- /dev/null+++ b/companions/src/boundaries.spec.ts@@ -0,0 +1,41 @@+import { readdirSync, readFileSync } from 'node:fs'+import { dirname, join, relative, resolve } from 'node:path'+import { fileURLToPath } from 'node:url'+import ts from 'typescript'+import { expect, it } from 'vitest'++const sourceRoot = fileURLToPath(new URL('.', import.meta.url))+function files(directory: string): string[] {+ return readdirSync(directory, { withFileTypes: true }).flatMap(entry => {+ const path = join(directory, entry.name)+ return entry.isDirectory() ? files(path) : path.endsWith('.ts') && !path.endsWith('.spec.ts') ? [path] : []+ })+}+function imports(path: string): string[] {+ const source = ts.createSourceFile(path, readFileSync(path, 'utf8'), ts.ScriptTarget.Latest, true)+ const found: string[] = []+ function visit(node: ts.Node): void {+ if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {+ found.push(node.moduleSpecifier.text)+ }+ if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments[0] && ts.isStringLiteral(node.arguments[0])) {+ found.push(node.arguments[0].text)+ }+ ts.forEachChild(node, visit)+ }+ visit(source)+ return found.map(specifier => relative(sourceRoot, resolve(dirname(path), specifier)).replaceAll('\\', '/'))+}++it('keeps knowledge independent of the character and application implementations', () => {+ const violations = files(join(sourceRoot, 'memory')).flatMap(path => imports(path)+ .filter(target => /^(companion|application)\//.test(target)).map(target => `${relative(sourceRoot, path)} -> ${target}`))+ expect(violations).toEqual([])+})++it('lets characters use only the public Memory contract', () => {+ const violations = files(join(sourceRoot, 'companion')).flatMap(path => imports(path)+ .filter(target => target.startsWith('application/') || target.startsWith('memory/') && target !== 'memory/api.js')+ .map(target => `${relative(sourceRoot, path)} -> ${target}`))+ expect(violations).toEqual([])+})diff --git a/companions/src/companion/api.ts b/companions/src/companion/api.tsnew file mode 100644index 000000000..a75fe718f--- /dev/null+++ b/companions/src/companion/api.ts@@ -0,0 +1,12 @@+/** Optional character subsystem. Importing this module starts no work. */+export { PairHarness, pairPackage, pairInstructions, type PairHarnessDeps, type PairHarnessRow } from './pairHarness.js'+export { PairBrain, type PairBrainDeps } from './brain.js'+export { PairControl, type ControlDeps } from './control.js'+export { PairSensor } from './sensor.js'+export { CompanionToolCalls } from './toolCalls.js'+export { PairJournal } from './journal.js'+export { PairToken } from './token.js'+export { CompanionZoo, companionIdentity } from './companionIdentity.js'+export { DaemonsSwitch } from './daemonsSwitch.js'+export { PlateService } from './plateService.js'+export type { CompanionMemory } from '../memory/api.js'diff --git a/cli/src/pair/brain.more.spec.ts b/companions/src/companion/brain.more.spec.tssimilarity index 100%rename from cli/src/pair/brain.more.spec.tsrename to companions/src/companion/brain.more.spec.tsdiff --git a/cli/src/pair/brain.spec.ts b/companions/src/companion/brain.spec.tssimilarity index 99%rename from cli/src/pair/brain.spec.tsrename to companions/src/companion/brain.spec.tsindex 3c9ec9570..f0b941963 100644--- a/cli/src/pair/brain.spec.ts+++ b/companions/src/companion/brain.spec.ts@@ -19,7 +19,7 @@ import { PairBrain, TALK_COST_NOTE, type AnswerResult } from './brain.js'import { ARM_MS, ShownLines } from './shown.js'import type { DaemonSay, PairEvent, PairQuestion } from './protocol.js'import type { Autonomy } from './floor.js'-import { BackendSocket } from '../backendSocket.js'+import { BackendSocket } from '../../../cli/src/backendSocket.js'type Frame = Record<string, unknown>diff --git a/cli/src/pair/brain.ts b/companions/src/companion/brain.tssimilarity index 100%rename from cli/src/pair/brain.tsrename to companions/src/companion/brain.tsdiff --git a/cli/src/pair/brief.more.spec.ts b/companions/src/companion/brief.more.spec.tssimilarity index 100%rename from cli/src/pair/brief.more.spec.tsrename to companions/src/companion/brief.more.spec.tsdiff --git a/cli/src/pair/brief.spec.ts b/companions/src/companion/brief.spec.tssimilarity index 100%rename from cli/src/pair/brief.spec.tsrename to companions/src/companion/brief.spec.tsdiff --git a/cli/src/pair/brief.ts b/companions/src/companion/brief.tssimilarity index 100%rename from cli/src/pair/brief.tsrename to companions/src/companion/brief.tsdiff --git a/cli/src/pair/client.spec.ts b/companions/src/companion/client.spec.tssimilarity index 100%rename from cli/src/pair/client.spec.tsrename to companions/src/companion/client.spec.tsdiff --git a/cli/src/pair/client.ts b/companions/src/companion/client.tssimilarity index 98%rename from cli/src/pair/client.tsrename to companions/src/companion/client.tsindex eb051bd48..ac2659b66 100644--- a/cli/src/pair/client.ts+++ b/companions/src/companion/client.ts@@ -9,10 +9,10 @@*/import { randomUUID } from 'node:crypto'import { CONTROL_TOOLS } from './control.js'-import { harnessPaneEnv } from './learn/approval.js'+import { harnessPaneEnv } from '../shared/approval.js'import { presentedToken } from './token.js'-import { HARNESS_SESSION_PREFIX } from '../lib/harnessSessionLabel.js'-import { conditionsSchema } from '../memory/types.js'+import { HARNESS_SESSION_PREFIX } from '../../../cli/src/lib/harnessSessionLabel.js'+import { conditionsSchema } from '../memory/api.js'export interface PairSocket {send(data: string): voiddiff --git a/cli/src/cable/companionIdentity.spec.ts b/companions/src/companion/companionIdentity.spec.tssimilarity index 98%rename from cli/src/cable/companionIdentity.spec.tsrename to companions/src/companion/companionIdentity.spec.tsindex f5e9e3aec..de7954903 100644--- a/cli/src/cable/companionIdentity.spec.ts+++ b/companions/src/companion/companionIdentity.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest'import { CompanionZoo, companionIdentity, readCompanionIdentity, COMPANION_SPECIES } from './companionIdentity.js'-import type { ZooIndividual } from '../pair/individuals.js'+import type { ZooIndividual } from './individuals.js'const individual = (id = 'tim', changes: Partial<ZooIndividual> = {}): ZooIndividual => ({id, uid: `individual_${id}`, seed: 123456, serial: 42, name: 'Pip', version: '0.1', hatched: 100_000, ...changes,diff --git a/cli/src/cable/companionIdentity.ts b/companions/src/companion/companionIdentity.tssimilarity index 70%rename from cli/src/cable/companionIdentity.tsrename to companions/src/companion/companionIdentity.tsindex 6d7643531..3b8c43313 100644--- a/cli/src/cable/companionIdentity.ts+++ b/companions/src/companion/companionIdentity.ts@@ -1,35 +1,17 @@-import { pairedIndividual, zooIndividuals, type ZooIndividual } from '../pair/individuals.js'-import { rollTraits } from '../pair/plates/render.g.js'-import { PLATE_ROSTER } from '../pair/plates/models.g.js'+import { pairedIndividual, zooIndividuals, type ZooIndividual } from './individuals.js'+import { rollTraits } from './plates/render.g.js'+import { PLATE_ROSTER } from './plates/models.g.js'++export { COMPANION_SPECIES, readCompanionIdentity, type CompanionIdentity } from '../../../cli/src/cable/companionProtocol.js'+import { COMPANION_SPECIES, type CompanionIdentity } from '../../../cli/src/cable/companionProtocol.js'-export const COMPANION_SPECIES = ['tim', 'gnu', 'lynx', 'mutt', 'yak', 'gopher', 'bug', 'tux', 'auk', 'beastie'] as const-export interface CompanionIdentity {- id: string- uid: string- seed: number- name: string- version: '0.1' | '1.0' | '2.0'- colour: number- mark: number-}export interface CompanionMilestone {token: stringkind: 'hatch' | 'grow'at: numbercompanion: CompanionIdentity}-export function readCompanionIdentity(value: unknown): CompanionIdentity | null {- if (!value || typeof value !== 'object') return null- const d = value as Record<string, unknown>- if (typeof d.id !== 'string' || !COMPANION_SPECIES.includes(d.id as typeof COMPANION_SPECIES[number]) ||- typeof d.uid !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(d.uid) ||- typeof d.name !== 'string' || !/^[\x20-\x7e]{1,24}$/.test(d.name) ||- !['0.1','1.0','2.0'].includes(d.version as string) ||- !Number.isInteger(d.seed) || (d.seed as number)<0 || (d.seed as number)>0xffffffff ||- !Number.isInteger(d.colour) || (d.colour as number)<-1 || (d.colour as number)>5 ||- !Number.isInteger(d.mark) || (d.mark as number)<0 || (d.mark as number)>4) return null- return {id:d.id,uid:d.uid,name:d.name,version:d.version as CompanionIdentity['version'],seed:d.seed as number,colour:d.colour as number,mark:d.mark as number}-}+export const sameCompanion = (a: CompanionIdentity | null | undefined, b: CompanionIdentity | null | undefined): boolean =>(!a || !b) ? !a && !b : a.id===b.id && a.uid===b.uid && a.seed===b.seed && a.name===b.name && a.version===b.version && a.colour===b.colour && a.mark===b.markdiff --git a/cli/src/pair/control.more.spec.ts b/companions/src/companion/control.more.spec.tssimilarity index 99%rename from cli/src/pair/control.more.spec.tsrename to companions/src/companion/control.more.spec.tsindex 46ef94ab9..f70197e7c 100644--- a/cli/src/pair/control.more.spec.ts+++ b/companions/src/companion/control.more.spec.ts@@ -10,7 +10,7 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, stimport { tmpdir } from 'node:os'import { join } from 'node:path'import { PairControl, SAY_MIN_GAP_MS, StartedHarnesses, type ControlDeps } from './control.js'-import { ApprovalNonces, type CallerVerdict } from './learn/approval.js'+import { ApprovalNonces, type CallerVerdict } from '../shared/approval.js'import { DIALOG_MAX, type DaemonSay } from './protocol.js'import { backLine } from './voice.js'import type { Autonomy } from './floor.js'diff --git a/cli/src/pair/control.spec.ts b/companions/src/companion/control.spec.tssimilarity index 100%rename from cli/src/pair/control.spec.tsrename to companions/src/companion/control.spec.tsdiff --git a/cli/src/pair/control.ts b/companions/src/companion/control.tssimilarity index 99%rename from cli/src/pair/control.tsrename to companions/src/companion/control.tsindex 628b3f013..7f692a669 100644--- a/cli/src/pair/control.ts+++ b/companions/src/companion/control.ts@@ -34,8 +34,8 @@ import { answerFloor, bareOption, type Autonomy } from './floor.js'import type { OwnerRow } from './owner.js'import { RateLimit } from './limit.js'import { redactDeep } from './redact.js'-import { APPROVAL_NONCE_TTL_MS, isPersonAction, PERSON_ACTIONS, type ApprovalNonces, type CallerVerdict } from './learn/approval.js'-import { MEMORY_RECALL_CONDITIONS_SCHEMA } from '../memory/context.js'+import { APPROVAL_NONCE_TTL_MS, isPersonAction, PERSON_ACTIONS, type ApprovalNonces, type CallerVerdict } from '../shared/approval.js'+import { MEMORY_RECALL_CONDITIONS_SCHEMA } from '../memory/api.js'export type ToolKind = 'read' | 'write' | 'say'diff --git a/cli/src/lib/daemonsSwitch.spec.ts b/companions/src/companion/daemonsSwitch.spec.tssimilarity index 78%rename from cli/src/lib/daemonsSwitch.spec.tsrename to companions/src/companion/daemonsSwitch.spec.tsindex 96a31b894..fef902f03 100644--- a/cli/src/lib/daemonsSwitch.spec.ts+++ b/companions/src/companion/daemonsSwitch.spec.ts@@ -12,8 +12,8 @@ import {} from './daemonsSwitch.js'import { ZooTurnReporter, ZOO_TURN_FLUSH_MS } from './zooTurns.js'import { ZooLessonReporter } from './zooLessons.js'-import { PairJournal } from '../pair/journal.js'-import { PairSensor } from '../pair/sensor.js'+import { PairJournal } from './journal.js'+import { PairSensor } from './sensor.js'const HOUR = 60 * 60_000const zoo = (pair: string | null = 'tim'): ZooRead => ({ status: 200, body: { success: true, data: { revision: 3, zoo: { pair, autonomy: 'watch', consent: { watching: true, at: 1 } } } } })@@ -404,80 +404,3 @@ describe('what stays untouched while off', () => {}})})--/**- * The switch only keeps harnessd idle if cli.ts routes everything daemon-related through it. runForeground is- * one very long function no unit test drives, so its wiring is asserted on the source, the way- * startupOrder.spec.ts asserts its declaration order.- */-describe('cli.ts routes everything daemon-related through the switch', () => {- const source = readFileSync(join(import.meta.dirname, '..', 'cli.ts'), 'utf-8')- const at = (needle: string): number => {- const index = source.indexOf(needle)- expect(index, needle).toBeGreaterThan(-1)- return index- }- /** The body of `onDaemonsChanged = (on) => { … }`, by brace balance. */- const onChanged = (() => {- const from = at('onDaemonsChanged = (on) => {')- let depth = 0- for (let i = source.indexOf('{', from); i < source.length; i++) {- if (source[i] === '{') depth++- else if (source[i] === '}' && --depth === 0) return source.slice(from, i + 1)- }- return ''- })()-- it('asks the backend for the zoo in exactly two places: the probe and the reporters\' POST, which it observes', () => {- expect(source.match(/'\/api\/zoo'/g)).toHaveLength(1)- expect(source.match(/'\/api\/zoo\/ops'/g)).toHaveLength(1)- expect(source).toContain("read: () => proxyBackend('GET', '/api/zoo')")- expect(source).toMatch(/const answer = await proxyBackend\('POST', '\/api\/zoo\/ops', body\)\s+daemons\.observe\(answer\)/)- expect(source).not.toContain('refreshPairFromZoo')- // A window's own read goes through the passthrough, killed here or observed.- expect(source).toContain('onZooRead: () => zooProxy.read()')- expect(source).toContain('onZooOps: (body) => zooProxy.ops(body)')- })-- it('arms the pair\'s timers only inside onDaemonsChanged, and starts the switch once all of it is wired', () => {- // Track the owned registrations, independent of the optional feature guards in their callbacks.- const timers = [...source.matchAll(/(?:learnTick|pairConfigTick)\s*\?\?=\s*setInterval\([^\n]+/g)]- expect(timers).toHaveLength(2)- for (const timer of timers) expect(onChanged).toContain(timer[0])- expect(onChanged).toContain('clearInterval(learnTick)')- expect(onChanged).toContain('clearInterval(pairConfigTick)')- expect(onChanged).toContain('zooTurnReporter.clear()')- expect(onChanged).toContain('pairHarness.off()')- expect(onChanged).toContain('if (daemons.on() && codingMemoryPreview()) codingMemory?.start()')- expect(onChanged).toContain('if (!codingMemoryPreview()) void pairLearner?.tick()')- expect(onChanged).toContain('codingMemory?.pause()')- expect(at('daemons.start()')).toBeGreaterThan(at('pairBrain = new PairBrain({'))- expect(at('daemons.start()')).toBeGreaterThan(at('onDaemonsChanged = (on) => {'))- })-- it('tells the windows already attached: the switch, pairing and the zoo\'s pair and dial all refresh the brain', () => {- expect(onChanged).toMatch(/applyPair\(\)\s+pairBrain\?\.refresh\(\)\s+\}$/)- const pairToggled = source.match(/onPairToggled = \(on\) => \{([\s\S]*?)\n \}/)?.[1] ?? ''- expect(pairToggled).toMatch(/if \(on\) questionWatcher\.reset\(\)[\s;]+pairBrain\?\.refresh\(\)/)- const applyPair = source.match(/const applyPair = \(\)(?:: void)? => \{([\s\S]*?)\n \}/)?.[1] ?? ''- expect(applyPair).toMatch(/pairSensor\.setPair\(pairing\.pair, [^\n]+\)[\s\S]*pairBrain\?\.refresh\(\)/)- expect(applyPair).toContain('refreshPairPackage()')- })-- it('gates the reporters, turns, lessons, the pair harness, the pair request and every daemon_* frame', () => {- expect(source.match(/enabled: \(\) => daemons\.on\(\)/g)).toHaveLength(3)- expect(source).toContain('if (daemons.on()) zooTurnCounter.started(')- expect(source).toContain('if (learnFrom && daemons.on() && !isTerminalEngine(learnFrom.engine)) {')- expect(source).toContain('if (!daemons.on()) return null') // lessons in launches- expect(source).toContain('pairHarnessActivity = (agentId) => { if (daemons.on()) pairHarness.activity(agentId) }')- expect(source).toContain('backend.daemonsOn = () => daemons.on()')- expect(source).toContain("if (!daemons.on()) { pairSensor.setPair(null); return }") // applyPair- for (const frame of ['daemon_act_result', 'daemon_confirm_result', 'daemon_talk_result']) {- expect(source).toMatch(new RegExp(`const off = !daemons\\.on\\(\\) \\? DAEMONS_OFF[^\\n]*\\n\\s+if \\(off\\) \\{ reply\\(\\{ type: '${frame}'`))- }- expect(source).toContain('onDaemonShown: (connId, payload) => { if (daemons.on()) pairBrain?.onShown(connId, payload) }')- expect(source).toContain('if (daemons.on()) pairBrain?.onPresence(connId, payload, meta)')- expect(source).toContain('onBackendConnected = () => { daemons.connected() }')- expect(source).toContain('backend.onZooChanged = () => daemons.zooChanged()')- })-})diff --git a/cli/src/lib/daemonsSwitch.ts b/companions/src/companion/daemonsSwitch.tssimilarity index 99%rename from cli/src/lib/daemonsSwitch.tsrename to companions/src/companion/daemonsSwitch.tsindex c10d1959b..df100006e 100644--- a/cli/src/lib/daemonsSwitch.ts+++ b/companions/src/companion/daemonsSwitch.ts@@ -28,7 +28,7 @@* without a second request.*/import { statSync, readFileSync } from 'node:fs'-import { parseJsonc } from '../pair/rules.js'+import { parseJsonc } from './rules.js'/** What a window, `harness pair` or a tool is answered while daemons are off. Never an error that breaks it. */export const DAEMONS_OFF = 'DAEMONS_OFF'diff --git a/cli/src/pair/fleet.spec.ts b/companions/src/companion/fleet.spec.tssimilarity index 100%rename from cli/src/pair/fleet.spec.tsrename to companions/src/companion/fleet.spec.tsdiff --git a/cli/src/pair/fleet.ts b/companions/src/companion/fleet.tssimilarity index 100%rename from cli/src/pair/fleet.tsrename to companions/src/companion/fleet.tsdiff --git a/cli/src/pair/floor.spec.ts b/companions/src/companion/floor.spec.tssimilarity index 100%rename from cli/src/pair/floor.spec.tsrename to companions/src/companion/floor.spec.tsdiff --git a/cli/src/pair/floor.ts b/companions/src/companion/floor.tssimilarity index 100%rename from cli/src/pair/floor.tsrename to companions/src/companion/floor.tsdiff --git a/companions/src/companion/frames.spec.ts b/companions/src/companion/frames.spec.tsnew file mode 100644index 000000000..c020a7186--- /dev/null+++ b/companions/src/companion/frames.spec.ts@@ -0,0 +1,109 @@+/**+ * P0 — the pair brain's contract and sealing (daemons/BRAIN.md).+ *+ * The frames between two machines' daemons carry question text and recaps, and one of them keys an+ * answer into a pane. Every one is sealed pairwise; the relay reads the outer type and nothing else, and+ * nothing it writes in the clear is believed. Driven against the REAL E2eeManager and RelaySessionCrypto,+ * so a type missing from applicationFrames.ts fails here rather than travelling plaintext.+ */+import { afterEach, describe, expect, it, vi } from 'vitest'+import * as C from '../../../cli/src/lib/e2ee/core.js'+import { RelaySessionCrypto } from '../../../cli/src/lib/e2ee/relayClient.js'+import {+ admitRelayedPairFrame, encryptDownFrame, encryptRpcResult, PAIR_PUSHES, PAIR_REQUESTS, PAIR_RESULTS, PLATE_REQUEST, PLATE_RESULT,+} from '../../../cli/src/lib/e2ee/applicationFrames.js'+import { BackendSocket } from '../../../cli/src/backendSocket.js'+import type { PairEvent, PairService, PairSnapshot } from './protocol.js'++type Frame = Record<string, unknown>++/** A paired peer (another machine's brain) with a live session on `socket`'s daemon. */+function pairedPeer(socket: BackendSocket, connId: string) {+ const e2ee = socket.e2ee as unknown as { store: { addPaired: (pub: string, label: string, at: number, role: 'web') => void; getIdentity: () => C.Identity } }+ const identity = C.newIdentity()+ e2ee.store.addPaired(C.b64e(identity.pub), 'peer brain', Date.now(), 'web')+ const sent: Array<{ connId: string; frame: Frame }> = []+ vi.spyOn(socket, 'sendTo').mockImplementation((to: string, frame: Frame) => { sent.push({ connId: to, frame }) })+ const crypto = new RelaySessionCrypto({ machineId: socket.machineId, selfIdentity: identity, peerPub: e2ee.store.getIdentity().pub })+ socket.e2ee.handleFrame(connId, crypto.helloFrame())+ const welcome = sent.pop()!+ expect(welcome.frame.type).toBe('e2e_welcome')+ expect(crypto.handleWelcome(welcome.frame.payload as Frame)).toBe(true)+ return { crypto, sent }+}++const SNAPSHOT: PairSnapshot = {+ machineId: 'machine-a', epoch: 'e1', seq: 3, rev: 7,+ harnesses: [{ agentId: 'a1', name: 'api', engine: 'claude', working: true, failing: null, lastDoneAt: null, recap: null,+ question: { requestId: 'q_1', text: 'Run the migration?', options: ['Yes', 'No'], multi: false, deny: false, allow: false, permission: false, since: 1 } }],+}++function fakeService(overrides: Partial<PairService> = {}): PairService & { pushes: Map<string, (e: PairEvent) => boolean> } {+ const pushes = new Map<string, (e: PairEvent) => boolean>()+ return {+ pushes,+ enabled: () => true,+ watch: (connId, push) => { pushes.set(connId, push); return SNAPSHOT },+ unwatch: (connId) => { pushes.delete(connId) },+ journal: () => ({ epoch: 'e1', seq: 3, entries: [] }),+ read: (payload) => ({ agentId: payload.agentId, recap: 'shipped the fix' }),+ local: async (payload) => ({ verb: payload.verb, ok: true }),+ ...overrides,+ }+}++afterEach(() => vi.restoreAllMocks())++describe('pair frames are sealed application frames', () => {++ it('registers every request, result and push, and nothing else under pair_', () => {+ expect([...PAIR_REQUESTS].sort()).toEqual(['pair_answer', 'pair_journal', 'pair_list', 'pair_pause', 'pair_read',+ 'pair_resume', 'pair_send', 'pair_start', 'pair_stop', 'pair_watch'])+ expect([...PAIR_PUSHES]).toEqual(['pair_event'])+ for (const type of PAIR_REQUESTS) {+ expect(encryptDownFrame(type)).toBe(true)+ expect(encryptRpcResult(`${type}_result`)).toBe(true)+ expect(PAIR_RESULTS.has(`${type}_result`)).toBe(true)+ }+ // The loopback `pair` is never sealed going down (it never leaves this computer) but its reply is,+ // should a relayed one ever be answered LOCAL_ONLY.+ expect(encryptDownFrame('pair')).toBe(false)+ expect(encryptRpcResult('pair_result')).toBe(true)+ })++ it('seals every pair request end to end; the relay sees only the type', async () => {+ const socket = new BackendSocket('token')+ const { crypto } = pairedPeer(socket, 'peer-1')+ for (const type of PAIR_REQUESTS) {+ const request = { requestId: `${type}-1`, agentId: 'a1', question: 'Run the migration?' }+ const sealed = crypto.wrapOutgoing({ type, payload: request })+ expect(JSON.stringify(sealed)).not.toContain('migration')+ expect(sealed.payload).not.toHaveProperty('agentId')+ expect(socket.e2ee.unwrapDown('peer-1', sealed)?.payload).toEqual(request)+ }+ await socket.stop()+ })++ it('pair_event pushed with wrapTarget opens on the watching machine, and only there', async () => {+ const socket = new BackendSocket('token')+ const { crypto } = pairedPeer(socket, 'peer-1')+ const event: PairEvent = { machineId: 'machine-a', rev: 8, agentId: 'a1', harness: SNAPSHOT.harnesses[0] }+ const sealed = socket.e2ee.wrapTarget('peer-1', 'pair_event', event as unknown as Frame)!+ expect(JSON.stringify(sealed)).not.toContain('migration')+ expect(admitRelayedPairFrame(sealed)).toBe(true)+ expect(crypto.unwrapIncoming(sealed)?.payload).toEqual(event)+ // A connection with no session gets nothing at all rather than a plaintext push.+ expect(socket.e2ee.wrapTarget('stranger', 'pair_event', event as unknown as Frame)).toBeNull()+ await socket.stop()+ })++ it('the watching machine believes no pair frame the relay wrote in the clear or under the group key', () => {+ expect(admitRelayedPairFrame({ type: 'pair_event', payload: { machineId: 'm', harness: {} } })).toBe(false)+ expect(admitRelayedPairFrame({ type: 'pair_watch_result', payload: { requestId: 'r', snapshot: SNAPSHOT } })).toBe(false)+ expect(admitRelayedPairFrame({ type: 'pair_event', payload: { __e2e: { v: 1, k: 'g', n: 1, ct: 'x' } } })).toBe(false)+ expect(admitRelayedPairFrame({ type: 'pair_event', payload: null })).toBe(false)+ // An older daemon's bare refusal is the one plaintext pair frame heard: it names the machine as too old.+ expect(admitRelayedPairFrame({ type: 'pair_watch_result', payload: { requestId: 'r', error: 'UNSUPPORTED' } })).toBe(true)+ expect(admitRelayedPairFrame({ type: 'pair_event', payload: { requestId: 'r', error: 'UNSUPPORTED' } })).toBe(false)+ })+})diff --git a/cli/src/pair/gate.more.spec.ts b/companions/src/companion/gate.more.spec.tssimilarity index 100%rename from cli/src/pair/gate.more.spec.tsrename to companions/src/companion/gate.more.spec.tsdiff --git a/cli/src/pair/gate.spec.ts b/companions/src/companion/gate.spec.tssimilarity index 100%rename from cli/src/pair/gate.spec.tsrename to companions/src/companion/gate.spec.tsdiff --git a/cli/src/pair/gate.ts b/companions/src/companion/gate.tssimilarity index 100%rename from cli/src/pair/gate.tsrename to companions/src/companion/gate.tsdiff --git a/cli/src/pair/individuals.spec.ts b/companions/src/companion/individuals.spec.tssimilarity index 100%rename from cli/src/pair/individuals.spec.tsrename to companions/src/companion/individuals.spec.tsdiff --git a/cli/src/pair/individuals.ts b/companions/src/companion/individuals.tssimilarity index 100%rename from cli/src/pair/individuals.tsrename to companions/src/companion/individuals.tsdiff --git a/companions/src/companion/intelligencePort.ts b/companions/src/companion/intelligencePort.tsnew file mode 100644index 000000000..75f611b4d--- /dev/null+++ b/companions/src/companion/intelligencePort.ts@@ -0,0 +1,10 @@+/** Observed model availability, supplied by the application. No engine or memory implementation. */+export interface IntelligenceStatus {+ state: 'off' | 'unopened' | 'waiting' | 'unsupported' | 'ready'+ agentId?: string+ engine?: string+ model?: string+ effort?: string+ contextKey?: string+ reason?: string+}diff --git a/cli/src/pair/journal.spec.ts b/companions/src/companion/journal.spec.tssimilarity index 100%rename from cli/src/pair/journal.spec.tsrename to companions/src/companion/journal.spec.tsdiff --git a/cli/src/pair/journal.ts b/companions/src/companion/journal.tssimilarity index 100%rename from cli/src/pair/journal.tsrename to companions/src/companion/journal.tsdiff --git a/cli/src/pair/limit.spec.ts b/companions/src/companion/limit.spec.tssimilarity index 100%rename from cli/src/pair/limit.spec.tsrename to companions/src/companion/limit.spec.tsdiff --git a/cli/src/pair/limit.ts b/companions/src/companion/limit.tssimilarity index 100%rename from cli/src/pair/limit.tsrename to companions/src/companion/limit.tsdiff --git a/cli/src/pair/mcp.more.spec.ts b/companions/src/companion/mcp.more.spec.tssimilarity index 100%rename from cli/src/pair/mcp.more.spec.tsrename to companions/src/companion/mcp.more.spec.tsdiff --git a/cli/src/pair/mcp.spec.ts b/companions/src/companion/mcp.spec.tssimilarity index 85%rename from cli/src/pair/mcp.spec.tsrename to companions/src/companion/mcp.spec.tsindex 0d134b781..d64e15040 100644--- a/cli/src/pair/mcp.spec.ts+++ b/companions/src/companion/mcp.spec.ts@@ -10,7 +10,7 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import { handleMcpMessage, MCP_SERVER_NAME, serveMcp } from './mcp.js'import { pairCommand, pairRequest, pairVerb, parsePairArgs, PairUsageError, type PairSocket } from './client.js'-import { BackendSocket } from '../backendSocket.js'+import { BackendSocket } from '../../../cli/src/backendSocket.js'type Json = Record<string, unknown>@@ -138,29 +138,3 @@ describe('harness pair <verb>', () => {expect(await pairCommand(['send_prompt'], deps)).toBe(2)})})--describe('a tool client on the loopback socket', () => {- it('is answered, but is not presence: no window, no pair brain, no daemon_* lines', async () => {- const socket = new BackendSocket('token')- const attached = vi.fn()- socket.onLocalClient = attached- const tool: Json[] = []- const window: Json[] = []- socket.registerLocalClient('local:tool', { sendFrame: (f) => { tool.push(f as Json); return true }, sendBinary: () => true }, { tool: true })- expect(socket.hasLocalClient()).toBe(false)- expect(socket.localClientIds()).toEqual([])- expect(attached).not.toHaveBeenCalled()- socket.registerLocalClient('local:window', { sendFrame: (f) => { window.push(f as Json); return true }, sendBinary: () => true })- expect(socket.hasLocalClient()).toBe(true)- socket.sendLocal({ type: 'daemon_say', payload: { id: 'x' } })- expect(window.map((f) => f.type)).toContain('daemon_say')- expect(tool.map((f) => f.type)).not.toContain('daemon_say')- socket.pairControl = { verbs: new Set(['list_harnesses']), local: async (payload) => ({ ok: true, verb: payload.verb }) }- socket.handleLocalFrame('local:tool', { type: 'pair', payload: { requestId: 'r1', verb: 'list_harnesses' } })- await vi.waitFor(() => expect(tool).toContainEqual({ type: 'pair_result', payload: { requestId: 'r1', ok: true, verb: 'list_harnesses' } }))- await socket.unregisterLocalClient('local:tool')- expect(attached).toHaveBeenCalledTimes(1) // the window only- await socket.unregisterLocalClient('local:window')- await socket.stop()- })-})diff --git a/cli/src/pair/mcp.ts b/companions/src/companion/mcp.tssimilarity index 100%rename from cli/src/pair/mcp.tsrename to companions/src/companion/mcp.tsdiff --git a/cli/src/pair/owner.more.spec.ts b/companions/src/companion/owner.more.spec.tssimilarity index 100%rename from cli/src/pair/owner.more.spec.tsrename to companions/src/companion/owner.more.spec.tsdiff --git a/cli/src/pair/owner.spec.ts b/companions/src/companion/owner.spec.tssimilarity index 98%rename from cli/src/pair/owner.spec.tsrename to companions/src/companion/owner.spec.tsindex 3b6db3228..617fb71fe 100644--- a/cli/src/pair/owner.spec.ts+++ b/companions/src/companion/owner.spec.ts@@ -12,8 +12,8 @@ import { PairSensor } from './sensor.js'import { PairOwner, type OwnerDeps, type OwnerSubject } from './owner.js'import { answerFloor, matchOption } from './floor.js'import type { Autonomy } from './floor.js'-import { AskQuestionController, parseEngineQuestionPane, questionRequestId, type QuestionView } from '../lib/askQuestion.js'-import type { RegisteredSession } from '../lib/registry.js'+import { AskQuestionController, parseEngineQuestionPane, questionRequestId, type QuestionView } from '../../../cli/src/lib/askQuestion.js'+import type { RegisteredSession } from '../../../cli/src/lib/registry.js'const SUBJECTS: Record<string, OwnerSubject> = {api: { agentId: 'api', name: 'api', engine: 'claude', status: 'live', untouchable: null, cwd: '/w/api' },@@ -146,7 +146,7 @@ describe('answers', () => {})describe('through the real AskQuestionController', () => {- const permission = (): string => readFileSync(join(__dirname, '../lib/__fixtures__/permission-claude.txt'), 'utf8')+ const permission = (): string => readFileSync(join(__dirname, '../../../cli/src/lib/__fixtures__/permission-claude.txt'), 'utf8')const changed = (): string => permission().replaceAll('curl -s https://api.coingecko.com/api/v3/simple/price?ids=bitcoin', 'npm run build')const idOf = (capture: string): string => questionRequestId('s1', parseEngineQuestionPane('claude', capture) as QuestionView)diff --git a/cli/src/pair/owner.ts b/companions/src/companion/owner.tssimilarity index 100%rename from cli/src/pair/owner.tsrename to companions/src/companion/owner.tsdiff --git a/cli/src/pair/pairHarness.engine.spec.ts b/companions/src/companion/pairHarness.engine.spec.tssimilarity index 100%rename from cli/src/pair/pairHarness.engine.spec.tsrename to companions/src/companion/pairHarness.engine.spec.tsdiff --git a/cli/src/pair/pairHarness.more.spec.ts b/companions/src/companion/pairHarness.more.spec.tssimilarity index 100%rename from cli/src/pair/pairHarness.more.spec.tsrename to companions/src/companion/pairHarness.more.spec.tsdiff --git a/cli/src/pair/pairHarness.spec.ts b/companions/src/companion/pairHarness.spec.tssimilarity index 91%rename from cli/src/pair/pairHarness.spec.tsrename to companions/src/companion/pairHarness.spec.tsindex 677afa006..117865e05 100644--- a/cli/src/pair/pairHarness.spec.ts+++ b/companions/src/companion/pairHarness.spec.ts@@ -5,18 +5,17 @@* demand; hidden from the catalog.*/import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { mkdtempSync, readFileSync, rmSync } from 'node:fs'+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { env } from '../config/env.js'+import { env } from '../../../cli/src/config/env.js'import { PairHarness, PAIR_HARNESS_ID, PAIR_IDLE_MS, pairPackage, type PairHarnessDeps, type PairHarnessRow } from './pairHarness.js'import { PairToken } from './token.js'-import { parseDshManifest } from '../dsh/manifest.js'-import { ensureBuiltinPair } from '../dsh/builtins.js'-import { installedDsh, invalidateInstalledDsh } from '../dsh/installed.js'-import { prepareHarnessLaunch } from '../dsh/runtime.js'-import { dshListRows } from '../dsh/wire.js'-import { PAIR_HARNESS_DSH } from '../lib/zooTurns.js'+import { parseDshManifest } from '../../../cli/src/dsh/manifest.js'+import { invalidateInstalledDsh, type InstalledDsh } from '../../../cli/src/dsh/installed.js'+import { prepareHarnessLaunch } from '../../../cli/src/dsh/runtime.js'+import { dshListRows } from '../../../cli/src/dsh/wire.js'+import { PAIR_HARNESS_DSH } from './zooTurns.js'let dir: stringlet originalDsh: string@@ -87,10 +86,15 @@ describe('the package', () => {expect(agents).toContain('harness pair <tool> [arguments] --json')})- it('installs as a hidden built-in: launchable as a harness, never in the catalog', () => {+ it('keeps an existing collection package launchable through ordinary DSH provisioning', () => {const files = pairPackage({ daemonId: 'tim', engine: 'claude', mcpCommand: MCP, tokenFile: '/t' })- expect(ensureBuiltinPair(PAIR_HARNESS_ID, files)).toBe(true)- const installed = installedDsh(PAIR_HARNESS_ID)!+ const packageDir = join(dir, 'package')+ mkdirSync(packageDir)+ for (const [name, file] of Object.entries(files)) writeFileSync(join(packageDir, name), file.content)+ const parsed = parseDshManifest(files['harness.json']!.content)+ if (!parsed.ok) throw new Error('Invalid companion package fixture')+ const installed: InstalledDsh = { id: PAIR_HARNESS_ID, dir: packageDir, realDir: packageDir,+ source: 'builtin:pair', linked: false, ref: null, commit: null, installedAt: Date.now(), manifest: parsed.manifest }expect(installed.manifest.name).toBe('Companions')expect(dshListRows([installed], []).map((row) => row.id)).not.toContain(PAIR_HARNESS_ID)// The dsh runtime hands the engine the injected server and its context, like any harness.@@ -104,8 +108,7 @@ describe('the package', () => {})describe('talking to it', () => {- function world(opts: { engine?: 'claude' | 'codex' | 'opencode' | null; pair?: string | null;- backgroundInUse?: (agentId: string) => boolean } = {}) {+ function world(opts: { engine?: 'claude' | 'codex' | 'opencode' | null; pair?: string | null } = {}) {let pair = opts.pair === undefined ? 'tim' : opts.pairconst rows: PairHarnessRow[] = []let working = false@@ -125,7 +128,6 @@ describe('talking to it', () => {stop: vi.fn<PairHarnessDeps['stop']>(async (agentId) => { rows.find((r) => r.agentId === agentId)!.status = 'stopped' }),send: vi.fn(),working: () => working,- backgroundInUse: opts.backgroundInUse,now: Date.now,}const harness = new PairHarness(deps)@@ -241,27 +243,20 @@ describe('talking to it', () => {expect(w.deps.stop).toHaveBeenCalledWith('pair-1')})- it.each(['claude', 'codex', 'opencode'] as const)('keeps the %s model connection available while background learning is enabled', async engine => {- let learning = true- const backgroundInUse = vi.fn((id: string) => id === 'pair-1' && learning)- const w = world({ engine, backgroundInUse })+ it.each(['claude', 'codex', 'opencode'] as const)('uses normal idle pause for a %s conversation without a memory keepalive', async engine => {+ const w = world({ engine })expect(await w.harness.open(undefined, engine)).toMatchObject({ ok: true, started: true })w.rows[0]!.hasConversation = trueawait vi.advanceTimersByTimeAsync(PAIR_IDLE_MS * 3)- expect(w.rows[0]!.status).toBe('live')- expect(w.deps.stop).not.toHaveBeenCalled()+ expect(w.rows[0]!.status).toBe('stopped')+ expect(w.deps.stop).toHaveBeenCalledExactlyOnceWith('pair-1')expect(w.deps.send).not.toHaveBeenCalled()expect(w.deps.resume).not.toHaveBeenCalled()expect(w.deps.create).toHaveBeenCalledOnce()- expect(w.deps.create.mock.calls[0]?.[0].prompt).toBe('')- learning = false- await vi.advanceTimersByTimeAsync(60_000)- expect(w.rows[0]!.status).toBe('stopped')- expect(w.deps.stop).toHaveBeenCalledExactlyOnceWith('pair-1')})it('still honors explicit off and never reopens a stopped companion for background learning', async () => {- const w = world({ backgroundInUse: () => true })+ const w = world()await w.harness.open()w.rows[0]!.hasConversation = trueawait w.harness.off()diff --git a/cli/src/pair/pairHarness.ts b/companions/src/companion/pairHarness.tssimilarity index 98%rename from cli/src/pair/pairHarness.tsrename to companions/src/companion/pairHarness.tsindex 7da9be4a1..9b9415b58 100644--- a/cli/src/pair/pairHarness.ts+++ b/companions/src/companion/pairHarness.ts@@ -22,8 +22,8 @@ import { CONTROL_TOOLS } from './control.js'import { MCP_SERVER_NAME } from './mcp.js'import { PAIR_TOKEN_FILE_ENV, type PairToken } from './token.js'import { rosterDaemon } from './voice.js'-import type { BundledFiles } from '../dsh/builtins.js'-import { DEFAULT_HARNESS_ENGINE, DEFAULT_HARNESS_PERMISSION, freshHarnessEnvironment } from '../lib/harnessDefaults.js'+import type { BundledFiles } from '../../../cli/src/dsh/builtins.js'+import { DEFAULT_HARNESS_ENGINE, DEFAULT_HARNESS_PERMISSION, freshHarnessEnvironment } from '../../../cli/src/lib/harnessDefaults.js'export const PAIR_HARNESS_ID = 'autonomous/pair'export type PairEngine = 'claude' | 'codex' | 'opencode'@@ -219,8 +219,6 @@ export interface PairHarnessDeps {send: (agentId: string, text: string) => void/** A turn is open on it right now. */working: (agentId: string) => boolean- /** Opted-in background learning still needs this runtime, even between review jobs. */- backgroundInUse?: (agentId: string) => booleannow: () => numberidleMs?: number}@@ -390,15 +388,14 @@ export class PairHarness {if (agentId === this.saved()?.agentId) this.touch()}- /** Pause unused conversations; keep the learning runtime available without submitting a turn. */+ /** Pause unused conversations, preserving their ordinary resume state. */async idleCheck(): Promise<boolean> {const agentId = this.activeAgentId ?? this.saved()?.agentIdconst row = agentId ? this.deps.find().find((r) => r.agentId === agentId) : nullif (!agentId || row?.status !== 'live') { this.unwatch(); return false }// An empty/setup terminal has no conversation to resume. Pausing it discards its selected model- // and strands a pending memory review; leave it open until a real conversation can be preserved.+ // before it can be preserved; leave setup open until a real conversation exists.if (row.hasConversation === false) return false- if (this.deps.backgroundInUse?.(agentId)) return falseif (this.deps.working(agentId) || this.deps.now() - this.lastActivity < (this.deps.idleMs ?? PAIR_IDLE_MS)) return falsetry {await this.deps.stop(agentId)diff --git a/cli/src/pair/plateRender.ts b/companions/src/companion/plateRender.tssimilarity index 100%rename from cli/src/pair/plateRender.tsrename to companions/src/companion/plateRender.tsdiff --git a/cli/src/pair/plateService.spec.ts b/companions/src/companion/plateService.spec.tssimilarity index 100%rename from cli/src/pair/plateService.spec.tsrename to companions/src/companion/plateService.spec.tsdiff --git a/cli/src/pair/plateService.ts b/companions/src/companion/plateService.tssimilarity index 99%rename from cli/src/pair/plateService.tsrename to companions/src/companion/plateService.tsindex b4b9d5a06..ea6f909ab 100644--- a/cli/src/pair/plateService.ts+++ b/companions/src/companion/plateService.ts@@ -39,7 +39,7 @@ import { join } from 'node:path'import { randomBytes } from 'node:crypto'import { createRequire } from 'node:module'import { fileURLToPath } from 'node:url'-import { DAEMONS_OFF, DAEMONS_OFF_DETAIL } from '../lib/daemonsSwitch.js'+import { DAEMONS_OFF, DAEMONS_OFF_DETAIL } from './daemonsSwitch.js'import { isPairDaemonId } from './protocol.js'import { isSeed, isUid, zooIndividuals, type ZooIndividual } from './individuals.js'import { hasPlateModel, plateRules, plateSource, renderPlateUnit, type PlateFrame, type PlateJob, type PlateSize, type PlateUnit } from './plateRender.js'diff --git a/cli/src/pair/plateWorker.ts b/companions/src/companion/plateWorker.tssimilarity index 100%rename from cli/src/pair/plateWorker.tsrename to companions/src/companion/plateWorker.tsdiff --git a/cli/src/pair/plates/auk.g.ts b/companions/src/companion/plates/auk.g.tssimilarity index 100%rename from cli/src/pair/plates/auk.g.tsrename to companions/src/companion/plates/auk.g.tsdiff --git a/cli/src/pair/plates/beastie.g.ts b/companions/src/companion/plates/beastie.g.tssimilarity index 100%rename from cli/src/pair/plates/beastie.g.tsrename to companions/src/companion/plates/beastie.g.tsdiff --git a/cli/src/pair/plates/bug.g.ts b/companions/src/companion/plates/bug.g.tssimilarity index 100%rename from cli/src/pair/plates/bug.g.tsrename to companions/src/companion/plates/bug.g.tsdiff --git a/cli/src/pair/plates/gnu.g.ts b/companions/src/companion/plates/gnu.g.tssimilarity index 100%rename from cli/src/pair/plates/gnu.g.tsrename to companions/src/companion/plates/gnu.g.tsdiff --git a/cli/src/pair/plates/gopher.g.ts b/companions/src/companion/plates/gopher.g.tssimilarity index 100%rename from cli/src/pair/plates/gopher.g.tsrename to companions/src/companion/plates/gopher.g.tsdiff --git a/cli/src/pair/plates/lynx.g.ts b/companions/src/companion/plates/lynx.g.tssimilarity index 100%rename from cli/src/pair/plates/lynx.g.tsrename to companions/src/companion/plates/lynx.g.tsdiff --git a/cli/src/pair/plates/models.g.ts b/companions/src/companion/plates/models.g.tssimilarity index 100%rename from cli/src/pair/plates/models.g.tsrename to companions/src/companion/plates/models.g.tsdiff --git a/cli/src/pair/plates/mutt.g.ts b/companions/src/companion/plates/mutt.g.tssimilarity index 100%rename from cli/src/pair/plates/mutt.g.tsrename to companions/src/companion/plates/mutt.g.tsdiff --git a/cli/src/pair/plates/plate.g.ts b/companions/src/companion/plates/plate.g.tssimilarity index 100%rename from cli/src/pair/plates/plate.g.tsrename to companions/src/companion/plates/plate.g.tsdiff --git a/cli/src/pair/plates/render.g.ts b/companions/src/companion/plates/render.g.tssimilarity index 100%rename from cli/src/pair/plates/render.g.tsrename to companions/src/companion/plates/render.g.tsdiff --git a/cli/src/pair/plates/tim.g.ts b/companions/src/companion/plates/tim.g.tssimilarity index 100%rename from cli/src/pair/plates/tim.g.tsrename to companions/src/companion/plates/tim.g.tsdiff --git a/cli/src/pair/plates/tux.g.ts b/companions/src/companion/plates/tux.g.tssimilarity index 100%rename from cli/src/pair/plates/tux.g.tsrename to companions/src/companion/plates/tux.g.tsdiff --git a/cli/src/pair/plates/yak.g.ts b/companions/src/companion/plates/yak.g.tssimilarity index 100%rename from cli/src/pair/plates/yak.g.tsrename to companions/src/companion/plates/yak.g.tsdiff --git a/cli/src/pair/protocol.spec.ts b/companions/src/companion/protocol.spec.tssimilarity index 100%rename from cli/src/pair/protocol.spec.tsrename to companions/src/companion/protocol.spec.tsdiff --git a/cli/src/pair/protocol.ts b/companions/src/companion/protocol.tssimilarity index 99%rename from cli/src/pair/protocol.tsrename to companions/src/companion/protocol.tsindex 1ac223ba9..4155d6779 100644--- a/cli/src/pair/protocol.ts+++ b/companions/src/companion/protocol.ts@@ -143,7 +143,7 @@ export function isPairDaemonId(value: unknown): value is string {// ── deny class ──────────────────────────────────────────────────────────────────────────────────────/** Which prompts are never approved, read over the whole dialog (pair/classify.ts). */-export { isDenyClass } from './classify.js'+export { isDenyClass } from '../shared/classify.js'// ── local frames (loopback only) ────────────────────────────────────────────────────────────────────diff --git a/cli/src/pair/redact.ts b/companions/src/companion/redact.tssimilarity index 97%rename from cli/src/pair/redact.tsrename to companions/src/companion/redact.tsindex e9c234584..b7c9f9cf6 100644--- a/cli/src/pair/redact.ts+++ b/companions/src/companion/redact.ts@@ -9,7 +9,7 @@* see exactly what a key would approve.*/import { homedir } from 'node:os'-import { redact } from './learn/guard.js'+import { redact } from '../shared/guard.js'import type { PairJournalEntry } from './protocol.js'export function redactText(text: string, home: string | null = homedir()): string {diff --git a/cli/src/pair/roster.g.ts b/companions/src/companion/roster.g.tssimilarity index 100%rename from cli/src/pair/roster.g.tsrename to companions/src/companion/roster.g.tsdiff --git a/cli/src/pair/rules.more.spec.ts b/companions/src/companion/rules.more.spec.tssimilarity index 100%rename from cli/src/pair/rules.more.spec.tsrename to companions/src/companion/rules.more.spec.tsdiff --git a/cli/src/pair/rules.spec.ts b/companions/src/companion/rules.spec.tssimilarity index 100%rename from cli/src/pair/rules.spec.tsrename to companions/src/companion/rules.spec.tsdiff --git a/cli/src/pair/rules.ts b/companions/src/companion/rules.tssimilarity index 99%rename from cli/src/pair/rules.tsrename to companions/src/companion/rules.tsindex 18b164dfc..1d5d4d549 100644--- a/cli/src/pair/rules.ts+++ b/companions/src/companion/rules.ts@@ -46,8 +46,8 @@ export interface PairRule {}/** Where approved skills may be exported (pair/learn/export.ts). */-export const EXPORT_DESTINATIONS = ['agents', 'claude'] as const-export type ExportDestination = typeof EXPORT_DESTINATIONS[number]+import { EXPORT_DESTINATIONS, type ExportDestination } from '../memory/api.js'+export { EXPORT_DESTINATIONS, type ExportDestination }export interface LearnConfig {borrow: booleandiff --git a/cli/src/pair/sensor.more.spec.ts b/companions/src/companion/sensor.more.spec.tssimilarity index 100%rename from cli/src/pair/sensor.more.spec.tsrename to companions/src/companion/sensor.more.spec.tsdiff --git a/cli/src/pair/sensor.spec.ts b/companions/src/companion/sensor.spec.tssimilarity index 100%rename from cli/src/pair/sensor.spec.tsrename to companions/src/companion/sensor.spec.tsdiff --git a/cli/src/pair/sensor.ts b/companions/src/companion/sensor.tssimilarity index 99%rename from cli/src/pair/sensor.tsrename to companions/src/companion/sensor.tsindex f21b9e42f..378146522 100644--- a/cli/src/pair/sensor.ts+++ b/companions/src/companion/sensor.ts@@ -17,9 +17,9 @@* Off unless the account's zoo has a paired daemon. Off, it records nothing and answers PAIR_OFF.*/import { homedir } from 'node:os'-import type { ShapedQuestion } from '../lib/askQuestion.js'+import type { ShapedQuestion } from '../../../cli/src/lib/askQuestion.js'import type { PairJournal } from './journal.js'-import { isAllowClass, type ToolCall } from './classify.js'+import { isAllowClass, type ToolCall } from '../shared/classify.js'import { redactEntry } from './redact.js'import type { JournalInput } from './journal.js'import {diff --git a/cli/src/pair/shown.more.spec.ts b/companions/src/companion/shown.more.spec.tssimilarity index 100%rename from cli/src/pair/shown.more.spec.tsrename to companions/src/companion/shown.more.spec.tsdiff --git a/cli/src/pair/shown.spec.ts b/companions/src/companion/shown.spec.tssimilarity index 100%rename from cli/src/pair/shown.spec.tsrename to companions/src/companion/shown.spec.tsdiff --git a/cli/src/pair/shown.ts b/companions/src/companion/shown.tssimilarity index 100%rename from cli/src/pair/shown.tsrename to companions/src/companion/shown.tsdiff --git a/cli/src/pair/startupProfile.spec.ts b/companions/src/companion/startupProfile.spec.tssimilarity index 91%rename from cli/src/pair/startupProfile.spec.tsrename to companions/src/companion/startupProfile.spec.tsindex c0e8b276f..da4edee19 100644--- a/cli/src/pair/startupProfile.spec.ts+++ b/companions/src/companion/startupProfile.spec.ts@@ -2,13 +2,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'-import type { RegisteredSession } from '../lib/registry.js'-import { parseRuntimeProfile, readStartupProfile, RuntimeProfileManager } from '../lib/runtimeProfile.js'+import type { RegisteredSession } from '../../../cli/src/lib/registry.js'+import { parseRuntimeProfile, readStartupProfile, RuntimeProfileManager } from '../../../cli/src/lib/runtimeProfile.js'import { CompanionStartupProfile } from './startupProfile.js'-import { CompanionIntelligence } from './intelligence.js'-import { ConversationReview } from './learn/conversationReview.js'-import { LessonDistiller } from './learn/distill.js'-import { LessonStore } from './learn/store.js'+import { CompanionIntelligence } from '../application/intelligence.js'+import { ConversationReview } from '../application/lessons/conversationReview.js'+import { LessonDistiller } from '../memory/lessons/distill.js'+import { LessonStore } from '../memory/lessons/store.js'let directory: stringbeforeEach(() => {@@ -80,7 +80,7 @@ describe('companion readiness before its first message', () => {it('expires evidence and isolates agents, process restarts, homes, and newly bound conversations', async () => {let current: RegisteredSession | null = session(), now = 1_000const capture = vi.fn(async () => CLAUDE_READY)- const observer = new CompanionStartupProfile({ current: () => current, capture, now: () => now })+ const observer = new CompanionStartupProfile({ read: readStartupProfile, current: () => current, capture, now: () => now })await observer.refresh()const original = currentexpect(observer.selected(original)?.profile).toContain(':claude:opus@auto')@@ -108,7 +108,7 @@ describe('companion readiness before its first message', () => {it('discards a capture that finishes after the companion changes', async () => {let current = session(), finish!: (pane: string) => void- const observer = new CompanionStartupProfile({ current: () => current,+ const observer = new CompanionStartupProfile({ read: readStartupProfile, current: () => current,capture: () => new Promise(resolve => { finish = resolve }) })const pending = observer.refresh()current = session({ agentId: 'other' })@@ -128,7 +128,7 @@ describe('companion readiness before its first message', () => {it('resumes a queued history review into pending memories without sending a first message', async () => {const value = session(), now = Date.now()- const observer = new CompanionStartupProfile({ current: () => value, capture: async () => CLAUDE_READY })+ const observer = new CompanionStartupProfile({ read: readStartupProfile, current: () => value, capture: async () => CLAUDE_READY })const run = vi.fn(async () => ({ text: JSON.stringify({ lessons: [{ sources: ['1'],reason: 'The person specified the editor layout.',lesson: { kind: 'note', lines: ['Keep DSH viewers on the left and the agent terminal on the right.'] },diff --git a/cli/src/pair/startupProfile.ts b/companions/src/companion/startupProfile.tssimilarity index 82%rename from cli/src/pair/startupProfile.tsrename to companions/src/companion/startupProfile.tsindex 7290037be..7747d9540 100644--- a/cli/src/pair/startupProfile.ts+++ b/companions/src/companion/startupProfile.ts@@ -1,13 +1,12 @@-import type { RegisteredSession } from '../lib/registry.js'-import { readStartupProfile } from '../lib/runtimeProfile.js'-import { processIdentityKey } from '../lib/terminalRuntime.js'+import type { RegisteredSession } from '../../../cli/src/lib/registry.js'+import type { readStartupProfile } from '../../../cli/src/lib/runtimeProfile.js'export interface StartupProfile { processKey: string; profile: string }interface StartupDeps {current: () => RegisteredSession | nullcapture: (agentId: string) => Promise<string | null>- read?: typeof readStartupProfile+ read: typeof readStartupProfilenow?: () => number}@@ -21,7 +20,7 @@ export class CompanionStartupProfile {if (!session || session.sessionId || !session.active || !session.processIdentity?.startMarker ||session.launch?.state === 'starting' || session.launch?.state === 'failed' ||!['claude', 'codex'].includes(session.engine) || session.grid || session.gridLaunch || session.gateway) return null- return JSON.stringify([session.agentId, processIdentityKey(session.engine, session.processIdentity),+ return JSON.stringify([session.agentId, [session.engine, session.processIdentity.pid, session.processIdentity.startMarker],session.primaryRuntimeKey, session.cwd, session.codexHome ?? null])}@@ -39,7 +38,7 @@ export class CompanionStartupProfile {this.refreshing = truetry {const pane = await this.deps.capture(session.agentId)- const profile = pane ? await (this.deps.read ?? readStartupProfile)(session, pane) : null+ const profile = pane ? await this.deps.read(session, pane) : null// Capturing a pane and reading configuration are async. Never attach their result to a new agent.this.observed = key === this.key(this.deps.current()) && profile? { processKey: key, profile, expires: (this.deps.now?.() ?? Date.now()) + 45_000 } : nulldiff --git a/cli/src/pair/token.spec.ts b/companions/src/companion/token.spec.tssimilarity index 100%rename from cli/src/pair/token.spec.tsrename to companions/src/companion/token.spec.tsdiff --git a/cli/src/pair/token.ts b/companions/src/companion/token.tssimilarity index 100%rename from cli/src/pair/token.tsrename to companions/src/companion/token.tsdiff --git a/companions/src/companion/toolCalls.spec.ts b/companions/src/companion/toolCalls.spec.tsnew file mode 100644index 000000000..b1df826b2--- /dev/null+++ b/companions/src/companion/toolCalls.spec.ts@@ -0,0 +1,12 @@+import { expect, it } from 'vitest'+import { CompanionToolCalls } from './toolCalls.js'++it('keeps exact pending inputs until their result or turn boundary, without a core recap service', () => {+ const calls = new CompanionToolCalls()+ calls.observe('s1', { type: 'tool_start', payload: { id: 't1', tool: 'Bash', input: { command: 'npm test', description: 'Run the tests' } } })+ calls.observe('s1', { type: 'tool_start', payload: { id: 't2', tool: 'Read', input: { file_path: '/w/a.ts' } } })+ calls.observe('s1', { type: 'tool_end', payload: { id: 't2', tool: 'Read', output: '', isError: false, summary: '' } })+ expect(calls.open('s1')).toEqual([{ name: 'Bash', input: { command: 'npm test', description: 'Run the tests' } }])+ calls.observe('s1', { type: 'turn_ended', payload: {} })+ expect(calls.open('s1')).toEqual([])+})diff --git a/companions/src/companion/toolCalls.ts b/companions/src/companion/toolCalls.tsnew file mode 100644index 000000000..138573749--- /dev/null+++ b/companions/src/companion/toolCalls.ts@@ -0,0 +1,24 @@+import type { LiveEvent } from '../../../cli/src/lib/normalize.js'++/** Exact open tool calls used by companion permission policy, outside the core recap pipeline. */+export class CompanionToolCalls {+ private readonly calls = new Map<string, Map<string, { name: string; input: unknown }>>()++ open(sessionId: string): Array<{ name: string; input: unknown }> {+ return [...(this.calls.get(sessionId)?.values() ?? [])]+ }++ forget(sessionId: string): void { this.calls.delete(sessionId) }++ observe(sessionId: string, event: LiveEvent): void {+ if (event.type === 'turn_started' || event.type === 'turn_ended') { this.forget(sessionId); return }+ if (event.type === 'tool_start') {+ let open = this.calls.get(sessionId)+ if (!open) { open = new Map(); this.calls.set(sessionId, open) }+ open.set(String(event.payload.id), { name: String(event.payload.tool || ''), input: event.payload.input })+ if (open.size > 32) open.delete(open.keys().next().value as string)+ } else if (event.type === 'tool_end') {+ this.calls.get(sessionId)?.delete(String(event.payload.id))+ }+ }+}diff --git a/cli/src/pair/triage.spec.ts b/companions/src/companion/triage.spec.tssimilarity index 100%rename from cli/src/pair/triage.spec.tsrename to companions/src/companion/triage.spec.tsdiff --git a/cli/src/pair/triage.ts b/companions/src/companion/triage.tssimilarity index 98%rename from cli/src/pair/triage.tsrename to companions/src/companion/triage.tsindex 9ff17cbbd..8cd16bfa2 100644--- a/cli/src/pair/triage.ts+++ b/companions/src/companion/triage.ts@@ -23,7 +23,7 @@*/import { needLine, rosterLine } from './voice.js'import { bareOption, isDeclineOption } from './floor.js'-import { isOneTimeYes, isPersistentOption } from './classify.js'+import { isOneTimeYes, isPersistentOption } from '../shared/classify.js'import { statusText, type DaemonAction, type PairQuestion } from './protocol.js'import { redactText } from './redact.js'@@ -58,7 +58,8 @@ export interface TriageResult {}/** Runs one small prompt; resolves the model's text, or null when there is no engine to run it on. */-export type PairOneShot = (prompt: string, opts: { timeoutMs: number; signal: AbortSignal }) => Promise<string | null>+import type { TextInference } from '../shared/inference.js'+export type PairOneShot = TextInferenceexport interface TriageDeps {oneshot?: PairOneShot | nulldiff --git a/cli/src/pair/voice.spec.ts b/companions/src/companion/voice.spec.tssimilarity index 100%rename from cli/src/pair/voice.spec.tsrename to companions/src/companion/voice.spec.tsdiff --git a/cli/src/pair/voice.ts b/companions/src/companion/voice.tssimilarity index 100%rename from cli/src/pair/voice.tsrename to companions/src/companion/voice.tsdiff --git a/cli/src/lib/zooLessons.spec.ts b/companions/src/companion/zooLessons.spec.tssimilarity index 100%rename from cli/src/lib/zooLessons.spec.tsrename to companions/src/companion/zooLessons.spec.tsdiff --git a/cli/src/lib/zooLessons.ts b/companions/src/companion/zooLessons.tssimilarity index 100%rename from cli/src/lib/zooLessons.tsrename to companions/src/companion/zooLessons.tsdiff --git a/cli/src/lib/zooTurns.spec.ts b/companions/src/companion/zooTurns.spec.tssimilarity index 100%rename from cli/src/lib/zooTurns.spec.tsrename to companions/src/companion/zooTurns.spec.tsdiff --git a/cli/src/lib/zooTurns.ts b/companions/src/companion/zooTurns.tssimilarity index 99%rename from cli/src/lib/zooTurns.tsrename to companions/src/companion/zooTurns.tsindex 9ad56662e..c2f9a0198 100644--- a/cli/src/lib/zooTurns.ts+++ b/companions/src/companion/zooTurns.ts@@ -29,7 +29,7 @@* off, nothing is counted, no timer is armed and nothing is sent.*/import { randomBytes } from 'node:crypto'-import { PAIR_ROSTER } from '../pair/roster.g.js'+import { PAIR_ROSTER } from './roster.g.js'/** How long counted turns gather before one report. */export const ZOO_TURN_FLUSH_MS = 60_000diff --git a/cli/src/memory/__fixtures__/opencode-1.18.34-overflow.json b/companions/src/memory/__fixtures__/opencode-1.18.34-overflow.jsonsimilarity index 100%rename from cli/src/memory/__fixtures__/opencode-1.18.34-overflow.jsonrename to companions/src/memory/__fixtures__/opencode-1.18.34-overflow.jsondiff --git a/cli/src/memory/__fixtures__/opencode-1.18.34-provider-refusal.json b/companions/src/memory/__fixtures__/opencode-1.18.34-provider-refusal.jsonsimilarity index 100%rename from cli/src/memory/__fixtures__/opencode-1.18.34-provider-refusal.jsonrename to companions/src/memory/__fixtures__/opencode-1.18.34-provider-refusal.jsondiff --git a/cli/src/memory/__fixtures__/opencode-1.18.34-recall.json b/companions/src/memory/__fixtures__/opencode-1.18.34-recall.jsonsimilarity index 100%rename from cli/src/memory/__fixtures__/opencode-1.18.34-recall.jsonrename to companions/src/memory/__fixtures__/opencode-1.18.34-recall.jsondiff --git a/cli/src/memory/__fixtures__/opencode-1.18.34-source.json b/companions/src/memory/__fixtures__/opencode-1.18.34-source.jsonsimilarity index 100%rename from cli/src/memory/__fixtures__/opencode-1.18.34-source.jsonrename to companions/src/memory/__fixtures__/opencode-1.18.34-source.jsondiff --git a/cli/src/memory/account.spec.ts b/companions/src/memory/account.spec.tssimilarity index 100%rename from cli/src/memory/account.spec.tsrename to companions/src/memory/account.spec.tsdiff --git a/cli/src/memory/account.ts b/companions/src/memory/account.tssimilarity index 97%rename from cli/src/memory/account.tsrename to companions/src/memory/account.tsindex 7e813f46d..542e4f858 100644--- a/cli/src/memory/account.ts+++ b/companions/src/memory/account.ts@@ -3,7 +3,7 @@ import { createHash } from 'node:crypto'import { open } from 'node:fs/promises'import { homedir, tmpdir, userInfo } from 'node:os'import { isAbsolute, join } from 'node:path'-import { oneShotParentEnv } from '../lib/loginShellEnv.js'+import { oneShotParentEnv } from '../../../cli/src/lib/loginShellEnv.js'export function memoryCodexHome(selected?: string | null, home = homedir(), environment = oneShotParentEnv()): string | null {const path = selected || environment.CODEX_HOME || join(home, '.codex')diff --git a/cli/src/memory/activity.spec.ts b/companions/src/memory/activity.spec.tssimilarity index 99%rename from cli/src/memory/activity.spec.tsrename to companions/src/memory/activity.spec.tsindex 0a0052a5f..5e89a92bb 100644--- a/cli/src/memory/activity.spec.ts+++ b/companions/src/memory/activity.spec.ts@@ -3,7 +3,7 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, beforeEach, expect, it } from 'vitest'import { CodingMemoryStore } from './store.js'-import { builtinSqlite } from '../lib/sqliteRead.js'+import { builtinSqlite } from '../../../cli/src/lib/sqliteRead.js'import type { Database } from './database.js'import type { MemoryRecord, MemoryDraft, SourceEvent } from './types.js'import type { ActivityReceiver } from './receipts.js'diff --git a/cli/src/lib/opencodeMemoryPlugin.spec.ts b/companions/src/memory/adapters/opencodeMemoryPlugin.spec.tssimilarity index 100%rename from cli/src/lib/opencodeMemoryPlugin.spec.tsrename to companions/src/memory/adapters/opencodeMemoryPlugin.spec.tsdiff --git a/cli/src/lib/opencodeMemoryPlugin.ts b/companions/src/memory/adapters/opencodeMemoryPlugin.tssimilarity index 100%rename from cli/src/lib/opencodeMemoryPlugin.tsrename to companions/src/memory/adapters/opencodeMemoryPlugin.tsdiff --git a/cli/src/lib/opencodeRecallPlugin.spec.ts b/companions/src/memory/adapters/opencodeRecallPlugin.spec.tssimilarity index 100%rename from cli/src/lib/opencodeRecallPlugin.spec.tsrename to companions/src/memory/adapters/opencodeRecallPlugin.spec.tsdiff --git a/cli/src/lib/opencodeRecallPlugin.ts b/companions/src/memory/adapters/opencodeRecallPlugin.tssimilarity index 100%rename from cli/src/lib/opencodeRecallPlugin.tsrename to companions/src/memory/adapters/opencodeRecallPlugin.tsdiff --git a/cli/src/memory/admission.spec.ts b/companions/src/memory/admission.spec.tssimilarity index 100%rename from cli/src/memory/admission.spec.tsrename to companions/src/memory/admission.spec.tsdiff --git a/cli/src/memory/admission.ts b/companions/src/memory/admission.tssimilarity index 98%rename from cli/src/memory/admission.tsrename to companions/src/memory/admission.tsindex 6c74fc7da..73bc725f0 100644--- a/cli/src/memory/admission.ts+++ b/companions/src/memory/admission.ts@@ -1,5 +1,5 @@import { createHash } from 'node:crypto'-import { hasInjection, hasSecret } from '../pair/learn/guard.js'+import { hasInjection, hasSecret } from '../shared/guard.js'import { hasPointer, MemoryError, type MemoryDraft, type MemoryState, type SourceEvent } from './types.js'/** Stable serialization for identity and comparison; object insertion order is not meaningful. */diff --git a/companions/src/memory/api.ts b/companions/src/memory/api.tsnew file mode 100644index 000000000..aee95b145--- /dev/null+++ b/companions/src/memory/api.ts@@ -0,0 +1,13 @@+/** Public memory contract used by the companion application. */+export { conditionsSchema } from './types.js'+export { MEMORY_RECALL_CONDITIONS_SCHEMA } from './context.js'+export type { RecallPacket, RecallRequest, MemoryAccess } from './types.js'+export type { MemoryRuntimeStatus, MemoryHostContext, MemoryHostSession } from './runtime.js'+export type { MemoryInference, MemoryInferenceRunOptions } from './learner.js'++/** The character layer can ask for context; it cannot open or mutate the database. */+export interface CompanionMemory {+ recall(agentId: string, query: string): Promise<{ text: string; status: string }>+}++export { EXPORT_DESTINATIONS, type ExportDestination } from './lessons/types.js'diff --git a/cli/src/memory/budget.ts b/companions/src/memory/budget.tssimilarity index 100%rename from cli/src/memory/budget.tsrename to companions/src/memory/budget.tsdiff --git a/cli/src/memory/capture.spec.ts b/companions/src/memory/capture.spec.tssimilarity index 100%rename from cli/src/memory/capture.spec.tsrename to companions/src/memory/capture.spec.tsdiff --git a/cli/src/memory/capture.ts b/companions/src/memory/capture.tssimilarity index 100%rename from cli/src/memory/capture.tsrename to companions/src/memory/capture.tsdiff --git a/cli/src/memory/claudeInference.spec.ts b/companions/src/memory/claudeInference.spec.tssimilarity index 100%rename from cli/src/memory/claudeInference.spec.tsrename to companions/src/memory/claudeInference.spec.tsdiff --git a/cli/src/memory/claudeInference.ts b/companions/src/memory/claudeInference.tssimilarity index 100%rename from cli/src/memory/claudeInference.tsrename to companions/src/memory/claudeInference.tsdiff --git a/cli/src/memory/client.spec.ts b/companions/src/memory/client.spec.tssimilarity index 100%rename from cli/src/memory/client.spec.tsrename to companions/src/memory/client.spec.tsdiff --git a/cli/src/memory/client.ts b/companions/src/memory/client.tssimilarity index 100%rename from cli/src/memory/client.tsrename to companions/src/memory/client.tsdiff --git a/cli/src/memory/context.ts b/companions/src/memory/context.tssimilarity index 100%rename from cli/src/memory/context.tsrename to companions/src/memory/context.tsdiff --git a/cli/src/memory/control.spec.ts b/companions/src/memory/control.spec.tssimilarity index 99%rename from cli/src/memory/control.spec.tsrename to companions/src/memory/control.spec.tsindex 60aaeb6d2..4a695564f 100644--- a/cli/src/memory/control.spec.ts+++ b/companions/src/memory/control.spec.ts@@ -1,7 +1,7 @@import { beforeEach, expect, it, vi } from 'vitest'import { MemoryControl } from './control.js'import type { CodingMemoryRuntime } from './runtime.js'-import type { CallerVerdict } from '../pair/learn/approval.js'+import type { CallerVerdict } from '../shared/approval.js'import { isOwnerProcess } from './ownerProcess.js'let owner: string | null, now: number, control: MemoryControldiff --git a/cli/src/memory/control.ts b/companions/src/memory/control.tssimilarity index 99%rename from cli/src/memory/control.tsrename to companions/src/memory/control.tsindex 0779382d6..b94262f9f 100644--- a/cli/src/memory/control.ts+++ b/companions/src/memory/control.ts@@ -4,7 +4,7 @@ import { z } from 'zod'import { libraryCommandSchema, libraryQuerySchema, libraryProjectQuerySchema, notebookQuerySchema, libraryActivityQuerySchema, type LibraryPreview } from './library.js'import { MemoryError, parse } from './types.js'import type { CodingMemoryRuntime } from './runtime.js'-import type { CallerVerdict } from '../pair/learn/approval.js'+import type { CallerVerdict } from '../shared/approval.js'import type { MemoryExperimentChoice } from './experiment.js'const requestSchema = z.discriminatedUnion('action', [diff --git a/cli/src/memory/database.ts b/companions/src/memory/database.tssimilarity index 100%rename from cli/src/memory/database.tsrename to companions/src/memory/database.tsdiff --git a/cli/src/memory/evaluation.spec.ts b/companions/src/memory/evaluation.spec.tssimilarity index 100%rename from cli/src/memory/evaluation.spec.tsrename to companions/src/memory/evaluation.spec.tsdiff --git a/cli/src/memory/evaluation.ts b/companions/src/memory/evaluation.tssimilarity index 100%rename from cli/src/memory/evaluation.tsrename to companions/src/memory/evaluation.tsdiff --git a/cli/src/memory/evaluationContext.ts b/companions/src/memory/evaluationContext.tssimilarity index 98%rename from cli/src/memory/evaluationContext.tsrename to companions/src/memory/evaluationContext.tsindex b4e1b3406..ed9b61f88 100644--- a/cli/src/memory/evaluationContext.ts+++ b/companions/src/memory/evaluationContext.ts@@ -1,7 +1,7 @@/** Validate diagnostic context independently of the serializer that produced it. No inference. */import { z } from 'zod'import { canonical } from './admission.js'-import { redact } from '../pair/learn/guard.js'+import { redact } from '../shared/guard.js'import { MemoryError, scopeSchema, verificationSchema, type MemoryRecord, type RecallRequest, type SourceEvent } from './types.js'const id = z.string().min(1).max(200).regex(/^[A-Za-z0-9_.:-]+$/)diff --git a/cli/src/memory/evaluationReview.spec.ts b/companions/src/memory/evaluationReview.spec.tssimilarity index 100%rename from cli/src/memory/evaluationReview.spec.tsrename to companions/src/memory/evaluationReview.spec.tsdiff --git a/cli/src/memory/evaluationReview.ts b/companions/src/memory/evaluationReview.tssimilarity index 100%rename from cli/src/memory/evaluationReview.tsrename to companions/src/memory/evaluationReview.tsdiff --git a/cli/src/memory/experiment.spec.ts b/companions/src/memory/experiment.spec.tssimilarity index 100%rename from cli/src/memory/experiment.spec.tsrename to companions/src/memory/experiment.spec.tsdiff --git a/cli/src/memory/experiment.ts b/companions/src/memory/experiment.tssimilarity index 100%rename from cli/src/memory/experiment.tsrename to companions/src/memory/experiment.tsdiff --git a/cli/src/backendSocket.memorySettings.spec.ts b/companions/src/memory/experimentControl.spec.tssimilarity index 55%rename from cli/src/backendSocket.memorySettings.spec.tsrename to companions/src/memory/experimentControl.spec.tsindex 7fd2bf8d0..df516fd7c 100644--- a/cli/src/backendSocket.memorySettings.spec.ts+++ b/companions/src/memory/experimentControl.spec.ts@@ -2,9 +2,8 @@ import { mkdtempSync, rmSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, expect, it, vi } from 'vitest'-import { BackendSocket } from './backendSocket.js'-import { MemoryControl } from './memory/control.js'-import { MemoryExperimentSettings } from './memory/experiment.js'+import { MemoryControl } from './control.js'+import { MemoryExperimentSettings } from './experiment.js'afterEach(() => vi.restoreAllMocks())@@ -13,7 +12,6 @@ it('lets the verified local owner disable coding memory while companions stay ofconst settings = new MemoryExperimentSettings(directory)const owner = 'a'.repeat(64)settings.write(owner, true, 0)- const socket = new BackendSocket('fixture')const runtime = vi.fn(() => null)let person = trueconst verify = vi.fn(async () => person ? { ok: true as const, pid: 123 }@@ -21,17 +19,7 @@ it('lets the verified local owner disable coding memory while companions stay ofconst memory = new MemoryControl({ runtime, verify,experiment: { owner: () => owner, read: key => settings.read(key),write: async (key, enabled, expected) => settings.write(key, enabled, expected) } })- socket.daemonsOn = () => false- socket.pairControl = { verbs: new Set(['memory']), local: (payload, connId) => memory.local(payload, connId) }- const frames: Array<Record<string, any>> = []- vi.spyOn(socket, 'sendTo').mockImplementation((_to, frame) => { frames.push(frame) })- socket.registerLocalClient('local:settings', { sendFrame: () => true, sendBinary: () => true }, { tool: true })- const ask = async (input: Record<string, unknown>) => {- const requestId = String(frames.length)- socket.handleLocalFrame('local:settings', { type: 'pair', payload: { requestId, verb: 'memory', ...input } })- await vi.waitFor(() => expect(frames.some(frame => frame.payload?.requestId === requestId)).toBe(true))- return frames.find(frame => frame.payload?.requestId === requestId)!.payload- }+ const ask = (input: Record<string, unknown>) => memory.local(input, 'owner')try {expect(await ask({ action: 'experiment' })).toMatchObject({ ok: true, enabled: true, revision: 1 })expect(await ask({ action: 'configure_experiment', enabled: false, expected: 1 }))@@ -45,18 +33,15 @@ it('lets the verified local owner disable coding memory while companions stay ofperson = trueexpect(await ask({ action: 'experiment', owner: 'b'.repeat(64) })).toMatchObject({ error: 'INVALID_INPUT' })verify.mockClear()- for (const action of ['status', 'list', 'show', 'preview', 'apply']) {- expect(await ask({ action })).toMatchObject({ error: 'DAEMONS_OFF' })+ for (const action of ['status', 'list']) {+ expect(await ask({ action })).toMatchObject({ error: 'UNSUPPORTED' })+ }+ for (const action of ['show', 'preview', 'apply']) {+ expect(await ask({ action })).toMatchObject({ error: 'INVALID_INPUT' })}- expect(await ask({ verb: 'recall_memory', query: 'test' })).toMatchObject({ error: 'DAEMONS_OFF' })expect(verify).not.toHaveBeenCalled()- expect(runtime).not.toHaveBeenCalled()expect(settings.enabled(owner)).toBe(false)- socket.pairControl = null- expect(await ask({ action: 'experiment' })).toMatchObject({ error: 'DAEMONS_OFF' })} finally {- await socket.unregisterLocalClient('local:settings')- await socket.stop()rmSync(directory, { recursive: true, force: true })}})diff --git a/cli/src/memory/extractionAuthorization.spec.ts b/companions/src/memory/extractionAuthorization.spec.tssimilarity index 97%rename from cli/src/memory/extractionAuthorization.spec.tsrename to companions/src/memory/extractionAuthorization.spec.tsindex 43af6fbdd..57d59ef11 100644--- a/cli/src/memory/extractionAuthorization.spec.ts+++ b/companions/src/memory/extractionAuthorization.spec.ts@@ -2,8 +2,8 @@ import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, beforeEach, expect, it, vi } from 'vitest'-import { CompanionIntelligence, type CompanionRuntime } from '../pair/intelligence.js'-import { encodeRuntimeProfile } from '../lib/runtimeProfile.js'+import { CompanionIntelligence, type CompanionRuntime } from '../application/intelligence.js'+import { encodeRuntimeProfile } from '../../../cli/src/lib/runtimeProfile.js'import { MemoryError } from './types.js'let directory: stringdiff --git a/cli/src/memory/extractionEvidence.spec.ts b/companions/src/memory/extractionEvidence.spec.tssimilarity index 100%rename from cli/src/memory/extractionEvidence.spec.tsrename to companions/src/memory/extractionEvidence.spec.tsdiff --git a/cli/src/memory/extractionEvidence.ts b/companions/src/memory/extractionEvidence.tssimilarity index 100%rename from cli/src/memory/extractionEvidence.tsrename to companions/src/memory/extractionEvidence.tsdiff --git a/cli/src/memory/feedback.spec.ts b/companions/src/memory/feedback.spec.tssimilarity index 99%rename from cli/src/memory/feedback.spec.tsrename to companions/src/memory/feedback.spec.tsindex 939276af9..afd9bbd7b 100644--- a/cli/src/memory/feedback.spec.ts+++ b/companions/src/memory/feedback.spec.ts@@ -3,7 +3,7 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, beforeEach, expect, it } from 'vitest'import { CodingMemoryStore } from './store.js'-import { builtinSqlite } from '../lib/sqliteRead.js'+import { builtinSqlite } from '../../../cli/src/lib/sqliteRead.js'import type { Database } from './database.js'import type { LibraryCommand } from './library.js'import type { MemoryDeliveryBinding } from './receipts.js'diff --git a/cli/src/memory/hostSessions.spec.ts b/companions/src/memory/hostSessions.spec.tssimilarity index 97%rename from cli/src/memory/hostSessions.spec.tsrename to companions/src/memory/hostSessions.spec.tsindex bcc6ea9e9..552dfa3c3 100644--- a/cli/src/memory/hostSessions.spec.ts+++ b/companions/src/memory/hostSessions.spec.ts@@ -1,7 +1,7 @@import { expect, it } from 'vitest'import { hasMemoryForegroundActivity, MemorySessionRoster } from './hostSessions.js'-import { lineToEvents, newTurnState } from '../lib/normalize.js'-import { CodexNormalizer } from '../engines/codex/normalizer.js'+import { lineToEvents, newTurnState } from '../../../cli/src/lib/normalize.js'+import { CodexNormalizer } from '../../../cli/src/engines/codex/normalizer.js'const session = { agentId: 'agent', engine: 'claude', sessionId: 'native', cwd: '/projects/code',transcriptPath: '/native/session.jsonl', registeredAt: 100 }diff --git a/cli/src/memory/hostSessions.ts b/companions/src/memory/hostSessions.tssimilarity index 98%rename from cli/src/memory/hostSessions.tsrename to companions/src/memory/hostSessions.tsindex 96013fdf4..325bb597f 100644--- a/cli/src/memory/hostSessions.ts+++ b/companions/src/memory/hostSessions.ts@@ -1,6 +1,6 @@import { isAbsolute, parse, resolve } from 'node:path'import type { MemoryHostSession } from './runtime.js'-import type { LiveEvent } from '../lib/normalize.js'+import type { LiveEvent } from '../../../cli/src/lib/normalize.js'/** A streamed reply or tool result is ongoing work, not a new foreground request. */export function hasMemoryForegroundActivity(events: readonly Pick<LiveEvent, 'type'>[],diff --git a/companions/src/memory/index.ts b/companions/src/memory/index.tsnew file mode 100644index 000000000..91a802e31--- /dev/null+++ b/companions/src/memory/index.ts@@ -0,0 +1,7 @@+/** Optional knowledge subsystem. The caller owns its explicit start/pause/close lifecycle. */+export * from './api.js'+export { CodingMemoryRuntime } from './runtime.js'+export { MemoryClient } from './client.js'+export { MemoryControl } from './control.js'+export { MemoryExperimentSettings } from './experiment.js'+export type { MemoryPort, Operation, Arguments, Result } from './operations.js'diff --git a/cli/src/memory/inference.spec.ts b/companions/src/memory/inference.spec.tssimilarity index 100%rename from cli/src/memory/inference.spec.tsrename to companions/src/memory/inference.spec.tsdiff --git a/cli/src/memory/inference.ts b/companions/src/memory/inference.tssimilarity index 100%rename from cli/src/memory/inference.tsrename to companions/src/memory/inference.tsdiff --git a/cli/src/memory/inferenceProcess.ts b/companions/src/memory/inferenceProcess.tssimilarity index 98%rename from cli/src/memory/inferenceProcess.tsrename to companions/src/memory/inferenceProcess.tsindex abc77e94a..f0bc63653 100644--- a/cli/src/memory/inferenceProcess.ts+++ b/companions/src/memory/inferenceProcess.ts@@ -1,6 +1,6 @@import { spawn } from 'node:child_process'import { StringDecoder } from 'node:string_decoder'-import type { OneShotOptions } from '../lib/oneshot.js'+import type { OneShotOptions } from '../../../cli/src/lib/oneshot.js'import { MemoryError } from './types.js'export interface MemoryInferenceObservation {diff --git a/cli/src/memory/inferenceStatus.ts b/companions/src/memory/inferenceStatus.tssimilarity index 100%rename from cli/src/memory/inferenceStatus.tsrename to companions/src/memory/inferenceStatus.tsdiff --git a/cli/src/memory/learner.spec.ts b/companions/src/memory/learner.spec.tssimilarity index 100%rename from cli/src/memory/learner.spec.tsrename to companions/src/memory/learner.spec.tsdiff --git a/cli/src/memory/learner.ts b/companions/src/memory/learner.tssimilarity index 100%rename from cli/src/memory/learner.tsrename to companions/src/memory/learner.tsdiff --git a/cli/src/pair/learn/borrow.more.spec.ts b/companions/src/memory/lessons/borrow.more.spec.tssimilarity index 99%rename from cli/src/pair/learn/borrow.more.spec.tsrename to companions/src/memory/lessons/borrow.more.spec.tsindex f5198bd95..7ef668a53 100644--- a/cli/src/pair/learn/borrow.more.spec.ts+++ b/companions/src/memory/lessons/borrow.more.spec.ts@@ -8,7 +8,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'import { chmodSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { dirname, join } from 'node:path'-import { mangleClaudeProjectDir } from '../../lib/claudeProject.js'+import { mangleClaudeProjectDir } from '../../../../cli/src/lib/claudeProject.js'import {BORROW_MAX_FILE_BYTES, LessonBorrower, borrowSignal, hermesProvenance, parseFrontmatter, readClaudeMemory, readCodexMemories, readHermesSkills,} from './borrow.js'diff --git a/cli/src/pair/learn/borrow.spec.ts b/companions/src/memory/lessons/borrow.spec.tssimilarity index 99%rename from cli/src/pair/learn/borrow.spec.tsrename to companions/src/memory/lessons/borrow.spec.tsindex 5ac7c865f..674f06ed1 100644--- a/cli/src/pair/learn/borrow.spec.ts+++ b/companions/src/memory/lessons/borrow.spec.ts@@ -6,7 +6,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'import { mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { dirname, join } from 'node:path'-import { mangleClaudeProjectDir } from '../../lib/claudeProject.js'+import { mangleClaudeProjectDir } from '../../../../cli/src/lib/claudeProject.js'import {BORROW_PENDING_MAX, BORROW_PER_PASS, LessonBorrower, borrowSignal, hermesProvenance, parseFrontmatter, readClaudeMemory, readCodexMemories, readHermesSkills,} from './borrow.js'diff --git a/cli/src/pair/learn/borrow.ts b/companions/src/memory/lessons/borrow.tssimilarity index 99%rename from cli/src/pair/learn/borrow.tsrename to companions/src/memory/lessons/borrow.tsindex 4cfec26ef..10741647b 100644--- a/cli/src/pair/learn/borrow.ts+++ b/companions/src/memory/lessons/borrow.ts@@ -24,9 +24,9 @@*/import { lstatSync, readFileSync, readdirSync, realpathSync } from 'node:fs'import { basename, join } from 'node:path'-import { mangleClaudeProjectDir } from '../../lib/claudeProject.js'+import { mangleClaudeProjectDir } from '../../../../cli/src/lib/claudeProject.js'import { guardLesson, slug, type DistillWhy } from './distill.js'-import { untrusted } from './guard.js'+import { untrusted } from '../../shared/guard.js'import type { LessonRecord, LessonStore } from './store.js'import { contentHash, projectHash, projectName, type Signal } from './types.js'diff --git a/cli/src/pair/learn/curate.spec.ts b/companions/src/memory/lessons/curate.spec.tssimilarity index 100%rename from cli/src/pair/learn/curate.spec.tsrename to companions/src/memory/lessons/curate.spec.tsdiff --git a/cli/src/pair/learn/curate.ts b/companions/src/memory/lessons/curate.tssimilarity index 100%rename from cli/src/pair/learn/curate.tsrename to companions/src/memory/lessons/curate.tsdiff --git a/cli/src/pair/learn/distill.more.spec.ts b/companions/src/memory/lessons/distill.more.spec.tssimilarity index 99%rename from cli/src/pair/learn/distill.more.spec.tsrename to companions/src/memory/lessons/distill.more.spec.tsindex d5c389434..dba093172 100644--- a/cli/src/pair/learn/distill.more.spec.ts+++ b/companions/src/memory/lessons/distill.more.spec.ts@@ -5,7 +5,7 @@*/import { describe, expect, it, vi } from 'vitest'import { DISTILL_BUDGET_MS, LessonDistiller, distillPrompt, guardLesson, parseDistilled, slug, templateLesson, whoHit } from './distill.js'-import type { PairOneShot } from '../triage.js'+import type { PairOneShot } from '../../companion/triage.js'import type { Provenance, Signal } from './types.js'const at = 1_000_000diff --git a/cli/src/pair/learn/distill.spec.ts b/companions/src/memory/lessons/distill.spec.tssimilarity index 99%rename from cli/src/pair/learn/distill.spec.tsrename to companions/src/memory/lessons/distill.spec.tsindex 884b8ddf7..fddd2de81 100644--- a/cli/src/pair/learn/distill.spec.ts+++ b/companions/src/memory/lessons/distill.spec.ts@@ -6,7 +6,7 @@import { describe, expect, it, vi } from 'vitest'import { LessonDistiller, distillPrompt, guardLesson, parseDistilled, templateLesson, type Distilled } from './distill.js'import type { Lesson, Provenance, Signal } from './types.js'-import type { PairOneShot } from '../triage.js'+import type { PairOneShot } from '../../companion/triage.js'const at = 1_000_000const from = (engine: string, agentId: string, turn = 1): Provenance => ({ engine, machine: 'm2', agentId, session: `s-${agentId}`, turn, project: 'abc123', at })diff --git a/cli/src/pair/learn/distill.ts b/companions/src/memory/lessons/distill.tssimilarity index 98%rename from cli/src/pair/learn/distill.tsrename to companions/src/memory/lessons/distill.tsindex 3f4b70bbf..3c6d90231 100644--- a/cli/src/pair/learn/distill.ts+++ b/companions/src/memory/lessons/distill.ts@@ -19,9 +19,9 @@* safety off, sends files out, or still speaks to a model; emails and home paths are redacted; the* AGENTS.md block's own markers can never appear in it.*/-import type { PairOneShot } from '../triage.js'-import { isDenyClass } from '../classify.js'-import { codeSpan, inert, redact, refusal, untrusted, type Refusal } from './guard.js'+import type { TextInference as PairOneShot } from '../../shared/inference.js'+import { isDenyClass } from '../../shared/classify.js'+import { codeSpan, inert, redact, refusal, untrusted, type Refusal } from '../../shared/guard.js'import type { Lesson, Provenance, Signal } from './types.js'export const SKILL_BODY_MAX_LINES = 30diff --git a/cli/src/pair/learn/export.more.spec.ts b/companions/src/memory/lessons/export.more.spec.tssimilarity index 99%rename from cli/src/pair/learn/export.more.spec.tsrename to companions/src/memory/lessons/export.more.spec.tsindex f125a90ee..d6e86967a 100644--- a/cli/src/pair/learn/export.more.spec.ts+++ b/companions/src/memory/lessons/export.more.spec.ts@@ -7,7 +7,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'-import type { ExportDestination } from '../rules.js'+import type { ExportDestination } from '../../companion/rules.js'import { LessonExporter, renderExported } from './export.js'import { LessonStore, type LessonRecord } from './store.js'import type { Lesson, Signal } from './types.js'diff --git a/cli/src/pair/learn/export.spec.ts b/companions/src/memory/lessons/export.spec.tssimilarity index 99%rename from cli/src/pair/learn/export.spec.tsrename to companions/src/memory/lessons/export.spec.tsindex fd5c20e6e..ae95af412 100644--- a/cli/src/pair/learn/export.spec.ts+++ b/companions/src/memory/lessons/export.spec.ts@@ -7,7 +7,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'-import type { ExportDestination } from '../rules.js'+import type { ExportDestination } from '../../companion/rules.js'import { LessonExporter, renderExported } from './export.js'import { LessonStore, type LessonRecord } from './store.js'import type { Lesson, Signal } from './types.js'diff --git a/cli/src/pair/learn/export.ts b/companions/src/memory/lessons/export.tssimilarity index 99%rename from cli/src/pair/learn/export.tsrename to companions/src/memory/lessons/export.tsindex 9a9eb240f..ed71bc664 100644--- a/cli/src/pair/learn/export.ts+++ b/companions/src/memory/lessons/export.ts@@ -16,7 +16,7 @@import { createHash } from 'node:crypto'import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, rmdirSync, writeFileSync } from 'node:fs'import { join } from 'node:path'-import type { ExportDestination } from '../rules.js'+import type { ExportDestination } from './types.js'import { renderSkill, type LessonRecord, type LessonStore } from './store.js'export interface ExportDirs { agents: string; claude: string }diff --git a/cli/src/pair/learn/publish.more.spec.ts b/companions/src/memory/lessons/publish.more.spec.tssimilarity index 100%rename from cli/src/pair/learn/publish.more.spec.tsrename to companions/src/memory/lessons/publish.more.spec.tsdiff --git a/cli/src/pair/learn/publish.spec.ts b/companions/src/memory/lessons/publish.spec.tssimilarity index 96%rename from cli/src/pair/learn/publish.spec.tsrename to companions/src/memory/lessons/publish.spec.tsindex 7463ec5be..214c7cab1 100644--- a/cli/src/pair/learn/publish.spec.ts+++ b/companions/src/memory/lessons/publish.spec.ts@@ -10,12 +10,21 @@ import { execFileSync } from 'node:child_process'import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { prepareHarnessLaunch } from '../../dsh/runtime.js'-import type { InstalledDsh } from '../../dsh/installed.js'+import { publishRuntimeLessons } from '../../application/lessons/runtime.js'+import { prepareHarnessLaunch as prepare } from '../../../../cli/src/dsh/runtime.js'+import type { RuntimeLessons } from './publish.js'+import type { InstalledDsh } from '../../../../cli/src/dsh/installed.js'import { LESSONS_BEGIN, LESSONS_END, LESSONS_MARK, NOTES_EXCLUDE, findProject, noteFile, notesPath, publishNote, runtimeLessons, unpublishNote, withdrawSkill } from './publish.js'import { LessonStore, type LessonRecord } from './store.js'import { projectHash, type Lesson, type Signal } from './types.js'+function prepareHarnessLaunch(...args: [...Parameters<typeof prepare>, lessons?: RuntimeLessons | null]) {+ const [dsh, workspace, engine, key, account, sourceKey, lessons] = args+ const launch = prepare(dsh, workspace, engine, key, account, sourceKey)+ publishRuntimeLessons(launch.env.HARNESS_CONTEXT_FILE!, lessons)+ return launch+}+let dir: stringlet home: stringlet ws: stringdiff --git a/cli/src/pair/learn/publish.ts b/companions/src/memory/lessons/publish.tssimilarity index 91%rename from cli/src/pair/learn/publish.tsrename to companions/src/memory/lessons/publish.tsindex 81dc713e8..aa720104d 100644--- a/cli/src/pair/learn/publish.ts+++ b/companions/src/memory/lessons/publish.ts@@ -18,10 +18,12 @@* exactly it, wherever it is.*/import { execFileSync } from 'node:child_process'-import { appendFileSync, chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, unlinkSync, writeFileSync } from 'node:fs'+import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, unlinkSync, writeFileSync } from 'node:fs'import { isAbsolute, join, resolve } from 'node:path'import type { LessonRecord, LessonStore } from './store.js'import { projectHash } from './types.js'+import { addExcludeEntry, isLink, isPlainDir, isPlainFile } from '../../../../cli/src/lib/projectFiles.js'+export { addExcludeEntry, isLink, isPlainDir, isPlainFile }/** What dsh/runtime.ts copies and lists for one session. */export interface RuntimeLessons {@@ -40,21 +42,6 @@ function hashesOf(dir: string): Set<string> {return hashes}-/** A regular file, not a symlink to one. */-export function isPlainFile(path: string): boolean {- try { const stat = lstatSync(path); return stat.isFile() && !stat.isSymbolicLink() } catch { return false }-}--/** A real folder, not a symlink to one. */-export function isPlainDir(path: string): boolean {- try { const stat = lstatSync(path); return stat.isDirectory() && !stat.isSymbolicLink() } catch { return false }-}--/** A symlink (to anything, or dangling). */-export function isLink(path: string): boolean {- try { return lstatSync(path).isSymbolicLink() } catch { return false }-}-/** The approved skills a session in `workspace` loads (every one made in no project, or in this one), and its notes. */export function runtimeLessons(store: Pick<LessonStore, 'approved' | 'skillsDir'>, workspace: string): RuntimeLessons | null {const here = hashesOf(workspace)@@ -246,20 +233,6 @@ export function excludeNotes(projectDir: string, git = 'git'): string | null {return addExcludeEntry(isAbsolute(path) ? path : resolve(projectDir, path), { pattern: NOTES_EXCLUDE, comment: 'Harness lessons (untracked notes)' })}-/**- * One line (under a `# comment` line) in an exclude file, once: an entry already there is left as it is.- * Never through a symlink: null when the file or its folder is one. Creates the folder when missing; read and- * write errors throw. Returns the file when the entry is there.- */-export function addExcludeEntry(file: string, entry: { pattern: string; comment: string }): string | null {- if (isLink(file) || isLink(join(file, '..'))) return null- const text = existsSync(file) ? readFileSync(file, 'utf8') : ''- if (text.split('\n').some((line) => line.trim() === entry.pattern)) return file- mkdirSync(join(file, '..'), { recursive: true })- appendFileSync(file, `${text && !text.endsWith('\n') ? '\n' : ''}# ${entry.comment}\n${entry.pattern}\n`)- return file-}-/*** Write a note for the project. Default: `.harness/lessons.md`, untracked. `agentsMd` (the person opted this* project in): into its AGENTS.md or CLAUDE.md block — only a file that exists, unless `create`.diff --git a/cli/src/pair/learn/signals.more.spec.ts b/companions/src/memory/lessons/signals.more.spec.tssimilarity index 100%rename from cli/src/pair/learn/signals.more.spec.tsrename to companions/src/memory/lessons/signals.more.spec.tsdiff --git a/cli/src/pair/learn/signals.spec.ts b/companions/src/memory/lessons/signals.spec.tssimilarity index 100%rename from cli/src/pair/learn/signals.spec.tsrename to companions/src/memory/lessons/signals.spec.tsdiff --git a/cli/src/pair/learn/signals.ts b/companions/src/memory/lessons/signals.tssimilarity index 99%rename from cli/src/pair/learn/signals.tsrename to companions/src/memory/lessons/signals.tsindex 171a17cf7..d5e421464 100644--- a/cli/src/pair/learn/signals.ts+++ b/companions/src/memory/lessons/signals.ts@@ -20,7 +20,7 @@*/import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'import { dirname } from 'node:path'-import { redactDeep, untrusted } from './guard.js'+import { redactDeep, untrusted } from '../../shared/guard.js'import { contentHash, projectHash, projectName, type Provenance, type Signal } from './types.js'export const FAILURE_WINDOW_MS = 7 * 24 * 60 * 60_000diff --git a/cli/src/pair/learn/store.more.spec.ts b/companions/src/memory/lessons/store.more.spec.tssimilarity index 100%rename from cli/src/pair/learn/store.more.spec.tsrename to companions/src/memory/lessons/store.more.spec.tsdiff --git a/cli/src/pair/learn/store.spec.ts b/companions/src/memory/lessons/store.spec.tssimilarity index 100%rename from cli/src/pair/learn/store.spec.tsrename to companions/src/memory/lessons/store.spec.tsdiff --git a/cli/src/pair/learn/store.ts b/companions/src/memory/lessons/store.tssimilarity index 99%rename from cli/src/pair/learn/store.tsrename to companions/src/memory/lessons/store.tsindex a1718b828..d0c9649fa 100644--- a/cli/src/pair/learn/store.ts+++ b/companions/src/memory/lessons/store.ts@@ -22,7 +22,7 @@ import { execFileSync } from 'node:child_process'import { randomBytes } from 'node:crypto'import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs'import { join } from 'node:path'-import { redactDeep, refusal } from './guard.js'+import { redactDeep, refusal } from '../../shared/guard.js'import { contentHash, type Lesson, type Provenance, type Signal, type SignalKind } from './types.js'export type LessonStatus = 'pending' | 'approved' | 'reverted' | 'skipped' | 'archived'diff --git a/cli/src/pair/learn/types.spec.ts b/companions/src/memory/lessons/types.spec.tssimilarity index 100%rename from cli/src/pair/learn/types.spec.tsrename to companions/src/memory/lessons/types.spec.tsdiff --git a/cli/src/pair/learn/types.ts b/companions/src/memory/lessons/types.tssimilarity index 95%rename from cli/src/pair/learn/types.tsrename to companions/src/memory/lessons/types.tsindex 948dc9ef0..db755cff6 100644--- a/cli/src/pair/learn/types.ts+++ b/companions/src/memory/lessons/types.ts@@ -78,3 +78,7 @@ export function projectName(cwd: string | null | undefined): string | null {export function contentHash(value: unknown): string {return createHash('sha256').update(JSON.stringify(value)).digest('hex').slice(0, 24)}++/** Explicit destinations for approved skill copies. */+export const EXPORT_DESTINATIONS = ['agents', 'claude'] as const+export type ExportDestination = typeof EXPORT_DESTINATIONS[number]diff --git a/cli/src/pair/learn/usage.more.spec.ts b/companions/src/memory/lessons/usage.more.spec.tssimilarity index 100%rename from cli/src/pair/learn/usage.more.spec.tsrename to companions/src/memory/lessons/usage.more.spec.tsdiff --git a/cli/src/pair/learn/usage.spec.ts b/companions/src/memory/lessons/usage.spec.tssimilarity index 100%rename from cli/src/pair/learn/usage.spec.tsrename to companions/src/memory/lessons/usage.spec.tsdiff --git a/cli/src/pair/learn/usage.ts b/companions/src/memory/lessons/usage.tssimilarity index 100%rename from cli/src/pair/learn/usage.tsrename to companions/src/memory/lessons/usage.tsdiff --git a/cli/src/memory/library.spec.ts b/companions/src/memory/library.spec.tssimilarity index 100%rename from cli/src/memory/library.spec.tsrename to companions/src/memory/library.spec.tsdiff --git a/cli/src/memory/library.ts b/companions/src/memory/library.tssimilarity index 100%rename from cli/src/memory/library.tsrename to companions/src/memory/library.tsdiff --git a/cli/src/memory/native.spec.ts b/companions/src/memory/native.spec.tssimilarity index 100%rename from cli/src/memory/native.spec.tsrename to companions/src/memory/native.spec.tsdiff --git a/cli/src/memory/native.ts b/companions/src/memory/native.tssimilarity index 97%rename from cli/src/memory/native.tsrename to companions/src/memory/native.tsindex 6a281c258..7002f29cd 100644--- a/cli/src/memory/native.ts+++ b/companions/src/memory/native.ts@@ -1,8 +1,8 @@/** Native conversation records, before live-view truncation. Thinking and injected instructions stay out. */import { digest } from './admission.js'import type { SourceEvent } from './types.js'-import { stripBashModeBlocks, stripContextSummary, stripSystemBlocks } from '../lib/normalize.js'-import { askKind, personAsk } from '../lib/sessionSearch/turns.js'+import { stripBashModeBlocks, stripContextSummary, stripSystemBlocks } from '../../../cli/src/lib/normalize.js'+import { askKind, personAsk } from '../../../cli/src/lib/sessionSearch/turns.js'export interface NativePart {nativeEventId: string; role: SourceEvent['role']; text: string; observedAt: numberdiff --git a/cli/src/memory/notebook.spec.ts b/companions/src/memory/notebook.spec.tssimilarity index 99%rename from cli/src/memory/notebook.spec.tsrename to companions/src/memory/notebook.spec.tsindex 89198a261..4dbb296cd 100644--- a/cli/src/memory/notebook.spec.ts+++ b/companions/src/memory/notebook.spec.ts@@ -3,7 +3,7 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, beforeEach, expect, it } from 'vitest'import { CodingMemoryStore } from './store.js'-import { builtinSqlite } from '../lib/sqliteRead.js'+import { builtinSqlite } from '../../../cli/src/lib/sqliteRead.js'import type { Database as MemoryDatabase } from './database.js'import type { NotebookLease } from './notebook.js'import type { MemoryAccess, MemoryDraft, MemoryRecord, SourceEvent } from './types.js'diff --git a/cli/src/memory/notebook.ts b/companions/src/memory/notebook.tssimilarity index 100%rename from cli/src/memory/notebook.tsrename to companions/src/memory/notebook.tsdiff --git a/cli/src/memory/opencodeBinding.spec.ts b/companions/src/memory/opencodeBinding.spec.tssimilarity index 100%rename from cli/src/memory/opencodeBinding.spec.tsrename to companions/src/memory/opencodeBinding.spec.tsdiff --git a/cli/src/memory/opencodeBinding.ts b/companions/src/memory/opencodeBinding.tssimilarity index 100%rename from cli/src/memory/opencodeBinding.tsrename to companions/src/memory/opencodeBinding.tsdiff --git a/cli/src/memory/opencodeCapture.spec.ts b/companions/src/memory/opencodeCapture.spec.tssimilarity index 99%rename from cli/src/memory/opencodeCapture.spec.tsrename to companions/src/memory/opencodeCapture.spec.tsindex b78ab8b3d..836fef747 100644--- a/cli/src/memory/opencodeCapture.spec.ts+++ b/companions/src/memory/opencodeCapture.spec.ts@@ -4,7 +4,7 @@ import { mkdtempSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSyncimport { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, beforeEach, expect, it } from 'vitest'-import { closeSqliteHandles, overrideBuiltinSqlite } from '../lib/sqliteRead.js'+import { closeSqliteHandles, overrideBuiltinSqlite } from '../../../cli/src/lib/sqliteRead.js'import { NativeMemoryCapture, type CaptureSession } from './capture.js'import { CodingMemoryStore } from './store.js'import type { Database } from './database.js'diff --git a/cli/src/memory/opencodeCapture.ts b/companions/src/memory/opencodeCapture.tssimilarity index 100%rename from cli/src/memory/opencodeCapture.tsrename to companions/src/memory/opencodeCapture.tsdiff --git a/cli/src/memory/opencodeInference.spec.ts b/companions/src/memory/opencodeInference.spec.tssimilarity index 100%rename from cli/src/memory/opencodeInference.spec.tsrename to companions/src/memory/opencodeInference.spec.tsdiff --git a/cli/src/memory/opencodeInference.ts b/companions/src/memory/opencodeInference.tssimilarity index 100%rename from cli/src/memory/opencodeInference.tsrename to companions/src/memory/opencodeInference.tsdiff --git a/cli/src/memory/opencodeRead.ts b/companions/src/memory/opencodeRead.tssimilarity index 98%rename from cli/src/memory/opencodeRead.tsrename to companions/src/memory/opencodeRead.tsindex f1b750d99..74ff59648 100644--- a/cli/src/memory/opencodeRead.ts+++ b/companions/src/memory/opencodeRead.ts@@ -1,6 +1,6 @@/** Bounded, read-only access to one host-bound OpenCode session. Never loads the live UI's clipped text. */import { z } from 'zod'-import { sqliteReadAll, type SqliteParam } from '../lib/sqliteRead.js'+import { sqliteReadAll, type SqliteParam } from '../../../cli/src/lib/sqliteRead.js'import { MemoryError } from './types.js'import type { OpenCodeSourceMessage } from './opencodeSource.js'diff --git a/cli/src/memory/opencodeSource.ts b/companions/src/memory/opencodeSource.tssimilarity index 100%rename from cli/src/memory/opencodeSource.tsrename to companions/src/memory/opencodeSource.tsdiff --git a/cli/src/memory/operations.ts b/companions/src/memory/operations.tssimilarity index 100%rename from cli/src/memory/operations.tsrename to companions/src/memory/operations.tsdiff --git a/cli/src/memory/ownerProcess.ts b/companions/src/memory/ownerProcess.tssimilarity index 100%rename from cli/src/memory/ownerProcess.tsrename to companions/src/memory/ownerProcess.tsdiff --git a/cli/src/memory/project.spec.ts b/companions/src/memory/project.spec.tssimilarity index 100%rename from cli/src/memory/project.spec.tsrename to companions/src/memory/project.spec.tsdiff --git a/cli/src/memory/project.ts b/companions/src/memory/project.tssimilarity index 100%rename from cli/src/memory/project.tsrename to companions/src/memory/project.tsdiff --git a/cli/src/memory/queue.spec.ts b/companions/src/memory/queue.spec.tssimilarity index 99%rename from cli/src/memory/queue.spec.tsrename to companions/src/memory/queue.spec.tsindex c739ec437..1b7af678f 100644--- a/cli/src/memory/queue.spec.ts+++ b/companions/src/memory/queue.spec.ts@@ -3,7 +3,7 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, beforeEach, describe, expect, it } from 'vitest'import { CodingMemoryStore } from './store.js'-import { builtinSqlite } from '../lib/sqliteRead.js'+import { builtinSqlite } from '../../../cli/src/lib/sqliteRead.js'import type { CaptureBatch, LearningLease } from './queue.js'import type { MemoryAccess, MemoryDraft, SourceEvent } from './types.js'diff --git a/cli/src/memory/queue.ts b/companions/src/memory/queue.tssimilarity index 100%rename from cli/src/memory/queue.tsrename to companions/src/memory/queue.tsdiff --git a/cli/src/memory/recallSources.spec.ts b/companions/src/memory/recallSources.spec.tssimilarity index 100%rename from cli/src/memory/recallSources.spec.tsrename to companions/src/memory/recallSources.spec.tsdiff --git a/cli/src/memory/recallSources.ts b/companions/src/memory/recallSources.tssimilarity index 100%rename from cli/src/memory/recallSources.tsrename to companions/src/memory/recallSources.tsdiff --git a/cli/src/memory/receipts.spec.ts b/companions/src/memory/receipts.spec.tssimilarity index 100%rename from cli/src/memory/receipts.spec.tsrename to companions/src/memory/receipts.spec.tsdiff --git a/cli/src/memory/receipts.ts b/companions/src/memory/receipts.tssimilarity index 100%rename from cli/src/memory/receipts.tsrename to companions/src/memory/receipts.tsdiff --git a/cli/src/memory/retention.spec.ts b/companions/src/memory/retention.spec.tssimilarity index 100%rename from cli/src/memory/retention.spec.tsrename to companions/src/memory/retention.spec.tsdiff --git a/cli/src/memory/runtime.spec.ts b/companions/src/memory/runtime.spec.tssimilarity index 97%rename from cli/src/memory/runtime.spec.tsrename to companions/src/memory/runtime.spec.tsindex 4e61959b9..d3432e8d0 100644--- a/cli/src/memory/runtime.spec.ts+++ b/companions/src/memory/runtime.spec.ts@@ -96,27 +96,19 @@ it('opens no store and invokes no model while experimental, watching consent orexpect(inference.run).not.toHaveBeenCalled()})-it('keeps the companion available between reviews only while this owner has enabled learning', async () => {+it('changes memory consent without requiring or starting a companion conversation', async () => {sessions = []- expect(runtime.needsCompanion()).toBe(false)await runtime.tick()await runtime.configure({ learn: true, recall: false })- expect(runtime.needsCompanion()).toBe(true)+ expect(runtime.status().preferences).toMatchObject({ learn: true, recall: false })expect(inference.target).not.toHaveBeenCalled()expect(inference.run).not.toHaveBeenCalled()await runtime.configure({ learn: false, recall: true })- expect(runtime.needsCompanion()).toBe(false)- await runtime.configure({ learn: true, recall: true })+ expect(runtime.status().preferences).toMatchObject({ learn: false, recall: true })context.watching = false- expect(runtime.needsCompanion()).toBe(false)- context.watching = true; context.experimental = false- expect(runtime.needsCompanion()).toBe(false)- context.experimental = true; context.profileId = 'owner_b'- expect(runtime.needsCompanion()).toBe(false)- context.profileId = 'owner_a'- expect(runtime.needsCompanion()).toBe(true)+ expect(runtime.status().state).toBe('off')await runtime.pause()- expect(runtime.needsCompanion()).toBe(false)+ expect(inference.run).not.toHaveBeenCalled()})it.each(['replace', 'mutate'] as const)('binds activity to open host sessions and rejects a native-session %s during the read', async mode => {diff --git a/cli/src/memory/runtime.ts b/companions/src/memory/runtime.tssimilarity index 98%rename from cli/src/memory/runtime.tsrename to companions/src/memory/runtime.tsindex f454f4457..62a6dc65b 100644--- a/cli/src/memory/runtime.ts+++ b/companions/src/memory/runtime.ts@@ -1,6 +1,6 @@/** Local host lifecycle. Session authority and coding eligibility must come from the daemon. */import { join } from 'node:path'-import { redact } from '../pair/learn/guard.js'+import { redact } from '../shared/guard.js'import { z } from 'zod'import { digest } from './admission.js'import { NativeMemoryCapture, type CaptureOutcome } from './capture.js'@@ -116,11 +116,6 @@ export class CodingMemoryRuntime {return !this.stopped && context.experimental ? context.profileId : null}- /** Learning is a continuing use of the collection's model, even with an empty or deferred queue. */- needsCompanion(): boolean {- return !!this.active?.ready && this.authorized(this.active) && this.active.preferences.learn- }-/** Explicit owner controls remain usable with watching/learning/recall off. No capture is started. */async libraryStatus(owner: string) {return this.withOwner(owner, async port => ({ runtime: this.status(),diff --git a/cli/src/memory/store.spec.ts b/companions/src/memory/store.spec.tssimilarity index 99%rename from cli/src/memory/store.spec.tsrename to companions/src/memory/store.spec.tsindex ab7e75f23..0f056c9c3 100644--- a/cli/src/memory/store.spec.ts+++ b/companions/src/memory/store.spec.ts@@ -3,7 +3,7 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, beforeEach, describe, expect, it } from 'vitest'import { CodingMemoryStore } from './store.js'-import { builtinSqlite } from '../lib/sqliteRead.js'+import { builtinSqlite } from '../../../cli/src/lib/sqliteRead.js'import type { MemoryAccess, MemoryDraft, SourceEvent } from './types.js'const access: MemoryAccess = { profileId: 'owner', projectIds: ['project_a'], includeProfile: true }diff --git a/cli/src/memory/store.ts b/companions/src/memory/store.tssimilarity index 99%rename from cli/src/memory/store.tsrename to companions/src/memory/store.tsindex 769e27167..5ce2e9ac7 100644--- a/cli/src/memory/store.ts+++ b/companions/src/memory/store.ts@@ -5,8 +5,8 @@import { randomUUID } from 'node:crypto'import { chmodSync, existsSync, lstatSync, mkdirSync } from 'node:fs'import { basename, dirname, isAbsolute, join } from 'node:path'-import { builtinSqlite } from '../lib/sqliteRead.js'-import { redact } from '../pair/learn/guard.js'+import { builtinSqlite } from '../../../cli/src/lib/sqliteRead.js'+import { redact } from '../shared/guard.js'import { admission, assertSafe, canonical, digest, proposalFingerprint } from './admission.js'import type { ProjectLocator } from './project.js'import type { Database } from './database.js'diff --git a/cli/src/memory/types.ts b/companions/src/memory/types.tssimilarity index 100%rename from cli/src/memory/types.tsrename to companions/src/memory/types.tsdiff --git a/cli/src/memory/usefulness.spec.ts b/companions/src/memory/usefulness.spec.tssimilarity index 99%rename from cli/src/memory/usefulness.spec.tsrename to companions/src/memory/usefulness.spec.tsindex 643112b1b..520e4e777 100644--- a/cli/src/memory/usefulness.spec.ts+++ b/companions/src/memory/usefulness.spec.ts@@ -2,7 +2,7 @@ import { mkdtempSync, rmSync, readFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, beforeEach, expect, it } from 'vitest'-import { builtinSqlite } from '../lib/sqliteRead.js'+import { builtinSqlite } from '../../../cli/src/lib/sqliteRead.js'import type { Database } from './database.js'import { CodingMemoryStore } from './store.js'import type { MemoryDeliveryBinding } from './receipts.js'diff --git a/cli/src/memory/visibility.ts b/companions/src/memory/visibility.tssimilarity index 100%rename from cli/src/memory/visibility.tsrename to companions/src/memory/visibility.tsdiff --git a/cli/src/memory/worker.ts b/companions/src/memory/worker.tssimilarity index 100%rename from cli/src/memory/worker.tsrename to companions/src/memory/worker.tsdiff --git a/cli/src/pair/learn/approval.more.spec.ts b/companions/src/shared/approval.more.spec.tssimilarity index 100%rename from cli/src/pair/learn/approval.more.spec.tsrename to companions/src/shared/approval.more.spec.tsdiff --git a/cli/src/pair/learn/approval.spec.ts b/companions/src/shared/approval.spec.tssimilarity index 100%rename from cli/src/pair/learn/approval.spec.tsrename to companions/src/shared/approval.spec.tsdiff --git a/cli/src/pair/learn/approval.ts b/companions/src/shared/approval.tssimilarity index 100%rename from cli/src/pair/learn/approval.tsrename to companions/src/shared/approval.tsdiff --git a/cli/src/pair/classify.fuzz.spec.ts b/companions/src/shared/classify.fuzz.spec.tssimilarity index 100%rename from cli/src/pair/classify.fuzz.spec.tsrename to companions/src/shared/classify.fuzz.spec.tsdiff --git a/cli/src/pair/classify.more.spec.ts b/companions/src/shared/classify.more.spec.tssimilarity index 99%rename from cli/src/pair/classify.more.spec.tsrename to companions/src/shared/classify.more.spec.tsindex 2e69e635d..d3f8806c5 100644--- a/cli/src/pair/classify.more.spec.ts+++ b/companions/src/shared/classify.more.spec.ts@@ -8,7 +8,7 @@ import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSynimport { tmpdir } from 'node:os'import { join } from 'node:path'import { inProject, isAllowClass, isAllowedCommand, isAllowToolCall, matchToolCall, toolCommand } from './classify.js'-import { DIALOG_MAX } from './protocol.js'+import { DIALOG_MAX } from '../companion/protocol.js'const root = realpathSync(mkdtempSync(join(tmpdir(), 'classify-more-')))const home = join(root, 'home')diff --git a/cli/src/pair/classify.spec.ts b/companions/src/shared/classify.spec.tssimilarity index 93%rename from cli/src/pair/classify.spec.tsrename to companions/src/shared/classify.spec.tsindex 297eb39ee..bceb3029f 100644--- a/cli/src/pair/classify.spec.ts+++ b/companions/src/shared/classify.spec.ts@@ -9,10 +9,10 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import { inProject, isAllowClass, isAllowedCommand, isAllowToolCall, isDenyClass, isOneTimeYes, isPersistentOption, matchToolCall } from './classify.js'import { parseShell } from './shell.js'-import { parseEngineQuestionPane, type QuestionView } from '../lib/askQuestion.js'+import { parseEngineQuestionPane, type QuestionView } from '../../../cli/src/lib/askQuestion.js'const pane = (name: string): QuestionView =>- parseEngineQuestionPane(name.startsWith('codex') ? 'codex' : 'claude', readFileSync(join(__dirname, '../lib/__fixtures__', `permission-${name}.txt`), 'utf8')) as QuestionView+ parseEngineQuestionPane(name.startsWith('codex') ? 'codex' : 'claude', readFileSync(join(__dirname, '../../../cli/src/lib/__fixtures__', `permission-${name}.txt`), 'utf8')) as QuestionView// A real project on disk, a home around it, and a folder outside both: symlinks are resolved for real.const root = realpathSync(mkdtempSync(join(tmpdir(), 'classify-')))@@ -31,6 +31,18 @@ linkSync(join(home, '.bashrc'), join(cwd, 'hard.txt'))afterAll(() => rmSync(root, { recursive: true, force: true }))const at = { cwd, home }+it('classifies the current unframed permission prompt, not an answered command in scrollback', () => {+ const earlier = ['─'.repeat(60), ' Bash command', '', ' npm test', '',+ ' Do you want to proceed?', ' ❯ 1. Yes', ' 2. No', '', ' Esc to cancel · Tab to amend', '']+ const output = ['⏺ Bash(npm test)', ' ⎿ ok', '']+ const unframed = [' Do you want to proceed?', ' python3 scripts/wipe.py --all',+ ' ❯ 1. Yes', ' 2. No', '', ' Esc to cancel', '']+ const view = parseEngineQuestionPane('claude', [...earlier, ...output, ...unframed].join('\n')) as QuestionView+ expect(view.question).toBe('python3 scripts/wipe.py --all')+ expect(isAllowClass(view.dialog!, { ...at, permission: true })).toBe(false)+ expect(isAllowClass([' Bash command', '', ' npm test', ''].join('\n'), { ...at, permission: true })).toBe(true)+})+describe('deny-class', () => {it.each(['git push origin main', 'git push', 'git push --tags', 'npm test && git push', 'force-push the branch',diff --git a/cli/src/pair/classify.ts b/companions/src/shared/classify.tssimilarity index 99%rename from cli/src/pair/classify.tsrename to companions/src/shared/classify.tsindex 167e8ee6e..b818e9031 100644--- a/cli/src/pair/classify.ts+++ b/companions/src/shared/classify.ts@@ -65,7 +65,7 @@ export function isDenyClass(dialog: string, options: readonly string[] = []): bo}/** Options that answer for more than this once, and the one-time yes (pair/floor.ts, where the floor uses them). */-export { isOneTimeYes, isPersistentOption } from './floor.js'+export { isOneTimeYes, isPersistentOption } from '../companion/floor.js'// ── paths ───────────────────────────────────────────────────────────────────────────────────────────diff --git a/cli/src/pair/learn/guard.boundary.spec.ts b/companions/src/shared/guard.boundary.spec.tssimilarity index 100%rename from cli/src/pair/learn/guard.boundary.spec.tsrename to companions/src/shared/guard.boundary.spec.tsdiff --git a/cli/src/pair/learn/guard.fuzz.spec.ts b/companions/src/shared/guard.fuzz.spec.tssimilarity index 100%rename from cli/src/pair/learn/guard.fuzz.spec.tsrename to companions/src/shared/guard.fuzz.spec.tsdiff --git a/cli/src/pair/learn/guard.spec.ts b/companions/src/shared/guard.spec.tssimilarity index 100%rename from cli/src/pair/learn/guard.spec.tsrename to companions/src/shared/guard.spec.tsdiff --git a/cli/src/pair/learn/guard.ts b/companions/src/shared/guard.tssimilarity index 100%rename from cli/src/pair/learn/guard.tsrename to companions/src/shared/guard.tsdiff --git a/companions/src/shared/inference.ts b/companions/src/shared/inference.tsnew file mode 100644index 000000000..481009f7f--- /dev/null+++ b/companions/src/shared/inference.ts@@ -0,0 +1,2 @@+/** A bounded text-inference capability supplied by the optional application. */+export type TextInference = (prompt: string, opts: { timeoutMs: number; signal: AbortSignal }) => Promise<string | null>diff --git a/cli/src/pair/shell.spec.ts b/companions/src/shared/shell.spec.tssimilarity index 100%rename from cli/src/pair/shell.spec.tsrename to companions/src/shared/shell.spec.tsdiff --git a/cli/src/pair/shell.ts b/companions/src/shared/shell.tssimilarity index 100%rename from cli/src/pair/shell.tsrename to companions/src/shared/shell.tsdiff --git a/companions/tsconfig.json b/companions/tsconfig.jsonnew file mode 100644index 000000000..f27d96537--- /dev/null+++ b/companions/tsconfig.json@@ -0,0 +1,10 @@+{+ "extends": "../cli/tsconfig.json",+ "compilerOptions": {+ "rootDir": "..",+ "outDir": "dist",+ "tsBuildInfoFile": ".tsbuildinfo"+ },+ "include": ["src/**/*.ts"],+ "exclude": ["node_modules", "dist"]+}diff --git a/companions/vitest.config.ts b/companions/vitest.config.tsnew file mode 100644index 000000000..b632343e6--- /dev/null+++ b/companions/vitest.config.ts@@ -0,0 +1,8 @@+import { defineConfig } from 'vitest/config'++export default defineConfig({ test: {+ environment: 'node',+ setupFiles: ['./vitest.setup.ts'],+ include: ['src/**/*.spec.ts'],+ maxWorkers: 4,+} })diff --git a/companions/vitest.setup.ts b/companions/vitest.setup.tsnew file mode 100644index 000000000..876d3fabe--- /dev/null+++ b/companions/vitest.setup.ts@@ -0,0 +1,5 @@+import '../cli/vitest.setup.js'+import { join } from 'node:path'++// Optional feature tests own their fixture paths; the core never configures this store.+process.env.HARNESS_LESSONS_DIR = join(process.env.ADAPTER_DATA_DIR!, 'lessons')diff --git a/docs/architecture.md b/docs/architecture.mdindex 88ca021ad..b11b351a2 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -113,6 +113,15 @@ Runtime truth belongs to the daemon owning the work. A question answered throughmust resolve for the others. Closing an interface leaves execution running on an available host;it does not make a sleeping or disconnected host capable of continuing work elsewhere.+Companions and Memory have separate implementations in the optional+[companions package](../companions/README.md). Core does not construct either+subsystem or bundle their workers. Old optional requests receive an unsupported+response without changing their transport security boundaries. The package+currently builds as libraries; its application startup and client integration+remain disconnected. The [extraction plan](plans/2026-10-03-memory-companion-isolation.md)+records those remaining requirements. This extraction does not establish a+working companion-memory experience.+The current [orchestrator](../cli/src/orchestrator/service.ts) already persists local projectruns, task dependencies, and artifact handoffs. Cross-machine orchestration, project migration,and universal engine-session portability are separate capabilities; access to a remote terminaldiff --git a/docs/plans/2026-10-03-memory-companion-isolation.md b/docs/plans/2026-10-03-memory-companion-isolation.mdnew file mode 100644index 000000000..aeb54fdb5--- /dev/null+++ b/docs/plans/2026-10-03-memory-companion-isolation.md@@ -0,0 +1,222 @@+# Isolate memory and companions from the daemon++Companions and Memory form one optional product experience, implemented as two+separate subsystems outside the core daemon. The companion becomes useful through+what it remembers. Separating their implementation does not mean creating two+products, installations, or unrelated setup flows.++The Harness daemon will own machine execution, transport, authentication, and+ordinary agent lifecycle. It will not own memory capture, learning, recall policy,+companion personality, growth, collection state, or companion automation.++This document records the extraction requested on October 3, 2026, against+`35b57a9ce1d2ca792d353ab4d8b316cc759928d8`. The core-removal stage is implemented+on the isolated refactoring branch. The optional package builds as libraries,+with separate Companions and Memory APIs and an application composition layer.+It has no installed startup service or working desktop connection yet. See the+[package README](../../companions/README.md) for its runnable scope and gaps.++No installed services, user settings, or saved conversations were changed by+this extraction. The earlier [memory MVP](2026-10-03-personal-memory-mvp.md)+remains incomplete. This branch is a core-isolation candidate, not a claim that+companion memory works or is ready to release.++The product owner confirms that companion memory has not been released. The+refactor therefore protects existing Harness users and preserves development+data; it does not need a compatibility framework for unreleased feature clients.++## Required boundary++The daemon must build, start, serve ordinary clients, and shut down with the+optional package absent. Its runtime dependency graph must exclude both subsystems' implementations,+databases, model runners, artwork, and generated workers. Moving those imports+to another folder or lazily loading them inside the daemon does not meet this+requirement.++Ship one optional companion package. Within it, the Companions subsystem owns the+character experience, and the Memory subsystem owns durable knowledge. Each has+its own storage ownership, lifecycle and tests, joined by a small explicit API.+Keep memory's background workload in its own worker or process outside the core+daemon; the exact add-on process arrangement need not become a user-facing choice.++The optional package owns its startup, shutdown and bounded background jobs. The+daemon must not become its feature-specific supervisor or wait for it at startup+or shutdown. A companion's ordinary agent terminal remains a normal DSH session+managed through the existing agent API; it receives no special lifecycle rules.++```text+Desktop, CLI, mobile and other normal clients+ |+ Existing Harness commands and events+ |+ Harness daemon+ Sessions, transport, authentication,+ engine integration and device transport+ ^+ | existing authorized API+ +---------------+---------------------------------++ | Optional companion package |+ | |+ | Companions subsystem <-- API --> Memory subsystem|+ | DSH and viewer Capture |+ | Persona and growth Learning |+ | Collection and art Evidence |+ | Conversation and interaction Recall |+ | Review and edit|+ +-------------------------------------------------++```++Neither subsystem may import the other's implementation. Companions uses the+memory client contract. Memory ownership is the user and project, never an avatar+or companion terminal ID. Switching from Tim to GNU preserves what the system+knows about the person. There is no requirement to ship a standalone Memory app.++The companion DSH's explicit model selection supplies the memory configuration+through the contract. Memory owns its bounded inference jobs, rather than keeping+the foreground terminal alive. An unavailable configuration must remain+unavailable; it does not authorize a fallback account or provider. Provider and+framework adapters belong to the optional package, not core authentication.++Separate processes contain many failures but do not guarantee zero resource+interference on the same machine or create an OS security sandbox. The package+needs bounded concurrency, input sizes, queues, timeouts, retry backoff, and a+stop mechanism. It must never block the daemon's event loop with transcript+parsing, database queries, or model execution.++## Source inventory and destination++The table records dependencies in the original source and their extraction+responsibilities. Feature implementations and tests now live under+`companions/src/{companion,memory,application,shared}`. Core construction and+feature hooks have been removed. Application composition remains to be wired+to verified host capabilities; the moved modules are not running services.++| Current dependency | Extraction responsibility |+| --- | --- |+| [`cli.ts`](../../cli/src/cli.ts): `CodingMemoryRuntime`, `MemorySessionRoster`, `OpenCodeMemoryBinding`, settings, session-event ticks, pause and shutdown | Move capture, authorization mapping, settings, job scheduling and shutdown into Memory. Feed it only authorized input through the public client boundary. |+| [`authSession.ts`](../../cli/src/lib/authSession.ts): `memoryOwner`, `bindMemoryOwner`, refresh-time rebinding; `cli.ts` `/api/auth/me` interception | Core retains its general identity and revocation responsibilities. Memory maintains its own owner mapping. Remove memory-specific writes from the login file without resetting the sign-in, device identity, or refresh state. |+| [`hooks.ts`](../../cli/src/lib/hooks.ts), [`notify.mjs`](../../cli/hook/notify.mjs), [`hookServer.ts`](../../cli/src/hookServer.ts), OpenCode memory and recall plugins | Move native prompt context, provenance stamps, receipts and model-binding hooks into optional add-on adapters. Preserve ordinary session registration, turn and question hooks. Clean up only entries installed by this feature. |+| Memory runtime, client and native readers, formerly `cli/src/memory/`, now [`companions/src/memory/`](../../companions/src/memory/) | Move the entire memory workload outside the daemon. The optional package owns its storage worker, capture and orchestration; native reads may use synchronous SQLite only outside core. |+| [`cli.ts`](../../cli/src/cli.ts): `PairSensor`, `PairBrain`, `PairOwner`, `PairHarness`, rules, gates, fleet, journal, learning and reporting | Move companion observation, decisions, collection management and automation into Companions. Use ordinary agent commands; retain the relevant permissions and stale-question protections. |+| Intelligence, now [`application/intelligence.ts`](../../companions/src/application/intelligence.ts), and the removed `PairHarness.backgroundInUse` | Application composition binds the selected model to Memory's inference contract. Memory owns its background jobs; it cannot keep an ordinary terminal alive merely because learning is enabled. |+| [`dsh/runtime.ts`](../../cli/src/dsh/runtime.ts): automatic lesson installation; [`dsh/builtins.ts`](../../cli/src/dsh/builtins.ts): generated Pair package | Companion packaging belongs to its add-on. Lesson publication belongs to Memory through supported skill installation. Preserve ordinary DSH provisioning and already installed user skills. |+| [`backendSocket.ts`](../../cli/src/backendSocket.ts), [`localWsServer.ts`](../../cli/src/localWsServer.ts), [`applicationFrames.ts`](../../cli/src/lib/e2ee/applicationFrames.ts) | Remove feature handlers while preserving ordinary transport and authentication. Check that removing a feature frame cannot make sensitive input fall through to an unrestricted or plaintext route. |+| Identity, now [`companionIdentity.ts`](../../companions/src/companion/companionIdentity.ts), [`cableSession.ts`](../../cli/src/cable/cableSession.ts), zoo reporters and plate rendering | Companions owns traits, growth, artwork and rendering policy. Core retains only wire identity parsing and existing USB, status, notification, question and brightness transport. |+| [`build.mjs`](../../cli/build.mjs), [`build-bundle.mjs`](../../cli/build-bundle.mjs) | Move memory and plate worker payloads into the optional package. Package absence must be a supported core build configuration. |++Inspection of the original source established that its off state was incomplete:+authenticated profile responses can write memory ownership, and the OpenCode+message hook stamps provenance before checking whether learning is enabled.+Those core paths have been removed. These were observed code paths, not measured+evidence of a production incident.++## Existing APIs and unresolved gaps++Use the existing [command and event contract](../cli.md#automation) for normal+agent operations. Preserve the [DSH workspace contract](../../desktop/design/dsh-workspace.md):+viewer on the left and the real agent terminal on the right. A companion is a+client of this infrastructure.++Do not introduce a new daemon plug-in framework or an unrestricted extension RPC+to make the extraction convenient. First verify that existing APIs provide the+required identities, events and operations with appropriate authority. Specific+gaps still require investigation:++- Which existing client surface can provide scoped transcript access and revoke+ it promptly on logout, account change, or disabling learning?+- How can a native memory adapter verify the calling session and use its selected+ model without changing core authentication or copying credentials through an+ unrestricted endpoint?+- Which device API can accept optional companion presentation without moving USB+ ownership or allowing it to replace active questions and notifications?+- Which existing feature handlers can be removed together with the unreleased+ clients, and which shared code also serves released ordinary Harness features?++An unresolved gap disables the dependent add-on capability. It must not be filled+by weakening caller verification or silently widening core responsibilities.+Any necessary general protocol addition must have a separate, minimal contract+review under [CONTRIBUTING.md](../../CONTRIBUTING.md).++## Extraction order++1. **Establish the ordinary Harness baseline.** Map dependencies from the daemon+ entry point, generated hooks and bundle inputs. Record normal-session behavior+ without companion memory. Identify unrelated fixes in shared files so the+ extraction preserves them. There is no feature-client migration requirement+ for companion memory that has not shipped.+2. **Extract the two subsystems into the optional package.** Move their+ implementations, tests and data ownership behind explicit interfaces. Prove+ they can run against the existing daemon API in a disposable environment. Do not run+ old and new learners against the same data, and do not duplicate active+ companion sessions during this preparation.+3. **Connect the unreleased companion experience.** Update experimental settings,+ viewer, CLI/MCP commands and device presentation to use the package. Keep one+ coherent setup and existing consent controls. Do not build a legacy feature+ bridge or an independent Memory app. Feature requests must never fall through+ to an unrestricted command or plaintext path.+4. **Remove feature runtime dependencies from core.** Delete construction,+ callbacks, timers, account metadata handling, native hook additions, special+ terminal lifecycle behavior and bundled workers. Verify the daemon with the+ whole companion package absent. Preserve security guarantees while removing+ feature-specific protocol handling.+5. **Validate the candidate and prepare a separate PR.** Review the removal diff+ against current main, preserving unrelated fixes. Merging, installing on a+ real user's machine, or publishing is a later action; no release is part of+ this assessment.++The current runnable intermediate state is the ordinary CLI plus independently+built optional libraries. Core safely refuses the old feature requests. The+experimental viewer, automatic learning, old companion CLI/MCP commands and dial+companion synchronization remain unavailable through this core build. Steps 2+and 4 have been performed at the module/build boundary; host integration in+step 3 and end-to-end feature continuity remain open. Normal Harness operation+cannot depend on their completion. A broad revert of earlier PRs is unsuitable+because unrelated later work shares their files.++## Data preservation and disable behavior++Preserve the developer's existing conversations, collection IDs, memories,+evidence, corrections and consent records. Prefer retaining their current paths+initially. If a move is necessary, stop the old writer, stage a copy, validate it+and retain the original for rollback. Do not build a customer data migration+framework for this unreleased feature. Do not grant new consent from an avatar+selection or duplicate a conversation merely to give the package a workspace.++Disabling Memory stops capture, inference, recall delivery and retries, revokes+active work, and leaves its saved data available for explicit management.+Disabling Companions stops its automation and presentation. Existing terminal+conversations follow normal save/stop behavior and remain recoverable. Neither+toggle changes authentication, ordinary terminal settings, normal notifications,+or other installed hooks. There must be no memory-specific message mutation,+background job, model call or probe when Memory is disabled.++Development installations can retain old native hook entries even after their+source is removed from the next CLI bundle. Clean up only entries owned by this+feature, preserve unrelated hooks, and test both enabled and disabled paths.++## Evidence required before merge++Choose the checks once under the [validation guide](../validation-and-release.md).+This crosses shared lifecycle and protocol surfaces and requires the full affected+component suites, relevant native integration checks and packaging checks.+Core and package tests, dependency-graph checks, standalone artifact checks and+private-terminal integration checks cover the extraction. Logs and the exact+validation scope belong in the ignored validation receipt and review summary.+No live application, real-device or private-conversation test has been performed+for the new integration, because that integration is not implemented yet.++| Required evidence | Acceptance |+| --- | --- |+| Core build and dependency audit | Neither feature implementation nor generated feature payload is reachable from the daemon bundle. Build and boot with the optional package absent. Test static, dynamic and generated dependencies. |+| Ordinary session regression checks | Start, discover, prompt, answer, cancel, stop, resume, reconnect and shutdown work with the optional package absent, off and enabled. Cover the shipped engine and client matrix. |+| Failure isolation | Kill, hang and overload the optional package and its memory worker; fill its queue or corrupt its own database. Normal terminal input, questions and daemon responsiveness remain within an agreed baseline tolerance. No unbounded respawn. |+| Identity and permission checks | Logout, account switching, session replacement and opt-out revoke work and discard stale results. Neither subsystem can self-assert a user, bypass a question approval or impersonate a remote machine. |+| Existing customer compatibility | Existing ordinary clients continue to work against the refactored daemon. Preserve encrypted transport, request correlation, saved sessions and user data. Unsupported optional capabilities fail only that capability. |+| Hook and device checks | Remove only owned native hook entries. Companion presentation cannot disrupt device status, questions, notifications, connection or brightness controls. |+| Feature continuity | One real supported conversation teaches a sourced memory used correctly in a later session. Companion switching retains the collection conversation and user-owned memories. |++The full refactor is complete when removing the companion package leaves a functional+daemon with no implementation dependency on either subsystem, and the package+delivers a companion that learns and remembers through the separate Memory API.+The current extraction establishes the build boundary; it does not yet establish+the second result. Passing module tests or moving files alone is insufficient.diff --git a/scripts/record-ci-validation.py b/scripts/record-ci-validation.pyindex 3fce8676f..7f44aca23 100644--- a/scripts/record-ci-validation.py+++ b/scripts/record-ci-validation.py@@ -25,7 +25,7 @@ TUI_JOBS = {"tui-test (ubuntu-latest, x86_64-unknown-linux-musl)", "tui-test (ubDESKTOP_PLATFORMS = {"ubuntu-22.04", "macos-15"}DESKTOP_JOBS = {"desktop-test-summary"} | {f"desktop-tests ({platform}, {index})" for platform in DESKTOP_PLATFORMS for index in range(1, 5)}SCOPES = {"cli": CLI_JOBS, "tui": TUI_JOBS, "backend": {"backend-desk"}, "desktop": DESKTOP_JOBS, "process": set()}-SCOPES["full"] = CLI_JOBS | TUI_JOBS | SCOPES["backend"] | DESKTOP_JOBS+SCOPES["full"] = CLI_JOBS | TUI_JOBS | SCOPES["backend"] | DESKTOP_JOBS | {"companion-subsystems"}# These are the source boundaries enforced by CI's sparse checkouts. Keep the# whole workflow/action and helper trees: a changed test, toolchain pin, cachediff --git a/scripts/tests/test_record_ci_validation.py b/scripts/tests/test_record_ci_validation.pyindex 241c96c47..244e220b3 100644--- a/scripts/tests/test_record_ci_validation.py+++ b/scripts/tests/test_record_ci_validation.py@@ -308,6 +308,11 @@ class EvidenceTests(unittest.TestCase):self.assertIn("desktop_summary", result)self.assertEqual(result["artifact"]["id"], 987)self.assertEqual(result["desktop_artifact"]["id"], 988)+ optional = next(job for job in self.jobs if job["name"] == "companion-subsystems")+ optional["conclusion"] = "skipped"+ with self.assertRaisesRegex(ValueError, "required job was skipped: companion-subsystems"):+ self.collect(scope="full")+ optional["conclusion"] = "success"self.artifacts.pop()with self.assertRaisesRegex(ValueError, "Desktop coverage summary"):self.collect(scope="full")