@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 +1,885 @@
|
|
|
1
|
-
import{createHash as X,randomBytes as q}from"node:crypto";import{AUTONOMOUS_GOVERNANCE_EVIDENCE_TAG as Y,AUTONOMOUS_GOVERNANCE_REASON_CODES as $,autonomousGovernanceMetadata as K,buildAutonomousGovernanceEnvelope as Z,readAutonomousGovernanceEnvelopeFromMetadata as P,recordAutonomousGovernance as G}from"../../continuity/autonomous-governance.js";import{createDefaultHeadlessAdapterRegistry as J}from"./adapters.js";import{loadHeadlessRuntimeDefaults as W,resolveHeadlessRuntime as Q}from"./resolver.js";import{HEADLESS_REASON_CODES as m,boundPublicSummary as A,hashPublicValue as g,redaction as i}from"./types.js";const ee=300*1e3,te=30*1e3,re=30*1e3,oe=600*1e3,ae=1,ne=3,O=/^docs\/stories\/[A-Za-z0-9._-]+\.story\.md$/,se=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/,de=new Set(["schemaVersion","contractVersion","kind","commandClass","jobId","operationId","idempotencyKey","targetKind","targetRef","commandRef","storyId","executionMode","runtime","publicSummary","reasonCode","attempts","metadata","redactionSummary","publicSafe"]),ie=new Set(["runtimeId","modelId","source","reasonCode","publicSafe"]),R=/(raw[_-]?(?:logs?|payloads?)|std(?:out|err)|stack(?:[_-]?trace)?|transcript|objective(?:[_-]?(?:text|body|prompt))|prompt(?:[_-]?(?:body|text))?|private[_-]?(?:urls?|prompts?)|secret|token|password|protected(?:[_-]?(?:field|body|bodies|internals))?|workflow(?:[_-]?body)?|step(?:[_-]?body)?|customer(?:[_-]?(?:pii|data))?|\bpii\b|authorization|api[_-]?key|license[_-]?key|argv|args|executable(?:[_-]?path)?|binary(?:[_-]?path)?|shell|cwd|command[_-]?path|vendor(?:[_-]?(?:payload|corpus|response|output)))/i,y=/(https?:\/\/\S+|(?:^|\s)(?:\/(?:home|Users|media|mnt|tmp|var|etc|private)\/\S+|[A-Za-z]:\\\S+)|ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|-----BEGIN [A-Z ]*PRIVATE KEY-----|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=|raw[_-]?(?:logs?)\s*[:=]|transcript|stack\s*trace|stderr:|stdout:|system prompt|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|\bPII\b|VENDOR_CORPUS|P190[_-]?SYNTHETIC[_-]?(?:HEADLESS|CONTINUITY))/i,b=/(?:[;&|`$<>]|\$\(|\n|\r|\0)/;async function Te(e){const t=e.adapterRegistry??J(),r=E(e.limit??ae,1,10),a=E(e.leaseMs??ee,1e3,3600*1e3),n=E(e.staleLeaseAfterMs??te,0,1440*60*1e3),s=E(e.maxAttempts??ne,1,10),o=[],u=[],d=e.now(),c=ue({store:e.store,metadata:e.metadata,nowIso:d,maxAttempts:s,queueCap:e.queueCap});o.push(...c.reasonCodes);const p=e.store.recoverStaleHeadlessExecutionAttempts({nowIso:d,staleAfterMs:n,limit:r*2});p.recoveredAttemptIds.length>0&&(o.push(m.EXECUTION_BACKOFF),p.failedAttemptIds.length>0&&o.push(m.EXECUTION_TIMEOUT));const I=new Set(e.attemptIds??[]),_=e.store.listDueHeadlessExecutionAttempts({nowIso:e.now(),limit:Math.max(r*5,10)}).filter(l=>l.directive_kind==="run_yolo").filter(l=>I.size===0||I.has(l.attempt_id)).slice(0,r);for(const l of _){const S=await ce({store:e.store,projectRoot:e.projectRoot,runnerId:e.runnerId,attempt:l,registry:t,now:e.now,leaseMs:a,timeoutMs:E(e.timeoutMs??oe,1e3,18e5),backoffMs:E(e.backoffMs??re,1e3,36e5),maxAttempts:s,adapterOptions:e.adapterOptions,runtimeDefaults:e.runtimeDefaults,runtimeFallback:e.runtimeFallback,idFactory:e.idFactory??Ae});u.push(S),o.push(S.reasonCode)}return{ok:u.every(l=>l.outcome!=="failed")&&c.rejectedCount===0,enqueuedAttemptCount:c.enqueuedCount,dueAttemptCount:_.length,processedAttemptCount:u.filter(l=>l.outcome!=="ignored").length,recoveredAttemptIds:p.recoveredAttemptIds,receipts:u,reasonCodes:z(o.length>0?o:[m.OK]),publicSafe:!0}}function ue(e){let t=0,r=0;const a=[];for(const n of he(e.metadata)){if(!h(n)||n.kind!=="run_yolo")continue;const s=pe(n);if(!s.ok){r+=1,a.push(s.reasonCode);continue}const o=s.directive;if(!e.store.jobExists(o.jobId)){r+=1,a.push($.BYPASS_BLOCKED);continue}const u=Se(o);if(e.store.hasCompletedHeadlessExecutionDirectiveHash(u)){a.push(m.EXECUTION_COMPLETED);continue}const d=Z({autonomousKind:"run_yolo",source:ye(o.metadata,"headless-run-yolo"),targetKind:"story",targetRef:o.targetRef,storyId:o.storyId??v(o.targetRef),jobId:o.jobId,operationSeed:o.operationId,commandHash:g(o.commandRef)}),c=G(e.store,d,e.nowIso,{requireExistingJob:!0});if(!c.ok){r+=1,a.push(c.reasonCode);continue}const p=L("attempt",o.idempotencyKey),I=L("exec",o.operationId),_=e.store.enqueueHeadlessExecutionAttempt({attemptId:p,executionId:I,jobId:o.jobId,directiveHash:u,directiveKind:"run_yolo",commandClass:o.commandClass,targetKind:"story",targetRef:o.targetRef,storyId:o.storyId??v(o.targetRef),runtimeId:o.runtime?.runtimeId,modelId:o.runtime?.modelId,runtimeSource:Ce(o.runtime?.source),reasonCode:o.reasonCode,publicSummary:o.publicSummary,enqueuedAt:e.nowIso,notBeforeAt:e.nowIso,maxAttempts:e.maxAttempts,queueCap:e.queueCap,operationId:`${o.operationId}:enqueue`,idempotencyKey:o.idempotencyKey,counts:{directives:1},hashes:{directive:u},redactionSummary:o.redactionSummary,relativePaths:[o.targetRef],metadata:K(d,{schemaVersion:1,contractVersion:"continuity-v1",jobId:o.jobId,operationId:o.operationId,reasonCode:o.reasonCode??m.OK,targetRef:o.targetRef,directiveHash:u,...o.executionMode?{executionMode:o.executionMode}:{}})});if(!_.accepted){r+=1,a.push(_.reasonCode??"queue-cap-reached");continue}_.inserted&&(t+=1),a.push(m.OK)}return{enqueuedCount:t,rejectedCount:r,reasonCodes:z(a)}}async function ce(e){const t=e.now(),r=e.idFactory("lease",e.attempt.attempt_id),a=F(t,e.leaseMs);if(!e.store.claimHeadlessExecutionAttempt({attemptId:e.attempt.attempt_id,leaseId:r,runnerId:e.runnerId,claimedAt:t,leaseExpiresAt:a,reasonCode:m.OK}).inserted)return{attemptId:e.attempt.attempt_id,executionId:e.attempt.execution_id,jobId:e.attempt.job_id,status:e.attempt.status,outcome:"ignored",reasonCode:"lease-conflict",timestamp:t,redactionSummary:[],publicSafe:!0};if(e.store.hasCompletedHeadlessExecutionDirectiveHash(e.attempt.directive_hash,e.attempt.attempt_id))return k(e.store,e.attempt,{leaseId:r,runnerId:e.runnerId,status:"skipped",receiptStatus:"ignored",reasonCode:m.EXECUTION_COMPLETED,publicSummary:"Skipped duplicate run_yolo directive because the directive hash is already completed.",completedAt:e.now(),counts:{duplicateDirectiveHashes:1},hashes:{directive:e.attempt.directive_hash},redactionSummary:[],relativePaths:[e.attempt.target_ref]});const o=me(e);if(!o.ok)return k(e.store,e.attempt,{leaseId:r,runnerId:e.runnerId,status:o.status,receiptStatus:o.receiptStatus,reasonCode:o.reasonCode,publicSummary:o.publicSummary,completedAt:e.now(),counts:{rejectedDirectives:1},hashes:{directive:e.attempt.directive_hash},redactionSummary:o.redactionSummary,relativePaths:H(e.attempt)});const u=e.registry.getAdapter(o.input.runtimeId);if(!u.ok)return k(e.store,e.attempt,{leaseId:r,runnerId:e.runnerId,status:"failed",receiptStatus:"failed",reasonCode:u.reasonCode,publicSummary:u.publicSummary,completedAt:e.now(),counts:{rejectedAdapters:1},hashes:{directive:e.attempt.directive_hash},redactionSummary:u.redactionSummary,relativePaths:[e.attempt.target_ref],runtimeId:o.input.runtimeId,modelId:o.input.modelId,runtimeSource:o.input.runtimeSource});let d;try{d=await u.adapter.execute(o.input,{...e.adapterOptions,cwd:e.adapterOptions?.cwd??e.projectRoot})}catch{d={status:"failed",adapterId:o.input.runtimeId,runtimeId:o.input.runtimeId,...o.input.modelId?{modelId:o.input.modelId}:{},...o.input.runtimeSource?{runtimeSource:o.input.runtimeSource}:{},reasonCode:m.EXECUTION_FAILED,reasonCodes:[m.EXECUTION_FAILED,m.RECEIPT_REDACTED],exitCode:1,signal:null,durationMs:0,counts:{adapterExceptions:1},hashes:{directive:e.attempt.directive_hash},publicSummary:"Headless adapter failed with public-safe exception summary.",redactionSummary:[i("adapter","raw_log","value-denied")],relativePaths:[e.attempt.target_ref],receipt:o.input.receipt,publicSafe:!0}}const c=Ie(e.attempt,d,e.maxAttempts,e.backoffMs,e.now()),p=c.retry?"backoff":d.status,I=c.retry?m.EXECUTION_BACKOFF:d.reasonCode,_=p==="completed"?"applied":p==="backoff"?"deferred":p==="skipped"?"ignored":"failed";return k(e.store,e.attempt,{leaseId:r,runnerId:e.runnerId,status:p,receiptStatus:_,reasonCode:I,publicSummary:c.retry?"Headless run_yolo execution scheduled bounded retry after transient adapter outcome.":d.publicSummary,completedAt:e.now(),durationMs:d.durationMs,notBeforeAt:c.notBeforeAt,retryCount:c.retryCount,counts:d.counts,hashes:{...d.hashes,directive:e.attempt.directive_hash},redactionSummary:d.redactionSummary,relativePaths:d.relativePaths.length>0?d.relativePaths:[e.attempt.target_ref],runtimeId:d.runtimeId,modelId:d.modelId,runtimeSource:d.runtimeSource})}function me(e){const t=P(e.attempt.metadata_json,{autonomousKind:"run_yolo",jobId:e.attempt.job_id,targetKind:"story",targetRef:e.attempt.target_ref});if(!t.ok)return{ok:!1,status:"failed",receiptStatus:"failed",reasonCode:m.DIRECTIVE_REJECTED,publicSummary:t.publicSummary,redactionSummary:t.redactionSummary};const r=g(`*yolo @${e.attempt.target_ref}`),a=g(`*yolo @${e.attempt.target_ref} branchless-preparation`),n=t.envelope.hashes.command===a;if(!n&&t.envelope.hashes.command!==r)return{ok:!1,status:"failed",receiptStatus:"failed",reasonCode:m.DIRECTIVE_REJECTED,publicSummary:"Headless run_yolo governance command does not match an authorized execution mode.",redactionSummary:[i("autonomousGovernance.commandHash","prompt_body","operation-denied")]};const s=fe(e.attempt);if(!s.ok)return s;const o=le(e);return o.ok?{ok:!0,input:{promptKind:n?"yolo-branchless-preparation":"yolo",targetKind:"story",targetRef:e.attempt.target_ref,...e.attempt.story_id?{storyId:e.attempt.story_id}:{},runtimeId:o.runtimeId,...o.modelId?{modelId:o.modelId}:{},runtimeSource:o.runtimeSource,timeoutMs:e.timeoutMs,receipt:{attemptId:e.attempt.attempt_id,subagentId:e.attempt.attempt_id,executionId:e.attempt.execution_id,jobId:e.attempt.job_id,operationId:e.attempt.execution_id,idempotencyKey:e.attempt.directive_hash,runnerId:e.runnerId},publicSummary:A(e.attempt.public_summary??"Headless run_yolo execution attempt."),publicSafe:!0}}:{ok:!1,status:"failed",receiptStatus:"failed",reasonCode:o.reasonCode,publicSummary:o.publicSummary,redactionSummary:o.redactionSummary}}function le(e){const t=e.runtimeDefaults!==void 0?e.runtimeDefaults:W({projectRoot:e.projectRoot});if(h(t)&&t.ok===!1)return{ok:!1,reasonCode:m.RUNTIME_UNTRUSTED,publicSummary:typeof t.publicSummary=="string"?t.publicSummary:"Headless runtime defaults failed public-safety validation.",redactionSummary:Array.isArray(t.redactionSummary)?t.redactionSummary:[]};const r=Ee(e.attempt.runtime_source)??"explicit",a=e.attempt.runtime_id||e.attempt.model_id?{...e.attempt.runtime_id?{runtimeId:e.attempt.runtime_id}:{},...e.attempt.model_id?{modelId:e.attempt.model_id}:{},source:r,publicSafe:!0}:void 0,n={registry:e.registry,defaults:t,fallback:e.runtimeFallback};a&&(r==="origin"?n.origin=a:r==="default"?n.projectDefault=a:r==="fallback"?n.fallback=a:n.explicit=a);const s=Q(n);return s.ok?{ok:!0,runtimeId:s.runtimeId,...s.modelId?{modelId:s.modelId}:{},runtimeSource:s.runtimeSource}:{ok:!1,reasonCode:s.reasonCode,publicSummary:s.publicSummary,redactionSummary:s.redactionSummary}}function fe(e){const t=[];e.directive_kind!=="run_yolo"&&t.push(i("directiveKind","unsafe_key","value-denied")),e.target_kind!=="story"&&t.push(i("targetKind","prompt_body","value-denied")),(!O.test(e.target_ref)||b.test(e.target_ref)||y.test(e.target_ref))&&t.push(i("targetRef","prompt_body","value-denied"));const r=v(e.target_ref);return e.story_id&&e.story_id!==r&&t.push(i("storyId","prompt_body","value-denied")),t.length>0?{ok:!1,status:"failed",receiptStatus:"failed",reasonCode:m.PROMPT_REJECTED,publicSummary:"Headless run_yolo attempt did not match the canonical public story prompt shape.",redactionSummary:t}:{ok:!0,input:{promptKind:"yolo",targetKind:"story",targetRef:e.target_ref,...e.story_id?{storyId:e.story_id}:{},runtimeId:"fake",publicSafe:!0}}}function pe(e){const t=[];for(const C of Object.keys(e))(!de.has(C)||R.test(C))&&t.push(i(C,T(C),"key-denied"));e.publicSafe!==!0&&t.push(i("publicSafe","unsafe_key","value-denied"));const r=f(e,"kind"),a=f(e,"commandClass"),n=f(e,"jobId"),s=f(e,"operationId"),o=f(e,"idempotencyKey"),u=f(e,"targetKind"),d=f(e,"targetRef"),c=f(e,"commandRef"),p=f(e,"publicSummary"),I=f(e,"storyId"),_=f(e,"executionMode");r!=="run_yolo"&&t.push(i("kind","unsafe_key","value-denied")),a!=="goal-tick"&&a!=="loop-tick"&&t.push(i("commandClass","unsafe_key","value-denied")),j(n)||t.push(i("jobId","unsafe_key","value-denied")),j(s)||t.push(i("operationId","unsafe_key","value-denied")),j(o)||t.push(i("idempotencyKey","unsafe_key","value-denied")),(u!=="story"||!d||!O.test(d)||y.test(d))&&t.push(i("targetRef","prompt_body","value-denied")),_!==void 0&&_!=="branchless_child_preparation"&&t.push(i("executionMode","unsafe_key","value-denied"));const l=h(e.metadata)?e.metadata:void 0,S=_==="branchless_child_preparation";S&&(l?.governanceSource!=="delegated-subagent"||l.childWorkspace!=="branchless_sandbox"||l.integrationOwner!=="root_agent"||l.maxDepth!==1||typeof l.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(l.graphRevision))&&t.push(i("executionMode","unsafe_key","value-denied"));const V=d?`*yolo @${d}${S?" branchless-preparation":""}`:void 0;(!c||c!==V||c.includes("@neocortex")||b.test(c)||y.test(c))&&t.push(i("commandRef","prompt_body","value-denied")),I&&d&&I!==v(d)&&t.push(i("storyId","prompt_body","value-denied")),(!p||p.length>240||y.test(p))&&t.push(i("publicSummary","unbounded_text","value-denied")),e.reasonCode!==void 0&&(typeof e.reasonCode!="string"||y.test(e.reasonCode))&&t.push(i("reasonCode","unsafe_key","value-denied"));const N=_e(e.runtime,t);e.attempts!==void 0&&x(e.attempts,"attempts",t),e.metadata!==void 0&&x(e.metadata,"metadata",t);const w=be(e.redactionSummary,t);return t.length>0||r!=="run_yolo"||!a||!n||!s||!o||!d||!c||!p?{ok:!1,reasonCode:t.some(B=>B.reason==="prompt_body")?m.PROMPT_REJECTED:m.DIRECTIVE_REJECTED,redactionSummary:t}:{ok:!0,directive:{kind:"run_yolo",commandClass:a,jobId:n,operationId:s,idempotencyKey:o,targetKind:"story",targetRef:d,commandRef:c,...I?{storyId:I}:{},...S?{executionMode:"branchless_child_preparation"}:{},...N?{runtime:N}:{},publicSummary:p,...typeof e.reasonCode=="string"?{reasonCode:e.reasonCode}:{},...l?{metadata:l}:{},...w.length>0?{redactionSummary:w}:{},publicSafe:!0}}}function ye(e,t){return e?.governanceSource==="delegated-subagent"?"delegated-subagent":t}function _e(e,t){if(e===void 0)return;if(!h(e)){t.push(i("runtime","unsafe_key","value-denied"));return}for(const s of Object.keys(e))(!ie.has(s)||R.test(s))&&t.push(i(`runtime.${s}`,T(s),"key-denied"));e.publicSafe!==!0&&t.push(i("runtime.publicSafe","unsafe_key","value-denied"));const r=f(e,"runtimeId"),a=f(e,"modelId"),n=f(e,"source");if(r&&(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,79}$/.test(r)||y.test(r)||b.test(r))&&t.push(i("runtime.runtimeId","unsafe_key","value-denied")),a&&(!/^[A-Za-z0-9][A-Za-z0-9._:+/-]{0,119}$/.test(a)||y.test(a)||b.test(a))&&t.push(i("runtime.modelId","unsafe_key","value-denied")),n!==void 0&&n!=="explicit"&&n!=="origin"&&n!=="default"&&n!=="fallback"&&n!=="unspecified"&&t.push(i("runtime.source","unsafe_key","value-denied")),e.reasonCode!==void 0&&(typeof e.reasonCode!="string"||y.test(e.reasonCode))&&t.push(i("runtime.reasonCode","unsafe_key","value-denied")),e.publicSafe===!0)return{...r?{runtimeId:r}:{},...a?{modelId:a}:{},...n==="explicit"||n==="origin"||n==="default"||n==="fallback"||n==="unspecified"?{source:n}:{},...typeof e.reasonCode=="string"?{reasonCode:e.reasonCode}:{},publicSafe:!0}}function k(e,t,r){const a=r.redactionSummary??[],n=r.relativePaths??H(t),s=U(r.counts),o=U(r.hashes),u={schemaVersion:1,contractVersion:"continuity-v1",attemptId:t.attempt_id,executionId:t.execution_id,jobId:t.job_id,directiveHash:t.directive_hash,status:r.status,reasonCode:r.reasonCode,...r.runtimeId?{runtimeId:r.runtimeId}:{},...r.modelId?{modelId:r.modelId}:{},...r.runtimeSource?{runtimeSource:r.runtimeSource}:{},...r.retryCount!==void 0?{retryCount:r.retryCount}:{},...r.reasonCode===$.BYPASS_BLOCKED?{governanceEvidence:Y}:{},publicSummary:A(r.publicSummary)},d=P(t.metadata_json,{autonomousKind:"run_yolo",jobId:t.job_id,targetKind:"story",targetRef:t.target_ref}),c=d.ok?K(d.envelope,u):u;return e.completeHeadlessExecutionAttempt({attemptId:t.attempt_id,executionId:t.execution_id,jobId:t.job_id,leaseId:r.leaseId,runnerId:r.runnerId,status:r.status,completedAt:r.completedAt,durationMs:r.durationMs,reasonCode:r.reasonCode,publicSummary:A(r.publicSummary),notBeforeAt:r.notBeforeAt,retryCount:r.retryCount,counts:s,hashes:o,redactionSummary:a,relativePaths:n,metadata:c}),e.recordHeadlessExecutionReceipt({receiptId:`receipt-${D("headless",`${t.attempt_id}-${r.status}`)}`,attemptId:t.attempt_id,executionId:t.execution_id,jobId:t.job_id,status:r.receiptStatus,reasonCode:r.reasonCode,createdAt:r.completedAt,operationId:`${t.execution_id}:${r.status}:receipt`,idempotencyKey:`${t.directive_hash}:${r.status}:receipt`,counts:s,hashes:o,redactionSummary:a,relativePaths:n,metadata:c}),e.recordHeadlessExecutionSummary({eventId:`event-${D("headless-summary",`${t.attempt_id}-${r.status}`)}`,attemptId:t.attempt_id,executionId:t.execution_id,jobId:t.job_id,status:r.status,runtimeId:r.runtimeId,modelId:r.modelId,publicSummary:A(r.publicSummary),reasonCode:r.reasonCode,createdAt:r.completedAt,durationMs:r.durationMs,counts:s,hashes:o,redactionSummary:a,relativePaths:n,metadata:c}),{attemptId:t.attempt_id,executionId:t.execution_id,jobId:t.job_id,status:r.status,outcome:r.receiptStatus,reasonCode:r.reasonCode,timestamp:r.completedAt,redactionSummary:a,publicSafe:!0}}function Ie(e,t,r,a,n){if(!(t.status==="timed_out"||t.reasonCode===m.EXECUTION_FAILED||t.reasonCode===m.ADAPTER_UNAVAILABLE))return{retry:!1};const o=e.retry_count+1;if(o>=Math.max(1,e.max_attempts||r))return{retry:!1,retryCount:o};const u=Math.min(8,2**Math.max(0,e.retry_count));return{retry:!0,retryCount:o,notBeforeAt:F(n,a*u)}}function he(e){const t=Array.isArray(e)?e:e?[e]:[],r=[];for(const a of t){const n=a.continuityExecutionDirectives;Array.isArray(n)&&r.push(...n)}return r}function Se(e){return g(M({kind:e.kind,commandClass:e.commandClass,jobId:e.jobId,targetRef:e.targetRef,commandRef:e.commandRef,storyId:e.storyId,executionMode:e.executionMode,runtime:e.runtime}))}function M(e){return Array.isArray(e)?`[${e.map(M).join(",")}]`:h(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${M(e[t])}`).join(",")}}`:JSON.stringify(e)}function x(e,t,r){if(typeof e=="string"){(y.test(e)||b.test(e))&&r.push(i(t,T(t),"value-denied"));return}if(!(e==null||typeof e=="number"||typeof e=="boolean")){if(Array.isArray(e)){e.forEach((a,n)=>x(a,`${t}.${n}`,r));return}if(h(e)){for(const[a,n]of Object.entries(e)){const s=`${t}.${a}`;R.test(a)&&r.push(i(s,T(a),"key-denied")),x(n,s,r)}return}r.push(i(t,"unsafe_key","value-denied"))}}function be(e,t){if(e===void 0)return[];if(!Array.isArray(e))return t.push(i("redactionSummary","unsafe_key","value-denied")),[];const r=[];for(const[a,n]of e.entries()){if(!h(n)||n.publicSafe!==!0){t.push(i(`redactionSummary.${a}`,"unsafe_key","value-denied"));continue}const s=f(n,"field"),o=f(n,"reason"),u=f(n,"evidence");if(!s||!o||!u||y.test(s)||y.test(o)||y.test(u)){t.push(i(`redactionSummary.${a}`,"unsafe_key","value-denied"));continue}r.push({field:s,reason:o,evidence:u,publicSafe:!0})}return r}function H(e){return O.test(e.target_ref)?[e.target_ref]:[]}function U(e){if(!e)return;const t={};for(const[r,a]of Object.entries(e))!/^[A-Za-z0-9_.:-]{1,80}$/.test(r)||R.test(r)||y.test(r)||typeof a=="string"&&y.test(a)||(t[r]=a);return Object.keys(t).length>0?t:void 0}function v(e){return e.replace(/^docs\/stories\//,"").replace(/\.story\.md$/,"")}function Ee(e){if(e==="explicit"||e==="origin"||e==="default"||e==="fallback")return e}function Ce(e){if(e==="explicit"||e==="origin"||e==="default"||e==="fallback"||e==="unspecified")return e}function T(e){return/prompt|commandRef/i.test(e)?"prompt_body":/std(?:out|err)|raw|log|transcript|stack/i.test(e)?"raw_log":/url/i.test(e)?"private_url":/path|cwd|argv|args|shell|command|binary|executable/i.test(e)?"executable_path":/secret|token|password|authorization|api[_-]?key|license/i.test(e)?"secret_or_pii":"unsafe_key"}function f(e,t){return typeof e[t]=="string"?e[t]:void 0}function j(e){return!!(e&&se.test(e)&&!y.test(e)&&!b.test(e))}function h(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function D(e,t){const r=`${e}-${t}`.replace(/[^A-Za-z0-9_.:-]+/g,"-").replace(/^-+|-+$/g,"");return r.length>0&&r.length<=120?r:`${e}-${X("sha256").update(t).digest("hex").slice(0,32)}`}function L(e,t){return D(e,t)}function Ae(e,t){return D(e,`${t}-${Date.now()}-${q(4).toString("hex")}`)}function F(e,t){const r=Date.parse(e);return new Date((Number.isFinite(r)?r:Date.now())+t).toISOString()}function E(e,t,r){return Number.isFinite(e)?Math.max(t,Math.min(r,Math.floor(e))):t}function z(e){return Array.from(new Set(e))}export{re as DEFAULT_HEADLESS_EXECUTION_BACKOFF_MS,ee as DEFAULT_HEADLESS_EXECUTION_LEASE_MS,ae as DEFAULT_HEADLESS_EXECUTION_LIMIT,ne as DEFAULT_HEADLESS_EXECUTION_MAX_ATTEMPTS,te as DEFAULT_HEADLESS_EXECUTION_STALE_LEASE_AFTER_MS,oe as DEFAULT_HEADLESS_EXECUTION_TIMEOUT_MS,L as headlessExecutionEntityId,Te as runYoloExecutionPhase};
|
|
1
|
+
/**
|
|
2
|
+
* @license FSL-1.1
|
|
3
|
+
* Copyright (c) 2026 OrNexus AI
|
|
4
|
+
*
|
|
5
|
+
* P190.05 -- runner execution plane for one-story run_yolo directives.
|
|
6
|
+
*/
|
|
7
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
8
|
+
import { AUTONOMOUS_GOVERNANCE_EVIDENCE_TAG, AUTONOMOUS_GOVERNANCE_REASON_CODES, autonomousGovernanceMetadata, buildAutonomousGovernanceEnvelope, readAutonomousGovernanceEnvelopeFromMetadata, recordAutonomousGovernance, } from '../../continuity/autonomous-governance.js';
|
|
9
|
+
import { createDefaultHeadlessAdapterRegistry } from './adapters.js';
|
|
10
|
+
import { loadHeadlessRuntimeDefaults, resolveHeadlessRuntime } from './resolver.js';
|
|
11
|
+
import { HEADLESS_REASON_CODES, boundPublicSummary, hashPublicValue, redaction, } from './types.js';
|
|
12
|
+
export const DEFAULT_HEADLESS_EXECUTION_LEASE_MS = 5 * 60 * 1000;
|
|
13
|
+
export const DEFAULT_HEADLESS_EXECUTION_STALE_LEASE_AFTER_MS = 30 * 1000;
|
|
14
|
+
export const DEFAULT_HEADLESS_EXECUTION_BACKOFF_MS = 30 * 1000;
|
|
15
|
+
export const DEFAULT_HEADLESS_EXECUTION_TIMEOUT_MS = 10 * 60 * 1000;
|
|
16
|
+
export const DEFAULT_HEADLESS_EXECUTION_LIMIT = 1;
|
|
17
|
+
export const DEFAULT_HEADLESS_EXECUTION_MAX_ATTEMPTS = 3;
|
|
18
|
+
const STORY_TARGET_PATTERN = /^docs\/stories\/[A-Za-z0-9._-]+\.story\.md$/;
|
|
19
|
+
const SAFE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/;
|
|
20
|
+
const EXECUTION_DIRECTIVE_ALLOWED_KEYS = new Set([
|
|
21
|
+
'schemaVersion',
|
|
22
|
+
'contractVersion',
|
|
23
|
+
'kind',
|
|
24
|
+
'commandClass',
|
|
25
|
+
'jobId',
|
|
26
|
+
'operationId',
|
|
27
|
+
'idempotencyKey',
|
|
28
|
+
'targetKind',
|
|
29
|
+
'targetRef',
|
|
30
|
+
'commandRef',
|
|
31
|
+
'storyId',
|
|
32
|
+
'executionMode',
|
|
33
|
+
'runtime',
|
|
34
|
+
'publicSummary',
|
|
35
|
+
'reasonCode',
|
|
36
|
+
'attempts',
|
|
37
|
+
'metadata',
|
|
38
|
+
'redactionSummary',
|
|
39
|
+
'publicSafe',
|
|
40
|
+
]);
|
|
41
|
+
const RUNTIME_ALLOWED_KEYS = new Set(['runtimeId', 'modelId', 'source', 'reasonCode', 'publicSafe']);
|
|
42
|
+
const UNSAFE_KEY_PATTERN = /(raw[_-]?(?:logs?|payloads?)|std(?:out|err)|stack(?:[_-]?trace)?|transcript|objective(?:[_-]?(?:text|body|prompt))|prompt(?:[_-]?(?:body|text))?|private[_-]?(?:urls?|prompts?)|secret|token|password|protected(?:[_-]?(?:field|body|bodies|internals))?|workflow(?:[_-]?body)?|step(?:[_-]?body)?|customer(?:[_-]?(?:pii|data))?|\bpii\b|authorization|api[_-]?key|license[_-]?key|argv|args|executable(?:[_-]?path)?|binary(?:[_-]?path)?|shell|cwd|command[_-]?path|vendor(?:[_-]?(?:payload|corpus|response|output)))/i;
|
|
43
|
+
const UNSAFE_VALUE_PATTERN = /(https?:\/\/\S+|(?:^|\s)(?:\/(?:home|Users|media|mnt|tmp|var|etc|private)\/\S+|[A-Za-z]:\\\S+)|ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|-----BEGIN [A-Z ]*PRIVATE KEY-----|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=|raw[_-]?(?:logs?)\s*[:=]|transcript|stack\s*trace|stderr:|stdout:|system prompt|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|\bPII\b|VENDOR_CORPUS|P190[_-]?SYNTHETIC[_-]?(?:HEADLESS|CONTINUITY))/i;
|
|
44
|
+
const SHELL_FRAGMENT_PATTERN = /(?:[;&|`$<>]|\$\(|\n|\r|\0)/;
|
|
45
|
+
export async function runYoloExecutionPhase(options) {
|
|
46
|
+
const registry = options.adapterRegistry ?? createDefaultHeadlessAdapterRegistry();
|
|
47
|
+
const limit = boundedInteger(options.limit ?? DEFAULT_HEADLESS_EXECUTION_LIMIT, 1, 10);
|
|
48
|
+
const leaseMs = boundedInteger(options.leaseMs ?? DEFAULT_HEADLESS_EXECUTION_LEASE_MS, 1_000, 60 * 60 * 1000);
|
|
49
|
+
const staleLeaseAfterMs = boundedInteger(options.staleLeaseAfterMs ?? DEFAULT_HEADLESS_EXECUTION_STALE_LEASE_AFTER_MS, 0, 24 * 60 * 60 * 1000);
|
|
50
|
+
const maxAttempts = boundedInteger(options.maxAttempts ?? DEFAULT_HEADLESS_EXECUTION_MAX_ATTEMPTS, 1, 10);
|
|
51
|
+
const reasonCodes = [];
|
|
52
|
+
const receipts = [];
|
|
53
|
+
const nowIso = options.now();
|
|
54
|
+
const enqueueResult = enqueueRunYoloExecutionDirectives({
|
|
55
|
+
store: options.store,
|
|
56
|
+
metadata: options.metadata,
|
|
57
|
+
nowIso,
|
|
58
|
+
maxAttempts,
|
|
59
|
+
queueCap: options.queueCap,
|
|
60
|
+
});
|
|
61
|
+
reasonCodes.push(...enqueueResult.reasonCodes);
|
|
62
|
+
const recovered = options.store.recoverStaleHeadlessExecutionAttempts({
|
|
63
|
+
nowIso,
|
|
64
|
+
staleAfterMs: staleLeaseAfterMs,
|
|
65
|
+
limit: limit * 2,
|
|
66
|
+
});
|
|
67
|
+
if (recovered.recoveredAttemptIds.length > 0) {
|
|
68
|
+
reasonCodes.push(HEADLESS_REASON_CODES.EXECUTION_BACKOFF);
|
|
69
|
+
if (recovered.failedAttemptIds.length > 0)
|
|
70
|
+
reasonCodes.push(HEADLESS_REASON_CODES.EXECUTION_TIMEOUT);
|
|
71
|
+
}
|
|
72
|
+
const allowedAttemptIds = new Set(options.attemptIds ?? []);
|
|
73
|
+
const dueAttempts = options.store
|
|
74
|
+
.listDueHeadlessExecutionAttempts({ nowIso: options.now(), limit: Math.max(limit * 5, 10) })
|
|
75
|
+
.filter((attempt) => attempt.directive_kind === 'run_yolo')
|
|
76
|
+
.filter((attempt) => allowedAttemptIds.size === 0 || allowedAttemptIds.has(attempt.attempt_id))
|
|
77
|
+
.slice(0, limit);
|
|
78
|
+
for (const attempt of dueAttempts) {
|
|
79
|
+
const receipt = await processRunYoloAttempt({
|
|
80
|
+
store: options.store,
|
|
81
|
+
projectRoot: options.projectRoot,
|
|
82
|
+
runnerId: options.runnerId,
|
|
83
|
+
attempt,
|
|
84
|
+
registry,
|
|
85
|
+
now: options.now,
|
|
86
|
+
leaseMs,
|
|
87
|
+
timeoutMs: boundedInteger(options.timeoutMs ?? DEFAULT_HEADLESS_EXECUTION_TIMEOUT_MS, 1_000, 30 * 60 * 1000),
|
|
88
|
+
backoffMs: boundedInteger(options.backoffMs ?? DEFAULT_HEADLESS_EXECUTION_BACKOFF_MS, 1_000, 60 * 60 * 1000),
|
|
89
|
+
maxAttempts,
|
|
90
|
+
adapterOptions: options.adapterOptions,
|
|
91
|
+
runtimeDefaults: options.runtimeDefaults,
|
|
92
|
+
runtimeFallback: options.runtimeFallback,
|
|
93
|
+
idFactory: options.idFactory ?? defaultHeadlessIdFactory,
|
|
94
|
+
});
|
|
95
|
+
receipts.push(receipt);
|
|
96
|
+
reasonCodes.push(receipt.reasonCode);
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
ok: receipts.every((receipt) => receipt.outcome !== 'failed') && enqueueResult.rejectedCount === 0,
|
|
100
|
+
enqueuedAttemptCount: enqueueResult.enqueuedCount,
|
|
101
|
+
dueAttemptCount: dueAttempts.length,
|
|
102
|
+
processedAttemptCount: receipts.filter((receipt) => receipt.outcome !== 'ignored').length,
|
|
103
|
+
recoveredAttemptIds: recovered.recoveredAttemptIds,
|
|
104
|
+
receipts,
|
|
105
|
+
reasonCodes: unique(reasonCodes.length > 0 ? reasonCodes : [HEADLESS_REASON_CODES.OK]),
|
|
106
|
+
publicSafe: true,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
function enqueueRunYoloExecutionDirectives(input) {
|
|
110
|
+
let enqueuedCount = 0;
|
|
111
|
+
let rejectedCount = 0;
|
|
112
|
+
const reasonCodes = [];
|
|
113
|
+
for (const candidate of extractExecutionDirectiveCandidates(input.metadata)) {
|
|
114
|
+
if (!isRecord(candidate) || candidate.kind !== 'run_yolo')
|
|
115
|
+
continue;
|
|
116
|
+
const validation = validateRunYoloExecutionDirective(candidate);
|
|
117
|
+
if (!validation.ok) {
|
|
118
|
+
rejectedCount += 1;
|
|
119
|
+
reasonCodes.push(validation.reasonCode);
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
const directive = validation.directive;
|
|
123
|
+
if (!input.store.jobExists(directive.jobId)) {
|
|
124
|
+
rejectedCount += 1;
|
|
125
|
+
reasonCodes.push(AUTONOMOUS_GOVERNANCE_REASON_CODES.BYPASS_BLOCKED);
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
const directiveHash = hashDirective(directive);
|
|
129
|
+
if (input.store.hasCompletedHeadlessExecutionDirectiveHash(directiveHash)) {
|
|
130
|
+
reasonCodes.push(HEADLESS_REASON_CODES.EXECUTION_COMPLETED);
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
const governanceEnvelope = buildAutonomousGovernanceEnvelope({
|
|
134
|
+
autonomousKind: 'run_yolo',
|
|
135
|
+
source: governanceSourceFromDirective(directive.metadata, 'headless-run-yolo'),
|
|
136
|
+
targetKind: 'story',
|
|
137
|
+
targetRef: directive.targetRef,
|
|
138
|
+
storyId: directive.storyId ?? storyIdFromTargetRef(directive.targetRef),
|
|
139
|
+
jobId: directive.jobId,
|
|
140
|
+
operationSeed: directive.operationId,
|
|
141
|
+
commandHash: hashPublicValue(directive.commandRef),
|
|
142
|
+
});
|
|
143
|
+
const governance = recordAutonomousGovernance(input.store, governanceEnvelope, input.nowIso, { requireExistingJob: true });
|
|
144
|
+
if (!governance.ok) {
|
|
145
|
+
rejectedCount += 1;
|
|
146
|
+
reasonCodes.push(governance.reasonCode);
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
const attemptId = headlessExecutionEntityId('attempt', directive.idempotencyKey);
|
|
150
|
+
const executionId = headlessExecutionEntityId('exec', directive.operationId);
|
|
151
|
+
const result = input.store.enqueueHeadlessExecutionAttempt({
|
|
152
|
+
attemptId,
|
|
153
|
+
executionId,
|
|
154
|
+
jobId: directive.jobId,
|
|
155
|
+
directiveHash,
|
|
156
|
+
directiveKind: 'run_yolo',
|
|
157
|
+
commandClass: directive.commandClass,
|
|
158
|
+
targetKind: 'story',
|
|
159
|
+
targetRef: directive.targetRef,
|
|
160
|
+
storyId: directive.storyId ?? storyIdFromTargetRef(directive.targetRef),
|
|
161
|
+
runtimeId: directive.runtime?.runtimeId,
|
|
162
|
+
modelId: directive.runtime?.modelId,
|
|
163
|
+
runtimeSource: normalizeStoredRuntimeSource(directive.runtime?.source),
|
|
164
|
+
reasonCode: directive.reasonCode,
|
|
165
|
+
publicSummary: directive.publicSummary,
|
|
166
|
+
enqueuedAt: input.nowIso,
|
|
167
|
+
notBeforeAt: input.nowIso,
|
|
168
|
+
maxAttempts: input.maxAttempts,
|
|
169
|
+
queueCap: input.queueCap,
|
|
170
|
+
operationId: `${directive.operationId}:enqueue`,
|
|
171
|
+
idempotencyKey: directive.idempotencyKey,
|
|
172
|
+
counts: { directives: 1 },
|
|
173
|
+
hashes: { directive: directiveHash },
|
|
174
|
+
redactionSummary: directive.redactionSummary,
|
|
175
|
+
relativePaths: [directive.targetRef],
|
|
176
|
+
metadata: autonomousGovernanceMetadata(governanceEnvelope, {
|
|
177
|
+
schemaVersion: 1,
|
|
178
|
+
contractVersion: 'continuity-v1',
|
|
179
|
+
jobId: directive.jobId,
|
|
180
|
+
operationId: directive.operationId,
|
|
181
|
+
reasonCode: directive.reasonCode ?? HEADLESS_REASON_CODES.OK,
|
|
182
|
+
targetRef: directive.targetRef,
|
|
183
|
+
directiveHash,
|
|
184
|
+
...(directive.executionMode ? { executionMode: directive.executionMode } : {}),
|
|
185
|
+
}),
|
|
186
|
+
});
|
|
187
|
+
if (!result.accepted) {
|
|
188
|
+
rejectedCount += 1;
|
|
189
|
+
reasonCodes.push(result.reasonCode ?? 'queue-cap-reached');
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
if (result.inserted)
|
|
193
|
+
enqueuedCount += 1;
|
|
194
|
+
reasonCodes.push(HEADLESS_REASON_CODES.OK);
|
|
195
|
+
}
|
|
196
|
+
return { enqueuedCount, rejectedCount, reasonCodes: unique(reasonCodes) };
|
|
197
|
+
}
|
|
198
|
+
async function processRunYoloAttempt(input) {
|
|
199
|
+
const claimedAt = input.now();
|
|
200
|
+
const leaseId = input.idFactory('lease', input.attempt.attempt_id);
|
|
201
|
+
const leaseExpiresAt = addMilliseconds(claimedAt, input.leaseMs);
|
|
202
|
+
const claim = input.store.claimHeadlessExecutionAttempt({
|
|
203
|
+
attemptId: input.attempt.attempt_id,
|
|
204
|
+
leaseId,
|
|
205
|
+
runnerId: input.runnerId,
|
|
206
|
+
claimedAt,
|
|
207
|
+
leaseExpiresAt,
|
|
208
|
+
reasonCode: HEADLESS_REASON_CODES.OK,
|
|
209
|
+
});
|
|
210
|
+
if (!claim.inserted) {
|
|
211
|
+
return {
|
|
212
|
+
attemptId: input.attempt.attempt_id,
|
|
213
|
+
executionId: input.attempt.execution_id,
|
|
214
|
+
jobId: input.attempt.job_id,
|
|
215
|
+
status: input.attempt.status,
|
|
216
|
+
outcome: 'ignored',
|
|
217
|
+
reasonCode: 'lease-conflict',
|
|
218
|
+
timestamp: claimedAt,
|
|
219
|
+
redactionSummary: [],
|
|
220
|
+
publicSafe: true,
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
const duplicateCompletion = input.store.hasCompletedHeadlessExecutionDirectiveHash(input.attempt.directive_hash, input.attempt.attempt_id);
|
|
224
|
+
if (duplicateCompletion) {
|
|
225
|
+
return persistAttemptOutcome(input.store, input.attempt, {
|
|
226
|
+
leaseId,
|
|
227
|
+
runnerId: input.runnerId,
|
|
228
|
+
status: 'skipped',
|
|
229
|
+
receiptStatus: 'ignored',
|
|
230
|
+
reasonCode: HEADLESS_REASON_CODES.EXECUTION_COMPLETED,
|
|
231
|
+
publicSummary: 'Skipped duplicate run_yolo directive because the directive hash is already completed.',
|
|
232
|
+
completedAt: input.now(),
|
|
233
|
+
counts: { duplicateDirectiveHashes: 1 },
|
|
234
|
+
hashes: { directive: input.attempt.directive_hash },
|
|
235
|
+
redactionSummary: [],
|
|
236
|
+
relativePaths: [input.attempt.target_ref],
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
const preparation = prepareAttemptInput(input);
|
|
240
|
+
if (!preparation.ok) {
|
|
241
|
+
return persistAttemptOutcome(input.store, input.attempt, {
|
|
242
|
+
leaseId,
|
|
243
|
+
runnerId: input.runnerId,
|
|
244
|
+
status: preparation.status,
|
|
245
|
+
receiptStatus: preparation.receiptStatus,
|
|
246
|
+
reasonCode: preparation.reasonCode,
|
|
247
|
+
publicSummary: preparation.publicSummary,
|
|
248
|
+
completedAt: input.now(),
|
|
249
|
+
counts: { rejectedDirectives: 1 },
|
|
250
|
+
hashes: { directive: input.attempt.directive_hash },
|
|
251
|
+
redactionSummary: preparation.redactionSummary,
|
|
252
|
+
relativePaths: safeAttemptRelativePaths(input.attempt),
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
const adapterLookup = input.registry.getAdapter(preparation.input.runtimeId);
|
|
256
|
+
if (!adapterLookup.ok) {
|
|
257
|
+
return persistAttemptOutcome(input.store, input.attempt, {
|
|
258
|
+
leaseId,
|
|
259
|
+
runnerId: input.runnerId,
|
|
260
|
+
status: 'failed',
|
|
261
|
+
receiptStatus: 'failed',
|
|
262
|
+
reasonCode: adapterLookup.reasonCode,
|
|
263
|
+
publicSummary: adapterLookup.publicSummary,
|
|
264
|
+
completedAt: input.now(),
|
|
265
|
+
counts: { rejectedAdapters: 1 },
|
|
266
|
+
hashes: { directive: input.attempt.directive_hash },
|
|
267
|
+
redactionSummary: adapterLookup.redactionSummary,
|
|
268
|
+
relativePaths: [input.attempt.target_ref],
|
|
269
|
+
runtimeId: preparation.input.runtimeId,
|
|
270
|
+
modelId: preparation.input.modelId,
|
|
271
|
+
runtimeSource: preparation.input.runtimeSource,
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
let adapterResult;
|
|
275
|
+
try {
|
|
276
|
+
adapterResult = await adapterLookup.adapter.execute(preparation.input, {
|
|
277
|
+
...input.adapterOptions,
|
|
278
|
+
cwd: input.adapterOptions?.cwd ?? input.projectRoot,
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
catch {
|
|
282
|
+
adapterResult = {
|
|
283
|
+
status: 'failed',
|
|
284
|
+
adapterId: preparation.input.runtimeId,
|
|
285
|
+
runtimeId: preparation.input.runtimeId,
|
|
286
|
+
...(preparation.input.modelId ? { modelId: preparation.input.modelId } : {}),
|
|
287
|
+
...(preparation.input.runtimeSource ? { runtimeSource: preparation.input.runtimeSource } : {}),
|
|
288
|
+
reasonCode: HEADLESS_REASON_CODES.EXECUTION_FAILED,
|
|
289
|
+
reasonCodes: [HEADLESS_REASON_CODES.EXECUTION_FAILED, HEADLESS_REASON_CODES.RECEIPT_REDACTED],
|
|
290
|
+
exitCode: 1,
|
|
291
|
+
signal: null,
|
|
292
|
+
durationMs: 0,
|
|
293
|
+
counts: { adapterExceptions: 1 },
|
|
294
|
+
hashes: { directive: input.attempt.directive_hash },
|
|
295
|
+
publicSummary: 'Headless adapter failed with public-safe exception summary.',
|
|
296
|
+
redactionSummary: [redaction('adapter', 'raw_log', 'value-denied')],
|
|
297
|
+
relativePaths: [input.attempt.target_ref],
|
|
298
|
+
receipt: preparation.input.receipt,
|
|
299
|
+
publicSafe: true,
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
const retry = retryDecision(input.attempt, adapterResult, input.maxAttempts, input.backoffMs, input.now());
|
|
303
|
+
const status = retry.retry ? 'backoff' : adapterResult.status;
|
|
304
|
+
const reasonCode = retry.retry ? HEADLESS_REASON_CODES.EXECUTION_BACKOFF : adapterResult.reasonCode;
|
|
305
|
+
const receiptStatus = status === 'completed' ? 'applied' : status === 'backoff' ? 'deferred' : status === 'skipped' ? 'ignored' : 'failed';
|
|
306
|
+
return persistAttemptOutcome(input.store, input.attempt, {
|
|
307
|
+
leaseId,
|
|
308
|
+
runnerId: input.runnerId,
|
|
309
|
+
status,
|
|
310
|
+
receiptStatus,
|
|
311
|
+
reasonCode,
|
|
312
|
+
publicSummary: retry.retry
|
|
313
|
+
? 'Headless run_yolo execution scheduled bounded retry after transient adapter outcome.'
|
|
314
|
+
: adapterResult.publicSummary,
|
|
315
|
+
completedAt: input.now(),
|
|
316
|
+
durationMs: adapterResult.durationMs,
|
|
317
|
+
notBeforeAt: retry.notBeforeAt,
|
|
318
|
+
retryCount: retry.retryCount,
|
|
319
|
+
counts: adapterResult.counts,
|
|
320
|
+
hashes: { ...adapterResult.hashes, directive: input.attempt.directive_hash },
|
|
321
|
+
redactionSummary: adapterResult.redactionSummary,
|
|
322
|
+
relativePaths: adapterResult.relativePaths.length > 0 ? adapterResult.relativePaths : [input.attempt.target_ref],
|
|
323
|
+
runtimeId: adapterResult.runtimeId,
|
|
324
|
+
modelId: adapterResult.modelId,
|
|
325
|
+
runtimeSource: adapterResult.runtimeSource,
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
function prepareAttemptInput(input) {
|
|
329
|
+
const governance = readAutonomousGovernanceEnvelopeFromMetadata(input.attempt.metadata_json, {
|
|
330
|
+
autonomousKind: 'run_yolo',
|
|
331
|
+
jobId: input.attempt.job_id,
|
|
332
|
+
targetKind: 'story',
|
|
333
|
+
targetRef: input.attempt.target_ref,
|
|
334
|
+
});
|
|
335
|
+
if (!governance.ok) {
|
|
336
|
+
return {
|
|
337
|
+
ok: false,
|
|
338
|
+
status: 'failed',
|
|
339
|
+
receiptStatus: 'failed',
|
|
340
|
+
reasonCode: HEADLESS_REASON_CODES.DIRECTIVE_REJECTED,
|
|
341
|
+
publicSummary: governance.publicSummary,
|
|
342
|
+
redactionSummary: governance.redactionSummary,
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
const directCommandHash = hashPublicValue(`*yolo @${input.attempt.target_ref}`);
|
|
346
|
+
const branchlessCommandHash = hashPublicValue(`*yolo @${input.attempt.target_ref} branchless-preparation`);
|
|
347
|
+
const branchlessPreparation = governance.envelope.hashes.command === branchlessCommandHash;
|
|
348
|
+
if (!branchlessPreparation && governance.envelope.hashes.command !== directCommandHash) {
|
|
349
|
+
return {
|
|
350
|
+
ok: false,
|
|
351
|
+
status: 'failed',
|
|
352
|
+
receiptStatus: 'failed',
|
|
353
|
+
reasonCode: HEADLESS_REASON_CODES.DIRECTIVE_REJECTED,
|
|
354
|
+
publicSummary: 'Headless run_yolo governance command does not match an authorized execution mode.',
|
|
355
|
+
redactionSummary: [redaction('autonomousGovernance.commandHash', 'prompt_body', 'operation-denied')],
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
const promptValidation = validateRunYoloAttemptShape(input.attempt);
|
|
359
|
+
if (!promptValidation.ok)
|
|
360
|
+
return promptValidation;
|
|
361
|
+
const runtime = resolveAttemptRuntime(input);
|
|
362
|
+
if (!runtime.ok) {
|
|
363
|
+
return {
|
|
364
|
+
ok: false,
|
|
365
|
+
status: 'failed',
|
|
366
|
+
receiptStatus: 'failed',
|
|
367
|
+
reasonCode: runtime.reasonCode,
|
|
368
|
+
publicSummary: runtime.publicSummary,
|
|
369
|
+
redactionSummary: runtime.redactionSummary,
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
return {
|
|
373
|
+
ok: true,
|
|
374
|
+
input: {
|
|
375
|
+
promptKind: branchlessPreparation ? 'yolo-branchless-preparation' : 'yolo',
|
|
376
|
+
targetKind: 'story',
|
|
377
|
+
targetRef: input.attempt.target_ref,
|
|
378
|
+
...(input.attempt.story_id ? { storyId: input.attempt.story_id } : {}),
|
|
379
|
+
runtimeId: runtime.runtimeId,
|
|
380
|
+
...(runtime.modelId ? { modelId: runtime.modelId } : {}),
|
|
381
|
+
runtimeSource: runtime.runtimeSource,
|
|
382
|
+
timeoutMs: input.timeoutMs,
|
|
383
|
+
receipt: {
|
|
384
|
+
attemptId: input.attempt.attempt_id,
|
|
385
|
+
subagentId: input.attempt.attempt_id,
|
|
386
|
+
executionId: input.attempt.execution_id,
|
|
387
|
+
jobId: input.attempt.job_id,
|
|
388
|
+
operationId: input.attempt.execution_id,
|
|
389
|
+
idempotencyKey: input.attempt.directive_hash,
|
|
390
|
+
runnerId: input.runnerId,
|
|
391
|
+
},
|
|
392
|
+
publicSummary: boundPublicSummary(input.attempt.public_summary ?? 'Headless run_yolo execution attempt.'),
|
|
393
|
+
publicSafe: true,
|
|
394
|
+
},
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
function resolveAttemptRuntime(input) {
|
|
398
|
+
const defaults = input.runtimeDefaults !== undefined
|
|
399
|
+
? input.runtimeDefaults
|
|
400
|
+
: loadHeadlessRuntimeDefaults({ projectRoot: input.projectRoot });
|
|
401
|
+
if (isRecord(defaults) && defaults.ok === false) {
|
|
402
|
+
return {
|
|
403
|
+
ok: false,
|
|
404
|
+
reasonCode: HEADLESS_REASON_CODES.RUNTIME_UNTRUSTED,
|
|
405
|
+
publicSummary: typeof defaults.publicSummary === 'string' ? defaults.publicSummary : 'Headless runtime defaults failed public-safety validation.',
|
|
406
|
+
redactionSummary: Array.isArray(defaults.redactionSummary) ? defaults.redactionSummary : [],
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
const source = normalizeRuntimeSource(input.attempt.runtime_source) ?? 'explicit';
|
|
410
|
+
const hint = (input.attempt.runtime_id || input.attempt.model_id)
|
|
411
|
+
? {
|
|
412
|
+
...(input.attempt.runtime_id ? { runtimeId: input.attempt.runtime_id } : {}),
|
|
413
|
+
...(input.attempt.model_id ? { modelId: input.attempt.model_id } : {}),
|
|
414
|
+
source,
|
|
415
|
+
publicSafe: true,
|
|
416
|
+
}
|
|
417
|
+
: undefined;
|
|
418
|
+
const resolutionInput = {
|
|
419
|
+
registry: input.registry,
|
|
420
|
+
defaults,
|
|
421
|
+
fallback: input.runtimeFallback,
|
|
422
|
+
};
|
|
423
|
+
if (hint) {
|
|
424
|
+
if (source === 'origin')
|
|
425
|
+
resolutionInput.origin = hint;
|
|
426
|
+
else if (source === 'default')
|
|
427
|
+
resolutionInput.projectDefault = hint;
|
|
428
|
+
else if (source === 'fallback')
|
|
429
|
+
resolutionInput.fallback = hint;
|
|
430
|
+
else
|
|
431
|
+
resolutionInput.explicit = hint;
|
|
432
|
+
}
|
|
433
|
+
const resolution = resolveHeadlessRuntime(resolutionInput);
|
|
434
|
+
if (!resolution.ok) {
|
|
435
|
+
return {
|
|
436
|
+
ok: false,
|
|
437
|
+
reasonCode: resolution.reasonCode,
|
|
438
|
+
publicSummary: resolution.publicSummary,
|
|
439
|
+
redactionSummary: resolution.redactionSummary,
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
return {
|
|
443
|
+
ok: true,
|
|
444
|
+
runtimeId: resolution.runtimeId,
|
|
445
|
+
...(resolution.modelId ? { modelId: resolution.modelId } : {}),
|
|
446
|
+
runtimeSource: resolution.runtimeSource,
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
function validateRunYoloAttemptShape(attempt) {
|
|
450
|
+
const redactions = [];
|
|
451
|
+
if (attempt.directive_kind !== 'run_yolo')
|
|
452
|
+
redactions.push(redaction('directiveKind', 'unsafe_key', 'value-denied'));
|
|
453
|
+
if (attempt.target_kind !== 'story')
|
|
454
|
+
redactions.push(redaction('targetKind', 'prompt_body', 'value-denied'));
|
|
455
|
+
if (!STORY_TARGET_PATTERN.test(attempt.target_ref) || SHELL_FRAGMENT_PATTERN.test(attempt.target_ref) || UNSAFE_VALUE_PATTERN.test(attempt.target_ref)) {
|
|
456
|
+
redactions.push(redaction('targetRef', 'prompt_body', 'value-denied'));
|
|
457
|
+
}
|
|
458
|
+
const storyId = storyIdFromTargetRef(attempt.target_ref);
|
|
459
|
+
if (attempt.story_id && attempt.story_id !== storyId)
|
|
460
|
+
redactions.push(redaction('storyId', 'prompt_body', 'value-denied'));
|
|
461
|
+
if (redactions.length > 0) {
|
|
462
|
+
return {
|
|
463
|
+
ok: false,
|
|
464
|
+
status: 'failed',
|
|
465
|
+
receiptStatus: 'failed',
|
|
466
|
+
reasonCode: HEADLESS_REASON_CODES.PROMPT_REJECTED,
|
|
467
|
+
publicSummary: 'Headless run_yolo attempt did not match the canonical public story prompt shape.',
|
|
468
|
+
redactionSummary: redactions,
|
|
469
|
+
};
|
|
470
|
+
}
|
|
471
|
+
return {
|
|
472
|
+
ok: true,
|
|
473
|
+
input: {
|
|
474
|
+
promptKind: 'yolo',
|
|
475
|
+
targetKind: 'story',
|
|
476
|
+
targetRef: attempt.target_ref,
|
|
477
|
+
...(attempt.story_id ? { storyId: attempt.story_id } : {}),
|
|
478
|
+
runtimeId: 'fake',
|
|
479
|
+
publicSafe: true,
|
|
480
|
+
},
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
function validateRunYoloExecutionDirective(input) {
|
|
484
|
+
const redactions = [];
|
|
485
|
+
for (const key of Object.keys(input)) {
|
|
486
|
+
if (!EXECUTION_DIRECTIVE_ALLOWED_KEYS.has(key) || UNSAFE_KEY_PATTERN.test(key)) {
|
|
487
|
+
redactions.push(redaction(key, unsafeKeyReason(key), 'key-denied'));
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
if (input.publicSafe !== true)
|
|
491
|
+
redactions.push(redaction('publicSafe', 'unsafe_key', 'value-denied'));
|
|
492
|
+
const kind = stringField(input, 'kind');
|
|
493
|
+
const commandClass = stringField(input, 'commandClass');
|
|
494
|
+
const jobId = stringField(input, 'jobId');
|
|
495
|
+
const operationId = stringField(input, 'operationId');
|
|
496
|
+
const idempotencyKey = stringField(input, 'idempotencyKey');
|
|
497
|
+
const targetKind = stringField(input, 'targetKind');
|
|
498
|
+
const targetRef = stringField(input, 'targetRef');
|
|
499
|
+
const commandRef = stringField(input, 'commandRef');
|
|
500
|
+
const publicSummary = stringField(input, 'publicSummary');
|
|
501
|
+
const storyId = stringField(input, 'storyId');
|
|
502
|
+
const executionMode = stringField(input, 'executionMode');
|
|
503
|
+
if (kind !== 'run_yolo')
|
|
504
|
+
redactions.push(redaction('kind', 'unsafe_key', 'value-denied'));
|
|
505
|
+
if (commandClass !== 'goal-tick' && commandClass !== 'loop-tick')
|
|
506
|
+
redactions.push(redaction('commandClass', 'unsafe_key', 'value-denied'));
|
|
507
|
+
if (!isSafeIdentifier(jobId))
|
|
508
|
+
redactions.push(redaction('jobId', 'unsafe_key', 'value-denied'));
|
|
509
|
+
if (!isSafeIdentifier(operationId))
|
|
510
|
+
redactions.push(redaction('operationId', 'unsafe_key', 'value-denied'));
|
|
511
|
+
if (!isSafeIdentifier(idempotencyKey))
|
|
512
|
+
redactions.push(redaction('idempotencyKey', 'unsafe_key', 'value-denied'));
|
|
513
|
+
if (targetKind !== 'story' || !targetRef || !STORY_TARGET_PATTERN.test(targetRef) || UNSAFE_VALUE_PATTERN.test(targetRef)) {
|
|
514
|
+
redactions.push(redaction('targetRef', 'prompt_body', 'value-denied'));
|
|
515
|
+
}
|
|
516
|
+
if (executionMode !== undefined && executionMode !== 'branchless_child_preparation') {
|
|
517
|
+
redactions.push(redaction('executionMode', 'unsafe_key', 'value-denied'));
|
|
518
|
+
}
|
|
519
|
+
const metadata = isRecord(input.metadata) ? input.metadata : undefined;
|
|
520
|
+
const branchlessPreparation = executionMode === 'branchless_child_preparation';
|
|
521
|
+
if (branchlessPreparation && (metadata?.governanceSource !== 'delegated-subagent'
|
|
522
|
+
|| metadata.childWorkspace !== 'branchless_sandbox'
|
|
523
|
+
|| metadata.integrationOwner !== 'root_agent'
|
|
524
|
+
|| metadata.maxDepth !== 1
|
|
525
|
+
|| typeof metadata.graphRevision !== 'string'
|
|
526
|
+
|| !/^[a-f0-9]{64}$/.test(metadata.graphRevision))) {
|
|
527
|
+
redactions.push(redaction('executionMode', 'unsafe_key', 'value-denied'));
|
|
528
|
+
}
|
|
529
|
+
const expectedCommandRef = targetRef
|
|
530
|
+
? `*yolo @${targetRef}${branchlessPreparation ? ' branchless-preparation' : ''}`
|
|
531
|
+
: undefined;
|
|
532
|
+
if (!commandRef || commandRef !== expectedCommandRef || commandRef.includes('@neocortex') || SHELL_FRAGMENT_PATTERN.test(commandRef) || UNSAFE_VALUE_PATTERN.test(commandRef)) {
|
|
533
|
+
redactions.push(redaction('commandRef', 'prompt_body', 'value-denied'));
|
|
534
|
+
}
|
|
535
|
+
if (storyId && targetRef && storyId !== storyIdFromTargetRef(targetRef))
|
|
536
|
+
redactions.push(redaction('storyId', 'prompt_body', 'value-denied'));
|
|
537
|
+
if (!publicSummary || publicSummary.length > 240 || UNSAFE_VALUE_PATTERN.test(publicSummary)) {
|
|
538
|
+
redactions.push(redaction('publicSummary', 'unbounded_text', 'value-denied'));
|
|
539
|
+
}
|
|
540
|
+
if (input.reasonCode !== undefined && (typeof input.reasonCode !== 'string' || UNSAFE_VALUE_PATTERN.test(input.reasonCode))) {
|
|
541
|
+
redactions.push(redaction('reasonCode', 'unsafe_key', 'value-denied'));
|
|
542
|
+
}
|
|
543
|
+
const runtime = validateDirectiveRuntime(input.runtime, redactions);
|
|
544
|
+
if (input.attempts !== undefined)
|
|
545
|
+
assertPublicSafeCandidate(input.attempts, 'attempts', redactions);
|
|
546
|
+
if (input.metadata !== undefined)
|
|
547
|
+
assertPublicSafeCandidate(input.metadata, 'metadata', redactions);
|
|
548
|
+
const redactionSummary = validateDirectiveRedactions(input.redactionSummary, redactions);
|
|
549
|
+
if (redactions.length > 0 || kind !== 'run_yolo' || !commandClass || !jobId || !operationId || !idempotencyKey || !targetRef || !commandRef || !publicSummary) {
|
|
550
|
+
const promptRejected = redactions.some((item) => item.reason === 'prompt_body');
|
|
551
|
+
return {
|
|
552
|
+
ok: false,
|
|
553
|
+
reasonCode: promptRejected ? HEADLESS_REASON_CODES.PROMPT_REJECTED : HEADLESS_REASON_CODES.DIRECTIVE_REJECTED,
|
|
554
|
+
redactionSummary: redactions,
|
|
555
|
+
};
|
|
556
|
+
}
|
|
557
|
+
return {
|
|
558
|
+
ok: true,
|
|
559
|
+
directive: {
|
|
560
|
+
kind: 'run_yolo',
|
|
561
|
+
commandClass: commandClass,
|
|
562
|
+
jobId: jobId,
|
|
563
|
+
operationId: operationId,
|
|
564
|
+
idempotencyKey: idempotencyKey,
|
|
565
|
+
targetKind: 'story',
|
|
566
|
+
targetRef: targetRef,
|
|
567
|
+
commandRef: commandRef,
|
|
568
|
+
...(storyId ? { storyId } : {}),
|
|
569
|
+
...(branchlessPreparation ? { executionMode: 'branchless_child_preparation' } : {}),
|
|
570
|
+
...(runtime ? { runtime } : {}),
|
|
571
|
+
publicSummary: publicSummary,
|
|
572
|
+
...(typeof input.reasonCode === 'string' ? { reasonCode: input.reasonCode } : {}),
|
|
573
|
+
...(metadata ? { metadata } : {}),
|
|
574
|
+
...(redactionSummary.length > 0 ? { redactionSummary } : {}),
|
|
575
|
+
publicSafe: true,
|
|
576
|
+
},
|
|
577
|
+
};
|
|
578
|
+
}
|
|
579
|
+
function governanceSourceFromDirective(metadata, fallback) {
|
|
580
|
+
return metadata?.governanceSource === 'delegated-subagent' ? 'delegated-subagent' : fallback;
|
|
581
|
+
}
|
|
582
|
+
function validateDirectiveRuntime(value, redactions) {
|
|
583
|
+
if (value === undefined)
|
|
584
|
+
return undefined;
|
|
585
|
+
if (!isRecord(value)) {
|
|
586
|
+
redactions.push(redaction('runtime', 'unsafe_key', 'value-denied'));
|
|
587
|
+
return undefined;
|
|
588
|
+
}
|
|
589
|
+
for (const key of Object.keys(value)) {
|
|
590
|
+
if (!RUNTIME_ALLOWED_KEYS.has(key) || UNSAFE_KEY_PATTERN.test(key))
|
|
591
|
+
redactions.push(redaction(`runtime.${key}`, unsafeKeyReason(key), 'key-denied'));
|
|
592
|
+
}
|
|
593
|
+
if (value.publicSafe !== true)
|
|
594
|
+
redactions.push(redaction('runtime.publicSafe', 'unsafe_key', 'value-denied'));
|
|
595
|
+
const runtimeId = stringField(value, 'runtimeId');
|
|
596
|
+
const modelId = stringField(value, 'modelId');
|
|
597
|
+
const source = stringField(value, 'source');
|
|
598
|
+
if (runtimeId && (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,79}$/.test(runtimeId) || UNSAFE_VALUE_PATTERN.test(runtimeId) || SHELL_FRAGMENT_PATTERN.test(runtimeId))) {
|
|
599
|
+
redactions.push(redaction('runtime.runtimeId', 'unsafe_key', 'value-denied'));
|
|
600
|
+
}
|
|
601
|
+
if (modelId && (!/^[A-Za-z0-9][A-Za-z0-9._:+/-]{0,119}$/.test(modelId) || UNSAFE_VALUE_PATTERN.test(modelId) || SHELL_FRAGMENT_PATTERN.test(modelId))) {
|
|
602
|
+
redactions.push(redaction('runtime.modelId', 'unsafe_key', 'value-denied'));
|
|
603
|
+
}
|
|
604
|
+
if (source !== undefined && source !== 'explicit' && source !== 'origin' && source !== 'default' && source !== 'fallback' && source !== 'unspecified') {
|
|
605
|
+
redactions.push(redaction('runtime.source', 'unsafe_key', 'value-denied'));
|
|
606
|
+
}
|
|
607
|
+
if (value.reasonCode !== undefined && (typeof value.reasonCode !== 'string' || UNSAFE_VALUE_PATTERN.test(value.reasonCode))) {
|
|
608
|
+
redactions.push(redaction('runtime.reasonCode', 'unsafe_key', 'value-denied'));
|
|
609
|
+
}
|
|
610
|
+
if (value.publicSafe !== true)
|
|
611
|
+
return undefined;
|
|
612
|
+
return {
|
|
613
|
+
...(runtimeId ? { runtimeId } : {}),
|
|
614
|
+
...(modelId ? { modelId } : {}),
|
|
615
|
+
...(source === 'explicit' || source === 'origin' || source === 'default' || source === 'fallback' || source === 'unspecified' ? { source } : {}),
|
|
616
|
+
...(typeof value.reasonCode === 'string' ? { reasonCode: value.reasonCode } : {}),
|
|
617
|
+
publicSafe: true,
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
function persistAttemptOutcome(store, attempt, outcome) {
|
|
621
|
+
const redactionSummary = outcome.redactionSummary ?? [];
|
|
622
|
+
const relativePaths = outcome.relativePaths ?? safeAttemptRelativePaths(attempt);
|
|
623
|
+
const counts = sanitizePublicRecord(outcome.counts);
|
|
624
|
+
const hashes = sanitizePublicRecord(outcome.hashes);
|
|
625
|
+
const outcomeMetadata = {
|
|
626
|
+
schemaVersion: 1,
|
|
627
|
+
contractVersion: 'continuity-v1',
|
|
628
|
+
attemptId: attempt.attempt_id,
|
|
629
|
+
executionId: attempt.execution_id,
|
|
630
|
+
jobId: attempt.job_id,
|
|
631
|
+
directiveHash: attempt.directive_hash,
|
|
632
|
+
status: outcome.status,
|
|
633
|
+
reasonCode: outcome.reasonCode,
|
|
634
|
+
...(outcome.runtimeId ? { runtimeId: outcome.runtimeId } : {}),
|
|
635
|
+
...(outcome.modelId ? { modelId: outcome.modelId } : {}),
|
|
636
|
+
...(outcome.runtimeSource ? { runtimeSource: outcome.runtimeSource } : {}),
|
|
637
|
+
...(outcome.retryCount !== undefined ? { retryCount: outcome.retryCount } : {}),
|
|
638
|
+
...(outcome.reasonCode === AUTONOMOUS_GOVERNANCE_REASON_CODES.BYPASS_BLOCKED ? { governanceEvidence: AUTONOMOUS_GOVERNANCE_EVIDENCE_TAG } : {}),
|
|
639
|
+
publicSummary: boundPublicSummary(outcome.publicSummary),
|
|
640
|
+
};
|
|
641
|
+
const governance = readAutonomousGovernanceEnvelopeFromMetadata(attempt.metadata_json, {
|
|
642
|
+
autonomousKind: 'run_yolo',
|
|
643
|
+
jobId: attempt.job_id,
|
|
644
|
+
targetKind: 'story',
|
|
645
|
+
targetRef: attempt.target_ref,
|
|
646
|
+
});
|
|
647
|
+
// Backoff reuses the same attempt row. Preserve only its already-validated,
|
|
648
|
+
// public-safe authority envelope so retry preparation remains fail-closed
|
|
649
|
+
// without converting a recoverable execution boundary into a rejection.
|
|
650
|
+
const metadata = governance.ok
|
|
651
|
+
? autonomousGovernanceMetadata(governance.envelope, outcomeMetadata)
|
|
652
|
+
: outcomeMetadata;
|
|
653
|
+
store.completeHeadlessExecutionAttempt({
|
|
654
|
+
attemptId: attempt.attempt_id,
|
|
655
|
+
executionId: attempt.execution_id,
|
|
656
|
+
jobId: attempt.job_id,
|
|
657
|
+
leaseId: outcome.leaseId,
|
|
658
|
+
runnerId: outcome.runnerId,
|
|
659
|
+
status: outcome.status,
|
|
660
|
+
completedAt: outcome.completedAt,
|
|
661
|
+
durationMs: outcome.durationMs,
|
|
662
|
+
reasonCode: outcome.reasonCode,
|
|
663
|
+
publicSummary: boundPublicSummary(outcome.publicSummary),
|
|
664
|
+
notBeforeAt: outcome.notBeforeAt,
|
|
665
|
+
retryCount: outcome.retryCount,
|
|
666
|
+
counts,
|
|
667
|
+
hashes,
|
|
668
|
+
redactionSummary,
|
|
669
|
+
relativePaths,
|
|
670
|
+
metadata,
|
|
671
|
+
});
|
|
672
|
+
store.recordHeadlessExecutionReceipt({
|
|
673
|
+
receiptId: `receipt-${safeEntityId('headless', `${attempt.attempt_id}-${outcome.status}`)}`,
|
|
674
|
+
attemptId: attempt.attempt_id,
|
|
675
|
+
executionId: attempt.execution_id,
|
|
676
|
+
jobId: attempt.job_id,
|
|
677
|
+
status: outcome.receiptStatus,
|
|
678
|
+
reasonCode: outcome.reasonCode,
|
|
679
|
+
createdAt: outcome.completedAt,
|
|
680
|
+
operationId: `${attempt.execution_id}:${outcome.status}:receipt`,
|
|
681
|
+
idempotencyKey: `${attempt.directive_hash}:${outcome.status}:receipt`,
|
|
682
|
+
counts,
|
|
683
|
+
hashes,
|
|
684
|
+
redactionSummary,
|
|
685
|
+
relativePaths,
|
|
686
|
+
metadata,
|
|
687
|
+
});
|
|
688
|
+
store.recordHeadlessExecutionSummary({
|
|
689
|
+
eventId: `event-${safeEntityId('headless-summary', `${attempt.attempt_id}-${outcome.status}`)}`,
|
|
690
|
+
attemptId: attempt.attempt_id,
|
|
691
|
+
executionId: attempt.execution_id,
|
|
692
|
+
jobId: attempt.job_id,
|
|
693
|
+
status: outcome.status,
|
|
694
|
+
runtimeId: outcome.runtimeId,
|
|
695
|
+
modelId: outcome.modelId,
|
|
696
|
+
publicSummary: boundPublicSummary(outcome.publicSummary),
|
|
697
|
+
reasonCode: outcome.reasonCode,
|
|
698
|
+
createdAt: outcome.completedAt,
|
|
699
|
+
durationMs: outcome.durationMs,
|
|
700
|
+
counts,
|
|
701
|
+
hashes,
|
|
702
|
+
redactionSummary,
|
|
703
|
+
relativePaths,
|
|
704
|
+
metadata,
|
|
705
|
+
});
|
|
706
|
+
return {
|
|
707
|
+
attemptId: attempt.attempt_id,
|
|
708
|
+
executionId: attempt.execution_id,
|
|
709
|
+
jobId: attempt.job_id,
|
|
710
|
+
status: outcome.status,
|
|
711
|
+
outcome: outcome.receiptStatus,
|
|
712
|
+
reasonCode: outcome.reasonCode,
|
|
713
|
+
timestamp: outcome.completedAt,
|
|
714
|
+
redactionSummary,
|
|
715
|
+
publicSafe: true,
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
function retryDecision(attempt, result, maxAttempts, backoffMs, nowIso) {
|
|
719
|
+
const transient = result.status === 'timed_out'
|
|
720
|
+
|| result.reasonCode === HEADLESS_REASON_CODES.EXECUTION_FAILED
|
|
721
|
+
|| result.reasonCode === HEADLESS_REASON_CODES.ADAPTER_UNAVAILABLE;
|
|
722
|
+
if (!transient)
|
|
723
|
+
return { retry: false };
|
|
724
|
+
const retryCount = attempt.retry_count + 1;
|
|
725
|
+
if (retryCount >= Math.max(1, attempt.max_attempts || maxAttempts))
|
|
726
|
+
return { retry: false, retryCount };
|
|
727
|
+
const multiplier = Math.min(8, 2 ** Math.max(0, attempt.retry_count));
|
|
728
|
+
return {
|
|
729
|
+
retry: true,
|
|
730
|
+
retryCount,
|
|
731
|
+
notBeforeAt: addMilliseconds(nowIso, backoffMs * multiplier),
|
|
732
|
+
};
|
|
733
|
+
}
|
|
734
|
+
function extractExecutionDirectiveCandidates(metadata) {
|
|
735
|
+
const records = Array.isArray(metadata) ? metadata : metadata ? [metadata] : [];
|
|
736
|
+
const directives = [];
|
|
737
|
+
for (const record of records) {
|
|
738
|
+
const value = record.continuityExecutionDirectives;
|
|
739
|
+
if (Array.isArray(value))
|
|
740
|
+
directives.push(...value);
|
|
741
|
+
}
|
|
742
|
+
return directives;
|
|
743
|
+
}
|
|
744
|
+
function hashDirective(directive) {
|
|
745
|
+
return hashPublicValue(stableJson({
|
|
746
|
+
kind: directive.kind,
|
|
747
|
+
commandClass: directive.commandClass,
|
|
748
|
+
jobId: directive.jobId,
|
|
749
|
+
targetRef: directive.targetRef,
|
|
750
|
+
commandRef: directive.commandRef,
|
|
751
|
+
storyId: directive.storyId,
|
|
752
|
+
executionMode: directive.executionMode,
|
|
753
|
+
runtime: directive.runtime,
|
|
754
|
+
}));
|
|
755
|
+
}
|
|
756
|
+
function stableJson(value) {
|
|
757
|
+
if (Array.isArray(value))
|
|
758
|
+
return `[${value.map(stableJson).join(',')}]`;
|
|
759
|
+
if (isRecord(value)) {
|
|
760
|
+
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`).join(',')}}`;
|
|
761
|
+
}
|
|
762
|
+
return JSON.stringify(value);
|
|
763
|
+
}
|
|
764
|
+
function assertPublicSafeCandidate(value, path, redactions) {
|
|
765
|
+
if (typeof value === 'string') {
|
|
766
|
+
if (UNSAFE_VALUE_PATTERN.test(value) || SHELL_FRAGMENT_PATTERN.test(value))
|
|
767
|
+
redactions.push(redaction(path, unsafeKeyReason(path), 'value-denied'));
|
|
768
|
+
return;
|
|
769
|
+
}
|
|
770
|
+
if (value === undefined || value === null || typeof value === 'number' || typeof value === 'boolean')
|
|
771
|
+
return;
|
|
772
|
+
if (Array.isArray(value)) {
|
|
773
|
+
value.forEach((item, index) => assertPublicSafeCandidate(item, `${path}.${index}`, redactions));
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
if (isRecord(value)) {
|
|
777
|
+
for (const [key, child] of Object.entries(value)) {
|
|
778
|
+
const field = `${path}.${key}`;
|
|
779
|
+
if (UNSAFE_KEY_PATTERN.test(key))
|
|
780
|
+
redactions.push(redaction(field, unsafeKeyReason(key), 'key-denied'));
|
|
781
|
+
assertPublicSafeCandidate(child, field, redactions);
|
|
782
|
+
}
|
|
783
|
+
return;
|
|
784
|
+
}
|
|
785
|
+
redactions.push(redaction(path, 'unsafe_key', 'value-denied'));
|
|
786
|
+
}
|
|
787
|
+
function validateDirectiveRedactions(value, redactions) {
|
|
788
|
+
if (value === undefined)
|
|
789
|
+
return [];
|
|
790
|
+
if (!Array.isArray(value)) {
|
|
791
|
+
redactions.push(redaction('redactionSummary', 'unsafe_key', 'value-denied'));
|
|
792
|
+
return [];
|
|
793
|
+
}
|
|
794
|
+
const safe = [];
|
|
795
|
+
for (const [index, item] of value.entries()) {
|
|
796
|
+
if (!isRecord(item) || item.publicSafe !== true) {
|
|
797
|
+
redactions.push(redaction(`redactionSummary.${index}`, 'unsafe_key', 'value-denied'));
|
|
798
|
+
continue;
|
|
799
|
+
}
|
|
800
|
+
const field = stringField(item, 'field');
|
|
801
|
+
const reason = stringField(item, 'reason');
|
|
802
|
+
const evidence = stringField(item, 'evidence');
|
|
803
|
+
if (!field || !reason || !evidence || UNSAFE_VALUE_PATTERN.test(field) || UNSAFE_VALUE_PATTERN.test(reason) || UNSAFE_VALUE_PATTERN.test(evidence)) {
|
|
804
|
+
redactions.push(redaction(`redactionSummary.${index}`, 'unsafe_key', 'value-denied'));
|
|
805
|
+
continue;
|
|
806
|
+
}
|
|
807
|
+
safe.push({ field, reason, evidence, publicSafe: true });
|
|
808
|
+
}
|
|
809
|
+
return safe;
|
|
810
|
+
}
|
|
811
|
+
function safeAttemptRelativePaths(attempt) {
|
|
812
|
+
return STORY_TARGET_PATTERN.test(attempt.target_ref) ? [attempt.target_ref] : [];
|
|
813
|
+
}
|
|
814
|
+
function sanitizePublicRecord(record) {
|
|
815
|
+
if (!record)
|
|
816
|
+
return undefined;
|
|
817
|
+
const output = {};
|
|
818
|
+
for (const [key, value] of Object.entries(record)) {
|
|
819
|
+
if (!/^[A-Za-z0-9_.:-]{1,80}$/.test(key) || UNSAFE_KEY_PATTERN.test(key) || UNSAFE_VALUE_PATTERN.test(key))
|
|
820
|
+
continue;
|
|
821
|
+
if (typeof value === 'string' && UNSAFE_VALUE_PATTERN.test(value))
|
|
822
|
+
continue;
|
|
823
|
+
output[key] = value;
|
|
824
|
+
}
|
|
825
|
+
return Object.keys(output).length > 0 ? output : undefined;
|
|
826
|
+
}
|
|
827
|
+
function storyIdFromTargetRef(targetRef) {
|
|
828
|
+
return targetRef.replace(/^docs\/stories\//, '').replace(/\.story\.md$/, '');
|
|
829
|
+
}
|
|
830
|
+
function normalizeRuntimeSource(value) {
|
|
831
|
+
if (value === 'explicit' || value === 'origin' || value === 'default' || value === 'fallback')
|
|
832
|
+
return value;
|
|
833
|
+
return undefined;
|
|
834
|
+
}
|
|
835
|
+
function normalizeStoredRuntimeSource(value) {
|
|
836
|
+
if (value === 'explicit' || value === 'origin' || value === 'default' || value === 'fallback' || value === 'unspecified')
|
|
837
|
+
return value;
|
|
838
|
+
return undefined;
|
|
839
|
+
}
|
|
840
|
+
function unsafeKeyReason(key) {
|
|
841
|
+
if (/prompt|commandRef/i.test(key))
|
|
842
|
+
return 'prompt_body';
|
|
843
|
+
if (/std(?:out|err)|raw|log|transcript|stack/i.test(key))
|
|
844
|
+
return 'raw_log';
|
|
845
|
+
if (/url/i.test(key))
|
|
846
|
+
return 'private_url';
|
|
847
|
+
if (/path|cwd|argv|args|shell|command|binary|executable/i.test(key))
|
|
848
|
+
return 'executable_path';
|
|
849
|
+
if (/secret|token|password|authorization|api[_-]?key|license/i.test(key))
|
|
850
|
+
return 'secret_or_pii';
|
|
851
|
+
return 'unsafe_key';
|
|
852
|
+
}
|
|
853
|
+
function stringField(record, key) {
|
|
854
|
+
return typeof record[key] === 'string' ? record[key] : undefined;
|
|
855
|
+
}
|
|
856
|
+
function isSafeIdentifier(value) {
|
|
857
|
+
return Boolean(value && SAFE_ID_PATTERN.test(value) && !UNSAFE_VALUE_PATTERN.test(value) && !SHELL_FRAGMENT_PATTERN.test(value));
|
|
858
|
+
}
|
|
859
|
+
function isRecord(value) {
|
|
860
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
861
|
+
}
|
|
862
|
+
function safeEntityId(prefix, value) {
|
|
863
|
+
const normalized = `${prefix}-${value}`.replace(/[^A-Za-z0-9_.:-]+/g, '-').replace(/^-+|-+$/g, '');
|
|
864
|
+
if (normalized.length > 0 && normalized.length <= 120)
|
|
865
|
+
return normalized;
|
|
866
|
+
return `${prefix}-${createHash('sha256').update(value).digest('hex').slice(0, 32)}`;
|
|
867
|
+
}
|
|
868
|
+
export function headlessExecutionEntityId(prefix, value) {
|
|
869
|
+
return safeEntityId(prefix, value);
|
|
870
|
+
}
|
|
871
|
+
function defaultHeadlessIdFactory(prefix, attemptId) {
|
|
872
|
+
return safeEntityId(prefix, `${attemptId}-${Date.now()}-${randomBytes(4).toString('hex')}`);
|
|
873
|
+
}
|
|
874
|
+
function addMilliseconds(iso, ms) {
|
|
875
|
+
const base = Date.parse(iso);
|
|
876
|
+
return new Date((Number.isFinite(base) ? base : Date.now()) + ms).toISOString();
|
|
877
|
+
}
|
|
878
|
+
function boundedInteger(value, min, max) {
|
|
879
|
+
if (!Number.isFinite(value))
|
|
880
|
+
return min;
|
|
881
|
+
return Math.max(min, Math.min(max, Math.floor(value)));
|
|
882
|
+
}
|
|
883
|
+
function unique(values) {
|
|
884
|
+
return Array.from(new Set(values));
|
|
885
|
+
}
|