From 0cfe243cd60e4f740ff807031fe9a2f6c8e5dba2 Mon Sep 17 00:00:00 2001 From: Phototonic <35551999+Phototonic@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:23:30 +1100 Subject: [PATCH 1/5] test(windows): prove permission checks start no process --- tests/backend/windows-no-process.test.ts | 115 +++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 tests/backend/windows-no-process.test.ts diff --git a/tests/backend/windows-no-process.test.ts b/tests/backend/windows-no-process.test.ts new file mode 100644 index 0000000..1f932b3 --- /dev/null +++ b/tests/backend/windows-no-process.test.ts @@ -0,0 +1,115 @@ +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import cp from 'node:child_process'; +import {syncBuiltinESMExports} from 'node:module'; +import {pathToFileURL} from 'node:url'; + +/** Windows permission checks must never start a process. Portable proof: an + * isolated source copy is switched to the Windows code path (the platform flag and + * the drive-letter path syntax are the only substitutions) and every child-process + * entry point is spied on. Real NTFS behaviour is covered by the native Windows + * suite; this test only proves that nothing on these paths can spawn. */ +const spawnApis=['spawn','spawnSync','exec','execSync','execFile','execFileSync','fork'] as const; + +test('no product source starts a process or imports child_process',()=>{ + const offenders:string[]=[]; + const visit=(dir:string)=>{ + for(const entry of fs.readdirSync(dir,{withFileTypes:true})){ + const file=path.join(dir,entry.name); + if(entry.isDirectory())visit(file); + else if(/\.(?:ts|mjs|js)$/.test(entry.name)&&/(?:from\s*|import\s*\(\s*|require\s*\(\s*)['"](?:node:)?child_process['"]/.test(fs.readFileSync(file,'utf8')))offenders.push(file); + } + }; + for(const dir of ['plugin','service','setup','shared'])visit(path.resolve(dir)); + assert.deepEqual(offenders,[]); +}); + +test('Windows setup, service and companion paths start no process',{skip:process.platform==='win32'},async t=>{ + const root=fs.mkdtempSync('/tmp/opencode/windows-no-process-'); + const saved=new Map(); + const calls:string[]=[],phases:Record={}; + const phase=(name:string)=>{phases[name]=calls.length;calls.length=0;}; + let dispose:undefined|(()=>Promise),setup:any; + try{ + const source=path.join(root,'source'); + for(const dir of ['shared','setup','service','plugin'])fs.cpSync(path.resolve(dir),path.join(source,dir),{recursive:true}); + fs.symlinkSync(path.resolve('node_modules'),path.join(source,'node_modules')); + const platform=path.join(source,'shared/platform.ts'); + let text=fs.readFileSync(platform,'utf8'); + assert.ok(text.includes("export const windows = process.platform === 'win32';")); + text=text.replace("export const windows = process.platform === 'win32';",'export const windows = true;'); + const start=text.indexOf(" if (value.includes('\\0')",text.indexOf('function windowsPathsInner(')); + const end=text.indexOf(' let current = clean;',start); + assert.ok(start>0&&end>start); + // Disposable POSIX paths stand in for drive-absolute NTFS paths. + text=text.slice(0,start)+" if (!path.isAbsolute(value) || path.resolve(value) !== value) throw new PlatformError('path-unverified');\n const clean = value;\n"+text.slice(end); + fs.writeFileSync(platform,text); + + const env:NodeJS.ProcessEnv={PATH:process.env.PATH??'/usr/bin:/bin',HOME:`${root}/home`,XDG_CONFIG_HOME:`${root}/config`,XDG_DATA_HOME:`${root}/data`,SystemRoot:'C:\\Windows'}; + for(const dir of ['home','config/opencode','data/opencode','project'])fs.mkdirSync(`${root}/${dir}`,{recursive:true,mode:0o700}); + for(const [k,v]of Object.entries({...env,AGENT_PROGRESS_BINDING:undefined,OPENCODE_DB:undefined,OPENCODE_CONFIG_DIR:undefined})){saved.set(k,process.env[k]);if(v===undefined)delete process.env[k];else process.env[k]=v;} + + // A pre-change build answered through this fake helper; the fixed build must + // never reach it, so any call is recorded and fails the test below. + for(const api of spawnApis){ + t.mock.method(cp,api,((command:string,_args?:string[],options?:{input?:string})=>{ + calls.push(`${api}:${path.basename(String(command))}`); + if(api!=='spawnSync')throw new Error(`unexpected ${api}`); + const input=JSON.parse(String(options?.input??'{}')) as {paths:string[];create?:string[]}; + for(const dir of input.create??[])fs.mkdirSync(dir,{mode:0o700}); + return {pid:1,output:[],stdout:JSON.stringify(input.paths.map(()=>({owned:true,private:true,reparse:false,unsafeParent:false}))),stderr:'',status:0,signal:null}; + })as never); + } + syncBuiltinESMExports(); + + const {SetupController}=await import(pathToFileURL(path.join(source,'service/setup-controller.ts')).href); + const {default:plugin}=await import(pathToFileURL(path.join(source,'plugin/index.ts')).href); + const {managedBindingFile}=await import(pathToFileURL(path.join(source,'shared/managed-binding.ts')).href); + const {RELEASE}=await import(pathToFileURL(path.join(source,'shared/release.ts')).href); + const payload={plugin:'// Synthetic',guidance:'Synthetic',removal:'// removal',version:RELEASE}; + + // (b) Setup and service: inspection, configuration and status. + setup=new SetupController({env},()=>payload); + const review=setup.run('managed-inspect',{}).delivery.review; + setup.run('managed-configure',{confirmed:true,expected:review.expected}); + assert.equal(setup.status().configured,true); + phase('setup and service'); + + // (a) Companion: load, guard (report tool), tool hooks and status inspect. + const hooks=new Map>();let execute:any,inspect:any; + const hook=async(name:string,fn:any)=>{let set=hooks.get(name);if(!set)hooks.set(name,set=new Set());set.add(fn);return {dispose:async()=>{set.delete(fn);}};}; + const ctx:any={ + session:{hook,get:async({sessionID}:any)=>({id:sessionID,agent:'build',location:{directory:`${root}/project`},projectID:'project_fixture'})}, + skill:{transform:async(fn:any)=>fn({add:()=>{}})}, + tool:{hook,transform:async(fn:any)=>fn({namespace:()=>{},add:(tool:any)=>{execute=tool.execute;}}),list:async()=>[{id:'agent_progress_report',options:{codemode:false}}]}, + rpc:{register:async(_:unknown,impl:{inspect:()=>Promise})=>{inspect=impl.inspect;}},permission:{assert:async()=>{}}, + event:{subscribe:()=>(async function*(){})()}, + }; + const binding=managedBindingFile(env); + const bindingReads=()=>reads.filter(f=>f===binding).length; + const reads:string[]=[],lstat=fs.lstatSync; + t.mock.method(fs,'lstatSync',((file:any,...rest:any[])=>{reads.push(String(file));return (lstat as any)(file,...rest);})as typeof fs.lstatSync); + syncBuiltinESMExports(); + dispose=await plugin.setup(ctx); + for(const fn of [...(hooks.get('context')??[])])await fn({sessionID:'ses_fixture',system:[],tools:{agent_progress_report:{}}}); + phase('companion load'); + const loaded=bindingReads();assert.ok(loaded>0,'loading the companion read the binding'); + const receipt=JSON.parse((await execute({op:'start',plan:'P-win',oid:'start',rev:0,title:'Synthetic',items:[{id:'work',kind:'task',title:'Work'}]},{sessionID:'ses_fixture',agent:'build',messageID:'msg',id:'call'})).content); + assert.equal(receipt.rev,1,'a guarded report succeeds'); + phase('guarded report'); + const beforeHooks=bindingReads(); + for(const name of ['execute.before','execute.after']) + for(const fn of hooks.get(name)??[])try{await fn({sessionID:'ses_fixture',callID:'call_hook',tool:'bash',input:{},output:{}});}catch{/* only the hook's guard matters */} + assert.ok(bindingReads()>beforeHooks,'tool hooks re-checked the binding'); + phase('tool hooks'); + const status:any=await inspect();assert.equal(status.toolAvailable,true); + phase('status inspect'); + assert.deepEqual(phases,{'setup and service':0,'companion load':0,'guarded report':0,'tool hooks':0,'status inspect':0},'process calls per phase'); + }finally{ + await dispose?.();setup?.close();t.mock.restoreAll();syncBuiltinESMExports(); + for(const [k,v]of saved){if(v===undefined)delete process.env[k];else process.env[k]=v;} + fs.rmSync(root,{recursive:true,force:true}); + } +}); From 9e7e6d1fc6531c4fba66dcd88f3f33ab3953d964 Mon Sep 17 00:00:00 2001 From: Phototonic <35551999+Phototonic@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:46:55 +1100 Subject: [PATCH 2/5] fix(windows): stop starting PowerShell for permission checks --- .../windows-default-permissions/proposal.md | 41 ++ .../specs/managed-companion-delivery/spec.md | 29 ++ .../windows-setup-responsiveness/spec.md | 142 +++++++ .../windows-default-permissions/tasks.md | 9 + plugin/document.ts | 10 +- scripts/verify-package.ts | 6 +- service/request-worker.ts | 36 +- service/setup-controller.ts | 36 +- service/suggestions.ts | 5 +- setup/lifecycle.ts | 219 +++++------ setup/managed-inspection.ts | 162 ++++---- setup/managed-migration.ts | 231 ++++++------ setup/managed-observation.ts | 106 +++--- setup/managed-step-effects.ts | 202 +++++----- setup/managed-step-engine.ts | 67 ++-- setup/managed-step-journal.ts | 6 +- shared/binding.ts | 5 +- shared/cleanup.ts | 9 +- shared/managed-binding.ts | 86 ++--- shared/managed-steps.ts | 16 - shared/platform.ts | 351 +++--------------- shared/store.ts | 17 +- tests/backend/managed-fresh-store.test.ts | 22 +- tests/backend/managed-health.test.ts | 2 +- tests/backend/managed-http-worker.ts | 12 +- tests/backend/managed-inspection.test.ts | 17 +- tests/backend/managed-migration-steps.test.ts | 24 +- tests/backend/managed-migration.test.ts | 8 +- tests/backend/managed-request-worker.test.ts | 15 +- tests/backend/managed-step-contract.test.ts | 11 +- tests/backend/managed-step-engine.test.ts | 85 ++--- tests/backend/managed-step-http.test.ts | 112 ++---- tests/backend/managed-step-journal.test.ts | 2 - .../managed-step-prepare-budget.test.ts | 142 ------- tests/backend/managed-step-removal.test.ts | 42 +-- tests/backend/managed-step-upgrade.test.ts | 20 +- tests/backend/windows-platform.test.ts | 228 +++--------- tests/backend/windows-security-query.test.ts | 148 -------- .../backend/windows-service-observer.test.ts | 24 +- tests/backend/windows-service.test.ts | 62 +--- tests/backend/windows-spawn-budget.test.ts | 71 ---- tests/fixtures/windows-observer-probe.mjs | 6 +- tests/fixtures/windows-service-driver.ts | 53 +-- tests/fixtures/windows-service-observer.mjs | 66 +--- 44 files changed, 1074 insertions(+), 1889 deletions(-) create mode 100644 openspec/changes/windows-default-permissions/proposal.md create mode 100644 openspec/changes/windows-default-permissions/specs/managed-companion-delivery/spec.md create mode 100644 openspec/changes/windows-default-permissions/specs/windows-setup-responsiveness/spec.md create mode 100644 openspec/changes/windows-default-permissions/tasks.md delete mode 100644 tests/backend/managed-step-prepare-budget.test.ts delete mode 100644 tests/backend/windows-security-query.test.ts delete mode 100644 tests/backend/windows-spawn-budget.test.ts diff --git a/openspec/changes/windows-default-permissions/proposal.md b/openspec/changes/windows-default-permissions/proposal.md new file mode 100644 index 0000000..d79a807 --- /dev/null +++ b/openspec/changes/windows-default-permissions/proposal.md @@ -0,0 +1,41 @@ +# Windows relies on default per-user permissions + +## Why + +On native Windows, every ownership, privacy and ancestor check started Windows PowerShell synchronously (1 to 2.4 seconds each). The companion runs inside the OpenCode process, and loading it, guarding a report, running a tool hook and answering a status request each started one or more of them. That blocked OpenCode's event loop for tens of seconds, so its model catalogue request timed out and the model list stayed empty for the life of the process. + +The maintainer decided the checks are not worth that cost for a per-user extension: Windows state is protected by the user profile's default permissions, like other per-user applications. + +## What Changes + +- **Breaking for a stated check:** Windows no longer queries, applies or repairs ACLs, and no longer refuses a root for its owner, its permissions or the permissions of an ancestor. No process is started for any permission check, on any platform. +- Windows keeps the checks that need only plain filesystem calls: drive-qualified path syntax, canonical path, symbolic link and junction refusal, hard-link refusal for owned files, content-ownership markers, hashes and schema validation. Directories are created with default inheritance. +- Linux and macOS keep their uid and mode checks unchanged. +- The managed companion's load, guard, tool hooks and status inspection start no process. +- The per-request spawn ceiling, the helper cold-start budgets and the PowerShell mutex barrier are removed. The work and response deadlines, the writer slots and the fresh validation of every mutation stay. `accounting.securitySpawns` stays on the wire as a constant 0 so older and newer Setup frames keep working. +- Existing installs whose roots carry private ACLs keep working unchanged; their ACLs are never touched. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `managed-companion-delivery`: the binding's permission checks on Windows, and a new requirement that the companion starts no process. +- `windows-setup-responsiveness`: health, request bounds, step authority and native evidence no longer involve security helpers. + +## Impact + +Affected owners: `shared/platform.ts` and every caller of its Windows checks, the managed setup engine and its budget, the service request worker's writer fence, the Windows native and portable tests, and the setup, backend, contracts and compatibility guides. + +Protocol and schema stay at 2. No route, request field, store format or capability changes. Fixed diagnostic codes stay accepted so earlier journals and clients keep working, although these codes are no longer produced. + +## IN / OUT / Must NOT have + +IN: removing the Windows ACL queries everywhere; a test that proves no process starts on the companion, setup and service paths; guides and these specs. + +OUT: any replacement permission check; archiving this change, which the release pull request does; release notes and the changelog. + +The change MUST NOT alter Linux or macOS mode checks, and MUST NOT remove canonical-path, link, hard-link, marker, hash or schema validation. diff --git a/openspec/changes/windows-default-permissions/specs/managed-companion-delivery/spec.md b/openspec/changes/windows-default-permissions/specs/managed-companion-delivery/spec.md new file mode 100644 index 0000000..48993be --- /dev/null +++ b/openspec/changes/windows-default-permissions/specs/managed-companion-delivery/spec.md @@ -0,0 +1,29 @@ +## MODIFIED Requirements + +### Requirement: Single private verified binding + +Service and managed companion SHALL discover the same single descriptor in a dedicated product-owned subfolder of the canonical OpenCode data root derived from XDG data/HOME. They SHALL keep marker, canonical-path, binding and Store/source validation, and private modes on Linux and macOS. Windows relies on the user profile's default permissions: no ACL is queried, applied or repaired. They MUST NOT scan roots, fall back from invalid state or auto-adopt legacy selectors. + +#### Scenario: Service environment omits state root +- **WHEN** the service lacks `XDG_STATE_HOME` and an explicit binding variable but shares the supported XDG data root with managed OpenCode +- **THEN** both resolve the same owned descriptor and verify the same store/source without duplicate descriptor copies + +#### Scenario: Missing selection +- **WHEN** the descriptor is absent and setup or a dormant companion is inspected +- **THEN** the state is unconfigured and no directory, ownership marker, descriptor or store is automatically created or adopted + +#### Scenario: Invalid selection +- **WHEN** the selected directory, marker, descriptor, source scope or Store is invalid, modified, aliased, foreign, unsupported or, on Linux and macOS, non-private +- **THEN** capture fails closed and existing bytes remain intact +- **AND** a present invalid selection is not treated as absence or permission to try another root + +## ADDED Requirements + +### Requirement: Companion checks start no process + +The managed companion's load, guard, tool-hook and status paths SHALL start no child process on any platform. Re-reading the binding uses plain filesystem calls only. + +#### Scenario: Windows companion in the host +- **WHEN** the companion loads on native Windows, guards a report, runs a tool hook or answers a status inspection +- **THEN** no child process is started, so the host event loop is never blocked waiting on one +- **AND** a changed or invalid binding still retires the companion and refuses the call diff --git a/openspec/changes/windows-default-permissions/specs/windows-setup-responsiveness/spec.md b/openspec/changes/windows-default-permissions/specs/windows-setup-responsiveness/spec.md new file mode 100644 index 0000000..04f37f0 --- /dev/null +++ b/openspec/changes/windows-default-permissions/specs/windows-setup-responsiveness/spec.md @@ -0,0 +1,142 @@ +## MODIFIED Requirements + +### Requirement: Cheap honest health and nonblocking admission + +Authenticated health SHALL return a cheap last-observed liveness/admission snapshot without filesystem validation or legacy discovery. Starting or unverified state MUST NOT be presented as fresh Store authority. + +#### Scenario: Admission and worker boundaries +- **WHEN** migration, fresh configuration or data access needs admission +- **THEN** required fresh admission SHALL be obtained on demand without blocking the health-serving event loop +- **AND** fresh inspection, effects, controls and status SHALL reuse the existing request-driven worker boundary, not an autonomous job + +#### Scenario: Cold legacy upgrade +- **WHEN** the service starts with a released legacy installation and no managed selection +- **THEN** health responds without opening/adopting the legacy store or starting any process +- **AND** Setup and background composer access can request admission rather than treating starting as permanently unavailable + +#### Scenario: Slow security work is active +- **WHEN** a migration, fresh-setup or admission request is running +- **THEN** a concurrent authenticated health request remains responsive and honest +- **AND** no permission check starts a process, so none can block that request + +#### Scenario: No fresh store yet +- **WHEN** a fresh operation has prepared its journal but has not created its store +- **THEN** status shows the durable pending operation with unknown capture and no configured binding +- **AND** observation neither creates storage nor treats planned absence as a corrupt existing database + +### Requirement: Bounded separate setup requests + +Each migration or negotiated fresh-setup step SHALL be a separate request driven by Setup, bounded by a 17-second work deadline and an 18-second response deadline below the host's 20-second limit. No step starts a process; deadline exhaustion SHALL be explicit rather than weakening checks. + +#### Scenario: Request deadline allocation +- **WHEN** a request is admitted +- **THEN** work and response deadlines SHALL remain 17 and 18 seconds respectively, and no step starts a process +- **AND** inspection/status SHALL be trimmed or continued to meet the same deadlines +- **AND** fresh store-directory creation, database initialization and source registration MUST NOT be hidden inside an already full preparation request + +#### Scenario: A phase exceeds the request budget +- **WHEN** inspection, creation, record publication, removal or final status cannot fit after its fresh validation +- **THEN** the work is split at a safe durable boundary or refused without skipping required validation +- **AND** Setup receives bounded progress and explicitly drives the next request rather than one long background operation + +#### Scenario: Helper exceeds the planning assumption +- **WHEN** a request runs past its work deadline, for example on a slow disk +- **THEN** the request stops admitting further work and reports pending, uncertain or failed effects honestly +- **AND** no unbounded retry or misleading rollback/success claim occurs + +#### Scenario: Supported migration on a slow machine +- **WHEN** the supported legacy fixture is inspected and migrated +- **THEN** the full switch completes successfully through separate requests below the 20-second host limit with no process started +- **AND** repeated bounded refusals are not accepted as successful migration + +#### Scenario: Fresh setup on a slow machine +- **WHEN** a supported Windows fixture has no legacy install, managed journal or store +- **THEN** reviewed fresh setup completes with a valid selected Store/source and verified capture through requests below twenty seconds with no process started +- **AND** repeated bounded refusals do not count as successful setup +- **AND** persistent deadline exhaustion is a bounded recovery refusal, not a guarantee of eventual completion + +### Requirement: Fresh authority for every mutation step + +Every step SHALL freshly validate its current target, consent/sequence, canonical path, links, relevant files and Store/source identity before its mutation. Previous discoveries and durable progress MUST NOT replace current checks. Windows applies no ACL or ownership query. + +#### Scenario: Fresh creation authority +- **WHEN** a step creates an object +- **THEN** full legacy ownership-of-content and existing removal safeguards SHALL remain, and nothing is cached across requests or mutations +- **AND** fresh creation SHALL validate absence and frozen proposed identity where objects do not yet exist, and freshly validate resulting objects before further effects +- **AND** proposed identities MUST NOT authorize ordinary selected-binding or companion admission + +#### Scenario: State changes between steps +- **WHEN** a path object, manifest, source/store, reviewed selection or operation sequence changes +- **THEN** the next affected mutation refuses before acting on stale authority +- **AND** no foreign bytes, history or existing locks are removed to force progress + +#### Scenario: Object appears at a reviewed absent target +- **WHEN** a directory, database, sidecar or selector appears without this operation's sufficient creation evidence +- **THEN** the next effect refuses rather than adopting, replacing or initializing that object +- **AND** a copied journal or matching path alone is not authority + +### Requirement: Precise accessible progress and compatibility refusal + +Setup SHALL show actual step progress, pending/paused state, fixed last-action stage/code, capture observation and recovery actions in English, Russian and Simplified Chinese at phone width with accessible focus/announcements. Fresh progress SHALL reflect its frozen plan and creation/reconnection consequences, not the fixed legacy removal-stage count. + +#### Scenario: Fresh capability negotiation +- **WHEN** a client negotiates fresh setup +- **THEN** the service SHALL advertise fresh support independently as `managedFreshSteps: 1` in authenticated health and Setup delivery +- **AND** fresh requests SHALL use version 2 on the existing step route; version-1 migration shapes and capability SHALL remain unchanged +- **AND** old single-request migration input and old Windows inspect/configure input SHALL receive a fast non-mutating compatibility refusal +- **AND** new UI SHALL negotiate fresh support rather than fall back to an unsafe long request + +#### Scenario: Older UI or service +- **WHEN** an older UI sends the old migration input to the new service +- **THEN** the old URL returns HTTP 409 with managed-action-required before migration work, using the existing update-together guidance +- **AND** the new UI sends no step mutation to an older service that lacks the corresponding capability + +#### Scenario: Failure or retired context +- **WHEN** a step fails or the host/source changes while a response is outstanding +- **THEN** allowlisted diagnostics remain visible without private/raw error content and retired replies cannot resume the driver +- **AND** no invented percentage, completion claim or additional polling loop replaces actual step results + +#### Scenario: Older fresh client on Windows +- **WHEN** an authenticated caller posts old managed-inspect or managed-configure input to the new Windows service +- **THEN** it receives HTTP 409 with exactly the existing managed-action-required error object +- **AND** no worker or product write occurs + +#### Scenario: Non-Windows compatibility +- **WHEN** an older caller uses the old fresh routes on Linux or macOS with no legacy discovery or journal +- **THEN** the existing nonce-bound confirmation and writer-fenced fresh path remains supported +- **AND** any journal or legacy/conflicting state retains its existing no-write refusal + +#### Scenario: Fresh capability absent +- **WHEN** the new UI needs fresh setup but the service does not advertise managedFreshSteps version 1 +- **THEN** it shows update-together guidance and sends neither fresh mutation nor automatic old-route fallback +- **AND** independently supported migration and capture controls are not disabled merely by this missing capability + +#### Scenario: Reopen fresh progress +- **WHEN** Setup observes a format-3 operation through delivery.freshProgress +- **THEN** the existing driver/card offers the explicit appropriate recovery action and displays its actual plan +- **AND** migrationProgress retains its version-1 shape for older consumers + +### Requirement: Native Windows responsiveness evidence + +Acceptance SHALL include native Windows released-legacy migration and fresh setup over authenticated HTTP, an independent count of process launches that must be zero, sanitized per-step traces and health checks. Requests SHALL take at most 8 seconds, providing more than twofold margin to the host timeout. + +#### Scenario: Evidence fidelity +- **WHEN** acceptance results are recorded +- **THEN** native effect/recovery evidence and browser screenshots SHALL accompany logic checks +- **AND** portable tests SHALL spy on every child-process entry point and prove none is called, but MUST NOT be described as native Windows measurements + +#### Scenario: CI verifies the built candidate +- **WHEN** the final built service migrates an isolated released 1.1.1 installation under a non-admin Windows test principal +- **THEN** inspect, step, failure, retry and status paths start no process and meet the time bound with retained identities/history and honest capture state +- **AND** traces contain only bounded stage/code/timing/count/state facts, never account names, paths, credentials or raw logs + +#### Scenario: CI verifies empty-store setup +- **WHEN** the built candidate starts with only isolated config/data roots and no legacy, managed directory, store or journal +- **THEN** fresh journeys complete within the request bound with no process started +- **AND** health starts no process and responds within the existing 1.25-second native health bound +- **AND** representative restart, dropped-reply, pause/resume, retained reconnection and over-budget cases assert actual durable effects + +#### Scenario: Rendered fresh Setup +- **WHEN** current-source guests run the fresh journey in the existing rendered browser harness +- **THEN** screenshots and interaction checks cover review, running creation, paused off/unknown, failure/recovery and completion in EN/RU/zh-CN at phone width +- **AND** keyboard acknowledgement/confirmation, focus return and context retirement remain operable without private fixture data diff --git a/openspec/changes/windows-default-permissions/tasks.md b/openspec/changes/windows-default-permissions/tasks.md new file mode 100644 index 0000000..cf3df66 --- /dev/null +++ b/openspec/changes/windows-default-permissions/tasks.md @@ -0,0 +1,9 @@ +# Tasks + +## 1. Remove the Windows permission queries + +- [x] 1.1 Add a regression test that fails first: a simulated Windows path, with every child-process entry point spied on, starts no process while setup, the service and the companion load, guard, run a tool hook and answer a status inspection. +- [x] 1.2 Replace the Windows permission queries in `shared/platform.ts` with plain filesystem checks, drop the scope, cache, spawn budget and mutex barrier, and keep the work deadline and writer fence. +- [x] 1.3 Remove the wrappers and the now-dead error paths in setup, service and the companion. +- [x] 1.4 Delete the tests of the removed machinery and rewrite the portable and native tests that counted launches so they assert none. +- [x] 1.5 Update the setup, backend, contracts and compatibility guides, the step protocol notes and the contributing guide. diff --git a/plugin/document.ts b/plugin/document.ts index 9febd9a..5d52cf1 100644 --- a/plugin/document.ts +++ b/plugin/document.ts @@ -2,7 +2,7 @@ import { constants, realpathSync, openSync, closeSync, fstatSync, lstatSync, rea import path from 'node:path'; import { LIMITS, type Capture, type DocumentRef } from '../shared/progress.ts'; import { digest } from '../shared/store.ts'; -import { windowsDocumentPath, platformSecurityScope } from '../shared/platform.ts'; +import { windowsPath } from '../shared/platform.ts'; import type { BigIntStats } from 'node:fs'; /** Caller authorization is mandatory and happens before any document-byte read. */ @@ -59,23 +59,23 @@ async function captureWindowsDocument(reference:string,directory:string,authoriz await authorize(requested); // Do not conceal traversal, ADS, reserved names or device paths by resolve(). const raw=path.isAbsolute(reference)?reference:directory+'\\'+reference; - const canonicalPath=platformSecurityScope(()=>windowsDocumentPath(raw,true)); + const canonicalPath=(windowsPath(raw,true)); await authorize(canonicalPath); if(previous?.canonicalPath&&canonicalPath!==previous.canonicalPath)return result('moved',canonicalPath); const bound=lstatSync(canonicalPath,{bigint:true}); - if(platformSecurityScope(()=>windowsDocumentPath(raw))!==canonicalPath)return result('changed-during-read'); + if((windowsPath(raw))!==canonicalPath)return result('changed-during-read'); if(!bound.isFile()||bound.isSymbolicLink())return result('non-text',canonicalPath); const parents=ancestors(canonicalPath); if(bound.size>BigInt(LIMITS.documentBytes))return result('oversized',canonicalPath); fd=openSync(canonicalPath,constants.O_RDONLY); const before=fstatSync(fd,{bigint:true});const current=lstatSync(canonicalPath,{bigint:true}); - if(!before.isFile()||before.ino===0n||!unchanged(bound,before)||!unchanged(before,current)||platformSecurityScope(()=>windowsDocumentPath(raw))!==canonicalPath)return result('changed-during-read'); + if(!before.isFile()||before.ino===0n||!unchanged(bound,before)||!unchanged(before,current)||(windowsPath(raw))!==canonicalPath)return result('changed-during-read'); for(const[p,stat]of parents)if(!sameFile(stat,lstatSync(p,{bigint:true})))return result('changed-during-read'); const bytes=Buffer.alloc(LIMITS.documentBytes+1);let offset=0; while(offsetLIMITS.documentBytes)return result('oversized',canonicalPath); const after=fstatSync(fd,{bigint:true}),still=lstatSync(canonicalPath,{bigint:true}); - if(!still.isFile()||still.isSymbolicLink()||!unchanged(before,after)||!unchanged(after,still)||platformSecurityScope(()=>windowsDocumentPath(raw))!==canonicalPath)return result('changed-during-read'); + if(!still.isFile()||still.isSymbolicLink()||!unchanged(before,after)||!unchanged(after,still)||(windowsPath(raw))!==canonicalPath)return result('changed-during-read'); for(const[p,stat]of parents)if(!sameFile(stat,lstatSync(p,{bigint:true})))return result('changed-during-read'); let text:string;try{text=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(bytes.subarray(0,offset));}catch{return result('non-text',canonicalPath);} if(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(text))return result('non-text',canonicalPath); diff --git a/scripts/verify-package.ts b/scripts/verify-package.ts index fea94f3..bb21ebf 100644 --- a/scripts/verify-package.ts +++ b/scripts/verify-package.ts @@ -49,8 +49,8 @@ async function verifyPackage() { const reservation=createServer();reservation.listen(0,'127.0.0.1');await once(reservation,'listening');const port=(reservation.address() as {port:number}).port;await new Promise(r=>reservation.close(()=>r())); service=spawn(process.execPath,[path.join(folder,'build/service/main.js')],{env:{...fixtureEnv,OPENCHAMBER_SERVICE_PORT:String(port),OPENCHAMBER_SERVICE_TOKEN:'package-fixture-only'},cwd:root,stdio:'ignore'}); const request=async(route:string,body?:unknown,method:'GET'|'POST'=body===undefined?'GET':'POST')=>{ - // Undelayed portable package smoke budget, not the host's 20s limit or - // native slow-PowerShell certification (covered by the Windows suite). + // Portable package smoke budget, not the host's 20s limit or native + // Windows certification (covered by the Windows suite). const r=await fetch(`http://127.0.0.1:${port}${route}`,{method,headers:{authorization:'Bearer package-fixture-only','content-type':'application/json'},...(body===undefined?{}:{body:JSON.stringify(body)}),signal:AbortSignal.timeout(8000)}); lastHttpStatus=r.status;const value=await r.clone().json(),code=typeof value.error==='string'?value.error:value.error?.code; lastHttpCode=[...MANAGED_ACTION_CODES,...MANAGED_STEP_CODES,'managed-action-required','invalid','not-found','body-not-allowed'].includes(code)?code:code?'unrecognized-code':null; @@ -61,7 +61,7 @@ async function verifyPackage() { const action=async(name:string,storeRoot?:string)=>{const r=await request('/v1/setup/managed-inspect',storeRoot?{storeRoot}:{});assert.equal(r.status,200);const reviewed=await r.json();return request(`/v1/setup/${name}`,{...(storeRoot?{storeRoot}:{}),confirmed:true,expected:reviewed.delivery.review.expected});}; const step=async(body:ManagedStepRequest)=>{ const response=await request('/v1/setup/managed-step',body),value=await response.json() as ManagedStepResponse; - assert.equal(value.version,1);assert.ok(value.accounting.securitySpawns<=6);assert.equal(response.status===200,value.error===null); + assert.equal(value.version,1);assert.equal(value.accounting.securitySpawns,0);assert.equal(response.status===200,value.error===null); return {status:response.status,value}; }; const inspectMigration=async()=>{ diff --git a/service/request-worker.ts b/service/request-worker.ts index f930947..47975cc 100644 --- a/service/request-worker.ts +++ b/service/request-worker.ts @@ -1,9 +1,8 @@ import {Worker,isMainThread,parentPort,workerData} from 'node:worker_threads'; import path from 'node:path'; -import {type Socket} from 'node:net'; -import {randomBytes,randomUUID,timingSafeEqual} from 'node:crypto'; +import {randomUUID} from 'node:crypto'; import {SetupController} from './setup-controller.ts'; -import {PlatformRequestBudget,withPlatformRequestBudget,writerTargetPort} from '../shared/platform.ts'; +import {PlatformRequestBudget,withPlatformRequestBudget} from '../shared/platform.ts'; import {MANAGED_STEP_LIMITS,MANAGED_FRESH_INSPECTION_STEPS,managedSetupStepRequest,type ManagedStepAccounting,type ManagedSetupStepResponse,type ManagedSetupStepRequest,type ManagedSetupStepProgress,type ManagedStepDiagnostic,type ManagedFreshStepDiagnostic,type ManagedInspection,type ManagedFreshInspection} from '../shared/managed-steps.ts'; import {type ManagedSetupAction} from '../shared/progress.ts'; import {canonical,digest} from '../shared/store.ts'; @@ -36,8 +35,7 @@ interface SetupWorkerInput { payload:Payload|undefined; request:SetupWorkerRequest; startedAt:bigint; - counter:SharedArrayBuffer; - fence:{port:number;nonce:string;targets:string[]}; + fence:{targets:string[]}; inspection?:InspectionSession; journal?:ManagedSetupStepJournal; } @@ -80,7 +78,7 @@ function stepResponse(version:1|2,fields:{disposition:ManagedSetupStepResponse[' export function runSetupRequestWorker():void { if(!isSetupRequestWorker()||!parentPort)throw new Error('managed-step-unsupported'); const input=workerData as SetupWorkerInput; - const budget=new PlatformRequestBudget(input.startedAt,input.counter,input.fence); + const budget=new PlatformRequestBudget(input.startedAt,input.fence); let setup:SetupController|undefined; let value:unknown,code:string|undefined; let inspection:InspectionSession|undefined; @@ -170,8 +168,7 @@ export function runSetupRequestWorker():void { /** One run at a time (identical payload-free status reads may share its reply), * no autonomous continuation and no terminate-on-timeout. * A timeout settles the reply, NOT the worker: busy remains true until exit. - * The TCP writer slot is retained over that whole interval. Windows security - * children also cross the account-scoped mutex/nonce barrier in platform.ts. */ + * The TCP writer slot is retained over that whole interval. */ export class SetupRequestWorker { private active=false; private statusRun?:{context:string;promise:Promise}; @@ -215,26 +212,9 @@ export class SetupRequestWorker { const timer=setTimeout(()=>finish(refused('managed-step-deadline')),remaining); // Separate scope and Store slots also fence distinct discovery roots // sharing capture control. Routing claims are checked by the fresh owner. - const fence={port:writerTargetPort(targets[0]!),nonce:randomBytes(32).toString('hex'),targets}; - const expected=Buffer.from(fence.nonce+'\n'); - const sockets=new Set(); - const connection=(socket:Socket)=>{ - sockets.add(socket);socket.once('close',()=>sockets.delete(socket)); - socket.setTimeout(1000,()=>socket.destroy()); - let bytes=Buffer.alloc(0); - socket.on('error',()=>socket.destroy()); - socket.on('data',chunk=>{ - bytes=Buffer.concat([bytes,chunk]); - if(bytes.length>expected.length){socket.destroy();return;} - if(bytes.length!==expected.length)return; - let admitted=false; - try{budget.require();admitted=timingSafeEqual(bytes,expected);}catch{/* Expired workers receive no new effect admission. */} - socket.end(admitted?'ok\n':'no\n'); - }); - }; - acquireWriterSlots(targets,connection,()=>{result=refused('managed-step-unsettled');finish(result);}).then(unlock=>{ + const fence={targets}; + acquireWriterSlots(targets,undefined,()=>{result=refused('managed-step-unsettled');finish(result);}).then(unlock=>{ const release=(reply:SetupWorkerResult)=>{ - for(const socket of sockets)socket.destroy(); void unlock().then(()=>{this.active=false;finish(reply);}).catch(()=>{ this.active=false;this.inspection=undefined;this.journal=undefined; finish(refused('managed-step-unsettled')); @@ -244,7 +224,7 @@ export class SetupRequestWorker { try { budget.require(); worker=new Worker(this.entry,{workerData:{kind:'agent-progress-setup-request',requestId,env,payload,request, - startedAt,counter:budget.counter.buffer,fence,...(saved&&consumesInspection?{inspection:saved}:{}),...(journal?{journal}:{})} satisfies SetupWorkerInput}); + startedAt,fence,...(saved&&consumesInspection?{inspection:saved}:{}),...(journal?{journal}:{})} satisfies SetupWorkerInput}); } catch(error) {release(refused(diagnostic(error)));return;} worker.on('message',(message:SetupWorkerMessage)=>{ // A received message alone is not worker settlement. Wait for exit. diff --git a/service/setup-controller.ts b/service/setup-controller.ts index e87c329..3561bc5 100644 --- a/service/setup-controller.ts +++ b/service/setup-controller.ts @@ -10,7 +10,7 @@ import { activationFingerprint } from '../shared/activation.ts'; import { lifecycle, normalizeTargets, SetupError, type Targets, type Payload, type Action } from '../setup/lifecycle.ts'; import {legacyMigration,readMigration,writeMigration,sameMigrationTarget,removalRecorded,migrationError,type MigrationRecord} from '../setup/managed-migration.ts'; import { setupSuggestions, type HostPathContext } from './suggestions.ts'; -import { windows, windowsPath, privatePaths, privateDirectory, isOwned, platformSecurityScope, syncFile, syncDirectory, PlatformError, platformErrorCode, sameWindowsDirectory, sameWindowsObject,writerTarget,requirePlatformStoreFence } from '../shared/platform.ts'; +import { windows, windowsPath, privatePaths, privateDirectory, isOwned, syncFile, syncDirectory, PlatformError, platformErrorCode, sameWindowsDirectory, sameWindowsObject,writerTarget,requirePlatformStoreFence } from '../shared/platform.ts'; import {SetupRequestWorker,withSetupWriter,type SetupWorkerRequest,type SetupWorkerHealth} from './request-worker.ts'; import {setupWriterTargets} from './writer-fence.ts'; @@ -30,7 +30,6 @@ function refuseMigrationPresence(configRoot:string,file:string,action:'inspect'| export class SetupController { private store?: Store; private binding?: Binding; private error: Code = 'binding'; private expectedDescriptor: string | null = null; private canPersist = true; - private securityUnavailable = false; private fixedError?: PlatformError | ManagedBindingError; private activation = 'unknown'; private readonly readonlyPayload: () => Payload; @@ -74,7 +73,7 @@ export class SetupController { this.workerEntry=workerEntry; this.readonlyPayload=readonlyPayload;this.suggestionContext=suggestionContext; if(typeof privateFile !== 'string') { - // Listening and host liveness must not wait on cold security helpers. No + // Listening and host liveness must not wait on filesystem validation. No // background admission: real setup/data operations validate synchronously. this.managedEnv={...privateFile.env};this.bindingFile=''; return; @@ -98,7 +97,7 @@ export class SetupController { health() { if(this.workerHealth)return {...this.workerHealth,diagnostics:[...this.workerHealth.diagnostics]}; const diagnostics=this.managedDiagnostic?[this.managedDiagnostic]:this.store?[]: - this.securityUnavailable?['windows-security-unavailable']:this.binding||!this.canPersist?[this.fixedError?.code??this.error]:[]; + this.binding||!this.canPersist?[this.fixedError?.code??this.error]:[]; return {state:!this.checked?'starting':this.store?'ready':diagnostics.length?'refused':'unconfigured', ready:!!this.store,sqlite:!!this.store,diagnostics,subagentRuns:!!this.store&&this.runsAvailable}; } @@ -109,13 +108,13 @@ export class SetupController { // Validate optional run storage before admitting the store, not later in // /health capability discovery where a schema refusal fails host readiness. try{verifyStore(next,b);const runs=next.subagentRunStorage();this.runsAvailable=runs==='current'||runs==='previous';next.bindReads(b.source.id,b.source.verified);}catch(e){next.close();throw e;} - this.store?.close();this.store=next;this.binding=b;this.securityUnavailable=false;this.fixedError=undefined; + this.store?.close();this.store=next;this.binding=b;this.fixedError=undefined; } - private recordError(e:unknown) {this.error=storageError(e).code;this.fixedError=e instanceof ManagedBindingError||platformErrorCode(e)?e as ManagedBindingError|PlatformError:undefined;this.securityUnavailable=e instanceof PlatformError&&e.code==='windows-security-unavailable';} + private recordError(e:unknown) {this.error=storageError(e).code;this.fixedError=e instanceof ManagedBindingError||platformErrorCode(e)?e as ManagedBindingError|PlatformError:undefined;} private refresh() { this.workerHealth=undefined; - platformSecurityScope(()=>this.refreshInner()); - // Once per admitted package generation, outside read-only security scopes. + this.refreshInner(); + // Once per admitted package generation, outside read-only observation. // Failure remains an unknown expectation, not an authorization or a retry loop. if(this.managedEnv&&this.store&&this.binding&&this.expectationPending){ this.expectationPending=false; @@ -149,9 +148,9 @@ export class SetupController { const targets=this.targets(); if(!targets){ const suggestions=includeSuggestions?setupSuggestions(this.suggestionContext):undefined; - return {configured:false,verified:false,installed:false,captureEnabled:null,targets:null,version:null,activation:'unknown',separateLifecycle:true,historyRetained:true,diagnostics:[...(!this.canPersist?['service-binding-collision']:[]),...(this.securityUnavailable?['windows-security-unavailable']:[]),this.error==='binding'?'targets-unverified':this.error],...(suggestions?{suggestions}:{})}; + return {configured:false,verified:false,installed:false,captureEnabled:null,targets:null,version:null,activation:'unknown',separateLifecycle:true,historyRetained:true,diagnostics:[...(!this.canPersist?['service-binding-collision']:[]),this.error==='binding'?'targets-unverified':this.error],...(suggestions?{suggestions}:{})}; } - const base:SetupRead={configured:true,verified:this.binding!.source.verified,installed:false,captureEnabled:this.store?this.store.list({limit:1}).captureEnabled:null,targets:{configRoot:targets.configRoot,dataRoot:targets.dataRoot,storeRoot:targets.storeRoot},version:null,activation:this.activation,separateLifecycle:true,historyRetained:true,diagnostics:this.store?[]:[...(this.securityUnavailable?['windows-security-unavailable']:[]),this.error]}; + const base:SetupRead={configured:true,verified:this.binding!.source.verified,installed:false,captureEnabled:this.store?this.store.list({limit:1}).captureEnabled:null,targets:{configRoot:targets.configRoot,dataRoot:targets.dataRoot,storeRoot:targets.storeRoot},version:null,activation:this.activation,separateLifecycle:true,historyRetained:true,diagnostics:this.store?[]:[this.error]}; if(this.store)base.reportingIdentity={storeId:this.binding!.storeId,sourceId:this.binding!.source.id,verified:this.binding!.source.verified}; let payload:Payload|undefined; if(this.store&&base.verified)try{payload=this.readonlyPayload();}catch{/* Missing bundled bytes make no update claim. */} @@ -187,7 +186,7 @@ export class SetupController { if(!targets.confirmed)throw new SetupError('confirmation-required'); requirePlatformStoreFence(path.join(targets.storeRoot,'progress.sqlite')); if(['disable','enable','remove-capture'].includes(action)) { - const current=this.targets();if(!current||!(windows?platformSecurityScope(()=>sameWindowsDirectory(current.configRoot,targets.configRoot)&&sameWindowsDirectory(current.dataRoot,targets.dataRoot)&&sameWindowsDirectory(current.storeRoot,targets.storeRoot)):current.configRoot===targets.configRoot&¤t.dataRoot===targets.dataRoot&¤t.storeRoot===targets.storeRoot))throw new SetupError('ownership-invalid'); + const current=this.targets();if(!current||!(windows?(sameWindowsDirectory(current.configRoot,targets.configRoot)&&sameWindowsDirectory(current.dataRoot,targets.dataRoot)&&sameWindowsDirectory(current.storeRoot,targets.storeRoot)):current.configRoot===targets.configRoot&¤t.dataRoot===targets.dataRoot&¤t.storeRoot===targets.storeRoot))throw new SetupError('ownership-invalid'); } if(action==='install'||action==='update'){ this.validateDescriptor(); @@ -222,7 +221,7 @@ export class SetupController { } /** Compatibility HTTP path for fresh configuration only. The caller holds the * same scope/Store writer slots as step workers for the entire synchronous - * operation. Keep the existing review nonce and legacy security timeouts. */ + * operation. Keep the existing review nonce. */ runFreshManaged(action:'managed-inspect'|'managed-configure',body:unknown):SetupRead { if(!this.managedEnv)throw new SetupError('managed-service-required'); const result=this.runManaged(action,body,true); @@ -247,7 +246,7 @@ export class SetupController { writeManagedExpectation(b,{format:1,storeId:b.storeId,sourceId:b.source.id,installId:b.installId,version:payload.version,fingerprint}); } private managedMigration(_targets?:Targets):ManagedMigrationState { - return platformSecurityScope(()=>this.managedMigrationInner().state); + return this.managedMigrationInner().state; } private managedMigrationInner():{state:ManagedMigrationState;captureEnabled:boolean|null} { this.migrationDiagnostic=undefined; @@ -276,7 +275,7 @@ export class SetupController { } private managedStatus():SetupRead { this.refresh(); - return platformSecurityScope(()=>this.managedStatusInner()); + return this.managedStatusInner(); } private managedStatusInner():SetupRead { const b=this.binding,targets=this.targets(),migration=this.managedMigrationInner(); @@ -309,7 +308,6 @@ export class SetupController { } private managedControlCandidate(storeRoot?:string): {review:ManagedReview;binding:Binding;targets:Targets} { this.refresh(); - if(this.securityUnavailable)throw new PlatformError('windows-security-unavailable'); if(!this.store||!this.binding)throw this.fixedError??new ProgressError(this.error); const b=this.binding,targets=this.targets()!; if(!b.source.verified)throw new ProgressError('source-unverified'); @@ -322,7 +320,7 @@ export class SetupController { private managedFullCandidate(storeRoot?:string,freshOnly?:'inspect'|'configure'): ManagedCandidate { this.checked=true; if(freshOnly){ - // A non-authoritative local presence hint avoids cold PowerShell just to + // A non-authoritative local presence hint avoids a full validation just to // refuse. Absence/read failure grants nothing: the full fresh validation // and canonical presence check below still run before review or effects. const env=this.managedEnv!,home=env.HOME??homedir(); @@ -333,7 +331,7 @@ export class SetupController { catch(e){if(e instanceof SetupError)throw e; /* The validated owner diagnoses unreadable/invalid paths. */} } } - return platformSecurityScope(()=>this.managedFullCandidateInner(storeRoot,freshOnly)); + return this.managedFullCandidateInner(storeRoot,freshOnly); } private managedFullCandidateInner(storeRoot?:string,freshOnly?:'inspect'|'configure'): ManagedCandidate { const env=this.managedEnv!,roots=managedSourceRoots(env),file=managedBindingFile(env); @@ -426,7 +424,7 @@ export class SetupController { private migrate(candidate:ReturnType):SetupRead { const env=this.managedEnv!; // The candidate was fully inspected in this synchronous request. The lock - // boundary below obtains a new candidate, with a fresh security scope. + // boundary below obtains a new candidate. const {record:prior,legacy}=candidate; if(prior?.phase==='complete'&&legacy)throw new SetupError('managed-migration-conflict'); if(prior?.phase==='complete'&&!legacy)return {...this.managedStatus(),action:'managed-migrate'}; @@ -465,7 +463,7 @@ export class SetupController { } } private validateDescriptor() { - try{return platformSecurityScope(()=>this.validateDescriptorInner());}catch(e){throw e instanceof PlatformError?new SetupError(e.code):e;} + try{return this.validateDescriptorInner();}catch(e){throw e instanceof PlatformError?new SetupError(e.code):e;} } private validateDescriptorInner() { if(!this.canPersist)throw new SetupError('service-binding-collision'); diff --git a/service/suggestions.ts b/service/suggestions.ts index 1714d70..4fcca14 100644 --- a/service/suggestions.ts +++ b/service/suggestions.ts @@ -1,7 +1,7 @@ import { lstatSync,realpathSync } from 'node:fs'; import path from 'node:path'; import { homedir } from 'node:os'; -import { windowsPath, platformSecurityScope, isOwned, sameWindowsDirectory } from '../shared/platform.ts'; +import { windowsPath, isOwned, sameWindowsDirectory } from '../shared/platform.ts'; import type { SetupSuggestions,Suggestion } from '../shared/progress.ts'; /** Trusted service-host inputs only; never supplied by an HTTP caller. */ @@ -13,9 +13,6 @@ export interface HostPathContext { /** Read-only prefill. Observed folders still do not establish effective source identity. */ export function setupSuggestions(context?:HostPathContext):SetupSuggestions|undefined { - return platformSecurityScope(()=>suggestions(context)); -} -function suggestions(context?:HostPathContext):SetupSuggestions|undefined { const host=context??{platform:process.platform,env:{HOME:process.env.HOME,XDG_CONFIG_HOME:process.env.XDG_CONFIG_HOME,XDG_DATA_HOME:process.env.XDG_DATA_HOME},uid:process.getuid?.()}; if(host.platform!=='linux'&&host.platform!=='win32')return undefined; const nativeWindows=host.platform==='win32'&&process.platform==='win32'; diff --git a/setup/lifecycle.ts b/setup/lifecycle.ts index d675b5d..9c4feae 100644 --- a/setup/lifecycle.ts +++ b/setup/lifecycle.ts @@ -6,14 +6,14 @@ import { Store, canonical, digest } from '../shared/store.ts'; import { VERSION, type CompanionUpdateRead } from '../shared/progress.ts'; import { type Binding, readBinding, verifyStore } from '../shared/binding.ts'; import { activationFingerprint } from '../shared/activation.ts'; -import { windows, windowsPath, windowsPaths, platformSecurityScope, privatePaths, privateDirectory, isOwned, syncFile, syncDirectory, PlatformError, sameWindowsObject, sameWindowsDirectory, requirePlatformWriteBoundary } from '../shared/platform.ts'; +import { windows, windowsPath, windowsPaths, privatePaths, privateDirectory, isOwned, syncFile, syncDirectory, PlatformError, sameWindowsObject, sameWindowsDirectory, requirePlatformWriteBoundary } from '../shared/platform.ts'; import { MANAGED_STEP_LIMITS, type ManagedCaptureObservation, type ManagedStepRef } from '../shared/managed-steps.ts'; import type {ManagedLegacyEvidence,ManagedPathClaim,ManagedStepJournal} from './managed-step-journal.ts'; export interface Targets { configRoot: string; dataRoot: string; storeRoot: string; confirmed: boolean } /** Trim directory suffixes only; do not resolve traversal or conceal symlinks. */ export function normalizeTargets(targets:Targets):Targets { - if(windows)try{return platformSecurityScope(()=>{const [configRoot,dataRoot,storeRoot]=windowsPaths([targets.configRoot,targets.dataRoot,targets.storeRoot,path.join(targets.configRoot,'plugins','agent-progress'),path.join(targets.storeRoot,'payloads')],true);return {...targets,configRoot:configRoot!,dataRoot:dataRoot!,storeRoot:storeRoot!};});}catch(e){throw e instanceof PlatformError?new SetupError(e.code):e;} + if(windows)try{const [configRoot,dataRoot,storeRoot]=windowsPaths([targets.configRoot,targets.dataRoot,targets.storeRoot,path.join(targets.configRoot,'plugins','agent-progress'),path.join(targets.storeRoot,'payloads')],true);return {...targets,configRoot:configRoot!,dataRoot:dataRoot!,storeRoot:storeRoot!};}catch(e){throw e instanceof PlatformError?new SetupError(e.code):e;} const trim=(value:string)=>{const root=path.parse(value).root;while(value.length>root.length&&value.endsWith(path.sep))value=value.slice(0,-1);return value;}; return {...targets,configRoot:trim(targets.configRoot),dataRoot:trim(targets.dataRoot),storeRoot:trim(targets.storeRoot)}; } @@ -94,9 +94,6 @@ function verifyFiles(root:string, expected:Record, extras:string[ for(const [name,hash]of Object.entries(expected)){const file=path.join(root,name);need(existsSync(file),'modified-owned-files');if(!windows)safe(file);const st=lstatSync(file);need(st.isFile()&&(windows||st.uid===process.getuid?.()&&(st.mode&0o777)===0o600)&&digest(readFileSync(file))===hash,'modified-owned-files');} } export function inspect(targets:Targets) { - return platformSecurityScope(()=>inspectInner(targets)); -} -function inspectInner(targets:Targets) { targets=normalizeTargets(targets); safe(targets.configRoot);safe(targets.dataRoot);safe(targets.storeRoot,true); for(const root of [targets.configRoot,targets.dataRoot])need(lstatSync(root).isDirectory()&&isOwned(root),'path-unverified'); @@ -136,16 +133,14 @@ function removableSelectors(o:ReturnType) { } /** Migration preflight repeats every removal check BEFORE its disable-first path. */ export function migrationBinding(targets:Targets) { - return platformSecurityScope(()=>{ - const o=owned(targets);removableSelectors(o); - need(o.binding.source.verified&&privatePaths([o.root,path.join(o.root,'.ownership.json')]),'ownership-invalid'); - const store=new Store(o.binding.database,{readOnly:true}); - try{verifyStore(store,o.binding);store.subagentRunStorage();}finally{store.close();} - const active=path.join(targets.storeRoot,'payloads',o.manifest.active); - return {binding:o.binding, - fingerprint:activationFingerprint(readBinding(path.join(active,'progress-binding.json')),readFileSync(path.join(active,'index.js')),readFileSync(path.join(active,'SKILL.md'))), - ownership:digest(readFileSync(path.join(o.root,'.ownership.json')))}; - }); + const o=owned(targets);removableSelectors(o); + need(o.binding.source.verified&&privatePaths([o.root,path.join(o.root,'.ownership.json')]),'ownership-invalid'); + const store=new Store(o.binding.database,{readOnly:true}); + try{verifyStore(store,o.binding);store.subagentRunStorage();}finally{store.close();} + const active=path.join(targets.storeRoot,'payloads',o.manifest.active); + return {binding:o.binding, + fingerprint:activationFingerprint(readBinding(path.join(active,'progress-binding.json')),readFileSync(path.join(active,'index.js')),readFileSync(path.join(active,'SKILL.md'))), + ownership:digest(readFileSync(path.join(o.root,'.ownership.json')))}; } function migrationObject(file:string) { @@ -174,40 +169,36 @@ function migrationOwnedPaths(targets:Targets,m:Manifest,selectors:string[]) { /** Full read-only discovery owner for a known target. Inspection may stage its * path discovery separately; callers must charge all queries to that request. */ export function migrationEvidence(targets:Targets):{binding:Binding;legacy:Extract;plan:ManagedStepRef[]} { - return platformSecurityScope(()=>{ - const o=owned(targets),selectors=removableSelectors(o).sort(),ownership=readFileSync(path.join(o.root,'.ownership.json'),'utf8'); - const m=migrationOwnership(ownership),paths=migrationOwnedPaths(targets,m,selectors); - if(paths.length>MANAGED_STEP_LIMITS.claimPaths||Buffer.byteLength(ownership)>MANAGED_STEP_LIMITS.journalBytes)throw new SetupError('managed-step-limit'); - need(canonical(m)===canonical(o.manifest)&&o.binding.source.verified&&privatePaths([o.root,path.join(o.root,'.ownership.json')]),'ownership-invalid'); - const store=new Store(o.binding.database,{readOnly:true}); - try{verifyStore(store,o.binding);store.subagentRunStorage();}finally{store.close();} - return {binding:o.binding,legacy:{kind:'manifest',ownership,ownershipDigest:digest(ownership),claims:paths.map(migrationClaim)}, - plan:migrationRemovalPlan(selectors.length)}; - }); + const o=owned(targets),selectors=removableSelectors(o).sort(),ownership=readFileSync(path.join(o.root,'.ownership.json'),'utf8'); + const m=migrationOwnership(ownership),paths=migrationOwnedPaths(targets,m,selectors); + if(paths.length>MANAGED_STEP_LIMITS.claimPaths||Buffer.byteLength(ownership)>MANAGED_STEP_LIMITS.journalBytes)throw new SetupError('managed-step-limit'); + need(canonical(m)===canonical(o.manifest)&&o.binding.source.verified&&privatePaths([o.root,path.join(o.root,'.ownership.json')]),'ownership-invalid'); + const store=new Store(o.binding.database,{readOnly:true}); + try{verifyStore(store,o.binding);store.subagentRunStorage();}finally{store.close();} + return {binding:o.binding,legacy:{kind:'manifest',ownership,ownershipDigest:digest(ownership),claims:paths.map(migrationClaim)}, + plan:migrationRemovalPlan(selectors.length)}; } /** Read-only path discovery, not ownership or removal authority. Read the fixed * descriptor/manifest first; never obtain arbitrary paths from caller claims. * A later request must recheck these bytes before following the discovered set. */ export function discoverMigrationPaths(targets:Pick) { - return platformSecurityScope(()=>{ - const root=path.join(targets.configRoot,'plugins','agent-progress'); - const manifestFile=path.join(root,'.ownership.json'),descriptor=path.join(root,'progress-binding.json'); - const fixed=[targets.configRoot,targets.dataRoot,root,manifestFile,descriptor]; - if(windows)windowsPaths(fixed); - for(const file of [manifestFile,descriptor]){ - safe(file);const s=lstatSync(file); - need(s.isFile()&&!s.isSymbolicLink()&&s.nlink===1&&s.size<=MANAGED_STEP_LIMITS.journalBytes&&privatePaths([root,file]),'ownership-invalid'); - } - const before=migrationSnapshot(manifestFile),ownership=readFileSync(manifestFile,'utf8'),manifest=migrationOwnership(ownership); - need(before===migrationSnapshot(manifestFile),'installation-changed'); - const binding=readBinding(descriptor); - need(binding.source.verified&&binding.installId===manifest.installId&&binding.source.configRoot===targets.configRoot&& - binding.source.dataRoot===targets.dataRoot,'ownership-invalid'); - const selectors=windows?readdirSync(root).filter(n=>/^\.agent-progress-activation-[a-f0-9-]{36}$/.test(n)).map(n=>path.join(root,n)).sort():[]; - const paths=migrationOwnedPaths({...targets,storeRoot:path.dirname(binding.database),confirmed:true},manifest,selectors); - if(paths.length>MANAGED_STEP_LIMITS.claimPaths)throw new SetupError('managed-step-limit'); - return {binding,ownership,paths}; - }); + const root=path.join(targets.configRoot,'plugins','agent-progress'); + const manifestFile=path.join(root,'.ownership.json'),descriptor=path.join(root,'progress-binding.json'); + const fixed=[targets.configRoot,targets.dataRoot,root,manifestFile,descriptor]; + if(windows)windowsPaths(fixed); + for(const file of [manifestFile,descriptor]){ + safe(file);const s=lstatSync(file); + need(s.isFile()&&!s.isSymbolicLink()&&s.nlink===1&&s.size<=MANAGED_STEP_LIMITS.journalBytes&&privatePaths([root,file]),'ownership-invalid'); + } + const before=migrationSnapshot(manifestFile),ownership=readFileSync(manifestFile,'utf8'),manifest=migrationOwnership(ownership); + need(before===migrationSnapshot(manifestFile),'installation-changed'); + const binding=readBinding(descriptor); + need(binding.source.verified&&binding.installId===manifest.installId&&binding.source.configRoot===targets.configRoot&& + binding.source.dataRoot===targets.dataRoot,'ownership-invalid'); + const selectors=windows?readdirSync(root).filter(n=>/^\.agent-progress-activation-[a-f0-9-]{36}$/.test(n)).map(n=>path.join(root,n)).sort():[]; + const paths=migrationOwnedPaths({...targets,storeRoot:path.dirname(binding.database),confirmed:true},manifest,selectors); + if(paths.length>MANAGED_STEP_LIMITS.claimPaths)throw new SetupError('managed-step-limit'); + return {binding,ownership,paths}; } function migrationRemovalPlan(selectors:number):ManagedStepRef[] { return [{name:'prepare',batch:0},{name:'expectation',batch:0},{name:'disable',batch:0}, @@ -238,56 +229,54 @@ function removalLayout(journal:ManagedStepJournal) { } /** Full fresh remaining-set validation. Missing files are recognized only from * this operation's ordered completion or its exact before/after removal intent. - * The journal itself grants no ACL/object/Store authority. */ + * The journal itself grants no path/object/Store authority. */ export function validateMigrationRemoval(journal:ManagedStepJournal) { - return platformSecurityScope(()=>{ - const layout=removalLayout(journal),{targets,root,manifest,selectors,claims,removed,completed}=layout,m=journal.migration; - const database=journal.database,historyFile=path.join(targets.storeRoot,'installation-history.jsonl'); - const extra=[database,...['-journal','-wal','-shm'].map(s=>database+s),historyFile]; - // All paths come from the structurally checked frozen manifest/claims or - // fixed Store names. Include ancestors in one new batch; no cached verdict - // survives the caller's next mutation boundary. - if(windows)windowsPaths([...layout.paths,...extra],true); - const rootRemoved=completed>=m.plan.findIndex(s=>s.name==='record-removal'); - const rootMayBeMissing=rootRemoved||m.step?.name==='record-removal'&&layout.intentFor(root); - for(const claim of claims.values()){ - const s=lstatSync(claim.path,{throwIfNoEntry:false}); - const missingAllowed=removed.has(claim.path)||claim.path===layout.file(m.step)&&layout.intentFor(claim.path)||claim.path===root&&rootMayBeMissing; - if(!s){need(missingAllowed,'modified-owned-files');continue;} - need(!removed.has(claim.path)&&!(claim.path===root&&rootRemoved),'installation-changed'); - safe(claim.path);need(canonical(migrationObject(claim.path))===canonical(claim.object),'installation-changed'); - const publicRoot=claim.path===targets.configRoot||claim.path===targets.dataRoot; - need(!s.isSymbolicLink()&&(claim.kind==='directory'?s.isDirectory():claim.kind==='file'&&s.isFile()&&s.nlink===1)&& - (publicRoot?isOwned(claim.path):privatePaths([claim.path])),'ownership-invalid'); - if(claim.kind==='file'){ - const before=migrationSnapshot(claim.path);need(digest(readFileSync(claim.path))===claim.digest&&before===migrationSnapshot(claim.path),'modified-owned-files'); - } - } - // Saved claims cannot substitute arbitrary hashes for the original owner - // manifest, even if the current bytes happen to match those altered claims. - for(const [name,hash]of Object.entries(manifest.files))need(claims.get(path.join(root,name))?.digest===hash,'ownership-invalid'); - need(claims.get(path.join(root,'.ownership.json'))?.digest===m.legacy.ownershipDigest,'ownership-invalid'); - for(const [id,release]of Object.entries(manifest.releases)){ - const releaseRoot=path.join(targets.storeRoot,'payloads',id); - need(canonical(readdirSync(releaseRoot).sort())===canonical(Object.keys(release.files).sort()),'foreign-files'); - for(const [name,hash]of Object.entries(release.files))need(claims.get(path.join(releaseRoot,name))?.digest===hash,'ownership-invalid'); - } - if(lstatSync(root,{throwIfNoEntry:false})){ - const allowed=new Set([...layout.discovery,...selectors].filter(p=>!removed.has(p)&&lstatSync(p,{throwIfNoEntry:false})).map(p=>path.basename(p))); - need(readdirSync(root).every(name=>allowed.has(name)),'foreign-files'); + const layout=removalLayout(journal),{targets,root,manifest,selectors,claims,removed,completed}=layout,m=journal.migration; + const database=journal.database,historyFile=path.join(targets.storeRoot,'installation-history.jsonl'); + const extra=[database,...['-journal','-wal','-shm'].map(s=>database+s),historyFile]; + // All paths come from the structurally checked frozen manifest/claims or + // fixed Store names. Include ancestors in one new batch; no cached verdict + // survives the caller's next mutation boundary. + if(windows)windowsPaths([...layout.paths,...extra],true); + const rootRemoved=completed>=m.plan.findIndex(s=>s.name==='record-removal'); + const rootMayBeMissing=rootRemoved||m.step?.name==='record-removal'&&layout.intentFor(root); + for(const claim of claims.values()){ + const s=lstatSync(claim.path,{throwIfNoEntry:false}); + const missingAllowed=removed.has(claim.path)||claim.path===layout.file(m.step)&&layout.intentFor(claim.path)||claim.path===root&&rootMayBeMissing; + if(!s){need(missingAllowed,'modified-owned-files');continue;} + need(!removed.has(claim.path)&&!(claim.path===root&&rootRemoved),'installation-changed'); + safe(claim.path);need(canonical(migrationObject(claim.path))===canonical(claim.object),'installation-changed'); + const publicRoot=claim.path===targets.configRoot||claim.path===targets.dataRoot; + need(!s.isSymbolicLink()&&(claim.kind==='directory'?s.isDirectory():claim.kind==='file'&&s.isFile()&&s.nlink===1)&& + (publicRoot?isOwned(claim.path):privatePaths([claim.path])),'ownership-invalid'); + if(claim.kind==='file'){ + const before=migrationSnapshot(claim.path);need(digest(readFileSync(claim.path))===claim.digest&&before===migrationSnapshot(claim.path),'modified-owned-files'); } - const binding=readBinding(path.join(targets.storeRoot,'payloads',manifest.active,'progress-binding.json')); - need(binding.installId===m.legacyInstallId&&binding.database===database&&binding.storeId===journal.storeId&&canonical(binding.source)===canonical(journal.source),'ownership-invalid'); - removableSelectors({root,manifest,binding,staged:selectors.filter(p=>lstatSync(p,{throwIfNoEntry:false})).map(p=>path.basename(p))}); - for(const p of extra){ - const s=lstatSync(p,{throwIfNoEntry:false});if(!s)continue; - safe(p);need(s.isFile()&&!s.isSymbolicLink()&&s.nlink===1&&privatePaths([p]),'store-permissions'); - } - const store=new Store(database,{readOnly:true});let enabled:boolean; - try{verifyStore(store,binding);store.subagentRunStorage();enabled=store.list({limit:1}).captureEnabled;}finally{store.close();} - const capture:ManagedCaptureObservation={state:enabled?'on':'off',observedAt:new Date().toISOString()}; - return {...layout,capture}; - }); + } + // Saved claims cannot substitute arbitrary hashes for the original owner + // manifest, even if the current bytes happen to match those altered claims. + for(const [name,hash]of Object.entries(manifest.files))need(claims.get(path.join(root,name))?.digest===hash,'ownership-invalid'); + need(claims.get(path.join(root,'.ownership.json'))?.digest===m.legacy.ownershipDigest,'ownership-invalid'); + for(const [id,release]of Object.entries(manifest.releases)){ + const releaseRoot=path.join(targets.storeRoot,'payloads',id); + need(canonical(readdirSync(releaseRoot).sort())===canonical(Object.keys(release.files).sort()),'foreign-files'); + for(const [name,hash]of Object.entries(release.files))need(claims.get(path.join(releaseRoot,name))?.digest===hash,'ownership-invalid'); + } + if(lstatSync(root,{throwIfNoEntry:false})){ + const allowed=new Set([...layout.discovery,...selectors].filter(p=>!removed.has(p)&&lstatSync(p,{throwIfNoEntry:false})).map(p=>path.basename(p))); + need(readdirSync(root).every(name=>allowed.has(name)),'foreign-files'); + } + const binding=readBinding(path.join(targets.storeRoot,'payloads',manifest.active,'progress-binding.json')); + need(binding.installId===m.legacyInstallId&&binding.database===database&&binding.storeId===journal.storeId&&canonical(binding.source)===canonical(journal.source),'ownership-invalid'); + removableSelectors({root,manifest,binding,staged:selectors.filter(p=>lstatSync(p,{throwIfNoEntry:false})).map(p=>path.basename(p))}); + for(const p of extra){ + const s=lstatSync(p,{throwIfNoEntry:false});if(!s)continue; + safe(p);need(s.isFile()&&!s.isSymbolicLink()&&s.nlink===1&&privatePaths([p]),'store-permissions'); + } + const store=new Store(database,{readOnly:true});let enabled:boolean; + try{verifyStore(store,binding);store.subagentRunStorage();enabled=store.list({limit:1}).captureEnabled;}finally{store.close();} + const capture:ManagedCaptureObservation={state:enabled?'on':'off',observedAt:new Date().toISOString()}; + return {...layout,capture}; } /** One lifecycle-owned file effect only. Callers persist its exact intent first * under the shared writer fence. Missing current files reconcile; they never @@ -295,7 +284,7 @@ export function validateMigrationRemoval(journal:ManagedStepJournal) { export function removeMigrationFile(journal:ManagedStepJournal,validateJournal?:()=>void):{removed:boolean;capture:ManagedCaptureObservation} { requirePlatformWriteBoundary(); const m=journal.migration;need(m.state==='running'&&m.intent!==null&&['remove-selector','remove-discovery'].includes(m.step?.name??''),'managed-step-conflict'); - const before=platformSecurityScope(()=>{validateJournal?.();return validateMigrationRemoval(journal);}),file=before.file(m.step); + const before=(()=>{validateJournal?.();return validateMigrationRemoval(journal);})(),file=before.file(m.step); need(file&&before.intentFor(file)&&before.completed>=2&&before.capture.state==='off','managed-step-conflict'); if(!lstatSync(file,{throwIfNoEntry:false}))return {removed:false,capture:before.capture}; requirePlatformWriteBoundary();unlinkSync(file);syncDirectory(path.dirname(file)); @@ -328,16 +317,14 @@ function removalEvent(journal:ManagedStepJournal,capture:ManagedCaptureObservati /** Read-only construction of both subeffects' claims. The engine freezes these * in the durable intent before directory removal or history append. */ export function migrationRemovalRecordClaims(journal:ManagedStepJournal) { - return platformSecurityScope(()=>{ - const layout=validateMigrationRemoval(journal),m=journal.migration; - need(m.step?.name==='record-removal'&&m.intent===null&&layout.capture.state==='off','managed-step-conflict'); - need(readdirSync(layout.root).length===0,'foreign-files'); - const history=removalHistory(journal),event=removalEvent(journal,layout.capture); - if(history.bytes.length+Buffer.byteLength(event)>MANAGED_STEP_LIMITS.journalBytes)throw new SetupError('managed-step-limit'); - return {before:[layout.claims.get(layout.root)!,history.claim], - after:[{path:layout.root,kind:'absent' as const,object:null,digest:null}, - {...history.claim,digest:digest(Buffer.concat([history.bytes,Buffer.from(event)]))}],capture:layout.capture}; - }); + const layout=validateMigrationRemoval(journal),m=journal.migration; + need(m.step?.name==='record-removal'&&m.intent===null&&layout.capture.state==='off','managed-step-conflict'); + need(readdirSync(layout.root).length===0,'foreign-files'); + const history=removalHistory(journal),event=removalEvent(journal,layout.capture); + if(history.bytes.length+Buffer.byteLength(event)>MANAGED_STEP_LIMITS.journalBytes)throw new SetupError('managed-step-limit'); + return {before:[layout.claims.get(layout.root)!,history.claim], + after:[{path:layout.root,kind:'absent' as const,object:null,digest:null}, + {...history.claim,digest:digest(Buffer.concat([history.bytes,Buffer.from(event)]))}],capture:layout.capture}; } function validateRemovalRecord(journal:ManagedStepJournal) { const m=journal.migration,intent=m.intent; @@ -374,13 +361,13 @@ function validateRemovalRecord(journal:ManagedStepJournal) { * effect batch. It must be read-only and must prebatch any additional paths. */ export function recordMigrationRemoval(journal:ManagedStepJournal,validateJournal?:()=>void):{removed:boolean;recorded:boolean;capture:ManagedCaptureObservation} { requirePlatformWriteBoundary(); - let current=platformSecurityScope(()=>{validateJournal?.();return validateRemovalRecord(journal);}); + let current=(()=>{validateJournal?.();return validateRemovalRecord(journal);})(); let removed=false; if(lstatSync(current.layout.root,{throwIfNoEntry:false})){ requirePlatformWriteBoundary();rmdirSync(current.layout.root);syncDirectory(path.dirname(current.layout.root));removed=true; - // rmdir invalidates the actual security scope. Recheck the retained payloads, + // rmdir changes the filesystem. Recheck the retained payloads, // roots, Store, capture and history before admitting the second subeffect. - current=platformSecurityScope(()=>{validateJournal?.();return validateRemovalRecord(journal);}); + current=(()=>{validateJournal?.();return validateRemovalRecord(journal);})(); } if(!current.recorded){ requirePlatformWriteBoundary(); @@ -393,22 +380,20 @@ export function recordMigrationRemoval(journal:ManagedStepJournal,validateJourna /** Read-only completion proof, also required inside the journal checkpoint's * fresh validation batch. A missing directory without the event is incomplete. */ export function migrationRemovalRecorded(journal:ManagedStepJournal):boolean { - return platformSecurityScope(()=>validateRemovalRecord(journal).recorded); + return validateRemovalRecord(journal).recorded; } /** After the record-removal checkpoint the unresolved intent is gone. Later * steps still require this operation's lifecycle event in freshly owned history, * in addition to the full remaining-set and absent-directory verification. */ export function migrationRemovalComplete(journal:ManagedStepJournal):boolean { - return platformSecurityScope(()=>{ - const layout=validateMigrationRemoval(journal),m=journal.migration; - need(layout.completed>=m.plan.findIndex(s=>s.name==='record-removal'),'managed-step-conflict'); - const events=removalHistory(journal).text.split('\n').flatMap(line=>{ - try{const event=JSON.parse(line);return event?.action==='remove-capture'&&event.installId===m.legacyInstallId&&event.operationId===m.operationId?[event]:[];} - catch{return [];} - }); - return events.length===1&&typeof events[0].at==='string'&&Number.isFinite(Date.parse(events[0].at))&& - new Date(events[0].at).toISOString()===events[0].at; + const layout=validateMigrationRemoval(journal),m=journal.migration; + need(layout.completed>=m.plan.findIndex(s=>s.name==='record-removal'),'managed-step-conflict'); + const events=removalHistory(journal).text.split('\n').flatMap(line=>{ + try{const event=JSON.parse(line);return event?.action==='remove-capture'&&event.installId===m.legacyInstallId&&event.operationId===m.operationId?[event]:[];} + catch{return [];} }); + return events.length===1&&typeof events[0].at==='string'&&Number.isFinite(Date.parse(events[0].at))&& + new Date(events[0].at).toISOString()===events[0].at; } function history(targets:Targets,event:unknown){const file=path.join(targets.storeRoot,'installation-history.jsonl');safe(file,true);if(windows&&existsSync(file))need(privatePaths([file]),'store-permissions');appendFileSync(file,JSON.stringify(event)+'\n',{mode:0o600});syncFile(file);} /** Retained sources are candidates, not currently selected target assertions. */ @@ -423,7 +408,7 @@ function matchesRetainedSource(source:Binding['source'],targets:Targets) { } export type Action='inspect'|'dry-run'|'install'|'update'|'disable'|'enable'|'remove-capture'; export function lifecycle(action:Action,targets:Targets,payload?:Payload, testBoundary?:(name:'release-staged'|'before-activation'|'after-activation')=>void) { - try{return platformSecurityScope(()=>lifecycleInner(action,targets,payload,testBoundary));}catch(e){throw e instanceof PlatformError?new SetupError(e.code):e;} + try{return lifecycleInner(action,targets,payload,testBoundary);}catch(e){throw e instanceof PlatformError?new SetupError(e.code):e;} } function lifecycleInner(action:Action,targets:Targets,payload?:Payload, testBoundary?:(name:'release-staged'|'before-activation'|'after-activation')=>void) { const info=inspect(targets); diff --git a/setup/managed-inspection.ts b/setup/managed-inspection.ts index 6e2668a..74a4060 100644 --- a/setup/managed-inspection.ts +++ b/setup/managed-inspection.ts @@ -5,7 +5,7 @@ import {type Binding,verifyStore} from '../shared/binding.ts'; import {Store,canonical,digest} from '../shared/store.ts'; import {activationFingerprint} from '../shared/activation.ts'; import {managedSourceRoots,managedBindingFile,managedPath,readManagedBinding,managedExpectationFile} from '../shared/managed-binding.ts'; -import {windows,windowsPaths,privatePaths,isOwned,platformSecurityScope} from '../shared/platform.ts'; +import {windows,windowsPaths,privatePaths,isOwned} from '../shared/platform.ts'; import {MANAGED_INSPECTION_STEPS,MANAGED_STEP_LIMITS,type ManagedInspection,type ManagedCaptureObservation,type ManagedStepProgress} from '../shared/managed-steps.ts'; import type {ManagedReview} from '../shared/progress.ts'; import {SetupError,discoverMigrationPaths,migrationEvidence,validateMigrationRemoval,type Payload} from './lifecycle.ts'; @@ -18,7 +18,7 @@ import {readManagedFreshStepJournal} from './managed-migration.ts'; import {managedFreshJournalProgress,type ManagedFreshStepJournal} from './managed-step-journal.ts'; /** Private supervisor/worker state. NEVER accept this object from an HTTP body. - * Paths and hashes are discovery claims only, not reusable security verdicts. */ + * Paths and hashes are discovery claims only, not reusable verdicts. */ export interface ManagedInspectionSession { nonce:string; cursor:string; @@ -117,21 +117,19 @@ function reviewFor(session:ManagedInspectionSession,observed:ManagedCaptureObser /** Mutation admission calls this again under its OWN fresh batch/fence. An * opaque token alone, or a worker's earlier observation, never authorizes it. */ export function validateManagedInspectionReview(env:NodeJS.ProcessEnv,payload:Payload,session:ManagedInspectionSession) { - return platformSecurityScope(()=>{ - need(session.stage===MANAGED_INSPECTION_STEPS.length&&session.review&&session.candidate,'managed-inspection-expired'); - batch(paths(session));sameDiscovery(env,session); - const observed=validateCandidate(session,payload),review=reviewFor(session,observed); - need(review.expected===session.review.expected); - return {candidate:structuredClone(session.candidate),prior:session.prior&&structuredClone(session.prior), - operation:session.operation&&structuredClone(session.operation),capture:observed,review}; - }); + need(session.stage===MANAGED_INSPECTION_STEPS.length&&session.review&&session.candidate,'managed-inspection-expired'); + batch(paths(session));sameDiscovery(env,session); + const observed=validateCandidate(session,payload),review=reviewFor(session,observed); + need(review.expected===session.review.expected); + return {candidate:structuredClone(session.candidate),prior:session.prior&&structuredClone(session.prior), + operation:session.operation&&structuredClone(session.operation),capture:observed,review}; } /** Exactly one read-only stage. The supervisor supplies prior state, never the - * caller. Every stage gets a new opaque cursor and a fresh security scope. */ + * caller. Every stage gets a new opaque cursor and revalidates its paths. */ export function inspectManagedStep(env:NodeJS.ProcessEnv,payload:Payload,prior?:ManagedInspectionSession,storeRoot?:string):ManagedInspectionResult { let stage:typeof MANAGED_INSPECTION_STEPS[number]='roots',known:ManagedStepJournal|undefined; - try{return platformSecurityScope(()=>{ + try{ let session:ManagedInspectionSession; if(!prior){ const roots=managedSourceRoots(env);batch(basePaths(roots)); @@ -218,7 +216,7 @@ export function inspectManagedStep(env:NodeJS.ProcessEnv,payload:Payload,prior?: } session.stage++;session.cursor=randomUUID(); return {session,progress:session.operation?managedJournalProgress(session.operation):null,inspection:{state:'incomplete',stage,cursor:session.cursor}}; - });}catch(error){throw new ManagedStepFailure(error,stage,known);} + }catch(error){throw new ManagedStepFailure(error,stage,known);} } export interface ManagedFreshInspectionSession { @@ -302,82 +300,78 @@ function freshReview(s:ManagedFreshInspectionSession,observed:ManagedCaptureObse storeMode:f.storeMode,sourceMode:f.sourceMode,capturePolicy:f.capturePolicy,packageVersion:m.expectation.version,capture:observed,plan:structuredClone(m.plan)}; } export function validateManagedFreshInspectionReview(env:NodeJS.ProcessEnv,payload:Payload,s:ManagedFreshInspectionSession) { - return platformSecurityScope(()=>{ - need(s.family===2&&s.stage===MANAGED_FRESH_INSPECTION_STEPS.length&&s.review&&s.candidate,'managed-inspection-expired'); - batch(freshPaths(s));freshDiscovery(env,s); - const j=s.candidate; - need(canonical(j.migration.expectation)===canonical(expectation(j,payload))); - if(s.operation)need(canonical(readManagedFreshStepJournal(env))===canonical(s.operation)); - const observed=observeManagedFreshStore(j),review=freshReview(s,observed); - need(review.expected===s.review.expected); - return {candidate:structuredClone(j),operation:s.operation&&structuredClone(s.operation),capture:observed,review}; - }); + need(s.family===2&&s.stage===MANAGED_FRESH_INSPECTION_STEPS.length&&s.review&&s.candidate,'managed-inspection-expired'); + batch(freshPaths(s));freshDiscovery(env,s); + const j=s.candidate; + need(canonical(j.migration.expectation)===canonical(expectation(j,payload))); + if(s.operation)need(canonical(readManagedFreshStepJournal(env))===canonical(s.operation)); + const observed=observeManagedFreshStore(j),review=freshReview(s,observed); + need(review.expected===s.review.expected); + return {candidate:structuredClone(j),operation:s.operation&&structuredClone(s.operation),capture:observed,review}; } /** Fresh pages share the existing inspection owner, private cursor transport and * review nonce rules. No filesystem/DB/source/binding write occurs here. */ export function inspectManagedFreshStep(env:NodeJS.ProcessEnv,payload:Payload,prior?:ManagedFreshInspectionSession,storeRoot?:string):ManagedFreshInspectionResult { - return platformSecurityScope(()=>{ - let s:ManagedFreshInspectionSession; - if(!prior){ - const roots=managedSourceRoots(env),selected=storeRoot??path.join(roots.dataRoot,'openchamber-progress'); - batch([...basePaths(roots),selected]);const target=managedPath(selected,true); - need(![roots.configRoot,roots.dataRoot,path.join(roots.dataRoot,'agent-progress-managed')].includes(target),'managed-selection-conflict'); - for(const root of Object.values(roots))need(lstatSync(root).isDirectory()&&isOwned(root),'path-unverified'); - s={family:2,nonce:randomUUID(),cursor:randomUUID(),stage:1,roots,storeRoot:target,...(storeRoot!==undefined?{explicitStoreRoot:true as const}:{}),selection:claim(container(env)),record:claim(migrationFile(env))}; - return {session:s,progress:null,inspection:{state:'incomplete',stage:'roots',cursor:s.cursor}}; - } - s=structuredClone(prior);need(s.family===2&&s.stage>0&&s.stagemanagedFreshObjectClaim(database+x)); - let storeId:string=randomUUID(),source:Binding['source']={id:randomUUID(),...s.roots,verified:true},sourceMode:'create'|'reuse'='create',captureState:'unknown'|'on'|'off'='unknown'; - if(db.kind==='absent'){ - need(sidecars.every(c=>c.kind==='absent'),'managed-migration-conflict'); - if(directory.kind==='directory')need(readdirSync(s.storeRoot).length===0,'foreign-files'); - else need(lstatSync(path.dirname(s.storeRoot),{throwIfNoEntry:false})?.isDirectory(),'managed-path-unverified'); - }else{ - const store=new Store(database,{readOnly:true});try{ - store.subagentRunStorage();const e=store.list({limit:1});storeId=e.storeId;captureState=e.captureEnabled?'on':'off'; - const matches=e.sources.filter(x=>x.configRoot===s.roots.configRoot&&x.dataRoot===s.roots.dataRoot); - need(matches.length<=1&&matches.every(x=>x.verified),'managed-source-conflict'); - if(matches[0]){source={...matches[0]};sourceMode='reuse';} - need(!e.sources.some(x=>x.id===source.id&&canonical(x)!==canonical(source)),'managed-source-conflict'); - }finally{store.close();} - } - const storeMode=db.kind==='absent'?'create':'retain',plan=managedFreshPlan(storeMode,directory.kind==='absent',sourceMode); - const binding:Binding={protocolVersion:2,schemaVersion:2,installId:`managed-${digest(JSON.stringify([storeId,source]))}`,version:payload.version,database,storeId,source}; - s.candidate={...binding,migration:{format:3,planKind:'fresh',product:'openchamber-agent-progress-managed',phase:'pending', - operationId:s.nonce,sequence:1,state:'pending',step:plan[1]!,lastCompleted:plan[0]!, - consent:{reviewDigest:'0'.repeat(64),targetDigest:'0'.repeat(64),planDigest:digest(canonical(plan))},expectation:expectation(binding,payload),plan, - fresh:{storeMode,sourceMode,capturePolicy:storeMode==='create'?'enable-new':'preserve',directory,database:db,sidecars, - source:sourceMode==='reuse'?source:null,capture:captureState,selection:s.selection,journal:s.record, - legacy:{path:path.join(s.roots.configRoot,'plugins','agent-progress'),kind:'absent',object:null,digest:null}}, - created:{directory:null,database:null},intent:null,receipt:null,captureRenewals:[],capture:{state:'unknown',observedAt:null},diagnostic:null}}; - s.candidate.migration.consent.targetDigest=managedTargetDigest(s.candidate); + let s:ManagedFreshInspectionSession; + if(!prior){ + const roots=managedSourceRoots(env),selected=storeRoot??path.join(roots.dataRoot,'openchamber-progress'); + batch([...basePaths(roots),selected]);const target=managedPath(selected,true); + need(![roots.configRoot,roots.dataRoot,path.join(roots.dataRoot,'agent-progress-managed')].includes(target),'managed-selection-conflict'); + for(const root of Object.values(roots))need(lstatSync(root).isDirectory()&&isOwned(root),'path-unverified'); + s={family:2,nonce:randomUUID(),cursor:randomUUID(),stage:1,roots,storeRoot:target,...(storeRoot!==undefined?{explicitStoreRoot:true as const}:{}),selection:claim(container(env)),record:claim(migrationFile(env))}; + return {session:s,progress:null,inspection:{state:'incomplete',stage:'roots',cursor:s.cursor}}; + } + s=structuredClone(prior);need(s.family===2&&s.stage>0&&s.stagemanagedFreshObjectClaim(database+x)); + let storeId:string=randomUUID(),source:Binding['source']={id:randomUUID(),...s.roots,verified:true},sourceMode:'create'|'reuse'='create',captureState:'unknown'|'on'|'off'='unknown'; + if(db.kind==='absent'){ + need(sidecars.every(c=>c.kind==='absent'),'managed-migration-conflict'); + if(directory.kind==='directory')need(readdirSync(s.storeRoot).length===0,'foreign-files'); + else need(lstatSync(path.dirname(s.storeRoot),{throwIfNoEntry:false})?.isDirectory(),'managed-path-unverified'); + }else{ + const store=new Store(database,{readOnly:true});try{ + store.subagentRunStorage();const e=store.list({limit:1});storeId=e.storeId;captureState=e.captureEnabled?'on':'off'; + const matches=e.sources.filter(x=>x.configRoot===s.roots.configRoot&&x.dataRoot===s.roots.dataRoot); + need(matches.length<=1&&matches.every(x=>x.verified),'managed-source-conflict'); + if(matches[0]){source={...matches[0]};sourceMode='reuse';} + need(!e.sources.some(x=>x.id===source.id&&canonical(x)!==canonical(source)),'managed-source-conflict'); + }finally{store.close();} } - observeManagedFreshStore(s.candidate!); - }else if(stage==='review'){ - need(s.candidate,'managed-inspection-expired');freshDiscovery(env,s); - need(canonical(s.candidate.migration.expectation)===canonical(expectation(s.candidate,payload))); - const observed=observeManagedFreshStore(s.candidate);s.review=freshReview(s,observed);s.stage++;s.cursor=randomUUID(); - return {session:s,inspection:{state:'complete',stage:'review',cursor:null,review:s.review}, - progress:s.operation?managedFreshJournalProgress(s.operation,observed):null}; + const storeMode=db.kind==='absent'?'create':'retain',plan=managedFreshPlan(storeMode,directory.kind==='absent',sourceMode); + const binding:Binding={protocolVersion:2,schemaVersion:2,installId:`managed-${digest(JSON.stringify([storeId,source]))}`,version:payload.version,database,storeId,source}; + s.candidate={...binding,migration:{format:3,planKind:'fresh',product:'openchamber-agent-progress-managed',phase:'pending', + operationId:s.nonce,sequence:1,state:'pending',step:plan[1]!,lastCompleted:plan[0]!, + consent:{reviewDigest:'0'.repeat(64),targetDigest:'0'.repeat(64),planDigest:digest(canonical(plan))},expectation:expectation(binding,payload),plan, + fresh:{storeMode,sourceMode,capturePolicy:storeMode==='create'?'enable-new':'preserve',directory,database:db,sidecars, + source:sourceMode==='reuse'?source:null,capture:captureState,selection:s.selection,journal:s.record, + legacy:{path:path.join(s.roots.configRoot,'plugins','agent-progress'),kind:'absent',object:null,digest:null}}, + created:{directory:null,database:null},intent:null,receipt:null,captureRenewals:[],capture:{state:'unknown',observedAt:null},diagnostic:null}}; + s.candidate.migration.consent.targetDigest=managedTargetDigest(s.candidate); } - s.stage++;s.cursor=randomUUID(); - return {session:s,inspection:{state:'incomplete',stage,cursor:s.cursor},progress:s.operation?managedFreshJournalProgress(s.operation):null}; - }); + observeManagedFreshStore(s.candidate!); + }else if(stage==='review'){ + need(s.candidate,'managed-inspection-expired');freshDiscovery(env,s); + need(canonical(s.candidate.migration.expectation)===canonical(expectation(s.candidate,payload))); + const observed=observeManagedFreshStore(s.candidate);s.review=freshReview(s,observed);s.stage++;s.cursor=randomUUID(); + return {session:s,inspection:{state:'complete',stage:'review',cursor:null,review:s.review}, + progress:s.operation?managedFreshJournalProgress(s.operation,observed):null}; + } + s.stage++;s.cursor=randomUUID(); + return {session:s,inspection:{state:'incomplete',stage,cursor:s.cursor},progress:s.operation?managedFreshJournalProgress(s.operation):null}; } diff --git a/setup/managed-migration.ts b/setup/managed-migration.ts index e332e95..14a02bb 100644 --- a/setup/managed-migration.ts +++ b/setup/managed-migration.ts @@ -2,7 +2,7 @@ import {lstatSync,readFileSync,readdirSync} from 'node:fs'; import path from 'node:path'; import {readBinding,type Binding,verifyStore} from '../shared/binding.ts'; import {managedBindingFile,managedSourceRoots,managedPath,publishPrivateJson,ManagedBindingError,managedExpectationFile,readManagedBinding} from '../shared/managed-binding.ts'; -import {privatePaths,platformSecurityScope,isOwned,PlatformError,requirePlatformWriteBoundary,windows,windowsPaths} from '../shared/platform.ts'; +import {privatePaths,isOwned,PlatformError,requirePlatformWriteBoundary,windows,windowsPaths} from '../shared/platform.ts'; import {Store,canonical,storageError,digest} from '../shared/store.ts'; import {ProgressError} from '../shared/progress.ts'; import {SetupError,migrationBinding,validateMigrationRemoval,type Targets} from './lifecycle.ts'; @@ -18,26 +18,24 @@ export interface MigrationRecord { export function migrationFile(env:NodeJS.ProcessEnv){return path.join(path.dirname(managedBindingFile(env)),'migration.json');} /** A fixed private same-target selection, never a search or recovery authority for foreign bytes. */ export function readMigration(env:NodeJS.ProcessEnv):MigrationRecord|undefined { - return platformSecurityScope(()=>{ - const file=migrationFile(env);if(!lstatSync(file,{throwIfNoEntry:false}))return; - managedPath(file); - if(!privatePaths([path.dirname(file),file]))throw new SetupError('managed-migration-conflict'); - const raw=readBinding(file) as Binding&{migration?:{format:number;product:string;phase:MigrationRecord['phase'];legacyInstallId:string}}; - const m=raw.migration,roots=managedSourceRoots(env); - if(!m||m.format!==1||m.product!=='openchamber-agent-progress-managed'||!['pending','removed','complete'].includes(m.phase)|| - typeof m.legacyInstallId!=='string'||!m.legacyInstallId||m.legacyInstallId===raw.installId||raw.source.configRoot!==roots.configRoot||raw.source.dataRoot!==roots.dataRoot||!raw.source.verified|| - [roots.configRoot,roots.dataRoot,path.dirname(file)].includes(path.dirname(raw.database))|| - ![roots.configRoot,roots.dataRoot].every(root=>lstatSync(root).isDirectory()&&isOwned(root)))throw new SetupError('managed-migration-conflict'); - const {protocolVersion,schemaVersion,installId,version,database,storeId,source}=raw; - const binding={protocolVersion,schemaVersion,installId,version,database,storeId,source}; - const store=new Store(database,{readOnly:true});try{verifyStore(store,binding);store.subagentRunStorage();}finally{store.close();} - return {binding,phase:m.phase,legacyInstallId:m.legacyInstallId}; - }); + const file=migrationFile(env);if(!lstatSync(file,{throwIfNoEntry:false}))return; + managedPath(file); + if(!privatePaths([path.dirname(file),file]))throw new SetupError('managed-migration-conflict'); + const raw=readBinding(file) as Binding&{migration?:{format:number;product:string;phase:MigrationRecord['phase'];legacyInstallId:string}}; + const m=raw.migration,roots=managedSourceRoots(env); + if(!m||m.format!==1||m.product!=='openchamber-agent-progress-managed'||!['pending','removed','complete'].includes(m.phase)|| + typeof m.legacyInstallId!=='string'||!m.legacyInstallId||m.legacyInstallId===raw.installId||raw.source.configRoot!==roots.configRoot||raw.source.dataRoot!==roots.dataRoot||!raw.source.verified|| + [roots.configRoot,roots.dataRoot,path.dirname(file)].includes(path.dirname(raw.database))|| + ![roots.configRoot,roots.dataRoot].every(root=>lstatSync(root).isDirectory()&&isOwned(root)))throw new SetupError('managed-migration-conflict'); + const {protocolVersion,schemaVersion,installId,version,database,storeId,source}=raw; + const binding={protocolVersion,schemaVersion,installId,version,database,storeId,source}; + const store=new Store(database,{readOnly:true});try{verifyStore(store,binding);store.subagentRunStorage();}finally{store.close();} + return {binding,phase:m.phase,legacyInstallId:m.legacyInstallId}; } export function writeMigration(env:NodeJS.ProcessEnv,record:MigrationRecord) { - // One read-only preflight per publication. Never carry its security cache into - // the write or the next phase's revalidation. - const {prior,file}=platformSecurityScope(()=>({prior:readMigration(env),file:migrationFile(env)})); + // One read-only preflight per publication. Never carry its result into the + // write or the next phase's revalidation. + const {prior,file}=(({prior:readMigration(env),file:migrationFile(env)})); if(prior&&(canonical(prior.binding)!==canonical(record.binding)||prior.legacyInstallId!==record.legacyInstallId))throw new SetupError('managed-migration-conflict'); publishPrivateJson(file,{...record.binding,migration:{format:1,product:'openchamber-agent-progress-managed',phase:record.phase,legacyInstallId:record.legacyInstallId}},!!prior); } @@ -46,18 +44,13 @@ export function sameMigrationTarget(a:Binding,b:Binding) { } /** Ownership/identity evidence is distinct from inability to inspect it. */ export function migrationError(e:unknown):SetupError|ProgressError|PlatformError { - if(e instanceof PlatformError&&e.code==='windows-security-unavailable')return e; - if(e instanceof SetupError&&e.code==='windows-security-unavailable')return new PlatformError(e.code); if(e instanceof ProgressError&&e.code!=='binding')return e; if(e instanceof SetupError||e instanceof PlatformError||e instanceof ManagedBindingError||e instanceof SyntaxError||e instanceof ProgressError|| ['ENOENT','ENOTDIR','ELOOP'].includes((e as NodeJS.ErrnoException)?.code??''))return new SetupError('managed-migration-conflict'); return storageError(e); } /** Canonical legacy location only; the full removal preflight validates it and the actual Store. */ -export function legacyMigration(env:NodeJS.ProcessEnv) { - return platformSecurityScope(()=>legacyMigrationInner(env)); -} -function legacyMigrationInner(env:NodeJS.ProcessEnv):({targets:Targets}&ReturnType)|undefined { +export function legacyMigration(env:NodeJS.ProcessEnv):({targets:Targets}&ReturnType)|undefined { const roots=managedSourceRoots(env),root=path.join(roots.configRoot,'plugins/agent-progress'); if(!lstatSync(root,{throwIfNoEntry:false}))return; try{ @@ -68,9 +61,6 @@ function legacyMigrationInner(env:NodeJS.ProcessEnv):({targets:Targets}&ReturnTy } /** Removal can finish before the wrapper writes its next phase. Require its durable same-install receipt. */ export function removalRecorded(record:MigrationRecord) { - return platformSecurityScope(()=>removalRecordedInner(record)); -} -function removalRecordedInner(record:MigrationRecord) { const file=path.join(path.dirname(record.binding.database),'installation-history.jsonl'); managedPath(file); const s=lstatSync(file); @@ -85,45 +75,43 @@ export interface ManagedRemovalReceipt { history:ManagedPathClaim; entry:string * removes, repairs or appends anything. An earlier true removalRecorded() result * is deliberately not accepted as authority, nor is a coarse removed phase. */ export function readRemovalReceipt(record:MigrationRecord,retained?:ManagedRemovalReceipt):ManagedRemovalReceipt|undefined { - return platformSecurityScope(()=>{ - const b=record.binding; - const conflict=()=>{throw new SetupError('managed-migration-conflict');}; - if(!b.source.verified||!record.legacyInstallId||record.legacyInstallId===b.installId)conflict(); - for(const root of [b.source.configRoot,b.source.dataRoot,path.dirname(b.database)]){ - managedPath(root);if(!lstatSync(root).isDirectory()||!isOwned(root))conflict(); - } - const legacy=managedPath(path.join(b.source.configRoot,'plugins/agent-progress'),true); - // A receipt cannot authorize removing or overlooking remaining discovery. - if(lstatSync(legacy,{throwIfNoEntry:false}))conflict(); - for(const file of [b.database,...['-journal','-wal','-shm'].map(suffix=>b.database+suffix)]){ - const stat=lstatSync(file,{throwIfNoEntry:false});if(!stat)continue; - managedPath(file);if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1||!privatePaths([file]))conflict(); - } - const store=new Store(b.database,{readOnly:true}); - try{verifyStore(store,b);store.subagentRunStorage();}finally{store.close();} - const file=managedPath(path.join(path.dirname(b.database),'installation-history.jsonl')); - const before=lstatSync(file,{bigint:true}); - if(!before.isFile()||before.isSymbolicLink()||before.nlink!==1n||!privatePaths([path.dirname(file),file]))conflict(); - if(before.size>BigInt(MANAGED_STEP_LIMITS.journalBytes))throw new SetupError('managed-step-limit'); - const object={device:String(before.dev),inode:String(before.ino),birthNs:String(before.birthtimeNs)}; - if(retained&&(retained.history.path!==file||retained.history.kind!=='file'|| - canonical(retained.history.object)!==canonical(object)))conflict(); - const bytes=readFileSync(file),after=lstatSync(file,{bigint:true}); - if([before.dev,before.ino,before.birthtimeNs,before.size,before.mtimeNs,before.ctimeNs,before.nlink].join(':')!== - [after.dev,after.ino,after.birthtimeNs,after.size,after.mtimeNs,after.ctimeNs,after.nlink].join(':'))conflict(); - let text:string; - try{text=new TextDecoder('utf-8',{fatal:true}).decode(bytes);}catch{throw new SetupError('managed-migration-conflict');} - let entry:string|undefined; - for(const line of text.split('\n')){ - if(retained&&line!==retained.entry)continue; - try{const event=JSON.parse(line);if(event?.action==='remove-capture'&&event.installId===record.legacyInstallId){entry=line;break;}}catch{/* Other historical lines grant no authority. */} - } - if(!entry){if(retained)conflict();return;} - // Later appends are allowed only in this same freshly validated owned file - // with the exact retained event still present. The old hash is a claim, not - // an ACL verdict or a requirement that unrelated history stop growing. - return {history:{path:file,kind:'file',object,digest:digest(bytes)},entry}; - }); + const b=record.binding; + const conflict=()=>{throw new SetupError('managed-migration-conflict');}; + if(!b.source.verified||!record.legacyInstallId||record.legacyInstallId===b.installId)conflict(); + for(const root of [b.source.configRoot,b.source.dataRoot,path.dirname(b.database)]){ + managedPath(root);if(!lstatSync(root).isDirectory()||!isOwned(root))conflict(); + } + const legacy=managedPath(path.join(b.source.configRoot,'plugins/agent-progress'),true); + // A receipt cannot authorize removing or overlooking remaining discovery. + if(lstatSync(legacy,{throwIfNoEntry:false}))conflict(); + for(const file of [b.database,...['-journal','-wal','-shm'].map(suffix=>b.database+suffix)]){ + const stat=lstatSync(file,{throwIfNoEntry:false});if(!stat)continue; + managedPath(file);if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1||!privatePaths([file]))conflict(); + } + const store=new Store(b.database,{readOnly:true}); + try{verifyStore(store,b);store.subagentRunStorage();}finally{store.close();} + const file=managedPath(path.join(path.dirname(b.database),'installation-history.jsonl')); + const before=lstatSync(file,{bigint:true}); + if(!before.isFile()||before.isSymbolicLink()||before.nlink!==1n||!privatePaths([path.dirname(file),file]))conflict(); + if(before.size>BigInt(MANAGED_STEP_LIMITS.journalBytes))throw new SetupError('managed-step-limit'); + const object={device:String(before.dev),inode:String(before.ino),birthNs:String(before.birthtimeNs)}; + if(retained&&(retained.history.path!==file||retained.history.kind!=='file'|| + canonical(retained.history.object)!==canonical(object)))conflict(); + const bytes=readFileSync(file),after=lstatSync(file,{bigint:true}); + if([before.dev,before.ino,before.birthtimeNs,before.size,before.mtimeNs,before.ctimeNs,before.nlink].join(':')!== + [after.dev,after.ino,after.birthtimeNs,after.size,after.mtimeNs,after.ctimeNs,after.nlink].join(':'))conflict(); + let text:string; + try{text=new TextDecoder('utf-8',{fatal:true}).decode(bytes);}catch{throw new SetupError('managed-migration-conflict');} + let entry:string|undefined; + for(const line of text.split('\n')){ + if(retained&&line!==retained.entry)continue; + try{const event=JSON.parse(line);if(event?.action==='remove-capture'&&event.installId===record.legacyInstallId){entry=line;break;}}catch{/* Other historical lines grant no authority. */} + } + if(!entry){if(retained)conflict();return;} + // Later appends are allowed only in this same freshly validated owned file + // with the exact retained event still present. The old hash is a claim, not + // a permission verdict or a requirement that unrelated history stop growing. + return {history:{path:file,kind:'file',object,digest:digest(bytes)},entry}; } function journalSnapshot(file:string) { @@ -147,58 +135,54 @@ export function managedJournalPaths(journal:ManagedSetupStepJournal):string[] { /** Observe a proposed target before storage exists, without ordinary Binding/Store * admission. Missing completed/retained resources are refused, never recreated. */ export function readManagedFreshStepJournal(env:NodeJS.ProcessEnv):ManagedFreshStepJournal|undefined { - return platformSecurityScope(()=>{ - const file=migrationFile(env),root=path.dirname(file); - if(!lstatSync(root,{throwIfNoEntry:false}))return; - if(lstatSync(path.join(root,'.ownership.json'),{throwIfNoEntry:false})?.nlink!==1)throw new SetupError('managed-binding-invalid'); - const names=readdirSync(root); - if(names.includes('.configuration-lock'))throw new SetupError('managed-configuration-busy'); - if(names.some(n=>n.startsWith('migration.json.stage-')||n.startsWith('progress-binding.json.stage-')))throw new SetupError('managed-migration-conflict'); - const stat=lstatSync(file,{throwIfNoEntry:false});if(!stat)return; - managedPath(file); - if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1||!privatePaths([root,file]))throw new SetupError('managed-migration-conflict'); - if(stat.size>MANAGED_STEP_LIMITS.journalBytes)throw new SetupError('managed-step-limit'); - const before=journalSnapshot(file),journal=parseManagedFreshStepJournal(readFileSync(file)),roots=managedSourceRoots(env),m=journal.migration; - if(journal.source.configRoot!==roots.configRoot||journal.source.dataRoot!==roots.dataRoot|| - [roots.configRoot,roots.dataRoot,root].includes(path.dirname(journal.database))|| - ![roots.configRoot,roots.dataRoot].every(p=>lstatSync(p).isDirectory()&&isOwned(p)))throw new SetupError('managed-migration-conflict'); - for(const [p,directory] of [[path.dirname(journal.database),true],[journal.database,false],...m.fresh.sidecars.map(c=>[c.path,false] as const)] as const){ - managedPath(p,true);const s=lstatSync(p,{throwIfNoEntry:false}); - if(s&&(!privatePaths([p])||s.isSymbolicLink()||(directory?!s.isDirectory():!s.isFile()||s.nlink!==1)))throw new SetupError('managed-migration-conflict'); - } - if((m.fresh.directory.kind==='directory'||m.created.directory)&&!lstatSync(path.dirname(journal.database),{throwIfNoEntry:false})?.isDirectory()|| - (m.fresh.database.kind==='file'||m.created.database)&&!lstatSync(journal.database,{throwIfNoEntry:false})?.isFile()||before!==journalSnapshot(file)) - throw new SetupError('managed-migration-conflict'); - return journal; - }); + const file=migrationFile(env),root=path.dirname(file); + if(!lstatSync(root,{throwIfNoEntry:false}))return; + if(lstatSync(path.join(root,'.ownership.json'),{throwIfNoEntry:false})?.nlink!==1)throw new SetupError('managed-binding-invalid'); + const names=readdirSync(root); + if(names.includes('.configuration-lock'))throw new SetupError('managed-configuration-busy'); + if(names.some(n=>n.startsWith('migration.json.stage-')||n.startsWith('progress-binding.json.stage-')))throw new SetupError('managed-migration-conflict'); + const stat=lstatSync(file,{throwIfNoEntry:false});if(!stat)return; + managedPath(file); + if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1||!privatePaths([root,file]))throw new SetupError('managed-migration-conflict'); + if(stat.size>MANAGED_STEP_LIMITS.journalBytes)throw new SetupError('managed-step-limit'); + const before=journalSnapshot(file),journal=parseManagedFreshStepJournal(readFileSync(file)),roots=managedSourceRoots(env),m=journal.migration; + if(journal.source.configRoot!==roots.configRoot||journal.source.dataRoot!==roots.dataRoot|| + [roots.configRoot,roots.dataRoot,root].includes(path.dirname(journal.database))|| + ![roots.configRoot,roots.dataRoot].every(p=>lstatSync(p).isDirectory()&&isOwned(p)))throw new SetupError('managed-migration-conflict'); + for(const [p,directory] of [[path.dirname(journal.database),true],[journal.database,false],...m.fresh.sidecars.map(c=>[c.path,false] as const)] as const){ + managedPath(p,true);const s=lstatSync(p,{throwIfNoEntry:false}); + if(s&&(!privatePaths([p])||s.isSymbolicLink()||(directory?!s.isDirectory():!s.isFile()||s.nlink!==1)))throw new SetupError('managed-migration-conflict'); + } + if((m.fresh.directory.kind==='directory'||m.created.directory)&&!lstatSync(path.dirname(journal.database),{throwIfNoEntry:false})?.isDirectory()|| + (m.fresh.database.kind==='file'||m.created.database)&&!lstatSync(journal.database,{throwIfNoEntry:false})?.isFile()||before!==journalSnapshot(file)) + throw new SetupError('managed-migration-conflict'); + return journal; } /** Journal observation, not Store admission. This reader validates the private * envelope/roots and consistency only; each engine effect must freshly validate * its complete claims, lifecycle ownership and actual Store/source/schema. */ export function readManagedStepJournal(env:NodeJS.ProcessEnv):ManagedStepJournal|undefined { - return platformSecurityScope(()=>{ - const file=migrationFile(env),root=path.dirname(file); - if(!lstatSync(root,{throwIfNoEntry:false}))return; - if(lstatSync(path.join(root,'.ownership.json'),{throwIfNoEntry:false})?.nlink!==1)throw new SetupError('managed-binding-invalid'); - // Never sweep interrupted publication or a retained old configuration lock. - const names=readdirSync(root); - if(names.includes('.configuration-lock'))throw new SetupError('managed-configuration-busy'); - if(names.some(name=>name.startsWith('migration.json.stage-')))throw new SetupError('managed-migration-conflict'); - const stat=lstatSync(file,{throwIfNoEntry:false});if(!stat)return; - managedPath(file); - if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1||!privatePaths([root,file]))throw new SetupError('managed-migration-conflict'); - if(stat.size>MANAGED_STEP_LIMITS.journalBytes)throw new SetupError('managed-step-limit'); - const before=journalSnapshot(file),journal=parseManagedStepJournal(readFileSync(file)); - // Retain the existing Binding owner's native path/identity checks, including - // actual roots. Parsing the saved claims does not replace those checks. - const binding=readBinding(file),roots=managedSourceRoots(env); - if(canonical(managedJournalBinding(binding))!==canonical(managedJournalBinding(journal))|| - journal.source.configRoot!==roots.configRoot||journal.source.dataRoot!==roots.dataRoot|| - [roots.configRoot,roots.dataRoot,root].includes(path.dirname(journal.database))|| - ![roots.configRoot,roots.dataRoot].every(p=>lstatSync(p).isDirectory()&&isOwned(p))|| - before!==journalSnapshot(file))throw new SetupError('managed-migration-conflict'); - return journal; - }); + const file=migrationFile(env),root=path.dirname(file); + if(!lstatSync(root,{throwIfNoEntry:false}))return; + if(lstatSync(path.join(root,'.ownership.json'),{throwIfNoEntry:false})?.nlink!==1)throw new SetupError('managed-binding-invalid'); + // Never sweep interrupted publication or a retained old configuration lock. + const names=readdirSync(root); + if(names.includes('.configuration-lock'))throw new SetupError('managed-configuration-busy'); + if(names.some(name=>name.startsWith('migration.json.stage-')))throw new SetupError('managed-migration-conflict'); + const stat=lstatSync(file,{throwIfNoEntry:false});if(!stat)return; + managedPath(file); + if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1||!privatePaths([root,file]))throw new SetupError('managed-migration-conflict'); + if(stat.size>MANAGED_STEP_LIMITS.journalBytes)throw new SetupError('managed-step-limit'); + const before=journalSnapshot(file),journal=parseManagedStepJournal(readFileSync(file)); + // Retain the existing Binding owner's native path/identity checks, including + // actual roots. Parsing the saved claims does not replace those checks. + const binding=readBinding(file),roots=managedSourceRoots(env); + if(canonical(managedJournalBinding(binding))!==canonical(managedJournalBinding(journal))|| + journal.source.configRoot!==roots.configRoot||journal.source.dataRoot!==roots.dataRoot|| + [roots.configRoot,roots.dataRoot,root].includes(path.dirname(journal.database))|| + ![roots.configRoot,roots.dataRoot].every(p=>lstatSync(p).isDirectory()&&isOwned(p))|| + before!==journalSnapshot(file))throw new SetupError('managed-migration-conflict'); + return journal; } /** Guard journal evolution as well as its syntax. This is not a writer lock or @@ -257,14 +241,14 @@ export function validateManagedJournalChange(prior:ManagedSetupStepJournal,next: * expected is a compare-before-publication claim, not authority or an OS lock. */ export function writeManagedStepJournal(env:NodeJS.ProcessEnv,next:ManagedSetupStepJournal,expected?:ManagedSetupStepJournal,validate?:()=>void):void { publishManagedJournal(env,next,expected,validate); - const written=platformSecurityScope(()=>{if(windows)windowsPaths(managedJournalPaths(next),true);return next.migration.format===3?readManagedFreshStepJournal(env):readManagedStepJournal(env);}); + const written=(()=>{if(windows)windowsPaths(managedJournalPaths(next),true);return next.migration.format===3?readManagedFreshStepJournal(env):readManagedStepJournal(env);})(); if(!written||canonical(written)!==canonical(next))throw new SetupError('managed-step-unsettled'); } /** Publish only an unsequenced intent. Unlike a settled checkpoint, this is not * a successful action receipt. The effect owner MUST read it back and compare * it in its fresh admission batch before any effect (see recordMigrationRemoval). - * Combining those reads avoids a redundant launch without reusing authority + * Combining those reads avoids a redundant read without reusing authority * across a mutation. A crash here leaves running/unsettled, never completion. */ export function publishManagedStepIntent(env:NodeJS.ProcessEnv,next:ManagedSetupStepJournal,expected:ManagedSetupStepJournal,validate:()=>void):void { if(next.migration.state!=='running'||!next.migration.intent||next.migration.sequence!==expected.migration.sequence) @@ -273,7 +257,7 @@ export function publishManagedStepIntent(env:NodeJS.ProcessEnv,next:ManagedSetup } /** Read-only exact intent admission; caller may prebatch known paths in this - * same scope, but must end it before the effect. No prior ACL verdict is used. */ + * same read, and no result is carried across the effect. */ export function validatePublishedManagedIntent(env:NodeJS.ProcessEnv,expected:ManagedSetupStepJournal):void { const current=expected.migration.format===3?readManagedFreshStepJournal(env):readManagedStepJournal(env); if(expected.migration.state!=='running'||!expected.migration.intent||!current||canonical(current)!==canonical(expected)) @@ -298,7 +282,7 @@ export function upgradeManagedStepJournal(env:NodeJS.ProcessEnv,next:ManagedStep validateInitialManagedCheckpoint(checked); if(expected.phase==='complete'||canonical(managedJournalBinding(checked))!==canonical(expected.binding)|| m.legacyInstallId!==expected.legacyInstallId||m.capture.state!=='unknown')throw new SetupError('managed-step-conflict'); - const file=platformSecurityScope(()=>{ + const file=(()=>{ if(windows)windowsPaths(managedJournalPaths(checked),true); // Reuse the strict journal reader's container refusals even though its // format-2 parser cannot be used until after the upgrade. @@ -322,9 +306,9 @@ export function upgradeManagedStepJournal(env:NodeJS.ProcessEnv,next:ManagedStep } validate?.(); return file; - }); + })(); requirePlatformWriteBoundary();publishPrivateJson(file,checked,true); - const written=platformSecurityScope(()=>{if(windows)windowsPaths(managedJournalPaths(checked),true);return readManagedStepJournal(env);}); + const written=(()=>{if(windows)windowsPaths(managedJournalPaths(checked),true);return readManagedStepJournal(env);})(); if(!written||canonical(written)!==canonical(checked))throw new SetupError('managed-step-unsettled'); } @@ -333,7 +317,7 @@ function publishManagedJournal(env:NodeJS.ProcessEnv,next:ManagedSetupStepJourna // Parse serialized bytes before touching product state (also enforces limits). const checked=next.migration.format===3?parseManagedFreshStepJournal(JSON.stringify(next)):parseManagedStepJournal(JSON.stringify(next)); const known=managedJournalPaths(checked); - const file=platformSecurityScope(()=>{ + const file=(()=>{ if(windows)windowsPaths(known,true); const current=checked.migration.format===3?readManagedFreshStepJournal(env):readManagedStepJournal(env); if(expected? !current||canonical(current)!==canonical(expected):!!current)throw new SetupError('managed-step-conflict'); @@ -344,11 +328,10 @@ function publishManagedJournal(env:NodeJS.ProcessEnv,next:ManagedSetupStepJourna const roots=managedSourceRoots(env); if(checked.source.configRoot!==roots.configRoot||checked.source.dataRoot!==roots.dataRoot|| [roots.configRoot,roots.dataRoot,root].includes(path.dirname(checked.database)))throw new SetupError('managed-migration-conflict'); - // Engine-supplied lifecycle/Store verification shares only this fresh read - // batch. It is never run under the effect's earlier security scope. + // Engine-supplied lifecycle/Store verification runs in this same fresh read. validate?.(); return file; - }); + })(); requirePlatformWriteBoundary(); publishPrivateJson(file,checked,!!expected); } diff --git a/setup/managed-observation.ts b/setup/managed-observation.ts index 4ab9e46..1b4952c 100644 --- a/setup/managed-observation.ts +++ b/setup/managed-observation.ts @@ -3,7 +3,7 @@ import path from 'node:path'; import {readManagedBinding,managedBindingFile,ManagedBindingError,managedSourceRoots,managedExpectationFile,readManagedExpectation} from '../shared/managed-binding.ts'; import {Store,canonical,digest} from '../shared/store.ts'; import {verifyStore,type Binding} from '../shared/binding.ts'; -import {platformSecurityScope,requirePlatformWriteBoundary,requirePlatformStoreFence,windows,windowsPaths,PlatformError} from '../shared/platform.ts'; +import {requirePlatformWriteBoundary,requirePlatformStoreFence,windows,windowsPaths,PlatformError} from '../shared/platform.ts'; import {ProgressError,type SetupRead} from '../shared/progress.ts'; import {MANAGED_STEP_LIMITS} from '../shared/managed-steps.ts'; import {readManagedStepJournal,readManagedFreshStepJournal,readMigration,migrationFile,managedJournalPaths} from './managed-migration.ts'; @@ -78,70 +78,68 @@ export function observeManagedSetup(env:NodeJS.ProcessEnv,expectedDescriptor?:st } } function readSetup(env:NodeJS.ProcessEnv,expectedDescriptor?:string|null,family?:(fresh:boolean)=>void) { - return platformSecurityScope(()=>{ - const {binding:b,descriptor,journal,prior,legacy}=selection(env,expectedDescriptor,family); - const retained=b??journal??prior?.binding; - const base:SetupRead={configured:!!b,verified:false,installed:false,captureEnabled:null,targets:b?{configRoot:b.source.configRoot,dataRoot:b.source.dataRoot,storeRoot:path.dirname(b.database)}:null, - version:null,activation:'unknown',separateLifecycle:false,historyRetained:true,diagnostics:[], - delivery:{kind:'managed',revision:1,managedMigrationSteps:1,managedFreshSteps:1,configuration:b?'configured':'unconfigured',migration:journal?journal.migration.state==='complete'?legacy?'conflict':'complete':'pending':prior?prior.phase==='complete'?legacy?'conflict':'complete':'pending':legacy?'available':'none', - ...((journal?journal.migration.format===3:!prior&&!legacy)?{planKind:'fresh' as const}:{}), - mode:'unknown',observation:'unknown',expectedVersion:null}}; - if(journal){ - if(journal.migration.format===3)base.delivery!.freshProgress=managedFreshJournalProgress(journal as ManagedFreshStepJournal); - else base.delivery!.migrationProgress=managedJournalProgress(journal as ManagedStepJournal); + const {binding:b,descriptor,journal,prior,legacy}=selection(env,expectedDescriptor,family); + const retained=b??journal??prior?.binding; + const base:SetupRead={configured:!!b,verified:false,installed:false,captureEnabled:null,targets:b?{configRoot:b.source.configRoot,dataRoot:b.source.dataRoot,storeRoot:path.dirname(b.database)}:null, + version:null,activation:'unknown',separateLifecycle:false,historyRetained:true,diagnostics:[], + delivery:{kind:'managed',revision:1,managedMigrationSteps:1,managedFreshSteps:1,configuration:b?'configured':'unconfigured',migration:journal?journal.migration.state==='complete'?legacy?'conflict':'complete':'pending':prior?prior.phase==='complete'?legacy?'conflict':'complete':'pending':legacy?'available':'none', + ...((journal?journal.migration.format===3:!prior&&!legacy)?{planKind:'fresh' as const}:{}), + mode:'unknown',observation:'unknown',expectedVersion:null}}; + if(journal){ + if(journal.migration.format===3)base.delivery!.freshProgress=managedFreshJournalProgress(journal as ManagedFreshStepJournal); + else base.delivery!.migrationProgress=managedJournalProgress(journal as ManagedStepJournal); + } + if(!retained)return {status:base,descriptor,journal,subagentRuns:false}; + // Selection is independently validated. A refused Store must not erase it + // or promote partial observations into capture/identity authority. + const unavailable=structuredClone(base); + try{ + if(journal?.migration.format===3){ + if(windows)windowsPaths(managedJournalPaths(journal),true); + const observed=observeManagedFreshStore(journal as ManagedFreshStepJournal); + base.delivery!.freshProgress=managedFreshJournalProgress(journal as ManagedFreshStepJournal,observed); + base.captureEnabled=observed.state==='unknown'?null:observed.state==='on'; + // A proposed source/absent database is not ordinary Binding admission. + // Read-only progress can still honestly show unknown or initialized off. + if(!b)return {status:base,descriptor,journal,subagentRuns:false}; } - if(!retained)return {status:base,descriptor,journal,subagentRuns:false}; - // Selection is independently validated. A refused Store must not erase it - // or promote partial observations into capture/identity authority. - const unavailable=structuredClone(base); + storePaths(retained); + const store=new Store(retained.database,{readOnly:true}); try{ - if(journal?.migration.format===3){ - if(windows)windowsPaths(managedJournalPaths(journal),true); - const observed=observeManagedFreshStore(journal as ManagedFreshStepJournal); - base.delivery!.freshProgress=managedFreshJournalProgress(journal as ManagedFreshStepJournal,observed); - base.captureEnabled=observed.state==='unknown'?null:observed.state==='on'; - // A proposed source/absent database is not ordinary Binding admission. - // Read-only progress can still honestly show unknown or initialized off. - if(!b)return {status:base,descriptor,journal,subagentRuns:false}; + verifyStore(store,retained);const runs=store.subagentRunStorage(); + base.captureEnabled=store.list({limit:1}).captureEnabled; + if(journal){ + const capture={state:base.captureEnabled?'on' as const:'off' as const,observedAt:new Date().toISOString()}; + if(journal.migration.format===3)base.delivery!.freshProgress=managedFreshJournalProgress(journal as ManagedFreshStepJournal,capture); + else base.delivery!.migrationProgress=managedJournalProgress(journal as ManagedStepJournal,capture); } - storePaths(retained); - const store=new Store(retained.database,{readOnly:true}); - try{ - verifyStore(store,retained);const runs=store.subagentRunStorage(); - base.captureEnabled=store.list({limit:1}).captureEnabled; - if(journal){ - const capture={state:base.captureEnabled?'on' as const:'off' as const,observedAt:new Date().toISOString()}; - if(journal.migration.format===3)base.delivery!.freshProgress=managedFreshJournalProgress(journal as ManagedFreshStepJournal,capture); - else base.delivery!.migrationProgress=managedJournalProgress(journal as ManagedStepJournal,capture); - } - if(b){ - base.verified=b.source.verified;base.reportingIdentity={storeId:b.storeId,sourceId:b.source.id,verified:b.source.verified}; - const expected=readManagedExpectation(b); - if(expected){base.version=expected.version;base.delivery!.expectedVersion=expected.version; - const loaded=store.loadedFingerprint(b.source.id,b.installId);base.delivery!.observation=loaded===null?'not-observed':loaded===expected.fingerprint?'matching':'different';} - } - return {status:base,descriptor,journal,subagentRuns:!!b&&['current','previous'].includes(runs)}; - }finally{store.close();} - }catch(error){ - unavailable.diagnostics=[observationDiagnostic(error)]; - if(journal?.migration.format===3&&journal.migration.created.database===null&&journal.migration.state!=='complete'){ - // Only uncheckpointed creation lacks the evidence for a Resume card. - // Later read failures retain pending/complete progress with unknown capture. - unavailable.delivery!.migration='unavailable'; - delete unavailable.delivery!.freshProgress; + if(b){ + base.verified=b.source.verified;base.reportingIdentity={storeId:b.storeId,sourceId:b.source.id,verified:b.source.verified}; + const expected=readManagedExpectation(b); + if(expected){base.version=expected.version;base.delivery!.expectedVersion=expected.version; + const loaded=store.loadedFingerprint(b.source.id,b.installId);base.delivery!.observation=loaded===null?'not-observed':loaded===expected.fingerprint?'matching':'different';} } - return {status:unavailable,descriptor,journal,subagentRuns:false}; + return {status:base,descriptor,journal,subagentRuns:!!b&&['current','previous'].includes(runs)}; + }finally{store.close();} + }catch(error){ + unavailable.diagnostics=[observationDiagnostic(error)]; + if(journal?.migration.format===3&&journal.migration.created.database===null&&journal.migration.state!=='complete'){ + // Only uncheckpointed creation lacks the evidence for a Resume card. + // Later read failures retain pending/complete progress with unknown capture. + unavailable.delivery!.migration='unavailable'; + delete unavailable.delivery!.freshProgress; } - }); + return {status:unavailable,descriptor,journal,subagentRuns:false}; + } } /** Ordinary capture-off remains available without full legacy ownership. Enable * cannot bypass unfinished migration. The supervisor holds the shared writer - * fence; the fresh read scope ends before changing the capture bit. */ + * fence; the fresh read ends before changing the capture bit. */ export function controlManagedCapture(env:NodeJS.ProcessEnv,enabled:boolean,expectedDescriptor?:string|null) { requirePlatformWriteBoundary();let store:Store|undefined,descriptor:string|null=null; try{ - platformSecurityScope(()=>{ + { const current=enabled?selection(env,expectedDescriptor):{...selected(env,expectedDescriptor),journal:undefined,prior:undefined,legacy:false}; const {binding,journal,prior,legacy}=current;descriptor=current.descriptor; if(!binding)throw new SetupError('binding'); @@ -149,7 +147,7 @@ export function controlManagedCapture(env:NodeJS.ProcessEnv,enabled:boolean,expe if(!binding.source.verified)throw new SetupError('source-unverified'); if(enabled&&(legacy||(journal?journal.migration.state!=='complete':prior?prior.phase!=='complete':false)))throw new SetupError('managed-migration-required'); storePaths(binding);store=new Store(binding.database);verifyStore(store,binding);store.subagentRunStorage(); - }); + } requirePlatformWriteBoundary();store!.setEnabled(enabled); return {value:{ok:true,captureEnabled:enabled},descriptor}; }finally{store?.close();} diff --git a/setup/managed-step-effects.ts b/setup/managed-step-effects.ts index 208b7db..51c32e9 100644 --- a/setup/managed-step-effects.ts +++ b/setup/managed-step-effects.ts @@ -4,7 +4,7 @@ import {Store,canonical,digest} from '../shared/store.ts'; import {verifyStore} from '../shared/binding.ts'; import {activationFingerprint} from '../shared/activation.ts'; import {managedBindingFile,managedExpectationFile,managedPath,publishPrivateJson,readManagedBinding,readManagedExpectation} from '../shared/managed-binding.ts'; -import {platformSecurityScope,requirePlatformWriteBoundary,requirePlatformStoreFence,privateDirectory,windows,windowsPaths,privatePaths} from '../shared/platform.ts'; +import {requirePlatformWriteBoundary,requirePlatformStoreFence,privateDirectory,windows,windowsPaths,privatePaths} from '../shared/platform.ts'; import {MANAGED_STEP_LIMITS,type ManagedCaptureObservation,type ManagedStepRef} from '../shared/managed-steps.ts'; import {SetupError,validateMigrationRemoval,removeMigrationFile,migrationRemovalRecordClaims,recordMigrationRemoval,migrationRemovalRecorded,migrationRemovalComplete,type Payload} from './lifecycle.ts'; import {managedJournalBinding,type ManagedStepJournal,type ManagedFreshStepJournal,type ManagedSetupStepJournal,type ManagedPathClaim,type ManagedStepIntent} from './managed-step-journal.ts'; @@ -59,77 +59,73 @@ function freshCapture(journal:ManagedFreshStepJournal,created?:ManagedCreationRe return observeManagedFreshStore(j); } export function validateManagedStepTarget(env:NodeJS.ProcessEnv,payload:Payload,journal:ManagedSetupStepJournal,created?:ManagedCreationResult) { - return platformSecurityScope(()=>{ - if(windows)windowsPaths(managedJournalPaths(journal),true); - const current=journal.migration.format===3?readManagedFreshStepJournal(env):readManagedStepJournal(env);need(current&&canonical(current)===canonical(journal)); - const m=journal.migration,binding=managedJournalBinding(journal); - need(payload.plugin&&payload.guidance&&payload.version===m.expectation.version&& - activationFingerprint({...binding,version:payload.version},Buffer.from(payload.plugin),Buffer.from(payload.guidance))===m.expectation.fingerprint,'managed-review-stale'); - const selector=managedBindingFile(env),expectedFile=managedExpectationFile(journal); - for(const file of [selector,expectedFile]){ - if(lstatSync(path.dirname(file),{throwIfNoEntry:false}))need(!readdirSync(path.dirname(file)).some(n=>n.startsWith(path.basename(file)+'.stage-')),'managed-migration-conflict'); - fileClaim(file); // Include hard-link and bounded-file checks before the existing readers. - } - const selected=readManagedBinding(env),expected=readManagedExpectation(journal); - need(!selected||canonical(selected)===canonical(binding),'managed-selection-conflict'); - if(completed(journal,'expectation'))need(expected&&canonical(expected)===canonical(expectation(journal)),'managed-review-stale'); - if(completed(journal,'publish-binding'))need(selected,'managed-migration-conflict'); - let capture:ManagedCaptureObservation; - if(m.format===3){ - need(!lstatSync(m.fresh.legacy.path,{throwIfNoEntry:false}),'managed-migration-conflict'); - capture=freshCapture(journal as ManagedFreshStepJournal,created); - if(m.fresh.storeMode==='create'&&lstatSync(path.dirname(journal.database),{throwIfNoEntry:false})){ - const allowed=new Set([path.basename(journal.database),...['-journal','-wal','-shm'].map(s=>path.basename(journal.database)+s),path.basename(expectedFile)]); - need(readdirSync(path.dirname(journal.database)).every(n=>allowed.has(n)),'foreign-files'); - // No fresh setup step other than enable can turn capture on. Later - // manual disable is allowed, including on complete/reconcile replay. - if(!completed(journal,'enable')&&m.step?.name!=='enable')need(capture.state!=='on','managed-step-unsettled'); - } - // Reconnection explicitly reviews this package for the retained source. - // The reader already requires the same Store/source/install identity; the - // expectation intent freezes its prior bytes before atomic replacement. - const reconnect=m.fresh.storeMode==='retain'&&m.fresh.sourceMode==='reuse'&&!completed(journal,'expectation'); - if(expected&&!reconnect)need(canonical(expected)===canonical(expectation(journal)),'managed-review-stale'); - if(selected)need(completed(journal,'publish-binding')||m.intent?.step.name==='publish-binding','managed-selection-conflict'); - }else if(m.legacy.kind==='manifest'){ - capture=validateMigrationRemoval(journal as ManagedStepJournal).capture; - if(completed(journal,'record-removal'))need(migrationRemovalComplete(journal as ManagedStepJournal),'managed-migration-conflict'); - }else{ - need(readRemovalReceipt({binding,phase:'removed',legacyInstallId:m.legacyInstallId},m.legacy.receipt),'managed-migration-conflict'); - capture=observeCapture(journal as ManagedStepJournal); + if(windows)windowsPaths(managedJournalPaths(journal),true); + const current=journal.migration.format===3?readManagedFreshStepJournal(env):readManagedStepJournal(env);need(current&&canonical(current)===canonical(journal)); + const m=journal.migration,binding=managedJournalBinding(journal); + need(payload.plugin&&payload.guidance&&payload.version===m.expectation.version&& + activationFingerprint({...binding,version:payload.version},Buffer.from(payload.plugin),Buffer.from(payload.guidance))===m.expectation.fingerprint,'managed-review-stale'); + const selector=managedBindingFile(env),expectedFile=managedExpectationFile(journal); + for(const file of [selector,expectedFile]){ + if(lstatSync(path.dirname(file),{throwIfNoEntry:false}))need(!readdirSync(path.dirname(file)).some(n=>n.startsWith(path.basename(file)+'.stage-')),'managed-migration-conflict'); + fileClaim(file); // Include hard-link and bounded-file checks before the existing readers. + } + const selected=readManagedBinding(env),expected=readManagedExpectation(journal); + need(!selected||canonical(selected)===canonical(binding),'managed-selection-conflict'); + if(completed(journal,'expectation'))need(expected&&canonical(expected)===canonical(expectation(journal)),'managed-review-stale'); + if(completed(journal,'publish-binding'))need(selected,'managed-migration-conflict'); + let capture:ManagedCaptureObservation; + if(m.format===3){ + need(!lstatSync(m.fresh.legacy.path,{throwIfNoEntry:false}),'managed-migration-conflict'); + capture=freshCapture(journal as ManagedFreshStepJournal,created); + if(m.fresh.storeMode==='create'&&lstatSync(path.dirname(journal.database),{throwIfNoEntry:false})){ + const allowed=new Set([path.basename(journal.database),...['-journal','-wal','-shm'].map(s=>path.basename(journal.database)+s),path.basename(expectedFile)]); + need(readdirSync(path.dirname(journal.database)).every(n=>allowed.has(n)),'foreign-files'); + // No fresh setup step other than enable can turn capture on. Later + // manual disable is allowed, including on complete/reconcile replay. + if(!completed(journal,'enable')&&m.step?.name!=='enable')need(capture.state!=='on','managed-step-unsettled'); } - return capture; - }); + // Reconnection explicitly reviews this package for the retained source. + // The reader already requires the same Store/source/install identity; the + // expectation intent freezes its prior bytes before atomic replacement. + const reconnect=m.fresh.storeMode==='retain'&&m.fresh.sourceMode==='reuse'&&!completed(journal,'expectation'); + if(expected&&!reconnect)need(canonical(expected)===canonical(expectation(journal)),'managed-review-stale'); + if(selected)need(completed(journal,'publish-binding')||m.intent?.step.name==='publish-binding','managed-selection-conflict'); + }else if(m.legacy.kind==='manifest'){ + capture=validateMigrationRemoval(journal as ManagedStepJournal).capture; + if(completed(journal,'record-removal'))need(migrationRemovalComplete(journal as ManagedStepJournal),'managed-migration-conflict'); + }else{ + need(readRemovalReceipt({binding,phase:'removed',legacyInstallId:m.legacyInstallId},m.legacy.receipt),'managed-migration-conflict'); + capture=observeCapture(journal as ManagedStepJournal); + } + return capture; } /** Freeze one effect's before/after claims, while admission is still read-only. */ export function managedStepEffectClaims(env:NodeJS.ProcessEnv,payload:Payload,journal:ManagedSetupStepJournal):Pick { - return platformSecurityScope(()=>{ - const captureBefore=validateManagedStepTarget(env,payload,journal),m=journal.migration; - need(m.step&&m.step.name!=='prepare'&&!m.intent); - if(m.format===3&&(m.step.name==='store-directory'||m.step.name==='create-store')){ - const directory=m.step.name==='store-directory',before=directory?m.fresh.directory:m.fresh.database; - need(before.kind==='absent'); - return {before:[before],after:[{path:before.path,kind:directory?'directory':'file',object:null,digest:null}],captureBefore}; - } - if(m.step.name==='record-removal'){ - const claims=migrationRemovalRecordClaims(journal as ManagedStepJournal);return {before:claims.before,after:claims.after,captureBefore:claims.capture}; - } - if(['remove-selector','remove-discovery'].includes(m.step.name)){ - const layout=validateMigrationRemoval(journal as ManagedStepJournal),file=layout.file(m.step as ManagedStepRef);need(file&&captureBefore.state==='off'); - return {before:[layout.claims.get(file)!],after:[{path:file,kind:'absent',object:null,digest:null}],captureBefore}; - } - if(m.step.name==='expectation'||m.step.name==='publish-binding'){ - const file=m.step.name==='expectation'?managedExpectationFile(journal):managedBindingFile(env),before=fileClaim(file); - const value=m.step.name==='expectation'?expectation(journal):managedJournalBinding(journal); - // Existing identical selections are reconciled, never rewritten merely - // to impose JSON key ordering or manufacture a new file identity. - const after=m.step.name==='publish-binding'&&before.kind==='file'?before: - {path:file,kind:'file' as const,object:null,digest:digest(JSON.stringify(value))}; - return {before:[before],after:[after],captureBefore}; - } - return {before:[],after:[],captureBefore}; - }); + const captureBefore=validateManagedStepTarget(env,payload,journal),m=journal.migration; + need(m.step&&m.step.name!=='prepare'&&!m.intent); + if(m.format===3&&(m.step.name==='store-directory'||m.step.name==='create-store')){ + const directory=m.step.name==='store-directory',before=directory?m.fresh.directory:m.fresh.database; + need(before.kind==='absent'); + return {before:[before],after:[{path:before.path,kind:directory?'directory':'file',object:null,digest:null}],captureBefore}; + } + if(m.step.name==='record-removal'){ + const claims=migrationRemovalRecordClaims(journal as ManagedStepJournal);return {before:claims.before,after:claims.after,captureBefore:claims.capture}; + } + if(['remove-selector','remove-discovery'].includes(m.step.name)){ + const layout=validateMigrationRemoval(journal as ManagedStepJournal),file=layout.file(m.step as ManagedStepRef);need(file&&captureBefore.state==='off'); + return {before:[layout.claims.get(file)!],after:[{path:file,kind:'absent',object:null,digest:null}],captureBefore}; + } + if(m.step.name==='expectation'||m.step.name==='publish-binding'){ + const file=m.step.name==='expectation'?managedExpectationFile(journal):managedBindingFile(env),before=fileClaim(file); + const value=m.step.name==='expectation'?expectation(journal):managedJournalBinding(journal); + // Existing identical selections are reconciled, never rewritten merely + // to impose JSON key ordering or manufacture a new file identity. + const after=m.step.name==='publish-binding'&&before.kind==='file'?before: + {path:file,kind:'file' as const,object:null,digest:digest(JSON.stringify(value))}; + return {before:[before],after:[after],captureBefore}; + } + return {before:[],after:[],captureBefore}; } function matchesAfter(actual:ManagedPathClaim,expected:ManagedPathClaim) { @@ -154,38 +150,36 @@ function publication(journal:ManagedSetupStepJournal,env:NodeJS.ProcessEnv) { /** Read-only evidence for the CURRENT durable intent. Capture with an opposite * bit is ambiguous, not permission to repeat a disable/enable. */ export function managedStepEffectCommitted(env:NodeJS.ProcessEnv,payload:Payload,journal:ManagedSetupStepJournal,created?:ManagedCreationResult) { - return platformSecurityScope(()=>{ - const capture=validateManagedStepTarget(env,payload,journal,created),m=journal.migration; - need(m.intent&&m.step); - // Resume retains the intent in pending state. Projection is read-only and - // used only by lifecycle evidence checks which require a running intent; - // actual effects still admit the exact running journal below. - const evidence=structuredClone(journal);evidence.migration.state='running'; - if(m.state==='running')validatePublishedManagedIntent(env,journal); - let committed:boolean; - if(m.step.name==='expectation'||m.step.name==='publish-binding')committed=publication(journal,env).committed; - else if(m.format===3&&['store-directory','create-store'].includes(m.step.name)){ - const directory=m.step.name==='store-directory',file=directory?path.dirname(journal.database):journal.database; - need(canonical(m.intent.before)===canonical([{path:file,kind:'absent',object:null,digest:null}])&& - canonical(m.intent.after)===canonical([{path:file,kind:directory?'directory':'file',object:null,digest:null}])); - // An uncheckpointed directory is deliberately NOT adopted after restart. - // Only the immediate exclusive-creation result admits that completion. - committed=directory?!!created?.directory:capture.state==='off'; - } - else if(m.format===3&&m.step.name==='register-source'){ - need(m.intent.before.length===0&&m.intent.after.length===0); - const store=new Store(journal.database,{readOnly:true});try{committed=store.list({limit:1}).sources.some(s=>canonical(s)===canonical(journal.source));}finally{store.close();} - } - else if(m.step.name==='record-removal')committed=migrationRemovalRecorded(evidence as ManagedStepJournal); - else if(m.step.name==='remove-selector'||m.step.name==='remove-discovery'){ - const layout=validateMigrationRemoval(journal as ManagedStepJournal),file=layout.file(m.step);need(file&&layout.intentFor(file)); - committed=!lstatSync(file,{throwIfNoEntry:false}); - }else{ - need(m.intent.before.length===0&&m.intent.after.length===0); - committed=m.step.name==='reconcile'||capture.state===(m.step.name==='enable'?'on':'off'); - } - return {committed,capture}; - }); + const capture=validateManagedStepTarget(env,payload,journal,created),m=journal.migration; + need(m.intent&&m.step); + // Resume retains the intent in pending state. Projection is read-only and + // used only by lifecycle evidence checks which require a running intent; + // actual effects still admit the exact running journal below. + const evidence=structuredClone(journal);evidence.migration.state='running'; + if(m.state==='running')validatePublishedManagedIntent(env,journal); + let committed:boolean; + if(m.step.name==='expectation'||m.step.name==='publish-binding')committed=publication(journal,env).committed; + else if(m.format===3&&['store-directory','create-store'].includes(m.step.name)){ + const directory=m.step.name==='store-directory',file=directory?path.dirname(journal.database):journal.database; + need(canonical(m.intent.before)===canonical([{path:file,kind:'absent',object:null,digest:null}])&& + canonical(m.intent.after)===canonical([{path:file,kind:directory?'directory':'file',object:null,digest:null}])); + // An uncheckpointed directory is deliberately NOT adopted after restart. + // Only the immediate exclusive-creation result admits that completion. + committed=directory?!!created?.directory:capture.state==='off'; + } + else if(m.format===3&&m.step.name==='register-source'){ + need(m.intent.before.length===0&&m.intent.after.length===0); + const store=new Store(journal.database,{readOnly:true});try{committed=store.list({limit:1}).sources.some(s=>canonical(s)===canonical(journal.source));}finally{store.close();} + } + else if(m.step.name==='record-removal')committed=migrationRemovalRecorded(evidence as ManagedStepJournal); + else if(m.step.name==='remove-selector'||m.step.name==='remove-discovery'){ + const layout=validateMigrationRemoval(journal as ManagedStepJournal),file=layout.file(m.step);need(file&&layout.intentFor(file)); + committed=!lstatSync(file,{throwIfNoEntry:false}); + }else{ + need(m.intent.before.length===0&&m.intent.after.length===0); + committed=m.step.name==='reconcile'||capture.state===(m.step.name==='enable'?'on':'off'); + } + return {committed,capture}; } /** One effect only. The caller has published running+intent under its worker @@ -207,20 +201,20 @@ export function applyManagedStepEffect(env:NodeJS.ProcessEnv,payload:Payload,jou return {directory:createdObject(path.dirname(journal.database),true)}; } if(m.format===3&&m.step.name==='create-store'){ - // Share the existing primitive's preflight; never add an outer scope across - // its exclusive reservation or inherit pre-create ACL authority. + // Share the existing primitive's preflight; never carry a result across + // its exclusive reservation. let committed=false; // The exact retained initialization may already be committed. Do not open // it writable as evidence or initialize an existing partial file. if(lstatSync(journal.database,{throwIfNoEntry:false})){ - platformSecurityScope(()=>{committed=managedStepEffectCommitted(env,payload,journal).committed;validatePublishedManagedIntent(env,journal);}); + committed=managedStepEffectCommitted(env,payload,journal).committed;validatePublishedManagedIntent(env,journal); need(committed,'managed-step-unsettled'); }else {const initialized=Store.createFresh(journal.database,{storeId:journal.storeId,validate});initialized.close();} return {database:createdObject(journal.database)}; } let store:Store|undefined; try{ - const prepared=platformSecurityScope(()=>{ + const prepared=(()=>{ const result=managedStepEffectCommitted(env,payload,journal); if(result.committed)return; if(m.step?.name==='expectation'||m.step?.name==='publish-binding')return publication(journal,env); @@ -231,7 +225,7 @@ export function applyManagedStepEffect(env:NodeJS.ProcessEnv,payload:Payload,jou need(result.capture.state===m.intent!.captureBefore.state,'managed-step-unsettled'); store=new Store(journal.database);verifyStore(store,journal);store.subagentRunStorage(); return; - }); + })(); requirePlatformWriteBoundary(); if(prepared)publishPrivateJson(prepared.file,prepared.value,prepared.replace); else if(store){if(m.step!.name==='register-source')store.registerSource(journal.source);else store.setEnabled(m.step!.name==='enable');} diff --git a/setup/managed-step-engine.ts b/setup/managed-step-engine.ts index d575d81..9190c51 100644 --- a/setup/managed-step-engine.ts +++ b/setup/managed-step-engine.ts @@ -1,7 +1,7 @@ import path from 'node:path'; import {SetupError,type Payload} from './lifecycle.ts'; import {managedSourceRoots,createManagedBindingDirectory} from '../shared/managed-binding.ts'; -import {platformSecurityScope,windows,windowsPaths,requirePlatformWriteBoundary,requirePlatformStoreFence,type PlatformRequestBudget} from '../shared/platform.ts'; +import {windows,windowsPaths,requirePlatformWriteBoundary,requirePlatformStoreFence,type PlatformRequestBudget} from '../shared/platform.ts'; import {managedJournalProgress,managedFreshJournalProgress,managedRequestDigest,parseManagedStepJournal,parseManagedFreshStepJournal,sameManagedStep,type ManagedStepJournal,type ManagedFreshStepJournal,type ManagedSetupStepJournal,type ManagedCaptureRenewal,type ManagedFreshCaptureRenewal,type ManagedFreshStepIntent} from './managed-step-journal.ts'; import {readManagedStepJournal,readManagedFreshStepJournal,writeManagedStepJournal,upgradeManagedStepJournal,publishManagedStepIntent,managedJournalPaths} from './managed-migration.ts'; import {validateManagedInspectionReview,validateManagedFreshInspectionReview,type ManagedInspectionSession,type ManagedFreshInspectionSession} from './managed-inspection.ts'; @@ -13,14 +13,12 @@ import {managedDiagnostic,ManagedStepFailure} from './managed-diagnostic.ts'; /** Bounded observation only. It does not admit a Store, infer capture, scan * legacy payloads, repair metadata or resume an interrupted operation. */ export function observeManagedStep(env:NodeJS.ProcessEnv,operationId?:string,version:1|2=1):ManagedSetupStepJournal|undefined { - return platformSecurityScope(()=>{ - const roots=managedSourceRoots(env),root=path.join(roots.dataRoot,'agent-progress-managed'); - if(windows)windowsPaths([roots.configRoot,roots.dataRoot,root,path.join(root,'.ownership.json'), - path.join(root,'migration.json'),path.join(root,'progress-binding.json')],true); - const journal=version===2?readManagedFreshStepJournal(env):readManagedStepJournal(env); - if(operationId&&journal?.migration.operationId!==operationId)throw new SetupError('not-found'); - return journal; - }); + const roots=managedSourceRoots(env),root=path.join(roots.dataRoot,'agent-progress-managed'); + if(windows)windowsPaths([roots.configRoot,roots.dataRoot,root,path.join(root,'.ownership.json'), + path.join(root,'migration.json'),path.join(root,'progress-binding.json')],true); + const journal=version===2?readManagedFreshStepJournal(env):readManagedStepJournal(env); + if(operationId&&journal?.migration.operationId!==operationId)throw new SetupError('not-found'); + return journal; } type InspectionSession=ManagedInspectionSession|ManagedFreshInspectionSession; @@ -72,19 +70,15 @@ export function beginManagedStep(env:NodeJS.ProcessEnv,payload:Payload,request:E parseJournal(next,request.version); const validate=()=>{validateReview(env,payload,session);}; if('prior' in reviewed&&reviewed.prior){ - // Admission used one batch. Reserve replacement + readback before the - // format-1 record can change; no directory, capture or removal effect here. - budget.require(2,6_000); + // No directory, capture or removal effect here; refuse past the deadline. + budget.require(); upgradeManagedStepJournal(env,next as ManagedStepJournal,reviewed.prior,validate); }else{ - // The unchanged directory helper costs three launches on a fresh target; - // journal publication and its readback cost two. At the specified 2.5s - // planning latency this leaves one second for non-security settlement. - budget.require(5,13_500); + budget.require(); createManagedBindingDirectory(env); - // An unexpectedly slow helper may leave a valid marker/missing journal. - // Refuse before publication; fresh explicit review can recover that state. - budget.require(2,6_000); + // A slow disk may leave a valid marker and a missing journal. Refuse before + // publication; fresh explicit review can recover that state. + budget.require(); writeManagedStepJournal(env,next,undefined,validate); } return {disposition:'applied',progress:managedSetupJournalProgress(next),journal:next}; @@ -108,14 +102,12 @@ function loadOperation(env:NodeJS.ProcessEnv,request:MutationRequest,hint?:Manag // Only trusted supervisor transport may supply hints. Even there, parse and // compare against the private durable record before following the claims. const known=parseJournal(hint,request.version); - return platformSecurityScope(()=>{ - if(windows)windowsPaths(managedJournalPaths(known),true); - const current=request.version===2?readManagedFreshStepJournal(env):readManagedStepJournal(env);need(current&¤t.migration.operationId===request.operationId,'not-found'); - // The hint only supplies prebatch paths. Another process may have advanced - // the same journal; use the freshly read record, never reject valid work or - // authorize it from the hint. Target validation batches any newly read paths. - return current; - }); + if(windows)windowsPaths(managedJournalPaths(known),true); + const current=request.version===2?readManagedFreshStepJournal(env):readManagedStepJournal(env);need(current&¤t.migration.operationId===request.operationId,'not-found'); + // The hint only supplies prebatch paths. Another process may have advanced + // the same journal; use the freshly read record, never reject valid work or + // authorize it from the hint. Target validation batches any newly read paths. + return current; } function renewalFor(request:MutationRequest,journal:ManagedSetupStepJournal):ManagedCaptureRenewal|ManagedFreshCaptureRenewal|undefined { if(request.action!=='advance')return; @@ -148,7 +140,7 @@ function advance(env:NodeJS.ProcessEnv,payload:Payload,request:Extract|undefined,evidence:ReturnType|undefined; - const prior=platformSecurityScope(()=>{ + const prior=(()=>{ const journal=loadOperation(env,request,hint); remember(journal); // Receipt replay never needs old payloads/legacy discovery or writes. The @@ -160,7 +152,7 @@ function advance(env:NodeJS.ProcessEnv,payload:Payload,request:Extract{validateManagedStepTarget(env,payload,prior);});} catch(error){ // Atomic rename can succeed before fsync/return fails. Do not report a // known pending/no-intent state when publication may already be durable. try{ - budget.require(1,3_500); - const current=platformSecurityScope(()=>{if(windows)windowsPaths(managedJournalPaths(running),true);return request.version===2?readManagedFreshStepJournal(env):readManagedStepJournal(env);}); + budget.require(); + const current=(()=>{if(windows)windowsPaths(managedJournalPaths(running),true);return request.version===2?readManagedFreshStepJournal(env):readManagedStepJournal(env);})(); if(current&&canonical(current)===canonical(running))published=true; else if(current&&canonical(current)===canonical(prior))return result(prior,'refused',unknownCapture,diagnostic(error,prior)); else return result(running,'refused',unknownCapture,diagnostic(error,running,true)); @@ -230,7 +219,7 @@ function advance(env:NodeJS.ProcessEnv,payload:Payload,request:Extract, budget:PlatformRequestBudget,hint:ManagedSetupStepJournal|undefined,session:InspectionSession|undefined,remember:(journal:ManagedSetupStepJournal)=>void):ManagedMutationResult { requirePlatformWriteBoundary(); - const admitted=platformSecurityScope(()=>{ + const admitted=(()=>{ const journal=loadOperation(env,request,hint); remember(journal); return {journal,capture:replay(request,journal)?unknownCapture:validateManagedStepTarget(env,payload,journal)}; - }); + })(); const prior=admitted.journal;let capture=admitted.capture; const repeated=replay(request,prior);if(repeated)return repeated; requirePlatformStoreFence(prior.database); @@ -280,7 +269,7 @@ function control(env:NodeJS.ProcessEnv,payload:Payload,request:Extract{validateManagedStepTarget(env,payload,prior);if(review)validateCaptureReview();}); return result(next,'applied',capture); } diff --git a/setup/managed-step-journal.ts b/setup/managed-step-journal.ts index 6f97905..eda269e 100644 --- a/setup/managed-step-journal.ts +++ b/setup/managed-step-journal.ts @@ -11,7 +11,7 @@ import { MANAGED_FRESH_STEPS, managedFreshPlan, type ManagedFreshStepRef, type M type ManagedFreshStepRequest, type ManagedFreshStepProgress, type ManagedFreshStepDiagnostic, type ManagedFreshStoreMode, type ManagedFreshSourceMode, type ManagedFreshCapturePolicy } from '../shared/managed-steps.ts'; -/** Claims only: fresh path/ACL/object/hash validation is mandatory before use. */ +/** Claims only: fresh path/object/hash validation is mandatory before use. */ export interface ManagedPathClaim { path: string; kind: 'directory' | 'file' | 'absent'; @@ -90,7 +90,7 @@ export interface ManagedStepJournal extends Binding { }; } -/** Immutable review facts. Native identities/hashes are observations, not ACL authority. +/** Immutable review facts. Native identities/hashes are observations, not authority. * Sidecars are always the three fixed SQLite suffixes in journal/wal/shm order. */ export interface ManagedFreshFacts { storeMode: ManagedFreshStoreMode; @@ -141,7 +141,7 @@ const text=(value:unknown,max=256):value is string=>typeof value==='string'&&val const version=(value:unknown)=>text(value)&&/^\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?$/i.test(value); function pathname(value:unknown):asserts value is string { need(text(value,MANAGED_STEP_LIMITS.pathBytes)); - // Syntax only. Native canonical spelling, ancestors and ACLs are revalidated + // Syntax only. Native canonical spelling and ancestors are revalidated // by the filesystem owner, never by this portable journal parser. const dialect=/^[a-z]:[\\/]/i.test(value)?path.win32:path.posix; need(dialect.isAbsolute(value)&&dialect.normalize(value)===value); diff --git a/shared/binding.ts b/shared/binding.ts index be6c5b4..fc9a8eb 100644 --- a/shared/binding.ts +++ b/shared/binding.ts @@ -1,14 +1,11 @@ import { lstatSync, readFileSync, realpathSync } from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; -import { windows, windowsPath, windowsPaths, privatePaths, platformSecurityScope, sameWindowsDirectory, sameWindowsObject, isOwned } from './platform.ts'; +import { windows, windowsPath, windowsPaths, privatePaths, sameWindowsDirectory, sameWindowsObject, isOwned } from './platform.ts'; import { VERSION, requireProgress as need, type Source } from './progress.ts'; import type { Store } from './store.ts'; export interface Binding { protocolVersion: 2; schemaVersion: 2; installId: string; version: string; database: string; storeId: string; source: Source } export function readBinding(file: string | URL): Binding { - return platformSecurityScope(()=>readBindingInner(file)); -} -function readBindingInner(file: string | URL): Binding { const p = file instanceof URL ? file : path.resolve(file); const stat = lstatSync(p); need(!stat.isSymbolicLink() && stat.isFile() && (windows?sameWindowsObject(windowsPath(file instanceof URL?fileURLToPath(file):file),realpathSync.native(p))&&privatePaths([realpathSync.native(p)]):stat.uid===process.getuid?.() && (stat.mode & 0o777) === 0o600), 'binding'); const b = JSON.parse(readFileSync(p,'utf8')) as Binding; diff --git a/shared/cleanup.ts b/shared/cleanup.ts index daeff47..0bfdeb7 100644 --- a/shared/cleanup.ts +++ b/shared/cleanup.ts @@ -3,7 +3,7 @@ import { randomUUID, createHash } from 'node:crypto'; import { openSync, closeSync, lstatSync, unlinkSync, realpathSync, existsSync } from 'node:fs'; import path from 'node:path'; import { identifier, ProgressError, requireProgress as need } from './progress.ts'; -import { windows, windowsPaths, sameWindowsObject, sameWindowsDirectory, privatePaths, platformSecurityScope } from './platform.ts'; +import { windows, windowsPaths, sameWindowsObject, sameWindowsDirectory, privatePaths } from './platform.ts'; export type CleanupAction = 'archive' | 'restore' | 'delete'; export interface CleanupRequest { storeId:string; source:string; plan:string; rev:number; cleanupRev:number; oid:string; confirmed?:true; active?:true } @@ -70,9 +70,6 @@ function preflight(db:DatabaseSync,action:CleanupAction,r:CleanupRequest,install /** Consistent private recovery material, not a product undo or automatic restore. */ function backup(db:DatabaseSync,file:string) { - return platformSecurityScope(()=>backupPrivate(db,file)); -} -function backupPrivate(db:DatabaseSync,file:string) { const parent=path.dirname(file);const owned=lstatSync(parent); need(owned.isDirectory()&&!owned.isSymbolicLink()&&privatePaths([parent]),'binding'); if(windows){ @@ -84,8 +81,8 @@ function backupPrivate(db:DatabaseSync,file:string) { const fd=openSync(destination,'wx',0o600);closeSync(fd); let copy:DatabaseSync|undefined; try { - // Windows files inherit the already-verified private parent DACL; never repair - // an existing ACL. Verify the exclusive empty file before copying any content. + // Windows files inherit the parent's default permissions. Verify the + // exclusive empty file before copying any content. if(windows)need(sameWindowsObject(windowsPaths([destination])[0]!,destination),'binding'); need(privatePaths([destination]),'binding'); db.prepare('VACUUM INTO ?').run(destination); diff --git a/shared/managed-binding.ts b/shared/managed-binding.ts index f473a24..6614ca7 100644 --- a/shared/managed-binding.ts +++ b/shared/managed-binding.ts @@ -5,7 +5,7 @@ import { randomUUID } from 'node:crypto'; import { createHash } from 'node:crypto'; import { readBinding, type Binding } from './binding.ts'; import type { ManagedSetupErrorCode } from './progress.ts'; -import { windows, windowsPath, windowsPaths, privatePaths, privateDirectory, isOwned, platformSecurityScope, syncFile, syncDirectory } from './platform.ts'; +import { windows, windowsPath, windowsPaths, privatePaths, privateDirectory, isOwned, syncFile, syncDirectory } from './platform.ts'; export class ManagedBindingError extends Error { readonly code: ManagedSetupErrorCode; @@ -27,44 +27,37 @@ export function managedPath(value: string, missing = false): string { } /** The service's observation is not proof of an active runtime's scope. Each consumer verifies independently. */ export function managedSourceRoots(env: NodeJS.ProcessEnv = process.env) { - return platformSecurityScope(() => { - need(!env.OPENCODE_DB && !env.OPENCODE_CONFIG_DIR, 'managed-scope-unsupported'); - if(windows){ - const home=env.HOME??homedir(); - const config=env.XDG_CONFIG_HOME??path.join(home,'.config'),data=env.XDG_DATA_HOME??path.join(home,'.local/share'); - // Validate the raw inputs too: joining first must not normalize away unsafe - // syntax. All known roots/ancestors share one query and one bounded scope. - const inputs=[...(env.XDG_CONFIG_HOME===undefined||env.XDG_DATA_HOME===undefined?[home]:[]),config,data]; - const roots=windowsPaths([...inputs,path.join(config,'opencode'),path.join(data,'opencode')],true); - return {configRoot:roots[inputs.length]!,dataRoot:roots[inputs.length+1]!}; - } - const home = () => managedPath(env.HOME ?? homedir(), true); - const base = (key: 'XDG_DATA_HOME' | 'XDG_CONFIG_HOME', fallback: string) => - managedPath(env[key] !== undefined ? env[key]! : path.join(home(), fallback), true); - return { configRoot: managedPath(path.join(base('XDG_CONFIG_HOME', '.config'), 'opencode'), true), - dataRoot: managedPath(path.join(base('XDG_DATA_HOME', '.local/share'), 'opencode'), true) }; - }); + need(!env.OPENCODE_DB && !env.OPENCODE_CONFIG_DIR, 'managed-scope-unsupported'); + if(windows){ + const home=env.HOME??homedir(); + const config=env.XDG_CONFIG_HOME??path.join(home,'.config'),data=env.XDG_DATA_HOME??path.join(home,'.local/share'); + // Validate the raw inputs too: joining first must not normalize away unsafe + // syntax. All known roots/ancestors share one query and one bounded scope. + const inputs=[...(env.XDG_CONFIG_HOME===undefined||env.XDG_DATA_HOME===undefined?[home]:[]),config,data]; + const roots=windowsPaths([...inputs,path.join(config,'opencode'),path.join(data,'opencode')],true); + return {configRoot:roots[inputs.length]!,dataRoot:roots[inputs.length+1]!}; + } + const home = () => managedPath(env.HOME ?? homedir(), true); + const base = (key: 'XDG_DATA_HOME' | 'XDG_CONFIG_HOME', fallback: string) => + managedPath(env[key] !== undefined ? env[key]! : path.join(home(), fallback), true); + return { configRoot: managedPath(path.join(base('XDG_CONFIG_HOME', '.config'), 'opencode'), true), + dataRoot: managedPath(path.join(base('XDG_DATA_HOME', '.local/share'), 'opencode'), true) }; } /** Sole managed discovery path. State roots, overrides and package siblings are deliberately ignored. */ export function managedBindingFile(env: NodeJS.ProcessEnv = process.env): string { - return platformSecurityScope(() => { - const { dataRoot } = managedSourceRoots(env); - const proposed=path.join(dataRoot,'agent-progress-managed'); - const root = windows?windowsPaths([proposed,path.join(proposed,'.ownership.json'),path.join(proposed,'progress-binding.json')],true)[0]!:managedPath(proposed,true); - const stat = lstatSync(root, { throwIfNoEntry: false }); - if (stat) { - need(stat.isDirectory() && privatePaths([root])); - const marker = path.join(root, '.ownership.json'); - const m = lstatSync(marker, { throwIfNoEntry: false }); - need(m?.isFile() && !m.isSymbolicLink() && privatePaths([marker]) && readFileSync(marker, 'utf8') === markerText); - } - return path.join(root, 'progress-binding.json'); - }); + const { dataRoot } = managedSourceRoots(env); + const proposed=path.join(dataRoot,'agent-progress-managed'); + const root = windows?windowsPaths([proposed,path.join(proposed,'.ownership.json'),path.join(proposed,'progress-binding.json')],true)[0]!:managedPath(proposed,true); + const stat = lstatSync(root, { throwIfNoEntry: false }); + if (stat) { + need(stat.isDirectory() && privatePaths([root])); + const marker = path.join(root, '.ownership.json'); + const m = lstatSync(marker, { throwIfNoEntry: false }); + need(m?.isFile() && !m.isSymbolicLink() && privatePaths([marker]) && readFileSync(marker, 'utf8') === markerText); + } + return path.join(root, 'progress-binding.json'); } export function readManagedBinding(env: NodeJS.ProcessEnv = process.env): Binding | undefined { - return platformSecurityScope(() => readManagedBindingInner(env)); -} -function readManagedBindingInner(env: NodeJS.ProcessEnv): Binding | undefined { const file = managedBindingFile(env); if (!lstatSync(file, { throwIfNoEntry: false })) return undefined; let binding: Binding; @@ -77,18 +70,16 @@ function readManagedBindingInner(env: NodeJS.ProcessEnv): Binding | undefined { } /** Confirmed mutation only. Existing partial/foreign directories are never repaired. */ export function createManagedBindingDirectory(env: NodeJS.ProcessEnv = process.env) { - return platformSecurityScope(() => { - const file = managedBindingFile(env), root = path.dirname(file), { dataRoot } = managedSourceRoots(env); - need(lstatSync(dataRoot).isDirectory() && isOwned(dataRoot)); - if (!lstatSync(root, { throwIfNoEntry: false })) { - privateDirectory(root); - const marker = path.join(root, '.ownership.json'); - writeFileSync(marker, markerText, { mode: 0o600, flag: 'wx' }); - syncFile(marker); syncDirectory(root); syncDirectory(dataRoot); - } - managedBindingFile(env); - return file; - }); + const file = managedBindingFile(env), root = path.dirname(file), { dataRoot } = managedSourceRoots(env); + need(lstatSync(dataRoot).isDirectory() && isOwned(dataRoot)); + if (!lstatSync(root, { throwIfNoEntry: false })) { + privateDirectory(root); + const marker = path.join(root, '.ownership.json'); + writeFileSync(marker, markerText, { mode: 0o600, flag: 'wx' }); + syncFile(marker); syncDirectory(root); syncDirectory(dataRoot); + } + managedBindingFile(env); + return file; } /** Atomic publication; absent selectors use no-clobber publication, not replacement. */ export function publishPrivateJson(file: string, value: unknown, replace = false) { @@ -113,9 +104,6 @@ export function managedExpectationFile(binding: Binding) { } /** Missing/unreadable expectation is an unknown observation, never a matching load. */ export function readManagedExpectation(binding: Binding): ManagedExpectation | undefined { - return platformSecurityScope(()=>readManagedExpectationInner(binding)); -} -function readManagedExpectationInner(binding: Binding): ManagedExpectation | undefined { const file = managedExpectationFile(binding); if (!lstatSync(file, { throwIfNoEntry: false })) return undefined; managedPath(file); diff --git a/shared/managed-steps.ts b/shared/managed-steps.ts index 1c46989..e3905ec 100644 --- a/shared/managed-steps.ts +++ b/shared/managed-steps.ts @@ -5,7 +5,6 @@ import type { ManagedReview, ManagedFreshReview } from './progress.ts'; export const MANAGED_STEP_VERSION = 1; export const MANAGED_STEP_ROUTE = '/v1/setup/managed-step'; export const MANAGED_STEP_LIMITS = { - securitySpawns: 6, workMs: 17_000, responseMs: 18_000, hostMs: 20_000, @@ -223,18 +222,3 @@ export const MANAGED_OPERATION_TRANSITIONS = { abandoned: ['pending'], complete: [], } as const satisfies Record; - -/** Allocation ceilings, NOT measured costs. Retry consumes a spare slot or refuses. - * Mutation slots include fresh checks for intent, effect and completion; scopes end - * after each mutation. Cleanup never borrows from the next request's allowance. */ -export const MANAGED_STEP_SPAWN_ALLOCATION = { - prepare: { validation: 2, intent: 0, effect: 1, checkpoint: 2, cleanup: 1 }, - expectation: { validation: 1, intent: 1, effect: 1, checkpoint: 2, cleanup: 1 }, - disable: { validation: 1, intent: 1, effect: 1, checkpoint: 2, cleanup: 1 }, - 'remove-selector': { validation: 1, intent: 1, effect: 1, checkpoint: 2, cleanup: 1 }, - 'remove-discovery': { validation: 1, intent: 1, effect: 1, checkpoint: 2, cleanup: 1 }, - 'record-removal': { validation: 1, intent: 1, effect: 1, checkpoint: 2, cleanup: 1 }, - 'publish-binding': { validation: 1, intent: 1, effect: 1, checkpoint: 2, cleanup: 1 }, - enable: { validation: 1, intent: 1, effect: 1, checkpoint: 2, cleanup: 1 }, - reconcile: { validation: 2, intent: 1, effect: 0, checkpoint: 2, cleanup: 1 }, -} as const satisfies Record>; diff --git a/shared/platform.ts b/shared/platform.ts index d123b87..21c8e26 100644 --- a/shared/platform.ts +++ b/shared/platform.ts @@ -1,4 +1,3 @@ -import { spawnSync, type SpawnSyncOptionsWithStringEncoding, type SpawnSyncReturns } from 'node:child_process'; import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, realpathSync } from 'node:fs'; import path from 'node:path'; import {createHash} from 'node:crypto'; @@ -7,16 +6,16 @@ import { MANAGED_STEP_LIMITS } from './managed-steps.ts'; export const windows = process.platform === 'win32'; export class PlatformError extends Error { readonly code: string; - readonly reason?: 'timeout'|'spawn'|'exit'; - constructor(code: string, reason?: 'timeout'|'spawn'|'exit') { super(code); this.code = code; this.reason = reason; } + constructor(code: string) { super(code); this.code = code; } } -/** Public diagnostics are fixed codes, never arbitrary exception text. */ +/** Public diagnostics are fixed codes, never arbitrary exception text. The first + * three are no longer produced (Windows permission queries were removed) but stay + * accepted so earlier journals, status and clients keep their fixed vocabulary. */ export function platformErrorCode(error: unknown) { const codes = ['windows-security-unavailable','private-permissions','path-unverified','unsafe-parent','symlink-escape'] as const; return error instanceof PlatformError ? codes.find(code=>code===error.code) : undefined; } -type Security = { owned: boolean; private: boolean; reparse: boolean; unsafeParent: boolean }; -/** Coordination identity only, not path/ACL authority. Resolve existing aliases +/** Coordination identity only, not path authority. Resolve existing aliases * for the lock key; the ordinary owners still refuse unsafe paths before work. */ export function writerTarget(kind:'scope'|'store',value:string):string { let current=path.resolve(value);const missing:string[]=[]; @@ -36,43 +35,27 @@ export function writerTargetPort(target:string):number { while(writerPortDenylist.has(25000+offset))offset=(offset+1)%4000; return 25000+offset; } -const cache = new Map(); -const reparseCache = new Map(); -let scope = 0; -/** A worker-local request boundary, never a cached security verdict. The shared - * counter lets its supervisor report actual attempts even after a lost reply. - * Monotonic nanoseconds use the same clock in service and worker threads. */ +/** A worker-local request boundary: the work deadline and the writer fence. It + * starts no process. Monotonic nanoseconds use the same clock in service and + * worker threads. */ export class PlatformRequestBudget { - readonly counter: Int32Array; readonly startedAt: bigint; readonly deadline: bigint; - readonly writerFence?:{port:number;nonce:string;targets?:string[]}; - constructor(startedAt = process.hrtime.bigint(), counter = new SharedArrayBuffer(4),writerFence?:{port:number;nonce:string;targets?:string[]}) { - if(counter.byteLength!==4)throw new PlatformError('managed-step-budget'); - this.counter=new Int32Array(counter);this.startedAt=startedAt; + readonly writerFence?:{targets?:string[]}; + /** Wire compatibility only: the step accounting shape still carries this count, + * and no permission check starts a process any more. */ + readonly securitySpawns = 0; + constructor(startedAt = process.hrtime.bigint(),writerFence?:{targets?:string[]}) { + this.startedAt=startedAt; this.deadline=startedAt+BigInt(MANAGED_STEP_LIMITS.workMs)*1_000_000n; this.writerFence=writerFence; } - get securitySpawns(){return Atomics.load(this.counter,0);} get elapsedMs(){return Math.max(0,Number(process.hrtime.bigint()-this.startedAt)/1_000_000);} - /** Reserve before admitting effects. Reservation does not consume attempts. */ - require(spawns=0,headroomMs=0) { - if(!Number.isSafeInteger(spawns)||spawns<0||!Number.isFinite(headroomMs)||headroomMs<0|| - this.securitySpawns<0||this.securitySpawns+spawns>MANAGED_STEP_LIMITS.securitySpawns) - throw new PlatformError('managed-step-budget'); - if(Number(this.deadline-process.hrtime.bigint())/1_000_000<=headroomMs) + /** Refuse to admit further effects once the work deadline has passed. */ + require() { + if(Number(this.deadline-process.hrtime.bigint())/1_000_000<=0) throw new PlatformError('managed-step-deadline'); } - /** Charge before the OS call, including a failed/throwing process launch. */ - launch() { - this.require(1,1_000); - // There is one worker, but CAS also prevents accidental shared-counter - // consumers from exceeding the ceiling rather than discovering it later. - const before=this.securitySpawns; - if(before>=MANAGED_STEP_LIMITS.securitySpawns||Atomics.compareExchange(this.counter,0,before,before+1)!==before) - throw new PlatformError('managed-step-budget'); - return Math.max(1,Math.floor(Number(this.deadline-process.hrtime.bigint())/1_000_000-1_000)); - } } let requestBudget:PlatformRequestBudget|undefined; let writerTargets:string[]|undefined; @@ -89,32 +72,20 @@ export function withPlatformWriterTargets(targets:string[],run:()=>T):T { }finally{writerTargets=undefined;} } /** Synchronous request work only. Awaiting or resetting a nested budget is not - * supported; no caller may hide an outer security scope across requests. */ + * supported. */ export function withPlatformRequestBudget(budget:PlatformRequestBudget,run:()=>T):T { - if(requestBudget||scope)throw new PlatformError('managed-step-conflict'); - budget.require();requestBudget=budget;cache.clear();reparseCache.clear(); + if(requestBudget)throw new PlatformError('managed-step-conflict'); + budget.require();requestBudget=budget; try{ const result=run(); if(result!==null&&(typeof result==='object'||typeof result==='function')&&typeof (result as {then?:unknown}).then==='function') throw new PlatformError('managed-step-conflict'); return result; - }finally{requestBudget=undefined;cache.clear();reparseCache.clear();} -} -/** Cache only one synchronous operation, and only unchanged object snapshots. */ -export function platformSecurityScope(run: () => T): T { - const finish=beginPlatformSecurityScope(); - try { return run(); } finally { finish(); } + }finally{requestBudget=undefined;} } -export function beginPlatformSecurityScope():()=>void { - if (!scope) {cache.clear();reparseCache.clear();} - scope++; - return ()=>{if (!--scope) {cache.clear();reparseCache.clear();}}; -} -/** A mutation owner must end the actual scope, not merely a nested wrapper. - * Refuse misuse rather than clearing an enclosing reader's authority silently. */ -export function requirePlatformWriteBoundary(spawns=0,headroomMs=0):void { - if(scope)throw new PlatformError('managed-step-conflict'); - requestBudget?.require(spawns,headroomMs); +/** A mutation owner checks the request deadline before each effect. */ +export function requirePlatformWriteBoundary():void { + requestBudget?.require(); } /** A pre-dispatch metadata read may route locks, but never grant authority. The * fresh owner must bind its actual Store to an acquired slot before any effect. */ @@ -125,216 +96,17 @@ export function requirePlatformStoreFence(database:string):void { throw new PlatformError('managed-step-conflict'); } -/** Windows PowerShell can expand inherited module paths during startup. */ -export const windowsPowerShellBootstrap = String.raw` -$env:PSModulePath = $PSHOME + '\Modules' -$PSModuleAutoLoadingPreference = 'None' -Import-Module ($PSHOME + '\Modules\Microsoft.PowerShell.Utility\Microsoft.PowerShell.Utility.psd1') -ErrorAction Stop -`; - -/** Shared pure descriptor policy, also exercised by public .NET fixtures. */ -export const windowsDaclValidationScript = String.raw` -function Test-OrdinaryDacl($binary) { - $raw = [Security.AccessControl.RawSecurityDescriptor]::new($binary, 0) - if ($null -eq $raw.DiscretionaryAcl) { return $false } - foreach ($ace in $raw.DiscretionaryAcl) { - if ($ace -isnot [Security.AccessControl.CommonAce] -or $ace.IsCallback -or $ace.AceQualifier -notin @([Security.AccessControl.AceQualifier]::AccessAllowed, [Security.AccessControl.AceQualifier]::AccessDenied) -or ([int]$ace.AceFlags -band 224)) { return $false } - } - return $true -} -function Test-TrustedAncestorOwner($owner, $currentUser) { - # Owners can rewrite a DACL even without an explicit write ACE. The service - # SID below is Windows Modules Installer (TrustedInstaller), ancestor-only. - return $owner -in @($currentUser, 'S-1-5-18', 'S-1-5-32-544', 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464') -} -`; -// Trusted code only. User-supplied paths travel through UTF-8 JSON stdin. -const securityScript = String.raw` -$ErrorActionPreference = 'Stop' -[Console]::InputEncoding = [Text.UTF8Encoding]::new($false) -[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false) -${windowsPowerShellBootstrap} -${windowsDaclValidationScript} -$writerMutex = $null -$writerOwned = $false -$failureCode = 'windows-security-unavailable' -try { - $request = [Console]::In.ReadToEnd() | ConvertFrom-Json - $user = [Security.Principal.WindowsIdentity]::GetCurrent().User - if ($request.fence) { - $failureCode = 'managed-step-unsettled' - # The main service holds the TCP writer slot until its Node worker exits. - # This account-scoped mutex additionally fences a security child that might - # outlive that service. Obtain it BEFORE checking the current slot nonce. - # Every new writer's first fresh query crosses this barrier before effects. - $writerMutex = [Threading.Mutex]::new($false, ('Global\OpenChamberAgentProgressWriterV1-' + $user.Value)) - try { $writerOwned = $writerMutex.WaitOne(15000) } - catch [Threading.AbandonedMutexException] { $writerOwned = $true } - if (-not $writerOwned) { $failureCode = 'managed-step-unsettled'; throw 'writer-unsettled' } - $client = [Net.Sockets.TcpClient]::new() - try { - $client.SendTimeout = 1000; $client.ReceiveTimeout = 1000 - $client.Connect('127.0.0.1', [int]$request.fence.port) - $stream = $client.GetStream() - $bytes = [Text.Encoding]::ASCII.GetBytes(([string]$request.fence.nonce + [char]10)) - $stream.Write($bytes, 0, $bytes.Length) - $reply = [byte[]]::new(3); $offset = 0 - while ($offset -lt 3) { - $count = $stream.Read($reply, $offset, 3 - $offset) - if ($count -le 0) { throw 'writer-unsettled' } - $offset += $count - } - if ([Text.Encoding]::ASCII.GetString($reply) -ne ('ok' + [char]10)) { throw 'writer-unsettled' } - } finally { $client.Dispose() } - $failureCode = 'windows-security-unavailable' - } - $allowed = @($user.Value, 'S-1-5-18', 'S-1-5-32-544') - if ($request.create) { - foreach ($target in $request.create) { - if ($request.exclusive -and [IO.Directory]::Exists($target)) { throw 'creation-conflict' } - if (-not [IO.Directory]::Exists($target)) { - $security = [Security.AccessControl.DirectorySecurity]::new() - $security.SetOwner($user) - $security.SetAccessRuleProtection($true, $false) - foreach ($value in $allowed) { - $sid = [Security.Principal.SecurityIdentifier]::new($value) - $rule = [Security.AccessControl.FileSystemAccessRule]::new($sid, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow') - $security.AddAccessRule($rule) - } - [void][IO.Directory]::CreateDirectory($target, $security) - } - } - } - $results = @() - foreach ($target in $request.paths) { - $owned = $false; $private = $false; $reparse = $true; $unsafeParent = $true - try { - $attributes = [IO.File]::GetAttributes($target) - $reparse = [bool]($attributes -band [IO.FileAttributes]::ReparsePoint) - if ($attributes -band [IO.FileAttributes]::Directory) { $acl = [IO.Directory]::GetAccessControl($target) } - else { $acl = [IO.File]::GetAccessControl($target) } - $owner = $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value - $owned = $owner -eq $user.Value - $ordinary = Test-OrdinaryDacl ($acl.GetSecurityDescriptorBinaryForm()) - $private = $ordinary -and $owned -and $acl.AreAccessRulesCanonical -and -not $reparse - $unsafeParent = -not $ordinary -or -not (Test-TrustedAncestorOwner $owner $user.Value) - $granted = $false - $full = [Security.AccessControl.FileSystemRights]::FullControl - $replace = [Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles -bor [Security.AccessControl.FileSystemRights]::Delete -bor [Security.AccessControl.FileSystemRights]::ChangePermissions -bor [Security.AccessControl.FileSystemRights]::TakeOwnership -bor 0x10000000 - if ($ordinary) { foreach ($rule in $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) { - if ($rule.AccessControlType -ne 'Allow' -or $rule.IdentityReference.Value -notin $allowed) { $private = $false } - if (($attributes -band [IO.FileAttributes]::Directory) -and $rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -notin $allowed -and -not ($rule.PropagationFlags -band [Security.AccessControl.PropagationFlags]::InheritOnly) -and ($rule.FileSystemRights -band $replace)) { $unsafeParent = $true } - if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -eq $user.Value -and -not ($rule.PropagationFlags -band [Security.AccessControl.PropagationFlags]::InheritOnly) -and ($rule.FileSystemRights -band $full) -eq $full) { $granted = $true } - } } - $private = $private -and $granted - } catch { $private = $false; $unsafeParent = $true } - $results += @{owned=$owned;private=$private;reparse=$reparse;unsafeParent=$unsafeParent} - } - [Console]::Out.Write((ConvertTo-Json -InputObject $results -Compress)) -} catch { [Console]::Out.Write(('{"error":"' + $failureCode + '"}')); exit 1 } -finally { - if ($writerOwned) { $writerMutex.ReleaseMutex() } - if ($null -ne $writerMutex) { $writerMutex.Dispose() } -} -`; - -function snapshot(file: string) { - const s = lstatSync(file, { bigint: true }); - return [s.dev,s.ino,s.mode,s.nlink,s.size,s.mtimeNs,s.ctimeNs,s.birthtimeNs].join(':'); -} -function objectIdentity(file:string) {const s=lstatSync(file,{bigint:true});return[s.dev,s.ino,s.mode,s.birthtimeNs].join(':');} -/** Directory content timestamps do not describe reparse identity or permissions. */ -function reparsePaths(paths:string[],parents:Set) { - const fresh=new Map(); - const pending=paths.filter(p=>!scope||reparseCache.get(p)?.identity!==objectIdentity(p)); - const before=pending.map(objectIdentity),stats=pending.map(snapshot),results=pending.length?windowsSecurityQuery(pending):[]; - pending.forEach((p,i)=>{ - const after=objectIdentity(p);if(after!==before[i])throw new PlatformError('path-unverified'); - const result={identity:after,reparse:results[i]!.reparse,unsafeParent:results[i]!.unsafeParent};fresh.set(p,result); - if(reparseCache.size<1024||reparseCache.has(p))reparseCache.set(p,result); - // ACL caching remains stricter: full object and mutation metadata only. - if(snapshot(p)===stats[i]&&(cache.size<1024||cache.has(p)))cache.set(p,{snapshot:stats[i]!,result:results[i]!}); - }); - if(paths.some(p=>parents.has(p)&&(fresh.get(p)??reparseCache.get(p)!).unsafeParent))throw new PlatformError('unsafe-parent'); - return paths.some(p=>(fresh.get(p)??reparseCache.get(p)!).reparse); -} -let securityQueryAttempted = false; -/** Injectable process boundary; production callers always use the built-in spawn. */ -export function windowsSecurityQuery(paths: string[], create: string[] = [], spawn: (command: string, args: string[], options: SpawnSyncOptionsWithStringEncoding) => SpawnSyncReturns = spawnSync, exclusive=false): Security[] { - const systemRoot = process.env.SystemRoot ?? process.env.SYSTEMROOT; - if (!systemRoot || !/^[a-z]:[\\/]/i.test(systemRoot)) throw new PlatformError('windows-security-unavailable'); - // Do not inherit profile, module, proxy, Node or PowerShell startup overrides. - const env: NodeJS.ProcessEnv = {}; - for (const key of ['SystemRoot','SYSTEMROOT','WINDIR','TEMP','TMP','USERPROFILE','HOMEDRIVE','HOMEPATH','LOCALAPPDATA']) { - if (process.env[key]) env[key] = process.env[key]; - } - // Pin startup hints too; the trusted script resets the effective path and - // imports only the built-in utility module by its absolute system path. - env.PSModulePath=path.join(systemRoot,'System32','WindowsPowerShell','v1.0','Modules'); - const input = JSON.stringify({ paths, create, ...(exclusive?{exclusive:true}:{}), ...(requestBudget?.writerFence?{fence:requestBudget.writerFence}:{}) }); - const firstQuery = !securityQueryAttempted; - const run = () => { - const timeout=requestBudget?requestBudget.launch():firstQuery?30000:10000; - try{return spawn(path.join(systemRoot,'System32','WindowsPowerShell','v1.0','powershell.exe'), - ['-NoLogo','-NoProfile','-NonInteractive','-Command',securityScript], - { input, encoding:'utf8', env, windowsHide:true, shell:false, timeout, maxBuffer:1024*1024 }); - }finally{securityQueryAttempted=true;} - }; - // Only the process's first query gets cold-start headroom and one retry. - // Consume that budget even on failure; steady-state calls stay bounded at 10s. - // Existing creation targets are only inspected, never repaired, on a retry. - let child: SpawnSyncReturns; - child = run(); - if (!requestBudget && firstQuery && (child.error as NodeJS.ErrnoException | undefined)?.code === 'ETIMEDOUT') child = run(); - requestBudget?.require(); - if(requestBudget&&(child.error as NodeJS.ErrnoException|undefined)?.code==='ETIMEDOUT')throw new PlatformError('managed-step-deadline','timeout'); - if(requestBudget?.writerFence&&!child.error&&child.status!==0){ - let failure:unknown;try{failure=JSON.parse(child.stdout.replace(/^\uFEFF/,''));}catch{/* Never expose raw child text. */} - if(failure&&typeof failure==='object'&&Object.keys(failure).length===1&&(failure as {error?:unknown}).error==='managed-step-unsettled') - throw new PlatformError('managed-step-unsettled','exit'); - } - if (child.error || child.status !== 0) throw new PlatformError('windows-security-unavailable',child.error?(child.error as NodeJS.ErrnoException).code==='ETIMEDOUT'?'timeout':'spawn':'exit'); - let results: Security[]; - try { results = JSON.parse(child.stdout.replace(/^\uFEFF/,'')); } catch { throw new PlatformError('windows-security-unavailable'); } - if (!Array.isArray(results) || results.length !== paths.length || results.some(r => !r || ['owned','private','reparse','unsafeParent'].some(k => typeof r[k as keyof Security] !== 'boolean'))) throw new PlatformError('windows-security-unavailable'); - return results; -} -/** Batch related paths; never retain a security result across operations. */ -export function windowsSecurity(paths: string[]): Security[] { - const pending = new Map(); - const fresh = new Map(); - for (const file of paths) { const stat = snapshot(file); if (!scope || cache.get(file)?.snapshot !== stat) pending.set(file,stat); } - const files = [...pending.keys()]; - if (files.length) { - const results = windowsSecurityQuery(files); - files.forEach((file,i) => { - const after=snapshot(file),before=pending.get(file)!; - if (after.split(':').slice(0,2).join(':') !== before.split(':').slice(0,2).join(':')) throw new PlatformError('path-unverified'); - fresh.set(file,results[i]!); - if(reparseCache.size<1024||reparseCache.has(file))reparseCache.set(file,{identity:objectIdentity(file),reparse:results[i]!.reparse,unsafeParent:results[i]!.unsafeParent}); - // Shared ancestors can change while PowerShell starts (e.g. OS temp). - // Return the fresh observation, but never cache a changed snapshot. - if(after===before){if(cache.size<1024||cache.has(file))cache.set(file,{snapshot:before,result:results[i]!});} - else cache.delete(file); - }); - } - return paths.map(file => fresh.get(file)??cache.get(file)!.result); -} - -/** Reject ambiguous syntax BEFORE normalization; canonicalize actual spelling. */ +/** Reject ambiguous syntax BEFORE normalization; canonicalize actual spelling. + * Windows paths are checked with plain filesystem calls only (lstat/realpath): + * no process is started and no permission (ACL) query is made. */ export function windowsPath(value: string, allowMissing = false): string { return windowsPaths([value],allowMissing)[0]!; } export function windowsPaths(values: string[], allowMissing = false): string[] { - return platformSecurityScope(()=>windowsPathsInner(values,allowMissing)); -} -/** Source documents are authorized reads, not private product storage. */ -export function windowsDocumentPath(value:string,allowMissing=false):string { - return platformSecurityScope(()=>windowsPathsInner([value],allowMissing,false)[0]!); + return windowsPathsInner(values,allowMissing); } -function windowsPathsInner(values: string[], allowMissing = false, privateState=true): string[] { - const ancestors=new Set(),parents=new Set(); - const resolved=values.map(value=>{ +function windowsPathsInner(values: string[], allowMissing = false): string[] { + return values.map(value=>{ if (value.includes('\0') || value.length > 4096 || !/^[a-z]:[\\/]/i.test(value)) throw new PlatformError('path-unverified'); const normalized = value.replaceAll('/','\\'); const parts = normalized.slice(3).split('\\').filter(Boolean); @@ -349,70 +121,59 @@ function windowsPathsInner(values: string[], allowMissing = false, privateState= tail.unshift(path.basename(current)); const parent=path.dirname(current); if (parent===current) throw new PlatformError('path-unverified'); current=parent; } + // Node reports symbolic links and junctions as links; refuse any in the chain. for (let p=current;;p=path.dirname(p)) { - const stat=lstatSync(p); if(stat.isSymbolicLink()) throw new PlatformError('symlink-escape'); - ancestors.add(p); if(path.dirname(p)===p)break; + if(lstatSync(p).isSymbolicLink()) throw new PlatformError('symlink-escape'); + if(path.dirname(p)===p)break; } - for(let p=tail.length?current:path.dirname(current);;p=path.dirname(p)){parents.add(p);if(path.dirname(p)===p)break;} return path.join(realpathSync.native(current),...tail); }); - if (reparsePaths([...ancestors],privateState?parents:new Set())) throw new PlatformError('symlink-escape'); - return resolved; } +/** Windows has no uid to compare, and ownership is not queried: state lives under + * the user's profile and relies on its default per-user permissions. */ export function isOwned(file: string) { - return windows ? windowsSecurity([file])[0]!.owned : lstatSync(file).uid === process.getuid?.(); + if (windows) { lstatSync(file); return true; } + return lstatSync(file).uid === process.getuid?.(); } /** Compare native directory identities, preserving case-sensitive distinctions. */ export function sameWindowsDirectory(left:string,right:string) { return sameWindowsObject(left,right,true); } export function sameWindowsObject(left:string,right:string,directory=false) { - return platformSecurityScope(()=>{ - const [a,b]=windowsPaths([left,right]); - const first=lstatSync(a!,{bigint:true}),second=lstatSync(b!,{bigint:true}); - return (!directory||first.isDirectory()&&second.isDirectory())&&first.ino!==0n&&first.dev===second.dev&&first.ino===second.ino; - }); + const [a,b]=windowsPaths([left,right]); + const first=lstatSync(a!,{bigint:true}),second=lstatSync(b!,{bigint:true}); + return (!directory||first.isDirectory()&&second.isDirectory())&&first.ino!==0n&&first.dev===second.dev&&first.ino===second.ino; } export function privatePaths(files: string[]) { // Named aliases must not split SQLite journals or mutate retained metadata. - return windows ? files.every(file=>{const s=lstatSync(file);return !s.isFile()||s.nlink===1;})&&windowsSecurity(files).every(s=>s.private) : files.every(file=>{ + // Windows keeps only these pure filesystem checks; POSIX adds uid and mode. + return windows ? files.every(file=>{const s=lstatSync(file);return !s.isSymbolicLink()&&(!s.isFile()||s.nlink===1);}) : files.every(file=>{ const s=lstatSync(file);return !s.isSymbolicLink()&&s.uid===process.getuid?.()&&(s.mode&0o777)===(s.isDirectory()?0o700:0o600); }); } +/** POSIX creates 0700 directories. Windows creates ordinary directories that + * inherit the profile's default permissions; no ACL is applied or repaired. */ export function privateDirectory(file: string, recursive=false, creation?:{exclusive:true;validate:()=>void}) { if(creation){ requirePlatformWriteBoundary(); if(recursive||creation.exclusive!==true||typeof creation.validate!=='function')throw new PlatformError('managed-step-conflict'); - const target=platformSecurityScope(()=>{ - creation.validate(); - const target=windows?windowsPath(file,true):file,parent=path.dirname(target); - if(!path.isAbsolute(target)||path.resolve(target)!==target||!lstatSync(parent).isDirectory()|| - (!windows&&realpathSync(parent)!==parent)||lstatSync(target,{throwIfNoEntry:false}))throw new PlatformError('path-unverified'); - return target; - }); - // The real preflight scope has ended. Never carry its ACL cache over creation. - // Recheck after slow preflight: creation plus checkpoint validation/readback. - requirePlatformWriteBoundary(3,8_500); - if(windows){ - const [result]=windowsSecurityQuery([target],[target],undefined,true); - if(!result?.owned||!result.private||result.reparse||result.unsafeParent)throw new PlatformError('private-permissions'); - }else mkdirSync(target,{mode:0o700}); + creation.validate(); + const target=windows?windowsPath(file,true):file,parent=path.dirname(target); + if(!path.isAbsolute(target)||path.resolve(target)!==target||!lstatSync(parent).isDirectory()|| + (!windows&&realpathSync(parent)!==parent)||lstatSync(target,{throwIfNoEntry:false}))throw new PlatformError('path-unverified'); + requirePlatformWriteBoundary(); + // Exclusive: mkdir fails if the target appeared since validation. + if(windows)mkdirSync(target);else mkdirSync(target,{mode:0o700}); syncDirectory(path.dirname(target)); return; } if (!windows) { mkdirSync(file,{recursive,mode:0o700}); return; } - platformSecurityScope(()=>{ - const target=windowsPath(file,true); - const missing:string[]=[]; let parent=target; - while(!existsSync(parent)){missing.unshift(parent);parent=path.dirname(parent);} - if(!recursive&&missing.length>1)throw new PlatformError('path-unverified'); - if(missing.length) { - const results=windowsSecurityQuery(missing,missing); - if(results.some(r=>!r.private))throw new PlatformError('private-permissions'); - missing.forEach(p=>cache.delete(p)); - } else if(!lstatSync(target).isDirectory()||!privatePaths([target]))throw new PlatformError('private-permissions'); - }); + const target=windowsPath(file,true); + let missing=0; for(let parent=target;!existsSync(parent);parent=path.dirname(parent))missing++; + if(!recursive&&missing>1)throw new PlatformError('path-unverified'); + if(missing)mkdirSync(target,{recursive}); + else if(!lstatSync(target).isDirectory())throw new PlatformError('path-unverified'); } export function syncFile(file:string) {const fd=openSync(file,windows?'r+':'r');try{fsyncSync(fd);}finally{closeSync(fd);}} /** Windows has atomic selection/process recovery, not POSIX directory durability. */ diff --git a/shared/store.ts b/shared/store.ts index f59eaab..45a8289 100644 --- a/shared/store.ts +++ b/shared/store.ts @@ -16,7 +16,7 @@ import { searchWindow, searchState } from './plan-task-search.ts'; import { resumeSelection, type ResumeRequest } from './progress-resume.ts'; import type { SearchOptions, SearchKey } from './progress.ts'; import { DIGEST_LIMITS, aggregatePair, capDigest, emptyEvents, endpointCounts, validateDigestSnapshot, type ChangeDigest, type DigestReason, type DigestSnapshot } from './change-digest.ts'; -import { windows, windowsPath, windowsPaths, privatePaths, beginPlatformSecurityScope, platformSecurityScope, requirePlatformWriteBoundary, +import { windows, windowsPath, windowsPaths, privatePaths, requirePlatformWriteBoundary, requirePlatformStoreFence, syncDirectory, PlatformError, sameWindowsDirectory, sameWindowsObject } from './platform.ts'; import { VERSION, LIMITS, ProgressError, requireProgress as need, validRequest, parseRequest, countItems, validBlockerAnnotation, validBlockerInput, type BlockerInput, type BlockerItemInput, type Actor, type Source, type Capture, type PlanState, type PlanSummary, type Receipt, type Item, type Envelope, type PlanRead, type DocumentRead, type Contribution } from './progress.ts'; @@ -67,7 +67,6 @@ export class Store { constructor(file: string, options: { create?: boolean; busyMs?: number; readOnly?: boolean } = {}, fresh?:FreshStoreInitialization) { this.file=file; this.readOnly=options.readOnly??false; - const finish=fresh?()=>{}:beginPlatformSecurityScope(); try { if(fresh){ requirePlatformWriteBoundary(); @@ -100,7 +99,6 @@ export class Store { // Ordinary opens (including writable service handles) validate, never migrate. this.transaction(false,()=>receiptIndexInstalled(this.db)); } catch (e) { this.db!?.close(); if(e instanceof PlatformError)throw e;throw storageError(e); } - finally{finish();} } /** Journaled fresh creation only: exclusive reservation followed by NEW object * admission before the initial off/schema transaction. Partial files survive @@ -109,7 +107,7 @@ export class Store { requirePlatformWriteBoundary();requirePlatformStoreFence(file); need(identifier(options.storeId)&&typeof options.validate==='function','binding'); const parent=path.dirname(file),sidecars=['-journal','-wal','-shm'].map(s=>file+s); - const directory=platformSecurityScope(()=>{ + const directory=(()=>{ options.validate(); need(path.isAbsolute(file)&&path.resolve(file)===file&&path.basename(file)==='progress.sqlite','binding'); if(windows)need(windowsPaths([parent,file,...sidecars],true).every((p,i)=>p===[parent,file,...sidecars][i]),'binding'); @@ -117,20 +115,17 @@ export class Store { const stat=lstatSync(parent,{bigint:true});need(stat.isDirectory()&&!stat.isSymbolicLink()&&privatePaths([parent]),'binding'); need(![file,...sidecars].some(p=>lstatSync(p,{throwIfNoEntry:false})),'binding'); return storeObject(stat); - }); - // The final preflight may have spent the earlier engine reservation. Leave - // room for new-object admission and the journal's validation/readback. - requirePlatformWriteBoundary(3,8_500); + })(); + requirePlatformWriteBoundary(); const fd=openSync(file,'wx',0o600); try{ const reserved=storeObject(fstatSync(fd,{bigint:true})); - platformSecurityScope(()=>{ - // This is a new batch after reservation, never inherited pre-create ACLs. + { if(windows)windowsPaths([parent,file,...sidecars],true); const stat=lstatSync(file,{bigint:true}); need(storeObject(lstatSync(parent,{bigint:true}))===directory&&storeObject(stat)===reserved&&stat.isFile()&&!stat.isSymbolicLink()&&stat.nlink===1n&& stat.size===0n&&privatePaths([parent,file])&&!sidecars.some(p=>lstatSync(p,{throwIfNoEntry:false})),'binding'); - }); + } requirePlatformWriteBoundary(); const store=new Store(file,{}, {token:freshStoreToken,storeId:options.storeId,object:reserved}); try{fsyncSync(fd);syncDirectory(parent);return store;}catch(e){store.close();throw e;} diff --git a/tests/backend/managed-fresh-store.test.ts b/tests/backend/managed-fresh-store.test.ts index 80c18a9..3bc5a21 100644 --- a/tests/backend/managed-fresh-store.test.ts +++ b/tests/backend/managed-fresh-store.test.ts @@ -5,7 +5,7 @@ import path from 'node:path'; import {DatabaseSync} from 'node:sqlite'; import {syncBuiltinESMExports} from 'node:module'; import {Store} from '../../shared/store.ts'; -import {privateDirectory,platformSecurityScope} from '../../shared/platform.ts'; +import {privateDirectory,PlatformRequestBudget,withPlatformRequestBudget} from '../../shared/platform.ts'; import {receiptIndexInstalled} from '../../shared/receipt-index.ts'; function fixture(){const root=fs.mkdtempSync('/tmp/opencode/fresh-store-');return {root,file:path.join(root,'progress.sqlite'), @@ -36,12 +36,10 @@ test('existing empty, partial, initialized, linked and orphan-sidecar state is r }finally{f.close();} } }); -test('fresh validation refuses before reservation and cannot inherit an enclosing security scope',()=>{ +test('fresh validation refuses before reservation',()=>{ const f=fixture();try{ assert.throws(()=>Store.createFresh(f.file,{storeId:'new-store',validate(){throw new Error('synthetic refusal');}}),/synthetic refusal/); assert.equal(fs.existsSync(f.file),false); - assert.throws(()=>platformSecurityScope(()=>Store.createFresh(f.file,{storeId:'new-store',validate(){}})),{code:'managed-step-conflict'}); - assert.equal(fs.existsSync(f.file),false); }finally{f.close();} }); test('interrupted initialization retains its exclusively reserved partial file and ordinary opens never repair it',t=>{ @@ -78,6 +76,20 @@ test('exclusive directory creation shares preflight but refuses existing targets const missing=path.join(f.root,'other'); assert.throws(()=>privateDirectory(missing,false,{exclusive:true,validate(){throw new Error('synthetic refusal');}}),/synthetic refusal/); assert.equal(fs.existsSync(missing),false); - assert.throws(()=>platformSecurityScope(()=>privateDirectory(missing,false,{exclusive:true,validate(){}})),{code:'managed-step-conflict'}); + }finally{f.close();} +}); +test('creation refuses once the request deadline has passed, before any exclusive reservation',t=>{ + const f=fixture();try{ + let now=process.hrtime.bigint();const started=now; + const clock=t.mock.method(process.hrtime,'bigint',()=>now); + try{ + const expire=()=>{now=started+18_000_000_000n;}; + const dir=path.join(f.root,'store'); + assert.throws(()=>withPlatformRequestBudget(new PlatformRequestBudget(started),()=>privateDirectory(dir,false,{exclusive:true,validate:expire})),{code:'managed-step-deadline'}); + assert.equal(fs.existsSync(dir),false); + now=started; + assert.throws(()=>withPlatformRequestBudget(new PlatformRequestBudget(started),()=>Store.createFresh(f.file,{storeId:'slow-store',validate:expire})),{code:'managed-step-deadline'}); + assert.equal(fs.existsSync(f.file),false); + }finally{clock.mock.restore();} }finally{f.close();} }); diff --git a/tests/backend/managed-health.test.ts b/tests/backend/managed-health.test.ts index 9eb598c..16e6615 100644 --- a/tests/backend/managed-health.test.ts +++ b/tests/backend/managed-health.test.ts @@ -76,7 +76,7 @@ test('data routes preserve fixed admission and coordination refusals',async t=>{ try{ server.listen(0,'127.0.0.1');await once(server,'listening'); const url=`http://127.0.0.1:${(server.address() as {port:number}).port}`; - for(const error of [new PlatformError('private-permissions'),new PlatformError('windows-security-unavailable'),new ManagedBindingError('managed-binding-modified'),new PlatformError('untrusted-message')]){ + for(const error of [new PlatformError('private-permissions'),new ManagedBindingError('managed-binding-modified'),new PlatformError('untrusted-message')]){ const mock=t.mock.method(fs,'lstatSync',()=>{throw error;});syncBuiltinESMExports(); try{ // Managed capture now runs in a separate worker, so these main-thread diff --git a/tests/backend/managed-http-worker.ts b/tests/backend/managed-http-worker.ts index 042fabf..2826c3c 100644 --- a/tests/backend/managed-http-worker.ts +++ b/tests/backend/managed-http-worker.ts @@ -9,21 +9,15 @@ const fault=file&&fs.existsSync(file)?JSON.parse(fs.readFileSync(file,'utf8')):{ process.env.TEST_CRASH_STEP=fault.crashStep??''; process.env.TEST_CRASH_ORDER=fault.order??''; process.env.TEST_EFFECT_ERROR=fault.effectError?'1':''; -if(fault.spentSpawns)Atomics.store(new Int32Array(workerData.counter),0,fault.spentSpawns); if(fault.hold){ fs.writeFileSync(workerData.env.TEST_READY_FILE,'ready',{mode:0o600}); const deadline=Date.now()+10_000; while(!fs.existsSync(workerData.env.TEST_RELEASE_FILE)&&Date.now()clock()+BigInt(fault.clockOffset)*1_000_000n;} -if(workerData.env.TEST_WINDOWS==='1'){ - process.env.SystemRoot='C:\\Windows'; - cp.spawnSync=((_command:string,_args:string[],options:cp.SpawnSyncOptionsWithStringEncoding):cp.SpawnSyncReturns=>{ - if(fault.securityError)return {pid:1,output:[],stdout:JSON.stringify({error:fault.securityError}),stderr:'',status:1,signal:null}; - const input=JSON.parse(String(options.input));for(const p of input.create)fs.mkdirSync(p,{mode:0o700}); - return {pid:1,output:[],stdout:JSON.stringify(input.paths.map(()=>({owned:true,private:true,reparse:false,unsafeParent:false}))),stderr:'',status:0,signal:null}; - }) as unknown as typeof cp.spawnSync; -} +// The projection runs the Windows path on a POSIX host: no permission check +// may start a process, so any attempt fails the request. +cp.spawnSync=(()=>{throw new Error('no permission check may start a process');}) as unknown as typeof cp.spawnSync; if(fault.ownerCode){ const stat=fs.lstatSync,read=fs.readFileSync;let journalRead=false; Object.defineProperty(fs,'readFileSync',{value:((p:any,...args:any[])=>{ diff --git a/tests/backend/managed-inspection.test.ts b/tests/backend/managed-inspection.test.ts index 776a3d9..2989171 100644 --- a/tests/backend/managed-inspection.test.ts +++ b/tests/backend/managed-inspection.test.ts @@ -221,7 +221,7 @@ test('oversized discovered sets and history refuse without a truncated review',( } }); -test('each inspection stage and review revalidation charge at most six security launches',{skip:process.platform==='win32'},async t=>{ +test('each inspection stage and review revalidation start no process on the Windows path',{skip:process.platform==='win32'},async t=>{ const original=process.env.SystemRoot; try{for(const kind of ['manifest','upgrade','receipt','fresh','fresh-retained'] as const){ const fresh=kind==='fresh'||kind==='fresh-retained',f=fresh?freshFixture():fixture(kind);try{ @@ -236,26 +236,21 @@ test('each inspection stage and review revalidation charge at most six security const start=text.indexOf(" if (value.includes('\\0')",text.indexOf('function windowsPathsInner(')),end=text.indexOf(' let current = clean;',start); assert.ok(start>0&&end>start);text=text.slice(0,start)+" if (!path.isAbsolute(value) || path.resolve(value) !== value) throw new PlatformError('path-unverified');\n const clean = value;\n"+text.slice(end);fs.writeFileSync(platformFile,text); let spawns=0; - const mock=t.mock.method(cp,'spawnSync',((_command:string,_args:string[],options:cp.SpawnSyncOptionsWithStringEncoding):cp.SpawnSyncReturns=>{ - spawns++;const input=JSON.parse(String(options.input));assert.deepEqual(input.create,[]); - return {pid:1,output:[],stdout:JSON.stringify(input.paths.map(()=>({owned:true,private:true,reparse:false,unsafeParent:false}))),stderr:'',status:0,signal:null}; - }) as unknown as typeof cp.spawnSync);syncBuiltinESMExports();process.env.SystemRoot='C:\\Windows'; + const mock=t.mock.method(cp,'spawnSync',(()=>{spawns++;throw new Error('no permission check may start a process');}) as unknown as typeof cp.spawnSync);syncBuiltinESMExports();process.env.SystemRoot='C:\\Windows'; try{ const platform=await import(pathToFileURL(platformFile).href) as typeof import('../../shared/platform.ts'); const inspection=await import(pathToFileURL(path.join(source,'setup/managed-inspection.ts')).href) as typeof import('../../setup/managed-inspection.ts'); - const counts:number[]=[]; const run=(call:()=>T)=>{ - spawns=0;const budget=new platform.PlatformRequestBudget(); + const budget=new platform.PlatformRequestBudget(); const result=platform.withPlatformRequestBudget(budget,call); - assert.equal(budget.securitySpawns,spawns);assert.ok(spawns<=6);counts.push(spawns);return result; + assert.equal(spawns,0);return result; }; const session=fresh?inspectFresh(f,freshRoot,(...args)=>run(()=>inspection.inspectManagedFreshStep(...args))): inspectAll(f,(...args)=>run(()=>inspection.inspectManagedStep(...args))); - spawns=0;const budget=new platform.PlatformRequestBudget(); + const budget=new platform.PlatformRequestBudget(); platform.withPlatformRequestBudget(budget,()=>fresh?inspection.validateManagedFreshInspectionReview(f.env,payload,session as ManagedFreshInspectionSession): inspection.validateManagedInspectionReview(f.env,payload,session as ManagedInspectionSession)); - assert.equal(budget.securitySpawns,spawns);assert.ok(spawns<=6); - t.diagnostic(JSON.stringify({kind,stages:counts,reviewAdmission:spawns})); + assert.equal(spawns,0); }finally{mock.mock.restore();syncBuiltinESMExports();} }finally{f.cleanup();} }}finally{if(original===undefined)delete process.env.SystemRoot;else process.env.SystemRoot=original;} diff --git a/tests/backend/managed-migration-steps.test.ts b/tests/backend/managed-migration-steps.test.ts index 72138f0..993f60c 100644 --- a/tests/backend/managed-migration-steps.test.ts +++ b/tests/backend/managed-migration-steps.test.ts @@ -85,19 +85,18 @@ test('a legacy install identity cannot be adopted as the managed selection',()=> }finally{f.cleanup();} }); -for(const exhausted of ['spawns','time'] as const)test(`prepare reserves settlement ${exhausted} before directory creation`,()=>{ +test('prepare refuses an exhausted deadline before directory creation',()=>{ const f=fixture();try{ - const budget=new PlatformRequestBudget(process.hrtime.bigint()-(exhausted==='time'?4_000_000_000n:0n)); - if(exhausted==='spawns')Atomics.store(budget.counter,0,2); - assert.throws(()=>begin(f,f.session,f.request,budget),{code:exhausted==='spawns'?'managed-step-budget':'managed-step-deadline'}); + const budget=new PlatformRequestBudget(process.hrtime.bigint()-18_000_000_000n); + assert.throws(()=>begin(f,f.session,f.request,budget),{code:'managed-step-deadline'}); assert.equal(fs.existsSync(path.dirname(migrationFile(f.env))),false); }finally{f.cleanup();} }); -test('a slow directory helper stops before journal publication and permits explicit retry',t=>{ +test('a slow directory creation stops before journal publication and permits explicit retry',t=>{ const f=fixture();try{ const clock=process.hrtime.bigint,started=clock(),file=migrationFile(f.env); - const mock=t.mock.method(process.hrtime,'bigint',()=>fs.existsSync(path.join(path.dirname(file),'.ownership.json'))?started+12_000_000_000n:started); + const mock=t.mock.method(process.hrtime,'bigint',()=>fs.existsSync(path.join(path.dirname(file),'.ownership.json'))?started+18_000_000_000n:started); try{assert.throws(()=>begin(f,f.session,f.request,new PlatformRequestBudget(started)),{code:'managed-step-deadline'});} finally{mock.mock.restore();} assert.equal(fs.existsSync(file),false);assert.equal(fs.existsSync(path.join(path.dirname(file),'.ownership.json')),true); @@ -132,7 +131,7 @@ test('status is read-only, reports no operation when absent, and refuses a diffe }finally{f.cleanup();} }); -test('integrated prepare, upgrade, retry and status obey the per-request launch ceiling',{skip:process.platform==='win32'},async t=>{ +test('integrated prepare, upgrade, retry and status start no process on the Windows path',{skip:process.platform==='win32'},async t=>{ const original=process.env.SystemRoot; try{for(const kind of ['manifest','selected','upgrade','receipt'] as const){ const f=fixture(kind);try{ @@ -142,20 +141,15 @@ test('integrated prepare, upgrade, retry and status obey the per-request launch const start=text.indexOf(" if (value.includes('\\0')",text.indexOf('function windowsPathsInner(')),end=text.indexOf(' let current = clean;',start); assert.ok(start>0&&end>start);text=text.slice(0,start)+" if (!path.isAbsolute(value) || path.resolve(value) !== value) throw new PlatformError('path-unverified');\n const clean = value;\n"+text.slice(end);fs.writeFileSync(platformFile,text); let spawns=0; - const mock=t.mock.method(cp,'spawnSync',((_command:string,_args:string[],options:cp.SpawnSyncOptionsWithStringEncoding):cp.SpawnSyncReturns=>{ - spawns++;const input=JSON.parse(String(options.input));for(const p of input.create)fs.mkdirSync(p,{mode:0o700}); - return {pid:1,output:[],stdout:JSON.stringify(input.paths.map(()=>({owned:true,private:true,reparse:false,unsafeParent:false}))),stderr:'',status:0,signal:null}; - }) as unknown as typeof cp.spawnSync);syncBuiltinESMExports();process.env.SystemRoot='C:\\Windows'; + const mock=t.mock.method(cp,'spawnSync',(()=>{spawns++;throw new Error('no permission check may start a process');}) as unknown as typeof cp.spawnSync);syncBuiltinESMExports();process.env.SystemRoot='C:\\Windows'; try{ const platform=await import(pathToFileURL(platformFile).href) as typeof import('../../shared/platform.ts'); const engine=await import(pathToFileURL(path.join(source,'setup/managed-step-engine.ts')).href) as typeof import('../../setup/managed-step-engine.ts'); - const counts:Record={}; for(const name of ['begin','retry','status'] as const){ - spawns=0;const budget=new platform.PlatformRequestBudget(); + const budget=new platform.PlatformRequestBudget(); platform.withPlatformRequestBudget(budget,()=>name==='status'?engine.observeManagedStep(f.env,f.request.operationId):engine.beginManagedStep(f.env,payload,f.request,budget,name==='begin'?f.session:undefined)); - assert.equal(budget.securitySpawns,spawns);assert.ok(spawns<=6);counts[name]=spawns; + assert.equal(spawns,0,`${kind} ${name}`); } - t.diagnostic(JSON.stringify({kind,...counts})); }finally{mock.mock.restore();syncBuiltinESMExports();} }finally{f.cleanup();} }}finally{if(original===undefined)delete process.env.SystemRoot;else process.env.SystemRoot=original;} diff --git a/tests/backend/managed-migration.test.ts b/tests/backend/managed-migration.test.ts index 0b5e5ea..4044c57 100644 --- a/tests/backend/managed-migration.test.ts +++ b/tests/backend/managed-migration.test.ts @@ -97,12 +97,12 @@ test('expectation publication failure preserves enabled legacy discovery before }); test('legacy controller creation failures preserve fixed diagnostics; HTTP no longer invokes that path',async t=>{ - for(const code of ['windows-security-unavailable','private-permissions','untrusted-message'] as const)await t.test(code,async t=>{ + for(const code of ['private-permissions','untrusted-message'] as const)await t.test(code,async t=>{ const f=fixture();try{ const review=f.review(),before=fs.readFileSync(path.join(f.legacyRoot,'.ownership.json')); const original=fs.mkdirSync; const mock=t.mock.method(fs,'mkdirSync',((file:any,...args:any[])=>{ - if(path.basename(String(file))==='agent-progress-managed')throw new PlatformError(code,'timeout'); + if(path.basename(String(file))==='agent-progress-managed')throw new PlatformError(code); return(original as any)(file,...args); })as typeof fs.mkdirSync);syncBuiltinESMExports(); const expected=code==='untrusted-message'?'storage':code; @@ -279,11 +279,11 @@ test('confirmed managed capture-off survives modified legacy ownership without a }); test('migration inspection preserves operational diagnostics instead of claiming an ownership conflict',async t=>{ - for(const phase of ['legacy','record'])for(const code of ['busy','corrupt','schema','storage','windows-security-unavailable']as const)await t.test(`${phase}: ${code}`,async t=>{ + for(const phase of ['legacy','record'])for(const code of ['busy','corrupt','schema','storage']as const)await t.test(`${phase}: ${code}`,async t=>{ const f=fixture();try{ if(phase==='record')f.migrate(); const original=Store.prototype.subagentRunStorage; - t.mock.method(Store.prototype,'subagentRunStorage',function(this:Store){if(this.file===f.legacy.database)throw code==='windows-security-unavailable'?new PlatformError(code):new ProgressError(code);return original.call(this);}); + t.mock.method(Store.prototype,'subagentRunStorage',function(this:Store){if(this.file===f.legacy.database)throw new ProgressError(code);return original.call(this);}); const status=f.setup.status();assert.equal(status.delivery!.migration,'unavailable');assert.ok(status.diagnostics.includes(code)); await http(f,async request=>{const r=await request('managed-inspect',{}),body=await r.json(); if(r.status!==409)t.diagnostic(JSON.stringify({status:r.status,code:body.error,ports:f.setup.writerTargets().map(writerTargetPort)})); diff --git a/tests/backend/managed-request-worker.test.ts b/tests/backend/managed-request-worker.test.ts index b7d2757..30cea12 100644 --- a/tests/backend/managed-request-worker.test.ts +++ b/tests/backend/managed-request-worker.test.ts @@ -102,7 +102,7 @@ test('ordinary source service entry still listens before cheap authenticated hea } finally {child.kill('SIGTERM');await exited;rmSync(root,{recursive:true,force:true});} }); -test('supervisor refuses overlap and uses shared attempt accounting',{skip:process.platform==='win32'},async()=>{ +test('supervisor refuses overlap and reports its own accounting, never the worker message',{skip:process.platform==='win32'},async()=>{ const {root,env}=fixture(); try { const entry=path.join(root,'held-worker.mjs'); @@ -115,22 +115,21 @@ setTimeout(()=>parentPort.close(),50);\n`,{mode:0o600}); const overlap=await worker.run(env,payload,{action:'health'}); assert.equal(overlap.ok,false);if(!overlap.ok)assert.equal(overlap.code,'managed-step-unsettled'); const result=await first;assert.equal(result.ok,true);assert.equal(worker.busy,false); - assert.equal(result.accounting.securitySpawns,0,'supervisor uses the shared attempt counter, not message accounting'); + assert.equal(result.accounting.securitySpawns,0,'supervisor accounting, not message accounting'); }finally{rmSync(root,{recursive:true,force:true});} }); -test('payload-free status shares one run and spawn budget only in the identical context',async()=>{ +test('payload-free status shares one run and its budget only in the identical context',async()=>{ const {root,env}=fixture(); try{ const entry=path.join(root,'counted-status.mjs'); writeFileSync(entry,`import {parentPort,workerData} from 'node:worker_threads'; -Atomics.add(new Int32Array(workerData.counter),0,3); parentPort.postMessage({requestId:workerData.requestId,result:{ok:true,value:'synthetic',accounting:{securitySpawns:99,elapsedMs:99}}}); parentPort.close();\n`,{mode:0o600}); const worker=new SetupRequestWorker(pathToFileURL(entry)); const first=worker.run(env,undefined,{action:'status'}); const shared=Array.from({length:4},()=>worker.run({...env},undefined,{action:'status'})); - for(const promise of shared)assert.equal(promise,first,'same run, not another worker or counter'); + for(const promise of shared)assert.equal(promise,first,'same run, not another worker'); for(const [otherEnv,otherPayload,request] of [ [{...env,LANG:'synthetic'},undefined,{action:'status'}], [env,undefined,{action:'status',descriptor:'changed'}], @@ -145,10 +144,10 @@ parentPort.close();\n`,{mode:0o600}); assert.ok(!refused.ok);assert.equal(refused.code,'managed-step-unsettled'); } const results=await Promise.all([first,...shared]); - for(const result of results){assert.equal(result,results[0]);assert.equal(result.accounting.securitySpawns,3);} + for(const result of results){assert.equal(result,results[0]);assert.equal(result.accounting.securitySpawns,0);} assert.equal(worker.busy,false); const fresh=worker.run(env,undefined,{action:'status'});assert.notEqual(fresh,first,'no settled-result cache'); - assert.equal((await fresh).accounting.securitySpawns,3); + assert.equal((await fresh).accounting.securitySpawns,0); }finally{rmSync(root,{recursive:true,force:true});} }); @@ -276,7 +275,7 @@ test('target-derived slots permit unrelated targets but fence same scopes and sh const shared=setupWriterTargets(b.env,path.join(a.root,'store/progress.sqlite')); await assert.rejects(acquireWriterSlots(shared),{code:'managed-step-port-busy'},'different discovery roots still serialize shared capture'); const store=writerTarget('store',path.join(a.root,'store')); - const budget=new PlatformRequestBudget(process.hrtime.bigint(),new SharedArrayBuffer(4),{port:writerTargetPort(first[0]!),nonce:'a'.repeat(64),targets:first}); + const budget=new PlatformRequestBudget(process.hrtime.bigint(),{targets:first}); withPlatformRequestBudget(budget,()=>{ requirePlatformStoreFence(path.join(a.root,'store/progress.sqlite')); assert.throws(()=>requirePlatformStoreFence(path.join(b.root,'store/progress.sqlite')),{code:'managed-step-conflict'}); diff --git a/tests/backend/managed-step-contract.test.ts b/tests/backend/managed-step-contract.test.ts index 717e309..54e03b8 100644 --- a/tests/backend/managed-step-contract.test.ts +++ b/tests/backend/managed-step-contract.test.ts @@ -2,7 +2,7 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { mkdtempSync, rmSync } from 'node:fs'; import { MANAGED_STEP_LIMITS, MANAGED_MIGRATION_STEPS, MANAGED_OPERATION_TRANSITIONS, - MANAGED_STEP_SPAWN_ALLOCATION, managedStepRequest, type ManagedStepRequest } from '../../shared/managed-steps.ts'; + managedStepRequest, type ManagedStepRequest } from '../../shared/managed-steps.ts'; import { managedStepFixtures, managedStepPlan } from '../fixtures/managed-steps.ts'; import type { SetupView } from '../../ui/shared/model.ts'; import type { ManagedDelivery } from '../../shared/progress.ts'; @@ -138,16 +138,9 @@ test('receipt-proven removal honestly lacks a manifest and starts only the remai assert.equal(journal.migration.legacy.ownershipDigest, createHash('sha256').update(manifest).digest('hex')); }); -test('all effect allocations reserve checkpoints/cleanup within the real-spawn ceiling', () => { - assert.deepEqual(Object.keys(MANAGED_STEP_SPAWN_ALLOCATION), [...MANAGED_MIGRATION_STEPS]); - for (const allocation of Object.values(MANAGED_STEP_SPAWN_ALLOCATION)) { - assert.ok(Object.values(allocation).reduce((sum, n) => sum + n, 0) <= MANAGED_STEP_LIMITS.securitySpawns); - assert.ok(allocation.checkpoint > 0 && allocation.cleanup > 0); - } - assert.ok(MANAGED_STEP_LIMITS.securitySpawns * 2_500 < MANAGED_STEP_LIMITS.workMs); +test('request deadlines stay ordered below the host limit', () => { assert.ok(MANAGED_STEP_LIMITS.workMs < MANAGED_STEP_LIMITS.responseMs); assert.ok(MANAGED_STEP_LIMITS.responseMs < MANAGED_STEP_LIMITS.hostMs); - // This checks allocation arithmetic only, not actual engine/native spawn counts. }); test('pause and abandonment cannot jump to complete or enable; completion is terminal', () => { diff --git a/tests/backend/managed-step-engine.test.ts b/tests/backend/managed-step-engine.test.ts index d3f692c..2fee91a 100644 --- a/tests/backend/managed-step-engine.test.ts +++ b/tests/backend/managed-step-engine.test.ts @@ -467,13 +467,15 @@ test('a second ambiguous capture interruption cannot reuse a consumed renewal',t for(const action of ['pause','abandon','resume'] as const)test(`fenced running intent supports ${action} without capture or removal`,t=>{ const f=fixture();try{ // Leave a durable running expectation intent, simulating process loss after - // publication. Exhaust accounting so this request cannot settle a failure. - const prior=f.journal(),budget=new PlatformRequestBudget(),rename=fs.renameSync,file=migrationFile(f.env); + // publication. Expire the deadline so this request cannot settle a failure. + const prior=f.journal(),started=process.hrtime.bigint(),budget=new PlatformRequestBudget(started),rename=fs.renameSync,file=migrationFile(f.env); + let expired=false; + const clock=t.mock.method(process.hrtime,'bigint',()=>expired?started+18_000_000_000n:started); const mock=t.mock.method(fs,'renameSync',((from:any,to:any)=>{ - rename(from,to);if(String(to)===file){Atomics.store(budget.counter,0,6);throw new Error('synthetic interruption');} + rename(from,to);if(String(to)===file){expired=true;throw new Error('synthetic interruption');} }) as typeof fs.renameSync);syncBuiltinESMExports(); try{assert.equal(withPlatformRequestBudget(budget,()=>advanceManagedStep(f.env,payload,f.request(),budget,prior)).disposition,'refused');} - finally{mock.mock.restore();syncBuiltinESMExports();} + finally{mock.mock.restore();clock.mock.restore();syncBuiltinESMExports();} const running=f.journal();assert.equal(running.migration.state,'running'); const database=fs.readFileSync(running.database),history=fs.readFileSync(path.join(f.targets.storeRoot,'installation-history.jsonl')); const reply=f.control(action),next=f.journal(); @@ -485,12 +487,13 @@ for(const action of ['pause','abandon','resume'] as const)test(`fenced running i }finally{f.cleanup();} }); -for(const exhausted of ['spawns','time'] as const)test(`advance reserves ${exhausted} before intent and any effect`,()=>{ +test('advance refuses an exhausted deadline before intent and any effect',()=>{ const f=fixture();try{ - const budget=new PlatformRequestBudget(process.hrtime.bigint()-(exhausted==='time'?7_000_000_000n:0n)),before=fs.readFileSync(migrationFile(f.env)); - if(exhausted==='spawns')Atomics.store(budget.counter,0,3); - const reply=withPlatformRequestBudget(budget,()=>advanceManagedStep(f.env,payload,f.request(),budget,f.journal())); - assert.equal(reply.disposition,'refused');assert.equal(reply.error!.code,exhausted==='spawns'?'managed-step-budget':'managed-step-deadline'); + // An already expired budget, used directly: the engine's own check before the + // intent is published refuses, ahead of any intent or effect. + const budget=new PlatformRequestBudget(process.hrtime.bigint()-18_000_000_000n),before=fs.readFileSync(migrationFile(f.env)); + const reply=advanceManagedStep(f.env,payload,f.request(),budget,f.journal()); + assert.equal(reply.disposition,'refused');assert.equal(reply.error!.code,'managed-step-deadline'); assert.deepEqual(fs.readFileSync(migrationFile(f.env)),before);assert.equal(fs.existsSync(managedExpectationFile(f.journal())),false); }finally{f.cleanup();} }); @@ -509,7 +512,7 @@ test('failed settlement surfaces a journal conflict instead of swallowing it as }finally{f.cleanup();} }); -test('every integrated effect and control fits six launches with fresh supervisor claims',{skip:process.platform==='win32'},async t=>{ +test('every integrated effect and control starts no process on the Windows path',{skip:process.platform==='win32'},async t=>{ const f=fixture(),originalSystemRoot=process.env.SystemRoot; try{ const source=path.join(f.root,'source');for(const dir of ['shared','setup'])fs.cpSync(path.resolve(dir),path.join(source,dir),{recursive:true}); @@ -518,56 +521,47 @@ test('every integrated effect and control fits six launches with fresh superviso const start=text.indexOf(" if (value.includes('\\0')",text.indexOf('function windowsPathsInner(')),end=text.indexOf(' let current = clean;',start); assert.ok(start>0&&end>start);text=text.slice(0,start)+" if (!path.isAbsolute(value) || path.resolve(value) !== value) throw new PlatformError('path-unverified');\n const clean = value;\n"+text.slice(end);fs.writeFileSync(file,text); let spawns=0; - const mock=t.mock.method(cp,'spawnSync',((_command:string,_args:string[],options:cp.SpawnSyncOptionsWithStringEncoding):cp.SpawnSyncReturns=>{ - spawns++;const input=JSON.parse(String(options.input));assert.deepEqual(input.create,[]); - return {pid:1,output:[],stdout:JSON.stringify(input.paths.map(()=>({owned:true,private:true,reparse:false,unsafeParent:false}))),stderr:'',status:0,signal:null}; - }) as unknown as typeof cp.spawnSync);syncBuiltinESMExports();process.env.SystemRoot='C:\\Windows'; + const mock=t.mock.method(cp,'spawnSync',(()=>{spawns++;throw new Error('no permission check may start a process');}) as unknown as typeof cp.spawnSync);syncBuiltinESMExports();process.env.SystemRoot='C:\\Windows'; try{ const platform=await import(pathToFileURL(file).href) as typeof import('../../shared/platform.ts'); const engine=await import(pathToFileURL(path.join(source,'setup/managed-step-engine.ts')).href) as typeof import('../../setup/managed-step-engine.ts'); - const counts:Array<{step:string;spawns:number}>=[]; for(const action of ['pause','abandon','resume'] as const){ - const prior=f.journal(),budget=new platform.PlatformRequestBudget();spawns=0; + const prior=f.journal(),budget=new platform.PlatformRequestBudget(); const request={version:1 as const,action,operationId:prior.migration.operationId,expectedSequence:prior.migration.sequence}; const reply=platform.withPlatformRequestBudget(budget,()=>engine.controlManagedStep(f.env,payload,request,budget,prior)); - assert.equal(reply.disposition,'applied');assert.equal(spawns,budget.securitySpawns);assert.ok(spawns<=6); - counts.push({step:action,spawns}); + assert.equal(reply.disposition,'applied');assert.equal(spawns,0); } while(f.journal().migration.state!=='complete'){ - const prior=f.journal(),request=f.request(),budget=new platform.PlatformRequestBudget();spawns=0; + const prior=f.journal(),request=f.request(),budget=new platform.PlatformRequestBudget(); const reply=platform.withPlatformRequestBudget(budget,()=>engine.advanceManagedStep(f.env,payload,request,budget,prior)); - assert.equal(reply.disposition,'applied',`${request.step.name}: ${JSON.stringify(reply.error)}`);assert.equal(spawns,budget.securitySpawns);assert.ok(spawns<=6); - counts.push({step:`${request.step.name}:${request.step.batch}`,spawns}); - spawns=0;const replayBudget=new platform.PlatformRequestBudget(); + assert.equal(reply.disposition,'applied',`${request.step.name}: ${JSON.stringify(reply.error)}`);assert.equal(spawns,0); + const replayBudget=new platform.PlatformRequestBudget(); assert.equal(platform.withPlatformRequestBudget(replayBudget,()=>engine.advanceManagedStep(f.env,payload,request,replayBudget,reply.journal)).disposition,'replayed'); - assert.ok(spawns<=6); + assert.equal(spawns,0); } - t.diagnostic(JSON.stringify({effects:counts})); }finally{mock.mock.restore();syncBuiltinESMExports();} }finally{if(originalSystemRoot===undefined)delete process.env.SystemRoot;else process.env.SystemRoot=originalSystemRoot;f.cleanup();} }); -test('full fresh engine counts every creation, settlement, failure, replay and control launch',{skip:process.platform==='win32'},async t=>{ +test('full fresh engine starts no process for creation, settlement, replay or control on the Windows path',{skip:process.platform==='win32'},async t=>{ const sourceRoot=fs.mkdtempSync('/tmp/opencode/fresh-engine-counts-'),systemRoot=process.env.SystemRoot; + // The projected Windows path creates ordinary directories; a restrictive umask + // keeps the POSIX-side fixture readers satisfied. + const umask=process.umask(0o077); try{ const source=path.join(sourceRoot,'source');for(const dir of ['shared','setup'])fs.cpSync(path.resolve(dir),path.join(source,dir),{recursive:true}); const file=path.join(source,'shared/platform.ts');let text=fs.readFileSync(file,'utf8'); text=text.replace("export const windows = process.platform === 'win32';",'export const windows = true;'); const start=text.indexOf(" if (value.includes('\\0')",text.indexOf('function windowsPathsInner(')),end=text.indexOf(' let current = clean;',start); assert.ok(start>0&&end>start);text=text.slice(0,start)+" if (!path.isAbsolute(value) || path.resolve(value) !== value) throw new PlatformError('path-unverified');\n const clean = value;\n"+text.slice(end);fs.writeFileSync(file,text); - let spawns=0,failAt=0; - const mock=t.mock.method(cp,'spawnSync',((_command:string,_args:string[],options:cp.SpawnSyncOptionsWithStringEncoding):cp.SpawnSyncReturns=>{ - spawns++;if(failAt===spawns)return {pid:1,output:[],stdout:'',stderr:'',status:1,signal:null}; - const input=JSON.parse(String(options.input));for(const dir of input.create)fs.mkdirSync(dir,{mode:0o700}); - return {pid:1,output:[],stdout:JSON.stringify(input.paths.map(()=>({owned:true,private:true,reparse:false,unsafeParent:false}))),stderr:'',status:0,signal:null}; - }) as unknown as typeof cp.spawnSync);syncBuiltinESMExports();process.env.SystemRoot='C:\\Windows'; + let spawns=0; + const mock=t.mock.method(cp,'spawnSync',(()=>{spawns++;throw new Error('no permission check may start a process');}) as unknown as typeof cp.spawnSync);syncBuiltinESMExports();process.env.SystemRoot='C:\\Windows'; try{ const platform=await import(pathToFileURL(file).href) as typeof import('../../shared/platform.ts'); const engine=await import(pathToFileURL(path.join(source,'setup/managed-step-engine.ts')).href) as typeof import('../../setup/managed-step-engine.ts'); - const counts:Record={}; const run=(name:string,fn:(budget:InstanceType)=>T)=>{ - spawns=0;const budget=new platform.PlatformRequestBudget();try{return platform.withPlatformRequestBudget(budget,()=>fn(budget));} - finally{assert.equal(spawns,budget.securitySpawns,name);assert.ok(spawns<=6,`${name}: ${spawns}`);counts[name]=Math.max(counts[name]??0,spawns);} + const budget=new platform.PlatformRequestBudget();try{return platform.withPlatformRequestBudget(budget,()=>fn(budget));} + finally{assert.equal(spawns,0,name);} }; const begin=(f:ReturnType)=>{const session=f.review();return run('prepare',b=>engine.beginManagedStep(f.env,payload,{version:2,action:'begin',operationId:'11111111-1111-4111-8111-111111111111',confirmed:true,expected:session.review!.expected},b,session));}; const advance=(f:ReturnType)=>run(f.request().step.name,b=>engine.advanceManagedStep(f.env,payload,f.request(),b,f.journal())); @@ -581,27 +575,6 @@ test('full fresh engine counts every creation, settlement, failure, replay and c } } }finally{f.cleanup();}} - assert.deepEqual(Object.fromEntries(['prepare','store-directory','create-store','expectation','register-source','publish-binding','enable','reconcile','replay','pause','abandon','resume'].map(n=>[n,counts[n]])), - {prepare:6,'store-directory':6,'create-store':6,expectation:5,'register-source':5,'publish-binding':5,enable:5,reconcile:5,replay:1,pause:3,abandon:3,resume:3}); - for(let attempt=1;attempt<=6;attempt++){ - const f=freshFixture();try{ - failAt=attempt;assert.throws(()=>begin(f),{code:'windows-security-unavailable'});counts['failed-prepare']=Math.max(counts['failed-prepare']??0,spawns); - assert.equal(fs.existsSync(f.storeRoot),false); - }finally{failAt=0;f.cleanup();} - } - // Fail every charged boundary of each full effect, including completion - // and readback. Six-slot paths retain uncertain intent when settlement - // cannot fit; never borrow a seventh launch for diagnostics/cleanup. - for(const name of ['store-directory','create-store','expectation','register-source','publish-binding','enable','reconcile'])for(let attempt=1;attempt<=counts[name]!;attempt++){ - const f=freshFixture();try{ - begin(f);while(f.journal().migration.step?.name!==name)assert.equal(advance(f).disposition,'applied'); - failAt=attempt; - try{const r=run('failed-'+name,b=>engine.advanceManagedStep(f.env,payload,f.request(),b,f.journal()));assert.equal(r.disposition,'refused');} - catch(e){assert.equal((e as {code:string}).code,'windows-security-unavailable');} - finally{failAt=0;} - }finally{f.cleanup();} - } - t.diagnostic(JSON.stringify({freshEngineSecuritySpawns:counts})); }finally{mock.mock.restore();syncBuiltinESMExports();} - }finally{if(systemRoot===undefined)delete process.env.SystemRoot;else process.env.SystemRoot=systemRoot;fs.rmSync(sourceRoot,{recursive:true,force:true});} + }finally{process.umask(umask);if(systemRoot===undefined)delete process.env.SystemRoot;else process.env.SystemRoot=systemRoot;fs.rmSync(sourceRoot,{recursive:true,force:true});} }); diff --git a/tests/backend/managed-step-http.test.ts b/tests/backend/managed-step-http.test.ts index 0513982..fe93ca3 100644 --- a/tests/backend/managed-step-http.test.ts +++ b/tests/backend/managed-step-http.test.ts @@ -24,24 +24,16 @@ const payload={plugin:'// synthetic managed',guidance:'synthetic guidance',remov const operationId='11111111-1111-4111-8111-111111111111'; const projection=fs.mkdtempSync('/tmp/opencode/managed-http-source-'); const spawnSync=cp.spawnSync,systemRoot=process.env.SystemRoot; -let legacySpawns=0; -let legacySpawnDelay=0; -let legacySpawnLaterDelay=0,legacySpawnTimeout=false; -let legacySpawnEffect:(()=>void)|undefined; +let legacySpawns=0,priorUmask=0o022; let Controller:typeof import('../../service/setup-controller.ts').SetupController,serverFactory:typeof import('../../service/server.ts').createProgressServer,windowsServerFactory:typeof serverFactory; before(async()=>{ - // The compatibility routes remain in the controller on the main thread. - // Count their actual process boundary too, without using native PowerShell. + // The compatibility routes remain in the controller on the main thread. No + // permission check may start a process: count any attempt and refuse it. process.env.SystemRoot='C:\\Windows'; - cp.spawnSync=((_command:string,_args:string[],options:cp.SpawnSyncOptionsWithStringEncoding):cp.SpawnSyncReturns=>{ - legacySpawns++; - const ms=legacySpawnDelay||legacySpawnLaterDelay;legacySpawnDelay=0; - if(ms)Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms); - if(legacySpawnTimeout)return {pid:1,output:[],stdout:'',stderr:'',status:null,signal:null,error:Object.assign(new Error('synthetic timeout'),{code:'ETIMEDOUT'})}; - const effect=legacySpawnEffect;legacySpawnEffect=undefined;effect?.(); - const input=JSON.parse(String(options.input));for(const p of input.create)fs.mkdirSync(p,{mode:0o700}); - return {pid:1,output:[],stdout:JSON.stringify(input.paths.map(()=>({owned:true,private:true,reparse:false,unsafeParent:false}))),stderr:'',status:0,signal:null}; - }) as typeof cp.spawnSync; + // The projected Windows path creates ordinary directories; a restrictive umask + // keeps this test's POSIX-side readers satisfied. + priorUmask=process.umask(0o077); + cp.spawnSync=(()=>{legacySpawns++;throw new Error('no permission check may start a process');}) as unknown as typeof cp.spawnSync; syncBuiltinESMExports(); for(const dir of ['shared','setup','service'])fs.cpSync(path.resolve(dir),path.join(projection,dir),{recursive:true}); fs.symlinkSync(path.resolve('node_modules'),path.join(projection,'node_modules'),'dir'); @@ -68,7 +60,7 @@ before(async()=>{ fs.writeFileSync(path.join(projection,'service/server-windows.ts'),serverSource.replace("process.platform==='win32'",'true')); windowsServerFactory=(await import(pathToFileURL(path.join(projection,'service/server-windows.ts')).href)).createProgressServer; }); -after(()=>{cp.spawnSync=spawnSync;syncBuiltinESMExports();if(systemRoot===undefined)delete process.env.SystemRoot;else process.env.SystemRoot=systemRoot;fs.rmSync(projection,{recursive:true,force:true});}); +after(()=>{process.umask(priorUmask);cp.spawnSync=spawnSync;syncBuiltinESMExports();if(systemRoot===undefined)delete process.env.SystemRoot;else process.env.SystemRoot=systemRoot;fs.rmSync(projection,{recursive:true,force:true});}); async function fixture(kind:'manifest'|'receipt'|'empty'|'selector'='manifest',windowsRoutes=false){ const root=fs.mkdtempSync('/tmp/opencode/managed-http-fixture-'),env=isolatedEnvironment(root); @@ -85,7 +77,7 @@ async function fixture(kind:'manifest'|'receipt'|'empty'|'selector'='manifest',w writeMigration(env,{binding:{...evidence.binding,installId:'managed-synthetic'},legacyInstallId:evidence.binding.installId,phase:'pending'}); lifecycle('remove-capture',targets); } - Object.assign(env,{TEST_WINDOWS:'1',TEST_FAULT_FILE:path.join(root,'fault.json'),TEST_READY_FILE:path.join(root,'ready'),TEST_RELEASE_FILE:path.join(root,'release')}); + Object.assign(env,{TEST_FAULT_FILE:path.join(root,'fault.json'),TEST_READY_FILE:path.join(root,'ready'),TEST_RELEASE_FILE:path.join(root,'release')}); const worker=pathToFileURL(path.join(projection,'tests/backend/managed-http-worker.ts')); const setup=new Controller({env},()=>payload,undefined,undefined,worker),server=(windowsRoutes?windowsServerFactory:serverFactory)(undefined,'synthetic-http-fixture',undefined,setup); server.listen(0,'127.0.0.1');await once(server,'listening'); @@ -98,13 +90,13 @@ async function fixture(kind:'manifest'|'receipt'|'empty'|'selector'='manifest',w const counts:Array<{step:string;spawns:number}>=[]; const dispatch=setup.request.bind(setup); setup.request=async(request,startedAt)=>{ - const result=await dispatch(request,startedAt);assert.ok(result.accounting.securitySpawns<=6); + const result=await dispatch(request,startedAt);assert.equal(result.accounting.securitySpawns,0); if(request.action!=='managed-step')counts.push({step:request.action,spawns:result.accounting.securitySpawns}); return result; }; const step=async(request:ManagedStepRequest)=>{ const response=await http('/v1/setup/managed-step',request),body=response.body as ManagedStepResponse; - assert.equal(body.version,1);assert.ok(body.accounting.securitySpawns<=6);counts.push({step:request.action==='advance'?`${request.step.name}:${request.step.batch}`:request.action,spawns:body.accounting.securitySpawns}); + assert.equal(body.version,1);assert.equal(body.accounting.securitySpawns,0);counts.push({step:request.action==='advance'?`${request.step.name}:${request.step.batch}`:request.action,spawns:body.accounting.securitySpawns}); if('operationId' in request&&body.progress)assert.equal(body.progress.operationId,request.operationId); if(body.disposition==='applied'||body.disposition==='replayed'){ assert.equal(body.progress!.sequence,request.action==='begin'?1:'expectedSequence' in request?request.expectedSequence+1:NaN); @@ -149,7 +141,7 @@ async function freshHttpFixture(kind:'default'|'custom'|'retained-new'|'retained } const step=async(request:ManagedFreshStepRequest)=>{ const r=await f.http('/v1/setup/managed-step',request),body=r.body as ManagedFreshStepResponse; - assert.equal(body.version,2);assert.ok(body.accounting.securitySpawns<=6); + assert.equal(body.version,2);assert.equal(body.accounting.securitySpawns,0); assert.equal(body.error===null,r.status===200);if(body.progress)assert.equal(body.progress.planKind,'fresh'); f.counts.push({step:request.action==='advance'?request.step.name:request.action,spawns:body.accounting.securitySpawns}); return {...r,body}; @@ -319,7 +311,7 @@ test('fresh wire refuses a retained migration journal without translating or mut for(const body of [{version:2,action:'status',operationId},{version:2,action:'pause',operationId,expectedSequence:p.sequence}, {version:2,action:'begin',operationId,confirmed:true,expected:'a'.repeat(64)}]){ const r=await f.http('/v1/setup/managed-step',body);assert.equal(r.status,409);assert.equal(r.body.version,2);assert.equal(r.body.progress,null); - assert.equal(r.body.error.code,'managed-journal-unsupported');assert.ok(r.body.accounting.securitySpawns<=6);assert.deepEqual(fs.readFileSync(migrationFile(f.env)),bytes); + assert.equal(r.body.error.code,'managed-journal-unsupported');assert.equal(r.body.accounting.securitySpawns,0);assert.deepEqual(fs.readFileSync(migrationFile(f.env)),bytes); } }finally{await f.close();} }); @@ -495,7 +487,7 @@ for(const kind of ['receipt','empty'] as const)test(`Setup UI client capture con assert.deepEqual(result,{ok:false,code:'managed-step-port-busy'}); }finally{await release();} assert.equal((await f.http('/v1/setup')).body.captureEnabled,true); - for(const code of ['private-permissions','windows-security-unavailable']){ + for(const code of ['private-permissions','path-unverified']){ f.fault({platformCode:code}); assert.deepEqual(await setupCall(host,'managed-disable',null,true,undefined,capability),{ok:false,code}); } @@ -551,7 +543,7 @@ test('HTTP legacy compatibility refusal has zero writes or worker launches',asyn const r=await f.http('/v1/setup/'+route,route==='managed-inspect'?{}:{confirmed:true,expected:'a'.repeat(64)}); assert.equal(r.status,409);assert.deepEqual(r.body,{error:'managed-action-required'}); const spawns=legacySpawns-before;counts.push({route,spawns}); - assert.ok(spawns<=(route==='managed-migrate'?0:6));assert.ok(performance.now()-started<=8000); + assert.equal(spawns,0);assert.ok(performance.now()-started<=8000); } assert.equal(fs.existsSync(f.env.TEST_READY_FILE!),false);assert.equal(fs.existsSync(migrationFile(f.env)),false); assert.deepEqual(fs.readFileSync(path.join(f.targets.storeRoot,'progress.sqlite')),before); @@ -559,7 +551,7 @@ test('HTTP legacy compatibility refusal has zero writes or worker launches',asyn }finally{await f.close();} }); -test('HTTP fresh inspection and configuration retain legacy consent and spawn budgets',async t=>{ +test('HTTP fresh inspection and configuration retain legacy consent and start no process',async t=>{ const f=await fixture('empty');try{ const before=legacySpawns; const inspected=await f.http('/v1/setup/managed-inspect',{storeRoot:f.targets.storeRoot}); @@ -583,51 +575,12 @@ test('HTTP fresh inspection and configuration retain legacy consent and spawn bu assert.equal(configured.body.configured,true);assert.equal(configured.body.verified,true); assert.equal(configured.body.delivery.migration,'none'); assert.equal(configured.body.captureEnabled,true);assert.equal(fs.existsSync(migrationFile(f.env)),false); - assert.ok(inspectSpawns<=3,`inspect: ${inspectSpawns}`);assert.ok(configureSpawns<=24,`configure: ${configureSpawns}`); + assert.equal(inspectSpawns,0);assert.equal(configureSpawns,0); assert.equal((await f.http('/v1/setup')).body.configured,true); t.diagnostic(JSON.stringify({kind:'fresh',inspectSpawns,configureSpawns})); }finally{await f.close();} }); -for(const kind of ['manifest','empty'] as const)test(`HTTP cold security query on ${kind} compatibility inspection`,async()=>{ - const f=await fixture(kind);try{ - legacySpawnDelay=4500;legacySpawnLaterDelay=350; - const started=performance.now(),before=legacySpawns; - const r=await f.http('/v1/setup/managed-inspect',{storeRoot:f.targets.storeRoot}); - assert.equal(r.status,kind==='manifest'?409:200,JSON.stringify(r.body)); - if(kind==='manifest'){ - assert.deepEqual(r.body,{error:'managed-action-required'}); - assert.equal(legacySpawns-before,0,'refusal needs no security authority'); - assert.ok(performance.now()-started<8000); - }else{ - assert.ok(r.body.delivery.review.expected); - assert.ok(performance.now()-started>5000,'request receipt timeout is not a handler deadline'); - assert.ok(performance.now()-started<18000); - assert.equal(fs.existsSync(f.targets.storeRoot),false); - legacySpawnDelay=4500; - const configuring=performance.now(); - const configured=await f.http('/v1/setup/managed-configure',{storeRoot:f.targets.storeRoot,confirmed:true,expected:r.body.delivery.review.expected}); - assert.equal(configured.status,200,JSON.stringify(configured.body)); - assert.equal(configured.body.configured,true);assert.equal(configured.body.captureEnabled,true); - assert.ok(performance.now()-configuring>5000); - assert.ok(performance.now()-configuring<18000,'cold configure fits the host budget in this representative latency case'); - } - assert.equal(fs.existsSync(migrationFile(f.env)),false); - }finally{legacySpawnDelay=0;legacySpawnLaterDelay=0;await f.close();} -}); - -for(const action of ['managed-inspect','managed-configure'] as const)test(`HTTP fresh ${action} helper timeout retains its precise code without writes`,async()=>{ - const f=await fixture('empty');try{ - const expected=action==='managed-configure'?(await f.http('/v1/setup/managed-inspect',{storeRoot:f.targets.storeRoot})).body.delivery.review.expected:undefined; - legacySpawnTimeout=true; - const r=await f.http('/v1/setup/'+action,{storeRoot:f.targets.storeRoot,...(expected?{confirmed:true,expected}:{})}); - assert.equal(r.status,503);assert.deepEqual(r.body,{error:'windows-security-unavailable'}); - assert.equal(fs.existsSync(f.targets.storeRoot),false);assert.equal(fs.existsSync(path.dirname(migrationFile(f.env))),false); - legacySpawnTimeout=false; - assert.equal((await f.http('/v1/setup/managed-inspect',{storeRoot:f.targets.storeRoot})).status,200,'retry validates afresh'); - }finally{legacySpawnTimeout=false;await f.close();} -}); - test('HTTP legacy refusal with the native concurrent-health observer never enters its main-thread hold',async t=>{ const f=await fixture();let service:Awaited>|undefined; try{ @@ -658,14 +611,14 @@ test('HTTP fresh routes refuse ambiguous legacy plus managed selection without c test('HTTP fresh routes never treat an existing unknown journal as fresh configuration',async()=>{ const f=await fixture('empty');try{ createManagedBindingDirectory(f.env);fs.writeFileSync(migrationFile(f.env),'unknown journal',{mode:0o600}); - const before=legacySpawns;legacySpawnTimeout=true; + const before=legacySpawns; for(const route of ['managed-inspect','managed-configure']){ const r=await f.http('/v1/setup/'+route,route==='managed-inspect'?{}:{confirmed:true,expected:'a'.repeat(64)}); assert.equal(r.status,409);assert.deepEqual(r.body,{error:'managed-action-required'}); } assert.equal(fs.readFileSync(migrationFile(f.env),'utf8'),'unknown journal');assert.equal(fs.existsSync(f.targets.storeRoot),false); - assert.equal(legacySpawns,before,'journal presence refusal needs no security query'); - }finally{legacySpawnTimeout=false;await f.close();} + assert.equal(legacySpawns,before,'journal presence refusal starts no process'); + }finally{await f.close();} }); test('HTTP fresh confirmation refuses legacy discovery appearing after review',async()=>{ @@ -679,16 +632,20 @@ test('HTTP fresh confirmation refuses legacy discovery appearing after review',a }finally{await f.close();} }); -test('HTTP absent presence hint cannot authorize configuration when legacy appears during fresh validation',async()=>{ +test('HTTP absent presence hint cannot authorize configuration when legacy appears during fresh validation',async t=>{ const f=await fixture('empty');try{ const review=(await f.http('/v1/setup/managed-inspect',{storeRoot:f.targets.storeRoot})).body.delivery.review; const legacy=path.join(f.targets.configRoot,'plugins/agent-progress'); - legacySpawnEffect=()=>fs.mkdirSync(legacy,{recursive:true,mode:0o700}); + // The first canonical path resolution happens only in the full validation, + // after the presence hint found nothing: make legacy appear exactly then. + const real=fs.realpathSync.native;let appeared=false; + t.mock.method(fs.realpathSync,'native',((...args:Parameters)=>{if(!appeared){appeared=true;fs.mkdirSync(legacy,{recursive:true,mode:0o700});}return real(...args);}) as typeof real); const result=await f.http('/v1/setup/managed-configure',{storeRoot:f.targets.storeRoot,confirmed:true,expected:review.expected}); + assert.equal(appeared,true,'legacy appeared during fresh validation'); assert.equal(result.status,409);assert.deepEqual(result.body,{error:'managed-action-required'}); assert.equal(fs.existsSync(f.targets.storeRoot),false);assert.equal(fs.existsSync(path.dirname(migrationFile(f.env))),false); assert.deepEqual(fs.readdirSync(legacy),[]); - }finally{legacySpawnEffect=undefined;await f.close();} + }finally{t.mock.restoreAll();await f.close();} }); test('HTTP empty Setup omits progress and does not create metadata',async()=>{ @@ -696,7 +653,7 @@ test('HTTP empty Setup omits progress and does not create metadata',async()=>{ const read=await f.http('/v1/setup');assert.equal(read.status,200);assert.equal(read.body.delivery.managedMigrationSteps,1); assert.equal(Object.hasOwn(read.body.delivery,'migrationProgress'),false);assert.equal(read.body.captureEnabled,null); assert.equal((await f.http('/health')).body.state,'unconfigured');assert.equal(fs.existsSync(migrationFile(f.env)),false); - assert.ok(f.counts.every(c=>c.spawns<=6)); + assert.ok(f.counts.every(c=>c.spawns===0)); }finally{await f.close();} }); @@ -731,7 +688,7 @@ test('HTTP capture enable refuses an idle paused migration while disable remains test('HTTP capture routes preserve precise platform fault codes without changing capture',async()=>{ const f=await fixture('receipt');try{ let p=(await f.begin()).body.progress!;while(p.state!=='complete')p=(await f.advance(p)).body.progress!; - for(const code of ['private-permissions','windows-security-unavailable']){ + for(const code of ['private-permissions','path-unverified']){ f.fault({platformCode:code}); for(const enabled of [false,true]){ const r=await f.http(`/v1/capture/${enabled?'enable':'disable'}`,{}); @@ -778,7 +735,7 @@ for(const recovery of ['interrupted','capture-review'] as const)test(`real HTTP assert.deepEqual(requests[resumeAt+1],{version:1,action:'advance',operationId,expectedSequence:p.sequence+1,step:p.step}); assert.equal(driver.state.progress?.state,'complete');assert.equal(driver.state.outcome,null); assert.equal(maxInflight,1);assert.equal(f.capture(),true); - assert.ok(replies.every(r=>r.accounting.securitySpawns<=6)); + assert.ok(replies.every(r=>r.accounting.securitySpawns===0)); }finally{await f.close();} }); @@ -901,7 +858,6 @@ test('HTTP diagnostics preserve owner failures, corrupt journals and missing mar f.fault({ownerCode});const r=await f.advance(p);assert.equal(r.status,status);assert.equal(r.body.error!.code,code);assert.equal(r.body.error!.stage,'expectation');assert.equal(r.body.progress!.sequence,p.sequence); assert.ok(!JSON.stringify(r.body).includes('not public'));assert.deepEqual(fs.readFileSync(migrationFile(f.env)),bytes);f.fault({});p=await f.status(); } - f.fault({securityError:'managed-step-unsettled'});const fence=await f.advance(p);assert.equal(fence.status,503);assert.equal(fence.body.error!.code,'managed-step-unsettled');f.fault({}); fs.writeFileSync(migrationFile(f.env),'corrupt',{mode:0o600}); const first=await f.step({version:1,action:'inspect'});assert.equal(first.status,200); const corrupt=await f.step({version:1,action:'inspect',cursor:first.body.inspection!.cursor!});assert.equal(corrupt.status,409);assert.equal(corrupt.body.error!.code,'managed-journal-unsupported');assert.equal(corrupt.body.error!.stage,'managed-state'); @@ -911,12 +867,12 @@ test('HTTP diagnostics preserve owner failures, corrupt journals and missing mar }finally{await f.close();} }); -for(const exhausted of ['spawns','time'] as const)test(`HTTP pre-effect ${exhausted} exhaustion is a bounded refusal, not partial success`,async()=>{ +test('HTTP pre-effect deadline exhaustion is a bounded refusal, not partial success',async()=>{ const f=await fixture();try{ const p=(await f.begin()).body.progress!,before=fs.readFileSync(migrationFile(f.env)); - f.fault(exhausted==='spawns'?{spentSpawns:3}:{clockOffset:7000}); - const r=await f.advance(p);assert.equal(r.status,503);assert.equal(r.body.error!.code,exhausted==='spawns'?'managed-step-budget':'managed-step-deadline'); - assert.equal(r.body.progress!.sequence,p.sequence);assert.deepEqual(fs.readFileSync(migrationFile(f.env)),before);assert.equal(f.capture(),true); + f.fault({clockOffset:18000}); + const r=await f.advance(p);assert.equal(r.status,503);assert.equal(r.body.error!.code,'managed-step-deadline'); + assert.ok(r.body.progress===null||r.body.progress.sequence===p.sequence);assert.deepEqual(fs.readFileSync(migrationFile(f.env)),before);assert.equal(f.capture(),true); }finally{await f.close();} }); diff --git a/tests/backend/managed-step-journal.test.ts b/tests/backend/managed-step-journal.test.ts index 82f3915..0642008 100644 --- a/tests/backend/managed-step-journal.test.ts +++ b/tests/backend/managed-step-journal.test.ts @@ -6,7 +6,6 @@ import {syncBuiltinESMExports} from 'node:module'; import {managedStepFixtures} from '../fixtures/managed-steps.ts'; import {createFixtureBinding} from '../fixtures/managed.ts'; import {canonical,digest,Store} from '../../shared/store.ts'; -import {platformSecurityScope} from '../../shared/platform.ts'; import {publishPrivateJson} from '../../shared/managed-binding.ts'; import {parseManagedStepJournal,managedTargetDigest,managedRequestDigest,managedJournalProgress,type ManagedStepJournal} from '../../setup/managed-step-journal.ts'; import {readManagedStepJournal,writeManagedStepJournal,publishManagedStepIntent,validatePublishedManagedIntent,validateManagedJournalChange,migrationFile,readMigration} from '../../setup/managed-migration.ts'; @@ -171,7 +170,6 @@ test('private journal publication is no-clobber, compare-before-replace and read assert.deepEqual(readManagedStepJournal(f.env),next); assert.throws(()=>writeManagedStepJournal(f.env,control(f.journal,'paused'),f.journal),{code:'managed-step-conflict'}); assert.throws(()=>readMigration(f.env),{code:'managed-migration-conflict'},'older reader fails closed'); - assert.throws(()=>platformSecurityScope(()=>writeManagedStepJournal(f.env,control(next,'paused'),next)),{code:'managed-step-conflict'},'nested scopes do not clear outer authority'); }finally{f.cleanup();} }); diff --git a/tests/backend/managed-step-prepare-budget.test.ts b/tests/backend/managed-step-prepare-budget.test.ts deleted file mode 100644 index 5dc00b7..0000000 --- a/tests/backend/managed-step-prepare-budget.test.ts +++ /dev/null @@ -1,142 +0,0 @@ -import {test} from 'node:test'; -import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import path from 'node:path'; -import cp from 'node:child_process'; -import {syncBuiltinESMExports} from 'node:module'; -import {pathToFileURL} from 'node:url'; -import {lifecycle} from '../../setup/lifecycle.ts'; - -/** Feasibility measurement, not engine acceptance or native Windows evidence. - * Keep the existing directory helper, query sites, cache scopes and snapshots. - * Only the path dialect and actual OS process boundary are substituted. */ -test('existing managed bootstrap fits six launches with fresh known-path batches', {skip:process.platform==='win32'}, async t=>{ - const root=fs.mkdtempSync('/tmp/opencode/prepare-spawns-'); - const originalSystemRoot=process.env.SystemRoot; - try { - const source=path.join(root,'source'); - for(const dir of ['shared','setup'])fs.cpSync(path.resolve(dir),path.join(source,dir),{recursive:true}); - const platformFile=path.join(source,'shared/platform.ts'); - let text=fs.readFileSync(platformFile,'utf8'); - assert.ok(text.includes("export const windows = process.platform === 'win32';")); - text=text.replace("export const windows = process.platform === 'win32';",'export const windows = true;'); - const start=text.indexOf(" if (value.includes('\\0')",text.indexOf('function windowsPathsInner(')); - const end=text.indexOf(' let current = clean;',start); - assert.ok(start>0&&end>start); - text=text.slice(0,start)+" if (!path.isAbsolute(value) || path.resolve(value) !== value) throw new PlatformError('path-unverified');\n const clean = value;\n"+text.slice(end); - fs.writeFileSync(platformFile,text); - const env={HOME:path.join(root,'home space ü')}; - const configRoot=path.join(env.HOME,'.config/opencode'),dataRoot=path.join(env.HOME,'.local/share/opencode'); - for(const dir of [env.HOME,configRoot,dataRoot])fs.mkdirSync(dir,{recursive:true,mode:0o700}); - const targets={configRoot,dataRoot,storeRoot:path.join(dataRoot,'openchamber-progress'),confirmed:true}; - lifecycle('install',targets,{plugin:'// Synthetic',guidance:'Synthetic',removal:'// Synthetic',version:'1.1.1'}); - // Fixture enumeration supplies claims, never security authority. The fresh - // batch below and the real lifecycle owner validate all of them again. - const paths:string[]=[]; - function discover(file:string){paths.push(file);if(fs.lstatSync(file).isDirectory())for(const name of fs.readdirSync(file))discover(path.join(file,name));} - discover(env.HOME); - let spawns=0,afterSpawn:()=>void=()=>{}; - t.mock.method(cp,'spawnSync',((command:string,_args:string[],options:cp.SpawnSyncOptionsWithStringEncoding):cp.SpawnSyncReturns=>{ - assert.equal(path.basename(command),'powershell.exe'); - spawns++; - const request=JSON.parse(String(options.input)) as {paths:string[];create:string[]}; - for(const dir of request.create)fs.mkdirSync(dir,{mode:0o700}); - afterSpawn(); - return {pid:1,output:[],stdout:JSON.stringify(request.paths.map(()=>({owned:true,private:true,reparse:false,unsafeParent:false}))),stderr:'',status:0,signal:null}; - }) as unknown as typeof cp.spawnSync); - syncBuiltinESMExports();process.env.SystemRoot='C:\\Windows'; - const platform=await import(pathToFileURL(platformFile).href) as typeof import('../../shared/platform.ts'); - const managed=await import(pathToFileURL(path.join(source,'shared/managed-binding.ts')).href) as typeof import('../../shared/managed-binding.ts'); - const migration=await import(pathToFileURL(path.join(source,'setup/managed-migration.ts')).href) as typeof import('../../setup/managed-migration.ts'); - const binding=await import(pathToFileURL(path.join(source,'shared/binding.ts')).href) as typeof import('../../shared/binding.ts'); - const counts:Record={}; - const measured=(name:string,run:()=>T)=>{const before=spawns;try{return run();}finally{counts[name]=spawns-before;}}; - const budget=new platform.PlatformRequestBudget(); - let selector!:string,journal!:string,known!:string[]; - platform.withPlatformRequestBudget(budget,()=>{ - const legacy=measured('admission',()=>platform.platformSecurityScope(()=>{ - platform.windowsPaths(paths,true); - return migration.legacyMigration(env)!; - })); - selector=measured('unchangedDirectoryHelper',()=>managed.createManagedBindingDirectory(env)); - journal=path.join(path.dirname(selector),'migration.json'); - known=[...paths,path.dirname(selector),path.join(path.dirname(selector),'.ownership.json'),selector,journal]; - measured('publicationValidation',()=>platform.platformSecurityScope(()=>{ - platform.windowsPaths(known,true); - assert.equal(managed.managedBindingFile(env),selector); - assert.equal(migration.readMigration(env),undefined); - assert.equal(migration.legacyMigration(env)!.ownership,legacy.ownership); - })); - // Only the filesystem envelope is under test here, not journal semantics. - managed.publishPrivateJson(journal,legacy.binding); - measured('checkpointValidation',()=>platform.platformSecurityScope(()=>{ - platform.windowsPaths(known,true); - assert.equal(managed.managedBindingFile(env),selector); - assert.ok(platform.privatePaths([journal])); - assert.deepEqual(binding.readBinding(journal),legacy.binding); - })); - }); - t.diagnostic(JSON.stringify({prepareSecuritySpawns:spawns,stages:counts})); - assert.equal(budget.securitySpawns,spawns,'the request budget charges every fake spawn'); - assert.ok(spawns<=6,`prepare requires ${spawns} actual security launches`); - - // Early fresh-creation feasibility gate. Keep all six real boundaries and - // the actual primitive/publication owners. This is not full-engine evidence. - const {Store}=await import(pathToFileURL(path.join(source,'shared/store.ts')).href) as typeof import('../../shared/store.ts'); - const freshRoot=path.join(env.HOME,'new store'),database=path.join(freshRoot,'progress.sqlite'); - const freshKnown=[...known,freshRoot,database,...['-journal','-wal','-shm'].map(s=>database+s)]; - const validate=()=>{platform.windowsPaths(freshKnown,true);assert.equal(managed.managedBindingFile(env),selector); - assert.ok(platform.privatePaths(freshKnown.filter(p=>fs.lstatSync(p,{throwIfNoEntry:false}))));}; - const freshCounts:Record={}; - for(const name of ['store-directory','create-store'] as const){ - const before=spawns,requestBudget=new platform.PlatformRequestBudget(); - platform.withPlatformRequestBudget(requestBudget,()=>{ - platform.platformSecurityScope(validate); // admission - platform.platformSecurityScope(validate); // intent admission - managed.publishPrivateJson(journal,{step:name,state:'running'},true); - if(name==='store-directory')platform.privateDirectory(freshRoot,false,{exclusive:true,validate}); - else {const store=Store.createFresh(database,{storeId:'frozen-store',validate});assert.equal(store.list().captureEnabled,false);store.close();} - platform.platformSecurityScope(validate); // completion admission - managed.publishPrivateJson(journal,{step:name,state:'pending'},true); - platform.platformSecurityScope(validate); // completion readback - }); - freshCounts[name]=spawns-before;assert.equal(requestBudget.securitySpawns,freshCounts[name]); - assert.ok(freshCounts[name]!<=6,`${name} needs a technical amendment: ${freshCounts[name]} actual launches`); - } - t.diagnostic(JSON.stringify({freshCreationSecuritySpawns:freshCounts})); - - // Advance the deadline at the actual spawn seam, without wall-clock sleeps. - // A slow final preflight must not strand an uncheckpointed directory or DB. - let now=process.hrtime.bigint(); - const clock=t.mock.method(process.hrtime,'bigint',()=>now); - try{ - for(const name of ['create-store','store-directory'] as const){ - const parent=path.join(env.HOME,`slow-${name}`),file=path.join(parent,'progress.sqlite'); - if(name==='create-store')fs.mkdirSync(parent,{mode:0o700}); - const target=name==='store-directory'?parent:file; - const validate=()=>{platform.windowsPaths([...known,parent,file,...['-journal','-wal','-shm'].map(s=>file+s)],true);}; - const create=()=>{if(name==='store-directory')platform.privateDirectory(parent,false,{exclusive:true,validate}); - else {const store=Store.createFresh(file,{storeId:'slow-store',validate});store.close();}}; - const run=(slow:boolean)=>{ - const budget=new platform.PlatformRequestBudget(); - afterSpawn=()=>{now+=BigInt(slow&&budget.securitySpawns===3?6_000:2_500)*1_000_000n;}; - return platform.withPlatformRequestBudget(budget,()=>{ - platform.platformSecurityScope(validate); // request admission - platform.platformSecurityScope(validate); // intent publication admission - create(); // final preflight is the slower third launch - platform.platformSecurityScope(validate); // completion admission - platform.platformSecurityScope(validate); // completion readback - assert.equal(budget.securitySpawns,6); - }); - }; - assert.throws(()=>run(true),{code:'managed-step-deadline'}); - assert.equal(fs.existsSync(target),false,`${name} must refuse before exclusive creation`); - run(false);assert.equal(fs.existsSync(target),true,'a new bounded request safely retries absent storage'); - } - }finally{afterSpawn=()=>{};clock.mock.restore();} - } finally { - t.mock.restoreAll();syncBuiltinESMExports(); - if(originalSystemRoot===undefined)delete process.env.SystemRoot;else process.env.SystemRoot=originalSystemRoot; - fs.rmSync(root,{recursive:true,force:true}); - } -}); diff --git a/tests/backend/managed-step-removal.test.ts b/tests/backend/managed-step-removal.test.ts index 328f5ee..5972a15 100644 --- a/tests/backend/managed-step-removal.test.ts +++ b/tests/backend/managed-step-removal.test.ts @@ -7,7 +7,6 @@ import cp from 'node:child_process'; import {pathToFileURL} from 'node:url'; import {lifecycle,migrationEvidence,validateMigrationRemoval,removeMigrationFile,migrationRemovalRecordClaims,recordMigrationRemoval,migrationRemovalRecorded} from '../../setup/lifecycle.ts'; import {Store,canonical,digest} from '../../shared/store.ts'; -import {platformSecurityScope} from '../../shared/platform.ts'; import {parseManagedStepJournal,managedTargetDigest,type ManagedStepJournal} from '../../setup/managed-step-journal.ts'; import {isolatedEnvironment} from '../fixtures/managed.ts'; import {createManagedBindingDirectory,publishPrivateJson} from '../../shared/managed-binding.ts'; @@ -99,13 +98,12 @@ test('missing files without the current intent or completed same-operation evide }finally{f.cleanup();} }); -test('removal requires durable exact intent, fresh off capture and no enclosing security scope',()=>{ +test('removal requires durable exact intent and fresh off capture',()=>{ const f=fixture();try{ assert.throws(()=>removeMigrationFile(f.journal),{code:'managed-step-conflict'}); const file=authorize(f.journal);f.store.setEnabled(true); assert.throws(()=>removeMigrationFile(f.journal),{code:'managed-step-conflict'});assert.equal(fs.existsSync(file),true); f.store.setEnabled(false); - assert.throws(()=>platformSecurityScope(()=>removeMigrationFile(f.journal)),{code:'managed-step-conflict'}); const before=f.journal.migration.intent!.before;f.journal.migration.intent!.before=[]; assert.throws(()=>removeMigrationFile(f.journal),{code:'managed-step-conflict'});f.journal.migration.intent!.before=before; f.journal.migration.intent!.after[0]!.path=path.join(f.legacyRoot,'other'); @@ -229,12 +227,12 @@ test('record-removal tolerates later history appends only after its own exact ev }finally{f.cleanup();} }); -test('each one-file request fits six actual launches including both durable journal publications', {skip:process.platform==='win32'},async t=>{ +test('each one-file removal request and its journal publications start no process on the Windows path', {skip:process.platform==='win32'},async t=>{ const f=fixture(),originalSystemRoot=process.env.SystemRoot; try{ - // Source projection preserves the actual query/cache/publication owners. - // Only OS path dialect and the real process boundary are substituted. This - // establishes portable accounting, not native Windows ACL/timing evidence. + // Source projection preserves the actual publication owners. Only the OS + // path dialect is substituted, so this is portable evidence that nothing + // starts a process, not native Windows evidence. const source=path.join(f.root,'source'); for(const dir of ['shared','setup'])fs.cpSync(path.resolve(dir),path.join(source,dir),{recursive:true}); const platformFile=path.join(source,'shared/platform.ts');let text=fs.readFileSync(platformFile,'utf8'); @@ -245,22 +243,15 @@ test('each one-file request fits six actual launches including both durable jour fs.writeFileSync(platformFile,text); createManagedBindingDirectory(f.env);publishPrivateJson(migrationFile(f.env),f.journal); let spawns=0; - t.mock.method(cp,'spawnSync',((_command:string,_args:string[],options:cp.SpawnSyncOptionsWithStringEncoding):cp.SpawnSyncReturns=>{ - spawns++;const input=JSON.parse(String(options.input)); - assert.deepEqual(input.create,[],'removal never creates a directory'); - return {pid:1,output:[],stdout:JSON.stringify(input.paths.map(()=>({owned:true,private:true,reparse:false,unsafeParent:false}))),stderr:'',status:0,signal:null}; - }) as unknown as typeof cp.spawnSync);syncBuiltinESMExports();process.env.SystemRoot='C:\\Windows'; + t.mock.method(cp,'spawnSync',(()=>{spawns++;throw new Error('no permission check may start a process');}) as unknown as typeof cp.spawnSync);syncBuiltinESMExports();process.env.SystemRoot='C:\\Windows'; const platform=await import(pathToFileURL(platformFile).href) as typeof import('../../shared/platform.ts'); const owner=await import(pathToFileURL(path.join(source,'setup/lifecycle.ts')).href) as typeof import('../../setup/lifecycle.ts'); const migration=await import(pathToFileURL(path.join(source,'setup/managed-migration.ts')).href) as typeof import('../../setup/managed-migration.ts'); - const counts:number[]=[]; for(let batch=0;batch<6;batch++){ - const budget=new platform.PlatformRequestBudget(),before=spawns; + const budget=new platform.PlatformRequestBudget(); platform.withPlatformRequestBudget(budget,()=>{ - const prior=platform.platformSecurityScope(()=>{ - platform.windowsPaths(migration.managedJournalPaths(f.journal),true); - const current=migration.readManagedStepJournal(f.env)!;owner.validateMigrationRemoval(current);return current; - }); + platform.windowsPaths(migration.managedJournalPaths(f.journal),true); + const prior=migration.readManagedStepJournal(f.env)!;owner.validateMigrationRemoval(prior); const intent=structuredClone(prior),layoutFile=path.join(f.legacyRoot,[...Object.keys(JSON.parse(prior.migration.legacy.ownership!).files).sort(),'.ownership.json'][batch]!); intent.migration.state='running';intent.migration.intent={requestDigest:'4'.repeat(64),expectedSequence:prior.migration.sequence,step:prior.migration.step!,effect:'intent', before:[prior.migration.legacy.claims.find(c=>c.path===layoutFile)!],after:[{path:layoutFile,kind:'absent',object:null,digest:null}],captureBefore:prior.migration.capture,captureReviewSequence:null}; @@ -270,16 +261,12 @@ test('each one-file request fits six actual launches including both durable jour migration.writeManagedStepJournal(f.env,next,intent,()=>{owner.validateMigrationRemoval(intent);}); f.journal=next; }); - counts.push(spawns-before);assert.equal(budget.securitySpawns,spawns-before); - assert.ok(spawns-before<=6,`discovery batch ${batch} exceeded six real security launches`); + assert.equal(spawns,0,`discovery batch ${batch}`); } - t.diagnostic(JSON.stringify({removeDiscoverySecuritySpawns:counts})); - const budget=new platform.PlatformRequestBudget(),before=spawns; + const budget=new platform.PlatformRequestBudget(); platform.withPlatformRequestBudget(budget,()=>{ - const {prior,claims}=platform.platformSecurityScope(()=>{ - platform.windowsPaths(migration.managedJournalPaths(f.journal),true); - const current=migration.readManagedStepJournal(f.env)!;return {prior:current,claims:owner.migrationRemovalRecordClaims(current)}; - }); + platform.windowsPaths(migration.managedJournalPaths(f.journal),true); + const prior=migration.readManagedStepJournal(f.env)!,claims=owner.migrationRemovalRecordClaims(prior); const intent=structuredClone(prior); intent.migration.state='running';intent.migration.intent={requestDigest:'6'.repeat(64),expectedSequence:prior.migration.sequence,step:prior.migration.step!,effect:'intent', before:claims.before,after:claims.after,captureBefore:claims.capture,captureReviewSequence:null}; @@ -292,8 +279,7 @@ test('each one-file request fits six actual launches including both durable jour migration.writeManagedStepJournal(f.env,next,intent,()=>{assert.equal(owner.migrationRemovalRecorded(intent),true);}); f.journal=next; }); - assert.equal(budget.securitySpawns,spawns-before);assert.ok(spawns-before<=6); - t.diagnostic(JSON.stringify({recordRemovalSecuritySpawns:spawns-before})); + assert.equal(spawns,0); }finally{ t.mock.restoreAll();syncBuiltinESMExports(); if(originalSystemRoot===undefined)delete process.env.SystemRoot;else process.env.SystemRoot=originalSystemRoot; diff --git a/tests/backend/managed-step-upgrade.test.ts b/tests/backend/managed-step-upgrade.test.ts index 4ce3936..eefd120 100644 --- a/tests/backend/managed-step-upgrade.test.ts +++ b/tests/backend/managed-step-upgrade.test.ts @@ -11,7 +11,6 @@ import {Store,canonical,digest} from '../../shared/store.ts'; import {createManagedBindingDirectory,publishPrivateJson} from '../../shared/managed-binding.ts'; import {migrationFile,readMigration,writeMigration,readRemovalReceipt,readManagedStepJournal,upgradeManagedStepJournal,type MigrationRecord} from '../../setup/managed-migration.ts'; import {managedTargetDigest,managedRequestDigest,type ManagedStepJournal} from '../../setup/managed-step-journal.ts'; -import {platformSecurityScope} from '../../shared/platform.ts'; function fixture(removed:boolean,phase:MigrationRecord['phase']='pending'){ const root=fs.mkdtempSync('/tmp/opencode/step-upgrade-'),env=isolatedEnvironment(root); @@ -92,9 +91,8 @@ for(const damage of ['receipt-missing','receipt-replaced','history-alias','remai }); } -test('intact format-1 upgrade refuses changed retained ownership and an enclosing authority scope',()=>{ +test('intact format-1 upgrade refuses changed retained ownership',()=>{ const f=fixture(false);try{ - assert.throws(()=>platformSecurityScope(()=>upgradeManagedStepJournal(f.env,f.journal,f.record)),{code:'managed-step-conflict'}); fs.appendFileSync(path.join(f.legacyRoot,'index.js'),'changed');const before=fs.readFileSync(f.file); assert.throws(()=>upgradeManagedStepJournal(f.env,f.journal,f.record),{code:'modified-owned-files'}); assert.deepEqual(fs.readFileSync(f.file),before); @@ -115,7 +113,7 @@ for(const after of [false,true])test(`format-1 upgrade interruption ${after?'aft }finally{f.cleanup();} }); -test('format-1 upgrade admission, replacement and checkpoint fit the six-launch ceiling', {skip:process.platform==='win32'},async t=>{ +test('format-1 upgrade admission, replacement and checkpoint start no process on the Windows path', {skip:process.platform==='win32'},async t=>{ const originalSystemRoot=process.env.SystemRoot; try{ for(const removed of [false,true]){ @@ -127,24 +125,18 @@ test('format-1 upgrade admission, replacement and checkpoint fit the six-launch const start=text.indexOf(" if (value.includes('\\0')",text.indexOf('function windowsPathsInner(')),end=text.indexOf(' let current = clean;',start); assert.ok(start>0&&end>start);text=text.slice(0,start)+" if (!path.isAbsolute(value) || path.resolve(value) !== value) throw new PlatformError('path-unverified');\n const clean = value;\n"+text.slice(end); fs.writeFileSync(platformFile,text);let spawns=0; - const mock=t.mock.method(cp,'spawnSync',((_command:string,_args:string[],options:cp.SpawnSyncOptionsWithStringEncoding):cp.SpawnSyncReturns=>{ - spawns++;const input=JSON.parse(String(options.input));assert.deepEqual(input.create,[],'upgrade never recreates the container'); - return {pid:1,output:[],stdout:JSON.stringify(input.paths.map(()=>({owned:true,private:true,reparse:false,unsafeParent:false}))),stderr:'',status:0,signal:null}; - }) as unknown as typeof cp.spawnSync);syncBuiltinESMExports();process.env.SystemRoot='C:\\Windows'; + const mock=t.mock.method(cp,'spawnSync',(()=>{spawns++;throw new Error('no permission check may start a process');}) as unknown as typeof cp.spawnSync);syncBuiltinESMExports();process.env.SystemRoot='C:\\Windows'; try{ const platform=await import(pathToFileURL(platformFile).href) as typeof import('../../shared/platform.ts'); const migration=await import(pathToFileURL(path.join(source,'setup/managed-migration.ts')).href) as typeof import('../../setup/managed-migration.ts'); const owner=await import(pathToFileURL(path.join(source,'setup/lifecycle.ts')).href) as typeof import('../../setup/lifecycle.ts'); const budget=new platform.PlatformRequestBudget(); platform.withPlatformRequestBudget(budget,()=>{ - platform.platformSecurityScope(()=>{ - platform.windowsPaths(migration.managedJournalPaths(f.journal),true);assert.deepEqual(migration.readMigration(f.env),f.record); - if(removed)assert.ok(migration.readRemovalReceipt(f.record));else owner.validateMigrationRemoval(f.journal); - }); + platform.windowsPaths(migration.managedJournalPaths(f.journal),true);assert.deepEqual(migration.readMigration(f.env),f.record); + if(removed)assert.ok(migration.readRemovalReceipt(f.record));else owner.validateMigrationRemoval(f.journal); migration.upgradeManagedStepJournal(f.env,f.journal,f.record); }); - assert.equal(budget.securitySpawns,spawns);assert.ok(spawns<=6); - t.diagnostic(JSON.stringify({format1Upgrade:removed?'receipt':'manifest',securitySpawns:spawns})); + assert.equal(spawns,0); }finally{mock.mock.restore();syncBuiltinESMExports();} }finally{f.cleanup();} } diff --git a/tests/backend/windows-platform.test.ts b/tests/backend/windows-platform.test.ts index f77e515..7dc6274 100644 --- a/tests/backend/windows-platform.test.ts +++ b/tests/backend/windows-platform.test.ts @@ -6,7 +6,7 @@ import os from 'node:os'; import { randomUUID } from 'node:crypto'; import childProcess, { spawnSync } from 'node:child_process'; import { syncBuiltinESMExports } from 'node:module'; -import { privateDirectory, privatePaths, isOwned, windowsPath, platformSecurityScope, windowsSecurity, windowsSecurityQuery, sameWindowsDirectory, windowsDaclValidationScript, windowsPowerShellBootstrap } from '../../shared/platform.ts'; +import { privateDirectory, privatePaths, isOwned, windowsPath, sameWindowsDirectory } from '../../shared/platform.ts'; import { lifecycle, inspect, normalizeTargets, type Payload } from '../../setup/lifecycle.ts'; import { Store } from '../../shared/store.ts'; import { readBinding } from '../../shared/binding.ts'; @@ -19,13 +19,10 @@ import type { Actor } from '../../shared/progress.ts'; import { setupLegacy } from '../../plugin/index.ts'; const native = { skip: process.platform !== 'win32', timeout:120000 }; -// OS/profile temp ancestors may permit unrelated accounts to replace children. -// Use a new private root; never repair ACLs on an existing shared temp folder. +// Use a new root under the drive root so tests never touch an existing shared +// temp folder. Directories get the default inherited permissions of the profile. const fixtureParent = process.platform==='win32' ? path.join(path.parse(os.tmpdir()).root,`agent-progress-tests-${randomUUID()}`) : os.tmpdir(); if(process.platform==='win32') { - const started = performance.now(); - try { windowsSecurityQuery([path.parse(fixtureParent).root]); } - finally { console.log(`Windows first security query: ${Math.round(performance.now()-started)} ms (includes cold PowerShell launch, query and any timeout retry)`); } privateDirectory(fixtureParent); after(()=>fs.rmSync(fixtureParent,{recursive:true,force:true})); } @@ -36,132 +33,36 @@ function fixture() { privateDirectory(configRoot);privateDirectory(dataRoot); return {root,targets:{configRoot,dataRoot,storeRoot,confirmed:true},clean(){fs.rmSync(root,{recursive:true,force:true});}}; } -/** Synthetic ACL fixtures only; no profile or external resource access. */ -function changeAcl(file:string,kind:'public'|'readonly'|'deny'|'foreign'|'modify-parent'|'create-child'|'callback') { - const script=String.raw` -$ErrorActionPreference='Stop' -[Console]::InputEncoding=[Text.UTF8Encoding]::new($false) -[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false) -try { - $r=[Console]::In.ReadToEnd()|ConvertFrom-Json - $u=[Security.Principal.WindowsIdentity]::GetCurrent().User - if([IO.Directory]::Exists($r.file)){$a=[IO.Directory]::GetAccessControl($r.file)}else{$a=[IO.File]::GetAccessControl($r.file)} - if($r.kind -eq 'callback'){ - $raw=[Security.AccessControl.RawSecurityDescriptor]::new($a.GetSecurityDescriptorBinaryForm(),0) - $ace=[Security.AccessControl.CommonAce]::new([Security.AccessControl.AceFlags]::None,[Security.AccessControl.AceQualifier]::AccessAllowed,2032127,$u,$true,$null) - $raw.DiscretionaryAcl.InsertAce(0,$ace) - $binary=[byte[]]::new($raw.BinaryLength);$raw.GetBinaryForm($binary,0);$a.SetSecurityDescriptorBinaryForm($binary) - } - elseif($r.kind -eq 'foreign'){$a.SetOwner([Security.Principal.SecurityIdentifier]::new('S-1-5-32-544'))} - else { - if($r.kind -eq 'public'){$sid=[Security.Principal.SecurityIdentifier]::new('S-1-1-0');$rights='ReadAndExecute';$type='Allow'} - elseif($r.kind -eq 'modify-parent'){$sid=[Security.Principal.SecurityIdentifier]::new('S-1-1-0');$rights='Modify';$type='Allow'} - elseif($r.kind -eq 'create-child'){$sid=[Security.Principal.SecurityIdentifier]::new('S-1-1-0');$rights='ReadAndExecute,CreateDirectories,CreateFiles';$type='Allow'} - elseif($r.kind -eq 'deny'){$sid=$u;$rights='Write';$type='Deny'} - else {$sid=$u;$rights='ReadAndExecute';$type='Allow';foreach($rule in $a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($rule.IdentityReference.Value -eq $u.Value){[void]$a.RemoveAccessRuleSpecific($rule)}}} - $rule=[Security.AccessControl.FileSystemAccessRule]::new($sid,$rights,'None','None',$type) - $a.AddAccessRule($rule) - } - if([IO.Directory]::Exists($r.file)){[IO.Directory]::SetAccessControl($r.file,$a)}else{[IO.File]::SetAccessControl($r.file,$a)} - if($r.kind -eq 'callback'){ - if([IO.Directory]::Exists($r.file)){$actual=[IO.Directory]::GetAccessControl($r.file)}else{$actual=[IO.File]::GetAccessControl($r.file)} - $check=[Security.AccessControl.RawSecurityDescriptor]::new($actual.GetSecurityDescriptorBinaryForm(),0) - if(-not $actual.AreAccessRulesCanonical -or -not @($check.DiscretionaryAcl | Where-Object {$_ -is [Security.AccessControl.CommonAce] -and $_.IsCallback}).Count){exit 1} - } - [Console]::Out.Write('ok') -}catch{exit 1} -`; - const r=spawnSync(path.join(process.env.SystemRoot!,'System32','WindowsPowerShell','v1.0','powershell.exe'),['-NoLogo','-NoProfile','-NonInteractive','-Command',script],{input:JSON.stringify({file,kind}),encoding:'utf8',windowsHide:true,timeout:10000,maxBuffer:65536}); - return r.status===0&&r.stdout==='ok'; +/** Test-only fixtures: set and read an explicit, owner-only ACL with icacls. The + * product never applies, queries or repairs an ACL; these helpers exist only to + * prove that existing private ACLs keep working and are left unmodified. */ +const icaclsExe=()=>path.join(process.env.SystemRoot!,'System32','icacls.exe'); +function currentSid():string { + const r=spawnSync('whoami',['/user','/fo','csv','/nh'],{encoding:'utf8',windowsHide:true,timeout:20000}); + const sid=r.status===0?/"(S-1-5-[0-9-]+)"\s*$/.exec(r.stdout.trim())?.[1]:undefined; + assert.ok(sid,'current account SID is available to the fixture');return sid; } +function icacls(file:string,args:string[]):string { + const r=spawnSync(icaclsExe(),[file,...args],{encoding:'utf8',windowsHide:true,timeout:20000}); + assert.equal(r.status,0,'icacls fixture command succeeds');return r.stdout; +} +const makeOwnerOnly=(file:string)=>icacls(file,['/inheritance:r','/grant:r',`*${currentSid()}:(OI)(CI)F`]); +const readAcl=(file:string)=>icacls(file,[]); -test('Windows atomically private Unicode directories, inherited files, ACL refusals and cache invalidation',native,t=>{ - const f=fixture();try{ - privateDirectory(f.targets.storeRoot);const inherited=path.join(f.targets.storeRoot,'private 文書.txt');fs.writeFileSync(inherited,'synthetic'); - assert.equal(platformSecurityScope(()=>privatePaths([f.targets.storeRoot,inherited])),true); - const realSpawn=childProcess.spawnSync;let observedModulePath:string|undefined; - const spy=t.mock.method(childProcess,'spawnSync',((...args:Parameters)=>{observedModulePath=(args[2] as {env?:NodeJS.ProcessEnv})?.env?.PSModulePath;return(realSpawn as any)(...args);})as typeof childProcess.spawnSync);syncBuiltinESMExports(); - try{assert.equal(privatePaths([inherited]),true);assert.equal(observedModulePath,path.join(process.env.SystemRoot!,'System32','WindowsPowerShell','v1.0','Modules'));}finally{spy.mock.restore();syncBuiltinESMExports();} - assert.equal(isOwned(f.targets.storeRoot),true); - platformSecurityScope(()=>{ - assert.equal(privatePaths([inherited]),true);assert.equal(changeAcl(inherited,'public'),true); - assert.equal(privatePaths([inherited]),false,'an ACL mutation cannot reuse a cached private pass'); - }); - const before=fs.readFileSync(inherited);assert.equal(changeAcl(f.targets.storeRoot,'public'),true);assert.throws(()=>privateDirectory(f.targets.storeRoot),/private-permissions/);assert.deepEqual(fs.readFileSync(inherited),before); - for(const kind of ['readonly','deny'] as const){const dir=path.join(f.root,kind);privateDirectory(dir);assert.equal(changeAcl(dir,kind),true);assert.equal(privatePaths([dir]),false,`${kind} ACL must refuse`);} - const saved=process.env.SystemRoot;try{process.env.SystemRoot=path.join(f.root,'absent-system');assert.throws(()=>platformSecurityScope(()=>windowsSecurity([f.targets.configRoot])),/windows-security-unavailable/);}finally{process.env.SystemRoot=saved;} - }finally{f.clean();} -}); - -test('Windows unsupported callback ACEs preserve owner observation but refuse private and ancestor ACL policy',native,async t=>{ +test('Windows creates Unicode directories with default permissions and starts no process',native,t=>{ const f=fixture();try{ - const parent=path.join(f.root,'callback-parent');privateDirectory(parent);const child=path.join(parent,'private-child');privateDirectory(child);const file=path.join(child,'callback-file.txt');fs.writeFileSync(file,'synthetic'); - if(!changeAcl(file,'callback')){t.skip('Windows/.NET refused a canonical callback ACE fixture.');return;} - assert.equal(isOwned(file),true,'unsupported DACL forms do not change the observed owner');assert.equal(privatePaths([file]),false,'GetAccessRules omission cannot produce a private pass'); - await t.test('unsupported ancestor',childTest=>{ - if(!changeAcl(parent,'callback')){childTest.skip('Windows/.NET refused a canonical callback ACE on a directory.');return;} - assert.equal(isOwned(parent),true);assert.throws(()=>windowsPath(child),/unsafe-parent/); - }); + const spawns=t.mock.method(childProcess,'spawnSync',(()=>{throw new Error('no permission check may start a process');}) as unknown as typeof childProcess.spawnSync);syncBuiltinESMExports(); + try{ + privateDirectory(f.targets.storeRoot);const inherited=path.join(f.targets.storeRoot,'private 文書.txt');fs.writeFileSync(inherited,'synthetic'); + assert.equal(privatePaths([f.targets.storeRoot,inherited]),true);assert.equal(isOwned(f.targets.storeRoot),true); + assert.equal(windowsPath(inherited),inherited); + // An existing directory is accepted as it is; a file is not a directory target. + privateDirectory(f.targets.storeRoot);assert.throws(()=>privateDirectory(inherited),/path-unverified/); + assert.equal(spawns.mock.callCount(),0); + }finally{spawns.mock.restore();syncBuiltinESMExports();} }finally{f.clean();} }); -test('Windows PowerShell uses only the explicit built-in JSON module after startup expansion',native,()=>{ - const script=String.raw` -$ErrorActionPreference='Stop' -[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false) -${windowsPowerShellBootstrap} -$module=(Get-Command ConvertFrom-Json).Module.Path -[Console]::Out.Write((ConvertTo-Json -Compress -InputObject @{path=($env:PSModulePath -eq $PSHOME+'\Modules');builtin=$module.StartsWith($PSHOME+'\Modules\Microsoft.PowerShell.Utility\',[StringComparison]::OrdinalIgnoreCase);autoload=($PSModuleAutoLoadingPreference -eq 'None')})) -`; - const result=spawnSync(path.join(process.env.SystemRoot!,'System32','WindowsPowerShell','v1.0','powershell.exe'),['-NoLogo','-NoProfile','-NonInteractive','-Command',script],{env:{SystemRoot:process.env.SystemRoot,PSModulePath:path.join(fixtureParent,'caller-modules')},encoding:'utf8',windowsHide:true,timeout:10000,maxBuffer:65536}); - assert.equal(result.status,0);assert.deepEqual(JSON.parse(result.stdout),{path:true,builtin:true,autoload:true}); -}); - -test('Windows raw descriptor policy rejects null, callback, object and audit ACE forms using public .NET descriptors',native,()=>{ - const script=String.raw` -$ErrorActionPreference='Stop' -[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false) -${windowsDaclValidationScript} -$user=[Security.Principal.WindowsIdentity]::GetCurrent().User -function Check-Dacl($dacl) { - $raw=[Security.AccessControl.RawSecurityDescriptor]::new([Security.AccessControl.ControlFlags]::DiscretionaryAclPresent,$user,$user,$null,$dacl) - $bytes=[byte[]]::new($raw.BinaryLength);$raw.GetBinaryForm($bytes,0) - return Test-OrdinaryDacl $bytes -} -$ordinary=[Security.AccessControl.RawAcl]::new(2,1) -$ordinary.InsertAce(0,[Security.AccessControl.CommonAce]::new([Security.AccessControl.AceFlags]::None,[Security.AccessControl.AceQualifier]::AccessAllowed,2032127,$user,$false,$null)) -$callback=[Security.AccessControl.RawAcl]::new(2,1) -$callback.InsertAce(0,[Security.AccessControl.CommonAce]::new([Security.AccessControl.AceFlags]::None,[Security.AccessControl.AceQualifier]::AccessAllowed,2032127,$user,$true,$null)) -$object=[Security.AccessControl.RawAcl]::new(4,1) -$object.InsertAce(0,[Security.AccessControl.ObjectAce]::new([Security.AccessControl.AceFlags]::None,[Security.AccessControl.AceQualifier]::AccessAllowed,2032127,$user,[Security.AccessControl.ObjectAceFlags]::None,[Guid]::Empty,[Guid]::Empty,$false,$null)) -$audit=[Security.AccessControl.RawAcl]::new(2,1) -$audit.InsertAce(0,[Security.AccessControl.CommonAce]::new([Security.AccessControl.AceFlags]::SuccessfulAccess,[Security.AccessControl.AceQualifier]::SystemAudit,2032127,$user,$false,$null)) -[Console]::Out.Write((ConvertTo-Json -Compress -InputObject @{ordinary=(Check-Dacl $ordinary);nullDacl=(Check-Dacl $null);callback=(Check-Dacl $callback);object=(Check-Dacl $object);audit=(Check-Dacl $audit)})) -`; - const result=spawnSync(path.join(process.env.SystemRoot!,'System32','WindowsPowerShell','v1.0','powershell.exe'),['-NoLogo','-NoProfile','-NonInteractive','-Command',script],{encoding:'utf8',windowsHide:true,timeout:10000,maxBuffer:65536}); - assert.equal(result.status,0,'public .NET descriptor fixtures must execute');assert.deepEqual(JSON.parse(result.stdout),{ordinary:true,nullDacl:false,callback:false,object:false,audit:false}); -}); - -test('Windows ancestor owner policy rejects implicit foreign DACL control',native,()=>{ - const script=String.raw` -$ErrorActionPreference='Stop' -[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false) -${windowsDaclValidationScript} -$user=[Security.Principal.WindowsIdentity]::GetCurrent().User.Value -$results=@() -foreach($owner in @($user,'S-1-5-18','S-1-5-32-544','S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464','S-1-5-21-123-456-789-1001')) { - # A harmless read-only DACL cannot remove the owner's implicit WRITE_DAC. - $acl=[Security.AccessControl.DirectorySecurity]::new() - $acl.SetOwner([Security.Principal.SecurityIdentifier]::new($owner)) - $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($user),'ReadAndExecute','Allow')) - $results += Test-TrustedAncestorOwner ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value) $user -} -[Console]::Out.Write((ConvertTo-Json -Compress -InputObject $results)) -`; - const result=spawnSync(path.join(process.env.SystemRoot!,'System32','WindowsPowerShell','v1.0','powershell.exe'),['-NoLogo','-NoProfile','-NonInteractive','-Command',script],{encoding:'utf8',windowsHide:true,timeout:10000,maxBuffer:65536}); - assert.equal(result.status,0,'public .NET owner fixtures must execute');assert.deepEqual(JSON.parse(result.stdout),[true,true,true,true,false]); -}); - test('Windows hard-linked owned files refuse before database, metadata or history mutation',native,async()=>{ const f=fixture();try{ const env={XDG_DATA_HOME:path.join(f.root,'shared-data'),XDG_CONFIG_HOME:path.join(f.root,'shared-config')}; @@ -197,15 +98,28 @@ test('Windows hard-linked owned files refuse before database, metadata or histor }finally{f.clean();} }); -test('Windows existing permissive/foreign roots are read-only refusals; current owner is required',native,async t=>{ +test('Windows roots with an existing owner-only ACL keep working and their ACLs are never touched',native,t=>{ const f=fixture();try{ - fs.mkdirSync(f.targets.storeRoot);assert.equal(changeAcl(f.targets.storeRoot,'public'),true);const sentinel=path.join(f.targets.storeRoot,'foreign.txt');fs.writeFileSync(sentinel,'preserve'); - assert.throws(()=>inspect(f.targets),/store-permissions/);assert.equal(fs.readFileSync(sentinel,'utf8'),'preserve');assert.equal(privatePaths([f.targets.storeRoot]),false); - await t.test('foreign owner',child=>{ - const dir=path.join(f.root,'foreign-owner');privateDirectory(dir); - if(!changeAcl(dir,'foreign')){child.skip('Account cannot assign a foreign owner; real foreign-owner fixture unavailable.');return;} - assert.equal(isOwned(dir),false);assert.equal(privatePaths([dir]),false);assert.throws(()=>inspect({...f.targets,configRoot:dir}),/path-unverified/); - }); + makeOwnerOnly(f.targets.configRoot);makeOwnerOnly(f.targets.dataRoot); + const before=[readAcl(f.targets.configRoot),readAcl(f.targets.dataRoot)]; + const spawns=t.mock.method(childProcess,'spawnSync',(()=>{throw new Error('no permission check may start a process');}) as unknown as typeof childProcess.spawnSync);syncBuiltinESMExports(); + try{ + lifecycle('install',f.targets,payload); + assert.equal(lifecycle('inspect',f.targets).installed,true); + const binding=readBinding(path.join(f.targets.configRoot,'plugins','agent-progress','progress-binding.json')); + const store=new Store(binding.database);try{assert.equal(store.list().captureEnabled,true);}finally{store.close();} + lifecycle('update',f.targets,{...payload,version:'0.3.0'});lifecycle('disable',f.targets);lifecycle('enable',f.targets); + assert.equal(spawns.mock.callCount(),0); + }finally{spawns.mock.restore();syncBuiltinESMExports();} + assert.deepEqual([readAcl(f.targets.configRoot),readAcl(f.targets.dataRoot)],before,'existing ACLs are not applied, repaired or replaced'); + }finally{f.clean();} +}); + +test('Windows state under an ordinary or widely readable folder is accepted without any ACL check',native,()=>{ + const f=fixture();try{ + fs.mkdirSync(f.targets.storeRoot);icacls(f.targets.storeRoot,['/grant','*S-1-1-0:(OI)(CI)R']);const acl=readAcl(f.targets.storeRoot); + assert.doesNotThrow(()=>inspect(f.targets));assert.equal(readAcl(f.targets.storeRoot),acl,'an existing ACL is left as found'); + assert.equal(isOwned(f.targets.configRoot),true); }finally{f.clean();} }); @@ -222,18 +136,6 @@ test('Windows canonical drive roots, separator/case spellings, aliases and junct }finally{f.clean();} }); -test('Windows ancestor replacement rights refuse private state while ordinary authorized source reads remain usable',native,async()=>{ - const f=fixture();try{ - const shared=path.join(f.root,'shared-parent');fs.mkdirSync(shared);assert.equal(changeAcl(shared,'create-child'),true); - const child=path.join(shared,'private-child');privateDirectory(child);fs.writeFileSync(path.join(child,'synthetic.txt'),'preserve');assert.equal(privatePaths([child]),true); - assert.equal(windowsPath(child),child,'shared read/create-child permissions do not permit replacing a private child'); - assert.equal(changeAcl(shared,'modify-parent'),true);assert.equal(privatePaths([child]),true,'the child DACL alone cannot establish a safe ancestor chain'); - const source=path.join(shared,'ordinary-source.md');fs.writeFileSync(source,'# Authorized ordinary source\n');assert.equal((await captureDocument(source,f.root,async()=>{})).state,'captured','explicitly authorized ordinary documents do not need a private ancestor ACL'); - assert.throws(()=>windowsPath(child),/unsafe-parent/);assert.throws(()=>privateDirectory(path.join(shared,'new-private-child')),/unsafe-parent/);assert.equal(fs.existsSync(path.join(shared,'new-private-child')),false); - assert.throws(()=>inspect({...f.targets,storeRoot:child}),/unsafe-parent/);assert.equal(fs.readFileSync(path.join(child,'synthetic.txt'),'utf8'),'preserve'); - }finally{f.clean();} -}); - test('Windows lifecycle installs/updates atomically, retains history, recovers interruptions and controls loaded stores',native,()=>{ const f=fixture();let store:Store|undefined; try{ @@ -243,8 +145,7 @@ test('Windows lifecycle installs/updates atomically, retains history, recovers i store=new Store(binding.database);const actor:Actor={sourceId:binding.source.id,sessionId:'synthetic',agent:'build',directory:f.root,parentId:null,ancestry:[],verifiedSource:true}; store.db.exec('BEGIN IMMEDIATE; UPDATE meta SET enabled=0'); try{assert.equal(fs.existsSync(binding.database+'-journal'),true);assert.equal(privatePaths([binding.database,binding.database+'-journal']),true);}finally{store.db.exec('ROLLBACK');} - const side=binding.database+'-wal';fs.writeFileSync(side,'synthetic foreign side file');assert.equal(changeAcl(side,'public'),true);try{assert.throws(()=>new Store(binding.database),/binding/);}finally{fs.rmSync(side);} - const request={op:'start',plan:'synthetic',oid:'start',rev:0,title:'Synthetic',items:[{id:'a',title:'Task',kind:'task'}]}; + const request={op:'start',plan:'synthetic',oid:'start',rev:0,title:'Synthetic',items:[{id:'a',title:'Task',kind:'task'}]}; assert.deepEqual(store.apply(request,actor),store.apply(request,actor));store.apply({op:'change',plan:'synthetic',oid:'change',rev:1,changes:[{id:'a',status:'working'}]},actor); lifecycle('disable',f.targets);assert.throws(()=>store!.apply({op:'change',plan:'synthetic',oid:'denied',rev:2,changes:[{id:'a',status:'done'}]},actor),/disabled/);lifecycle('enable',f.targets); const manifest=path.join(f.targets.configRoot,'plugins','agent-progress','.ownership.json');const before=fs.readFileSync(manifest); @@ -295,11 +196,10 @@ test('Windows managed discovery is read-only and state-independent; confirmed se const env={HOME:f.root,XDG_DATA_HOME:path.join(f.root,'shared-data'),XDG_CONFIG_HOME:path.join(f.root,'shared-config')}; const configRoot=path.join(env.XDG_CONFIG_HOME,'opencode'),dataRoot=path.join(env.XDG_DATA_HOME,'opencode'); privateDirectory(configRoot,true);privateDirectory(dataRoot,true); - const realSpawn=childProcess.spawnSync;let queries=0; - const batch=t.mock.method(childProcess,'spawnSync',((...args:Parameters)=>{queries++;return(realSpawn as any)(...args);})as typeof childProcess.spawnSync);syncBuiltinESMExports(); + const batch=t.mock.method(childProcess,'spawnSync',(()=>{throw new Error('no permission check may start a process');}) as unknown as typeof childProcess.spawnSync);syncBuiltinESMExports(); try{ - assert.deepEqual(managedSourceRoots(env),{configRoot,dataRoot});assert.equal(queries,1,'known config/data paths and ancestors share a single security query'); - managedSourceRoots(env);assert.equal(queries,2,'a second operation does not inherit an ACL cache'); + assert.deepEqual(managedSourceRoots(env),{configRoot,dataRoot});managedSourceRoots(env); + assert.equal(batch.mock.callCount(),0,'discovery starts no process'); }finally{batch.mock.restore();syncBuiltinESMExports();} const selector=serviceBindingFile(env); assert.equal(fs.existsSync(path.dirname(selector)),false);assert.equal(readManagedBinding(env),undefined); @@ -310,7 +210,7 @@ test('Windows managed discovery is read-only and state-independent; confirmed se const status=controller.run('managed-configure',{storeRoot:f.targets.storeRoot,confirmed:true,expected:review.expected});assert.equal(status.configured,true); assert.equal(privatePaths([path.dirname(selector),path.join(path.dirname(selector),'.ownership.json')]),true); assert.equal(privatePaths([selector]),true);assert.equal(readManagedBinding(env)!.source.configRoot,configRoot); - const systemRoot=process.env.SystemRoot;try{process.env.SystemRoot=path.join(f.root,'absent-system');assert.ok(controller.status().diagnostics.includes('windows-security-unavailable'));assert.throws(()=>serviceBindingFile(env),/windows-security-unavailable/);}finally{if(systemRoot===undefined)delete process.env.SystemRoot;else process.env.SystemRoot=systemRoot;} + {const systemRoot=process.env.SystemRoot;try{process.env.SystemRoot=path.join(f.root,'absent-system');assert.equal(controller.status().configured,true);assert.equal(serviceBindingFile(env),selector);}finally{if(systemRoot===undefined)delete process.env.SystemRoot;else process.env.SystemRoot=systemRoot;}} controller.close();controller=new SetupController({env},()=>({...payload,version:'0.3.0'}));assert.equal(controller.status().version,'0.3.0'); const hints=setupSuggestions({platform:'win32',env:{HOME:f.root,XDG_CONFIG_HOME:path.dirname(f.targets.configRoot),XDG_DATA_HOME:path.dirname(f.targets.dataRoot)},uid:undefined});assert.ok(hints);assert.ok(hints.configRoot?.value.endsWith('opencode')); const hostHome=t.mock.method(os,'homedir',()=>f.root);syncBuiltinESMExports(); @@ -364,7 +264,7 @@ test('Windows directory filters match separator and drive spellings without file }finally{store?.close();f.clean();} }); -test('Windows cleanup snapshots inherit verified private ACLs; archive/restore/delete preserve source and directory matching',native,async()=>{ +test('Windows cleanup snapshots inherit the parent permissions; archive/restore/delete preserve source and directory matching',native,async()=>{ const f=fixture();let store:Store|undefined; try{ privateDirectory(f.targets.storeRoot);store=new Store(path.join(f.targets.storeRoot,'progress.sqlite'),{create:true}); @@ -400,8 +300,8 @@ test('Windows cleanup snapshots inherit verified private ACLs; archive/restore/d }finally{store?.close();f.clean();} }); -test('Windows first cleanup refuses changed public ACLs and hard-linked state without snapshot or mutation',native,()=>{ - for(const kind of ['parent-public','database-public','database-hardlink'] as const){ +test('Windows first cleanup refuses hard-linked state without snapshot or mutation',native,()=>{ + for(const kind of ['database-hardlink'] as const){ const f=fixture();let store:Store|undefined; try{ privateDirectory(f.targets.storeRoot);const database=path.join(f.targets.storeRoot,'progress.sqlite');store=new Store(database,{create:true}); @@ -412,7 +312,6 @@ test('Windows first cleanup refuses changed public ACLs and hard-linked state wi const request={storeId:store.list().storeId,source:source.id,plan:'P-done',rev:2,cleanupRev:0,oid:'archive'}; const before=store.db.prepare('SELECT * FROM plans').all(); if(kind==='database-hardlink')fs.linkSync(database,path.join(f.root,'database-alias.sqlite')); - else assert.equal(changeAcl(kind==='parent-public'?f.targets.storeRoot:database,'public'),true); assert.throws(()=>store!.cleanup('archive',request),e=>['binding','storage'].includes((e as {code:string}).code)); assert.deepEqual(store.db.prepare('SELECT * FROM plans').all(),before); assert.equal(store.db.prepare("SELECT name FROM sqlite_master WHERE name='cleanup_state'").get(),undefined); @@ -421,7 +320,7 @@ test('Windows first cleanup refuses changed public ACLs and hard-linked state wi } }); -test('Windows retained-source lookup skips unavailable history but keeps selected targets and security failures strict',native,t=>{ +test('Windows retained-source lookup skips unavailable history but keeps selected targets strict',native,()=>{ const f=fixture();let store:Store|undefined; try{ const historicalRoot=path.join(f.root,'historical-a'),retiredRoot=path.join(f.root,'retired-a'); @@ -442,18 +341,11 @@ test('Windows retained-source lookup skips unavailable history but keeps selecte store=new Store(database);store.apply({op:'start',plan:'history-b',oid:'start-b',rev:0,title:'Synthetic B',items:[{id:'b',title:'Task',kind:'task'}]},actor(second.source.id,'session-b'));store.apply({op:'change',plan:'history-b',oid:'change-b',rev:1,changes:[{id:'b',status:'working'}]},actor(second.source.id,'session-b')); assert.equal(store.list().sources[0]!.id,historical.id,'unavailable A must precede B during lookup');store.close();store=undefined; lifecycle('remove-capture',b);lifecycle('install',b,payload);assert.equal(readBinding(bindingFile).source.id,second.source.id,'B reuses its namespace after the missing earlier source'); - lifecycle('remove-capture',b);fs.renameSync(retiredRoot,historicalRoot);assert.equal(changeAcl(historicalRoot,'modify-parent'),true); - const realSpawn=childProcess.spawnSync;let historicalSecurityProbe=false; - const blocked=t.mock.method(childProcess,'spawnSync',((...args:Parameters)=>{ - const input=(args[2] as {input?:unknown})?.input; - if(typeof input==='string'&&(JSON.parse(input) as {paths?:string[]}).paths?.includes(a.configRoot)){historicalSecurityProbe=true;return{pid:0,output:[],stdout:'',stderr:'',status:1,signal:null};} - return(realSpawn as any)(...args); - })as typeof childProcess.spawnSync);syncBuiltinESMExports(); - try{assert.throws(()=>lifecycle('install',b,payload),/windows-security-unavailable/);assert.equal(historicalSecurityProbe,true);assert.equal(fs.existsSync(bindingFile),false);}finally{blocked.mock.restore();syncBuiltinESMExports();} - lifecycle('install',b,payload);assert.equal(readBinding(bindingFile).source.id,second.source.id,'unsafe historical A is also a nonmatch'); + lifecycle('remove-capture',b);fs.renameSync(retiredRoot,historicalRoot); + lifecycle('install',b,payload);assert.equal(readBinding(bindingFile).source.id,second.source.id,'a restored historical A is still a nonmatch for B'); const historyFile=path.join(f.targets.storeRoot,'installation-history.jsonl'),historyBefore=fs.readFileSync(historyFile),bindingBefore=fs.readFileSync(bindingFile); assert.throws(()=>lifecycle('install',{...b,configRoot:path.join(f.root,'missing-selected')},payload),/path-unverified/); - assert.throws(()=>lifecycle('install',a,payload),/unsafe-parent/);assert.deepEqual(fs.readFileSync(historyFile),historyBefore);assert.deepEqual(fs.readFileSync(bindingFile),bindingBefore); + assert.deepEqual(fs.readFileSync(historyFile),historyBefore);assert.deepEqual(fs.readFileSync(bindingFile),bindingBefore); store=new Store(database);assert.equal(store.list().sources.length,2);assert.equal(store.get(second.source.id,'history-b')!.revision,2);assert.equal(store.history(second.source.id,'history-b').data.length,2);assert.equal(store.history(historical.id,'history-a').data.length,1); }finally{store?.close();f.clean();} }); diff --git a/tests/backend/windows-security-query.test.ts b/tests/backend/windows-security-query.test.ts deleted file mode 100644 index a2d2b8c..0000000 --- a/tests/backend/windows-security-query.test.ts +++ /dev/null @@ -1,148 +0,0 @@ -import { test, type TestContext } from 'node:test'; -import assert from 'node:assert/strict'; -import type { SpawnSyncReturns } from 'node:child_process'; -import type { windowsSecurityQuery } from '../../shared/platform.ts'; - -const result = [{ owned:true, private:true, reparse:false, unsafeParent:false }]; -const success = (): SpawnSyncReturns => ({ pid:1, output:[], stdout:JSON.stringify(result), stderr:'', status:0, signal:null }); -const timeout = (): SpawnSyncReturns => ({ ...success(), status:null, error:Object.assign(new Error('synthetic timeout'), { code:'ETIMEDOUT' }) }); - -let moduleId = 0; -async function run(t: TestContext, attempts: SpawnSyncReturns[]) { - // Isolate process-lifetime state without exposing a product reset hook. - const { windowsSecurityQuery, PlatformError, PlatformRequestBudget, withPlatformRequestBudget, platformSecurityScope } = await import(`../../shared/platform.ts?query-test=${moduleId++}`) as typeof import('../../shared/platform.ts'); - const previous = process.env.SystemRoot; - process.env.SystemRoot = 'C:\\Windows'; - t.after(() => { if (previous === undefined) delete process.env.SystemRoot; else process.env.SystemRoot = previous; }); - const calls: Parameters[2]>>[] = []; - const query = () => windowsSecurityQuery(['C:\\Synthetic'], ['C:\\Synthetic'], (...args) => { - calls.push(args); - assert.ok(calls.length <= attempts.length, 'unexpected retry'); - return attempts[calls.length - 1]!; - }); - return { query, calls, PlatformError, PlatformRequestBudget, withPlatformRequestBudget, platformSecurityScope }; -} - -test('step requests charge every actual attempt and refuse the seventh before spawning',async t=>{ - const {query,calls,PlatformRequestBudget,withPlatformRequestBudget}=await run(t,Array.from({length:6},success)); - const budget=new PlatformRequestBudget(); - withPlatformRequestBudget(budget,()=>{ - for(let i=0;i<6;i++)assert.deepEqual(query(),result); - assert.throws(query,/managed-step-budget/); - }); - assert.equal(calls.length,6);assert.equal(budget.securitySpawns,6); - assert.ok(calls.every(c=>Number(c[2].timeout)>0&&Number(c[2].timeout)<=16000)); -}); - -test('step cold timeout consumes one attempt and has no automatic retry',async t=>{ - const {query,calls,PlatformRequestBudget,withPlatformRequestBudget}=await run(t,[timeout()]); - const budget=new PlatformRequestBudget(); - assert.throws(()=>withPlatformRequestBudget(budget,query),/managed-step-deadline/); - assert.equal(calls.length,1);assert.equal(budget.securitySpawns,1); -}); - -test('budget reservation and settlement headroom refuse before a helper starts',async t=>{ - const {query,calls,PlatformRequestBudget,withPlatformRequestBudget}=await run(t,[]); - const exhausted=new PlatformRequestBudget(process.hrtime.bigint()-17_000_000_000n); - assert.throws(()=>withPlatformRequestBudget(exhausted,query),/managed-step-deadline/); - const settling=new PlatformRequestBudget(process.hrtime.bigint()-16_500_000_000n); - assert.throws(()=>withPlatformRequestBudget(settling,query),/managed-step-deadline/); - const budget=new PlatformRequestBudget(); - assert.throws(()=>budget.require(7),/managed-step-budget/); - assert.throws(()=>budget.require(0,18000),/managed-step-deadline/); - assert.equal(calls.length,0);assert.equal(settling.securitySpawns,0); -}); - -test('a shared attempt counter cannot be reset by a new budget or nested scope',async t=>{ - const {query,calls,PlatformRequestBudget,withPlatformRequestBudget,platformSecurityScope}=await run(t,[success()]); - const first=new PlatformRequestBudget(),second=new PlatformRequestBudget(first.startedAt,first.counter.buffer as SharedArrayBuffer); - withPlatformRequestBudget(first,()=>{ - query(); - assert.throws(()=>withPlatformRequestBudget(second,query),/managed-step-conflict/); - }); - assert.equal(second.securitySpawns,1); - assert.throws(()=>platformSecurityScope(()=>withPlatformRequestBudget(second,query)),/managed-step-conflict/); - assert.equal(calls.length,1); -}); - -test('failed process starts consume the request allowance without enabling retries',async t=>{ - const failure={...success(),error:Object.assign(new Error('synthetic'),{code:'ENOENT'})}; - const {query,calls,PlatformRequestBudget,withPlatformRequestBudget}=await run(t,[failure]); - const budget=new PlatformRequestBudget(); - assert.throws(()=>withPlatformRequestBudget(budget,query),/windows-security-unavailable/); - assert.equal(budget.securitySpawns,1);assert.equal(calls.length,1); -}); - -test('synchronous budget refuses promises and custom thenables instead of silently ending early',async t=>{ - const {PlatformRequestBudget,withPlatformRequestBudget}=await run(t,[]); - for(const value of [Promise.resolve(null),{then(){throw new Error('must not assimilate');}}]){ - assert.throws(()=>withPlatformRequestBudget(new PlatformRequestBudget(),()=>value),{code:'managed-step-conflict'}); - } - assert.equal(withPlatformRequestBudget(new PlatformRequestBudget(),()=>42),42,'failure releases the local budget'); -}); - -test('fenced mutex timeout retains its precise unsettled diagnostic without retry',async t=>{ - const failure={...success(),status:1,stdout:'{"error":"managed-step-unsettled"}'}; - const {query,calls,PlatformRequestBudget,withPlatformRequestBudget}=await run(t,[failure]); - const budget=new PlatformRequestBudget(process.hrtime.bigint(),new SharedArrayBuffer(4),{port:47329,nonce:'a'.repeat(64)}); - assert.throws(()=>withPlatformRequestBudget(budget,query),{code:'managed-step-unsettled',reason:'exit'}); - assert.equal(calls.length,1);assert.equal(budget.securitySpawns,1); - assert.match(calls[0]![1][4]!,/\$failureCode = 'managed-step-unsettled'; throw 'writer-unsettled'/); -}); - -test('mutex diagnostic accepts only the exact allowlisted fenced-child failure',async t=>{ - const attempts=['{"error":"private raw text"}','{"error":"managed-step-unsettled","details":"private"}'].map(stdout=>({...success(),status:1,stdout})); - const {query,calls,PlatformRequestBudget,withPlatformRequestBudget}=await run(t,attempts); - for(const _ of attempts){ - const budget=new PlatformRequestBudget(process.hrtime.bigint(),new SharedArrayBuffer(4),{port:47329,nonce:'a'.repeat(64)}); - assert.throws(()=>withPlatformRequestBudget(budget,query),{code:'windows-security-unavailable'}); - } - assert.equal(calls.length,2); -}); - -test('first security query retries a timeout once with identical inputs and a 30-second bound', async t => { - const { query, calls, PlatformError } = await run(t, [timeout(), success(), timeout()]); - assert.deepEqual(query(), result); - assert.equal(calls.length, 2); - assert.deepEqual(calls[0], calls[1]); - assert.equal(calls[0]![2].timeout, 30000); - assert.throws(query, (error: unknown) => error instanceof PlatformError && error.reason === 'timeout'); - assert.equal(calls.length, 3); - assert.equal(calls[2]![2].timeout, 10000); -}); - -test('first security query fails closed after two timeouts and consumes the extended budget', async t => { - const { query, calls, PlatformError } = await run(t, [timeout(), timeout(), timeout()]); - assert.throws(query, (error: unknown) => error instanceof PlatformError && error.code === 'windows-security-unavailable' && error.reason === 'timeout'); - assert.equal(calls.length, 2); - assert.throws(query, (error: unknown) => error instanceof PlatformError && error.reason === 'timeout'); - assert.equal(calls.length, 3); - assert.equal(calls[2]![2].timeout, 10000); -}); - -test('successful first attempt consumes the extended budget without retry', async t => { - const { query, calls, PlatformError } = await run(t, [success(), timeout()]); - assert.deepEqual(query(), result); - assert.equal(calls.length, 1); - assert.equal(calls[0]![2].timeout, 30000); - assert.throws(query, (error: unknown) => error instanceof PlatformError && error.reason === 'timeout'); - assert.equal(calls.length, 2); - assert.equal(calls[1]![2].timeout, 10000); -}); - -for (const [name, attempt, reason] of [ - ['non-zero exit', { ...success(), status:1 }, 'exit'], - ['spawn error', { ...success(), error:Object.assign(new Error('synthetic spawn failure'), { code:'ENOENT' }) }, 'spawn'], - ['malformed JSON', { ...success(), stdout:'not JSON' }, undefined], - ['invalid security result', { ...success(), stdout:'[{"owned":true}]' }, undefined], -] as const) { - test(`security query does not retry ${name} and consumes the extended budget`, async t => { - const { query, calls, PlatformError } = await run(t, [attempt, timeout()]); - assert.throws(query, (error: unknown) => error instanceof PlatformError && error.code === 'windows-security-unavailable' && error.reason === reason); - assert.equal(calls.length, 1); - assert.equal(calls[0]![2].timeout, 30000); - assert.throws(query, (error: unknown) => error instanceof PlatformError && error.reason === 'timeout'); - assert.equal(calls.length, 2); - assert.equal(calls[1]![2].timeout, 10000); - }); -} diff --git a/tests/backend/windows-service-observer.test.ts b/tests/backend/windows-service-observer.test.ts index 6f291b8..611a994 100644 --- a/tests/backend/windows-service-observer.test.ts +++ b/tests/backend/windows-service-observer.test.ts @@ -4,38 +4,32 @@ import fs from 'node:fs'; import {isolatedEnvironment} from '../fixtures/managed.ts'; import {nativeService,NativeHarnessError,nativeHarnessCode,type Observation} from '../fixtures/windows-service-driver.ts'; -test('native observer attributes worker attempts/reads separately from concurrent health',{skip:process.platform==='win32',timeout:15000},async()=>{ +test('native observer counts every process launch and legacy read of a worker, separately from health',{skip:process.platform==='win32',timeout:15000},async()=>{ const root=fs.mkdtempSync('/tmp/opencode/native-observer-'),observations:Observation[]=[]; const service=await nativeService(isolatedEnvironment(root),o=>observations.push(o),'tests/fixtures/windows-observer-probe.mjs'); try{ - const request=await service.request('/v1/setup/managed-step',{},'probe',{concurrent:true,expectedStatus:200}); + const request=await service.request('/v1/setup/managed-step',{},'probe',{expectedStatus:200,maxSpawns:2}); assert.equal(request.counts.queries,2,'both real failed launch attempts count');assert.equal(request.counts.legacyReads,1);assert.equal(request.counts.workers,1); - assert.equal(observations.find(o=>o.phase==='probe')!.concurrent,true); - const health=observations.find(o=>o.phase==='probe-health')!; + const health=await service.request('/health',undefined,'probe-health',{expectedStatus:200}); assert.equal(health.counts.queries,0);assert.equal(health.counts.legacyReads,0);assert.equal(health.counts.workers,0); - await service.settings(null,2500); - const delayed=await service.request('/v1/setup/managed-step',{},'delayed',{concurrent:true,expectedStatus:200}); - assert.equal(delayed.counts.queries,2);assert.ok(delayed.counts.elapsedMs>=5000,'latency injection crosses the worker boundary'); + // The driver's default is zero launches: an unexpected one fails the request. + await assert.rejects(service.request('/v1/setup/managed-step',{},'unexpected-launch',{expectedStatus:200}),{code:'native-assertion-failed'}); }finally{await service.stop();fs.rmSync(root,{recursive:true,force:true});} }); -test('observer never holds main-thread spawns and driver refuses concurrency claims on synchronous routes',{skip:process.platform==='win32',timeout:15000},async()=>{ +test('observer attributes a main-thread launch to its request, not to a worker',{skip:process.platform==='win32',timeout:15000},async()=>{ const root=fs.mkdtempSync('/tmp/opencode/native-observer-main-'),observations:Observation[]=[]; const service=await nativeService(isolatedEnvironment(root),o=>observations.push(o),'tests/fixtures/windows-observer-probe.mjs'); try{ - await assert.rejects(service.request('/v1/setup/managed-inspect',{},'fresh',{concurrent:true}),{code:'native-worker-route-required'}); - // Deliberately broken worker fixture spawns on its main thread despite the - // hold header. It must finish promptly, then refuse the false concurrency - // claim, rather than waiting for an impossible IPC release notification. - await assert.rejects(service.request('/v1/setup/managed-step',{mainThread:true},'main-thread',{concurrent:true,limitMs:1500}),{code:'native-assertion-failed'}); + await assert.rejects(service.request('/v1/setup/managed-step',{mainThread:true},'main-thread',{limitMs:1500}),{code:'native-assertion-failed'}); const observed=observations.find(o=>o.phase==='main-thread')!; assert.equal(observed.counts.queries,1);assert.equal(observed.counts.workers,0); - assert.ok(observed.counts.elapsedMs<1500);assert.equal(observed.concurrent,false); + assert.ok(observed.counts.elapsedMs<1500); }finally{await service.stop();fs.rmSync(root,{recursive:true,force:true});} }); test('native harness failures expose fixed codes, never exception messages or paths',()=>{ - for(const code of ['native-service-exited','native-observer-timeout','native-worker-route-required'] as const)assert.equal(nativeHarnessCode(new NativeHarnessError(code)),code); + for(const code of ['native-service-exited','native-observer-timeout'] as const)assert.equal(nativeHarnessCode(new NativeHarnessError(code)),code); assert.equal(nativeHarnessCode(new assert.AssertionError({message:'private fixture /fixture/secret'})),'native-assertion-failed'); assert.equal(nativeHarnessCode(Object.assign(new Error('/fixture/private'),{name:'TimeoutError'})),'native-request-timeout'); assert.equal(nativeHarnessCode(Object.assign(new Error('/fixture/private'),{code:'ENOENT'})),'native-harness-failed'); diff --git a/tests/backend/windows-service.test.ts b/tests/backend/windows-service.test.ts index 2d22641..d2a2c73 100644 --- a/tests/backend/windows-service.test.ts +++ b/tests/backend/windows-service.test.ts @@ -29,10 +29,10 @@ const fullJourneySkip=process.env.AP_WINDOWS_FULL==='1'?false:'Full Windows jour // EMPTY runs first: no released installer, selected binding, Store or journal may // accidentally supply authority to the new-store journey. Retained fixtures use // only the Store owner, never an install followed by test-owned discovery removal. -for(const fixture of ['empty','empty-custom','empty-delayed','retained-off','retained-on','retained-new'] as const)test(`Windows built fresh steps (${fixture})`,{skip:fixture==='empty-delayed'&&fullJourneySkip||process.platform!=='win32',timeout:600000},async()=>{ +for(const fixture of ['empty','empty-custom','retained-off','retained-on','retained-new'] as const)test(`Windows built fresh steps (${fixture})`,{skip:process.platform!=='win32',timeout:600000},async()=>{ const root=path.join(path.parse(os.tmpdir()).root,`agent-progress-fresh-${randomUUID()}`); const retained=fixture.startsWith('retained'),newSource=fixture==='retained-new',custom=fixture==='empty-custom', - delayed=fixture==='empty-delayed',mode=delayed?'delayed':'undelayed',limitMs=delayed?19999:8000; + mode='undelayed',limitMs=8000; let running:Awaited>|undefined; let database='',managed='',storeRoot='',phase='fixture',failed=false; const freshStages=new Set([...MANAGED_FRESH_INSPECTION_STEPS,...MANAGED_FRESH_STEPS,'journal','lock']); @@ -52,7 +52,7 @@ for(const fixture of ['empty','empty-custom','empty-delayed','retained-off','ret // Keep the existing prefix/artifact collector; only fixed vocabulary, booleans // and numeric observations enter the public trace, never review/identity data. console.log('WINDOWS_MIGRATION_TRACE '+JSON.stringify({journey:'fresh',fixture,mode,request:o.phase,stage:freshStages.has(stage)?stage:null,code:codes.has(code)?code:code?'unrecognized-code':null, - status:o.status,elapsedMs:o.counts.elapsedMs,spawns:o.counts.queries,legacyReads:o.counts.legacyReads,workers:o.counts.workers,concurrentHealth:o.concurrent, + status:o.status,elapsedMs:o.counts.elapsedMs,spawns:o.counts.queries,legacyReads:o.counts.legacyReads,workers:o.counts.workers, sequence:Number.isSafeInteger(p?.sequence)?p.sequence:null,state:['pending','running','paused','failed','complete','abandoned'].includes(p?.state)?p.state:null, capture:['on','off','unknown'].includes(p?.capture?.state)?p.capture.state:null,...facts()})); if(o.phase==='first-health')assert.equal(o.value.managedFreshSteps,1,'built service must advertise fresh support even while starting'); @@ -105,9 +105,8 @@ for(const fixture of ['empty','empty-custom','empty-delayed','retained-off','ret const refused=await request(`/v1/setup/${route}`,route==='managed-configure'?{confirmed:true,expected:'a'.repeat(64)}:{},`fresh-old-${route}`,{maxSpawns:0,expectedStatus:409}); assert.deepEqual(refused.value,{error:'managed-action-required'});assert.equal(refused.counts.workers,0);assert.equal(refused.counts.legacyReads,0);pristine(); } - await running.settings(null,delayed?2500:0); const step=async(body:ManagedFreshStepRequest,label:string,expectedStatus=200)=>{ - const r=await request('/v1/setup/managed-step',body,`fresh-${label}`,{concurrent:true,expectedStatus}); + const r=await request('/v1/setup/managed-step',body,`fresh-${label}`,{expectedStatus}); const value=r.value as ManagedFreshStepResponse;assert.equal(value.version,2); if(expectedStatus===200)assert.equal(value.error,null,`${label}: success must not hide a refusal`); return {...r,value}; @@ -116,7 +115,7 @@ for(const fixture of ['empty','empty-custom','empty-delayed','retained-off','ret let cursor:string|undefined; for(const stage of MANAGED_FRESH_INSPECTION_STEPS){ const r=await step({version:2,action:'inspect',...(cursor?{cursor}:custom?{storeRoot}:{})},`inspect-${stage}`);pristine(); - assert.ok(r.counts.queries>0,'fresh inspection performs real security checks');assert.equal(r.value.inspection?.stage,stage); + assert.equal(r.counts.queries,0,'fresh inspection starts no process');assert.equal(r.value.inspection?.stage,stage); if(stage==='review'){assert.equal(r.value.inspection?.state,'complete');assert.ok(r.value.inspection?.review);return r.value.inspection.review;} assert.equal(r.value.inspection?.state,'incomplete');assert.equal(r.value.inspection?.review,undefined);assert.ok(r.value.inspection?.cursor);cursor=r.value.inspection.cursor; } @@ -132,12 +131,6 @@ for(const fixture of ['empty','empty-custom','empty-delayed','retained-off','ret if(newSource)assert.notEqual(review.sourceId,retainedSourceId);else assert.equal(review.sourceId,retainedSourceId); assert.equal(review.capture.state,initialCapture?'on':'off');} const operationId=randomUUID(); - if(fixture==='empty'){ - await running.settings('timeout'); - const refusal=await step({version:2,action:'begin',operationId,confirmed:true,expected:review.expected},'prepare-timeout',503); - assert.equal(refusal.value.disposition,'refused');assert.deepEqual(refusal.value.error,{stage:'prepare',code:'managed-step-deadline'});assert.ok(refusal.counts.queries>0);pristine(); - await running.settings();review=await inspect(); - } const begin:ManagedFreshStepRequest={version:2,action:'begin',operationId,confirmed:true,expected:review.expected}; let p=(await step(begin,'prepare')).value.progress!; assert.equal(p.sequence,1);assert.equal(p.state,'pending');assert.deepEqual(p.lastCompleted,{name:'prepare',batch:0});assert.deepEqual(p.plan,review.plan); @@ -147,8 +140,8 @@ for(const fixture of ['empty','empty-custom','empty-delayed','retained-off','ret const current=p,enabled=fs.existsSync(database)?capture():null; p=(await step({version:2,action:'pause',operationId,expectedSequence:p.sequence},`pause-${label}`)).value.progress!; assert.equal(p.state,'paused');assert.deepEqual(p.step,current.step); - await running!.stop();running=await nativeService(env,observe);await running.settings(null,delayed?2500:0); - const reopened=await request('/v1/setup',undefined,`fresh-reopen-${label}`,{concurrent:true,expectedStatus:200}); + await running!.stop();running=await nativeService(env,observe); + const reopened=await request('/v1/setup',undefined,`fresh-reopen-${label}`,{expectedStatus:200}); assert.equal(reopened.value.delivery.managedFreshSteps,1);assert.equal(reopened.value.delivery.freshProgress.state,'paused');assert.equal(reopened.value.delivery.freshProgress.sequence,p.sequence); assert.equal(reopened.value.captureEnabled,enabled);assert.equal(fs.existsSync(database)?capture():null,enabled); p=(await step({version:2,action:'resume',operationId,expectedSequence:p.sequence},`resume-${label}`)).value.progress!; @@ -177,7 +170,7 @@ for(const fixture of ['empty','empty-custom','empty-delayed','retained-off','ret assert.equal(readDatabase(db=>db.prepare('SELECT COUNT(*) AS n FROM sources WHERE id=? AND verified=1').get(review.sourceId)!.n),1); assert.equal(readDatabase(db=>db.prepare('SELECT COUNT(*) AS n FROM sources').get()!.n),newSource?2:1); if(custom)assert.equal(fs.existsSync(path.join(dataRoot,'openchamber-progress')),false,'custom selection must not create default storage'); - const status=await request('/v1/setup',undefined,'fresh-complete-status',{concurrent:true,expectedStatus:200}); + const status=await request('/v1/setup',undefined,'fresh-complete-status',{expectedStatus:200}); assert.equal(status.value.delivery.managedFreshSteps,1);assert.equal(status.value.delivery.freshProgress.state,'complete');assert.equal(status.value.configured,true); assert.equal(status.value.captureEnabled,retained?initialCapture:true);assert.equal(status.value.reportingIdentity.storeId,review.storeId);assert.equal(status.value.reportingIdentity.sourceId,review.sourceId); assert.equal(fs.existsSync(legacyRoot),false);assert.equal(privatePaths([managed,path.join(managed,'.ownership.json'),path.join(managed,'progress-binding.json'),database]),true); @@ -191,11 +184,11 @@ for(const fixture of ['empty','empty-custom','empty-delayed','retained-off','ret } }); -for(const delayed of [false,true])test(`Windows built released 1.1.1 step migration (${delayed?'2500ms helpers':'undelayed'})`,{skip:fullJourneySkip||process.platform!=='win32',timeout:600000},async()=>{ +test('Windows built released 1.1.1 step migration',{skip:fullJourneySkip||process.platform!=='win32',timeout:600000},async()=>{ const root=path.join(path.parse(os.tmpdir()).root,`agent-progress-service-${randomUUID()}`); let running:Awaited>|undefined; let database='',managed='',storeRoot='',phase='fixture',failed=false; - const mode=delayed?'delayed':'undelayed',limitMs=delayed?19999:8000; + const mode='undelayed',limitMs=8000; const capture=()=>{const db=new DatabaseSync(database,{readOnly:true});try{const enabled=db.prepare('SELECT enabled FROM meta WHERE singleton=1').get()?.enabled;assert.ok(enabled===0||enabled===1,'capture bit must be readable');return enabled===1;}finally{db.close();}}; function facts(){ let enabled:boolean|null=null;try{if(database&&fs.existsSync(database))enabled=capture();}catch{/* Unknown is not off. */} @@ -208,7 +201,7 @@ for(const delayed of [false,true])test(`Windows built released 1.1.1 step migrat const stage=diagnostic?.stage??o.value.inspection?.stage??p?.lastCompleted?.name; const code=typeof error==='string'?error:diagnostic?.code; console.log('WINDOWS_MIGRATION_TRACE '+JSON.stringify({mode,request:o.phase,stage:stages.has(stage)?stage:null,code:codes.has(code)?code:code?'unrecognized-code':null, - status:o.status,elapsedMs:o.counts.elapsedMs,spawns:o.counts.queries,legacyReads:o.counts.legacyReads,workers:o.counts.workers,concurrentHealth:o.concurrent, + status:o.status,elapsedMs:o.counts.elapsedMs,spawns:o.counts.queries,legacyReads:o.counts.legacyReads,workers:o.counts.workers, sequence:Number.isSafeInteger(p?.sequence)?p.sequence:null,state:['pending','running','paused','failed','complete','abandoned'].includes(p?.state)?p.state:null, capture:['on','off','unknown'].includes(p?.capture?.state)?p.capture.state:null,...facts()})); if(p){ @@ -262,9 +255,8 @@ for(const delayed of [false,true])test(`Windows built released 1.1.1 step migrat assert.equal(refused.counts.workers,0);assert.equal(refused.counts.legacyReads,0); untouched();assert.equal(fs.existsSync(managed),false); } - await running.settings(null,delayed?2500:0); const step=async(body:ManagedStepRequest,label:string,expectedStatus=200)=>{ - const r=await request('/v1/setup/managed-step',body,label,{concurrent:true,expectedStatus}); + const r=await request('/v1/setup/managed-step',body,label,{expectedStatus}); const value=r.value as ManagedStepResponse;assert.equal(value.version,1); if(expectedStatus===200)assert.equal(value.error,null,`${label}: successful step must not contain an error`); return {...r,value}; @@ -273,7 +265,7 @@ for(const delayed of [false,true])test(`Windows built released 1.1.1 step migrat let cursor:string|undefined; for(const stage of MANAGED_INSPECTION_STEPS){ const r=await step({version:1,action:'inspect',...(cursor?{cursor}:{})},`inspect-${stage}`); - assert.ok(r.counts.queries>0,'native inspection must perform real security checks'); + assert.equal(r.counts.queries,0,'native inspection starts no process'); assert.equal(r.value.inspection?.stage,stage); if(stage==='review'){assert.equal(r.value.inspection?.state,'complete');return r.value.inspection!.review!;} assert.equal(r.value.inspection?.state,'incomplete');assert.equal(r.value.inspection?.review,undefined);cursor=r.value.inspection!.cursor!; @@ -281,34 +273,14 @@ for(const delayed of [false,true])test(`Windows built released 1.1.1 step migrat throw new Error('native-inspection-incomplete'); }; const operationId=randomUUID();let review=await inspect();untouched();assert.equal(fs.existsSync(managed),false); - if(!delayed){ - for(const [fault,code]of [['timeout','managed-step-deadline'],['private','private-permissions']] as const){ - await running.settings(fault); - const refusal=await step({version:1,action:'begin',operationId,confirmed:true,expected:review.expected},`prepare-${fault}`,503); - assert.deepEqual(refusal.value.error,{stage:'prepare',code});assert.equal(refusal.value.disposition,'refused'); - assert.ok(refusal.counts.queries>0);untouched();assert.equal(fs.existsSync(managed),false); - await running.settings(); - const status=await request('/v1/setup',undefined,`${fault}-status`,{concurrent:true,expectedStatus:200}); - assert.equal(status.value.delivery.migration,'available');assert.equal(status.value.captureEnabled,null,'unselected legacy capture is unknown'); - review=await inspect(); // Refusal consumed the old ephemeral inspection. - } - // Late helper outlives the response deadline. No second writer may enter - // before actual worker exit; no timeout is treated as proof of rollback. - await running.settings('overrun'); - const late=await request('/v1/setup/managed-step',{version:1,action:'begin',operationId,confirmed:true,expected:review.expected},'prepare-overrun',{concurrent:true,limitMs:19999,expectedStatus:503}); - assert.deepEqual(late.value.error,{stage:'prepare',code:'managed-step-deadline'});untouched(); - const competing=await step({version:1,action:'status'},'late-competing-status',503); - assert.equal(competing.value.error?.code,'managed-step-unsettled');assert.equal(competing.counts.queries,0); - await late.waitForWorkerExit();await running.settings();untouched();review=await inspect(); - } let p=(await step({version:1,action:'begin',operationId,confirmed:true,expected:review.expected},'prepare')).value.progress!; assert.equal(p.sequence,1);assert.deepEqual(p.lastCompleted,{name:'prepare',batch:0});assert.equal(capture(),true);untouched(); const pauseResume=async(label:string)=>{ const current=p,enabled=capture(); p=(await step({version:1,action:'pause',operationId,expectedSequence:p.sequence},`pause-${label}`)).value.progress!; assert.equal(p.state,'paused');assert.deepEqual(p.step,current.step);assert.equal(capture(),enabled); - await running!.stop();running=await nativeService(env,observe);await running.settings(null,delayed?2500:0); - const status=await request('/v1/setup',undefined,`reopen-${label}`,{concurrent:true,expectedStatus:200}); + await running!.stop();running=await nativeService(env,observe); + const status=await request('/v1/setup',undefined,`reopen-${label}`,{expectedStatus:200}); assert.equal(status.value.delivery.migrationProgress.state,'paused');assert.equal(status.value.delivery.migrationProgress.sequence,p.sequence); assert.equal(status.value.captureEnabled,enabled);assert.equal(capture(),enabled); p=(await step({version:1,action:'resume',operationId,expectedSequence:p.sequence},`resume-${label}`)).value.progress!; @@ -329,7 +301,7 @@ for(const delayed of [false,true])test(`Windows built released 1.1.1 step migrat assert.equal(p.state,'complete','bounded driver must complete, not loop through refusals');assert.equal(p.step,null);assert.equal(p.capture.state,'on'); assert.deepEqual([...new Set(completed.map(s=>s.name))],MANAGED_MIGRATION_STEPS); for(const name of ['remove-selector','remove-discovery']){const batches=completed.filter(s=>s.name===name).map(s=>s.batch);assert.ok(batches.length>1,'exercise multiple removal batches');assert.deepEqual(batches,batches.map((_,i)=>i));} - const migrated=await request('/v1/setup',undefined,'complete-status',{concurrent:true,expectedStatus:200}); + const migrated=await request('/v1/setup',undefined,'complete-status',{expectedStatus:200}); assert.equal(migrated.value.delivery.migration,'complete');assert.equal(migrated.value.captureEnabled,true); assert.equal(migrated.value.reportingIdentity.storeId,legacy.storeId);assert.equal(migrated.value.reportingIdentity.sourceId,legacy.source.id); assert.equal(fs.existsSync(legacyRoot),false);assert.deepEqual(historySnapshot(),history);assert.deepEqual(payloadSnapshot(path.join(storeRoot,'payloads')),payloads); @@ -337,7 +309,7 @@ for(const delayed of [false,true])test(`Windows built released 1.1.1 step migrat const events=installationAfter.toString().trim().split('\n').map(line=>JSON.parse(line));assert.equal(events.filter(e=>e.action==='remove-capture').length,1); assert.equal(privatePaths([managed,path.join(managed,'.ownership.json'),path.join(managed,'progress-binding.json')]),true); const ready=await request('/health',undefined,'ready-health',{limitMs:HEALTH_MS,maxSpawns:0,expectedStatus:200});assert.equal(ready.value.ready,true);assert.equal(ready.counts.legacyReads,0); - if(!delayed){ + { // Retain selected cold start and hard-link admission/refusal/recovery. await running.stop();running=await nativeService(env,observe);await running.stop(); const alias=path.join(root,'database-alias.sqlite');fs.linkSync(database,alias);running=await nativeService(env,observe); diff --git a/tests/backend/windows-spawn-budget.test.ts b/tests/backend/windows-spawn-budget.test.ts deleted file mode 100644 index e8480e4..0000000 --- a/tests/backend/windows-spawn-budget.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import {test} from 'node:test'; -import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import path from 'node:path'; -import cp from 'node:child_process'; -import {syncBuiltinESMExports} from 'node:module'; -import {pathToFileURL} from 'node:url'; -import {lifecycle} from '../../setup/lifecycle.ts'; - -/** Portable launch accounting, NOT Windows ACL or timing evidence. Only the - * platform/path dialect and OS helper are substituted in an isolated source - * copy. Query sites, scopes, snapshots, validators and migration stay real. */ -test('managed operations count actual security spawns with a fake OS helper',{skip:process.platform==='win32'},async t=>{ - const root=fs.mkdtempSync('/tmp/opencode/security-spawns-'); - const originalSystemRoot=process.env.SystemRoot; - let setup:any; - try{ - const source=path.join(root,'source'); - for(const dir of ['shared','setup','service'])fs.cpSync(path.resolve(dir),path.join(source,dir),{recursive:true}); - const platform=path.join(source,'shared/platform.ts'); - let text=fs.readFileSync(platform,'utf8'); - assert.ok(text.includes("export const windows = process.platform === 'win32';")); - text=text.replace("export const windows = process.platform === 'win32';",'export const windows = true;'); - const start=text.indexOf(" if (value.includes('\\0')",text.indexOf('function windowsPathsInner(')); - const end=text.indexOf(' let current = clean;',start); - assert.ok(start>0&&end>start); - // Real disposable POSIX paths stand in for drive-absolute NTFS paths. Keep - // the ancestor walk and the reparsePaths/windowsSecurityQuery calls intact. - text=text.slice(0,start)+" if (!path.isAbsolute(value) || path.resolve(value) !== value) throw new PlatformError('path-unverified');\n const clean = value;\n"+text.slice(end); - fs.writeFileSync(platform,text); - const env={HOME:path.join(root,'home ü space')}; - const configRoot=path.join(env.HOME,'.config/opencode'),dataRoot=path.join(env.HOME,'.local/share/opencode'); - for(const dir of [env.HOME,configRoot,dataRoot])fs.mkdirSync(dir,{recursive:true,mode:0o700}); - const targets={configRoot,dataRoot,storeRoot:path.join(dataRoot,'openchamber-progress'),confirmed:true}; - const payload={plugin:'// Synthetic legacy payload',guidance:'Synthetic guidance',removal:'// Synthetic removal',version:'1.1.1'}; - lifecycle('install',targets,payload); - let spawns=0,fault=false,operation=''; - const migrationStages:Record={}; - // The production query uses only the string-encoding overload. Assert that - // contract; the mock need not implement spawnSync's unrelated Buffer forms. - t.mock.method(cp,'spawnSync',((command:string,_args:string[],options:cp.SpawnSyncOptionsWithStringEncoding):cp.SpawnSyncReturns=>{ - assert.equal(path.basename(String(command)),'powershell.exe','only the synthetic security helper may spawn'); - assert.equal(options.encoding,'utf8'); - spawns++; - if(operation==='migrate')migrationStages[setup.migrationStage]=(migrationStages[setup.migrationStage]??0)+1; - const input=JSON.parse(String(options.input)) as {paths:string[];create:string[]}; - if(fault&&input.create.some((p:string)=>path.basename(p)==='agent-progress-managed'))return {pid:0,output:[],stdout:'',stderr:'',status:null,signal:'SIGTERM',error:Object.assign(new Error('synthetic'),{code:'ETIMEDOUT'})}; - for(const dir of input.create)fs.mkdirSync(dir,{mode:0o700}); - return {pid:1,output:[],stdout:JSON.stringify(input.paths.map(()=>({owned:true,private:true,reparse:false,unsafeParent:false}))),stderr:'',status:0,signal:null}; - })as unknown as typeof cp.spawnSync); - syncBuiltinESMExports();process.env.SystemRoot='C:\\Windows'; - const {SetupController}=await import(pathToFileURL(path.join(source,'service/setup-controller.ts')).href); - setup=new SetupController({env},()=>payload); - const counts:Record={}; - function measure(name:string,run:()=>T){spawns=0;operation=name;try{return run();}finally{counts[name]=spawns;}} - const inspected=measure('inspect',()=>setup.run('managed-inspect',{})); - assert.equal(inspected.delivery.migration,'available'); - const body={confirmed:true,expected:inspected.delivery.review.expected}; - fault=true;measure('fault',()=>assert.throws(()=>setup.run('managed-migrate',body),/windows-security-unavailable/));fault=false; - const status=measure('status',()=>setup.status());assert.equal(status.delivery.migration,'available'); - const migrated=measure('migrate',()=>setup.run('managed-migrate',body)); - assert.equal(migrated.delivery.migration,'complete');assert.equal(migrated.captureEnabled,true); - t.diagnostic(JSON.stringify({securitySpawns:counts,migrationStages})); - assert.ok(Object.values(counts).every(n=>n>0),'every operation must query the fake OS boundary'); - assert.ok(counts.inspect!<=20);assert.ok(counts.migrate!<=56);assert.ok(counts.fault!<=14);assert.ok(counts.status!<=14); - }finally{ - setup?.close();t.mock.restoreAll();syncBuiltinESMExports(); - if(originalSystemRoot===undefined)delete process.env.SystemRoot;else process.env.SystemRoot=originalSystemRoot; - fs.rmSync(root,{recursive:true,force:true}); - } -}); diff --git a/tests/fixtures/windows-observer-probe.mjs b/tests/fixtures/windows-observer-probe.mjs index d0788a5..7bffed4 100644 --- a/tests/fixtures/windows-observer-probe.mjs +++ b/tests/fixtures/windows-observer-probe.mjs @@ -4,9 +4,9 @@ import {spawnSync} from 'node:child_process'; import {readFileSync} from 'node:fs'; import {createServer} from 'node:http'; if(!isMainThread){ - // Two real failed OS launches: the observer must count both, independently of + // Two real failed launches: the observer must count both, independently of // any production accounting. The absolute nonexistent path prevents PATH use. - for(let i=0;i<2;i++)spawnSync('/nonexistent-observer-fixture/powershell.exe',[],{input:'{"paths":[],"create":[]}',encoding:'utf8'}); + for(let i=0;i<2;i++)spawnSync('/nonexistent-observer-fixture/helper',[],{encoding:'utf8'}); try{readFileSync('/nonexistent-observer-fixture/plugins/agent-progress/index.js');}catch{} parentPort.postMessage({ok:true}); }else{ @@ -15,7 +15,7 @@ if(!isMainThread){ if(req.url==='/health'){res.end(JSON.stringify({state:'starting',ready:false,sqlite:false,managedMigrationSteps:1}));return;} let body='';for await(const part of req)body+=part; if(JSON.parse(body||'{}').mainThread){ - spawnSync('/nonexistent-observer-fixture/powershell.exe',[],{input:'{"paths":[],"create":[]}',encoding:'utf8'}); + spawnSync('/nonexistent-observer-fixture/helper',[],{encoding:'utf8'}); res.end('{"ok":true}');return; } const worker=new Worker(new URL(import.meta.url));await new Promise((resolve,reject)=>{worker.once('exit',resolve);worker.once('error',reject);}); diff --git a/tests/fixtures/windows-service-driver.ts b/tests/fixtures/windows-service-driver.ts index 24d1d7a..1096009 100644 --- a/tests/fixtures/windows-service-driver.ts +++ b/tests/fixtures/windows-service-driver.ts @@ -7,8 +7,8 @@ import {createServer} from 'node:net'; export const HEALTH_MS=1250,START_MS=12000; export type Counts={queries:number;legacyReads:number;elapsedMs:number;workers:number}; -export type Observation={phase:string;counts:Counts;value:any;status:number;concurrent:boolean}; -type HarnessCode='native-service-exited'|'native-observer-timeout'|'native-worker-route-required'|'native-assertion-failed'|'native-request-timeout'|'native-harness-failed'; +export type Observation={phase:string;counts:Counts;value:any;status:number}; +type HarnessCode='native-service-exited'|'native-observer-timeout'|'native-assertion-failed'|'native-request-timeout'|'native-harness-failed'; export class NativeHarnessError extends Error { readonly code:HarnessCode; constructor(code:HarnessCode){super(code);this.code=code;} @@ -22,7 +22,8 @@ export function nativeHarnessCode(error:unknown):HarnessCode { } /** Authenticated real HTTP; independent preload IPC is correlated by request ID, - * not response order. In particular a health reply cannot consume step counts. */ + * not response order. In particular a health reply cannot consume step counts. + * `queries` counts every child-process launch the service makes: it must be 0. */ export async function nativeService(env:NodeJS.ProcessEnv,observe:(value:Observation)=>void,entry='build/service/main.js'){ const reserve=createServer();reserve.listen(0,'127.0.0.1');await once(reserve,'listening'); const port=(reserve.address() as {port:number}).port;await new Promise(r=>reserve.close(()=>r())); @@ -40,52 +41,28 @@ export async function nativeService(env:NodeJS.ProcessEnv,observe:(value:Observa } function cancel(kind:string,id:string){const k=key(kind,id),w=waiters.get(k);if(w){clearTimeout(w.timer);waiters.delete(k);}} let sequence=0; - async function request(route:string,body?:unknown,phase=route,options:{concurrent?:boolean;limitMs?:number;expectedStatus?:number;maxSpawns?:number}={}):Promise<{status:number;value:any;counts:Counts;id:string;waitForWorkerExit:()=>Promise}>{ - // A synchronous compatibility route cannot answer health while its own - // thread is held. Never pretend that it is a worker concurrency check. - if(options.concurrent&&!['/v1/setup','/v1/setup/managed-step','/v1/capture/enable','/v1/capture/disable'].includes(route))throw new NativeHarnessError('native-worker-route-required'); + async function request(route:string,body?:unknown,phase=route,options:{limitMs?:number;expectedStatus?:number;maxSpawns?:number}={}):Promise<{status:number;value:any;counts:Counts;id:string;waitForWorkerExit:()=>Promise}>{ const id=String(++sequence),begin=performance.now(),limit=options.limitMs??8000; - const observed=message('request',id);let settled=false,concurrent=false; + const observed=message('request',id); void observed.catch(()=>{}); // IPC may fail before the HTTP response arrives. - const pending=(async()=>{ - const response=await fetch(`http://127.0.0.1:${port}${route}`,{method:body===undefined?'GET':'POST',headers:{authorization:'Bearer fixture-only','content-type':'application/json','x-native-request':id,...(options.concurrent?{'x-native-hold':'1'}:{})}, + try{ + const response=await fetch(`http://127.0.0.1:${port}${route}`,{method:body===undefined?'GET':'POST',headers:{authorization:'Bearer fixture-only','content-type':'application/json','x-native-request':id}, ...(body===undefined?{}:{body:JSON.stringify(body)}),signal:AbortSignal.timeout(25000)}); const value=await response.json(),observation=await observed; - return {status:response.status,value,counts:{queries:observation.queries,legacyReads:observation.legacyReads,workers:observation.workers,elapsedMs:Math.round(performance.now()-begin)} as Counts}; - })(); - // Attach a rejection handler immediately, including while awaiting the hold. - const finished=pending.then(()=>{settled=true;return false;},()=>{settled=true;return false;}); - try{ - if(options.concurrent){ - const held=await Promise.race([message('held',id).then(()=>true),finished]); - if(held){ - try{ - assert.equal(settled,false,'step must still be held while health is requested'); - const health=await request('/health',undefined,`${phase}-health`,{limitMs:HEALTH_MS,maxSpawns:0,expectedStatus:200}); - assert.equal(health.counts.legacyReads,0,'concurrent health must not inspect legacy files'); - assert.equal(health.counts.workers,0,'concurrent health must not launch a worker'); - assert.equal(settled,false,'health must finish before the held step is released');concurrent=true; - }finally{child.send({kind:'release',id});} - }else cancel('held',id); - } - const result=await pending; - observe({...result,phase,concurrent}); // Trace BEFORE assertions, also on refusals. + const result={status:response.status,value,counts:{queries:observation.queries,legacyReads:observation.legacyReads,workers:observation.workers,elapsedMs:Math.round(performance.now()-begin)} as Counts}; + observe({...result,phase}); // Trace BEFORE assertions, also on refusals. assert.ok(result.counts.elapsedMs<=limit,`${phase}: request exceeded ${limit}ms`); - assert.ok(result.counts.queries<=(options.maxSpawns??6),`${phase}: actual security spawn ceiling exceeded`); - if(result.value.accounting)assert.equal(result.counts.queries,result.value.accounting.securitySpawns,`${phase}: independent/engine spawn counts disagree`); + assert.ok(result.counts.queries<=(options.maxSpawns??0),`${phase}: the service started a process`); + if(result.value.accounting)assert.equal(result.counts.queries,result.value.accounting.securitySpawns,`${phase}: independent/engine launch counts disagree`); if(options.expectedStatus!==undefined)assert.equal(result.status,options.expectedStatus,`${phase}: unexpected HTTP status`); - if(options.concurrent&&result.counts.queries>0)assert.ok(concurrent,`${phase}: missing concurrent health evidence`); return {...result,id,waitForWorkerExit:async()=>{ const exited=await message('worker-exit',id); - assert.equal(exited.queries,result.counts.queries,`${phase}: late worker launched unaccounted security work`); + assert.equal(exited.queries,result.counts.queries,`${phase}: late worker started a process`); return exited; }}; }catch(error){ - // Settle any pending promise before teardown; never leave an unhandled - // HTTP/IPC failure obscuring the sanitized native trace. - if(!settled){child.send({kind:'release',id});await pending.catch(()=>{});} throw new NativeHarnessError(nativeHarnessCode(error)); - }finally{cancel('held',id);cancel('request',id);} + }finally{cancel('request',id);} } async function stop(){ if(child.exitCode===null&&child.signalCode===null){const exit=once(child,'exit');child.kill();const timer=setTimeout(()=>child.kill('SIGKILL'),3000);try{await exit;}finally{clearTimeout(timer);}} @@ -98,6 +75,6 @@ export async function nativeService(env:NodeJS.ProcessEnv,observe:(value:Observa assert.equal(health.value.state,'starting');assert.equal(health.value.ready,false);assert.equal(health.value.sqlite,false); assert.equal(health.value.managedMigrationSteps,1);assert.equal(health.counts.legacyReads,0); assert.ok(performance.now()-started{if(threads.isMainThread&&process.connected)process.send(message);}; const context=()=>inherited??contexts.getStore(); const counter=()=>context()?.counts??startup; -const wait=ms=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms); -const spawn=cp.spawnSync; -cp.spawnSync=function(command,args,options){ - if(path.basename(command).toLowerCase()!=='powershell.exe')return spawn(command,args,options); - const c=context(),first=Atomics.add(counter(),0,1)===0; - if(first&&!threads.isMainThread&&c?.hold&&c.port){ - c.port.postMessage('held'); - // Bounded synchronization, not a timing sleep: the parent proves concurrent - // health before releasing this request's first security launch. - if(Atomics.wait(c.gate,0,0,5000)==='timed-out')throw new Error('observer-health-release-timeout'); - } - const started=performance.now(),input=typeof options?.input==='string'?JSON.parse(options.input):{}; - const creation=input.create?.some(p=>path.basename(p)==='agent-progress-managed'); - if(c?.settings?.fault==='overrun'){ - // A real late helper; do not honor the shortened wait in this injected case. - // No product script runs and therefore no effect is possible after timeout. - args=['-NoLogo','-NoProfile','-NonInteractive','-Command','[Threading.Thread]::Sleep(22000)']; - options={...options,timeout:25000}; - }else if(creation&&c?.settings?.fault==='timeout'){ - args=['-NoLogo','-NoProfile','-NonInteractive','-Command','[Threading.Thread]::Sleep(10000)']; - options={...options,timeout:100}; - }else if(creation&&c?.settings?.fault==='private'){ - const result=JSON.stringify(input.paths.map(()=>({owned:true,private:false,reparse:false,unsafeParent:false}))); - args=['-NoLogo','-NoProfile','-NonInteractive','-Command',`[Console]::Out.Write('${result}')`]; - } - try{return spawn(command,args,options);} - finally{ - // Total helper latency (not 2.5s plus native launch time). Real ACL checks, - // mutation and the production monotonic deadline remain in force. - const remaining=(c?.settings?.latencyMs??0)-(performance.now()-started); - if(remaining>0)wait(remaining); - } -}; +for(const name of ['spawn','spawnSync','exec','execSync','execFile','execFileSync','fork']){ + const original=cp[name]; + cp[name]=function(...args){Atomics.add(counter(),0,1);return original.apply(this,args);}; +} const read=fs.readFileSync; fs.readFileSync=function(file,...args){ if(String(file).replaceAll('\\','/').includes('/plugins/agent-progress/'))Atomics.add(counter(),1,1); @@ -60,12 +29,9 @@ if(threads.isMainThread){ constructor(entry,options={}){ const c=contexts.getStore(); if(!c){super(entry,options);return;} - const {port1,port2}=new threads.MessageChannel(); - super(entry,{...options,workerData:{...options.workerData,nativeObserver:{counts:c.counts,gate:c.gate,hold:c.hold,settings:{...settings},port:port2}}, - transferList:[...(options.transferList??[]),port2]}); + super(entry,{...options,workerData:{...options.workerData,nativeObserver:{counts:c.counts}}}); c.workers++; - port1.on('message',message=>{if(message==='held')send({kind:'held',id:c.id});}); - this.once('exit',()=>{port1.close();send({kind:'worker-exit',id:c.id,queries:Atomics.load(c.counts,0),legacyReads:Atomics.load(c.counts,1)});}); + this.once('exit',()=>{send({kind:'worker-exit',id:c.id,queries:Atomics.load(c.counts,0),legacyReads:Atomics.load(c.counts,1)});}); } }; // Wrap emit, rather than a request listener: ALS must encompass ALL listeners @@ -74,11 +40,10 @@ if(threads.isMainThread){ http.Server.prototype.emit=function(event,...args){ if(event!=='request')return emit.call(this,event,...args); const [req,res]=args,id=String(req.headers['x-native-request']??''); - const c={id,counts:new Int32Array(new SharedArrayBuffer(8)),gate:new Int32Array(new SharedArrayBuffer(4)),hold:req.headers['x-native-hold']==='1',workers:0,settings:{...settings}}; - requests.set(id,c);const start=performance.now(); + const c={id,counts:new Int32Array(new SharedArrayBuffer(8)),workers:0}; + const start=performance.now(); res.once('finish',()=>{ send({kind:'request',id,queries:Atomics.load(c.counts,0),legacyReads:Atomics.load(c.counts,1),workers:c.workers,elapsedMs:Math.round(performance.now()-start)}); - requests.delete(id); }); return contexts.run(c,()=>emit.call(this,event,...args)); }; @@ -88,12 +53,5 @@ if(threads.isMainThread){ this.once('listening',()=>send({kind:'listening'})); return listen.apply(this,args); }; - process.on('message',message=>{ - if(message?.kind==='settings'&&[null,'timeout','private','overrun'].includes(message.fault)&&[0,2500].includes(message.latencyMs)){ - settings={fault:message.fault,latencyMs:message.latencyMs};send({kind:'settings-set'}); - }else if(message?.kind==='release'){ - const c=requests.get(String(message.id));if(c){Atomics.store(c.gate,0,1);Atomics.notify(c.gate,0);} - } - }); -}else inherited?.port.unref(); +} syncBuiltinESMExports(); From c7faa63179e11f8d0ffec359bcaf1193e8d82f9a Mon Sep 17 00:00:00 2001 From: Phototonic <35551999+Phototonic@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:48:17 +1100 Subject: [PATCH 3/5] docs(windows): describe default per-user permissions and no process launches --- .github/workflows/ci.yml | 4 +- CONTRIBUTING.md | 7 +- README.md | 2 +- docs/backend.md | 104 +++++++++------------- docs/compatibility.md | 92 ++++++++++--------- docs/contracts.md | 21 +++-- docs/setup.md | 141 ++++++++++++----------------- setup/managed-steps.md | 187 ++++++++++++++++++--------------------- 8 files changed, 248 insertions(+), 310 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 68b61b8..14c4052 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -214,8 +214,8 @@ jobs: shell: pwsh run: | $ErrorActionPreference = 'Stop' - # Hosted Windows runners are elevated; test the supported normal-user - # ownership semantics without relaxing the product's SID policy. + # Hosted Windows runners are elevated; run the native tests as a normal + # user with its own profile, as a real per-user installation would. $name = 'progress' + [Guid]::NewGuid().ToString('N').Substring(0, 10) $password = ConvertTo-SecureString ('Aa1!' + [Guid]::NewGuid().ToString('N')) -AsPlainText -Force $trace = Join-Path $env:RUNNER_TEMP 'windows-migration-trace.jsonl' diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 47d9a95..af5ee17 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -24,7 +24,7 @@ Larger changes to behaviour, storage or compatibility are proposed under `opensp Use **Node.js 24.x >= 24.19.0** and **Bun 1.3.14**; dependencies are pinned in `package.json` and `bun.lock`. Node 24.19.0 is the tested baseline and CI's release gate uses exactly 24.19.0 and a second job runs the newest 24.x; later 24.x releases are accepted but not separately certified. Linux integration was tested with OpenCode 2.1.4 and OpenChamber 2.5.1; native Windows validation used OpenCode 2.1.4 and OpenChamber 2.5.2. Current native runtime tests use the OpenCode baseline below. These are tested configurations, not proof of every newer runtime. Linux package checks also need system `zip` and `unzip`. -For native Windows development, use the built-in Windows PowerShell 5.1 and local NTFS storage. No native helper or compiler is part of the runtime. After the frozen dependency install, run `node --experimental-strip-types --test tests/backend/windows-platform.test.ts`, the root/UI typechecks, and the relevant browser tests. The Windows suite creates and cleans isolated private fixtures under a fresh drive-root folder; it does not use a live profile or model. Foreign-owner and persisted callback-ACE fixtures explicitly skip if the account/OS cannot create them; pure descriptor policy still runs. The existing Linux isolation/auth/performance helpers are not Windows tests. ZIP production can remain on Linux; Windows consumers install the built outputs without compiling. +For native Windows development, use local NTFS storage. No native helper, compiler or child process is part of the runtime: Windows permission checks are plain Node filesystem calls, and state relies on the user profile's default permissions. After the frozen dependency install, run `node --experimental-strip-types --test tests/backend/windows-platform.test.ts`, the root/UI typechecks, and the relevant browser tests. The Windows suite creates and cleans isolated fixtures under a fresh drive-root folder; it does not use a live profile or model. One fixture sets an owner-only ACL with the built-in `icacls` to prove that existing ACLs keep working and are never modified; the product never applies or queries an ACL. The existing Linux isolation/auth/performance helpers are not Windows tests. ZIP production can remain on Linux; Windows consumers install the built outputs without compiling. From the repository root: @@ -172,11 +172,10 @@ These cover the native tests' imports and backend build entries/payloads; unknown paths, an empty diff or a failed listing conservatively run Windows. Ordinary PRs and every `dev` push run the fast Windows set: all native tests -except the two released 1.1.1 migration journeys and the `empty-delayed` fresh -journey. Every PR into `main`, every `main` push, the weekly run and manual +except the released 1.1.1 migration journey. Every PR into `main`, every `main` push, the weekly run and manual dispatch run the full set, even for UI/docs-only changes. The workflow sets `AP_WINDOWS_FULL=1` only for those full runs and fetches `v1.1.1` only then. -Without that opt-in, the three journeys explicitly skip; no per-request +Without that opt-in, that journey explicitly skips; no per-request assertion, budget or deadline is relaxed. Local full native runs must also set `AP_WINDOWS_FULL=1`. The Windows job starts the platform file and the service file as two processes at once, each in its own serial test runner and as the same diff --git a/README.md b/README.md index b7d42a4..8584ddf 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,7 @@ No build step or dependency install is needed. Prefer a download? Each version i - **Three interface languages.** Use **More → Language** to follow OpenChamber or choose English, Russian or Simplified Chinese. Progress summaries follow the choice; plan and task text is never translated. - **Calm, qualified counts.** A `+` means a number may be low; **Some counts may be incomplete** explains it once, with **Load more** when available. Technical limits stay in **Troubleshooting → Advanced details** and the support summary. - **Phone views.** Open the rail or fullscreen board on a phone, with larger touch controls and a tap/pan/pinch dependency map. Physical-phone acceptance is deferred to the live release; current checks use browser emulation. -- **Windows setup and upgrades.** New setup and migration run in short, resumable steps with visible progress rather than one long PowerShell request. See [setup and recovery limits](docs/setup.md#install-review-confirm). +- **Windows setup and upgrades.** New setup and migration run in short, resumable steps with visible progress rather than one long request. Windows no longer starts PowerShell for permission checks, which had blocked OpenCode while the companion loaded. See [setup and recovery limits](docs/setup.md#install-review-confirm). - **Child reports are deliberate.** Assigned children with reporting permission receive their task brief only after verified binding, on a naturally occurring context. A first-turn-only child may finish without reporting. A bare final handoff records a claim only; an explicit combined handoff can atomically report assigned task changes too. Neither means the coordinator accepted the work. Optional host agent/resource labels are context, not task authority; Workflows navigation is not offered on the current SDK. diff --git a/docs/backend.md b/docs/backend.md index a39e8c7..61965ca 100644 --- a/docs/backend.md +++ b/docs/backend.md @@ -273,7 +273,7 @@ under the canonical XDG data/HOME OpenCode root, in the private marked state-root/env binding overrides, package siblings and legacy selectors are not fallbacks. Reads/dormant load create no binding, marker or store. Confirmed configuration alone persists a verified private Store/source selection. Existing -ownership, canonical-path, marker, mode/ACL and schema boundaries remain enforced. +ownership, canonical-path, marker, schema and (on Linux and macOS) mode boundaries remain enforced; Windows starts no process and relies on the profile's default permissions. Dormant/coalesced activation retries only at eligible native context/report boundaries, not a timer/watcher/probe. An active generation pins verified identity; @@ -309,16 +309,16 @@ returns an honest last-admission snapshot (`starting`, `unconfigured`, `ready`, `refused`), fixed diagnostics and capabilities captured during admission; no discovery, SQLite open or legacy inspection runs there. Unknown is never ready. All real Setup/store operations retain fresh fail-closed checks, descriptor -pinning, private ACL/ancestor/hard-link and schema validation. Read-only managed -validation shares a synchronous security scope and batches known paths, never a -TTL or process-lifetime ACL cache. No admission work is scheduled in the background. +pinning, canonical-path, link, hard-link and schema validation (plus mode checks on Linux and macOS). Read-only managed +validation reads plain filesystem state and keeps no result across operations, never a +TTL or process-lifetime cache. No admission work is scheduled in the background. The UI explicitly requests Setup admission then re-reads health on the new `starting`/`refused` snapshots; old services without the state field are unchanged. Managed step, ordinary Setup read and ordinary capture requests run in dedicated -workers, leaving health responsive during their security work. Other synchronous +workers, leaving health responsive during their work. Other synchronous data/configuration operations retain their existing event-loop limitations. Identical payload-free status requests in the same environment/descriptor context -share only the in-flight run, deadline and spawn counter; mutations, inspection and +share only the in-flight run and deadline; mutations, inspection and other contexts retain overlap refusal, without sharing or refreshing consent. The legacy controller's error funnel preserves only allowlisted `PlatformError` codes. Migration @@ -366,10 +366,9 @@ Changed-installation and invalid-payload failures map respectively to the frozen settle a journal due to a compare conflict is surfaced, not hidden by an earlier effect failure. -The worker budget charges actual security-process launch attempts, including -failed launches, through a shared counter. It refuses a seventh launch, suppresses -the legacy cold retry, and bounds helper waits by the monotonic 17-second work -deadline with one second of settlement headroom. The supervisor has an 18-second +The worker budget is the monotonic 17-second work deadline; it starts no process +and keeps no launch counter (the wire accounting field `securitySpawns` remains and +is always 0). The supervisor has an 18-second response deadline. A deadline reply never clears busy or terminates a worker as if its effects rolled back; settlement waits for worker exit. A worker crash is treated as an uncertain effect, requiring bounded observation/reconciliation. @@ -395,19 +394,16 @@ to its environment and payload, consumes continuation cursors once, and accepts state only after a matching single reply and successful worker exit before the deadline. A fresh inspection replaces it; restart or a changed environment/package expires it. Private manifest/journal claims never enter the public result. The -inspection review is not a durable action receipt or a substitute for fresh ACL +inspection review is not a durable action receipt or a substitute for fresh checks. -Portable launch accounting measures at most four queries per inspection stage -for intact, format-1 and receipt-proven fixtures, and one for fresh complete-review -admission. This is not native timing or the full slow-machine migration gate. The worker's confirmed `begin` path now consumes the supervisor review, freshly -validates it, reserves the remaining spawn/time budget, and executes only prepare +validates it, checks the remaining time budget, and executes only prepare through the existing directory and journal owners. It assigns the client operation identity and full-request receipt before publication. Format-1 consent upgrades are wired into this same path. Lost-reply retries after restart compare the durable receipt instead of requiring an expired review; changed requests cannot replace -the operation. A slow helper can leave a valid marker with no journal, requiring +the operation. A slow disk can leave a valid marker with no journal, requiring explicit retry, never automatic repair. Unmarked directories still refuse. Worker status is a bounded private-journal projection, with unknown capture and @@ -421,9 +417,8 @@ prepare has non-null lastCompleted; no speculative progress is projected. Its discovery indicator is not a confirmable ownership review. A requested different operation returns `not-found`, never the current operation's progress. Status does not consume an -unfinished inspection review. Portable accounting measures six launches for new -prepare, five with an existing same-target managed selection, three for format-1 -prepare, and three for cold begin replay/status. +unfinished inspection review. Prepare, format-1 prepare and cold begin +replay/status start no process. The private worker now also dispatches sequenced advance, pause, abandon and resume. Each advance publishes a running intent before one effect, verifies that @@ -454,17 +449,13 @@ published running intent to be read back under fresh validation. The supervisor privately carries the last journal as a discovery claim between workers. Admission reads the current private journal and revalidates -all known paths and lifecycle facts; no ACL result crosses a request or write. +all known paths and lifecycle facts; no validation result crosses a request or write. An outdated hint is discarded as authority, not a conflict with an otherwise valid current request; operation identity is still checked. -Status can restore those claims after restart. A cold mutation that cannot reserve -its remaining batches refuses before publishing an intent; explicit bounded +Status can restore those claims after restart. A cold mutation that cannot finish +before the work deadline refuses before publishing an intent; explicit bounded status/resume is the recovery path, not a hidden retry or a weakened check. -Portable HTTP accounting measures five launches for expectation, capture, -each selector/discovery file, binding publication and reconcile, six for prepare -and record-removal, three for controls/cold journal status, and at most four for -ordinary Setup reads. Exact settled replays with a supervisor hint use one. -These are query-count measurements, not native Windows timing evidence. +Portable HTTP tests assert that no step starts a process. The supervisor acquires deterministic per-target loopback writer slots for each request: a discovery data-root slot and a separate Store-root slot. This @@ -472,23 +463,18 @@ covers different discovery scopes sharing a Store without unnecessarily fencing unrelated profiles/users. Multiple slots are sorted/deduplicated by port, acquired without waiting and released together; partial acquisition releases all slots. Contention or -an unrelated listener is a refusal, not a takeover. Windows security children -additionally acquire an account-scoped system mutex **before** checking the -current writer slot's per-request nonce. A child surviving its parent therefore -either finishes while holding that barrier, or refuses when the nonce no longer -matches. A new writer's first fresh security query must cross the barrier before -any effect. Neither the slot nor an abandoned mutex proves an effect committed: -ordinary fresh validation and durable-intent reconciliation remain mandatory. -No extra security process, native dependency, persisted lease or age-based cleanup -is introduced. HTTP writers, including ordinary enable and disable, share this +an unrelated listener is a refusal, not a takeover. The slot does not prove an +effect committed: ordinary fresh validation and durable-intent reconciliation +remain mandatory. No extra process, native dependency, persisted lease or +age-based cleanup is introduced. (Earlier versions also fenced a Windows +security child through an account-scoped mutex; no such child exists any more.) HTTP writers, including ordinary enable and disable, share this boundary; an in-process busy flag alone is not sufficient. Capture-off verifies the selected Store without requiring successful legacy removal inspection. -Enable refuses unfinished migration. Native Windows late-child fencing remains -a separate gate. The first ordinary data admission's existing expectation write +Enable refuses unfinished migration. The first ordinary data admission's existing expectation write also acquires the shared slot; subsequent read-only admissions cannot publish it. Worker status/capture preserve the controller's selected-descriptor pin without returning that private digest over HTTP. A successful bounded Setup read updates -health's last-admission snapshot, not a reusable Store handle or ACL verdict. +health's last-admission snapshot, not a reusable Store handle or validation verdict. Ordinary Setup status and capture control do not load bundled migration payloads. Payload-free reads retain inspection consent without refreshing it; the next inspection/effect still compares its package-bound context. Journal hints bind @@ -528,28 +514,24 @@ ordinary binding/source and companion admission never accept proposed identities 2, receipt index, the frozen Store ID and capture off in one transaction. Folder creation and source registration are separate effects; expectation precedes source registration. Retained plans never change capture or recreate data. Creation -checkpoints record native object observations, not cached ACL authority; immutable +checkpoints record native object observations, not cached authority; immutable fresh facts remain in the target digest. Uncheckpointed folders and partial files are retained/refused, never adopted or repaired. Exact initialized database results can reconcile read-only from their matching durable creation intent. -Portable full-engine counters measure prepare/folder/database 6 launches, each -later effect 5, settled replay 1 and normal controls 3; ordinary fresh Setup status -uses 3 before selection/4 after. Failure settlement also stays within 6. These are -substituted OS-spawn measurements, not native Windows timing. Native CI tests -empty default/custom stores undelayed and the default store with 2.5-second helpers, -retained matching sources with capture on/off, and a retained new source with capture -off. Default fresh recovery tests prepare timeout, replay and restart/pause/resume; -migration tests add late-worker and slower-helper refusal. Native requests assert -six launches, eight seconds undelayed or below twenty seconds delayed, and concurrent -zero-query health. +Portable full-engine tests run the whole fresh engine on a projected Windows path +and assert that no creation, settlement, replay or control starts a process. +Native CI tests empty default/custom stores, retained matching sources with +capture on/off, and a retained new source with capture off. Default fresh +recovery tests replay and restart/pause/resume; migration tests add late-worker +refusal. Native requests assert no process launch and eight seconds, and health +answers with zero launches. The format-2 migration journal provides bounded strict parsing, canonical target/request digests, consistency/transition validation and private no-clobber publication with compare-before-replacement. Reads reject unsupported state, foreign scope, hard links, retained publication stages and old configuration -locks. Writes refuse an enclosing security scope so post-write validation cannot -reuse its ACL cache. These helpers do **not** admit a Store or authorize a saved +locks. Post-write validation rereads the filesystem and reuses no earlier result. These helpers do **not** admit a Store or authorize a saved claim: full fresh lifecycle/Store checks and writer fencing remain engine duties. Cold progress projection reports capture as unknown unless supplied a fresh observation. Both journal families are integrated through the same worker/fence; @@ -579,9 +561,9 @@ repair. History reads are bounded by the journal byte limit before effects. For this two-subeffect unit, unsequenced intent publication has no separate post-publication scan: the effect admission batch reads back and compares the durable intent before rmdir. Settled checkpoint publication still verifies its -write. This coalesces reads, not authority across writes. Portable accounting -measures six launches for the complete record-removal request, including both -journal writes and the fresh check between rmdir and append. The private step +write. This coalesces reads, not authority across writes. The complete +record-removal request, including both journal writes and the fresh check +between rmdir and append, starts no process. The private step engine now uses these owners; the old monolithic route is not made resumable. The format-1 upgrade writer accepts only an explicitly reviewed initial prepare @@ -594,8 +576,8 @@ retains the full plan even if the old coarse phase says removed. The only upgrad effect replaces the old journal atomically. Complete old records, different selectors, retained stages/locks and unsupported records refuse. The private worker supplies consent, fencing and lost-begin-reply handling; this writer never -runs automatically on startup. Portable tests measure three security launches -for admission plus upgrade/checkpoint, not native Windows latency. +runs automatically on startup. Portable tests assert that admission, upgrade and +checkpoint start no process. `readRemovalReceipt` returns the specific same-install history event and a freshly validated native file claim for format-1 recovery. It refuses remaining discovery, @@ -751,10 +733,10 @@ write transaction. Under `BEGIN IMMEDIATE`, eligibility, store/key, progress rev and cleanup generation are checked again before DDL/action commit. Backup/init failure never auto-restores or resets data; a race can leave a private recovery file. Snapshot privacy reuses `shared/platform.ts`: POSIX owner/mode checks, or Windows -native object/ancestor checks and private DACLs. An exclusively created Windows -backup inherits the verified private parent ACL and is checked before copying any -content and after snapshot completion; existing ACLs are never repaired. Changed -public ACLs and hard-linked Windows source state refuse without activating cleanup. +native object and hard-link checks. An exclusively created Windows backup inherits +the parent folder's default permissions and is checked before copying any +content and after snapshot completion; ACLs are never queried or repaired. +Hard-linked Windows source state refuses without activating cleanup. Archived directory filters retain the base's Windows separator/drive spelling equivalence without folding directory-name case or probing presentation paths. diff --git a/docs/compatibility.md b/docs/compatibility.md index 1f8554f..5e35ab5 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -456,13 +456,19 @@ SDK upgrade nor a task-named event family may auto-enable capture. ### Managed startup and released migration regression gate The fix for [#99](https://github.com/Phototonic/openchamber-progress/issues/99) -keeps construction and health free of security queries and moves legacy migration -to negotiated, explicitly confirmed steps. Each migration request admits at most -six PowerShell launches, with 17-second work and 18-second response deadlines -under the host's 20-second boundary. The UI preserves progress and capture -warnings, stops on failures (including failed replays), and offers explicit -pause, resume, status and reviewed capture recovery. Portable fixtures and -rendered synthetic-shell QA do not certify native Windows latency or ACLs. +keeps construction and health free of filesystem validation and moves legacy +migration to negotiated, explicitly confirmed steps, with 17-second work and +18-second response deadlines under the host's 20-second boundary. Versions 1.4.0 +to 1.5.1 also bounded each request at six PowerShell launches. Version 1.5.2 +removed those launches altogether +([#172](https://github.com/Phototonic/openchamber-progress/issues/172)): the +companion started PowerShell synchronously on load, on every guarded report, tool +hook and status request, and blocked the OpenCode event loop for 28 to 43 seconds. +Windows now relies on the user profile's default permissions, no ACL is queried, +applied or repaired, and existing private ACLs are left as found. The UI preserves +progress and capture warnings, stops on failures (including failed replays), and +offers explicit pause, resume, status and reviewed capture recovery. Portable +fixtures and rendered synthetic-shell QA do not certify native Windows latency. Fresh setup now uses the same bounded worker on every supported OS, negotiating `managedFreshSteps:1` independently from migration support. Wire 2 and journal @@ -470,25 +476,23 @@ format 3 are fresh-only; migration retains wire 1/format 2 and format-1 recovery Setup exposes optional `freshProgress`, never fresh data in `migrationProgress`. New UI/old service shows update-together guidance with no old-route fallback. Old UI/new Windows service receives exactly 409 `managed-action-required` from -old inspect/configure, before workers/security queries/writes. Linux/macOS keep +old inspect/configure, before workers or writes. Linux/macOS keep those compatibility routes only without legacy discovery or any journal. Old migrate refuses on all platforms. Older journal readers refuse format 3 even when complete; rollback retains all data/journals and uses fresh-capable recovery, not down-conversion or global-loader restoration. -The former 1.4.0 fresh Windows 3/24-launch synchronous exception is replaced by -portable measured prepare/folder/database requests at 6 launches each and later -effects at 5. New databases initialize off; retained stores keep capture and IDs. -These counters and rendered synthetic-shell checks do not certify native Windows -latency/ACLs. Native CI exercises empty default and custom stores undelayed, the -default store with 2.5-second helpers, and retained stores with matching sources -(capture on/off) or a new source (capture off). Fresh default recovery covers -prepare timeout, lost-reply replay, restart and pause/resume before/after creation; -the migration cases additionally cover slower-helper and late-worker refusal. -Every native request is gated at six launches and eight seconds undelayed or -below twenty seconds delayed, with concurrent zero-query health. These are the -job's assertions, not portable certification. Timeout never undoes changes or -permits cleanup/permission repair. See +The former 1.4.0 fresh Windows synchronous exception is replaced by bounded +prepare/folder/database requests and later effects, none of which starts a +process. New databases initialize off; retained stores keep capture and IDs. +Rendered synthetic-shell checks do not certify native Windows latency. Native CI +exercises empty default and custom stores, and retained stores with matching +sources (capture on/off) or a new source (capture off). Fresh default recovery +covers lost-reply replay, restart and pause/resume before/after creation; the +migration cases additionally cover late-worker refusal. Every native request is +gated at eight seconds with zero process launches. These are the job's +assertions, not portable certification. Timeout never undoes changes or permits +cleanup/permission repair. See [Setup](setup.md#install-review-confirm) for partial-creation refusal boundaries. The `Windows setup, storage and capture` CI job runs the native platform suite @@ -497,13 +501,12 @@ account, as two processes at once, each in its own serial test runner and each w with everything it started (`Start-Process -Wait` inside a thread job). Ordinary PRs run it when backend/build/test inputs change (unknown paths conservatively run it); UI, documentation, OpenSpec and browser-test-only PRs skip it, as do duplicate same-repository main/dev heads outside promotion. -Every `dev` push runs the fast set. This retains every native test except three -full-only journeys: released 1.1.1 migration undelayed, released 1.1.1 migration -with 2500ms helpers, and fresh setup `empty-delayed`. +Every `dev` push runs the fast set. This retains every native test except one +full-only journey: the released 1.1.1 migration. Every promotion PR into `main`, every `main` push, the weekly schedule and manual dispatch run all journeys, regardless of changed paths. Only these runs set -`AP_WINDOWS_FULL=1`; without it the three full-only journeys skip with an +`AP_WINDOWS_FULL=1`; without it the full-only journey skips with an explicit opt-in reason. The same opt-in is required for a local full native run. All assertions, budgets and deadlines inside each journey remain unchanged. Publication still requires the full Windows job on the exact `main` push. @@ -514,9 +517,9 @@ administrator product operation or runtime dependency download is used. The test launches a fresh child using the unmodified built service, synthetic HOME and XDG folders with spaces/Unicode, and an intact legacy -installation but no managed selector. A test-only preload records security-query -and legacy-read counts over IPC. Before listen and first health must both have -zero queries/legacy reads. First health must finish within 1.25 seconds and total +installation but no managed selector. A test-only preload records child-process +launch and legacy-read counts over IPC. Before listen and first health must both have +zero launches/legacy reads. First health must finish within 1.25 seconds and total startup within 12 seconds. These margins are below OpenChamber **v2.7.1** [`packages/web/server/lib/guests/service.js`](https://github.com/openchamber/openchamber/blob/v2.7.1/packages/web/server/lib/guests/service.js): 15-second startup deadline, 1.5-second authenticated health polls, 200 ms between @@ -526,20 +529,18 @@ inspection, diagnostic status and migration timings are checked against it. Authenticated inspection pages and confirmed migration steps must preserve Store/source identity, seeded schema-2 history/run storage and retained releases, remove only verified legacy discovery, and enable capture on completion. Each -request, including replay, stays within six launches and eight seconds on the -undelayed runner. A second journey adds 2.5 seconds per helper, still below the -20-second host boundary. Both exercise concurrent health and pause/reopen/resume -before and after capture is off. Injected timeout/private-creation refusals and -a worker that outlives its response must retain precise stage/code and fences, -not authorize a competing writer. Fresh children also exercise selected and invalid +request, including replay, starts no process and stays within eight seconds on the +undelayed runner. The journey exercises pause/reopen/resume before and after +capture is off. Fresh children also exercise selected and invalid hard-linked state: health never admits it, a real read refuses it, and legitimate restoration permits a fresh read. The existing Windows suite retains explicit-XDG, -canonical-alias, ACL mutation, foreign-owner and unsafe-ancestor coverage. +canonical-alias, junction and hard-link coverage, and checks that roots with an +existing owner-only ACL keep working with that ACL unchanged. `Upload sanitized Windows migration trace` uploads `windows-migration-trace` even when tests fail. Its JSONL contains only fixed stages, error **classes** (platform, -filesystem, storage, setup, test or timeout), allowlisted codes, timings, security -query/legacy-read counts, marker/lock/expectation/record/selector booleans, +filesystem, storage, setup, test or timeout), allowlisted codes, timings, process +launch/legacy-read counts, marker/lock/expectation/record/selector booleans, capture-enabled and migration-phase observations. Fixed harness codes distinguish assertion/request/proxy-budget failures from product refusals. It contains no raw logs, paths, SIDs, auth, commands or database content. Expected injected failures @@ -550,7 +551,7 @@ installation or managed companion-delivery certification. The native implementation adds no separate binary or compilation requirement for users. It uses the existing bundled JavaScript, ordinary Windows file identity -checks, and Windows PowerShell 5.1/public .NET APIs for ownership and private ACLs. +checks, with no ACL or ownership query and no child process. The [setup guide](setup.md#native-windows) defines its local-account, path and durability boundary. Historical Linux observations below remain scoped to their original configurations. @@ -569,15 +570,12 @@ cross-runtime SQLite busy handling, disable/enable of loaded code, and fresh recapture all passed. No external model/provider requests were made. Scripted execution proves the integration, not universal model compliance. -The Windows filesystem suite covers private creation/inheritance and refusal, -Unicode/case/separators/junctions, ACL mutation/cache invalidation, unsafe storage -parents, ordinary source reads, SQLite side files, binding, selector persistence, -interrupted activation/removal, hard-linked state refusal, and missing PowerShell. -Local runs explicitly skip two unavailable fixtures: the account cannot assign -a foreign owner, and Windows/.NET refused a persisted canonical callback -ACE fixture. Public .NET in-memory descriptors separately verify foreign-owner -policy and rejection of null, callback, object and audit DACL forms. Persisting -those unavailable fixtures is not claimed as tested. +The Windows filesystem suite covers directory creation with default permissions, +Unicode/case/separators/junctions, existing owner-only ACLs left unchanged, +ordinary source reads, SQLite side files, binding, selector persistence, +interrupted activation/removal and hard-linked state refusal. Versions before +1.5.2 also covered ACL mutation, foreign-owner, unsafe-ancestor and missing +PowerShell cases; those checks were removed with the queries they tested. Actual OpenChamber host startup opened the shared SQLite store under its bundled Node runtime. Panel, Work Status and full page showed matching reported counts, diff --git a/docs/contracts.md b/docs/contracts.md index 2ea9d69..9adea29 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -1366,8 +1366,8 @@ Other frames converge on their existing successful refresh, not a new bus/poll r No GET, service open or ordinary capture initializes the cleanup extension. After read-only eligibility checks, first explicit cleanup takes a verified private SQLite snapshot at `cleanup-backup-.sqlite` in the verified private store -folder (POSIX0700/file0600; on Windows the existing native path/owner/DACL policy -and private inherited file ACL), then revalidates and atomically installs format1 metadata and persistent +folder (POSIX0700/file0600; on Windows the native path and hard-link checks, with +default inherited permissions), then revalidates and atomically installs format1 metadata and persistent guards with the action. A racing or failed action can leave recovery material; it cannot partially change the selected plan. Unknown format/missing or altered guards fail closed, never silently repair/reset. No arbitrary backup destination. @@ -1641,7 +1641,7 @@ an error. Config roots use the corresponding XDG config/HOME rule. State roots, never select managed authority. `OPENCODE_DB` and `OPENCODE_CONFIG_DIR` are unsupported effective scopes; no search, fallback, automatic adoption or repair. The owned 0700 product directory and exact 0600 `.ownership.json` marker, private -descriptor, canonical non-symlink roots, owner, Windows ACL/object checks, +descriptor, canonical non-symlink roots, owner (POSIX), Windows object checks, `readBinding`, Store schema and `verifyStore` all remain required. Absent discovery is `unconfigured`; present unsafe/invalid/unsupported state is @@ -1664,7 +1664,7 @@ and settles sequence 1 with lastCompleted prepare. Advance performs one advertis step. Pause/abandon/resume retain intent and never imply undo or capture changes. Identical last-request replay reconciles durable evidence; changed/stale input refuses. Error overrides disposition, including replayed failure. All requests -retain the six-launch, 17-second-work/18-second-response budgets and writer fence. +retain the 17-second-work/18-second-response deadlines and writer fence, and start no process. Fresh review discloses `planKind:fresh`, store/source create/retain/reuse modes, capture policy, package version, canonical folders, identities and frozen plan. @@ -1702,7 +1702,7 @@ budgets and recovery boundaries. ### Compatibility controls On Windows old `managed-inspect` and `managed-configure` always return exactly -409 `{"error":"managed-action-required"}` before body parsing, security queries, +409 `{"error":"managed-action-required"}` before body parsing, worker dispatch or writes. Old `managed-migrate` refuses that way on every OS. Linux/macOS retain old fresh inspect/configure only without legacy discovery or any journal, under their nonce-bound review and writer fence. A new UI without @@ -1795,10 +1795,13 @@ against an explicitly injected legacy fixture refuse `managed-service-required`. Existing schema/binding/busy/corrupt/storage errors retain their 503 semantics; existing bounded bodies, auth, method and query checks remain unchanged. Migration inspection preserves schema/busy/corrupt/storage failures rather than -converting them into `managed-migration-conflict`. Platform security query failure -retains `windows-security-unavailable` in status diagnostics and the existing -503 `storage` mutation response. Retry requires resolving the underlying failure; -it does not authorize cleanup or takeover. +converting them into `managed-migration-conflict`. Windows starts no process for +permission checks, so `windows-security-unavailable`, `private-permissions` and +`unsafe-parent` are no longer produced; they stay in the fixed diagnostic +vocabulary so earlier journals and clients remain readable. A platform failure +retains its fixed code in status diagnostics and the existing 503 `storage` +mutation response. Retry requires resolving the underlying failure; it does not +authorize cleanup or takeover. Managed capture enable requires the valid verified managed binding and refuses a legacy conflict, not executable ownership in a global package. The existing diff --git a/docs/setup.md b/docs/setup.md index d645399..d29ddab 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -39,8 +39,8 @@ managed discovery selectors. No root scanning or automatic legacy adoption occur Opening Setup, inspecting status or loading an unconfigured companion creates no binding directory, marker, descriptor or store. Confirmed configuration creates -private product state (0700 directories and 0600 files on Linux, equivalent ACLs -on supported Windows). Mutable state never lives in the extension code folder. +product state (0700 directories and 0600 files on Linux and macOS; ordinary +per-user folders with the profile's default inherited permissions on Windows). Mutable state never lives in the extension code folder. After configuration, the next eligible native context/report boundary can activate a previously dormant companion; no global install or automatic restart is needed. @@ -94,22 +94,15 @@ retain the diagnostic vocabulary needed for support. ![Fresh Setup with the recording state, optional progress folder and collapsed technical disclosure (synthetic example)](images/setup-fresh.png) -Each request has at most six security launches, a 17-second work deadline and an -18-second response deadline below the host's 20-second limit. Health remains cheap -while workers run. Portable counters measure six launches for prepare, folder and -database creation and five for each later effect. Native Windows timing and -successful 2.5-second-helper journeys remain CI acceptance gates, not claims -inferred from Linux tests. Persistently slower helpers can still refuse within the -budget; a timeout is not rollback and never permits deleting metadata or changing -permissions to force a retry. Linux/macOS do not launch PowerShell. +Each request has a 17-second work deadline and an 18-second response deadline +below the host's 20-second limit, and no step starts a process. Health remains +cheap while workers run. A timeout is not rollback and never permits deleting +metadata or changing permissions to force a retry. The service's five-second HTTP `requestTimeout`/`headersTimeout` bounds receiving request bytes, not executing a fully received Setup request. It produces HTTP 408, -not a JSON `storage` failure. Portable regressions exercise fresh inspection and -configuration beyond five seconds with a 4.5-second first security launch and -350 ms later launches, still below the host budget. Actual helper timeouts retain -`windows-security-unavailable` (or `managed-step-deadline` in step mode), never -become evidence of absent state or permission to write. +not a JSON `storage` failure. A deadline refusal (`managed-step-deadline`) never +becomes evidence of absent state or permission to write. ## Reach and disable/removal @@ -166,20 +159,19 @@ Authenticated health and Setup delivery advertise independent `/v1/setup/managed-step` route uses wire 1 for migration and wire 2 for fresh setup. An absent fresh capability shows update-together guidance, with no old-route fallback. The old migrate -URL always returns 409 `managed-action-required` with no security launches or -migration work. On Windows the old inspect/configure URLs always refuse with that -exact 409 object before body parsing, workers, security queries or product writes. +URL always returns 409 `managed-action-required` with no migration work. On Windows the old inspect/configure URLs always refuse with that +exact 409 object before body parsing, workers or product writes. On Linux/macOS these compatibility routes do the same no-write refusal when legacy discovery or any migration journal applies (configuration of ambiguous legacy plus managed selection without a journal returns `managed-migration-conflict`, while inspection still returns `managed-action-required`). Legacy/journal inspect -refusal uses local presence hints before security queries, with no writes; its acceptance budget -is at most six security launches and eight seconds on the undelayed runner. The +refusal uses local presence hints before full validation, with no writes; its acceptance budget +is eight seconds on the undelayed runner. The old inspect/configure routes remain supported only on Linux/macOS for no-legacy, no-journal fresh setup under the existing nonce-bound review and writer fence; migration must never fall back to them. A presence hint authorizes only refusal: it neither validates nor reads the journal/legacy contents. An absent or unreadable -hint still runs the full fresh path, ACL and ownership checks, including canonical +hint still runs the full fresh path and filesystem checks, including canonical presence checks, before offering a review or writing. Invalid metadata without a migration hint retains its precise ownership/path refusal; step inspection diagnoses metadata behind a migration hint. @@ -246,8 +238,8 @@ reply; reopening reads status and requires an explicit Continue or Resume. At an unchanged journal sequence, a refreshed status observation can replace unknown capture and Resume with the actual capture bit and a required review. -Step errors retain fixed platform codes such as `windows-security-unavailable` -and `private-permissions`, alongside the actual requested step or journal/lock +Step errors retain fixed platform codes such as `path-unverified` +and `symlink-escape`, alongside the actual requested step or journal/lock stage. No raw exception, path, account identity, token, command or database content is included. A non-null error means failure even if the disposition says `replayed`: that is a failed receipt, not a successful retry. Budget/deadline/busy @@ -272,7 +264,7 @@ Managed-directory bootstrap also retains narrow **manual-recovery crash windows* from versions 1.2.0 and 1.3.0. A crash after directory creation but before the ownership marker, or between linking a published file and removing its staging link, can leave invalid private metadata. Such an unmarked directory, hard-link -anomaly, permissive ACL or foreign content is refused, never adopted, repaired or +anomaly or foreign content is refused, never adopted, repaired or deleted automatically. A valid marked same-target directory with no migration journal can be reused after fresh validation and confirmation; it is not the same as an unmarked directory. The step protocol's `prepare` stage uses this @@ -530,63 +522,46 @@ guide. Historical companion-update confirmations are not the managed update path ## Native Windows -Native filesystem protection uses existing JavaScript and built-in Windows -PowerShell 5.1/.NET, not a new executable/compiler/module. Fixed profile-free, -noninteractive scripts receive UTF-8 JSON through stdin; paths are not executable -command text. Missing/blocked PowerShell is a fixed privacy/setup failure. - -Outside the setup step engine, the first security query per loaded -service/companion has a 30-second attempt and -one identical retry only on timeout (up to 60 seconds configured wait). Later -queries have one 10-second attempt. Termination/OS overhead is additional; these -are not setup-operation deadlines. Non-zero exits, spawn errors and malformed -results are not retried. No path is admitted without parsed security evidence. - -Managed service construction and health perform **zero security queries** and no -legacy payload/Store preflight. Read-only validation scopes coalesce their known -paths; security results do not survive the synchronous operation, and mutation -boundaries retain fresh validation. There is no process-lifetime or TTL ACL cache. -The host's liveness deadline is separate from these security-helper budgets. -OpenChamber 2.7.1 also limits both the guest bridge and service proxy to **20 seconds** -per request (`packages/sdk/src/contract.ts:499`, `host.ts:607-618`, and -`packages/web/server/lib/guests/service.js:725,832,855-856` at tag `v2.7.1`). -Migration and fresh setup run as separate inspection pages and confirmed steps, with at most -**six actual PowerShell starts per request**, including failures, replay, checks, -publication and cleanup. The 17-second work and 18-second response deadlines sit -below the host limit; the undelayed runner gates each request at eight seconds. -The native suite also exercises helpers delayed by 2.5 seconds, concurrent health, -pause/reopen/resume and failed workers. Native results remain pending CI; these -are acceptance budgets, not a latency guarantee for every machine. - -Every request uses fresh ownership checks; no ACL result survives a mutation or -request boundary. A blocked helper fails closed, never skips a check to meet the -deadline, and step mode does not inherit the cold-query retry. Workers retain -their fence until exit; timeout is not rollback. The portable HTTP fixture counts -real helper-launch calls at a substituted OS boundary, not legacy file reads or -native NTFS security. Fresh inspection pages measure 1 each (retained roots can -take 2); prepare, store-directory and create-store measure 6 each; later effects -measure 5; settled replay 1, controls normally 3, Setup status 3 before binding and -4 afterwards. All failure/settlement attempts remain within 6. The old non-Windows -compatibility controller remains synchronous; its historical Windows accounting -was 3/24, not the current Windows path. -Measured portable manifest/selector journeys use 1, 1, 4, 1, 1, 1 launches for -the six inspection pages, 6 for prepare, 5 per ordinary advance/removal batch, -6 for recording removal, 1 for a successful replay, 3 per pause/stop/resume, -and 4 for an active-operation status read. Receipt recovery uses 2, 3, 2, 2, -1, 1 for inspection and 3 for prepare, then skips already completed removal. -Old-route refusals measure 0 for legacy/journal inspect/configure and for migrate. -These are fixture measurements, not a promise that every refusal has the same -cost; the six-launch ceiling includes failure and settlement work. -See [the step protocol](../setup/managed-steps.md#request-budgets-and-measured-stage-split) -for accounting and settlement rules. - -Use one account and local NTFS storage. Config/data roots require current-account -ownership; dedicated store and managed state require private ACLs permitting only -that account, SYSTEM and Administrators. New roots get ACLs at creation; existing -foreign/permissive roots or replaceable ancestors are refused, not repaired or -taken over. Ancestor ownership must be current user, SYSTEM, Administrators or -TrustedInstaller. Owned hard-linked state files are refused. Journals/side files -remain under the secured store. No elevation is attempted. +Native filesystem protection uses existing JavaScript and ordinary Node +filesystem calls only. No process is started for any permission check, no ACL is +queried, applied or repaired, and no native helper, compiler or module is part of +the runtime. State lives under the user's profile and relies on its default +per-user permissions, like other per-user applications. This was a maintainer +decision ([#172](https://github.com/Phototonic/openchamber-progress/issues/172)): +starting Windows PowerShell synchronously for each check (one to two seconds each) +blocked the OpenCode event loop inside the companion for tens of seconds. + +Windows keeps the checks that need only filesystem calls: drive-qualified path +syntax, canonical path, refusal of symbolic links and junctions in the path chain, +refusal of hard-linked owned state files, content-ownership markers, hashes and +schema validation. Directories are created with default inheritance, and an +existing directory is accepted as it is. Existing roots that carry a private ACL +from an earlier version keep working and are never modified. Linux and macOS keep +their uid and mode checks. + +Managed service construction and health do no legacy payload/Store preflight. +Every request and every mutation boundary repeats its path and object checks; no +result survives a request. The host's liveness deadline is separate from the +setup deadlines. OpenChamber 2.7.1 also limits both the guest bridge and service +proxy to **20 seconds** per request (`packages/sdk/src/contract.ts:499`, +`host.ts:607-618`, and `packages/web/server/lib/guests/service.js:725,832,855-856` +at tag `v2.7.1`). Migration and fresh setup run as separate inspection pages and +confirmed steps. The 17-second work and 18-second response deadlines sit below the +host limit; the undelayed runner gates each request at eight seconds. The native +suite also exercises pause/reopen/resume and failed workers, and an independent +observer asserts that the service starts no process. Native results remain +pending CI; these are acceptance budgets, not a latency guarantee for every +machine. + +Workers retain their fence until exit; timeout is not rollback. The portable +fixtures spy on every child-process entry point of a projected Windows path; they +do not exercise native NTFS behaviour. See +[the step protocol](../setup/managed-steps.md#request-budgets-and-measured-stage-split) +for deadline and settlement rules. + +Use one account and local NTFS storage. Owned hard-linked state files are +refused. Journals/side files remain in the store folder. No elevation is +attempted. Drive-qualified paths support either separator, spaces, Unicode and trailing directory separators through actual identity checks, not blind lowercasing. @@ -595,8 +570,8 @@ alternate data streams and reserved aliases are refused. Long paths and other filesystems are not certified; APPDATA is not assumed to be OpenCode config. Capture checks requested/canonical permissions, opened-file identity and bounded -bytes, then file/ancestor identity and mutation metadata. Source documents do not -need private-store ACLs. Failure retains prior text and valid structured reports. +bytes, then file/ancestor identity and mutation metadata. Source documents are +ordinary authorized reads. Failure retains prior text and valid structured reports. Trusted same-account processes are assumed; this is not Linux final-opened-path proof against coordinated hostile filesystem races. Windows flushes writable file descriptors but lacks POSIX directory fsync/power-loss namespace guarantees. diff --git a/setup/managed-steps.md b/setup/managed-steps.md index c45c7ce..454a74b 100644 --- a/setup/managed-steps.md +++ b/setup/managed-steps.md @@ -1,5 +1,16 @@ # Bounded managed setup contract +> **Since 1.5.2 no step starts a process.** The Windows permission queries +> (Windows PowerShell, one to two seconds each) were removed together with the +> six-launch ceiling, the helper cold-start budgets and the account-scoped mutex +> barrier. Windows relies on the profile's default permissions; ACLs are never +> queried, applied or repaired. The step names, the split into separate durable +> requests, the 17-second work and 18-second response deadlines, the writer slots +> and the fresh validation of every mutation are unchanged, and +> `accounting.securitySpawns` stays on the wire as a constant 0. Where this +> document describes launch counts, allocations or ACL checks below, read it as the +> history of why the steps are split, not as a current requirement. + ## Fresh consumer contract (wire 2 / journal 3) Fresh setup is a separate family on the same route: `ManagedFreshStepRequest`, @@ -50,48 +61,39 @@ Only pending/complete coarse phases exist, never fabricated removal evidence. The storage lane implements `Store.createFresh(file, {storeId, validate})`, returning a normal Store handle. `storeId` is the frozen proposed ID; `validate` is mandatory full same-target/intent validation, called in the helper's read-only preflight -scope. Creation is exclusive, uses mode 0600/private inherited Windows ACLs, checks -all fixed sidecars absent, ends the preflight before reservation, and freshly checks +scope. Creation is exclusive, uses mode 0600 (Windows: the default inherited +permissions), checks all fixed sidecars absent, ends the preflight before reservation, and freshly checks the reserved file/object/ancestors before initialization. The initial schema transaction installs the frozen ID, capture **off**, schema 2 and receipt index. It registers no source. Ordinary constructor defaults/partial-file refusals stay unchanged. Failed/partial files are retained, never reopened for initialization. Immediately before either exclusive creation, after the final read-only preflight, -the helper rechecks room for three launches and 8.5 seconds: creation/new-object -admission plus checkpoint validation and readback, at 2.5 seconds each with one -second headroom. Slow preflight can therefore refuse while the target is still -absent and safely retryable; the earlier engine reservation alone is insufficient. +the helper rechecks that the request deadline has not passed. A slow preflight can +therefore refuse while the target is still absent and safely retryable. The platform lane extends `privateDirectory(file, false, {exclusive: true, -validate})`. Mandatory validation shares its read-only path preflight; that actual -scope ends before the creation query. An existing/unexpected directory refuses, +validate})`. Mandatory validation shares its read-only path preflight, which ends +before creation. An existing/unexpected directory refuses, never becomes adopted authority. The caller checkpoints the resulting identity only through the corresponding durable intent. A crash before that checkpoint -requires manual diagnosis, not automatic adoption. No raw security-backend bypass, -claim file, repair, new schema or cached ACL authority is introduced. - -These interfaces are frozen for consumers. Portable full-engine measurements are -prepare/store-directory/create-store 6 launches each, expectation/register-source/ -publish-binding/enable/reconcile 5 each, settled replay 1 and normal controls 3. -Fresh inspection pages measure 1 each (retained roots can take 2); ordinary Setup -status measures 3 before selection/4 after. Injected failure settlement remains -within 6. These substitute only the OS-spawn boundary, not native timing or NTFS -ACLs. Native CI tests default/custom empty stores undelayed, the default store -with 2.5-second helpers, retained reused sources with capture on/off, and a retained -new source with capture off. Requests assert six launches, eight seconds undelayed -or below twenty seconds delayed, and concurrent zero-query health. -The six-launch gate includes all validation, -actual attempts, creation, readback and failure settlement. Stop for a technical -amendment if safe creation cannot fit. Format-3 observation before storage exists +requires manual diagnosis, not automatic adoption. No claim file, repair, new +schema or cached authority is introduced. + +These interfaces are frozen for consumers. Portable full-engine tests assert that +no step starts a process on a projected Windows path. Native CI tests default and +custom empty stores, retained reused sources with capture on/off, and a retained +new source with capture off. Requests assert no process launch and eight seconds, +and health answers with zero launches. Safe creation that cannot finish before +the deadline refuses and is retried by a new request. Format-3 observation before storage exists requires the fresh journal reader, not `readBinding` on an absent directory. Rollback retains journals/data and requires a fresh-capable build for recovery. The sections below retain the wire-1 / format-2 migration contract. Wire 2 and format 3 extend the same engine, worker and single Setup driver, not a parallel installer. Backend HTTP and rendered synthetic-shell journeys are integrated; -portable query accounting is **not a native performance result**. Fresh default -native recovery tests prepare timeout, replay and restart/pause/resume before and -after creation; migration tests additionally exercise slower/late-worker refusal. +portable tests are **not a native performance result**. Fresh default +native recovery tests replay and restart/pause/resume before and +after creation; migration tests additionally exercise late-worker refusal. Native acceptance and independent trust-boundary/error-path review remain delivery gates. ## Owners and invariants @@ -101,13 +103,13 @@ Native acceptance and independent trust-boundary/error-path review remain delive - Consumer examples: `tests/fixtures/managed-steps.ts` (synthetic, not traces). - Extend `setup/managed-migration.ts`, the lifecycle ownership/removal owner and the existing private-publication helpers. No alternate installer/remover. -- Preserve bearer authentication, current-account ownership, safe ancestors, +- Preserve bearer authentication, content ownership (POSIX: current-account + ownership and modes), canonical paths, no reparse/hard-linked private files, exact manifest/byte checks, Store/source identity and schema checks, independent companion admission, retained history, payloads and receipts. Neither a cursor nor journal nor health grants authority. -- No cached ACL verdict across requests **or mutations**. A nested - `platformSecurityScope` does not clear an outer scope. End/reset the actual - scope at every write boundary; a helper rename alone is not a reset. +- No validation result is cached across requests **or mutations**; every write + boundary rereads the filesystem. - Serialize across processes for both discovery target and shared Store capture control, including ordinary capture controls. Hold no lock over user think time. New locking must be crash-releasing or positively reconciled; a timestamp @@ -211,30 +213,29 @@ request refusal uses the same envelope with `disposition: refused`, non-null sequence/target/review, unsupported format/version and ownership conflicts are 409, including `managed-configuration-busy`, `managed-path-unverified` and `managed-scope-unsupported`; worker/coordination busy, deadline, budget and -unavailable security/storage are 503. A response +unavailable storage are 503. A response failure is not rollback. Unknown operation status is 404, never another target's progress. Ordinary authentication/method/body-limit failures keep existing HTTP handling and do not require this envelope. -Accounting uses an integer security-spawn count and finite nonnegative elapsed +Accounting uses an integer launch count (always 0) and finite nonnegative elapsed milliseconds; the monotonic duration may include a fractional millisecond. Non-null `error` overrides `disposition`, including a `replayed` failed receipt; clients must render that reply as failed, not continue the success path. A worker crash is treated as effect uncertainty and requires explicit observation/recovery. Old-shaped `/v1/setup/managed-migrate` returns exactly HTTP 409 -`{"error":"managed-action-required"}` with **zero security spawns and migration +`{"error":"managed-action-required"}` with **no migration writes**, before candidate discovery. It is never a partial-success 200. On Windows `managed-inspect` and `managed-configure` also return exactly that 409 -object with zero workers, security launches or product writes before body parsing. +object with zero workers or product writes before body parsing. On Linux/macOS they remain supported for fresh configuration with no canonical legacy installation or migration journal. They retain the existing controller's nonce-bound review, explicit confirmation and fresh locked revalidation. Presence of legacy discovery or any journal refuses these routes with 409 `managed-action-required` before monolithic legacy inspection or writes; use negotiated step inspection instead. Legacy/journal inspection refusal is -read-only, with at most six security launches and an eight-second undelayed -acceptance budget. Local legacy/journal presence hints refuse before security -queries; absent or unreadable hints grant no authority and still require full +read-only, with an eight-second undelayed acceptance budget. Local +legacy/journal presence hints refuse before full validation; absent or unreadable hints grant no authority and still require full fresh validation and the canonical presence check. These hints read no metadata contents and are not retained between requests or used to admit an effect. Without a journal, configuration with concurrent legacy discovery and a managed @@ -251,83 +252,64 @@ capability is independent. The old Linux/macOS inspection/configuration routes remain outside the negotiated step-request budget and worker boundary. They keep the synchronous 1.3.0 -controller and security timeouts, holding the same target-derived scope **and** +controller, holding the same target-derived scope **and** Store writer slots for the entire request, including publication and cleanup. A busy slot refuses before controller admission; fresh configuration cannot race a migration or capture worker. The fence releases on completion/failure, not on client disconnection. Partial bootstrap still has the existing recovery limits. -Historical portable Windows-helper accounting measured 3/24 launches for these -old routes. Windows now refuses them before work; the current UI uses negotiated +Windows refuses these old routes before work; the current UI uses negotiated fresh steps on all platforms. A compatibility timeout is not rollback: inspect state before explicitly retrying; never reset or repair it automatically. -Linux/macOS do not launch PowerShell. No old-route fallback is allowed from the -fresh client if its capability is absent. +No old-route fallback is allowed from the fresh client if its capability is absent. The five-second HTTP request/header timeouts limit receipt of bytes (HTTP 408), not handler execution after body parsing. They are not a five-second setup -deadline and remain unchanged. Portable HTTP regressions model a 4.5-second first -launch and 350 ms subsequent launches: both fresh inspection and confirmation -complete beyond five seconds but below the host limit. Real helper timeouts -remain `windows-security-unavailable` outside step mode and -`managed-step-deadline` inside it, not generic `storage` failures. This does not -authorize old Windows routes or remove bounded refusals for persistently slow helpers. - -## Request budgets and measured-stage split - -Six is the **total real process-start ceiling**, not six logical queries. Count -the first cold launch, failed launch attempts, retries, validation, creation, -post-write checks, journal/lock/staging cleanup and reply construction, including -work in another thread/process. No warm-up outside the charged request. Worker -spawn itself is not a security-process spawn; every PowerShell descendant is. - -The service's monotonic work deadline is 17 seconds from authenticated request -admission; response deadline is 18 seconds, below the 20-second host boundary. -Time waiting for serialization consumes this budget. Bound each helper wait by -remaining work time minus required settlement headroom; do not inherit the -30-second cold wait/retry. No automatic cold retry in step mode. Reserve the -remaining spawn/time slots for completion and cleanup **before** admitting an -effect. If a needed fresh batch exceeds the bound, stop before the effect with -`managed-step-budget` or `managed-step-deadline`. Return the already-known -diagnostic/progress without a synchronous status scan. After an uncertain effect, -return unknown capture and `managed-step-unsettled`/deadline, retaining intent. -Fence a late worker before any competing request can mutate. Termination is not -proof of rollback; health must continue to answer without security queries. - -The following is a required allocation for step requests, not a claim that -unmodified helpers fit. -The original stage totals overlap semantic work; do not add them to infer a new -total. All step requests, including status/replay/failure, remain capped at six. - -| Old measured stage | New request unit | Security-spawn allocation | -| --- | --- | --- | -| inspect 19 | `roots`, `managed-state`, `legacy-discovery`, `legacy-releases` per bounded release group, `store`, `review` | at most 4 validation + 2 failure/cleanup each; no writes | -| preflight + create 12 | discovery above, then `prepare` alone | 2 fresh validation + 1 private container creation + 2 publication/checkpoint validation + 1 cleanup = 6 | -| locked validation 10 | no standalone authority checkpoint; freshly batch the fully discovered target in **each** one-effect mutation request | 1 full known-path batch per validation boundary, as allocated below; reread every manifest/binding/hash/Store fact, never reuse an earlier verdict | -| expectation 1 | `expectation` only | 1 admission + 1 intent + 1 effect + 2 checkpoint/reconciliation + 1 cleanup = 6 | -| record writes 12 | initial prepare; intent/completion inside each separate effect; `record-removal`; final `reconcile` | same per-request six-slot envelope; no three phase publications plus final status in one request | -| removal 7 | one `remove-selector` per staged selector; one `remove-discovery` per root file; then `record-removal` | each 1 admission + 1 intent + 1 effect + 2 checkpoint + 1 cleanup = 6 | -| final status 11 | `publish-binding`, `enable`, then `reconcile`; ordinary status is a bounded projection | publication/enable use six-slot effect envelope; reconcile 2 validation + 1 intent + 2 checkpoint + 1 cleanup = 6; status <=4 reads +2 failure/cleanup | - -Full checks fit fewer launches by batching **already discovered path claims plus -all ancestors**, not by splitting authorization across requests. Claim paths +deadline and remain unchanged. A step that runs past its work deadline refuses with +`managed-step-deadline`, not a generic `storage` failure. + +## Request budgets and stage split + +No step starts a process, so there is no launch ceiling to allocate. The service's +monotonic work deadline is 17 seconds from authenticated request admission; +response deadline is 18 seconds, below the 20-second host boundary. Time waiting +for serialization consumes this budget. If a needed fresh validation cannot finish +before the deadline, stop before the effect with `managed-step-deadline` and +return the already-known diagnostic/progress without a synchronous status scan. +After an uncertain effect, return unknown capture and +`managed-step-unsettled`/deadline, retaining intent. Fence a late worker before +any competing request can mutate. Termination is not proof of rollback; health +must continue to answer without any filesystem validation. + +The original measured stages were split into the request units below to fit the +old per-request launch ceiling. The split is kept, because journals and the Setup +driver depend on it, but the ceiling itself is gone. + +| Old measured stage | New request unit | +| --- | --- | +| inspect | `roots`, `managed-state`, `legacy-discovery`, `legacy-releases` per bounded release group, `store`, `review`; no writes | +| preflight + create | discovery above, then `prepare` alone | +| locked validation | no standalone authority checkpoint; freshly validate the fully discovered target in **each** one-effect mutation request; reread every manifest/binding/hash/Store fact, never reuse an earlier verdict | +| expectation | `expectation` only | +| record writes | initial prepare; intent/completion inside each separate effect; `record-removal`; final `reconcile` | +| removal | one `remove-selector` per staged selector; one `remove-discovery` per root file; then `record-removal` | +| final status | `publish-binding`, `enable`, then `reconcile`; ordinary status is a bounded projection | + +Full checks batch **already discovered path claims plus all ancestors**, not +split authorization across requests. Claim paths include journal/marker/selector, roots, descriptors, manifest, every retained release file, removal candidates, expectation, history and existing SQLite side -files as applicable. Within each fresh batch check object snapshots before/after, -then reread and validate manifests/descriptors and all required hashes/Store -facts under that scope. A changed manifest, object or discovered set invalidates -the batch. Do not follow a newly discovered path from an unvalidated manifest or -authorize by cached byte hashes. Rechecking known safe paths may be coalesced; -new paths require another charged batch or a read-only discovery continuation. +files as applicable. Check object snapshots before/after, then reread and validate +manifests/descriptors and all required hashes/Store facts. A changed manifest, +object or discovered set invalidates the batch. Do not follow a newly discovered +path from an unvalidated manifest or authorize by cached byte hashes. The bounded claim set is at most 256 paths (ancestors additionally deduplicated); the byte/request/deadline bounds still apply. More paths or bytes are an explicit `managed-step-limit` **before confirmation/effects**, not a truncated successful review. Read-only release inspection may be paged, but full fresh ownership is -still required at every affected mutation. Increasing this limit or discovering -that a safe atomic step cannot fit six requires technical review, not weakened -checks. The supported released fixture must actually complete at 2.5 seconds -per launch; endless bounded refusals do not pass acceptance. +still required at every affected mutation. The supported released fixture must +complete; endless bounded refusals do not pass acceptance. ## Effect sequence and partial removal @@ -344,7 +326,7 @@ journal; no capture, expectation, loader or selector effect. Reuse the unchanged `createManagedBindingDirectory` helper, as the managed-configuration path does, then publish the initial journal as a **file** inside the validated managed directory using the existing no-clobber private-file publication. There is no -claim file, atomic-container requirement, new ACL mechanism or directory repair. +claim file, atomic-container requirement or directory repair. Only a fully published, freshly validated prepare checkpoint releases the next step. Existing managed directories/format-1 records require same-target validation rather than replacement of foreign bytes. @@ -356,7 +338,7 @@ rather than replacement of foreign bytes. | Managed directory absent | Freshly validate the confirmed target, then use existing directory creation. | | Valid private managed directory and exact marker; journal absent | Freshly validate the same target and consent, then publish only the initial journal. After restart before a durable request receipt exists, fresh inspection/confirmation may be needed. | | Valid managed directory, marker and same-operation journal | Validate the journal and reconcile/replay its durable receipt; never repeat completed effects. | -| Directory without a valid marker, foreign bytes, permissive ACLs or any reparse/hard-link anomaly | Refuse with stage `prepare` and `managed-binding-invalid` or the precise allowlisted failure code; never adopt, repair or delete. | +| Directory without a valid marker, foreign bytes or any reparse/hard-link anomaly | Refuse with stage `prepare` and `managed-binding-invalid` or the precise allowlisted failure code; never adopt, repair or delete. | | Retained publication stage or two-link state after interrupted file publication | Refuse ambiguous/invalid state without automatic cleanup, link adoption or overwriting. | | Existing format-1 state | Use its separately specified full same-target inspection/consent and validated upgrade path. | @@ -371,10 +353,9 @@ rather than claim that all bootstrap crashes resume automatically. On a refused partial bootstrap, stop migration and retain the state for manual diagnosis. Follow `docs/setup.md` recovery guidance; do not delete the directory, -publication stage or lock, change ACLs, or restore a global loader merely to make +publication stage or lock, or restore a global loader merely to make Setup continue. Public diagnostics contain only stage/code, never local paths. -All validation, creation, publication and failure/cleanup spawns still count -toward prepare's six-spawn limit. No warming or safety check is exempted. +No safety check is exempted to meet the deadline. The documented trusted-same-account-process assumption still applies; there is no new claim of resistance to coordinated hostile same-account races. Windows From 0acdc0a2fbe741ea4c0d2854b9017de65ca6d4b3 Mon Sep 17 00:00:00 2001 From: Phototonic <35551999+Phototonic@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:52:28 +1100 Subject: [PATCH 4/5] test(windows): give the released-installer fixture root its earlier owner-only ACL --- docs/setup.md | 7 ++++--- tests/backend/windows-platform.test.ts | 17 +-------------- tests/backend/windows-service.test.ts | 6 +++++- tests/fixtures/windows-acl.ts | 29 ++++++++++++++++++++++++++ 4 files changed, 39 insertions(+), 20 deletions(-) create mode 100644 tests/fixtures/windows-acl.ts diff --git a/docs/setup.md b/docs/setup.md index d29ddab..c4f30b4 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -535,8 +535,9 @@ Windows keeps the checks that need only filesystem calls: drive-qualified path syntax, canonical path, refusal of symbolic links and junctions in the path chain, refusal of hard-linked owned state files, content-ownership markers, hashes and schema validation. Directories are created with default inheritance, and an -existing directory is accepted as it is. Existing roots that carry a private ACL -from an earlier version keep working and are never modified. Linux and macOS keep +existing directory is accepted as it is. A custom store folder outside the +profile simply has whatever permissions it already carries. Existing roots that +carry a private ACL from an earlier version keep working and are never modified. Linux and macOS keep their uid and mode checks. Managed service construction and health do no legacy payload/Store preflight. @@ -556,7 +557,7 @@ machine. Workers retain their fence until exit; timeout is not rollback. The portable fixtures spy on every child-process entry point of a projected Windows path; they do not exercise native NTFS behaviour. See -[the step protocol](../setup/managed-steps.md#request-budgets-and-measured-stage-split) +[the step protocol](../setup/managed-steps.md#request-budgets-and-stage-split) for deadline and settlement rules. Use one account and local NTFS storage. Owned hard-linked state files are diff --git a/tests/backend/windows-platform.test.ts b/tests/backend/windows-platform.test.ts index 7dc6274..e35b8ab 100644 --- a/tests/backend/windows-platform.test.ts +++ b/tests/backend/windows-platform.test.ts @@ -16,6 +16,7 @@ import { createManagedBindingDirectory, readManagedBinding, managedSourceRoots } import { SetupController } from '../../service/setup-controller.ts'; import { setupSuggestions } from '../../service/suggestions.ts'; import type { Actor } from '../../shared/progress.ts'; +import { icacls, makeOwnerOnly, readAcl } from '../fixtures/windows-acl.ts'; import { setupLegacy } from '../../plugin/index.ts'; const native = { skip: process.platform !== 'win32', timeout:120000 }; @@ -33,22 +34,6 @@ function fixture() { privateDirectory(configRoot);privateDirectory(dataRoot); return {root,targets:{configRoot,dataRoot,storeRoot,confirmed:true},clean(){fs.rmSync(root,{recursive:true,force:true});}}; } -/** Test-only fixtures: set and read an explicit, owner-only ACL with icacls. The - * product never applies, queries or repairs an ACL; these helpers exist only to - * prove that existing private ACLs keep working and are left unmodified. */ -const icaclsExe=()=>path.join(process.env.SystemRoot!,'System32','icacls.exe'); -function currentSid():string { - const r=spawnSync('whoami',['/user','/fo','csv','/nh'],{encoding:'utf8',windowsHide:true,timeout:20000}); - const sid=r.status===0?/"(S-1-5-[0-9-]+)"\s*$/.exec(r.stdout.trim())?.[1]:undefined; - assert.ok(sid,'current account SID is available to the fixture');return sid; -} -function icacls(file:string,args:string[]):string { - const r=spawnSync(icaclsExe(),[file,...args],{encoding:'utf8',windowsHide:true,timeout:20000}); - assert.equal(r.status,0,'icacls fixture command succeeds');return r.stdout; -} -const makeOwnerOnly=(file:string)=>icacls(file,['/inheritance:r','/grant:r',`*${currentSid()}:(OI)(CI)F`]); -const readAcl=(file:string)=>icacls(file,[]); - test('Windows creates Unicode directories with default permissions and starts no process',native,t=>{ const f=fixture();try{ const spawns=t.mock.method(childProcess,'spawnSync',(()=>{throw new Error('no permission check may start a process');}) as unknown as typeof childProcess.spawnSync);syncBuiltinESMExports(); diff --git a/tests/backend/windows-service.test.ts b/tests/backend/windows-service.test.ts index d2a2c73..a0ac852 100644 --- a/tests/backend/windows-service.test.ts +++ b/tests/backend/windows-service.test.ts @@ -12,6 +12,7 @@ import {Store} from '../../shared/store.ts'; import {MANAGED_INSPECTION_STEPS,MANAGED_MIGRATION_STEPS,MANAGED_FRESH_INSPECTION_STEPS,MANAGED_FRESH_STEPS,MANAGED_STEP_CODES,type ManagedStepRequest,type ManagedStepResponse,type ManagedFreshStepRequest,type ManagedFreshStepResponse} from '../../shared/managed-steps.ts'; import {MANAGED_ACTION_CODES} from '../../shared/progress.ts'; import {nativeService,nativeHarnessCode,HEALTH_MS,type Observation} from '../fixtures/windows-service-driver.ts'; +import {makeOwnerOnly} from '../fixtures/windows-acl.ts'; /** Released emitted lifecycle AND Store, not a current-source reconstruction. */ async function released(root:string){ @@ -211,7 +212,10 @@ test('Windows built released 1.1.1 step migration',{skip:fullJourneySkip||proces } } try{ - privateDirectory(root);const home=path.join(root,'home ü space');privateDirectory(home); + privateDirectory(root); + // The released 1.1.1 installer below still checks ACLs itself: give its root the + // owner-only ACL that version created, which every folder under it inherits. + makeOwnerOnly(root);const home=path.join(root,'home ü space');privateDirectory(home); const env:NodeJS.ProcessEnv={HOME:home,USERPROFILE:home,TEMP:path.join(root,'temp'),TMP:path.join(root,'temp'), XDG_CONFIG_HOME:path.join(home,'.config'),XDG_DATA_HOME:path.join(home,'.local','share'),XDG_STATE_HOME:path.join(root,'state'),XDG_CACHE_HOME:path.join(root,'cache'),XDG_RUNTIME_DIR:path.join(root,'runtime')}; for(const key of ['SystemRoot','SYSTEMROOT','WINDIR'])if(process.env[key])env[key]=process.env[key]; diff --git a/tests/fixtures/windows-acl.ts b/tests/fixtures/windows-acl.ts new file mode 100644 index 0000000..1a49fbd --- /dev/null +++ b/tests/fixtures/windows-acl.ts @@ -0,0 +1,29 @@ +import assert from 'node:assert/strict'; +import path from 'node:path'; +import {spawnSync} from 'node:child_process'; + +/** Native Windows test fixtures only. The product never applies, queries or + * repairs an ACL. These helpers reproduce what an earlier version left behind, + * an owner/SYSTEM/Administrators-only folder, to prove that such a folder keeps + * working, and that the released 1.1.1 installer (which still checks ACLs in the + * test process) accepts the fixture root it migrates from. */ +const icaclsExe=()=>path.join(process.env.SystemRoot!,'System32','icacls.exe'); + +export function currentSid():string { + const r=spawnSync('whoami',['/user','/fo','csv','/nh'],{encoding:'utf8',windowsHide:true,timeout:20000}); + const sid=r.status===0?/"(S-1-5-[0-9-]+)"\s*$/.exec(r.stdout.trim())?.[1]:undefined; + assert.ok(sid,'current account SID is available to the fixture');return sid; +} + +export function icacls(file:string,args:string[]):string { + const r=spawnSync(icaclsExe(),[file,...args],{encoding:'utf8',windowsHide:true,timeout:20000}); + assert.equal(r.status,0,'icacls fixture command succeeds');return r.stdout; +} + +/** The private ACL earlier versions created: no inheritance, full control for + * the current account, SYSTEM and Administrators only, inherited by children. */ +export function makeOwnerOnly(file:string):string { + return icacls(file,['/inheritance:r','/grant:r',`*${currentSid()}:(OI)(CI)F`,'*S-1-5-18:(OI)(CI)F','*S-1-5-32-544:(OI)(CI)F']); +} + +export const readAcl=(file:string):string=>icacls(file,[]); From bb41fca6d36bc7de95bfde5392f8e422f617200c Mon Sep 17 00:00:00 2001 From: Phototonic <35551999+Phototonic@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:14:31 +1100 Subject: [PATCH 5/5] fix: keep a creation headroom, map lost creation races, retire the PowerShell copy --- docs/backend.md | 18 ++++--- docs/compatibility.md | 10 ++-- docs/setup.md | 29 ++++++---- .../windows-setup-responsiveness/spec.md | 5 +- setup/managed-step-engine.ts | 12 ++--- shared/platform.ts | 28 ++++++---- shared/store.ts | 4 +- tests/backend/managed-fresh-store.test.ts | 16 ++++++ tests/backend/managed-step-engine.test.ts | 10 ++++ tests/backend/platform-budget.test.ts | 53 +++++++++++++++++++ tests/browser/model.test.ts | 8 ++- ui/shared/setup.ts | 6 +-- 12 files changed, 157 insertions(+), 42 deletions(-) create mode 100644 tests/backend/platform-budget.test.ts diff --git a/docs/backend.md b/docs/backend.md index 61965ca..2167a8c 100644 --- a/docs/backend.md +++ b/docs/backend.md @@ -452,8 +452,11 @@ workers. Admission reads the current private journal and revalidates all known paths and lifecycle facts; no validation result crosses a request or write. An outdated hint is discarded as authority, not a conflict with an otherwise valid current request; operation identity is still checked. -Status can restore those claims after restart. A cold mutation that cannot finish -before the work deadline refuses before publishing an intent; explicit bounded +Status can restore those claims after restart. A mutation with less than +2.5 seconds of the work deadline left (`STEP_HEADROOM_MS`) refuses before +publishing an intent and again right before an exclusive creation (directory, +database or managed folder), so a creation is never stranded without its +checkpoint and the target stays absent and retryable; explicit bounded status/resume is the recovery path, not a hidden retry or a weakened check. Portable HTTP tests assert that no step starts a process. @@ -522,10 +525,13 @@ can reconcile read-only from their matching durable creation intent. Portable full-engine tests run the whole fresh engine on a projected Windows path and assert that no creation, settlement, replay or control starts a process. Native CI tests empty default/custom stores, retained matching sources with -capture on/off, and a retained new source with capture off. Default fresh -recovery tests replay and restart/pause/resume; migration tests add late-worker -refusal. Native requests assert no process launch and eight seconds, and health -answers with zero launches. +capture on/off, and a retained new source with capture off. Native recovery +covers replay and restart/pause/resume. Native requests assert no process launch +and eight seconds, and health answers with zero launches. Deadline refusal, a +response deadline with a late worker (the writer slot is held until it exits), +injected worker faults and concurrent writers are covered by the portable +`managed-step-http.test.ts` and `managed-request-worker.test.ts` fixtures only; +no native case injects them. The format-2 migration journal provides bounded strict parsing, canonical target/request digests, consistency/transition validation and private no-clobber diff --git a/docs/compatibility.md b/docs/compatibility.md index 5e35ab5..e47ea43 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -488,10 +488,12 @@ process. New databases initialize off; retained stores keep capture and IDs. Rendered synthetic-shell checks do not certify native Windows latency. Native CI exercises empty default and custom stores, and retained stores with matching sources (capture on/off) or a new source (capture off). Fresh default recovery -covers lost-reply replay, restart and pause/resume before/after creation; the -migration cases additionally cover late-worker refusal. Every native request is -gated at eight seconds with zero process launches. These are the job's -assertions, not portable certification. Timeout never undoes changes or permits +covers lost-reply replay, restart and pause/resume before/after creation. Every +native request is gated at eight seconds with zero process launches. Deadline +refusal, late-worker exclusion and injected faults are covered by portable +fixtures only (`managed-step-http.test.ts`, `managed-request-worker.test.ts`); +versions before 1.5.2 injected them natively through the slow helper. These are +the job's assertions, not portable certification. Timeout never undoes changes or permits cleanup/permission repair. See [Setup](setup.md#install-review-confirm) for partial-creation refusal boundaries. diff --git a/docs/setup.md b/docs/setup.md index c4f30b4..af3acf7 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -531,14 +531,24 @@ decision ([#172](https://github.com/Phototonic/openchamber-progress/issues/172)) starting Windows PowerShell synchronously for each check (one to two seconds each) blocked the OpenCode event loop inside the companion for tens of seconds. +**On Windows, Agent Progress no longer checks folder permissions.** It does not +check who owns a folder, who can write to it, or who can replace it or its parents. +A store or custom root in a folder that other accounts can write to (a shared +profile, `ProgramData`, a shared drive) is accepted, and so is state under a +parent that another account can replace. Protection is whatever the folder +already has: with the default profile location that is the user's own profile +permissions. A custom store folder outside the profile simply has the +permissions it already carries. Existing roots that carry a private ACL from an +earlier version keep working and are never modified. Linux and macOS keep their +uid and mode checks. + Windows keeps the checks that need only filesystem calls: drive-qualified path -syntax, canonical path, refusal of symbolic links and junctions in the path chain, -refusal of hard-linked owned state files, content-ownership markers, hashes and -schema validation. Directories are created with default inheritance, and an -existing directory is accepted as it is. A custom store folder outside the -profile simply has whatever permissions it already carries. Existing roots that -carry a private ACL from an earlier version keep working and are never modified. Linux and macOS keep -their uid and mode checks. +syntax, canonical path, refusal of hard-linked owned state files, content-ownership +markers, hashes and schema validation. In the path chain only **symbolic links and +junctions** are refused. Other reparse points, such as volume mount points or +cloud-storage placeholders, are not detected: they are resolved through their real +path. Directories are created with default inheritance, and an existing directory +is accepted as it is. Managed service construction and health do no legacy payload/Store preflight. Every request and every mutation boundary repeats its path and object checks; no @@ -549,8 +559,9 @@ proxy to **20 seconds** per request (`packages/sdk/src/contract.ts:499`, at tag `v2.7.1`). Migration and fresh setup run as separate inspection pages and confirmed steps. The 17-second work and 18-second response deadlines sit below the host limit; the undelayed runner gates each request at eight seconds. The native -suite also exercises pause/reopen/resume and failed workers, and an independent -observer asserts that the service starts no process. Native results remain +suite also exercises pause/reopen/resume, and an independent observer asserts +that the service starts no process. Failed-worker and late-worker cases are +portable-only. Native results remain pending CI; these are acceptance budgets, not a latency guarantee for every machine. diff --git a/openspec/changes/windows-default-permissions/specs/windows-setup-responsiveness/spec.md b/openspec/changes/windows-default-permissions/specs/windows-setup-responsiveness/spec.md index 04f37f0..2d1c24f 100644 --- a/openspec/changes/windows-default-permissions/specs/windows-setup-responsiveness/spec.md +++ b/openspec/changes/windows-default-permissions/specs/windows-setup-responsiveness/spec.md @@ -127,14 +127,15 @@ Acceptance SHALL include native Windows released-legacy migration and fresh setu #### Scenario: CI verifies the built candidate - **WHEN** the final built service migrates an isolated released 1.1.1 installation under a non-admin Windows test principal -- **THEN** inspect, step, failure, retry and status paths start no process and meet the time bound with retained identities/history and honest capture state +- **THEN** inspect, step, retry and status paths start no process and meet the time bound with retained identities/history and honest capture state - **AND** traces contain only bounded stage/code/timing/count/state facts, never account names, paths, credentials or raw logs #### Scenario: CI verifies empty-store setup - **WHEN** the built candidate starts with only isolated config/data roots and no legacy, managed directory, store or journal - **THEN** fresh journeys complete within the request bound with no process started - **AND** health starts no process and responds within the existing 1.25-second native health bound -- **AND** representative restart, dropped-reply, pause/resume, retained reconnection and over-budget cases assert actual durable effects +- **AND** representative restart, dropped-reply, pause/resume and retained reconnection cases assert actual durable effects +- **AND** over-budget, late-worker and injected-fault cases are covered by portable fixtures only, not by native CI #### Scenario: Rendered fresh Setup - **WHEN** current-source guests run the fresh journey in the existing rendered browser harness diff --git a/setup/managed-step-engine.ts b/setup/managed-step-engine.ts index 9190c51..310b58f 100644 --- a/setup/managed-step-engine.ts +++ b/setup/managed-step-engine.ts @@ -1,7 +1,7 @@ import path from 'node:path'; import {SetupError,type Payload} from './lifecycle.ts'; import {managedSourceRoots,createManagedBindingDirectory} from '../shared/managed-binding.ts'; -import {windows,windowsPaths,requirePlatformWriteBoundary,requirePlatformStoreFence,type PlatformRequestBudget} from '../shared/platform.ts'; +import {windows,windowsPaths,STEP_HEADROOM_MS,requirePlatformWriteBoundary,requirePlatformStoreFence,type PlatformRequestBudget} from '../shared/platform.ts'; import {managedJournalProgress,managedFreshJournalProgress,managedRequestDigest,parseManagedStepJournal,parseManagedFreshStepJournal,sameManagedStep,type ManagedStepJournal,type ManagedFreshStepJournal,type ManagedSetupStepJournal,type ManagedCaptureRenewal,type ManagedFreshCaptureRenewal,type ManagedFreshStepIntent} from './managed-step-journal.ts'; import {readManagedStepJournal,readManagedFreshStepJournal,writeManagedStepJournal,upgradeManagedStepJournal,publishManagedStepIntent,managedJournalPaths} from './managed-migration.ts'; import {validateManagedInspectionReview,validateManagedFreshInspectionReview,type ManagedInspectionSession,type ManagedFreshInspectionSession} from './managed-inspection.ts'; @@ -70,15 +70,15 @@ export function beginManagedStep(env:NodeJS.ProcessEnv,payload:Payload,request:E parseJournal(next,request.version); const validate=()=>{validateReview(env,payload,session);}; if('prior' in reviewed&&reviewed.prior){ - // No directory, capture or removal effect here; refuse past the deadline. - budget.require(); + // No directory, capture or removal effect here; refuse near the deadline. + budget.require(STEP_HEADROOM_MS); upgradeManagedStepJournal(env,next as ManagedStepJournal,reviewed.prior,validate); }else{ - budget.require(); + budget.require(STEP_HEADROOM_MS); createManagedBindingDirectory(env); // A slow disk may leave a valid marker and a missing journal. Refuse before // publication; fresh explicit review can recover that state. - budget.require(); + budget.require(STEP_HEADROOM_MS); writeManagedStepJournal(env,next,undefined,validate); } return {disposition:'applied',progress:managedSetupJournalProgress(next),journal:next}; @@ -174,7 +174,7 @@ function advance(env:NodeJS.ProcessEnv,payload:Payload,request:Extract{validateManagedStepTarget(env,payload,prior);});} catch(error){ diff --git a/shared/platform.ts b/shared/platform.ts index 21c8e26..18dadcd 100644 --- a/shared/platform.ts +++ b/shared/platform.ts @@ -35,6 +35,10 @@ export function writerTargetPort(target:string):number { while(writerPortDenylist.has(25000+offset))offset=(offset+1)%4000; return 25000+offset; } +/** Time kept in reserve before an effect that must be checkpointed, such as an + * exclusive creation or an intent publication: past this point the request would + * rather refuse (target still absent, safely retryable) than strand an object. */ +export const STEP_HEADROOM_MS = 2_500; /** A worker-local request boundary: the work deadline and the writer fence. It * starts no process. Monotonic nanoseconds use the same clock in service and * worker threads. */ @@ -51,9 +55,10 @@ export class PlatformRequestBudget { this.writerFence=writerFence; } get elapsedMs(){return Math.max(0,Number(process.hrtime.bigint()-this.startedAt)/1_000_000);} - /** Refuse to admit further effects once the work deadline has passed. */ - require() { - if(Number(this.deadline-process.hrtime.bigint())/1_000_000<=0) + /** Refuse to admit further effects once less than `headroomMs` of the work + * deadline is left (0: once it has passed). */ + require(headroomMs=0) { + if(Number(this.deadline-process.hrtime.bigint())/1_000_000<=headroomMs) throw new PlatformError('managed-step-deadline'); } } @@ -84,8 +89,8 @@ export function withPlatformRequestBudget(budget:PlatformRequestBudget,run:() }finally{requestBudget=undefined;} } /** A mutation owner checks the request deadline before each effect. */ -export function requirePlatformWriteBoundary():void { - requestBudget?.require(); +export function requirePlatformWriteBoundary(headroomMs=0):void { + requestBudget?.require(headroomMs); } /** A pre-dispatch metadata read may route locks, but never grant authority. The * fresh owner must bind its actual Store to an acquired slot before any effect. */ @@ -162,9 +167,11 @@ export function privateDirectory(file: string, recursive=false, creation?:{exclu const target=windows?windowsPath(file,true):file,parent=path.dirname(target); if(!path.isAbsolute(target)||path.resolve(target)!==target||!lstatSync(parent).isDirectory()|| (!windows&&realpathSync(parent)!==parent)||lstatSync(target,{throwIfNoEntry:false}))throw new PlatformError('path-unverified'); - requirePlatformWriteBoundary(); - // Exclusive: mkdir fails if the target appeared since validation. - if(windows)mkdirSync(target);else mkdirSync(target,{mode:0o700}); + requirePlatformWriteBoundary(STEP_HEADROOM_MS); + // Exclusive: mkdir fails if the target appeared since validation. On Windows + // that is a path refusal, not a raw filesystem error. + try{if(windows)mkdirSync(target);else mkdirSync(target,{mode:0o700});} + catch(error){if(windows&&(error as NodeJS.ErrnoException).code==='EEXIST')throw new PlatformError('path-unverified');throw error;} syncDirectory(path.dirname(target)); return; } @@ -172,7 +179,10 @@ export function privateDirectory(file: string, recursive=false, creation?:{exclu const target=windowsPath(file,true); let missing=0; for(let parent=target;!existsSync(parent);parent=path.dirname(parent))missing++; if(!recursive&&missing>1)throw new PlatformError('path-unverified'); - if(missing)mkdirSync(target,{recursive}); + if(missing){ + try{mkdirSync(target,{recursive});} + catch(error){if(['EEXIST','ENOTDIR'].includes((error as NodeJS.ErrnoException).code??''))throw new PlatformError('path-unverified');throw error;} + } else if(!lstatSync(target).isDirectory())throw new PlatformError('path-unverified'); } export function syncFile(file:string) {const fd=openSync(file,windows?'r+':'r');try{fsyncSync(fd);}finally{closeSync(fd);}} diff --git a/shared/store.ts b/shared/store.ts index 45a8289..9a9acc6 100644 --- a/shared/store.ts +++ b/shared/store.ts @@ -17,7 +17,7 @@ import { resumeSelection, type ResumeRequest } from './progress-resume.ts'; import type { SearchOptions, SearchKey } from './progress.ts'; import { DIGEST_LIMITS, aggregatePair, capDigest, emptyEvents, endpointCounts, validateDigestSnapshot, type ChangeDigest, type DigestReason, type DigestSnapshot } from './change-digest.ts'; import { windows, windowsPath, windowsPaths, privatePaths, requirePlatformWriteBoundary, - requirePlatformStoreFence, syncDirectory, PlatformError, sameWindowsDirectory, sameWindowsObject } from './platform.ts'; + requirePlatformStoreFence, STEP_HEADROOM_MS, syncDirectory, PlatformError, sameWindowsDirectory, sameWindowsObject } from './platform.ts'; import { VERSION, LIMITS, ProgressError, requireProgress as need, validRequest, parseRequest, countItems, validBlockerAnnotation, validBlockerInput, type BlockerInput, type BlockerItemInput, type Actor, type Source, type Capture, type PlanState, type PlanSummary, type Receipt, type Item, type Envelope, type PlanRead, type DocumentRead, type Contribution } from './progress.ts'; import { canonical } from './canonical.ts'; @@ -116,7 +116,7 @@ export class Store { need(![file,...sidecars].some(p=>lstatSync(p,{throwIfNoEntry:false})),'binding'); return storeObject(stat); })(); - requirePlatformWriteBoundary(); + requirePlatformWriteBoundary(STEP_HEADROOM_MS); const fd=openSync(file,'wx',0o600); try{ const reserved=storeObject(fstatSync(fd,{bigint:true})); diff --git a/tests/backend/managed-fresh-store.test.ts b/tests/backend/managed-fresh-store.test.ts index 3bc5a21..e52861f 100644 --- a/tests/backend/managed-fresh-store.test.ts +++ b/tests/backend/managed-fresh-store.test.ts @@ -93,3 +93,19 @@ test('creation refuses once the request deadline has passed, before any exclusiv }finally{clock.mock.restore();} }finally{f.close();} }); +test('a slow final preflight inside the headroom refuses while the target is still absent',t=>{ + const f=fixture();try{ + let now=process.hrtime.bigint();const started=now; + const clock=t.mock.method(process.hrtime,'bigint',()=>now); + try{ + // Validation consumes the time until only one second of the work deadline is left. + const slow=()=>{now=started+16_000_000_000n;}; + const dir=path.join(f.root,'store'); + assert.throws(()=>withPlatformRequestBudget(new PlatformRequestBudget(started),()=>privateDirectory(dir,false,{exclusive:true,validate:slow})),{code:'managed-step-deadline'}); + assert.equal(fs.existsSync(dir),false,'no directory is stranded without its checkpoint'); + now=started; + assert.throws(()=>withPlatformRequestBudget(new PlatformRequestBudget(started),()=>Store.createFresh(f.file,{storeId:'slow-store',validate:slow})),{code:'managed-step-deadline'}); + assert.equal(fs.existsSync(f.file),false,'no empty database file is stranded'); + }finally{clock.mock.restore();} + }finally{f.close();} +}); diff --git a/tests/backend/managed-step-engine.test.ts b/tests/backend/managed-step-engine.test.ts index 2fee91a..9f0dcc4 100644 --- a/tests/backend/managed-step-engine.test.ts +++ b/tests/backend/managed-step-engine.test.ts @@ -497,6 +497,16 @@ test('advance refuses an exhausted deadline before intent and any effect',()=>{ assert.deepEqual(fs.readFileSync(migrationFile(f.env)),before);assert.equal(fs.existsSync(managedExpectationFile(f.journal())),false); }finally{f.cleanup();} }); +test('advance refuses inside the headroom before intent and any effect',()=>{ + const f=fixture();try{ + // A budget with only one second left, used directly: the engine's own check before the + // intent is published refuses, ahead of any intent or effect. + const budget=new PlatformRequestBudget(process.hrtime.bigint()-16_000_000_000n),before=fs.readFileSync(migrationFile(f.env)); + const reply=advanceManagedStep(f.env,payload,f.request(),budget,f.journal()); + assert.equal(reply.disposition,'refused');assert.equal(reply.error!.code,'managed-step-deadline'); + assert.deepEqual(fs.readFileSync(migrationFile(f.env)),before);assert.equal(fs.existsSync(managedExpectationFile(f.journal())),false); + }finally{f.cleanup();} +}); test('failed settlement surfaces a journal conflict instead of swallowing it as the effect error',t=>{ const f=fixture();try{ diff --git a/tests/backend/platform-budget.test.ts b/tests/backend/platform-budget.test.ts new file mode 100644 index 0000000..75701f9 --- /dev/null +++ b/tests/backend/platform-budget.test.ts @@ -0,0 +1,53 @@ +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import {syncBuiltinESMExports} from 'node:module'; +import {pathToFileURL} from 'node:url'; +import {PlatformRequestBudget,withPlatformRequestBudget} from '../../shared/platform.ts'; + +test('a request budget is synchronous-only: a Promise or custom thenable is refused and the budget is released',()=>{ + for(const value of [Promise.resolve(1),{then(){}},Object.assign(()=>{},{then(){}})]) + assert.throws(()=>withPlatformRequestBudget(new PlatformRequestBudget(),()=>value),{code:'managed-step-conflict'}); + assert.equal(withPlatformRequestBudget(new PlatformRequestBudget(),()=>42),42,'a refusal releases the local budget'); +}); + +test('a nested request budget is refused, and a failure releases the outer one',()=>{ + assert.throws(()=>withPlatformRequestBudget(new PlatformRequestBudget(),()=>withPlatformRequestBudget(new PlatformRequestBudget(),()=>1)),{code:'managed-step-conflict'}); + assert.throws(()=>withPlatformRequestBudget(new PlatformRequestBudget(),()=>{throw new Error('synthetic');}),/synthetic/); + assert.equal(withPlatformRequestBudget(new PlatformRequestBudget(),()=>'ok'),'ok'); +}); + +test('a budget past its deadline, or inside the requested headroom, refuses',()=>{ + const started=process.hrtime.bigint()-16_000_000_000n; + assert.doesNotThrow(()=>new PlatformRequestBudget(started).require()); + assert.throws(()=>new PlatformRequestBudget(started).require(2_500),{code:'managed-step-deadline'}); + assert.throws(()=>new PlatformRequestBudget(started-2_000_000_000n).require(),{code:'managed-step-deadline'}); + assert.equal(new PlatformRequestBudget().securitySpawns,0); +}); + +/** The platform flag and the drive-letter syntax are the only substitutions. */ +test('Windows exclusive directory creation maps a lost creation race to a path refusal',{skip:process.platform==='win32'},async t=>{ + const root=fs.mkdtempSync('/tmp/opencode/platform-race-'); + try{ + const source=path.join(root,'source'); + fs.cpSync(path.resolve('shared'),path.join(source,'shared'),{recursive:true}); + const file=path.join(source,'shared/platform.ts'); + let text=fs.readFileSync(file,'utf8'); + text=text.replace("export const windows = process.platform === 'win32';",'export const windows = true;'); + const start=text.indexOf(" if (value.includes('\\0')",text.indexOf('function windowsPathsInner(')); + const end=text.indexOf(' let current = clean;',start); + assert.ok(start>0&&end>start); + text=text.slice(0,start)+" if (!path.isAbsolute(value) || path.resolve(value) !== value) throw new PlatformError('path-unverified');\n const clean = value;\n"+text.slice(end); + fs.writeFileSync(file,text); + const platform=await import(pathToFileURL(file).href) as typeof import('../../shared/platform.ts'); + const target=path.join(root,'created'); + // Another writer wins the race between validation and creation. + const real=fs.mkdirSync; + const mock=t.mock.method(fs,'mkdirSync',((dir:any,...rest:any[])=>{if(String(dir)===target)(real as any)(dir);return (real as any)(dir,...rest);}) as typeof fs.mkdirSync); + syncBuiltinESMExports(); + try{assert.throws(()=>platform.privateDirectory(target,false,{exclusive:true,validate(){}}),{code:'path-unverified'});} + finally{mock.mock.restore();syncBuiltinESMExports();} + assert.equal(fs.existsSync(target),true,'the winner\'s directory is left untouched'); + }finally{fs.rmSync(root,{recursive:true,force:true});} +}); diff --git a/tests/browser/model.test.ts b/tests/browser/model.test.ts index b3a69da..f9665ea 100644 --- a/tests/browser/model.test.ts +++ b/tests/browser/model.test.ts @@ -354,7 +354,13 @@ test('setup paths: POSIX and drive-qualified Windows folders reach service inspe }); assert.deepEqual(state.form, { ...targets, dataRoot: '' }, 'late Windows hints preserve custom folders and a deliberate clear'); assert.doesNotMatch(setupErrorText('store-permissions'), /700/); - assert.match(setupErrorText('windows-security-unavailable'), /Windows PowerShell/); + // The Windows permission check no longer exists: an old failure may be stale, so every language says to retry. + for (const [locale, retry] of [['en', /try again/i], ['ru', /повторите/i], ['zh-CN', /重试/]] as const) { + const text = setupErrorText('windows-security-unavailable', locale); + assert.doesNotMatch(text, /PowerShell/, locale); + assert.match(text, retry, locale); + assert.match(text, locale === 'en' ? /stale/i : locale === 'ru' ? /устарев/i : /过时/, locale); + } assert.doesNotMatch(setupErrorText('private-permissions'), /private-permissions/); }); diff --git a/ui/shared/setup.ts b/ui/shared/setup.ts index 30ff8d9..63826cd 100644 --- a/ui/shared/setup.ts +++ b/ui/shared/setup.ts @@ -47,7 +47,7 @@ const ERROR_TEXT = { 'modified-owned-files': 'Installed companion files were changed outside setup. They were left untouched.', 'store-permissions': 'The progress store folder must be owned by you and private to your account.', 'private-permissions': 'Check that the progress folder belongs to your account and is private, then review again. Setup will not change existing permissions.', - 'windows-security-unavailable': 'Windows could not check folder ownership and privacy using its built-in PowerShell. Check that Windows PowerShell is available, then try again.', + 'windows-security-unavailable': 'An earlier version could not check folder permissions on Windows. That failure may be stale: try again. This version no longer runs that check.', 'not-installed': 'The companion is not installed in these folders.', 'ownership-invalid': 'The installation does not match the folders this extension is set up for. Nothing was changed.', 'payload-invalid': 'The companion packaged with this extension is incomplete. Reinstall the extension.', @@ -100,7 +100,7 @@ const ERROR_RU: typeof ERROR_TEXT = { 'modified-owned-files': 'Установленные файлы компаньона изменены вне настройки. Они оставлены нетронутыми.', 'store-permissions': 'Папка хранилища прогресса должна принадлежать вам и быть доступна только вашей учётной записи.', 'private-permissions': 'Проверьте, что папка прогресса принадлежит вашей учётной записи и приватна, затем повторите проверку. Настройка не меняет существующие права.', - 'windows-security-unavailable': 'Windows не удалось проверить владельца и приватность папки встроенным PowerShell. Проверьте доступность Windows PowerShell и повторите попытку.', + 'windows-security-unavailable': 'Прежняя версия не смогла проверить права на папку в Windows. Эта ошибка может быть устаревшей: повторите попытку. Эта версия больше не выполняет такую проверку.', 'not-installed': 'Компаньон не установлен в этих папках.', 'ownership-invalid': 'Установка не соответствует папкам, для которых настроено расширение. Ничего не изменено.', 'payload-invalid': 'Компаньон в комплекте расширения неполон. Переустановите расширение.', @@ -163,7 +163,7 @@ const ERROR_ZH: typeof ERROR_TEXT = { 'modified-owned-files': '已安装的 companion 文件在设置之外被修改,这些文件保持原样。', 'store-permissions': '进度存储文件夹必须归你所有,且仅你的账户可访问。', 'private-permissions': '用于进度的文件夹必须归你所有,且仅你的账户可访问。', - 'windows-security-unavailable': 'Windows 无法使用内置 PowerShell 检查文件夹的所有权和私有性。请确认 Windows PowerShell 可用后重试。', + 'windows-security-unavailable': '较早的版本无法在 Windows 上检查文件夹权限。该失败可能已过时,请重试。当前版本已不再执行该检查。', 'not-installed': '这些文件夹中未安装 companion。', 'ownership-invalid': '安装内容与此扩展所设置的文件夹不匹配,未做任何更改。', 'payload-invalid': '此扩展附带的 companion 不完整,请重新安装扩展。',