@ornexus/neocortex 4.60.72 → 4.60.73
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/release-source.json +1 -1
- package/dist/sbom.cdx.json +24 -24
- package/install.ps1 +1 -1
- package/install.sh +1 -1
- package/package.json +2 -2
- package/packages/client/dist/adapters/adapter-registry.js +108 -1
- package/packages/client/dist/adapters/antigravity-adapter.js +77 -2
- package/packages/client/dist/adapters/claude-code-adapter.js +79 -3
- package/packages/client/dist/adapters/codex-adapter.js +80 -2
- package/packages/client/dist/adapters/cursor-adapter.js +115 -4
- package/packages/client/dist/adapters/gemini-adapter.js +71 -2
- package/packages/client/dist/adapters/grok-adapter.js +42 -2
- package/packages/client/dist/adapters/index.js +22 -1
- package/packages/client/dist/adapters/platform-detector.js +212 -1
- package/packages/client/dist/adapters/target-adapter.js +12 -0
- package/packages/client/dist/adapters/vscode-adapter.js +72 -2
- package/packages/client/dist/agent/refresh-stubs.js +417 -2
- package/packages/client/dist/agent/update-agent-yaml.js +102 -1
- package/packages/client/dist/agent/update-description.js +251 -1
- package/packages/client/dist/cache/crypto-utils.js +78 -1
- package/packages/client/dist/cache/encrypted-cache.js +108 -1
- package/packages/client/dist/cache/in-memory-asset-cache.js +73 -1
- package/packages/client/dist/cache/index.js +13 -1
- package/packages/client/dist/cache/protected-pi-boundary.js +44 -1
- package/packages/client/dist/checkpoint/checkpoint-client-reader.js +127 -2
- package/packages/client/dist/checkpoint/index.js +11 -1
- package/packages/client/dist/checkpoint/shared-checkpoint-types.js +32 -1
- package/packages/client/dist/cli.js +358 -5
- package/packages/client/dist/commands/activate.js +394 -8
- package/packages/client/dist/commands/architecture-answers.js +274 -7
- package/packages/client/dist/commands/architecture-memory-terminal.js +253 -4
- package/packages/client/dist/commands/architecture-non-ui-continuation.js +100 -1
- package/packages/client/dist/commands/architecture-root-binding.js +51 -1
- package/packages/client/dist/commands/cache-status.js +112 -2
- package/packages/client/dist/commands/config.js +88 -1
- package/packages/client/dist/commands/doctor.js +635 -2
- package/packages/client/dist/commands/invoke.js +7200 -143
- package/packages/client/dist/commands/legacy-epic-terminal.js +71 -1
- package/packages/client/dist/commands/legacy-story-branch.js +96 -1
- package/packages/client/dist/commands/legacy-story-pr.js +276 -1
- package/packages/client/dist/commands/mutation-qa-checkpoint.js +285 -5
- package/packages/client/dist/commands/mutation-qa-gate.js +54 -1
- package/packages/client/dist/commands/mutation-qa-git.js +41 -1
- package/packages/client/dist/commands/mutation-qa-policy.js +102 -1
- package/packages/client/dist/commands/mutation-qa-run.js +219 -3
- package/packages/client/dist/commands/mutation-qa-verdict.js +149 -1
- package/packages/client/dist/commands/mutation-qa.js +220 -1
- package/packages/client/dist/commands/native-agent.js +136 -2
- package/packages/client/dist/commands/planning-diagnosis.js +43 -1
- package/packages/client/dist/commands/planning-generation.js +53 -1
- package/packages/client/dist/commands/planning-memory.js +40 -1
- package/packages/client/dist/commands/planning-research.js +42 -1
- package/packages/client/dist/commands/private-session.js +75 -1
- package/packages/client/dist/commands/property-qa.js +139 -1
- package/packages/client/dist/commands/qa-control.js +16 -1
- package/packages/client/dist/commands/qa-scan-browser-launch.js +55 -1
- package/packages/client/dist/commands/qa-scan-browser-route.js +28 -1
- package/packages/client/dist/commands/qa-scan-capture.js +663 -5
- package/packages/client/dist/commands/qa-scan-discovery.js +376 -3
- package/packages/client/dist/commands/qa-scan-review.js +826 -5
- package/packages/client/dist/commands/qa-synthetic-backend-capture.js +266 -1
- package/packages/client/dist/commands/qa-synthetic-backend-review.js +297 -1
- package/packages/client/dist/commands/qa-synthetic-backend.js +340 -2
- package/packages/client/dist/commands/qa-synthetic-broker-port.js +85 -1
- package/packages/client/dist/commands/qa-synthetic-browser.js +39 -1
- package/packages/client/dist/commands/refactor-characterization.js +671 -21
- package/packages/client/dist/commands/refactor-commit.js +399 -13
- package/packages/client/dist/commands/refactor-control.js +142 -3
- package/packages/client/dist/commands/refactor-cpp-assertions.js +93 -3
- package/packages/client/dist/commands/refactor-review.js +283 -5
- package/packages/client/dist/commands/refactor-root.js +588 -7
- package/packages/client/dist/commands/refresh-memory.js +156 -3
- package/packages/client/dist/commands/shared-architecture-non-ui.js +24 -1
- package/packages/client/dist/commands/story-checkpoint.js +171 -1
- package/packages/client/dist/config/profile-directory.js +13 -1
- package/packages/client/dist/config/resolver-selection.js +278 -1
- package/packages/client/dist/config/secure-config.js +281 -12
- package/packages/client/dist/config.js +223 -2
- package/packages/client/dist/constants.js +25 -1
- package/packages/client/dist/context/context-collector.js +222 -2
- package/packages/client/dist/context/context-sanitizer.js +145 -1
- package/packages/client/dist/continuity/autonomous-governance.js +285 -1
- package/packages/client/dist/continuity/continuity-client-state-store.js +1587 -1
- package/packages/client/dist/continuity/invoke-hooks.js +129 -1
- package/packages/client/dist/continuity/migrations/001-initial-schema.js +12 -2
- package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +12 -2
- package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +12 -2
- package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +12 -2
- package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +12 -2
- package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +10 -2
- package/packages/client/dist/continuity/native-agent-store.js +69 -1
- package/packages/client/dist/continuity/native-agent-types.js +90 -1
- package/packages/client/dist/continuity/outbox.js +117 -1
- package/packages/client/dist/continuity/runner-bootstrap-policy.js +172 -1
- package/packages/client/dist/continuity/sqlite-store.d.ts +22 -1
- package/packages/client/dist/continuity/sqlite-store.js +2612 -81
- package/packages/client/dist/effects/invoke-effect-gateways.js +62 -1
- package/packages/client/dist/errors/error-messages.js +228 -2
- package/packages/client/dist/errors/frontmatter-diagnostics.js +125 -1
- package/packages/client/dist/evidence/collector.js +347 -1
- package/packages/client/dist/evidence/index.js +1 -1
- package/packages/client/dist/evidence/types.js +2 -0
- package/packages/client/dist/fs/atomic-state-replace.js +152 -1
- package/packages/client/dist/generated/command-registry.generated.js +4076 -1
- package/packages/client/dist/generated/public-projections.generated.js +149 -1
- package/packages/client/dist/git/direct-yolo-c01-retry.js +138 -4
- package/packages/client/dist/git/direct-yolo-checkpoint.js +1234 -4
- package/packages/client/dist/git/epic-operational-state.d.ts +198 -0
- package/packages/client/dist/git/epic-operational-state.js +672 -0
- package/packages/client/dist/git/git-lifecycle-step-ids.js +14 -1
- package/packages/client/dist/git/git-lifecycle-store.d.ts +9 -1
- package/packages/client/dist/git/git-lifecycle-store.js +1981 -9
- package/packages/client/dist/git/legacy-story-branch-checkpoint.js +259 -9
- package/packages/client/dist/git/legacy-story-branch-setup.js +348 -4
- package/packages/client/dist/git/legacy-story-pr.js +3538 -70
- package/packages/client/dist/git/secure-filesystem-boundary.js +182 -5
- package/packages/client/dist/graph-retrieval/pre-command-hook.js +284 -1
- package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +237 -1
- package/packages/client/dist/i18n/first-run.js +60 -2
- package/packages/client/dist/index.js +47 -1
- package/packages/client/dist/invocation/invoke-input.js +24 -1
- package/packages/client/dist/license/index.js +5 -1
- package/packages/client/dist/license/license-client.js +304 -1
- package/packages/client/dist/machine/fingerprint.js +163 -2
- package/packages/client/dist/machine/index.js +5 -1
- package/packages/client/dist/memory/project-memory-path-scope.js +62 -1
- package/packages/client/dist/memory/project-memory-writer.js +1007 -40
- package/packages/client/dist/memory/shared-project-memory-types.js +253 -2
- package/packages/client/dist/migrations/epic-lifecycle-backfill.d.ts +97 -0
- package/packages/client/dist/migrations/epic-lifecycle-backfill.js +1060 -0
- package/packages/client/dist/migrations/project-identity-capability.js +50 -1
- package/packages/client/dist/migrations/project-identity.js +493 -7
- package/packages/client/dist/migrations/state-json.d.ts +22 -0
- package/packages/client/dist/migrations/state-json.js +393 -4
- package/packages/client/dist/policy/architecture-policy.js +184 -2
- package/packages/client/dist/policy/index.js +7 -1
- package/packages/client/dist/policy/shared-policy-types.js +38 -0
- package/packages/client/dist/policy/subagent-approval-policy.js +55 -1
- package/packages/client/dist/private-execution/clean-baseline.js +279 -2
- package/packages/client/dist/private-execution/codex-executor.js +574 -4
- package/packages/client/dist/private-execution/codex-host-runtime.js +137 -1
- package/packages/client/dist/private-execution/codex-lifecycle-guard.js +97 -1
- package/packages/client/dist/private-execution/codex-scoped-permissions.js +128 -1
- package/packages/client/dist/private-execution/delivery.js +410 -13
- package/packages/client/dist/private-execution/diagnosis-root-review.js +294 -2
- package/packages/client/dist/private-execution/frozen-handoff.js +19 -6
- package/packages/client/dist/private-execution/implementation-validation.js +106 -2
- package/packages/client/dist/private-execution/isolated-admission.js +1432 -23
- package/packages/client/dist/private-execution/isolated-session.js +725 -5
- package/packages/client/dist/private-execution/isolated-workspace.js +122 -1
- package/packages/client/dist/private-execution/pact-consumer-runtime.js +409 -3
- package/packages/client/dist/private-execution/pact-test-source.js +258 -1
- package/packages/client/dist/private-execution/pact-toolchain.js +290 -3
- package/packages/client/dist/private-execution/pact-write-set.js +172 -1
- package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +406 -5
- package/packages/client/dist/private-execution/planning-generation-checkpoint.js +462 -5
- package/packages/client/dist/private-execution/planning-memory-checkpoint.js +139 -3
- package/packages/client/dist/private-execution/planning-research-checkpoint.js +325 -4
- package/packages/client/dist/private-execution/private-report-store.js +42 -1
- package/packages/client/dist/private-execution/property-test-candidate.js +103 -1
- package/packages/client/dist/private-execution/property-test-choices.js +147 -3
- package/packages/client/dist/private-execution/property-test-plan.js +271 -7
- package/packages/client/dist/private-execution/property-test-review.js +258 -4
- package/packages/client/dist/private-execution/property-test-runtime.js +372 -9
- package/packages/client/dist/private-execution/property-test-source.js +139 -1
- package/packages/client/dist/private-execution/root-checkpoint.js +80 -1
- package/packages/client/dist/private-execution/root-memory-git-evidence.js +135 -3
- package/packages/client/dist/private-execution/root-memory-recovery.js +93 -1
- package/packages/client/dist/private-execution/root-memory-request.js +29 -1
- package/packages/client/dist/private-execution/root-memory-scope.js +178 -1
- package/packages/client/dist/private-execution/root-memory-writer.js +102 -1
- package/packages/client/dist/private-execution/session-lease.js +63 -1
- package/packages/client/dist/private-execution/shared-private-admission-types.js +50 -1
- package/packages/client/dist/private-execution/shared-project-validation.js +66 -1
- package/packages/client/dist/private-execution/shared-root-memory-types.js +61 -1
- package/packages/client/dist/private-execution/ux-source-validation.js +372 -1
- package/packages/client/dist/private-execution/ux-write-set.js +191 -2
- package/packages/client/dist/registry/registry-reconciliation.js +234 -1
- package/packages/client/dist/resilience/circuit-breaker.js +170 -1
- package/packages/client/dist/resilience/degradation-manager.js +164 -1
- package/packages/client/dist/resilience/freshness-indicator.js +100 -1
- package/packages/client/dist/resilience/index.js +8 -1
- package/packages/client/dist/resilience/recovery-detector.js +74 -1
- package/packages/client/dist/resolvers/asset-resolver.js +13 -0
- package/packages/client/dist/resolvers/local-resolver.js +255 -8
- package/packages/client/dist/resolvers/remote-resolver.js +233 -1
- package/packages/client/dist/runner/binary.js +404 -1
- package/packages/client/dist/runner/cli.js +1571 -17
- package/packages/client/dist/runner/headless/adapters.js +49 -1
- package/packages/client/dist/runner/headless/claude-code-adapter.js +79 -1
- package/packages/client/dist/runner/headless/continuous-story-workspace.js +1628 -11
- package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +69 -1
- package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +110 -2
- package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +1236 -8
- package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +318 -2
- package/packages/client/dist/runner/headless/fake-adapter.js +62 -1
- package/packages/client/dist/runner/headless/managed-profile.js +132 -1
- package/packages/client/dist/runner/headless/opencode-adapter.js +145 -2
- package/packages/client/dist/runner/headless/prepared-story-bundle.js +43 -1
- package/packages/client/dist/runner/headless/resolver.js +231 -1
- package/packages/client/dist/runner/headless/run-yolo.js +885 -1
- package/packages/client/dist/runner/headless/run-yoloop.js +2574 -2
- package/packages/client/dist/runner/headless/types.js +574 -2
- package/packages/client/dist/runner/local-console.js +396 -13
- package/packages/client/dist/runner/portal-sync-worker.js +1487 -1
- package/packages/client/dist/runner/project-identity.js +106 -1
- package/packages/client/dist/runner/scheduler.js +995 -7
- package/packages/client/dist/runner-cli.js +18 -2
- package/packages/client/dist/state/invocation-shape.js +13 -1
- package/packages/client/dist/state/project-state-snapshot.d.ts +8 -0
- package/packages/client/dist/state/project-state-snapshot.js +1731 -1
- package/packages/client/dist/state/state-json-repair.js +785 -3
- package/packages/client/dist/state/structural-dag-projection.js +118 -1
- package/packages/client/dist/telemetry/index.js +5 -1
- package/packages/client/dist/telemetry/offline-queue.js +131 -1
- package/packages/client/dist/tier/index.js +5 -1
- package/packages/client/dist/tier/tier-aware-client.js +405 -1
- package/packages/client/dist/types/index.js +38 -1
- package/packages/client/dist/version.js +27 -1
- package/packages/client/dist/yolo/change-evidence-collector.js +126 -1
- package/packages/client/dist/yolo/invoke-envelope-capability.js +62 -1
- package/packages/client/dist/yolo/spec-envelope-collector.js +184 -5
- package/packages/client/dist/yoloop/discovery-hook.js +300 -2
- package/packages/client/dist/yoloop/index.js +8 -1
- package/packages/client/dist/yoloop/invoke-hooks.js +669 -12
- package/packages/client/dist/yoloop/shared-discover-epics.js +1007 -1
- package/packages/client/dist/yoloop/shared-yoloop-types.d.ts +65 -1
- package/packages/client/dist/yoloop/shared-yoloop-types.js +33 -1
- package/packages/client/dist/yoloop/target-normalization.js +180 -1
- package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +8 -0
- package/packages/client/dist/yoloop/yoloop-client-state-store.js +1920 -1
- package/packages/shared/dist/yolo/spec-envelope.js +3 -6
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/skill/SKILL.md +1 -1
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +2 -2
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +2 -2
- package/targets-stubs/codex/AGENTS.md +1 -1
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/opencode/neocortex-root.md +1 -1
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -1,5 +1,826 @@
|
|
|
1
|
-
import{createHash as he,randomUUID as Y}from"node:crypto";import{closeSync as $,constants as X,existsSync as D,fstatSync as Z,fsyncSync as J,linkSync as ee,lstatSync as k,mkdirSync as re,openSync as z,readFileSync as j,realpathSync as B,unlinkSync as te,writeFileSync as ne}from"node:fs";import{isAbsolute as ve,join as b,resolve as E}from"node:path";import{inflateSync as pe}from"node:zlib";import{mutationQaGit as Q}from"./mutation-qa-git.js";const F=/^[a-f0-9]{64}$/,we=/^[a-z][a-z0-9-]{0,63}$/,ge=/^[a-z][a-z0-9-]{0,63}\.(?:png|json)$/,oe=8*1024*1024,T=128*1024,V=2,se=Buffer.from([137,80,78,71,13,10,26,10]),ye=Uint32Array.from({length:256},(r,t)=>{let e=t;for(let n=0;n<8;n++)e=(e&1)!==0?3988292384^e>>>1:e>>>1;return e>>>0}),M=["visual","responsive","responsive-tablet","responsive-desktop","accessibility","interaction","console-network","performance"],Se=Object.freeze({visual:"browser-screenshot",responsive:"browser-screenshot","responsive-tablet":"browser-screenshot","responsive-desktop":"browser-screenshot",accessibility:"axe-scan",interaction:"browser-interaction","console-network":"console-capture",performance:"performance-trace"}),me=Object.freeze({visual:"PNG 8-bit non-interlaced CRC+IDAT verified; width=1440, 600<=height<=4096, pixels<=8000000",responsive:"PNG 8-bit non-interlaced CRC+IDAT verified; width=375, 600<=height<=4096","responsive-tablet":"PNG 8-bit non-interlaced CRC+IDAT verified; width=768, 600<=height<=4096","responsive-desktop":"PNG 8-bit non-interlaced CRC+IDAT verified; width=1024, 600<=height<=4096",accessibility:"JSON: schemaVersion=1 engine=axe-core violationCount=0 incompleteCount=0 passCount>0",interaction:"JSON: schemaVersion=2 syntheticTarget=true networkAttemptsAfterAction=0 checks=[{id:functional-safe-slug,passed:true}] (1..32 distinct)","console-network":"JSON: schemaVersion=1 initialCapture=true consoleErrors=0 pageErrors=0 failedRequests=0 requestsObserved>0",performance:"JSON: schemaVersion=1 metric=load 0<=observedMs<=budgetMs<=30000"});function _(r,t=1e6){return Number.isSafeInteger(r)&&r>=0&&r<=t}function qe(r,t,e){let n=4294967295;for(let o=t;o<e;o++)n=ye[(n^r[o])&255]^n>>>8;return(n^4294967295)>>>0}function Ee(r,t){if(r.length<57||!r.subarray(0,8).equals(se))return!1;let e=8,n=0,o=0,s=0,c=0,d=!1,a=!1,g=!1,f=!1,l=0;const p=[];for(;e<r.length;){if(++l>1024||r.length-e<12)return!1;const w=r.readUInt32BE(e),S=e+8+w,x=S+4;if(w>oe||x>r.length)return!1;const A=r.toString("ascii",e+4,e+8);if(!/^[A-Za-z]{4}$/.test(A)||qe(r,e+4,S)!==r.readUInt32BE(S))return!1;if(A==="IHDR"){if(d||e!==8||w!==13||(d=!0,n=r.readUInt32BE(e+8),o=r.readUInt32BE(e+12),c=r[e+17],s=c===0?1:c===2?3:c===4?2:c===6?4:0,!s||r[e+16]!==8||r[e+18]!==0||r[e+19]!==0||r[e+20]!==0||n<1||o<1||n>4096||o>4096||n*o>8e6))return!1}else if(A==="IDAT"){if(!d||f||w===0)return!1;p.push(r.subarray(e+8,S))}else if(A==="PLTE"){if(!d||g||p.length>0||c!==2&&c!==6||w===0||w>768||w%3!==0)return!1;g=!0}else if(A==="IEND"){if(!d||p.length===0||w!==0||x!==r.length)return!1;a=!0;break}else{if(!d||A[0]===A[0]?.toUpperCase())return!1;p.length&&(f=!0)}e=x}const y={visual:1440,responsive:375,"responsive-tablet":768,"responsive-desktop":1024}[t];if(!a||n!==y||o<600)return!1;const i=n*s,v=o*(i+1);try{const w=pe(Buffer.concat(p),{maxOutputLength:v+1});if(w.length!==v)return!1;for(let S=0;S<o;S++)if(w[S*(i+1)]>4)return!1;return!0}catch{return!1}}function Ae(r,t){if(r==="visual"||r==="responsive"||r==="responsive-tablet"||r==="responsive-desktop")return Ee(t,r);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{return!1}if(r==="accessibility")return m(e,["schemaVersion","engine","violationCount","incompleteCount","passCount"])&&e.schemaVersion===1&&e.engine==="axe-core"&&e.violationCount===0&&e.incompleteCount===0&&_(e.passCount)&&e.passCount>0;if(r==="interaction"){if(!m(e,["schemaVersion","syntheticTarget","networkAttemptsAfterAction","checks"])||e.schemaVersion!==2||e.syntheticTarget!==!0||e.networkAttemptsAfterAction!==0||!Array.isArray(e.checks)||e.checks.length<1||e.checks.length>32)return!1;const n=new Set;return e.checks.every(o=>!m(o,["id","passed"])||typeof o.id!="string"||!/^functional-[a-z][a-z0-9-]{0,50}$/.test(o.id)||n.has(o.id)||o.passed!==!0?!1:(n.add(o.id),!0))}return r==="console-network"?m(e,["schemaVersion","initialCapture","consoleErrors","pageErrors","failedRequests","requestsObserved"])&&e.schemaVersion===1&&e.initialCapture===!0&&e.consoleErrors===0&&e.pageErrors===0&&e.failedRequests===0&&_(e.requestsObserved)&&e.requestsObserved>0:m(e,["schemaVersion","metric","observedMs","budgetMs"])&&e.schemaVersion===1&&e.metric==="load"&&_(e.observedMs,3e4)&&_(e.budgetMs,3e4)&&e.budgetMs>0&&e.observedMs<=e.budgetMs}function C(r){return he("sha256").update(r).digest("hex")}function m(r,t){return r!==null&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).sort().join("\0")===[...t].sort().join("\0")}function I(r,t){const e=Q(r,["rev-parse","--git-common-dir"]).toString("utf8").trim(),n=ve(e)?E(e):E(r,e);if(B(n)!==n||k(n).isSymbolicLink()||k(n).uid!==process.getuid?.())throw new Error("qa-scan-review-unverified");const o=b(n,"neocortex-qa-scan");t&&re(o,{recursive:!0,mode:448});const s=k(o);if(!s.isDirectory()||s.isSymbolicLink()||s.uid!==process.getuid?.()||(s.mode&63)!==0)throw new Error("qa-scan-review-unverified");return o}function H(r,t){const e=b(I(r,t),"evidence");t&&re(e,{recursive:!0,mode:448});const n=k(e);if(!n.isDirectory()||n.isSymbolicLink()||n.uid!==process.getuid?.()||(n.mode&63)!==0)throw new Error("qa-scan-review-unverified");return e}function Ve(r){return H(E(r),!1)}function L(r){if(B(r)!==r||!k(r).isDirectory()||Q(r,["rev-parse","--show-toplevel"]).toString("utf8").trim()!==r)throw new Error("qa-scan-review-unverified");if(Q(r,["status","--porcelain=v1","-z","--untracked-files=all"]).toString("utf8").split("\0").filter(Boolean).some(n=>!/^.{2} \.neocortex\//.test(n)))throw new Error("qa-scan-review-source-dirty");const e=Q(r,["rev-parse","--verify","HEAD"]).toString("utf8").trim();if(!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(e))throw new Error("qa-scan-review-unverified");return e}function ke(r){let t;try{t=new URL(r)}catch{throw new Error("qa-scan-review-target-invalid")}if(t.protocol!=="http:"||!["127.0.0.1","localhost","[::1]"].includes(t.hostname)||!t.port||t.username||t.password||t.search||t.hash)throw new Error("qa-scan-review-target-invalid");return C(`qa-scan-loopback-target-v1\0${t.href}`)}function P(r,t,e){try{if(!we.test(t))throw new Error("qa-scan-review-surface-invalid");const n=E(r),o=L(n),s=ke(e);H(n,!0);const c={schemaVersion:1,evidenceContractVersion:V,kind:"root-qa-scan-plan",sourceHead:o,surface:t,targetSha256:s,requiredKinds:M,qaAccepted:!1,localOnly:!0};return Object.freeze({...c,planSha256:C(`root-qa-scan-plan-v2\0${JSON.stringify(c)}`)})}catch(n){throw n instanceof Error&&n.message.startsWith("qa-scan-review-")?n:new Error("qa-scan-review-unverified")}}function ie(r,t){const e=new Set,n=[];for(const o of t.observations){if(!m(o,["kind","artifactId","captureMethod","sha256","capturedAt","rationale"])||!M.includes(o.kind)||!ge.test(o.artifactId)||e.has(o.artifactId)||o.captureMethod!==Se[o.kind]||!F.test(o.sha256)||typeof o.rationale!="string"||o.rationale.length<30||o.rationale.length>500||/[\x00-\x1f\x7f]/.test(o.rationale))throw new Error("qa-scan-review-unverified");const s=typeof o.capturedAt=="string"?Date.parse(o.capturedAt):NaN;if(!Number.isFinite(s)||new Date(s).toISOString()!==o.capturedAt||s>Date.now()+5*6e4||Date.now()-s>60*6e4)throw new Error("qa-scan-review-unverified");e.add(o.artifactId);const c=b(H(r,!1),o.artifactId),d=k(c);if(!d.isFile()||d.isSymbolicLink()||d.uid!==process.getuid?.()||(d.mode&63)!==0||d.size<8||d.size>oe||B(c)!==c)throw new Error("qa-scan-review-unverified");const a=z(c,X.O_RDONLY|(X.O_NOFOLLOW??0));let g;try{const f=Z(a);if(!f.isFile()||f.dev!==d.dev||f.ino!==d.ino||f.uid!==d.uid||f.size!==d.size)throw new Error("qa-scan-review-unverified");g=j(a);const l=Z(a),p=k(c);if(l.dev!==f.dev||l.ino!==f.ino||l.size!==f.size||l.mtimeMs!==f.mtimeMs||l.ctimeMs!==f.ctimeMs||p.dev!==f.dev||p.ino!==f.ino)throw new Error("qa-scan-review-unverified")}finally{$(a)}if(C(g)!==o.sha256)throw new Error("qa-scan-review-unverified");if(o.artifactId.endsWith(".png")){if(o.captureMethod!=="browser-screenshot"||!g.subarray(0,8).equals(se))throw new Error("qa-scan-review-unverified")}else{if(o.captureMethod==="browser-screenshot")throw new Error("qa-scan-review-unverified");try{const f=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(g));if(!f||typeof f!="object"||Array.isArray(f))throw new Error}catch{throw new Error("qa-scan-review-unverified")}}if(t.verdict==="approved"&&!Ae(o.kind,g))throw new Error("qa-scan-review-unverified");n.push(`${o.kind}:${o.artifactId}:${o.sha256}`)}return C(`root-qa-scan-evidence-v2\0${n.sort().join("\0")}`)}function G(r,t,e,n){try{const o=P(r,t,e);if(!m(n,["schemaVersion","evidenceContractVersion","kind","sourceHead","planSha256","surface","targetSha256","verdict","observations","issues"])||n.schemaVersion!==1||n.evidenceContractVersion!==V||n.kind!=="root-qa-scan-report"||n.sourceHead!==o.sourceHead||n.planSha256!==o.planSha256||n.surface!==o.surface||n.targetSha256!==o.targetSha256||n.verdict!=="approved"&&n.verdict!=="issues-found"||!Array.isArray(n.observations)||n.observations.length!==M.length||!Array.isArray(n.issues)||n.issues.length>128||Buffer.byteLength(JSON.stringify(n))>T)throw new Error("qa-scan-review-unverified");const s=n;if(s.observations.map(a=>a.kind).sort().join("\0")!==[...M].sort().join("\0"))throw new Error("qa-scan-review-unverified");const c=ie(E(r),s),d=new Set(s.observations.map(a=>a.artifactId));for(const a of s.issues)if(!m(a,["severity","evidenceArtifactId","summary"])||!["critical","high","medium","low"].includes(a.severity)||!d.has(a.evidenceArtifactId)||typeof a.summary!="string"||a.summary.length<20||a.summary.length>500||/[\x00-\x1f\x7f]/.test(a.summary))throw new Error("qa-scan-review-unverified");if(s.verdict==="approved"!=(s.issues.length===0))throw new Error("qa-scan-review-unverified");if(L(E(r))!==o.sourceHead||ie(E(r),s)!==c)throw new Error("qa-scan-review-unverified");return Object.freeze({plan:o,report:s,evidenceSha256:c,reviewSha256:C(`root-qa-scan-review-v2\0${JSON.stringify(s)}`)})}catch{throw new Error("qa-scan-review-unverified")}}function ae(r){return Object.freeze({schemaVersion:1,evidenceContractVersion:V,kind:"root-qa-scan-review",sourceHead:r.plan.sourceHead,planSha256:r.plan.planSha256,evidenceSha256:r.evidenceSha256,reviewSha256:r.reviewSha256,evidenceCount:8,issueCount:r.report.issues.length,verdict:r.report.verdict,qaAccepted:r.report.verdict==="approved",checkpointAccepted:!1,workflowContinuationAuthorized:!1,localOnly:!0,publicSafe:!0})}function Ce(r,t,e,n){try{const o=E(r),s=G(o,t,e,n),c=ae(s),d=I(o,!0),a=b(d,`review-${c.planSha256}.json`),g={report:s.report,receipt:c},f={schemaVersion:1,kind:"root-qa-scan-review-record",...g,checksumSha256:C(`root-qa-scan-review-record-v1\0${JSON.stringify(g)}`)},l=`${JSON.stringify(f)}
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
/** Root-owned, local-only QA scan review bound to physical browser evidence. */
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { closeSync, constants, existsSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { isAbsolute, join, resolve } from 'node:path';
|
|
5
|
+
import { inflateSync } from 'node:zlib';
|
|
6
|
+
import { mutationQaGit } from './mutation-qa-git.js';
|
|
7
|
+
const SHA256 = /^[a-f0-9]{64}$/;
|
|
8
|
+
const SURFACE = /^[a-z][a-z0-9-]{0,63}$/;
|
|
9
|
+
const ARTIFACT = /^[a-z][a-z0-9-]{0,63}\.(?:png|json)$/;
|
|
10
|
+
const MAX_ARTIFACT_BYTES = 8 * 1024 * 1024;
|
|
11
|
+
const MAX_REPORT_BYTES = 128 * 1024;
|
|
12
|
+
const EVIDENCE_CONTRACT_VERSION = 2;
|
|
13
|
+
const PNG = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
|
|
14
|
+
const PNG_CRC_TABLE = Uint32Array.from({ length: 256 }, (_, index) => {
|
|
15
|
+
let value = index;
|
|
16
|
+
for (let bit = 0; bit < 8; bit++) {
|
|
17
|
+
value = (value & 1) !== 0 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
|
|
18
|
+
}
|
|
19
|
+
return value >>> 0;
|
|
20
|
+
});
|
|
21
|
+
const KINDS = ['visual', 'responsive', 'responsive-tablet', 'responsive-desktop',
|
|
22
|
+
'accessibility', 'interaction', 'console-network', 'performance'];
|
|
23
|
+
const METHODS = Object.freeze({
|
|
24
|
+
visual: 'browser-screenshot', responsive: 'browser-screenshot',
|
|
25
|
+
'responsive-tablet': 'browser-screenshot', 'responsive-desktop': 'browser-screenshot',
|
|
26
|
+
accessibility: 'axe-scan', interaction: 'browser-interaction',
|
|
27
|
+
'console-network': 'console-capture', performance: 'performance-trace',
|
|
28
|
+
});
|
|
29
|
+
const APPROVED_EVIDENCE_CONTRACT = Object.freeze({
|
|
30
|
+
visual: 'PNG 8-bit non-interlaced CRC+IDAT verified; width=1440, 600<=height<=4096, pixels<=8000000',
|
|
31
|
+
responsive: 'PNG 8-bit non-interlaced CRC+IDAT verified; width=375, 600<=height<=4096',
|
|
32
|
+
'responsive-tablet': 'PNG 8-bit non-interlaced CRC+IDAT verified; width=768, 600<=height<=4096',
|
|
33
|
+
'responsive-desktop': 'PNG 8-bit non-interlaced CRC+IDAT verified; width=1024, 600<=height<=4096',
|
|
34
|
+
accessibility: 'JSON: schemaVersion=1 engine=axe-core violationCount=0 incompleteCount=0 passCount>0',
|
|
35
|
+
interaction: 'JSON: schemaVersion=2 syntheticTarget=true networkAttemptsAfterAction=0 checks=[{id:functional-safe-slug,passed:true}] (1..32 distinct)',
|
|
36
|
+
'console-network': 'JSON: schemaVersion=1 initialCapture=true consoleErrors=0 pageErrors=0 failedRequests=0 requestsObserved>0',
|
|
37
|
+
performance: 'JSON: schemaVersion=1 metric=load 0<=observedMs<=budgetMs<=30000',
|
|
38
|
+
});
|
|
39
|
+
function nonnegativeInteger(value, maximum = 1_000_000) {
|
|
40
|
+
return Number.isSafeInteger(value) && value >= 0 && value <= maximum;
|
|
41
|
+
}
|
|
42
|
+
function pngCrc(bytes, start, end) {
|
|
43
|
+
let crc = 0xffffffff;
|
|
44
|
+
for (let index = start; index < end; index++) {
|
|
45
|
+
crc = PNG_CRC_TABLE[(crc ^ bytes[index]) & 0xff] ^ (crc >>> 8);
|
|
46
|
+
}
|
|
47
|
+
return (crc ^ 0xffffffff) >>> 0;
|
|
48
|
+
}
|
|
49
|
+
/** An IHDR-sized prefix is not a screenshot. Check the bounded PNG stream,
|
|
50
|
+
* chunk checksums and decompressed scanlines before an approved QA verdict. */
|
|
51
|
+
export function validateRootQaScanPng(bytes, kind) {
|
|
52
|
+
if (bytes.length < 57 || !bytes.subarray(0, 8).equals(PNG))
|
|
53
|
+
return false;
|
|
54
|
+
let offset = 8;
|
|
55
|
+
let width = 0;
|
|
56
|
+
let height = 0;
|
|
57
|
+
let channels = 0;
|
|
58
|
+
let colorType = 0;
|
|
59
|
+
let seenIhdr = false;
|
|
60
|
+
let seenIend = false;
|
|
61
|
+
let seenPalette = false;
|
|
62
|
+
let closedIdat = false;
|
|
63
|
+
let chunks = 0;
|
|
64
|
+
const idat = [];
|
|
65
|
+
while (offset < bytes.length) {
|
|
66
|
+
if (++chunks > 1024)
|
|
67
|
+
return false;
|
|
68
|
+
if (bytes.length - offset < 12)
|
|
69
|
+
return false;
|
|
70
|
+
const length = bytes.readUInt32BE(offset);
|
|
71
|
+
const dataEnd = offset + 8 + length;
|
|
72
|
+
const next = dataEnd + 4;
|
|
73
|
+
if (length > MAX_ARTIFACT_BYTES || next > bytes.length)
|
|
74
|
+
return false;
|
|
75
|
+
const type = bytes.toString('ascii', offset + 4, offset + 8);
|
|
76
|
+
if (!/^[A-Za-z]{4}$/.test(type)
|
|
77
|
+
|| pngCrc(bytes, offset + 4, dataEnd) !== bytes.readUInt32BE(dataEnd))
|
|
78
|
+
return false;
|
|
79
|
+
if (type === 'IHDR') {
|
|
80
|
+
if (seenIhdr || offset !== 8 || length !== 13)
|
|
81
|
+
return false;
|
|
82
|
+
seenIhdr = true;
|
|
83
|
+
width = bytes.readUInt32BE(offset + 8);
|
|
84
|
+
height = bytes.readUInt32BE(offset + 12);
|
|
85
|
+
colorType = bytes[offset + 17];
|
|
86
|
+
channels = colorType === 0 ? 1 : colorType === 2 ? 3 : colorType === 4 ? 2
|
|
87
|
+
: colorType === 6 ? 4 : 0;
|
|
88
|
+
if (!channels || bytes[offset + 16] !== 8 || bytes[offset + 18] !== 0
|
|
89
|
+
|| bytes[offset + 19] !== 0 || bytes[offset + 20] !== 0
|
|
90
|
+
|| width < 1 || height < 1 || width > 4096 || height > 4096
|
|
91
|
+
|| width * height > 8_000_000)
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
else if (type === 'IDAT') {
|
|
95
|
+
if (!seenIhdr || closedIdat || length === 0)
|
|
96
|
+
return false;
|
|
97
|
+
idat.push(bytes.subarray(offset + 8, dataEnd));
|
|
98
|
+
}
|
|
99
|
+
else if (type === 'PLTE') {
|
|
100
|
+
if (!seenIhdr || seenPalette || idat.length > 0
|
|
101
|
+
|| (colorType !== 2 && colorType !== 6)
|
|
102
|
+
|| length === 0 || length > 768 || length % 3 !== 0)
|
|
103
|
+
return false;
|
|
104
|
+
seenPalette = true;
|
|
105
|
+
}
|
|
106
|
+
else if (type === 'IEND') {
|
|
107
|
+
if (!seenIhdr || idat.length === 0 || length !== 0 || next !== bytes.length)
|
|
108
|
+
return false;
|
|
109
|
+
seenIend = true;
|
|
110
|
+
break;
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
if (!seenIhdr || type[0] === type[0]?.toUpperCase())
|
|
114
|
+
return false;
|
|
115
|
+
if (idat.length)
|
|
116
|
+
closedIdat = true;
|
|
117
|
+
}
|
|
118
|
+
offset = next;
|
|
119
|
+
}
|
|
120
|
+
const requiredWidth = { visual: 1440, responsive: 375,
|
|
121
|
+
'responsive-tablet': 768, 'responsive-desktop': 1024 }[kind];
|
|
122
|
+
if (!seenIend || width !== requiredWidth || height < 600)
|
|
123
|
+
return false;
|
|
124
|
+
const rowBytes = width * channels;
|
|
125
|
+
const expectedBytes = height * (rowBytes + 1);
|
|
126
|
+
try {
|
|
127
|
+
const pixels = inflateSync(Buffer.concat(idat), { maxOutputLength: expectedBytes + 1 });
|
|
128
|
+
if (pixels.length !== expectedBytes)
|
|
129
|
+
return false;
|
|
130
|
+
for (let row = 0; row < height; row++) {
|
|
131
|
+
if (pixels[row * (rowBytes + 1)] > 4)
|
|
132
|
+
return false;
|
|
133
|
+
}
|
|
134
|
+
return true;
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/** A positive root verdict needs closed, complete observation claims, not generic JSON. */
|
|
141
|
+
export function validateRootQaScanArtifact(kind, bytes) {
|
|
142
|
+
if (kind === 'visual' || kind === 'responsive'
|
|
143
|
+
|| kind === 'responsive-tablet' || kind === 'responsive-desktop') {
|
|
144
|
+
return validateRootQaScanPng(bytes, kind);
|
|
145
|
+
}
|
|
146
|
+
let value;
|
|
147
|
+
try {
|
|
148
|
+
value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
if (kind === 'accessibility') {
|
|
154
|
+
return exact(value, ['schemaVersion', 'engine', 'violationCount', 'incompleteCount', 'passCount'])
|
|
155
|
+
&& value.schemaVersion === 1 && value.engine === 'axe-core'
|
|
156
|
+
&& value.violationCount === 0 && value.incompleteCount === 0
|
|
157
|
+
&& nonnegativeInteger(value.passCount) && value.passCount > 0;
|
|
158
|
+
}
|
|
159
|
+
if (kind === 'interaction') {
|
|
160
|
+
if (!exact(value, ['schemaVersion', 'syntheticTarget', 'networkAttemptsAfterAction', 'checks'])
|
|
161
|
+
|| value.schemaVersion !== 2 || value.syntheticTarget !== true
|
|
162
|
+
|| value.networkAttemptsAfterAction !== 0
|
|
163
|
+
|| !Array.isArray(value.checks) || value.checks.length < 1 || value.checks.length > 32)
|
|
164
|
+
return false;
|
|
165
|
+
const ids = new Set();
|
|
166
|
+
return value.checks.every((item) => {
|
|
167
|
+
if (!exact(item, ['id', 'passed']) || typeof item.id !== 'string'
|
|
168
|
+
|| !/^functional-[a-z][a-z0-9-]{0,50}$/.test(item.id)
|
|
169
|
+
|| ids.has(item.id) || item.passed !== true)
|
|
170
|
+
return false;
|
|
171
|
+
ids.add(item.id);
|
|
172
|
+
return true;
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
if (kind === 'console-network') {
|
|
176
|
+
return exact(value, ['schemaVersion', 'initialCapture', 'consoleErrors', 'pageErrors',
|
|
177
|
+
'failedRequests', 'requestsObserved']) && value.schemaVersion === 1
|
|
178
|
+
&& value.initialCapture === true && value.consoleErrors === 0
|
|
179
|
+
&& value.pageErrors === 0 && value.failedRequests === 0
|
|
180
|
+
&& nonnegativeInteger(value.requestsObserved) && value.requestsObserved > 0;
|
|
181
|
+
}
|
|
182
|
+
return exact(value, ['schemaVersion', 'metric', 'observedMs', 'budgetMs'])
|
|
183
|
+
&& value.schemaVersion === 1 && value.metric === 'load'
|
|
184
|
+
&& nonnegativeInteger(value.observedMs, 30_000)
|
|
185
|
+
&& nonnegativeInteger(value.budgetMs, 30_000) && value.budgetMs > 0
|
|
186
|
+
&& value.observedMs <= value.budgetMs;
|
|
187
|
+
}
|
|
188
|
+
function sha(value) {
|
|
189
|
+
return createHash('sha256').update(value).digest('hex');
|
|
190
|
+
}
|
|
191
|
+
function exact(value, keys) {
|
|
192
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
193
|
+
&& Object.keys(value).sort().join('\0') === [...keys].sort().join('\0');
|
|
194
|
+
}
|
|
195
|
+
function privateDirectory(root, create) {
|
|
196
|
+
const commonRaw = mutationQaGit(root, ['rev-parse', '--git-common-dir']).toString('utf8').trim();
|
|
197
|
+
const common = isAbsolute(commonRaw) ? resolve(commonRaw) : resolve(root, commonRaw);
|
|
198
|
+
if (realpathSync(common) !== common || lstatSync(common).isSymbolicLink()
|
|
199
|
+
|| lstatSync(common).uid !== process.getuid?.())
|
|
200
|
+
throw new Error('qa-scan-review-unverified');
|
|
201
|
+
const directory = join(common, 'neocortex-qa-scan');
|
|
202
|
+
if (create)
|
|
203
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
204
|
+
const stat = lstatSync(directory);
|
|
205
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.()
|
|
206
|
+
|| (stat.mode & 0o077) !== 0)
|
|
207
|
+
throw new Error('qa-scan-review-unverified');
|
|
208
|
+
return directory;
|
|
209
|
+
}
|
|
210
|
+
function evidenceDirectory(root, create) {
|
|
211
|
+
const directory = join(privateDirectory(root, create), 'evidence');
|
|
212
|
+
if (create)
|
|
213
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
214
|
+
const stat = lstatSync(directory);
|
|
215
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.()
|
|
216
|
+
|| (stat.mode & 0o077) !== 0)
|
|
217
|
+
throw new Error('qa-scan-review-unverified');
|
|
218
|
+
return directory;
|
|
219
|
+
}
|
|
220
|
+
/** The capture adapter may write only beneath the same private directory that
|
|
221
|
+
* the independent root reviewer reopens and hashes. */
|
|
222
|
+
export function rootQaScanEvidenceDirectory(projectRoot) {
|
|
223
|
+
return evidenceDirectory(resolve(projectRoot), false);
|
|
224
|
+
}
|
|
225
|
+
function physicalSource(root) {
|
|
226
|
+
if (realpathSync(root) !== root || !lstatSync(root).isDirectory()
|
|
227
|
+
|| mutationQaGit(root, ['rev-parse', '--show-toplevel']).toString('utf8').trim() !== root) {
|
|
228
|
+
throw new Error('qa-scan-review-unverified');
|
|
229
|
+
}
|
|
230
|
+
const status = mutationQaGit(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all'])
|
|
231
|
+
.toString('utf8').split('\0').filter(Boolean);
|
|
232
|
+
if (status.some((entry) => !/^.{2} \.neocortex\//.test(entry))) {
|
|
233
|
+
throw new Error('qa-scan-review-source-dirty');
|
|
234
|
+
}
|
|
235
|
+
const head = mutationQaGit(root, ['rev-parse', '--verify', 'HEAD']).toString('utf8').trim();
|
|
236
|
+
if (!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(head))
|
|
237
|
+
throw new Error('qa-scan-review-unverified');
|
|
238
|
+
return head;
|
|
239
|
+
}
|
|
240
|
+
function targetDigest(url) {
|
|
241
|
+
let parsed;
|
|
242
|
+
try {
|
|
243
|
+
parsed = new URL(url);
|
|
244
|
+
}
|
|
245
|
+
catch {
|
|
246
|
+
throw new Error('qa-scan-review-target-invalid');
|
|
247
|
+
}
|
|
248
|
+
if (parsed.protocol !== 'http:' || !['127.0.0.1', 'localhost', '[::1]'].includes(parsed.hostname)
|
|
249
|
+
|| !parsed.port || parsed.username || parsed.password || parsed.search || parsed.hash) {
|
|
250
|
+
throw new Error('qa-scan-review-target-invalid');
|
|
251
|
+
}
|
|
252
|
+
return sha(`qa-scan-loopback-target-v1\0${parsed.href}`);
|
|
253
|
+
}
|
|
254
|
+
/** Creates only an owner-private evidence directory; no project or QA state is changed. */
|
|
255
|
+
export function planRootQaScan(projectRoot, surface, targetUrl) {
|
|
256
|
+
try {
|
|
257
|
+
if (!SURFACE.test(surface))
|
|
258
|
+
throw new Error('qa-scan-review-surface-invalid');
|
|
259
|
+
const root = resolve(projectRoot);
|
|
260
|
+
const sourceHead = physicalSource(root);
|
|
261
|
+
const targetSha256 = targetDigest(targetUrl);
|
|
262
|
+
evidenceDirectory(root, true);
|
|
263
|
+
const fields = { schemaVersion: 1, evidenceContractVersion: EVIDENCE_CONTRACT_VERSION,
|
|
264
|
+
kind: 'root-qa-scan-plan',
|
|
265
|
+
sourceHead, surface, targetSha256, requiredKinds: KINDS,
|
|
266
|
+
qaAccepted: false, localOnly: true };
|
|
267
|
+
return Object.freeze({ ...fields,
|
|
268
|
+
planSha256: sha(`root-qa-scan-plan-v2\0${JSON.stringify(fields)}`) });
|
|
269
|
+
}
|
|
270
|
+
catch (error) {
|
|
271
|
+
if (error instanceof Error && error.message.startsWith('qa-scan-review-'))
|
|
272
|
+
throw error;
|
|
273
|
+
throw new Error('qa-scan-review-unverified');
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
function checkedEvidence(root, report) {
|
|
277
|
+
const ids = new Set();
|
|
278
|
+
const hashes = [];
|
|
279
|
+
for (const row of report.observations) {
|
|
280
|
+
if (!exact(row, ['kind', 'artifactId', 'captureMethod', 'sha256', 'capturedAt', 'rationale'])
|
|
281
|
+
|| !KINDS.includes(row.kind) || !ARTIFACT.test(row.artifactId)
|
|
282
|
+
|| ids.has(row.artifactId) || row.captureMethod !== METHODS[row.kind]
|
|
283
|
+
|| !SHA256.test(row.sha256) || typeof row.rationale !== 'string'
|
|
284
|
+
|| row.rationale.length < 30 || row.rationale.length > 500
|
|
285
|
+
|| /[\x00-\x1f\x7f]/.test(row.rationale))
|
|
286
|
+
throw new Error('qa-scan-review-unverified');
|
|
287
|
+
const capturedMs = typeof row.capturedAt === 'string' ? Date.parse(row.capturedAt) : NaN;
|
|
288
|
+
if (!Number.isFinite(capturedMs) || new Date(capturedMs).toISOString() !== row.capturedAt
|
|
289
|
+
|| capturedMs > Date.now() + 5 * 60_000 || Date.now() - capturedMs > 60 * 60_000) {
|
|
290
|
+
throw new Error('qa-scan-review-unverified');
|
|
291
|
+
}
|
|
292
|
+
ids.add(row.artifactId);
|
|
293
|
+
const path = join(evidenceDirectory(root, false), row.artifactId);
|
|
294
|
+
const stat = lstatSync(path);
|
|
295
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid?.()
|
|
296
|
+
|| (stat.mode & 0o077) !== 0 || stat.size < 8 || stat.size > MAX_ARTIFACT_BYTES
|
|
297
|
+
|| realpathSync(path) !== path)
|
|
298
|
+
throw new Error('qa-scan-review-unverified');
|
|
299
|
+
const handle = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
300
|
+
let bytes;
|
|
301
|
+
try {
|
|
302
|
+
const before = fstatSync(handle);
|
|
303
|
+
if (!before.isFile() || before.dev !== stat.dev || before.ino !== stat.ino
|
|
304
|
+
|| before.uid !== stat.uid || before.size !== stat.size) {
|
|
305
|
+
throw new Error('qa-scan-review-unverified');
|
|
306
|
+
}
|
|
307
|
+
bytes = readFileSync(handle);
|
|
308
|
+
const after = fstatSync(handle);
|
|
309
|
+
const current = lstatSync(path);
|
|
310
|
+
if (after.dev !== before.dev || after.ino !== before.ino || after.size !== before.size
|
|
311
|
+
|| after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs
|
|
312
|
+
|| current.dev !== before.dev || current.ino !== before.ino) {
|
|
313
|
+
throw new Error('qa-scan-review-unverified');
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
finally {
|
|
317
|
+
closeSync(handle);
|
|
318
|
+
}
|
|
319
|
+
if (sha(bytes) !== row.sha256)
|
|
320
|
+
throw new Error('qa-scan-review-unverified');
|
|
321
|
+
if (row.artifactId.endsWith('.png')) {
|
|
322
|
+
if (row.captureMethod !== 'browser-screenshot' || !bytes.subarray(0, 8).equals(PNG)) {
|
|
323
|
+
throw new Error('qa-scan-review-unverified');
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
else {
|
|
327
|
+
if (row.captureMethod === 'browser-screenshot')
|
|
328
|
+
throw new Error('qa-scan-review-unverified');
|
|
329
|
+
try {
|
|
330
|
+
const parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
|
|
331
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
332
|
+
throw new Error();
|
|
333
|
+
}
|
|
334
|
+
catch {
|
|
335
|
+
throw new Error('qa-scan-review-unverified');
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
if (report.verdict === 'approved' && !validateRootQaScanArtifact(row.kind, bytes)) {
|
|
339
|
+
throw new Error('qa-scan-review-unverified');
|
|
340
|
+
}
|
|
341
|
+
hashes.push(`${row.kind}:${row.artifactId}:${row.sha256}`);
|
|
342
|
+
}
|
|
343
|
+
return sha(`root-qa-scan-evidence-v2\0${hashes.sort().join('\0')}`);
|
|
344
|
+
}
|
|
345
|
+
/** The root must independently inspect every physical artifact before signing this report. */
|
|
346
|
+
export function validateRootQaScanReview(projectRoot, surface, targetUrl, input) {
|
|
347
|
+
try {
|
|
348
|
+
const plan = planRootQaScan(projectRoot, surface, targetUrl);
|
|
349
|
+
if (!exact(input, ['schemaVersion', 'evidenceContractVersion', 'kind', 'sourceHead', 'planSha256', 'surface',
|
|
350
|
+
'targetSha256', 'verdict', 'observations', 'issues'])
|
|
351
|
+
|| input.schemaVersion !== 1 || input.evidenceContractVersion !== EVIDENCE_CONTRACT_VERSION
|
|
352
|
+
|| input.kind !== 'root-qa-scan-report'
|
|
353
|
+
|| input.sourceHead !== plan.sourceHead || input.planSha256 !== plan.planSha256
|
|
354
|
+
|| input.surface !== plan.surface || input.targetSha256 !== plan.targetSha256
|
|
355
|
+
|| (input.verdict !== 'approved' && input.verdict !== 'issues-found')
|
|
356
|
+
|| !Array.isArray(input.observations) || input.observations.length !== KINDS.length
|
|
357
|
+
|| !Array.isArray(input.issues) || input.issues.length > 128
|
|
358
|
+
|| Buffer.byteLength(JSON.stringify(input)) > MAX_REPORT_BYTES)
|
|
359
|
+
throw new Error('qa-scan-review-unverified');
|
|
360
|
+
const report = input;
|
|
361
|
+
if (report.observations.map((row) => row.kind).sort().join('\0') !== [...KINDS].sort().join('\0')) {
|
|
362
|
+
throw new Error('qa-scan-review-unverified');
|
|
363
|
+
}
|
|
364
|
+
const evidenceSha256 = checkedEvidence(resolve(projectRoot), report);
|
|
365
|
+
const ids = new Set(report.observations.map((row) => row.artifactId));
|
|
366
|
+
for (const issue of report.issues) {
|
|
367
|
+
if (!exact(issue, ['severity', 'evidenceArtifactId', 'summary'])
|
|
368
|
+
|| !['critical', 'high', 'medium', 'low'].includes(issue.severity)
|
|
369
|
+
|| !ids.has(issue.evidenceArtifactId) || typeof issue.summary !== 'string'
|
|
370
|
+
|| issue.summary.length < 20 || issue.summary.length > 500
|
|
371
|
+
|| /[\x00-\x1f\x7f]/.test(issue.summary))
|
|
372
|
+
throw new Error('qa-scan-review-unverified');
|
|
373
|
+
}
|
|
374
|
+
if ((report.verdict === 'approved') !== (report.issues.length === 0)) {
|
|
375
|
+
throw new Error('qa-scan-review-unverified');
|
|
376
|
+
}
|
|
377
|
+
if (physicalSource(resolve(projectRoot)) !== plan.sourceHead
|
|
378
|
+
|| checkedEvidence(resolve(projectRoot), report) !== evidenceSha256) {
|
|
379
|
+
throw new Error('qa-scan-review-unverified');
|
|
380
|
+
}
|
|
381
|
+
return Object.freeze({ plan, report, evidenceSha256,
|
|
382
|
+
reviewSha256: sha(`root-qa-scan-review-v2\0${JSON.stringify(report)}`) });
|
|
383
|
+
}
|
|
384
|
+
catch {
|
|
385
|
+
throw new Error('qa-scan-review-unverified');
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
function receiptFrom(checked) {
|
|
389
|
+
return Object.freeze({ schemaVersion: 1, evidenceContractVersion: EVIDENCE_CONTRACT_VERSION,
|
|
390
|
+
kind: 'root-qa-scan-review',
|
|
391
|
+
sourceHead: checked.plan.sourceHead, planSha256: checked.plan.planSha256,
|
|
392
|
+
evidenceSha256: checked.evidenceSha256, reviewSha256: checked.reviewSha256,
|
|
393
|
+
evidenceCount: 8, issueCount: checked.report.issues.length, verdict: checked.report.verdict,
|
|
394
|
+
qaAccepted: checked.report.verdict === 'approved', checkpointAccepted: false,
|
|
395
|
+
workflowContinuationAuthorized: false, localOnly: true, publicSafe: true });
|
|
396
|
+
}
|
|
397
|
+
/** Immutable local record: a tested report is not inferred from a server selection. */
|
|
398
|
+
export function acceptRootQaScanReview(projectRoot, surface, targetUrl, input) {
|
|
399
|
+
try {
|
|
400
|
+
const root = resolve(projectRoot);
|
|
401
|
+
const checked = validateRootQaScanReview(root, surface, targetUrl, input);
|
|
402
|
+
const receipt = receiptFrom(checked);
|
|
403
|
+
const directory = privateDirectory(root, true);
|
|
404
|
+
const target = join(directory, `review-${receipt.planSha256}.json`);
|
|
405
|
+
const payload = { report: checked.report, receipt };
|
|
406
|
+
const record = { schemaVersion: 1, kind: 'root-qa-scan-review-record', ...payload,
|
|
407
|
+
checksumSha256: sha(`root-qa-scan-review-record-v1\0${JSON.stringify(payload)}`) };
|
|
408
|
+
const encoded = `${JSON.stringify(record)}\n`;
|
|
409
|
+
if (existsSync(target)) {
|
|
410
|
+
const stat = lstatSync(target);
|
|
411
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid?.()
|
|
412
|
+
|| (stat.mode & 0o077) !== 0 || readFileSync(target, 'utf8') !== encoded) {
|
|
413
|
+
throw new Error('qa-scan-review-unverified');
|
|
414
|
+
}
|
|
415
|
+
return receipt;
|
|
416
|
+
}
|
|
417
|
+
const temporary = join(directory, `review-${randomUUID()}.tmp`);
|
|
418
|
+
const handle = openSync(temporary, 'wx', 0o600);
|
|
419
|
+
try {
|
|
420
|
+
writeFileSync(handle, encoded);
|
|
421
|
+
fsyncSync(handle);
|
|
422
|
+
}
|
|
423
|
+
finally {
|
|
424
|
+
closeSync(handle);
|
|
425
|
+
}
|
|
426
|
+
try {
|
|
427
|
+
if (validateRootQaScanReview(root, surface, targetUrl, input).reviewSha256 !== receipt.reviewSha256) {
|
|
428
|
+
throw new Error('qa-scan-review-unverified');
|
|
429
|
+
}
|
|
430
|
+
linkSync(temporary, target);
|
|
431
|
+
const directoryHandle = openSync(directory, 'r');
|
|
432
|
+
try {
|
|
433
|
+
fsyncSync(directoryHandle);
|
|
434
|
+
}
|
|
435
|
+
finally {
|
|
436
|
+
closeSync(directoryHandle);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
finally {
|
|
440
|
+
if (existsSync(temporary))
|
|
441
|
+
unlinkSync(temporary);
|
|
442
|
+
}
|
|
443
|
+
return receipt;
|
|
444
|
+
}
|
|
445
|
+
catch {
|
|
446
|
+
throw new Error('qa-scan-review-unverified');
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
/** Rechecks the private report and every artifact against the current physical source. */
|
|
450
|
+
export function readRootQaScanReview(projectRoot, surface, targetUrl) {
|
|
451
|
+
return readRootQaScanReviewedEvidence(projectRoot, surface, targetUrl).receipt;
|
|
452
|
+
}
|
|
453
|
+
/** Private worker/root read only. CLI projections must return the receipt alone. */
|
|
454
|
+
export function readRootQaScanReviewedEvidence(projectRoot, surface, targetUrl) {
|
|
455
|
+
try {
|
|
456
|
+
const root = resolve(projectRoot);
|
|
457
|
+
const plan = planRootQaScan(root, surface, targetUrl);
|
|
458
|
+
const target = join(privateDirectory(root, false), `review-${plan.planSha256}.json`);
|
|
459
|
+
const stat = lstatSync(target);
|
|
460
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid?.()
|
|
461
|
+
|| (stat.mode & 0o077) !== 0 || stat.size < 1 || stat.size > MAX_REPORT_BYTES + 4096) {
|
|
462
|
+
throw new Error('qa-scan-review-unverified');
|
|
463
|
+
}
|
|
464
|
+
const raw = readFileSync(target, 'utf8');
|
|
465
|
+
const record = JSON.parse(raw);
|
|
466
|
+
if (!exact(record, ['schemaVersion', 'kind', 'report', 'receipt', 'checksumSha256'])
|
|
467
|
+
|| record.schemaVersion !== 1 || record.kind !== 'root-qa-scan-review-record'
|
|
468
|
+
|| typeof record.checksumSha256 !== 'string' || !SHA256.test(record.checksumSha256)
|
|
469
|
+
|| raw !== `${JSON.stringify(record)}\n`)
|
|
470
|
+
throw new Error('qa-scan-review-unverified');
|
|
471
|
+
const payload = { report: record.report, receipt: record.receipt };
|
|
472
|
+
if (record.checksumSha256 !== sha(`root-qa-scan-review-record-v1\0${JSON.stringify(payload)}`)) {
|
|
473
|
+
throw new Error('qa-scan-review-unverified');
|
|
474
|
+
}
|
|
475
|
+
const checked = validateRootQaScanReview(root, surface, targetUrl, record.report);
|
|
476
|
+
const expected = receiptFrom(checked);
|
|
477
|
+
if (!exact(record.receipt, Object.keys(expected))
|
|
478
|
+
|| JSON.stringify(record.receipt) !== JSON.stringify(expected))
|
|
479
|
+
throw new Error('qa-scan-review-unverified');
|
|
480
|
+
return Object.freeze({ receipt: expected, report: Object.freeze(structuredClone(checked.report)) });
|
|
481
|
+
}
|
|
482
|
+
catch {
|
|
483
|
+
throw new Error('qa-scan-review-unverified');
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
/** Reopens every independent root verdict and its eight physical artifacts.
|
|
487
|
+
* Covers the selected nonempty surface set, never server graph or release authority. */
|
|
488
|
+
export function aggregateRootQaScanReviews(projectRoot, input) {
|
|
489
|
+
try {
|
|
490
|
+
if (!exact(input, ['schemaVersion', 'targets']) || input.schemaVersion !== 1
|
|
491
|
+
|| !Array.isArray(input.targets) || input.targets.length < 1 || input.targets.length > 16) {
|
|
492
|
+
throw new Error('qa-scan-review-aggregate-unverified');
|
|
493
|
+
}
|
|
494
|
+
const root = resolve(projectRoot);
|
|
495
|
+
const sourceHead = physicalSource(root);
|
|
496
|
+
const surfaces = new Set();
|
|
497
|
+
const targetDigests = new Set();
|
|
498
|
+
let origin;
|
|
499
|
+
const targets = input.targets.map((target) => {
|
|
500
|
+
if (!exact(target, ['surface', 'targetUrl']) || typeof target.surface !== 'string'
|
|
501
|
+
|| typeof target.targetUrl !== 'string' || surfaces.has(target.surface)) {
|
|
502
|
+
throw new Error('qa-scan-review-aggregate-unverified');
|
|
503
|
+
}
|
|
504
|
+
const plan = planRootQaScan(root, target.surface, target.targetUrl);
|
|
505
|
+
const targetOrigin = new URL(target.targetUrl).origin;
|
|
506
|
+
if (plan.sourceHead !== sourceHead || targetDigests.has(plan.targetSha256)
|
|
507
|
+
|| (origin !== undefined && origin !== targetOrigin)) {
|
|
508
|
+
throw new Error('qa-scan-review-aggregate-unverified');
|
|
509
|
+
}
|
|
510
|
+
origin = targetOrigin;
|
|
511
|
+
surfaces.add(target.surface);
|
|
512
|
+
targetDigests.add(plan.targetSha256);
|
|
513
|
+
return { surface: target.surface, targetUrl: target.targetUrl, plan };
|
|
514
|
+
}).sort((a, b) => a.surface < b.surface ? -1 : a.surface > b.surface ? 1 : 0);
|
|
515
|
+
const read = () => targets.map(({ surface, targetUrl, plan }) => {
|
|
516
|
+
const receipt = readRootQaScanReview(root, surface, targetUrl);
|
|
517
|
+
if (receipt.sourceHead !== sourceHead || receipt.planSha256 !== plan.planSha256) {
|
|
518
|
+
throw new Error('qa-scan-review-aggregate-unverified');
|
|
519
|
+
}
|
|
520
|
+
return receipt;
|
|
521
|
+
});
|
|
522
|
+
const first = read();
|
|
523
|
+
const last = read();
|
|
524
|
+
if (physicalSource(root) !== sourceHead || JSON.stringify(first) !== JSON.stringify(last)) {
|
|
525
|
+
throw new Error('qa-scan-review-aggregate-unverified');
|
|
526
|
+
}
|
|
527
|
+
if (new Set(last.map((receipt) => receipt.evidenceSha256)).size !== last.length) {
|
|
528
|
+
throw new Error('qa-scan-review-aggregate-unverified');
|
|
529
|
+
}
|
|
530
|
+
const issueCount = last.reduce((total, receipt) => total + receipt.issueCount, 0);
|
|
531
|
+
const approved = last.every((receipt) => receipt.qaAccepted && receipt.verdict === 'approved');
|
|
532
|
+
const aggregateSha256 = sha(`root-qa-scan-aggregate-v2\0${sourceHead}\0${last.map((receipt) => [
|
|
533
|
+
receipt.planSha256, receipt.evidenceSha256, receipt.reviewSha256,
|
|
534
|
+
receipt.verdict, receipt.issueCount,
|
|
535
|
+
].join(':')).join('\0')}`);
|
|
536
|
+
return Object.freeze({ schemaVersion: 1, evidenceContractVersion: EVIDENCE_CONTRACT_VERSION,
|
|
537
|
+
kind: 'root-qa-scan-aggregate',
|
|
538
|
+
sourceHead, aggregateSha256, surfaceCount: last.length,
|
|
539
|
+
evidenceCount: last.reduce((total, receipt) => total + receipt.evidenceCount, 0),
|
|
540
|
+
issueCount, verdict: approved ? 'approved' : 'issues-found', qaAccepted: approved,
|
|
541
|
+
checkpointAccepted: false, workflowContinuationAuthorized: false,
|
|
542
|
+
localOnly: true, publicSafe: true });
|
|
543
|
+
}
|
|
544
|
+
catch {
|
|
545
|
+
throw new Error('qa-scan-review-aggregate-unverified');
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
function phaseCheckpointFrom(aggregate) {
|
|
549
|
+
if ((aggregate.qaAccepted && (aggregate.verdict !== 'approved' || aggregate.issueCount !== 0))
|
|
550
|
+
|| (!aggregate.qaAccepted && (aggregate.verdict !== 'issues-found' || aggregate.issueCount < 1))) {
|
|
551
|
+
throw new Error('qa-scan-review-phase-unverified');
|
|
552
|
+
}
|
|
553
|
+
return Object.freeze({ schemaVersion: 1, evidenceContractVersion: EVIDENCE_CONTRACT_VERSION,
|
|
554
|
+
kind: 'root-qa-scan-phase-checkpoint',
|
|
555
|
+
sourceHead: aggregate.sourceHead, aggregateSha256: aggregate.aggregateSha256,
|
|
556
|
+
surfaceCount: aggregate.surfaceCount,
|
|
557
|
+
q01DiscoveryEvidenceValidated: true, q02InteractionEvidenceValidated: true,
|
|
558
|
+
q03RootTriageValidated: true, qaAccepted: aggregate.qaAccepted,
|
|
559
|
+
rootPhaseCheckpointAccepted: true, workflowContinuationAuthorized: false,
|
|
560
|
+
localOnly: true, publicSafe: true });
|
|
561
|
+
}
|
|
562
|
+
/** Revalidates every private review and artifact, then saves an immutable root
|
|
563
|
+
* synthesis. This is local QA state only, never a server graph advancement. */
|
|
564
|
+
export function acceptRootQaScanPhaseCheckpoint(projectRoot, input) {
|
|
565
|
+
try {
|
|
566
|
+
const root = resolve(projectRoot);
|
|
567
|
+
const aggregate = aggregateRootQaScanReviews(root, input);
|
|
568
|
+
const receipt = phaseCheckpointFrom(aggregate);
|
|
569
|
+
const directory = privateDirectory(root, true);
|
|
570
|
+
const target = join(directory, `phase-${receipt.aggregateSha256}.json`);
|
|
571
|
+
const payload = { receipt };
|
|
572
|
+
const record = { schemaVersion: 1, kind: 'root-qa-scan-phase-record', ...payload,
|
|
573
|
+
checksumSha256: sha(`root-qa-scan-phase-record-v1\0${JSON.stringify(payload)}`) };
|
|
574
|
+
const encoded = `${JSON.stringify(record)}\n`;
|
|
575
|
+
if (existsSync(target)) {
|
|
576
|
+
if (readRootQaScanPhaseCheckpoint(root, input).aggregateSha256 !== receipt.aggregateSha256) {
|
|
577
|
+
throw new Error('qa-scan-review-phase-unverified');
|
|
578
|
+
}
|
|
579
|
+
return receipt;
|
|
580
|
+
}
|
|
581
|
+
const temporary = join(directory, `phase-${randomUUID()}.tmp`);
|
|
582
|
+
const handle = openSync(temporary, 'wx', 0o600);
|
|
583
|
+
try {
|
|
584
|
+
writeFileSync(handle, encoded);
|
|
585
|
+
fsyncSync(handle);
|
|
586
|
+
}
|
|
587
|
+
finally {
|
|
588
|
+
closeSync(handle);
|
|
589
|
+
}
|
|
590
|
+
try {
|
|
591
|
+
const fresh = phaseCheckpointFrom(aggregateRootQaScanReviews(root, input));
|
|
592
|
+
if (JSON.stringify(fresh) !== JSON.stringify(receipt)) {
|
|
593
|
+
throw new Error('qa-scan-review-phase-unverified');
|
|
594
|
+
}
|
|
595
|
+
linkSync(temporary, target);
|
|
596
|
+
const directoryHandle = openSync(directory, 'r');
|
|
597
|
+
try {
|
|
598
|
+
fsyncSync(directoryHandle);
|
|
599
|
+
}
|
|
600
|
+
finally {
|
|
601
|
+
closeSync(directoryHandle);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
finally {
|
|
605
|
+
if (existsSync(temporary))
|
|
606
|
+
unlinkSync(temporary);
|
|
607
|
+
}
|
|
608
|
+
return receipt;
|
|
609
|
+
}
|
|
610
|
+
catch {
|
|
611
|
+
throw new Error('qa-scan-review-phase-unverified');
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
/** A checkpoint is valid only while the current source and all underlying
|
|
615
|
+
* root reviews and artifacts still match its immutable aggregate. */
|
|
616
|
+
export function readRootQaScanPhaseCheckpoint(projectRoot, input) {
|
|
617
|
+
try {
|
|
618
|
+
const root = resolve(projectRoot);
|
|
619
|
+
const expected = phaseCheckpointFrom(aggregateRootQaScanReviews(root, input));
|
|
620
|
+
const target = join(privateDirectory(root, false), `phase-${expected.aggregateSha256}.json`);
|
|
621
|
+
const stat = lstatSync(target);
|
|
622
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid?.()
|
|
623
|
+
|| (stat.mode & 0o077) !== 0 || stat.size < 1 || stat.size > 4096) {
|
|
624
|
+
throw new Error('qa-scan-review-phase-unverified');
|
|
625
|
+
}
|
|
626
|
+
const raw = readFileSync(target, 'utf8');
|
|
627
|
+
const record = JSON.parse(raw);
|
|
628
|
+
if (!exact(record, ['schemaVersion', 'kind', 'receipt', 'checksumSha256'])
|
|
629
|
+
|| record.schemaVersion !== 1 || record.kind !== 'root-qa-scan-phase-record'
|
|
630
|
+
|| record.checksumSha256 !== sha(`root-qa-scan-phase-record-v1\0${JSON.stringify({ receipt: record.receipt })}`)
|
|
631
|
+
|| !exact(record.receipt, Object.keys(expected))
|
|
632
|
+
|| JSON.stringify(record.receipt) !== JSON.stringify(expected)
|
|
633
|
+
|| raw !== `${JSON.stringify(record)}\n`)
|
|
634
|
+
throw new Error('qa-scan-review-phase-unverified');
|
|
635
|
+
return expected;
|
|
636
|
+
}
|
|
637
|
+
catch {
|
|
638
|
+
throw new Error('qa-scan-review-phase-unverified');
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
export async function qaScanReviewCliHandler(args) {
|
|
642
|
+
const action = args[0];
|
|
643
|
+
let projectRoot = process.cwd();
|
|
644
|
+
let surface = '';
|
|
645
|
+
let targetUrl = '';
|
|
646
|
+
let format = 'plain';
|
|
647
|
+
let authorizeReview = false;
|
|
648
|
+
let authorizeCapture = false;
|
|
649
|
+
let authorizeInteraction = false;
|
|
650
|
+
let authorizeDiscovery = false;
|
|
651
|
+
let authorizeRootCheckpoint = false;
|
|
652
|
+
let discoverySha256 = '';
|
|
653
|
+
let actionId = '';
|
|
654
|
+
let expectedStatus = '';
|
|
655
|
+
const seen = new Set();
|
|
656
|
+
try {
|
|
657
|
+
if (action !== 'plan' && action !== 'capture' && action !== 'interact' && action !== 'accept'
|
|
658
|
+
&& action !== 'status' && action !== 'aggregate' && action !== 'phase-checkpoint'
|
|
659
|
+
&& action !== 'phase-status' && action !== 'discover' && action !== 'discovery-status'
|
|
660
|
+
&& action !== 'discovered-phase-checkpoint' && action !== 'discovered-phase-status') {
|
|
661
|
+
throw new Error('qa-scan-review-action-invalid');
|
|
662
|
+
}
|
|
663
|
+
for (let index = 1; index < args.length; index++) {
|
|
664
|
+
const token = args[index];
|
|
665
|
+
if (seen.has(token))
|
|
666
|
+
throw new Error('qa-scan-review-argument-duplicate');
|
|
667
|
+
seen.add(token);
|
|
668
|
+
const next = () => args[++index] ?? '';
|
|
669
|
+
if (token === '--project-root')
|
|
670
|
+
projectRoot = next();
|
|
671
|
+
else if (token === '--surface')
|
|
672
|
+
surface = next();
|
|
673
|
+
else if (token === '--target-url')
|
|
674
|
+
targetUrl = next();
|
|
675
|
+
else if (token === '--action-id')
|
|
676
|
+
actionId = next();
|
|
677
|
+
else if (token === '--expected-status')
|
|
678
|
+
expectedStatus = next();
|
|
679
|
+
else if (token === '--discovery-sha')
|
|
680
|
+
discoverySha256 = next();
|
|
681
|
+
else if (token === '--format') {
|
|
682
|
+
const selected = next();
|
|
683
|
+
if (selected !== 'json' && selected !== 'plain')
|
|
684
|
+
throw new Error('qa-scan-review-format-invalid');
|
|
685
|
+
format = selected;
|
|
686
|
+
}
|
|
687
|
+
else if (token === '--authorize-review')
|
|
688
|
+
authorizeReview = true;
|
|
689
|
+
else if (token === '--authorize-capture')
|
|
690
|
+
authorizeCapture = true;
|
|
691
|
+
else if (token === '--authorize-interaction')
|
|
692
|
+
authorizeInteraction = true;
|
|
693
|
+
else if (token === '--authorize-discovery')
|
|
694
|
+
authorizeDiscovery = true;
|
|
695
|
+
else if (token === '--authorize-root-checkpoint')
|
|
696
|
+
authorizeRootCheckpoint = true;
|
|
697
|
+
else
|
|
698
|
+
throw new Error('qa-scan-review-argument-invalid');
|
|
699
|
+
}
|
|
700
|
+
const discoveredPhaseAction = action === 'discovered-phase-checkpoint'
|
|
701
|
+
|| action === 'discovered-phase-status';
|
|
702
|
+
const targetListAction = action === 'aggregate' || action === 'phase-checkpoint'
|
|
703
|
+
|| action === 'phase-status' || discoveredPhaseAction;
|
|
704
|
+
const discoveryAction = action === 'discover' || action === 'discovery-status';
|
|
705
|
+
const checkpointAction = action === 'phase-checkpoint' || action === 'discovered-phase-checkpoint';
|
|
706
|
+
if (!projectRoot || (targetListAction || action === 'discovery-status'
|
|
707
|
+
? seen.has('--surface') || seen.has('--target-url')
|
|
708
|
+
: action === 'discover' ? seen.has('--surface') || !targetUrl : !surface || !targetUrl)
|
|
709
|
+
|| authorizeReview !== (action === 'accept')
|
|
710
|
+
|| authorizeCapture !== (action === 'capture')
|
|
711
|
+
|| authorizeInteraction !== (action === 'interact')
|
|
712
|
+
|| authorizeDiscovery !== (action === 'discover')
|
|
713
|
+
|| authorizeRootCheckpoint !== checkpointAction
|
|
714
|
+
|| (discoveredPhaseAction || action === 'discovery-status'
|
|
715
|
+
? !SHA256.test(discoverySha256) : seen.has('--discovery-sha'))
|
|
716
|
+
|| (action === 'interact' ? !actionId || !expectedStatus
|
|
717
|
+
: seen.has('--action-id') || seen.has('--expected-status'))) {
|
|
718
|
+
throw new Error('qa-scan-review-authorization-or-target-required');
|
|
719
|
+
}
|
|
720
|
+
if (targetListAction) {
|
|
721
|
+
let input = '';
|
|
722
|
+
for await (const chunk of process.stdin) {
|
|
723
|
+
input += String(chunk);
|
|
724
|
+
if (Buffer.byteLength(input) > MAX_REPORT_BYTES)
|
|
725
|
+
throw new Error('qa-scan-review-too-large');
|
|
726
|
+
}
|
|
727
|
+
const { parseDocument } = await import('yaml');
|
|
728
|
+
const document = parseDocument(input, { strict: true, uniqueKeys: true,
|
|
729
|
+
schema: 'core', customTags: [] });
|
|
730
|
+
if (document.errors.length || document.warnings.length)
|
|
731
|
+
throw new Error(action === 'aggregate'
|
|
732
|
+
? 'qa-scan-review-aggregate-unverified' : 'qa-scan-review-phase-unverified');
|
|
733
|
+
const targets = JSON.parse(input);
|
|
734
|
+
const receipt = discoveredPhaseAction
|
|
735
|
+
? action === 'discovered-phase-checkpoint'
|
|
736
|
+
? (await import('./qa-scan-discovery.js')).acceptRootQaScanDiscoveredPhase(projectRoot, discoverySha256, targets)
|
|
737
|
+
: (await import('./qa-scan-discovery.js')).readRootQaScanDiscoveredPhase(projectRoot, discoverySha256, targets)
|
|
738
|
+
: action === 'aggregate' ? aggregateRootQaScanReviews(projectRoot, targets)
|
|
739
|
+
: action === 'phase-checkpoint' ? acceptRootQaScanPhaseCheckpoint(projectRoot, targets)
|
|
740
|
+
: readRootQaScanPhaseCheckpoint(projectRoot, targets);
|
|
741
|
+
if (format === 'json')
|
|
742
|
+
console.log(JSON.stringify(receipt));
|
|
743
|
+
else if ('verdict' in receipt)
|
|
744
|
+
console.log(`Root QA scan aggregate ${receipt.verdict}; surfaces=${receipt.surfaceCount}, issues=${receipt.issueCount}, workflow-continuation=unauthorized`);
|
|
745
|
+
else
|
|
746
|
+
console.log(`Root QA scan bounded local evidence checkpoint; surfaces=${receipt.surfaceCount}, qa-accepted=${receipt.qaAccepted}, workflow-continuation=unauthorized`);
|
|
747
|
+
return receipt.qaAccepted ? 0 : 2;
|
|
748
|
+
}
|
|
749
|
+
if (discoveryAction) {
|
|
750
|
+
const { discoverRootQaScanLinks, readRootQaScanDiscovery } = await import('./qa-scan-discovery.js');
|
|
751
|
+
const receipt = action === 'discover'
|
|
752
|
+
? await discoverRootQaScanLinks({ projectRoot, seedUrl: targetUrl, authorizeDiscovery })
|
|
753
|
+
: readRootQaScanDiscovery(projectRoot, discoverySha256);
|
|
754
|
+
if (format === 'json')
|
|
755
|
+
console.log(JSON.stringify(receipt));
|
|
756
|
+
else
|
|
757
|
+
console.log(`Root QA scan link inventory; targets=${receipt.targetCount}, QA=not-accepted`);
|
|
758
|
+
return 0;
|
|
759
|
+
}
|
|
760
|
+
if (action === 'capture') {
|
|
761
|
+
const { captureRootQaScan } = await import('./qa-scan-capture.js');
|
|
762
|
+
const receipt = await captureRootQaScan({ projectRoot, surface, targetUrl,
|
|
763
|
+
authorizeCapture });
|
|
764
|
+
if (format === 'json')
|
|
765
|
+
console.log(JSON.stringify(receipt));
|
|
766
|
+
else
|
|
767
|
+
console.log(`Root QA scan captured ${receipt.evidenceCount} private artifacts; independent review required`);
|
|
768
|
+
return 0;
|
|
769
|
+
}
|
|
770
|
+
if (action === 'interact') {
|
|
771
|
+
const { captureRootQaScanInteraction } = await import('./qa-scan-capture.js');
|
|
772
|
+
const receipt = await captureRootQaScanInteraction({ projectRoot, surface, targetUrl,
|
|
773
|
+
actionId, expectedStatus, authorizeInteraction });
|
|
774
|
+
if (format === 'json')
|
|
775
|
+
console.log(JSON.stringify(receipt));
|
|
776
|
+
else
|
|
777
|
+
console.log('Root QA scan synthetic interaction captured; independent review required');
|
|
778
|
+
return 0;
|
|
779
|
+
}
|
|
780
|
+
if (action === 'plan') {
|
|
781
|
+
const plan = planRootQaScan(projectRoot, surface, targetUrl);
|
|
782
|
+
const evidencePath = evidenceDirectory(resolve(projectRoot), false);
|
|
783
|
+
if (format === 'json')
|
|
784
|
+
console.log(JSON.stringify({ plan, evidenceDirectory: evidencePath,
|
|
785
|
+
approvedEvidenceContract: APPROVED_EVIDENCE_CONTRACT }));
|
|
786
|
+
else
|
|
787
|
+
console.log(`Root QA scan plan ${plan.planSha256}; evidence directory ${evidencePath}; no QA accepted; use --format json for approved evidence contract`);
|
|
788
|
+
return 0;
|
|
789
|
+
}
|
|
790
|
+
if (action === 'status') {
|
|
791
|
+
const receipt = readRootQaScanReview(projectRoot, surface, targetUrl);
|
|
792
|
+
if (format === 'json')
|
|
793
|
+
console.log(JSON.stringify(receipt));
|
|
794
|
+
else
|
|
795
|
+
console.log(`Root QA scan ${receipt.verdict}; evidence=${receipt.evidenceCount}, issues=${receipt.issueCount}, qaAccepted=${receipt.qaAccepted}`);
|
|
796
|
+
return receipt.qaAccepted ? 0 : 2;
|
|
797
|
+
}
|
|
798
|
+
let input = '';
|
|
799
|
+
for await (const chunk of process.stdin) {
|
|
800
|
+
input += String(chunk);
|
|
801
|
+
if (Buffer.byteLength(input) > MAX_REPORT_BYTES)
|
|
802
|
+
throw new Error('qa-scan-review-too-large');
|
|
803
|
+
}
|
|
804
|
+
const { parseDocument } = await import('yaml');
|
|
805
|
+
const document = parseDocument(input, { strict: true, uniqueKeys: true,
|
|
806
|
+
schema: 'core', customTags: [] });
|
|
807
|
+
if (document.errors.length || document.warnings.length)
|
|
808
|
+
throw new Error('qa-scan-review-unverified');
|
|
809
|
+
const report = JSON.parse(input);
|
|
810
|
+
const receipt = acceptRootQaScanReview(projectRoot, surface, targetUrl, report);
|
|
811
|
+
if (format === 'json')
|
|
812
|
+
console.log(JSON.stringify(receipt));
|
|
813
|
+
else
|
|
814
|
+
console.log(`Root QA scan ${receipt.verdict}; evidence=${receipt.evidenceCount}, issues=${receipt.issueCount}, qaAccepted=${receipt.qaAccepted}`);
|
|
815
|
+
return receipt.qaAccepted ? 0 : 2;
|
|
816
|
+
}
|
|
817
|
+
catch (error) {
|
|
818
|
+
const reasonCode = error instanceof Error && /^qa-scan-review-[a-z-]+$/.test(error.message)
|
|
819
|
+
? error.message : 'qa-scan-review-unverified';
|
|
820
|
+
if (format === 'json')
|
|
821
|
+
console.log(JSON.stringify({ ok: false, reasonCode }));
|
|
822
|
+
else
|
|
823
|
+
console.error(reasonCode);
|
|
824
|
+
return 1;
|
|
825
|
+
}
|
|
826
|
+
}
|