@wildo-ai/dev-companion 1.1.1 → 1.1.3
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/esm/.tsbuildinfo +1 -1
- package/dist/esm/claude-cli/models/coding-agent-dispatch.models.d.ts +12 -1
- package/dist/esm/claude-cli/models/coding-agent-dispatch.models.d.ts.map +1 -1
- package/dist/esm/claude-cli/models/coding-agent-dispatch.models.js +11 -0
- package/dist/esm/claude-cli/models/coding-agent-dispatch.models.js.map +1 -1
- package/dist/esm/claude-cli/services/coding-agent-dispatch.companion.service.d.ts +153 -1
- package/dist/esm/claude-cli/services/coding-agent-dispatch.companion.service.d.ts.map +1 -1
- package/dist/esm/claude-cli/services/coding-agent-dispatch.companion.service.js +408 -38
- package/dist/esm/claude-cli/services/coding-agent-dispatch.companion.service.js.map +1 -1
- package/dist/esm/claude-cli/services/research-agent-dispatch.companion.service.d.ts +25 -10
- package/dist/esm/claude-cli/services/research-agent-dispatch.companion.service.d.ts.map +1 -1
- package/dist/esm/claude-cli/services/research-agent-dispatch.companion.service.js +65 -24
- package/dist/esm/claude-cli/services/research-agent-dispatch.companion.service.js.map +1 -1
- package/dist/esm/claude-cli/services/research-evidence-store.companion.d.ts +70 -0
- package/dist/esm/claude-cli/services/research-evidence-store.companion.d.ts.map +1 -0
- package/dist/esm/claude-cli/services/research-evidence-store.companion.js +110 -0
- package/dist/esm/claude-cli/services/research-evidence-store.companion.js.map +1 -0
- package/dist/esm/companion-api/companion-api.schemas.d.ts +59 -2
- package/dist/esm/companion-api/companion-api.schemas.d.ts.map +1 -1
- package/dist/esm/companion-api/companion-api.schemas.js +60 -0
- package/dist/esm/companion-api/companion-api.schemas.js.map +1 -1
- package/dist/esm/companion-api/controllers/companion.controller.d.ts +62 -1
- package/dist/esm/companion-api/controllers/companion.controller.d.ts.map +1 -1
- package/dist/esm/companion-api/controllers/companion.controller.js +295 -19
- package/dist/esm/companion-api/controllers/companion.controller.js.map +1 -1
- package/dist/esm/core/inject/models/container.d.ts.map +1 -1
- package/dist/esm/core/inject/models/container.js +11 -0
- package/dist/esm/core/inject/models/container.js.map +1 -1
- package/dist/esm/core/inject/models/service-types.d.ts +5 -0
- package/dist/esm/core/inject/models/service-types.d.ts.map +1 -1
- package/dist/esm/core/inject/models/service-types.js +5 -0
- package/dist/esm/core/inject/models/service-types.js.map +1 -1
- package/dist/esm/core/introspection/behaviors/companion-introspection-behavior-definitions.d.ts.map +1 -1
- package/dist/esm/core/introspection/behaviors/companion-introspection-behavior-definitions.js +81 -0
- package/dist/esm/core/introspection/behaviors/companion-introspection-behavior-definitions.js.map +1 -1
- package/dist/esm/core/introspection/models/companion-introspection.models.d.ts +11 -1
- package/dist/esm/core/introspection/models/companion-introspection.models.d.ts.map +1 -1
- package/dist/esm/core/introspection/models/companion-introspection.models.js +39 -0
- package/dist/esm/core/introspection/models/companion-introspection.models.js.map +1 -1
- package/dist/esm/core/introspection/resources/creation-plane-dispatch.custom-impl.companion.service.d.ts +8 -0
- package/dist/esm/core/introspection/resources/creation-plane-dispatch.custom-impl.companion.service.d.ts.map +1 -0
- package/dist/esm/core/introspection/resources/creation-plane-dispatch.custom-impl.companion.service.js +317 -0
- package/dist/esm/core/introspection/resources/creation-plane-dispatch.custom-impl.companion.service.js.map +1 -0
- package/dist/esm/core/introspection/resources/creation-plane-projection.companion.service.d.ts +45 -0
- package/dist/esm/core/introspection/resources/creation-plane-projection.companion.service.d.ts.map +1 -0
- package/dist/esm/core/introspection/resources/creation-plane-projection.companion.service.js +243 -0
- package/dist/esm/core/introspection/resources/creation-plane-projection.companion.service.js.map +1 -0
- package/dist/esm/core/introspection/resources/introspection-resource-notifier.companion.service.d.ts +123 -0
- package/dist/esm/core/introspection/resources/introspection-resource-notifier.companion.service.d.ts.map +1 -0
- package/dist/esm/core/introspection/resources/introspection-resource-notifier.companion.service.js +298 -0
- package/dist/esm/core/introspection/resources/introspection-resource-notifier.companion.service.js.map +1 -0
- package/dist/esm/core/introspection/resources/introspection-resource-source.companion.service.d.ts +78 -1
- package/dist/esm/core/introspection/resources/introspection-resource-source.companion.service.d.ts.map +1 -1
- package/dist/esm/core/introspection/resources/introspection-resource-source.companion.service.js +155 -6
- package/dist/esm/core/introspection/resources/introspection-resource-source.companion.service.js.map +1 -1
- package/dist/esm/core/introspection/services/companion-introspection.companion.service.d.ts +131 -2
- package/dist/esm/core/introspection/services/companion-introspection.companion.service.d.ts.map +1 -1
- package/dist/esm/core/introspection/services/companion-introspection.companion.service.js +259 -9
- package/dist/esm/core/introspection/services/companion-introspection.companion.service.js.map +1 -1
- package/dist/esm/core/introspection/services/introspection-derivation-state.companion.service.d.ts +243 -0
- package/dist/esm/core/introspection/services/introspection-derivation-state.companion.service.d.ts.map +1 -0
- package/dist/esm/core/introspection/services/introspection-derivation-state.companion.service.js +417 -0
- package/dist/esm/core/introspection/services/introspection-derivation-state.companion.service.js.map +1 -0
- package/dist/esm/core/introspection/services/introspection-source-state.companion.service.d.ts +186 -0
- package/dist/esm/core/introspection/services/introspection-source-state.companion.service.d.ts.map +1 -0
- package/dist/esm/core/introspection/services/introspection-source-state.companion.service.js +368 -0
- package/dist/esm/core/introspection/services/introspection-source-state.companion.service.js.map +1 -0
- package/dist/esm/core/introspection/services/introspection-source-watcher.companion.service.d.ts +101 -0
- package/dist/esm/core/introspection/services/introspection-source-watcher.companion.service.d.ts.map +1 -0
- package/dist/esm/core/introspection/services/introspection-source-watcher.companion.service.js +278 -0
- package/dist/esm/core/introspection/services/introspection-source-watcher.companion.service.js.map +1 -0
- package/dist/esm/core/introspection/subprocess/application-domain-model.behavior.d.ts +370 -0
- package/dist/esm/core/introspection/subprocess/application-domain-model.behavior.d.ts.map +1 -0
- package/dist/esm/core/introspection/subprocess/application-domain-model.behavior.js +167 -0
- package/dist/esm/core/introspection/subprocess/application-domain-model.behavior.js.map +1 -0
- package/dist/esm/core/introspection/subprocess/companion-introspection-behavior-handlers.d.ts.map +1 -1
- package/dist/esm/core/introspection/subprocess/companion-introspection-behavior-handlers.js +332 -3
- package/dist/esm/core/introspection/subprocess/companion-introspection-behavior-handlers.js.map +1 -1
- package/dist/esm/core/introspection/subprocess/family-aspects.behavior.d.ts +40 -0
- package/dist/esm/core/introspection/subprocess/family-aspects.behavior.d.ts.map +1 -0
- package/dist/esm/core/introspection/subprocess/family-aspects.behavior.js +126 -0
- package/dist/esm/core/introspection/subprocess/family-aspects.behavior.js.map +1 -0
- package/dist/esm/core/introspection/subprocess/specification-artifacts.behavior.d.ts +51 -0
- package/dist/esm/core/introspection/subprocess/specification-artifacts.behavior.d.ts.map +1 -0
- package/dist/esm/core/introspection/subprocess/specification-artifacts.behavior.js +391 -0
- package/dist/esm/core/introspection/subprocess/specification-artifacts.behavior.js.map +1 -0
- package/dist/esm/core/runtime/dev-compile-quiet.companion.d.ts +103 -0
- package/dist/esm/core/runtime/dev-compile-quiet.companion.d.ts.map +1 -0
- package/dist/esm/core/runtime/dev-compile-quiet.companion.js +124 -0
- package/dist/esm/core/runtime/dev-compile-quiet.companion.js.map +1 -0
- package/dist/esm/core/runtime/services/start-companion-application.service.d.ts +39 -2
- package/dist/esm/core/runtime/services/start-companion-application.service.d.ts.map +1 -1
- package/dist/esm/core/runtime/services/start-companion-application.service.js +122 -11
- package/dist/esm/core/runtime/services/start-companion-application.service.js.map +1 -1
- package/dist/esm/core/specifications/non-composite-view-specification-context.shared.d.ts +6 -0
- package/dist/esm/core/specifications/non-composite-view-specification-context.shared.d.ts.map +1 -1
- package/dist/esm/core/specifications/non-composite-view-specification-context.shared.js.map +1 -1
- package/dist/esm/core/specifications/specification-context-factory.shared.d.ts +23 -0
- package/dist/esm/core/specifications/specification-context-factory.shared.d.ts.map +1 -1
- package/dist/esm/core/specifications/specification-context-factory.shared.js +26 -4
- package/dist/esm/core/specifications/specification-context-factory.shared.js.map +1 -1
- package/dist/esm/executions/services/companion-executions.companion.service.d.ts.map +1 -1
- package/dist/esm/executions/services/companion-executions.companion.service.js +13 -8
- package/dist/esm/executions/services/companion-executions.companion.service.js.map +1 -1
- package/dist/esm/i18n/components/APP_LAYOUTS_MAIN_CONTAINER.en.d.ts +12 -0
- package/dist/esm/i18n/components/APP_LAYOUTS_MAIN_CONTAINER.en.d.ts.map +1 -0
- package/dist/esm/i18n/components/APP_LAYOUTS_MAIN_CONTAINER.en.js +12 -0
- package/dist/esm/i18n/components/APP_LAYOUTS_MAIN_CONTAINER.en.js.map +1 -0
- package/dist/esm/i18n/components/LOW_LEVEL_FORM_FIELD.en.d.ts +1 -1
- package/dist/esm/i18n/components/LOW_LEVEL_FORM_FIELD.en.js +1 -1
- package/dist/esm/i18n/components/LOW_LEVEL_FORM_FIELD.en.js.map +1 -1
- package/dist/esm/i18n/composite_views/app.creation-board.en.d.ts +13 -0
- package/dist/esm/i18n/composite_views/app.creation-board.en.d.ts.map +1 -0
- package/dist/esm/i18n/composite_views/app.creation-board.en.js +91 -0
- package/dist/esm/i18n/composite_views/app.creation-board.en.js.map +1 -0
- package/dist/esm/i18n/composite_views/app.domain-model.en.d.ts +38 -0
- package/dist/esm/i18n/composite_views/app.domain-model.en.d.ts.map +1 -0
- package/dist/esm/i18n/composite_views/app.domain-model.en.js +41 -0
- package/dist/esm/i18n/composite_views/app.domain-model.en.js.map +1 -0
- package/dist/esm/i18n/index.d.ts +3 -3
- package/dist/esm/i18n/index.js +3 -3
- package/dist/esm/i18n/index.js.map +1 -1
- package/dist/esm/i18n/resources/wildoApplicationActorSystemExecutions.en.d.ts +24 -0
- package/dist/esm/i18n/resources/wildoApplicationActorSystemExecutions.en.d.ts.map +1 -0
- package/dist/esm/i18n/resources/wildoApplicationActorSystemExecutions.en.js +20 -0
- package/dist/esm/i18n/resources/wildoApplicationActorSystemExecutions.en.js.map +1 -0
- package/dist/esm/i18n/resources/wildoApplicationActorTasks.en.d.ts +31 -0
- package/dist/esm/i18n/resources/wildoApplicationActorTasks.en.d.ts.map +1 -0
- package/dist/esm/i18n/resources/wildoApplicationActorTasks.en.js +27 -0
- package/dist/esm/i18n/resources/wildoApplicationActorTasks.en.js.map +1 -0
- package/dist/esm/i18n/resources/wildoApplicationFlowSystemExecutions.en.d.ts +24 -0
- package/dist/esm/i18n/resources/wildoApplicationFlowSystemExecutions.en.d.ts.map +1 -0
- package/dist/esm/i18n/resources/wildoApplicationFlowSystemExecutions.en.js +20 -0
- package/dist/esm/i18n/resources/wildoApplicationFlowSystemExecutions.en.js.map +1 -0
- package/dist/esm/i18n/resources/workbenchBuildPlanTasks.en.d.ts +28 -0
- package/dist/esm/i18n/resources/workbenchBuildPlanTasks.en.d.ts.map +1 -0
- package/dist/esm/i18n/resources/workbenchBuildPlanTasks.en.js +24 -0
- package/dist/esm/i18n/resources/workbenchBuildPlanTasks.en.js.map +1 -0
- package/dist/esm/i18n/resources/workbenchDomainResources.en.d.ts +138 -0
- package/dist/esm/i18n/resources/workbenchDomainResources.en.d.ts.map +1 -0
- package/dist/esm/i18n/resources/workbenchDomainResources.en.js +100 -0
- package/dist/esm/i18n/resources/workbenchDomainResources.en.js.map +1 -0
- package/dist/esm/i18n/resources/workbenchPlaybooks.en.d.ts +29 -0
- package/dist/esm/i18n/resources/workbenchPlaybooks.en.d.ts.map +1 -0
- package/dist/esm/i18n/resources/workbenchPlaybooks.en.js +25 -0
- package/dist/esm/i18n/resources/workbenchPlaybooks.en.js.map +1 -0
- package/dist/esm/i18n/resources/workbenchRunWriteRecords.en.d.ts +27 -0
- package/dist/esm/i18n/resources/workbenchRunWriteRecords.en.d.ts.map +1 -0
- package/dist/esm/i18n/resources/workbenchRunWriteRecords.en.js +23 -0
- package/dist/esm/i18n/resources/workbenchRunWriteRecords.en.js.map +1 -0
- package/dist/esm/i18n/resources/workbenchSpecificationArtifacts.en.d.ts +806 -0
- package/dist/esm/i18n/resources/workbenchSpecificationArtifacts.en.d.ts.map +1 -0
- package/dist/esm/i18n/resources/workbenchSpecificationArtifacts.en.js +326 -0
- package/dist/esm/i18n/resources/workbenchSpecificationArtifacts.en.js.map +1 -0
- package/dist/esm/i18n/resources/workbenchTraceSessions.en.d.ts +26 -0
- package/dist/esm/i18n/resources/workbenchTraceSessions.en.d.ts.map +1 -0
- package/dist/esm/i18n/resources/workbenchTraceSessions.en.js +22 -0
- package/dist/esm/i18n/resources/workbenchTraceSessions.en.js.map +1 -0
- package/dist/esm/i18n/system_enums/market.en.d.ts +202 -0
- package/dist/esm/i18n/system_enums/market.en.d.ts.map +1 -0
- package/dist/esm/i18n/system_enums/market.en.js +209 -0
- package/dist/esm/i18n/system_enums/market.en.js.map +1 -0
- package/dist/esm/meta-workflows/models/application-coding-agent.actors-system.definitions.d.ts +31 -0
- package/dist/esm/meta-workflows/models/application-coding-agent.actors-system.definitions.d.ts.map +1 -1
- package/dist/esm/meta-workflows/models/application-coding-agent.actors-system.definitions.js +91 -8
- package/dist/esm/meta-workflows/models/application-coding-agent.actors-system.definitions.js.map +1 -1
- package/dist/esm/meta-workflows/models/application-research-agent.actors-system.definitions.d.ts +4 -2
- package/dist/esm/meta-workflows/models/application-research-agent.actors-system.definitions.d.ts.map +1 -1
- package/dist/esm/meta-workflows/models/application-research-agent.actors-system.definitions.js +10 -7
- package/dist/esm/meta-workflows/models/application-research-agent.actors-system.definitions.js.map +1 -1
- package/dist/esm/meta-workflows/services/application-build-dispatch.companion.service.d.ts +80 -7
- package/dist/esm/meta-workflows/services/application-build-dispatch.companion.service.d.ts.map +1 -1
- package/dist/esm/meta-workflows/services/application-build-dispatch.companion.service.js +261 -24
- package/dist/esm/meta-workflows/services/application-build-dispatch.companion.service.js.map +1 -1
- package/dist/esm/meta-workflows/services/application-build-generation-step.companion.service.d.ts +46 -3
- package/dist/esm/meta-workflows/services/application-build-generation-step.companion.service.d.ts.map +1 -1
- package/dist/esm/meta-workflows/services/application-build-generation-step.companion.service.js +95 -2
- package/dist/esm/meta-workflows/services/application-build-generation-step.companion.service.js.map +1 -1
- package/dist/esm/meta-workflows/services/execution-trace-read.companion.service.d.ts +9 -0
- package/dist/esm/meta-workflows/services/execution-trace-read.companion.service.d.ts.map +1 -1
- package/dist/esm/meta-workflows/services/execution-trace-read.companion.service.js +13 -0
- package/dist/esm/meta-workflows/services/execution-trace-read.companion.service.js.map +1 -1
- package/dist/esm/meta-workflows/services/playbook-run-write-register.companion.service.d.ts +12 -0
- package/dist/esm/meta-workflows/services/playbook-run-write-register.companion.service.d.ts.map +1 -1
- package/dist/esm/meta-workflows/services/playbook-run-write-register.companion.service.js +23 -0
- package/dist/esm/meta-workflows/services/playbook-run-write-register.companion.service.js.map +1 -1
- package/dist/esm/meta-workflows/services/playbook-run.companion.service.d.ts +113 -1
- package/dist/esm/meta-workflows/services/playbook-run.companion.service.d.ts.map +1 -1
- package/dist/esm/meta-workflows/services/playbook-run.companion.service.js +517 -54
- package/dist/esm/meta-workflows/services/playbook-run.companion.service.js.map +1 -1
- package/dist/esm/meta-workflows/services/playbook-suspended-run.companion.service.d.ts +40 -0
- package/dist/esm/meta-workflows/services/playbook-suspended-run.companion.service.d.ts.map +1 -1
- package/dist/esm/meta-workflows/services/playbook-suspended-run.companion.service.js +63 -1
- package/dist/esm/meta-workflows/services/playbook-suspended-run.companion.service.js.map +1 -1
- package/dist/esm/technical-doc/services/technical-doc.companion.service.d.ts +21 -0
- package/dist/esm/technical-doc/services/technical-doc.companion.service.d.ts.map +1 -1
- package/dist/esm/technical-doc/services/technical-doc.companion.service.js +84 -2
- package/dist/esm/technical-doc/services/technical-doc.companion.service.js.map +1 -1
- package/dist/esm/technical-doc/services/technical-documentation-application-derivation.companion.service.d.ts +10 -1
- package/dist/esm/technical-doc/services/technical-documentation-application-derivation.companion.service.d.ts.map +1 -1
- package/dist/esm/technical-doc/services/technical-documentation-application-derivation.companion.service.js +10 -1
- package/dist/esm/technical-doc/services/technical-documentation-application-derivation.companion.service.js.map +1 -1
- package/package.json +17 -17
- package/dist/esm/.builder.pid +0 -9
- package/dist/esm/i18n/resources/workbenchApplicationModules.en.d.ts +0 -36
- package/dist/esm/i18n/resources/workbenchApplicationModules.en.d.ts.map +0 -1
- package/dist/esm/i18n/resources/workbenchApplicationModules.en.js +0 -32
- package/dist/esm/i18n/resources/workbenchApplicationModules.en.js.map +0 -1
- package/dist/esm/i18n/resources/workbenchResourceRelationships.en.d.ts +0 -29
- package/dist/esm/i18n/resources/workbenchResourceRelationships.en.d.ts.map +0 -1
- package/dist/esm/i18n/resources/workbenchResourceRelationships.en.js +0 -25
- package/dist/esm/i18n/resources/workbenchResourceRelationships.en.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"coding-agent-dispatch.companion.service.js","sourceRoot":"","sources":["../../../../../src/claude-cli/services/coding-agent-dispatch.companion.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;;;;;;;;;;;;;AAEH,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAChF,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAEnD,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EACL,oBAAoB,EACpB,0BAA0B,EAC1B,aAAa,EACb,kBAAkB,EAClB,wBAAwB,EACxB,mBAAmB,GACpB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,iBAAiB,EAEjB,2BAA2B,EAC3B,SAAS,EACT,uBAAuB,EACvB,kBAAkB,EAClB,mBAAmB,GAGpB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAIL,sBAAsB,GAGvB,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,mCAAmC,GAEpC,MAAM,oDAAoD,CAAC;AAC5D,OAAO,EACL,4BAA4B,IAAI,gCAAgC,EAChE,qBAAqB,GACtB,MAAM,+BAA+B,CAAC;AAEvC,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAA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E,OAAO;YACpB,OAAO,GAAG,IAAI,CAAC;YACf,SAAS,CAAC,KAAK,CAAC,CAAC;QACnB,CAAC;QACD,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE;YAChB,IAAI,OAAO;gBAAE,OAAO;YACpB,OAAO,GAAG,IAAI,CAAC;YACf,QAAQ,CAAC,KAAK,CAAC,CAAC;QAClB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Application coding-task host — the typed Flows/Actors coding path.\n *\n * `runApplicationCodingTask` admits one typed `ApplicationCodingTaskContract`\n * (the episode runtime's coding revision owner is the caller), renders its\n * prompt from the sealed contract, creates an `Actors_Task` row, spawns the\n * Claude CLI in the background against the application worktree, captures\n * a read-only git change set with per-file attribution, runs the contract's\n * registered verification checks, then PATCHes the task with status/output/\n * artifacts. One admission never spans the multi-minute run (P-16) —\n * callers await the settlement or poll `/tasks/actors/:taskId`. The raw\n * `POST /coding-agent/dispatch` endpoint (caller-composed prompt) was\n * deleted at the first-activation hard cut.\n *\n * # Locking & recursion cap (P-20 / P-19b / P-35)\n *\n * Runs are single-flight, serialized by a cross-process lock on the\n * dedicated target `<saasRoot>/.wildo-saas/state/workspace-mutation.lock`\n * (`withDedicatedFileLock` from `@wildo-ai/platform-config-lib`,\n * proper-lockfile pattern — an in-memory mutex alone is forbidden because\n * the CLI mutates the same worktree from other processes). An in-memory\n * flag fronts the lock for fast 409s. The lock is held for the WHOLE run.\n *\n * The P-35 recursion cap falls out structurally: a dispatched run that\n * calls dispatch (it has shell access and can read the machine-local\n * token) always finds the lock held by ITS OWN run and is rejected 409 —\n * a dispatched run can never dispatch. Deliberately, the lock does NOT\n * gate Paul's parallel sessions (P-19b): CLAUDE.md forbids session\n * coordination; per-file attribution is the compensation, not exclusion.\n *\n * # Traceability (P-21)\n *\n * L2 runs are NOT traced by the engine `AgentCallTraceSink` — the direct\n * claude-cli lane bypasses it AND Bottleneck rate limiting. Do not assume\n * traced-for-free: this service owns its companion-traceability events\n * (DEBUG) and artifacts (DEBUG_VERBOSE); a sink wrapper emission is\n * deferred. The background phase runs under an INTERNAL trace session\n * (`createInternalSession`) because the HTTP request session ends at the\n * 202-style response.\n *\n * # Run limits (P-18)\n *\n * Defaults 30 min / 10 MiB; request-overridable up to hard caps\n * 60 min / 32 MiB. The byte cap REJECTS (kills the run), it does not\n * truncate. Args stay `--print` + `--model` (no extraArgs field), prompt\n * on stdin, env = `{ PATH, HOME, SHELL, TERM }` (composed inside\n * the ACP session runner).\n */\n\nimport { isAbsolute, join, normalize, relative, sep, dirname } from 'node:path';\nimport { existsSync, realpathSync } from 'node:fs';\n\nimport { inject, injectable } from 'inversify';\nimport {\n AgentsBackendService,\n ErrorBuilderBackendService,\n LoggerService,\n SAAS_SERVICE_TYPES,\n executeBoundedSubprocess,\n describeCaughtError,\n} from '@wildo-ai/saas-backend-lib';\nimport {\n Actor_Task_Topics,\n type AgentTraceContext,\n ErrorCustomMessageReference,\n ErrorType,\n FlowsActors_IO_PartKind,\n FlowsActors_Status,\n isWildoBackendError,\n type ArtifactInstance,\n type FlowsActors_Agent_Invocation,\n} from '@wildo-ai/saas-models';\nimport {\n CodingAgent_OperationContext_BaseSchema,\n CodingAgent_RunTaskInputSchema,\n CodingAgent_RunTaskOutputSchema,\n CodingAgent_StopReason,\n type CodingAgent_RunTaskOutput,\n type CodingAgent_Usage,\n} from '@wildo-ai/external-connectors-models';\nimport {\n ApplicationCodingTaskContractSchema,\n type ApplicationCodingTaskContract,\n} from '@wildo-ai/saas-specifications/application-creation';\nimport {\n getWorkspaceMutationLockPath as resolveWorkspaceMutationLockPath,\n withDedicatedFileLock,\n} from '@wildo-ai/platform-config-lib';\n\nimport { COMPANION_SERVICE_TYPES } from '../../core/inject/models/service-types';\nimport type { CompanionContext } from '../../core/context/companion-context';\nimport type {\n CompanionExecutionSessionContext,\n} from '../../core/traceability/companion-traceability.models';\nimport { CompanionTraceabilityLevel, CompanionTraceAliasKind } from '../../core/traceability/companion-traceability.models';\nimport { CompanionTraceabilityService } from '../../core/traceability/companion-traceability.service';\nimport { CompanionIntrospectionService } from '../../core/introspection/services/companion-introspection.companion.service';\nimport { CompanionExecutionsCompanionService } from '../../executions/services/companion-executions.companion.service';\nimport {\n CompanionCreateActorTaskRequestSchema,\n CompanionUpdateActorTaskRequestSchema,\n type CompanionCodingAgentStatusResponse,\n} from '../../companion-api/companion-api.schemas';\nimport { GitChangeSetCompanionService } from './git-change-set.companion.service';\nimport { APPLICATION_CODING_AGENT_REF } from '../../meta-workflows/models/application-coding-agent.actors-system.definitions';\nimport {\n ChangeSetAttributionClass,\n ApplicationCodingTaskDisposition,\n type ApplicationCodingTaskRunAdmission,\n type ApplicationCodingTaskVerificationPlan,\n DISPATCH_DEFAULT_MAX_CAPTURED_BYTES,\n DISPATCH_DEFAULT_TIMEOUT_MS,\n DISPATCH_HARD_MAX_CAPTURED_BYTES,\n DISPATCH_HARD_MAX_TIMEOUT_MS,\n VerificationKind,\n renderApplicationCodingTaskAgentPrompt,\n resolveApplicationCodingTaskVerificationPlans,\n type GitChangeSetCapture,\n type GitWorktreeSnapshot,\n} from '../models/coding-agent-dispatch.models';\n\n/** Fixed, non-overridable limits for the verification hook subprocess. */\nconst VERIFICATION_TIMEOUT_MS = 10 * 60_000;\nconst VERIFICATION_MAX_CAPTURED_BYTES = 10 * 1024 * 1024;\n\n\n/**\n * The session frames worth retaining on the durable row: what the agent DID and\n * what it changed. Message chunks are already summarised by the output tail, and\n * usage frames are superseded by the recorded totals.\n */\nconst RETAINED_CODING_SESSION_EVENT_KINDS: ReadonlySet<string> = new Set(['tool_call', 'tool_call_update', 'plan']);\n/** Ceiling on retained frames — a bound, not a sample: excess is dropped, never summarised. */\nconst RETAINED_CODING_SESSION_FRAME_LIMIT = 200;\n\n/** Tail size persisted on the task row; full streams go to traceability artifacts. */\nconst OUTPUT_TAIL_CHARS = 16_000;\n\ntype DispatchedTaskRow = Awaited<\n ReturnType<CompanionExecutionsCompanionService['createActorTask']>\n>;\n\ninterface ActiveRunState {\n taskId: string;\n startedAt: string;\n /** Cancels the in-flight coding session. Cooperative first, kill second. */\n abortController: AbortController;\n}\n\ninterface VerificationOutcome {\n kind: VerificationKind;\n path: string | null;\n success: boolean;\n message: string;\n stdoutTail: string;\n stderrTail: string;\n}\n\n/** Result of checking every attributed changed-during-run file against the sealed task scope. */\ninterface ApplicationCodingTaskScopeAssessment {\n allowed: boolean;\n violatingPaths: string[];\n /**\n * A commit landed inside the run window, so this window's attribution is\n * INCOMPLETE: a commit empties the dirty set every other class here is\n * computed from, and a parallel session's commit is indistinguishable from\n * the agent's own.\n *\n * RECORDED, NOT REFUSED — decided 2026-08-19, and the reasoning is the same\n * rule the plan applies to every other strictness in this vertical: exactness\n * is retained where a protected, accepted-state or real-effect consumer needs\n * it, and nowhere else. A coding run produces a WORKING result; it mutates no\n * accepted truth. Refusing the whole run here bought no protection of\n * anything accepted, while on a shared tree with parallel sessions ANY commit\n * overlapping ANY run — including one touching nothing the agent touched —\n * failed that run, with no worktree isolation to fall back on (ruled out for\n * this application) and no remedy a single session can enforce.\n *\n * What replaces the refusal is visibility that a consumer cannot miss: the\n * committed paths are recovered into the change set as\n * `COMMITTED_DURING_RUN`, and this flag rides on the recorded result. The\n * OBLIGATION moves with it — whatever later accepts this working result must\n * treat `historyMutated` as attribution it cannot rely on, and must not\n * promote it without review. That is the acceptance tier's job, which is\n * where exactness belongs.\n */\n historyMutated: boolean;\n}\n\n/**\n * Scope checking is deliberately based on the post-run attribution capture,\n * not only clean-baseline files. A baseline-dirty file changed again during a\n * run is not safely attributable to the Agent, but it is still a real effect\n * inside the host window and must not be used to bypass a declared boundary.\n */\nfunction assessApplicationCodingTaskMutationScope(\n changeSet: GitChangeSetCapture,\n allowedPrefixes: readonly string[],\n prohibitedPrefixes: readonly string[],\n): ApplicationCodingTaskScopeAssessment {\n const normalizedAllowed = allowedPrefixes.map(normalizeApplicationRelativePrefix);\n const normalizedProhibited = prohibitedPrefixes.map(normalizeApplicationRelativePrefix);\n /*\n * Committed paths are deliberately EXCLUDED from the scope decision. They are\n * present in `changeSet.files` (as `COMMITTED_DURING_RUN`) so nothing is\n * invisible, but nobody can attribute them: a parallel session's commit and\n * the agent's own look identical from here, so refusing on them would fail\n * runs for other people's work. `historyMutated` carries that fact forward\n * instead, and the acceptance tier decides what an unattributable window is\n * worth.\n */\n /*\n * A disappearance is only a VIOLATION when the run can be held responsible for it, and a commit\n * landing inside the window is precisely when it cannot.\n *\n * `disappearedFromBaseline` is \"dirty at baseline, no longer dirty post-run\", which has two\n * causes that look identical from here: the agent reverted or deleted the file (attributable,\n * and a real boundary breach if the path is out of scope), or a commit emptied the dirty set\n * (not attributable — a parallel session's commit and the agent's own are indistinguishable,\n * which is the exact reasoning the `COMMITTED_DURING_RUN` exclusion above already applies).\n *\n * Including them unconditionally made the two treatments contradict each other: the committed\n * PATHS were excluded as unattributable while the disappearance THAT SAME COMMIT CAUSED was\n * used to fail the run. Measured 2026-08-28 on wonder-crm — a run that stopped cleanly at\n * `end_turn`, honoured every permission decision and wrote NOTHING (`runExclusive: 0`,\n * `appearedDuringRun: 0`) was recorded `mutation_scope_violation` against 13 engine paths it\n * never touched, because a human committed at 17:47:56 and 17 baseline-dirty files left the\n * set. The field's own contract already said they \"are NOT attributed change-set entries\".\n *\n * So the exclusion is conditional, not blanket: with no commit in the window a disappearance\n * IS the run's doing and still fails it. Only the case the run cannot be responsible for is\n * dropped, and it stays visible — the paths remain on `disappearedFromBaseline`, and\n * `historyMutated` tells the acceptance tier the window is unattributable.\n */\n const disappearancesAttributableToTheRun = changeSet.headMovedDuringRun\n ? []\n : changeSet.disappearedFromBaseline;\n\n const violatingPaths = [\n ...changeSet.files\n .filter((entry) => entry.attribution !== ChangeSetAttributionClass.COMMITTED_DURING_RUN)\n .map((entry) => entry.path),\n ...disappearancesAttributableToTheRun,\n ]\n .filter((path) => {\n const normalizedPath = normalizeApplicationRelativePrefix(path);\n const inAllowedScope = normalizedAllowed.some((prefix) => matchesApplicationRelativePrefix(normalizedPath, prefix));\n const inProhibitedScope = normalizedProhibited.some((prefix) => matchesApplicationRelativePrefix(normalizedPath, prefix));\n return !inAllowedScope || inProhibitedScope;\n });\n return {\n // `historyMutated` does NOT gate admissibility (see the field's contract):\n // it is recorded so the consumer of this working result can see that the\n // window is unattributable, not used to fail a run that protected nothing.\n allowed: violatingPaths.length === 0,\n violatingPaths,\n historyMutated: changeSet.headMovedDuringRun,\n };\n}\n\n/**\n * The LIVE counterpart of {@link assessApplicationCodingTaskMutationScope}:\n * decides, while the agent is still running, whether one absolute path is\n * inside the task's declared mutation scope.\n *\n * Deliberately reuses the SAME normalisation and boundary matching as the\n * post-hoc assessment. Two predicates answering \"is this path in scope?\" with\n * different rules would produce the worst possible outcome — a run permitted\n * live and then judged a scope violation afterwards, or the reverse.\n *\n * It NARROWS and never widens: the permission ceiling still decides the KIND of\n * operation, and this only refuses a path that ceiling would otherwise allow.\n * A path outside the workspace is refused outright rather than reasoned about.\n */\nexport function buildApplicationCodingTaskLocationPredicate(\n workspaceRootPath: string,\n allowedPrefixes: readonly string[],\n prohibitedPrefixes: readonly string[],\n): (absolutePath: string) => boolean {\n const normalizedAllowed = allowedPrefixes.map(normalizeApplicationRelativePrefix);\n const normalizedProhibited = prohibitedPrefixes.map(normalizeApplicationRelativePrefix);\n\n /*\n * Compare against BOTH the configured root and its physical realpath.\n *\n * Agents report CANONICAL absolute paths. Measured live on 2026-08-27: with a\n * workspace under `/var/folders/...` (a macOS symlink to `/private/var/...`),\n * the agent's permission request named the `/private/...` form while the\n * configured root was the `/var/...` form, so an IN-SCOPE edit was refused and\n * the run reported the agent declining to do its job. A scope predicate that\n * silently denies everything is worse than one that denies nothing, because\n * it looks like the agent failing rather than the guard misfiring.\n */\n const candidateRoots = [workspaceRootPath];\n try {\n const physicalRoot = realpathSync.native(workspaceRootPath);\n if (physicalRoot !== workspaceRootPath) {\n candidateRoots.push(physicalRoot);\n }\n } catch {\n // An unresolvable root is left as authored; the relative check below still\n // refuses anything outside it.\n }\n\n return (absolutePath: string): boolean => {\n if (!isAbsolute(absolutePath)) {\n return false;\n }\n const relativePath = candidateRoots\n .map((root) => relative(root, absolutePath))\n .find((candidate) => candidate && !candidate.startsWith('..') && !isAbsolute(candidate));\n if (!relativePath) {\n return false;\n }\n const normalizedPath = normalizeApplicationRelativePrefix(relativePath.split(sep).join('/'));\n const inAllowedScope = normalizedAllowed.some((prefix) => matchesApplicationRelativePrefix(normalizedPath, prefix));\n const inProhibitedScope = normalizedProhibited.some((prefix) => matchesApplicationRelativePrefix(normalizedPath, prefix));\n return inAllowedScope && !inProhibitedScope;\n };\n}\n\nfunction normalizeApplicationRelativePrefix(value: string): string {\n return value.replace(/\\\\/g, '/').replace(/^\\.\\//, '').replace(/\\/+$/, '');\n}\n\n/** Prefix matches require a path boundary: `src/app` does not admit `src/application`. */\nfunction matchesApplicationRelativePrefix(path: string, prefix: string): boolean {\n return path === prefix || path.startsWith(`${prefix}/`);\n}\n\n@injectable()\nexport class CodingAgentDispatchCompanionService {\n private readonly logDebug: (message: string, context?: Record<string, unknown>) => void;\n\n /**\n * In-memory single-flight flag — the FAST 409 in front of the\n * cross-process lockfile, never a replacement for it (P-20).\n */\n private activeRun: ActiveRunState | null = null;\n /**\n * Per-process settlement signal of every application coding task THIS\n * process admitted: resolved when the background run has recorded its\n * terminal durable result (or given up trying). This is the \"owner's\n * completion hook\" the episode driver waits on instead of polling the\n * Actor Task row; a task admitted by a previous process has no entry here,\n * which is correct — restart reconciliation already terminalized it.\n */\n private readonly applicationCodingTaskSettlements = new Map<string, { readonly promise: Promise<void>; resolve(): void }>();\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.Logger)\n private readonly logger: LoggerService,\n @inject(SAAS_SERVICE_TYPES.ErrorBuilderService)\n private readonly errorBuilder: ErrorBuilderBackendService,\n @inject(COMPANION_SERVICE_TYPES.CompanionContext)\n private readonly companionContext: CompanionContext,\n @inject(SAAS_SERVICE_TYPES.AgentsBackendService)\n private readonly agentsService: AgentsBackendService,\n @inject(COMPANION_SERVICE_TYPES.GitChangeSetService)\n private readonly gitChangeSetService: GitChangeSetCompanionService,\n @inject(COMPANION_SERVICE_TYPES.ExecutionsService)\n private readonly executionsService: CompanionExecutionsCompanionService,\n @inject(COMPANION_SERVICE_TYPES.TraceabilityService)\n private readonly traceabilityService: CompanionTraceabilityService,\n @inject(COMPANION_SERVICE_TYPES.IntrospectionService)\n private readonly introspectionService: CompanionIntrospectionService,\n ) {\n this.logDebug = this.logger.debugByType('CodingAgentDispatchCompanionService');\n this.logger.setDebugTypeLogging('CodingAgentDispatchCompanionService', true);\n }\n\n /**\n * Admit one application-authored coding task onto the normal Flows/Actors\n * Claude Code path — the ONLY coding entry since the raw dispatch endpoint\n * was deleted at the first-activation hard cut. This method accepts only the\n * sealed typed task produced by application composition. The returned\n * acknowledgement is intentionally non-terminal; a completed Actor Task\n * records a working code result and its evidence, never accepted\n * application truth.\n */\n public async runApplicationCodingTask(\n rawTask: ApplicationCodingTaskContract,\n sessionContext?: CompanionExecutionSessionContext,\n ): Promise<ApplicationCodingTaskRunAdmission> {\n /*\n * Both admission refusals below are TYPED.\n *\n * A malformed contract surfaced as a raw `ZodError` and an unregistered\n * check ref as a plain `Error`, so the two refusals a caller can actually\n * provoke reached the transport as unclassified failures and answered 500\n * INTERNAL — indistinguishable from the host being broken. They are\n * VALIDATION: the request is refused, nothing was locked, created or run.\n */\n const task = this.admitTypedInput(\n () => ApplicationCodingTaskContractSchema.parse(rawTask),\n 'Application coding task contract is not valid.',\n );\n // Resolve before acquiring the lock or creating a task. A semantic check\n // name is not a command and cannot silently fall back to an arbitrary\n // workspace typecheck.\n const verificationPlans = this.admitTypedInput(\n () => resolveApplicationCodingTaskVerificationPlans(task.verificationIntent.requiredChecks),\n 'Application coding task names an unregistered verification check.',\n );\n const traceStep = this.createOperationTraceStep(sessionContext, 'application-coding-task-admission');\n const renderedPrompt = renderApplicationCodingTaskAgentPrompt(task);\n await this.traceOperationStart({\n sessionContext,\n step: traceStep,\n type: 'application-coding-task-admission-start',\n summary: `Admit application coding task ${task.taskRef}`,\n payload: this.buildApplicationCodingTaskTraceSummary(task),\n artifactFileName: 'application-coding-task-input.txt',\n artifactContent: renderedPrompt,\n });\n\n if (this.activeRun) {\n throw this.buildDispatchConflictError(\n `A coding-agent run is already active (task ${this.activeRun.taskId}, started ${this.activeRun.startedAt}). `\n + 'Application coding tasks share the same cross-process mutation lock.',\n );\n }\n\n const admission = createDeferred<{ task: DispatchedTaskRow; baseline: GitWorktreeSnapshot }>();\n const backgroundRun = withDedicatedFileLock(\n this.getWorkspaceMutationLockPath(),\n async () => {\n let admitted: { task: DispatchedTaskRow; baseline: GitWorktreeSnapshot };\n try {\n const baseline = await this.gitChangeSetService.captureWorktreeSnapshot();\n const durableTask = await this.createApplicationCodingTask(task, baseline, sessionContext);\n this.activeRun = {\n taskId: durableTask._id,\n startedAt: new Date().toISOString(),\n abortController: new AbortController(),\n };\n admitted = { task: durableTask, baseline };\n // Registered BEFORE the admission is resolved, so a caller that\n // awaits the settlement right after admission can never miss it.\n const settlement = createDeferred<void>();\n this.applicationCodingTaskSettlements.set(durableTask._id, { promise: settlement.promise, resolve: () => settlement.resolve(undefined) });\n admission.resolve(admitted);\n } catch (error) {\n admission.reject(error);\n return;\n }\n\n try {\n await this.executeApplicationCodingTask(task, renderedPrompt, verificationPlans, admitted.task, admitted.baseline);\n } finally {\n this.activeRun = null;\n this.applicationCodingTaskSettlements.get(admitted.task._id)?.resolve();\n }\n },\n { retries: { retries: 0 } },\n );\n backgroundRun.catch((error: unknown) => {\n admission.reject(this.mapLockError(error));\n this.logDebug('Application coding-task background run chain terminated with error', {\n error: describeCaughtError(error),\n taskRef: task.taskRef,\n });\n });\n\n const admitted = await admission.promise;\n const response: ApplicationCodingTaskRunAdmission = {\n taskId: admitted.task._id,\n status: FlowsActors_Status.PROCESSING,\n taskRef: task.taskRef,\n baselineHeadSha: admitted.baseline.headSha,\n baselineDirtyFileCount: Object.keys(admitted.baseline.files).length,\n };\n await this.traceOperationSuccess({\n sessionContext,\n step: traceStep,\n type: 'application-coding-task-admission-success',\n summary: `Admitted application coding task ${task.taskRef} as Actor Task ${admitted.task._id}`,\n payload: response,\n artifactFileName: 'application-coding-task-admission.json',\n artifactContent: response,\n });\n return response;\n }\n\n /**\n * The settlement of one application coding task admitted by THIS process:\n * resolves once its terminal durable result has been recorded (success or\n * failure) — the only moment a waiting episode can read a non-PROCESSING\n * row. `null` for a task this process did not admit (a previous process's\n * row, already terminalized by restart reconciliation, or an unknown id):\n * there is nothing to wait for, and a caller must not spin on it.\n */\n public awaitApplicationCodingTaskSettlement(taskId: string): Promise<void> | null {\n return this.applicationCodingTaskSettlements.get(taskId)?.promise ?? null;\n }\n\n /**\n * Reconcile only a previous process's unfinished application-coding rows.\n *\n * A companion restart cannot prove the previous Claude Code subprocess is\n * still running. Retrying could duplicate a worktree mutation, while\n * reverting would destroy evidence. The safe v0 result is therefore a\n * terminal physical abort plus an explicit human-review disposition. Root\n * wires this method into ordinary startup in a later, separately reviewed\n * join; this source slice never invokes it automatically.\n */\n public async reconcileInterruptedApplicationCodingTasks(\n sessionContext?: CompanionExecutionSessionContext,\n ): Promise<{ reconciledTaskIds: string[] }> {\n const processingTasks = await this.executionsService.listActorTasks({\n status: FlowsActors_Status.PROCESSING,\n limit: 200,\n }, sessionContext);\n const reconciledTaskIds: string[] = [];\n\n for (const task of processingTasks) {\n if (task.actors?.actorRef !== APPLICATION_CODING_AGENT_REF) continue;\n let currentSnapshot: GitWorktreeSnapshot | null = null;\n let captureError: unknown = null;\n try {\n currentSnapshot = await this.gitChangeSetService.captureWorktreeSnapshot();\n } catch (error) {\n captureError = error;\n }\n\n const updatePayload = CompanionUpdateActorTaskRequestSchema.parse({\n status: FlowsActors_Status.ABORTED,\n output: {\n succeeded: false,\n disposition: ApplicationCodingTaskDisposition.INTERRUPTED_REQUIRES_REVIEW,\n recoveryEvidence: currentSnapshot\n ? {\n headSha: currentSnapshot.headSha,\n dirtyFileCount: Object.keys(currentSnapshot.files).length,\n capturedAt: currentSnapshot.capturedAt,\n }\n : null,\n ...(captureError ? { recoveryCaptureError: buildOutputErrorPayload(captureError) } : {}),\n },\n });\n await this.executionsService.updateActorTask(task._id, updatePayload, sessionContext);\n reconciledTaskIds.push(task._id);\n }\n\n return { reconciledTaskIds };\n }\n\n /**\n * Readiness snapshot for the status route. HONESTY CONTRACT: the\n * underlying `isAvailable()` checks ONLY that the provider registry\n * exposes an AGENT_CLIENT_PROTOCOL contract for anthropic — it does NOT\n * guarantee the ACP adapter is installed, spawnable, or authenticated. A\n * `true` here can still be followed by a spawn/auth failure at run time.\n */\n /**\n * The cross-process workspace-mutation lock path (P-19b) — one lock for\n * every mutating coding run against this application worktree.\n */\n public getWorkspaceMutationLockPath(): string {\n return resolveWorkspaceMutationLockPath(this.companionContext.saasRoot);\n }\n\n /**\n * Cancel the in-flight coding run, if there is one.\n *\n * Cooperative by construction: this signals the session, and the runner sends\n * `session/cancel` and waits before killing anything. The run therefore\n * TERMINALISES NORMALLY — with stop reason `cancelled` and a captured change\n * set — rather than vanishing. That distinction is the whole point: an\n * operator who stops a run still needs to know what it had already written.\n *\n * Returns the task that was asked to stop, or `null` when nothing is running.\n * Idempotent: cancelling an already-cancelled run signals an aborted\n * controller again, which is a no-op.\n */\n public cancelActiveApplicationCodingTask(): { taskId: string; startedAt: string } | null {\n const active = this.activeRun;\n if (!active) {\n return null;\n }\n this.logDebug('Cancelling active application coding task', { taskId: active.taskId });\n active.abortController.abort();\n return { taskId: active.taskId, startedAt: active.startedAt };\n }\n\n public getStatus(): CompanionCodingAgentStatusResponse {\n return {\n // Reports a fact this service can actually establish: whether the coding\n // agent is registered. It deliberately does NOT claim the transport is\n // usable — that depends on the provider configuration and on an agent\n // process this service has not started, and a status field that overstates\n // its knowledge is worse than one that is narrow about it.\n codingAgentRegistered: this.agentsService.getAgent(APPLICATION_CODING_AGENT_REF) !== undefined,\n activeRun: this.activeRun ? { ...this.activeRun } : null,\n limits: {\n defaultTimeoutMs: DISPATCH_DEFAULT_TIMEOUT_MS,\n hardMaxTimeoutMs: DISPATCH_HARD_MAX_TIMEOUT_MS,\n defaultMaxCapturedBytes: DISPATCH_DEFAULT_MAX_CAPTURED_BYTES,\n hardMaxCapturedBytes: DISPATCH_HARD_MAX_CAPTURED_BYTES,\n },\n lockFilePath: this.getWorkspaceMutationLockPath(),\n };\n }\n\n /**\n * Persist only replayable task identity and guard evidence, never\n * prompt/context bytes.\n *\n * CORRELATION BACK TO THE EPISODE runs through `input.candidateRef`, which is\n * the assessment episode's working-subject identity for the iteration that\n * composed this task — the same value the private checkpoint carries as\n * `basis.episode.candidateRef`. It is recorded here deliberately so the join\n * exists in BOTH directions: the checkpoint names the taskId once the task is\n * admitted, and this row names the candidate that caused it, so an auditor\n * starting from a workspace mutation can reach the episode without scanning\n * every checkpoint.\n *\n * A dedicated `episodeRef` column is NOT added: no caller supplies one yet\n * (the coding revision owner lands later), and a field with no producer is a\n * dormant surface that later readers mistake for a guarantee. The candidate\n * ref is exact per ITERATION, which is the granularity an auditor wants.\n */\n private async createApplicationCodingTask(\n task: ApplicationCodingTaskContract,\n baseline: GitWorktreeSnapshot,\n sessionContext?: CompanionExecutionSessionContext,\n ): Promise<DispatchedTaskRow> {\n const payload = CompanionCreateActorTaskRequestSchema.parse({\n title: `Application coding task ${task.taskRef}`,\n description: `Typed application coding task for ${task.objectiveRef}; acceptance remains outside the coding host.`,\n topic: Actor_Task_Topics.IMPLEMENTATION,\n status: FlowsActors_Status.PROCESSING,\n actors: { actorRef: APPLICATION_CODING_AGENT_REF },\n input: {\n taskRef: task.taskRef,\n objectiveRef: task.objectiveRef,\n candidateRef: task.candidateRef,\n mutationScope: task.mutationScope,\n contextPlan: {\n planRef: task.contextPlan.planRef,\n objectiveRef: task.contextPlan.objectiveRef,\n },\n contextSelection: {\n planRef: task.contextSelection.planRef,\n selectedSourceRefs: task.contextSelection.selectedSources.map((source) => source.sourceRef),\n selectedSourceCount: task.contextSelection.selectedSources.length,\n },\n verificationIntent: task.verificationIntent,\n installedSkillRefs: task.installedSkillRefs,\n baseline: {\n headSha: baseline.headSha,\n dirtyFileCount: Object.keys(baseline.files).length,\n capturedAt: baseline.capturedAt,\n },\n },\n context: {},\n startedAt: new Date().toISOString(),\n });\n return this.executionsService.createActorTask(payload, sessionContext);\n }\n\n /**\n * Executes the normal Agent invocation and lands the full working-result\n * evidence. This method runs inside the worktree lock and therefore is the\n * sole typed path allowed to observe its own before/after Git boundary.\n */\n private async executeApplicationCodingTask(\n task: ApplicationCodingTaskContract,\n renderedPrompt: string,\n verificationPlans: readonly ApplicationCodingTaskVerificationPlan[],\n durableTask: DispatchedTaskRow,\n baseline: GitWorktreeSnapshot,\n ): Promise<void> {\n let runSession: CompanionExecutionSessionContext | undefined;\n let runStep: ReturnType<CompanionTraceabilityService['createStep']> | undefined;\n const traceabilityErrors: unknown[] = [];\n const traceBestEffort = async (operation: string, write: () => Promise<void>): Promise<void> => {\n try {\n await write();\n } catch (error) {\n // Traceability is required evidence, but it must not become a control\n // flow escape that leaves the durable task PROCESSING after possible\n // source changes. The final task row records this failure and remains\n // visibly non-accepted for explicit follow-up.\n traceabilityErrors.push(error);\n this.logger.error('Application coding-task trace operation failed', {\n taskId: durableTask._id,\n taskRef: task.taskRef,\n operation,\n error: describeCaughtError(error),\n });\n }\n };\n await traceBestEffort('initialize-session', async () => {\n runSession = this.traceabilityService.createInternalSession({\n label: 'application-coding-task-run',\n metadata: { taskId: durableTask._id, taskRef: task.taskRef },\n });\n if (!runSession) return;\n await this.traceabilityService.registerAlias(runSession, CompanionTraceAliasKind.ACTOR_TASK, durableTask._id);\n runStep = this.createOperationTraceStep(runSession, 'application-coding-task-run');\n });\n const traceContext: AgentTraceContext = {\n label: `application-coding-task:${task.taskRef}`,\n attributes: {\n taskId: durableTask._id,\n taskRef: task.taskRef,\n objectiveRef: task.objectiveRef,\n candidateRef: task.candidateRef,\n },\n };\n const invocation: FlowsActors_Agent_Invocation<\n typeof CodingAgent_RunTaskInputSchema,\n typeof CodingAgent_RunTaskOutputSchema,\n typeof CodingAgent_OperationContext_BaseSchema\n > = {\n agentRef: APPLICATION_CODING_AGENT_REF,\n initiator: {},\n invocationContext: [],\n input: { prompt: renderedPrompt },\n output: { finalMessage: '', stopReason: CodingAgent_StopReason.END_TURN },\n executionContext: { callTimestamp: new Date().toISOString() },\n artifactBindings: [],\n };\n\n const startedAtMs = Date.now();\n let runError: unknown = null;\n let agentOutput = '';\n let codingUsage: CodingAgent_Usage | undefined;\n let codingDeniedPermissionCount: number | undefined;\n let codingPermissionDecisions: CodingAgent_RunTaskOutput['permissionDecisions'];\n let agentStopReason: CodingAgent_StopReason | undefined;\n /*\n * Counted in full, RETAINED in part.\n *\n * The previous shape pushed every notification into an unbounded array and\n * then persisted only its length — so a 30-minute run grew memory the\n * process never read, and the tool-call and diff frames (the reason to\n * observe a session at all) were collected and discarded. Now the count is a\n * counter, and only the frames a reader would actually open are retained, up\n * to a fixed ceiling.\n */\n let codingSessionEventCount = 0;\n const retainedCodingSessionFrames: Array<{ readonly kind: string; readonly payload: unknown }> = [];\n await traceBestEffort('record-start', () => this.traceOperationStart({\n sessionContext: runSession,\n step: runStep,\n type: 'application-coding-task-run-start',\n summary: `Run application coding task ${task.taskRef}`,\n payload: this.buildApplicationCodingTaskTraceSummary(task),\n artifactFileName: 'application-coding-task-input.txt',\n artifactContent: renderedPrompt,\n }));\n try {\n const response = await this.agentsService.invokeAgent(\n invocation,\n traceContext,\n {\n workspaceRootPath: this.companionContext.saasRoot,\n // Hold the agent to the task's declared scope WHILE it runs, not only\n // in the change set afterwards. The post-hoc assessment stays — it is\n // the authoritative record, because an agent can write a file it never\n // asked permission for — but a refusal in the moment is the only one\n // that prevents the write rather than reporting it.\n isPermittedCodingLocation: buildApplicationCodingTaskLocationPredicate(\n this.companionContext.saasRoot,\n task.mutationScope.allowedPathPrefixes,\n task.mutationScope.prohibitedPathPrefixes,\n ),\n onCodingSessionEvent: (event) => {\n codingSessionEventCount += 1;\n if (\n retainedCodingSessionFrames.length < RETAINED_CODING_SESSION_FRAME_LIMIT\n && RETAINED_CODING_SESSION_EVENT_KINDS.has(event.kind)\n ) {\n retainedCodingSessionFrames.push(event);\n }\n },\n ...(this.activeRun ? { codingSessionAbortSignal: this.activeRun.abortController.signal } : {}),\n },\n );\n const codingOutput = response.output as Partial<CodingAgent_RunTaskOutput> | undefined;\n // The agent runtime publishes provider-learned facts on `executionContext`.\n codingUsage = (response.executionContext as { usage?: CodingAgent_Usage } | undefined)?.usage;\n codingDeniedPermissionCount = codingOutput?.deniedPermissionCount;\n codingPermissionDecisions = codingOutput?.permissionDecisions;\n const text = codingOutput?.finalMessage;\n agentStopReason = codingOutput?.stopReason;\n // A CANCELLED turn is not a completed one, and its partial change set must\n // not be read as a working result. Refused here rather than downstream so\n // the disposition names the actual reason.\n if (agentStopReason === CodingAgent_StopReason.CANCELLED) {\n throw new Error('Application coding Agent turn was cancelled before it completed.');\n }\n if (typeof text !== 'string' || text.trim().length === 0) {\n throw new Error('Application coding Agent returned no final message.');\n }\n agentOutput = text;\n } catch (error) {\n runError = error;\n }\n\n let changeSet: GitChangeSetCapture | null = null;\n let captureError: unknown = null;\n try {\n changeSet = await this.gitChangeSetService.captureChangeSet(baseline);\n } catch (error) {\n captureError = error;\n }\n\n const scopeAssessment = changeSet\n ? assessApplicationCodingTaskMutationScope(changeSet, task.mutationScope.allowedPathPrefixes, task.mutationScope.prohibitedPathPrefixes)\n : null;\n // Verification is deliberately sequential. Each check has a fixed\n // semantic meaning, but several checks can still contend for the same\n // application package/cache if started together. The ordered outcomes are\n // easier to inspect and avoid turning a bounded coding task into an\n // accidental local-build fan-out.\n const verification: Array<{ checkRef: string; outcome: VerificationOutcome }> = [];\n let verificationInfrastructureError: unknown = null;\n if (!runError && !captureError && scopeAssessment?.allowed) {\n for (const plan of verificationPlans) {\n try {\n verification.push({\n checkRef: plan.checkRef,\n // The FK-resolution check is not a CLI command: it runs in the companion's\n // introspection subprocess (fresh working-tree import), so it branches before\n // the argv-plan path.\n outcome: plan.kind === VerificationKind.FRONTEND_FK_RESOLUTION\n ? await this.runForeignKeyResolutionVerification()\n : plan.kind === VerificationKind.SETTINGS_PLACEMENT_CONTENT\n ? await this.runSettingsPlacementContentVerification()\n : await this.runVerification(this.buildVerificationPlan(plan.kind, plan.path ?? undefined)),\n });\n } catch (error) {\n verificationInfrastructureError ??= error;\n verification.push({\n checkRef: plan.checkRef,\n outcome: {\n kind: plan.kind,\n path: plan.path,\n success: false,\n message: describeCaughtError(error),\n stdoutTail: '',\n stderrTail: '',\n },\n });\n }\n }\n }\n const failedVerification = verification.find(({ outcome }) => !outcome.success) ?? null;\n\n if (agentOutput) {\n await traceBestEffort('write-agent-output', () =>\n this.traceOperationArtifact(runSession, runStep, 'application-coding-task-agent-output.txt', agentOutput));\n }\n if (changeSet?.fullDiffText) {\n await traceBestEffort('write-change-set', () =>\n this.traceOperationArtifact(runSession, runStep, 'application-coding-task-change-set.diff', changeSet.fullDiffText));\n }\n\n const disposition = runError\n ? ApplicationCodingTaskDisposition.AGENT_EXECUTION_FAILED\n : captureError\n ? ApplicationCodingTaskDisposition.CHANGE_SET_CAPTURE_FAILED\n : !scopeAssessment?.allowed\n ? ApplicationCodingTaskDisposition.MUTATION_SCOPE_VIOLATION\n : failedVerification\n ? ApplicationCodingTaskDisposition.VERIFICATION_FAILED\n : traceabilityErrors.length > 0\n ? ApplicationCodingTaskDisposition.TRACEABILITY_FAILED\n : ApplicationCodingTaskDisposition.WORKING_RESULT_RECORDED;\n const succeeded = disposition === ApplicationCodingTaskDisposition.WORKING_RESULT_RECORDED;\n const output = {\n succeeded,\n disposition,\n durationMs: Date.now() - startedAtMs,\n agentOutputTail: agentOutput.slice(-OUTPUT_TAIL_CHARS),\n // Recorded on the durable row because it is the difference between \"the\n // agent finished\" and \"the agent stopped\": a turn that ended on\n // `max_tokens` or `refusal` leaves a partial change set that looks exactly\n // like a complete one from the diff alone.\n ...(agentStopReason ? { agentStopReason } : {}),\n ...(codingSessionEventCount > 0 ? { codingSessionEventCount } : {}),\n ...(retainedCodingSessionFrames.length > 0 ? { codingSessionFrames: retainedCodingSessionFrames } : {}),\n // #2: the run's real cost, recorded on the durable row.\n //\n // This is what the previous transport structurally could not report, and\n // it was captured by the runner and dropped here — so the budget still saw\n // nothing. `usage` is optional in every field by contract, so absence is\n // preserved as absence rather than written as zero.\n ...(codingUsage ? { usage: codingUsage } : {}),\n ...(codingDeniedPermissionCount !== undefined\n ? { deniedPermissionCount: codingDeniedPermissionCount }\n : {}),\n // WHY each permission was decided, beside how many were refused. A refusal an operator\n // cannot explain is a refusal they cannot act on — see the field's contract.\n ...(codingPermissionDecisions && codingPermissionDecisions.length > 0\n ? { permissionDecisions: codingPermissionDecisions }\n : {}),\n ...(runError ? { error: buildOutputErrorPayload(runError) } : {}),\n ...(captureError ? { changeSetCaptureError: buildOutputErrorPayload(captureError) } : {}),\n ...(verificationInfrastructureError ? { verificationInfrastructureError: buildOutputErrorPayload(verificationInfrastructureError) } : {}),\n ...(traceabilityErrors.length > 0 ? { traceabilityErrors: traceabilityErrors.map(buildOutputErrorPayload) } : {}),\n ...(scopeAssessment ? { scopeAssessment } : {}),\n verification,\n ...(changeSet ? {\n changeSetSummary: {\n baselineHeadSha: changeSet.baselineHeadSha,\n postRunHeadSha: changeSet.postRunHeadSha,\n headMovedDuringRun: changeSet.headMovedDuringRun,\n stats: changeSet.stats,\n },\n } : { changeSetSummary: null }),\n };\n\n try {\n const updatePayload = CompanionUpdateActorTaskRequestSchema.parse({\n status: succeeded ? FlowsActors_Status.COMPLETED : FlowsActors_Status.FAILED,\n output,\n ...(changeSet ? { artifacts: [buildChangeSetArtifact(durableTask._id, changeSet)] } : {}),\n });\n await this.executionsService.updateActorTask(durableTask._id, updatePayload, runSession);\n } catch (error) {\n // Do not turn a failed durable PATCH into a retry: the agent may already\n // have changed files and re-execution would duplicate an unclassified\n // effect. The PROCESSING row is deliberately visible for the explicit\n // restart-review hook, while the trace records why it was not terminal.\n this.logger.error('Failed to persist terminal application coding-task result', {\n taskId: durableTask._id,\n taskRef: task.taskRef,\n error: describeCaughtError(error),\n });\n await traceBestEffort('record-terminal-patch-failure', () => this.traceOperationFailure({\n sessionContext: runSession,\n step: runStep,\n type: 'application-coding-task-terminal-patch-failure',\n summary: `Failed to persist terminal result for application coding task ${task.taskRef}`,\n error,\n payload: output,\n }));\n return;\n }\n\n if (succeeded) {\n await traceBestEffort('record-success', () => this.traceOperationSuccess({\n sessionContext: runSession,\n step: runStep,\n type: 'application-coding-task-run-success',\n summary: `Recorded working result for application coding task ${task.taskRef}`,\n payload: output,\n }));\n return;\n }\n await traceBestEffort('record-failure', () => this.traceOperationFailure({\n sessionContext: runSession,\n step: runStep,\n type: 'application-coding-task-run-failure',\n summary: `Application coding task ${task.taskRef} requires follow-up`,\n error: runError ?? captureError ?? verificationInfrastructureError ?? traceabilityErrors[0] ?? new Error(`Application coding task disposition: ${disposition}`),\n payload: output,\n }));\n }\n\n private buildApplicationCodingTaskTraceSummary(task: ApplicationCodingTaskContract): Record<string, unknown> {\n return {\n taskRef: task.taskRef,\n objectiveRef: task.objectiveRef,\n candidateRef: task.candidateRef,\n mutationScope: task.mutationScope,\n contextPlanRef: task.contextPlan.planRef,\n selectedSourceRefs: task.contextSelection.selectedSources.map((source) => source.sourceRef),\n verificationRef: task.verificationIntent.verificationRef,\n requiredChecks: task.verificationIntent.requiredChecks,\n installedSkillRefs: task.installedSkillRefs,\n };\n }\n\n // ================================================================\n // Verification hook (P-29c — enum vocabulary, never a command string)\n // ================================================================\n\n private buildVerificationPlan(kind: VerificationKind, requestedPath?: string): VerificationPlan {\n if (kind === VerificationKind.VITEST_PATH) {\n const sanitized = this.sanitizeRelativePath(requestedPath ?? '');\n const absoluteTestPath = join(this.companionContext.saasRoot, sanitized);\n const packageDir = this.findNearestPackageDir(dirname(absoluteTestPath));\n return {\n kind,\n path: sanitized,\n command: 'pnpm',\n args: ['exec', 'vitest', 'run', relative(packageDir, absoluteTestPath)],\n cwd: packageDir,\n };\n }\n\n // TYPECHECK — optional path points at a workspace package directory.\n const sanitized = requestedPath ? this.sanitizeRelativePath(requestedPath) : null;\n return {\n kind,\n path: sanitized,\n command: 'pnpm',\n args: ['exec', 'tsc', '--noEmit'],\n cwd: sanitized ? join(this.companionContext.saasRoot, sanitized) : this.companionContext.saasRoot,\n };\n }\n\n /**\n * The FK-resolution sweep, sourced from the `resources-registry` introspection\n * behavior — a FRESH subprocess import of the app's shared-lib, never the\n * companion's boot-time cache, so it judges exactly the bytes the mutation\n * left on disk. Fails the check when any `.isForeignKey()` field has no\n * registered relationship edge: invisible to every typecheck in the plan and\n * to the backend boot, fatal to the app's frontend at first page load\n * (`frontend_fk_resolution_failed` — wonder-crm, 2026-08-27).\n */\n private async runForeignKeyResolutionVerification(): Promise<VerificationOutcome> {\n const backendServiceKey = Object.entries(this.companionContext.servicesByKey)\n .find(([, service]) => !service.frontendType)?.[0];\n if (!backendServiceKey) {\n throw new Error('No backend service is available to run the frontend-fk-resolution verification.');\n }\n const result = await this.introspectionService.requestInfo({\n serviceKey: backendServiceKey,\n behavior: 'resources-registry',\n });\n if (!result.success) {\n throw new Error(`resources-registry introspection failed: ${JSON.stringify(result)}`);\n }\n const unresolved = (result.data as { unresolvableForeignKeyFields?: Array<{ resourceType: string; fieldName: string }> })\n .unresolvableForeignKeyFields ?? [];\n const success = unresolved.length === 0;\n return {\n kind: VerificationKind.FRONTEND_FK_RESOLUTION,\n path: null,\n success,\n message: success\n ? 'every isForeignKey() field resolves through a registered relationship'\n : `${unresolved.length} FK field(s) cannot be resolved to a resource type: `\n + unresolved.map(({ resourceType, fieldName }) => `${resourceType}.${fieldName}`).join(', ')\n + ' — declare a relationship with the corresponding foreignKeyField.',\n stdoutTail: '',\n stderrTail: '',\n };\n }\n\n /**\n * The settings-rail content sweep — the SHELL_PLACEMENT counterpart of the FK sweep,\n * and it exists for the same reason: the defect it catches is invisible to a typecheck.\n *\n * A placement naming a `destinationRef` the engine catalog does not ship is not a type\n * error. `resolveSettingsHubConfig` DROPS it, and the section silently never renders —\n * so a coding task that typo'd a ref passes `check:app-typecheck`, reports verified, and\n * leaves the application missing a settings section nobody is told about.\n *\n * WARNINGS do not fail the check. Only errors do: the verifier reports both severities,\n * and failing a coding task on an advisory would train the lane to ignore its own gate.\n */\n private async runSettingsPlacementContentVerification(): Promise<VerificationOutcome> {\n // Mirrors the FK sweep's resolution, on the other side of the same predicate: that\n // one wants a backend service, this one a FRONTEND service, because the settings rail\n // is authored in the frontend workspace and only that subprocess can import it.\n const frontendServiceKey = Object.entries(this.companionContext.servicesByKey)\n .find(([, service]) => service.frontendType)?.[0];\n if (!frontendServiceKey) {\n throw new Error('No frontend service is available to run the settings-placement-content verification.');\n }\n const result = await this.introspectionService.requestInfo({\n serviceKey: frontendServiceKey,\n behavior: 'settings-placement-content',\n });\n if (!result.success) {\n throw new Error(`settings-placement-content introspection failed: ${JSON.stringify(result)}`);\n }\n const data = result.data as {\n authored?: boolean;\n errors?: Array<{ severity: string; code: string; message: string }>;\n };\n const blocking = (data.errors ?? []).filter((error) => error.severity !== 'warning');\n const success = blocking.length === 0;\n return {\n kind: VerificationKind.SETTINGS_PLACEMENT_CONTENT,\n path: null,\n success,\n message: success\n ? (data.authored === false\n // Not a silent pass: an application with no authored rail has nothing to\n // verify, and saying so is the difference between \"checked and clean\" and\n // \"there was nothing to check\".\n ? 'no settings rail is authored — nothing to verify'\n : 'every authored placement names a destination the engine ships')\n : `${blocking.length} settings-placement error(s): `\n + blocking.map((error) => `${error.code}: ${error.message}`).join(' | '),\n stdoutTail: '',\n stderrTail: '',\n };\n }\n\n private async runVerification(plan: VerificationPlan): Promise<VerificationOutcome> {\n try {\n const result = await executeBoundedSubprocess({\n command: plan.command,\n args: plan.args,\n cwd: plan.cwd,\n env: buildVerificationEnv(),\n timeoutMs: VERIFICATION_TIMEOUT_MS,\n maxCapturedBytes: VERIFICATION_MAX_CAPTURED_BYTES,\n });\n return {\n kind: plan.kind,\n path: plan.path,\n success: true,\n message: `${plan.command} ${plan.args.join(' ')} passed`,\n stdoutTail: result.stdout.slice(-OUTPUT_TAIL_CHARS),\n stderrTail: result.stderr.slice(-OUTPUT_TAIL_CHARS),\n };\n } catch (error) {\n const details = (error as { details?: { stdout?: string; stderr?: string } }).details;\n return {\n kind: plan.kind,\n path: plan.path,\n success: false,\n message: describeCaughtError(error),\n stdoutTail: (details?.stdout ?? '').slice(-OUTPUT_TAIL_CHARS),\n stderrTail: (details?.stderr ?? '').slice(-OUTPUT_TAIL_CHARS),\n };\n }\n }\n\n /**\n * Run one admission-time validation and convert ANY refusal into a typed\n * VALIDATION error, preserving the original message as context.\n *\n * Deliberately a wrapper rather than N rewritten throw sites: the pure\n * resolver in the models layer has no error builder and should not grow one,\n * and a future admission check gets the same classification by being placed\n * here rather than by remembering to.\n */\n private admitTypedInput<T>(validate: () => T, message: string): T {\n try {\n return validate();\n } catch (error) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n message,\n validationError: describeCaughtError(error),\n },\n });\n }\n }\n\n /**\n * Sanitize an app-root-relative path from the wire: rejects absolute\n * paths, `..` escapes, backslashes, NUL bytes, and flag-lookalikes\n * (leading `-` would be parsed as an argv flag by the fixed commands).\n */\n private sanitizeRelativePath(requestedPath: string): string {\n const candidate = requestedPath.trim();\n const reject = (reason: string): never => {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n message: `Invalid verification path: ${reason}`,\n requestedPath,\n },\n });\n };\n\n if (!candidate) reject('path is empty');\n if (candidate.includes('\\0')) reject('path contains a NUL byte');\n if (candidate.includes('\\\\')) reject('use forward slashes');\n if (isAbsolute(candidate)) reject('path must be relative to the application root');\n if (candidate.startsWith('-')) reject('path must not start with a dash');\n const normalized = normalize(candidate);\n if (normalized.split(sep).includes('..')) reject('path must not escape the application root');\n\n const absolute = join(this.companionContext.saasRoot, normalized);\n const relativeFromRoot = relative(this.companionContext.saasRoot, absolute);\n if (relativeFromRoot.startsWith('..') || isAbsolute(relativeFromRoot)) {\n reject('path resolves outside the application root');\n }\n return normalized;\n }\n\n /** Nearest ancestor dir (within the app root) holding a package.json. */\n private findNearestPackageDir(startDir: string): string {\n let current = startDir;\n const root = this.companionContext.saasRoot;\n while (current.startsWith(root)) {\n if (existsSync(join(current, 'package.json'))) {\n return current;\n }\n const parent = dirname(current);\n if (parent === current) break;\n current = parent;\n }\n return root;\n }\n\n // ================================================================\n // Error + traceability helpers (service-owned wrappers, P-13 pattern)\n // ================================================================\n\n private buildDispatchConflictError(message: string): unknown {\n return this.errorBuilder.buildError(ErrorType.CONFLICT, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFLICT,\n context: { message },\n });\n }\n\n /** Map proper-lockfile ELOCKED contention onto the 409 vocabulary. */\n private mapLockError(error: unknown): unknown {\n if ((error as { code?: string })?.code === 'ELOCKED') {\n return this.buildDispatchConflictError(\n 'The workspace-mutation lock is held by another process (companion run or CLI). '\n + 'Dispatch is single-flight across processes (P-20); retry after the active run completes. '\n + 'If you are a dispatched coding-agent run: dispatching from a dispatched run is forbidden (P-35).',\n );\n }\n return error;\n }\n\n private createOperationTraceStep(\n sessionContext: CompanionExecutionSessionContext | undefined,\n label: string,\n ) {\n return sessionContext\n ? this.traceabilityService.createStep(sessionContext, {\n kind: 'coding-agent-dispatch',\n label,\n })\n : undefined;\n }\n\n private async traceOperationStart(input: {\n sessionContext?: CompanionExecutionSessionContext;\n step?: ReturnType<CompanionTraceabilityService['createStep']>;\n type: string;\n summary: string;\n payload?: unknown;\n artifactFileName?: string;\n artifactContent?: unknown;\n }): Promise<void> {\n if (!input.sessionContext) return;\n\n await this.traceabilityService.traceEvent({\n session: input.sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG,\n type: input.type,\n summary: input.summary,\n ...(input.payload !== undefined ? { payload: input.payload } : {}),\n ...(input.step ? { step: input.step } : {}),\n });\n if (input.artifactFileName && input.artifactContent !== undefined) {\n await this.traceabilityService.writeArtifact({\n session: input.sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG_VERBOSE,\n fileName: input.artifactFileName,\n content: input.artifactContent,\n ...(input.step ? { step: input.step } : {}),\n });\n }\n }\n\n private async traceOperationSuccess(input: {\n sessionContext?: CompanionExecutionSessionContext;\n step?: ReturnType<CompanionTraceabilityService['createStep']>;\n type: string;\n summary: string;\n payload?: unknown;\n artifactFileName?: string;\n artifactContent?: unknown;\n }): Promise<void> {\n if (!input.sessionContext) return;\n\n if (input.artifactFileName && input.artifactContent !== undefined) {\n await this.traceabilityService.writeArtifact({\n session: input.sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG_VERBOSE,\n fileName: input.artifactFileName,\n content: input.artifactContent,\n ...(input.step ? { step: input.step } : {}),\n });\n }\n await this.traceabilityService.traceEvent({\n session: input.sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG,\n type: input.type,\n summary: input.summary,\n ...(input.payload !== undefined ? { payload: input.payload } : {}),\n ...(input.step ? { step: input.step } : {}),\n });\n }\n\n private async traceOperationFailure(input: {\n sessionContext?: CompanionExecutionSessionContext;\n step?: ReturnType<CompanionTraceabilityService['createStep']>;\n type: string;\n summary: string;\n error: unknown;\n payload?: unknown;\n }): Promise<void> {\n if (!input.sessionContext) return;\n\n await this.traceabilityService.traceEvent({\n session: input.sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG,\n type: input.type,\n summary: input.summary,\n payload: {\n ...(input.payload && typeof input.payload === 'object'\n ? input.payload as Record<string, unknown>\n : { input: input.payload }),\n error: buildOutputErrorPayload(input.error),\n },\n ...(input.step ? { step: input.step } : {}),\n });\n }\n\n private async traceOperationArtifact(\n sessionContext: CompanionExecutionSessionContext | undefined,\n step: ReturnType<CompanionTraceabilityService['createStep']> | undefined,\n fileName: string,\n content: unknown,\n ): Promise<void> {\n if (!sessionContext) return;\n await this.traceabilityService.writeArtifact({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG_VERBOSE,\n fileName,\n content,\n ...(step ? { step } : {}),\n });\n }\n}\n\ninterface VerificationPlan {\n kind: VerificationKind;\n path: string | null;\n command: string;\n args: string[];\n cwd: string;\n}\n\n/**\n * Change-set artifact persisted on the task row (P-19: file list + stats\n * + head SHAs + attribution classes). `fullDiffText` is deliberately\n * stripped — the raw diff lives in the traceability artifact only.\n *\n * Persisted as `FlowsActors_IO_PartKind.STRUCTURED` with the capture in\n * `content.data`. History: on 2026-07-03 this was temporarily JSON-encoded\n * into a TEXT artifact because the zod-to-mongoose converter flattened\n * nested discriminated unions (`artifacts[]` on the task row) onto their\n * FIRST variant, making `content.text` a required Mongoose path for every\n * artifact. The converter now merges nested union variants into an\n * all-optional superset schema, so the natural STRUCTURED shape persists\n * again (requires a saas-backend-lib dist carrying that fix).\n */\nfunction buildChangeSetArtifact(taskId: string, changeSet: GitChangeSetCapture): ArtifactInstance {\n const { fullDiffText: _fullDiffText, ...structuredCapture } = changeSet;\n return {\n ref: `coding-agent-change-set-${taskId}`,\n type: FlowsActors_IO_PartKind.STRUCTURED,\n name: 'coding-agent-change-set',\n description: 'Read-only git change-set capture with per-file attribution (P-19)',\n origin: { taskId },\n content: { data: structuredCapture },\n createdAt: new Date().toISOString(),\n };\n}\n\n/** Same minimal allowlist the CLI spawn uses (P-18). */\nfunction buildVerificationEnv(): NodeJS.ProcessEnv {\n // Same minimal identity allowlist the CLI spawn uses (P-18) — incl.\n // USER/LOGNAME so a verification hook that shells out to per-user\n // tooling behaves like the agent run. Kept in lockstep with\n // `ClaudeCliCompanionService`'s allowlist.\n const env: NodeJS.ProcessEnv = {};\n for (const key of ['PATH', 'HOME', 'USER', 'LOGNAME', 'SHELL', 'TERM']) {\n const value = process.env[key];\n if (value !== undefined) env[key] = value;\n }\n return env;\n}\n\nfunction buildOutputErrorPayload(error: unknown): unknown {\n if (isWildoBackendError(error)) return error;\n if (error instanceof Error) {\n return {\n message: error.message,\n name: error.name,\n ...(error.stack ? { stack: error.stack } : {}),\n };\n }\n return { message: String(error) };\n}\n\nfunction createDeferred<T>(): {\n promise: Promise<T>;\n resolve: (value: T) => void;\n reject: (error: unknown) => void;\n} {\n let settled = false;\n let resolveFn!: (value: T) => void;\n let rejectFn!: (error: unknown) => void;\n const promise = new Promise<T>((resolve, reject) => {\n resolveFn = resolve;\n rejectFn = reject;\n });\n return {\n promise,\n resolve: (value) => {\n if (settled) return;\n settled = true;\n resolveFn(value);\n },\n reject: (error) => {\n if (settled) return;\n settled = true;\n rejectFn(error);\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"coding-agent-dispatch.companion.service.js","sourceRoot":"","sources":["../../../../../src/claude-cli/services/coding-agent-dispatch.companion.service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;;;;;;;;;;;;;AAEH,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAChF,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAEnD,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EACL,oBAAoB,EACpB,0BAA0B,EAC1B,aAAa,EACb,kBAAkB,EAClB,wBAAwB,EACxB,mBAAmB,GACpB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,iBAAiB,EAEjB,2BAA2B,EAC3B,SAAS,EACT,uBAAuB,EACvB,kBAAkB,EAClB,mBAAmB,GAGpB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAKL,mCAAmC,EACnC,sBAAsB,GAIvB,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,mCAAmC,GAEpC,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plicationCodingTask` admits one typed `ApplicationCodingTaskContract`\n * (the episode runtime's coding revision owner is the caller), renders its\n * prompt from the sealed contract, creates an `Actors_Task` row, spawns the\n * Claude CLI in the background against the application worktree, captures\n * a read-only git change set with per-file attribution, runs the contract's\n * registered verification checks, then PATCHes the task with status/output/\n * artifacts. One admission never spans the multi-minute run (P-16) —\n * callers await the settlement or poll `/tasks/actors/:taskId`. The raw\n * `POST /coding-agent/dispatch` endpoint (caller-composed prompt) was\n * deleted at the first-activation hard cut.\n *\n * # Locking & recursion cap (P-20 / P-19b / P-35)\n *\n * Runs are single-flight, serialized by a cross-process lock on the\n * dedicated target `<saasRoot>/.wildo-saas/state/workspace-mutation.lock`\n * (`withDedicatedFileLock` from `@wildo-ai/platform-config-lib`,\n * proper-lockfile pattern — an in-memory mutex alone is forbidden because\n * the CLI mutates the same worktree from other processes). An in-memory\n * flag fronts the lock for fast 409s. The lock is held for the WHOLE run.\n *\n * The P-35 recursion cap falls out structurally: a dispatched run that\n * calls dispatch (it has shell access and can read the machine-local\n * token) always finds the lock held by ITS OWN run and is rejected 409 —\n * a dispatched run can never dispatch. Deliberately, the lock does NOT\n * gate Paul's parallel sessions (P-19b): CLAUDE.md forbids session\n * coordination; per-file attribution is the compensation, not exclusion.\n *\n * # Traceability (P-21)\n *\n * L2 runs are NOT traced by the engine `AgentCallTraceSink` — the direct\n * claude-cli lane bypasses it AND Bottleneck rate limiting. Do not assume\n * traced-for-free: this service owns its companion-traceability events\n * (DEBUG) and artifacts (DEBUG_VERBOSE); a sink wrapper emission is\n * deferred. The background phase runs under an INTERNAL trace session\n * (`createInternalSession`) because the HTTP request session ends at the\n * 202-style response.\n *\n * # Run limits (P-18)\n *\n * Defaults 30 min / 10 MiB; request-overridable up to hard caps\n * 60 min / 32 MiB. The byte cap REJECTS (kills the run), it does not\n * truncate. Args stay `--print` + `--model` (no extraArgs field), prompt\n * on stdin, env = `{ PATH, HOME, SHELL, TERM }` (composed inside\n * the ACP session runner).\n */\n\nimport { isAbsolute, join, normalize, relative, sep, dirname } from 'node:path';\nimport { existsSync, realpathSync } from 'node:fs';\n\nimport { inject, injectable } from 'inversify';\nimport {\n AgentsBackendService,\n ErrorBuilderBackendService,\n LoggerService,\n SAAS_SERVICE_TYPES,\n executeBoundedSubprocess,\n describeCaughtError,\n} from '@wildo-ai/saas-backend-lib';\nimport {\n Actor_Task_Topics,\n type AgentTraceContext,\n ErrorCustomMessageReference,\n ErrorType,\n FlowsActors_IO_PartKind,\n FlowsActors_Status,\n isWildoBackendError,\n type ArtifactInstance,\n type FlowsActors_Agent_Invocation,\n} from '@wildo-ai/saas-models';\nimport {\n CodingAgent_EndOfTurnClassification,\n CodingAgent_OperationContext_BaseSchema,\n CodingAgent_RunTaskInputSchema,\n CodingAgent_RunTaskOutputSchema,\n CodingAgent_SessionSuspensionSchema,\n CodingAgent_StopReason,\n type CodingAgent_RunTaskOutput,\n type CodingAgent_SessionSuspension,\n type CodingAgent_Usage,\n} from '@wildo-ai/external-connectors-models';\nimport {\n ApplicationCodingTaskContractSchema,\n type ApplicationCodingTaskContract,\n} from '@wildo-ai/saas-specifications/application-creation';\nimport {\n getWorkspaceMutationLockPath as resolveWorkspaceMutationLockPath,\n withDedicatedFileLock,\n} from '@wildo-ai/platform-config-lib';\n\nimport { sanitizeWorkbenchCreationPlaneIdentity } from '@wildo-ai/platform-core-shared';\nimport { COMPANION_SERVICE_TYPES } from '../../core/inject/models/service-types';\nimport type { CompanionContext } from '../../core/context/companion-context';\nimport type {\n CompanionExecutionSessionContext,\n} from '../../core/traceability/companion-traceability.models';\nimport { CompanionTraceabilityLevel, CompanionTraceAliasKind } from '../../core/traceability/companion-traceability.models';\nimport { CompanionTraceabilityService } from '../../core/traceability/companion-traceability.service';\nimport { CompanionIntrospectionService } from '../../core/introspection/services/companion-introspection.companion.service';\nimport { CompanionExecutionsCompanionService } from '../../executions/services/companion-executions.companion.service';\nimport {\n CompanionCreateActorTaskRequestSchema,\n CompanionUpdateActorTaskRequestSchema,\n type CompanionCodingAgentStatusResponse,\n} from '../../companion-api/companion-api.schemas';\nimport { GitChangeSetCompanionService } from './git-change-set.companion.service';\nimport {\n APPLICATION_CODING_AGENT_REF,\n APPLICATION_CODING_TURN_CLASSIFIER_AGENT_REF,\n CodingTurnEndClassificationOutputSchema,\n} from '../../meta-workflows/models/application-coding-agent.actors-system.definitions';\nimport {\n ChangeSetAttributionClass,\n ApplicationCodingTaskDisposition,\n type ApplicationCodingTaskRunAdmission,\n type ApplicationCodingTaskVerificationPlan,\n DISPATCH_DEFAULT_MAX_CAPTURED_BYTES,\n DISPATCH_DEFAULT_TIMEOUT_MS,\n DISPATCH_HARD_MAX_CAPTURED_BYTES,\n DISPATCH_HARD_MAX_TIMEOUT_MS,\n VerificationKind,\n renderApplicationCodingTaskAgentPrompt,\n resolveApplicationCodingTaskVerificationPlans,\n type GitChangeSetCapture,\n type GitWorktreeSnapshot,\n} from '../models/coding-agent-dispatch.models';\n\n/** Fixed, non-overridable limits for the verification hook subprocess. */\nconst VERIFICATION_TIMEOUT_MS = 10 * 60_000;\nconst VERIFICATION_MAX_CAPTURED_BYTES = 10 * 1024 * 1024;\n\n\n/**\n * The session frames worth retaining on the durable row: what the agent DID and\n * what it changed. Message chunks are already summarised by the output tail, and\n * usage frames are superseded by the recorded totals.\n */\nconst RETAINED_CODING_SESSION_EVENT_KINDS: ReadonlySet<string> = new Set(['tool_call', 'tool_call_update', 'plan']);\n/** Ceiling on retained frames — a bound, not a sample: excess is dropped, never summarised. */\nconst RETAINED_CODING_SESSION_FRAME_LIMIT = 200;\n\n/** Tail size persisted on the task row; full streams go to traceability artifacts. */\nconst OUTPUT_TAIL_CHARS = 16_000;\n\ntype DispatchedTaskRow = Awaited<\n ReturnType<CompanionExecutionsCompanionService['createActorTask']>\n>;\n\ninterface ActiveRunState {\n taskId: string;\n startedAt: string;\n /** Cancels the in-flight coding session. Cooperative first, kill second. */\n abortController: AbortController;\n}\n\n/**\n * A run that PARKED on a genuine question, retained in memory so the operator's\n * answer can resume the SAME agent session with the task's full context.\n *\n * In-process only, by design: the agent persists the session on disk (so\n * `session/load` could resume it after a restart), but the task CONTRACT — the\n * mutation scope the resume must still be held to, the verification plan, the\n * original baseline the final change set is measured against — lives here. A\n * companion restart therefore drops the answerable state, which surfaces as a\n * typed refusal rather than a resume that has forgotten the task's bounds.\n */\nexport interface ParkedCodingSessionState {\n readonly durableTask: DispatchedTaskRow;\n readonly task: ApplicationCodingTaskContract;\n readonly verificationPlans: readonly ApplicationCodingTaskVerificationPlan[];\n readonly baseline: GitWorktreeSnapshot;\n readonly suspension: CodingAgent_SessionSuspension;\n readonly parkedAt: string;\n}\n\n/** Local narrow: is this an indexable object (not null, not an array)? */\nfunction isRecordValue(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** One live frame relayed to an SSE subscriber: an agent event or a ladder state change. */\nexport interface CodingSessionLiveFrame {\n readonly channel: 'event' | 'state';\n readonly payload: unknown;\n}\n\ninterface VerificationOutcome {\n kind: VerificationKind;\n path: string | null;\n success: boolean;\n message: string;\n stdoutTail: string;\n stderrTail: string;\n}\n\n/** Result of checking every attributed changed-during-run file against the sealed task scope. */\ninterface ApplicationCodingTaskScopeAssessment {\n allowed: boolean;\n violatingPaths: string[];\n /**\n * A commit landed inside the run window, so this window's attribution is\n * INCOMPLETE: a commit empties the dirty set every other class here is\n * computed from, and a parallel session's commit is indistinguishable from\n * the agent's own.\n *\n * RECORDED, NOT REFUSED — decided 2026-08-19, and the reasoning is the same\n * rule the plan applies to every other strictness in this vertical: exactness\n * is retained where a protected, accepted-state or real-effect consumer needs\n * it, and nowhere else. A coding run produces a WORKING result; it mutates no\n * accepted truth. Refusing the whole run here bought no protection of\n * anything accepted, while on a shared tree with parallel sessions ANY commit\n * overlapping ANY run — including one touching nothing the agent touched —\n * failed that run, with no worktree isolation to fall back on (ruled out for\n * this application) and no remedy a single session can enforce.\n *\n * What replaces the refusal is visibility that a consumer cannot miss: the\n * committed paths are recovered into the change set as\n * `COMMITTED_DURING_RUN`, and this flag rides on the recorded result. The\n * OBLIGATION moves with it — whatever later accepts this working result must\n * treat `historyMutated` as attribution it cannot rely on, and must not\n * promote it without review. That is the acceptance tier's job, which is\n * where exactness belongs.\n */\n historyMutated: boolean;\n}\n\n/**\n * Scope checking is deliberately based on the post-run attribution capture,\n * not only clean-baseline files. A baseline-dirty file changed again during a\n * run is not safely attributable to the Agent, but it is still a real effect\n * inside the host window and must not be used to bypass a declared boundary.\n */\nfunction assessApplicationCodingTaskMutationScope(\n changeSet: GitChangeSetCapture,\n allowedPrefixes: readonly string[],\n prohibitedPrefixes: readonly string[],\n): ApplicationCodingTaskScopeAssessment {\n const normalizedAllowed = allowedPrefixes.map(normalizeApplicationRelativePrefix);\n const normalizedProhibited = prohibitedPrefixes.map(normalizeApplicationRelativePrefix);\n /*\n * Committed paths are deliberately EXCLUDED from the scope decision. They are\n * present in `changeSet.files` (as `COMMITTED_DURING_RUN`) so nothing is\n * invisible, but nobody can attribute them: a parallel session's commit and\n * the agent's own look identical from here, so refusing on them would fail\n * runs for other people's work. `historyMutated` carries that fact forward\n * instead, and the acceptance tier decides what an unattributable window is\n * worth.\n */\n /*\n * A disappearance is only a VIOLATION when the run can be held responsible for it, and a commit\n * landing inside the window is precisely when it cannot.\n *\n * `disappearedFromBaseline` is \"dirty at baseline, no longer dirty post-run\", which has two\n * causes that look identical from here: the agent reverted or deleted the file (attributable,\n * and a real boundary breach if the path is out of scope), or a commit emptied the dirty set\n * (not attributable — a parallel session's commit and the agent's own are indistinguishable,\n * which is the exact reasoning the `COMMITTED_DURING_RUN` exclusion above already applies).\n *\n * Including them unconditionally made the two treatments contradict each other: the committed\n * PATHS were excluded as unattributable while the disappearance THAT SAME COMMIT CAUSED was\n * used to fail the run. Measured 2026-08-28 on wonder-crm — a run that stopped cleanly at\n * `end_turn`, honoured every permission decision and wrote NOTHING (`runExclusive: 0`,\n * `appearedDuringRun: 0`) was recorded `mutation_scope_violation` against 13 engine paths it\n * never touched, because a human committed at 17:47:56 and 17 baseline-dirty files left the\n * set. The field's own contract already said they \"are NOT attributed change-set entries\".\n *\n * So the exclusion is conditional, not blanket: with no commit in the window a disappearance\n * IS the run's doing and still fails it. Only the case the run cannot be responsible for is\n * dropped, and it stays visible — the paths remain on `disappearedFromBaseline`, and\n * `historyMutated` tells the acceptance tier the window is unattributable.\n */\n const disappearancesAttributableToTheRun = changeSet.headMovedDuringRun\n ? []\n : changeSet.disappearedFromBaseline;\n\n const violatingPaths = [\n ...changeSet.files\n .filter((entry) => entry.attribution !== ChangeSetAttributionClass.COMMITTED_DURING_RUN)\n .map((entry) => entry.path),\n ...disappearancesAttributableToTheRun,\n ]\n .filter((path) => {\n const normalizedPath = normalizeApplicationRelativePrefix(path);\n const inAllowedScope = normalizedAllowed.some((prefix) => matchesApplicationRelativePrefix(normalizedPath, prefix));\n const inProhibitedScope = normalizedProhibited.some((prefix) => matchesApplicationRelativePrefix(normalizedPath, prefix));\n return !inAllowedScope || inProhibitedScope;\n });\n return {\n // `historyMutated` does NOT gate admissibility (see the field's contract):\n // it is recorded so the consumer of this working result can see that the\n // window is unattributable, not used to fail a run that protected nothing.\n allowed: violatingPaths.length === 0,\n violatingPaths,\n historyMutated: changeSet.headMovedDuringRun,\n };\n}\n\n/**\n * The LIVE counterpart of {@link assessApplicationCodingTaskMutationScope}:\n * decides, while the agent is still running, whether one absolute path is\n * inside the task's declared mutation scope.\n *\n * Deliberately reuses the SAME normalisation and boundary matching as the\n * post-hoc assessment. Two predicates answering \"is this path in scope?\" with\n * different rules would produce the worst possible outcome — a run permitted\n * live and then judged a scope violation afterwards, or the reverse.\n *\n * It NARROWS and never widens: the permission ceiling still decides the KIND of\n * operation, and this only refuses a path that ceiling would otherwise allow.\n * A path outside the workspace is refused outright rather than reasoned about.\n */\nexport function buildApplicationCodingTaskLocationPredicate(\n workspaceRootPath: string,\n allowedPrefixes: readonly string[],\n prohibitedPrefixes: readonly string[],\n): (absolutePath: string) => boolean {\n const normalizedAllowed = allowedPrefixes.map(normalizeApplicationRelativePrefix);\n const normalizedProhibited = prohibitedPrefixes.map(normalizeApplicationRelativePrefix);\n\n /*\n * Compare against BOTH the configured root and its physical realpath.\n *\n * Agents report CANONICAL absolute paths. Measured live on 2026-08-27: with a\n * workspace under `/var/folders/...` (a macOS symlink to `/private/var/...`),\n * the agent's permission request named the `/private/...` form while the\n * configured root was the `/var/...` form, so an IN-SCOPE edit was refused and\n * the run reported the agent declining to do its job. A scope predicate that\n * silently denies everything is worse than one that denies nothing, because\n * it looks like the agent failing rather than the guard misfiring.\n */\n const candidateRoots = [workspaceRootPath];\n try {\n const physicalRoot = realpathSync.native(workspaceRootPath);\n if (physicalRoot !== workspaceRootPath) {\n candidateRoots.push(physicalRoot);\n }\n } catch {\n // An unresolvable root is left as authored; the relative check below still\n // refuses anything outside it.\n }\n\n return (absolutePath: string): boolean => {\n if (!isAbsolute(absolutePath)) {\n return false;\n }\n const relativePath = candidateRoots\n .map((root) => relative(root, absolutePath))\n .find((candidate) => candidate && !candidate.startsWith('..') && !isAbsolute(candidate));\n if (!relativePath) {\n return false;\n }\n const normalizedPath = normalizeApplicationRelativePrefix(relativePath.split(sep).join('/'));\n const inAllowedScope = normalizedAllowed.some((prefix) => matchesApplicationRelativePrefix(normalizedPath, prefix));\n const inProhibitedScope = normalizedProhibited.some((prefix) => matchesApplicationRelativePrefix(normalizedPath, prefix));\n return inAllowedScope && !inProhibitedScope;\n };\n}\n\nfunction normalizeApplicationRelativePrefix(value: string): string {\n return value.replace(/\\\\/g, '/').replace(/^\\.\\//, '').replace(/\\/+$/, '');\n}\n\n/** Prefix matches require a path boundary: `src/app` does not admit `src/application`. */\nfunction matchesApplicationRelativePrefix(path: string, prefix: string): boolean {\n return path === prefix || path.startsWith(`${prefix}/`);\n}\n\n@injectable()\nexport class CodingAgentDispatchCompanionService {\n private readonly logDebug: (message: string, context?: Record<string, unknown>) => void;\n\n /**\n * In-memory single-flight flag — the FAST 409 in front of the\n * cross-process lockfile, never a replacement for it (P-20).\n */\n private activeRun: ActiveRunState | null = null;\n /**\n * Per-process settlement signal of every application coding task THIS\n * process admitted: resolved when the background run has recorded its\n * terminal durable result (or given up trying). This is the \"owner's\n * completion hook\" the episode driver waits on instead of polling the\n * Actor Task row; a task admitted by a previous process has no entry here,\n * which is correct — restart reconciliation already terminalized it.\n */\n private readonly applicationCodingTaskSettlements = new Map<string, { readonly promise: Promise<void>; resolve(): void }>();\n\n /**\n * Tasks parked on a question, keyed by task id — the answerable set. A task\n * enters here when a run returns a `suspension` and leaves when it is answered\n * (resumed) or explicitly abandoned. See {@link ParkedCodingSessionState}.\n */\n private readonly parkedCodingSessions = new Map<string, ParkedCodingSessionState>();\n\n /**\n * Live-frame subscribers keyed by task id. Fed by the coding session's own\n * event stream and the ladder's state transitions while a run is active;\n * drained by the SSE endpoint. Best-effort throughout — a slow or throwing\n * subscriber never touches the run it observes.\n */\n private readonly codingSessionSubscribers = new Map<string, Set<(frame: CodingSessionLiveFrame) => void>>();\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.Logger)\n private readonly logger: LoggerService,\n @inject(SAAS_SERVICE_TYPES.ErrorBuilderService)\n private readonly errorBuilder: ErrorBuilderBackendService,\n @inject(COMPANION_SERVICE_TYPES.CompanionContext)\n private readonly companionContext: CompanionContext,\n @inject(SAAS_SERVICE_TYPES.AgentsBackendService)\n private readonly agentsService: AgentsBackendService,\n @inject(COMPANION_SERVICE_TYPES.GitChangeSetService)\n private readonly gitChangeSetService: GitChangeSetCompanionService,\n @inject(COMPANION_SERVICE_TYPES.ExecutionsService)\n private readonly executionsService: CompanionExecutionsCompanionService,\n @inject(COMPANION_SERVICE_TYPES.TraceabilityService)\n private readonly traceabilityService: CompanionTraceabilityService,\n @inject(COMPANION_SERVICE_TYPES.IntrospectionService)\n private readonly introspectionService: CompanionIntrospectionService,\n ) {\n this.logDebug = this.logger.debugByType('CodingAgentDispatchCompanionService');\n this.logger.setDebugTypeLogging('CodingAgentDispatchCompanionService', true);\n }\n\n /**\n * Admit one application-authored coding task onto the normal Flows/Actors\n * Claude Code path — the ONLY coding entry since the raw dispatch endpoint\n * was deleted at the first-activation hard cut. This method accepts only the\n * sealed typed task produced by application composition. The returned\n * acknowledgement is intentionally non-terminal; a completed Actor Task\n * records a working code result and its evidence, never accepted\n * application truth.\n */\n public async runApplicationCodingTask(\n rawTask: ApplicationCodingTaskContract,\n sessionContext?: CompanionExecutionSessionContext,\n ): Promise<ApplicationCodingTaskRunAdmission> {\n /*\n * Both admission refusals below are TYPED.\n *\n * A malformed contract surfaced as a raw `ZodError` and an unregistered\n * check ref as a plain `Error`, so the two refusals a caller can actually\n * provoke reached the transport as unclassified failures and answered 500\n * INTERNAL — indistinguishable from the host being broken. They are\n * VALIDATION: the request is refused, nothing was locked, created or run.\n */\n const task = this.admitTypedInput(\n () => ApplicationCodingTaskContractSchema.parse(rawTask),\n 'Application coding task contract is not valid.',\n );\n // Resolve before acquiring the lock or creating a task. A semantic check\n // name is not a command and cannot silently fall back to an arbitrary\n // workspace typecheck.\n const verificationPlans = this.admitTypedInput(\n () => resolveApplicationCodingTaskVerificationPlans(task.verificationIntent.requiredChecks),\n 'Application coding task names an unregistered verification check.',\n );\n const traceStep = this.createOperationTraceStep(sessionContext, 'application-coding-task-admission');\n const renderedPrompt = renderApplicationCodingTaskAgentPrompt(task);\n await this.traceOperationStart({\n sessionContext,\n step: traceStep,\n type: 'application-coding-task-admission-start',\n summary: `Admit application coding task ${task.taskRef}`,\n payload: this.buildApplicationCodingTaskTraceSummary(task),\n artifactFileName: 'application-coding-task-input.txt',\n artifactContent: renderedPrompt,\n });\n\n if (this.activeRun) {\n throw this.buildDispatchConflictError(\n `A coding-agent run is already active (task ${this.activeRun.taskId}, started ${this.activeRun.startedAt}). `\n + 'Application coding tasks share the same cross-process mutation lock.',\n );\n }\n\n const admission = createDeferred<{ task: DispatchedTaskRow; baseline: GitWorktreeSnapshot }>();\n const backgroundRun = withDedicatedFileLock(\n this.getWorkspaceMutationLockPath(),\n async () => {\n let admitted: { task: DispatchedTaskRow; baseline: GitWorktreeSnapshot };\n try {\n const baseline = await this.gitChangeSetService.captureWorktreeSnapshot();\n const durableTask = await this.createApplicationCodingTask(task, baseline, sessionContext);\n this.activeRun = {\n taskId: durableTask._id,\n startedAt: new Date().toISOString(),\n abortController: new AbortController(),\n };\n admitted = { task: durableTask, baseline };\n // Registered BEFORE the admission is resolved, so a caller that\n // awaits the settlement right after admission can never miss it.\n const settlement = createDeferred<void>();\n this.applicationCodingTaskSettlements.set(durableTask._id, { promise: settlement.promise, resolve: () => settlement.resolve(undefined) });\n admission.resolve(admitted);\n } catch (error) {\n admission.reject(error);\n return;\n }\n\n try {\n await this.executeApplicationCodingTask(task, renderedPrompt, verificationPlans, admitted.task, admitted.baseline);\n } finally {\n this.activeRun = null;\n this.applicationCodingTaskSettlements.get(admitted.task._id)?.resolve();\n }\n },\n { retries: { retries: 0 } },\n );\n backgroundRun.catch((error: unknown) => {\n admission.reject(this.mapLockError(error));\n this.logDebug('Application coding-task background run chain terminated with error', {\n error: describeCaughtError(error),\n taskRef: task.taskRef,\n });\n });\n\n const admitted = await admission.promise;\n const response: ApplicationCodingTaskRunAdmission = {\n taskId: admitted.task._id,\n status: FlowsActors_Status.PROCESSING,\n taskRef: task.taskRef,\n baselineHeadSha: admitted.baseline.headSha,\n baselineDirtyFileCount: Object.keys(admitted.baseline.files).length,\n };\n await this.traceOperationSuccess({\n sessionContext,\n step: traceStep,\n type: 'application-coding-task-admission-success',\n summary: `Admitted application coding task ${task.taskRef} as Actor Task ${admitted.task._id}`,\n payload: response,\n artifactFileName: 'application-coding-task-admission.json',\n artifactContent: response,\n });\n return response;\n }\n\n /**\n * The settlement of one application coding task admitted by THIS process:\n * resolves once its terminal durable result has been recorded (success or\n * failure) — the only moment a waiting episode can read a non-PROCESSING\n * row. `null` for a task this process did not admit (a previous process's\n * row, already terminalized by restart reconciliation, or an unknown id):\n * there is nothing to wait for, and a caller must not spin on it.\n */\n public awaitApplicationCodingTaskSettlement(taskId: string): Promise<void> | null {\n return this.applicationCodingTaskSettlements.get(taskId)?.promise ?? null;\n }\n\n /**\n * Reconcile only a previous process's unfinished application-coding rows.\n *\n * A companion restart cannot prove the previous Claude Code subprocess is\n * still running. Retrying could duplicate a worktree mutation, while\n * reverting would destroy evidence. The safe v0 result is therefore a\n * terminal physical abort plus an explicit human-review disposition. Root\n * wires this method into ordinary startup in a later, separately reviewed\n * join; this source slice never invokes it automatically.\n */\n public async reconcileInterruptedApplicationCodingTasks(\n sessionContext?: CompanionExecutionSessionContext,\n ): Promise<{ reconciledTaskIds: string[] }> {\n const processingTasks = await this.executionsService.listActorTasks({\n status: FlowsActors_Status.PROCESSING,\n limit: 200,\n }, sessionContext);\n const reconciledTaskIds: string[] = [];\n\n for (const task of processingTasks) {\n if (task.actors?.actorRef !== APPLICATION_CODING_AGENT_REF) continue;\n /*\n * A PARKED task is deliberately PROCESSING with no live child — its agent process is already\n * closed and the answer resumes the persisted session via `session/load`. That is the ONE\n * PROCESSING shape a restart must NOT terminalize: surviving the restart is the suspension's\n * whole design (`reconstructParkedCodingTaskForResume` re-selects it from the build plan).\n * Measured 2026-09-04, first live park on a restart: this sweep terminalized the parked row\n * and nulled its suspension three seconds before the operator's answer arrived, so the\n * restart-durability door refused with \"no coding task is awaiting an answer\". Only a FRESH,\n * RESUMABLE suspension is exempt — an expired `parkedUntil`, or an agent that cannot\n * `session/load`, leaves a question nobody can answer on the same session, and terminalizing\n * it for review is then the honest outcome.\n */\n const parkedOutput = (task as { output?: { disposition?: unknown; suspension?: unknown } }).output;\n if (parkedOutput?.disposition === ApplicationCodingTaskDisposition.AWAITING_OPERATOR_INPUT) {\n const parsedSuspension = CodingAgent_SessionSuspensionSchema.safeParse(parkedOutput.suspension);\n const stillAnswerable = parsedSuspension.success\n && parsedSuspension.data.resumable\n && Date.parse(parsedSuspension.data.parkedUntil) > Date.now();\n if (stillAnswerable) continue;\n }\n let currentSnapshot: GitWorktreeSnapshot | null = null;\n let captureError: unknown = null;\n try {\n currentSnapshot = await this.gitChangeSetService.captureWorktreeSnapshot();\n } catch (error) {\n captureError = error;\n }\n\n const updatePayload = CompanionUpdateActorTaskRequestSchema.parse({\n status: FlowsActors_Status.ABORTED,\n output: {\n succeeded: false,\n disposition: ApplicationCodingTaskDisposition.INTERRUPTED_REQUIRES_REVIEW,\n recoveryEvidence: currentSnapshot\n ? {\n headSha: currentSnapshot.headSha,\n dirtyFileCount: Object.keys(currentSnapshot.files).length,\n capturedAt: currentSnapshot.capturedAt,\n }\n : null,\n ...(captureError ? { recoveryCaptureError: buildOutputErrorPayload(captureError) } : {}),\n },\n });\n await this.executionsService.updateActorTask(task._id, updatePayload, sessionContext);\n reconciledTaskIds.push(task._id);\n }\n\n return { reconciledTaskIds };\n }\n\n /**\n * Readiness snapshot for the status route. HONESTY CONTRACT: the\n * underlying `isAvailable()` checks ONLY that the provider registry\n * exposes an AGENT_CLIENT_PROTOCOL contract for anthropic — it does NOT\n * guarantee the ACP adapter is installed, spawnable, or authenticated. A\n * `true` here can still be followed by a spawn/auth failure at run time.\n */\n /**\n * The cross-process workspace-mutation lock path (P-19b) — one lock for\n * every mutating coding run against this application worktree.\n */\n public getWorkspaceMutationLockPath(): string {\n return resolveWorkspaceMutationLockPath(this.companionContext.saasRoot);\n }\n\n /**\n * Cancel the in-flight coding run, if there is one.\n *\n * Cooperative by construction: this signals the session, and the runner sends\n * `session/cancel` and waits before killing anything. The run therefore\n * TERMINALISES NORMALLY — with stop reason `cancelled` and a captured change\n * set — rather than vanishing. That distinction is the whole point: an\n * operator who stops a run still needs to know what it had already written.\n *\n * Returns the task that was asked to stop, or `null` when nothing is running.\n * Idempotent: cancelling an already-cancelled run signals an aborted\n * controller again, which is a no-op.\n */\n public cancelActiveApplicationCodingTask(): { taskId: string; startedAt: string } | null {\n const active = this.activeRun;\n if (!active) {\n return null;\n }\n this.logDebug('Cancelling active application coding task', { taskId: active.taskId });\n active.abortController.abort();\n return { taskId: active.taskId, startedAt: active.startedAt };\n }\n\n public getStatus(): CompanionCodingAgentStatusResponse {\n return {\n // Reports a fact this service can actually establish: whether the coding\n // agent is registered. It deliberately does NOT claim the transport is\n // usable — that depends on the provider configuration and on an agent\n // process this service has not started, and a status field that overstates\n // its knowledge is worse than one that is narrow about it.\n codingAgentRegistered: this.agentsService.getAgent(APPLICATION_CODING_AGENT_REF) !== undefined,\n activeRun: this.activeRun ? { taskId: this.activeRun.taskId, startedAt: this.activeRun.startedAt } : null,\n // The answerable set: what is parked waiting for an operator response.\n pendingQuestions: this.listPendingCodingQuestions(),\n limits: {\n defaultTimeoutMs: DISPATCH_DEFAULT_TIMEOUT_MS,\n hardMaxTimeoutMs: DISPATCH_HARD_MAX_TIMEOUT_MS,\n defaultMaxCapturedBytes: DISPATCH_DEFAULT_MAX_CAPTURED_BYTES,\n hardMaxCapturedBytes: DISPATCH_HARD_MAX_CAPTURED_BYTES,\n },\n lockFilePath: this.getWorkspaceMutationLockPath(),\n };\n }\n\n /**\n * Persist only replayable task identity and guard evidence, never\n * prompt/context bytes.\n *\n * CORRELATION BACK TO THE EPISODE runs through `input.candidateRef`, which is\n * the assessment episode's working-subject identity for the iteration that\n * composed this task — the same value the private checkpoint carries as\n * `basis.episode.candidateRef`. It is recorded here deliberately so the join\n * exists in BOTH directions: the checkpoint names the taskId once the task is\n * admitted, and this row names the candidate that caused it, so an auditor\n * starting from a workspace mutation can reach the episode without scanning\n * every checkpoint.\n *\n * A dedicated `episodeRef` column is NOT added: no caller supplies one yet\n * (the coding revision owner lands later), and a field with no producer is a\n * dormant surface that later readers mistake for a guarantee. The candidate\n * ref is exact per ITERATION, which is the granularity an auditor wants.\n */\n private async createApplicationCodingTask(\n task: ApplicationCodingTaskContract,\n baseline: GitWorktreeSnapshot,\n sessionContext?: CompanionExecutionSessionContext,\n ): Promise<DispatchedTaskRow> {\n const payload = CompanionCreateActorTaskRequestSchema.parse({\n title: `Application coding task ${task.taskRef}`,\n /* The cross-plane join key — the board's build-plan row this task executes (Phase 4, R5). */\n workbenchBuildPlanTaskId: sanitizeWorkbenchCreationPlaneIdentity(task.taskRef),\n description: `Typed application coding task for ${task.objectiveRef}; acceptance remains outside the coding host.`,\n topic: Actor_Task_Topics.IMPLEMENTATION,\n status: FlowsActors_Status.PROCESSING,\n actors: { actorRef: APPLICATION_CODING_AGENT_REF },\n input: {\n taskRef: task.taskRef,\n objectiveRef: task.objectiveRef,\n candidateRef: task.candidateRef,\n mutationScope: task.mutationScope,\n contextPlan: {\n planRef: task.contextPlan.planRef,\n objectiveRef: task.contextPlan.objectiveRef,\n },\n contextSelection: {\n planRef: task.contextSelection.planRef,\n selectedSourceRefs: task.contextSelection.selectedSources.map((source) => source.sourceRef),\n selectedSourceCount: task.contextSelection.selectedSources.length,\n },\n verificationIntent: task.verificationIntent,\n installedSkillRefs: task.installedSkillRefs,\n baseline: {\n headSha: baseline.headSha,\n dirtyFileCount: Object.keys(baseline.files).length,\n capturedAt: baseline.capturedAt,\n },\n },\n context: {},\n startedAt: new Date().toISOString(),\n });\n return this.executionsService.createActorTask(payload, sessionContext);\n }\n\n /**\n * Executes the normal Agent invocation and lands the full working-result\n * evidence. This method runs inside the worktree lock and therefore is the\n * sole typed path allowed to observe its own before/after Git boundary.\n */\n private async executeApplicationCodingTask(\n task: ApplicationCodingTaskContract,\n renderedPrompt: string,\n verificationPlans: readonly ApplicationCodingTaskVerificationPlan[],\n durableTask: DispatchedTaskRow,\n baseline: GitWorktreeSnapshot,\n /**\n * Present when this run ANSWERS a parked question rather than starting the\n * task: the agent session is resumed by id via `session/load` and the answer\n * is delivered as the next turn. The task's mutation scope, verification plan\n * and original baseline are unchanged — the resume is held to exactly the\n * bounds the first run was.\n */\n resume?: { readonly continuationOfSessionId: string; readonly answerPrompt: string },\n ): Promise<void> {\n let runSession: CompanionExecutionSessionContext | undefined;\n let runStep: ReturnType<CompanionTraceabilityService['createStep']> | undefined;\n const traceabilityErrors: unknown[] = [];\n const traceBestEffort = async (operation: string, write: () => Promise<void>): Promise<void> => {\n try {\n await write();\n } catch (error) {\n // Traceability is required evidence, but it must not become a control\n // flow escape that leaves the durable task PROCESSING after possible\n // source changes. The final task row records this failure and remains\n // visibly non-accepted for explicit follow-up.\n traceabilityErrors.push(error);\n this.logger.error('Application coding-task trace operation failed', {\n taskId: durableTask._id,\n taskRef: task.taskRef,\n operation,\n error: describeCaughtError(error),\n });\n }\n };\n await traceBestEffort('initialize-session', async () => {\n runSession = this.traceabilityService.createInternalSession({\n label: 'application-coding-task-run',\n metadata: { taskId: durableTask._id, taskRef: task.taskRef },\n });\n if (!runSession) return;\n await this.traceabilityService.registerAlias(runSession, CompanionTraceAliasKind.ACTOR_TASK, durableTask._id);\n runStep = this.createOperationTraceStep(runSession, 'application-coding-task-run');\n });\n const traceContext: AgentTraceContext = {\n label: `application-coding-task:${task.taskRef}`,\n attributes: {\n taskId: durableTask._id,\n taskRef: task.taskRef,\n objectiveRef: task.objectiveRef,\n candidateRef: task.candidateRef,\n },\n };\n const invocation: FlowsActors_Agent_Invocation<\n typeof CodingAgent_RunTaskInputSchema,\n typeof CodingAgent_RunTaskOutputSchema,\n typeof CodingAgent_OperationContext_BaseSchema\n > = {\n agentRef: APPLICATION_CODING_AGENT_REF,\n initiator: {},\n invocationContext: [],\n // A resume delivers the operator's ANSWER as the turn and re-enters the\n // parked session; a first run delivers the rendered task.\n input: resume\n ? { prompt: resume.answerPrompt, continuationOfSessionId: resume.continuationOfSessionId }\n : { prompt: renderedPrompt },\n output: { finalMessage: '', stopReason: CodingAgent_StopReason.END_TURN },\n executionContext: { callTimestamp: new Date().toISOString() },\n artifactBindings: [],\n };\n\n const startedAtMs = Date.now();\n let runError: unknown = null;\n let agentOutput = '';\n let codingUsage: CodingAgent_Usage | undefined;\n let codingDeniedPermissionCount: number | undefined;\n let codingPermissionDecisions: CodingAgent_RunTaskOutput['permissionDecisions'];\n let agentStopReason: CodingAgent_StopReason | undefined;\n /*\n * Counted in full, RETAINED in part.\n *\n * The previous shape pushed every notification into an unbounded array and\n * then persisted only its length — so a 30-minute run grew memory the\n * process never read, and the tool-call and diff frames (the reason to\n * observe a session at all) were collected and discarded. Now the count is a\n * counter, and only the frames a reader would actually open are retained, up\n * to a fixed ceiling.\n */\n let codingSessionEventCount = 0;\n const retainedCodingSessionFrames: Array<{ readonly kind: string; readonly payload: unknown }> = [];\n await traceBestEffort('record-start', () => this.traceOperationStart({\n sessionContext: runSession,\n step: runStep,\n type: 'application-coding-task-run-start',\n summary: `Run application coding task ${task.taskRef}`,\n payload: this.buildApplicationCodingTaskTraceSummary(task),\n artifactFileName: 'application-coding-task-input.txt',\n artifactContent: renderedPrompt,\n }));\n try {\n const response = await this.agentsService.invokeAgent(\n invocation,\n traceContext,\n {\n workspaceRootPath: this.companionContext.saasRoot,\n // Hold the agent to the task's declared scope WHILE it runs, not only\n // in the change set afterwards. The post-hoc assessment stays — it is\n // the authoritative record, because an agent can write a file it never\n // asked permission for — but a refusal in the moment is the only one\n // that prevents the write rather than reporting it.\n isPermittedCodingLocation: buildApplicationCodingTaskLocationPredicate(\n this.companionContext.saasRoot,\n task.mutationScope.allowedPathPrefixes,\n task.mutationScope.prohibitedPathPrefixes,\n ),\n onCodingSessionEvent: (event) => {\n codingSessionEventCount += 1;\n if (\n retainedCodingSessionFrames.length < RETAINED_CODING_SESSION_FRAME_LIMIT\n && RETAINED_CODING_SESSION_EVENT_KINDS.has(event.kind)\n ) {\n retainedCodingSessionFrames.push(event);\n }\n this.publishCodingSessionFrame(durableTask._id, { channel: 'event', payload: event });\n },\n // The JUDGMENT half of the interactive lane: classify each end-of-turn\n // message so the engine ladder can auto-continue a self-pause and park\n // a genuine question. The engine fails OPEN if this throws, so a\n // classifier fault degrades to \"the turn is complete\" rather than\n // hanging the run — this method may therefore throw freely.\n classifyCodingTurnEnd: (input) => this.classifyCodingTurnEnd(input),\n onCodingSessionStateChange: (state) => {\n this.publishCodingSessionFrame(durableTask._id, { channel: 'state', payload: state });\n },\n ...(this.activeRun ? { codingSessionAbortSignal: this.activeRun.abortController.signal } : {}),\n },\n );\n const codingOutput = response.output as Partial<CodingAgent_RunTaskOutput> | undefined;\n // The agent runtime publishes provider-learned facts on `executionContext`.\n codingUsage = (response.executionContext as { usage?: CodingAgent_Usage } | undefined)?.usage;\n codingDeniedPermissionCount = codingOutput?.deniedPermissionCount;\n codingPermissionDecisions = codingOutput?.permissionDecisions;\n const text = codingOutput?.finalMessage;\n agentStopReason = codingOutput?.stopReason;\n // A PARKED run stopped WITHOUT finishing to ask the operator a question.\n // Its `finalMessage` is the question and its partial edits are NOT a final\n // change set — so it must skip assessment, verification and the\n // terminal disposition entirely, and instead record an answerable,\n // non-terminal state. Handled here, before the CANCELLED/empty checks,\n // because a question is a non-empty END_TURN message that would otherwise\n // read as a completed working result.\n if (codingOutput?.suspension) {\n await this.recordParkedApplicationCodingTask({\n task,\n verificationPlans,\n durableTask,\n baseline,\n suspension: codingOutput.suspension,\n output: codingOutput,\n usage: codingUsage,\n codingSessionEventCount,\n retainedCodingSessionFrames,\n startedAtMs,\n runSession,\n runStep,\n traceBestEffort,\n });\n return;\n }\n // A CANCELLED turn is not a completed one, and its partial change set must\n // not be read as a working result. Refused here rather than downstream so\n // the disposition names the actual reason.\n if (agentStopReason === CodingAgent_StopReason.CANCELLED) {\n throw new Error('Application coding Agent turn was cancelled before it completed.');\n }\n if (typeof text !== 'string' || text.trim().length === 0) {\n throw new Error('Application coding Agent returned no final message.');\n }\n agentOutput = text;\n } catch (error) {\n runError = error;\n }\n\n let changeSet: GitChangeSetCapture | null = null;\n let captureError: unknown = null;\n try {\n changeSet = await this.gitChangeSetService.captureChangeSet(baseline);\n } catch (error) {\n captureError = error;\n }\n\n const scopeAssessment = changeSet\n ? assessApplicationCodingTaskMutationScope(changeSet, task.mutationScope.allowedPathPrefixes, task.mutationScope.prohibitedPathPrefixes)\n : null;\n // Verification is deliberately sequential. Each check has a fixed\n // semantic meaning, but several checks can still contend for the same\n // application package/cache if started together. The ordered outcomes are\n // easier to inspect and avoid turning a bounded coding task into an\n // accidental local-build fan-out.\n const shouldVerify = !runError && !captureError && scopeAssessment?.allowed === true;\n const { verification, infrastructureError: verificationInfrastructureError } = shouldVerify\n ? await this.executeVerificationPlans(verificationPlans)\n : { verification: [] as Array<{ checkRef: string; outcome: VerificationOutcome }>, infrastructureError: null as unknown };\n const failedVerification = verification.find(({ outcome }) => !outcome.success) ?? null;\n\n if (agentOutput) {\n await traceBestEffort('write-agent-output', () =>\n this.traceOperationArtifact(runSession, runStep, 'application-coding-task-agent-output.txt', agentOutput));\n }\n if (changeSet?.fullDiffText) {\n await traceBestEffort('write-change-set', () =>\n this.traceOperationArtifact(runSession, runStep, 'application-coding-task-change-set.diff', changeSet.fullDiffText));\n }\n\n const disposition = runError\n ? ApplicationCodingTaskDisposition.AGENT_EXECUTION_FAILED\n : captureError\n ? ApplicationCodingTaskDisposition.CHANGE_SET_CAPTURE_FAILED\n : !scopeAssessment?.allowed\n ? ApplicationCodingTaskDisposition.MUTATION_SCOPE_VIOLATION\n : failedVerification\n ? ApplicationCodingTaskDisposition.VERIFICATION_FAILED\n : traceabilityErrors.length > 0\n ? ApplicationCodingTaskDisposition.TRACEABILITY_FAILED\n : ApplicationCodingTaskDisposition.WORKING_RESULT_RECORDED;\n const succeeded = disposition === ApplicationCodingTaskDisposition.WORKING_RESULT_RECORDED;\n const output = {\n succeeded,\n disposition,\n durationMs: Date.now() - startedAtMs,\n agentOutputTail: agentOutput.slice(-OUTPUT_TAIL_CHARS),\n // Recorded on the durable row because it is the difference between \"the\n // agent finished\" and \"the agent stopped\": a turn that ended on\n // `max_tokens` or `refusal` leaves a partial change set that looks exactly\n // like a complete one from the diff alone.\n ...(agentStopReason ? { agentStopReason } : {}),\n ...(codingSessionEventCount > 0 ? { codingSessionEventCount } : {}),\n ...(retainedCodingSessionFrames.length > 0 ? { codingSessionFrames: retainedCodingSessionFrames } : {}),\n // #2: the run's real cost, recorded on the durable row.\n //\n // This is what the previous transport structurally could not report, and\n // it was captured by the runner and dropped here — so the budget still saw\n // nothing. `usage` is optional in every field by contract, so absence is\n // preserved as absence rather than written as zero.\n ...(codingUsage ? { usage: codingUsage } : {}),\n ...(codingDeniedPermissionCount !== undefined\n ? { deniedPermissionCount: codingDeniedPermissionCount }\n : {}),\n // WHY each permission was decided, beside how many were refused. A refusal an operator\n // cannot explain is a refusal they cannot act on — see the field's contract.\n ...(codingPermissionDecisions && codingPermissionDecisions.length > 0\n ? { permissionDecisions: codingPermissionDecisions }\n : {}),\n ...(runError ? { error: buildOutputErrorPayload(runError) } : {}),\n ...(captureError ? { changeSetCaptureError: buildOutputErrorPayload(captureError) } : {}),\n ...(verificationInfrastructureError ? { verificationInfrastructureError: buildOutputErrorPayload(verificationInfrastructureError) } : {}),\n ...(traceabilityErrors.length > 0 ? { traceabilityErrors: traceabilityErrors.map(buildOutputErrorPayload) } : {}),\n ...(scopeAssessment ? { scopeAssessment } : {}),\n verification,\n ...(changeSet ? {\n changeSetSummary: {\n baselineHeadSha: changeSet.baselineHeadSha,\n postRunHeadSha: changeSet.postRunHeadSha,\n headMovedDuringRun: changeSet.headMovedDuringRun,\n stats: changeSet.stats,\n },\n } : { changeSetSummary: null }),\n };\n\n try {\n const updatePayload = CompanionUpdateActorTaskRequestSchema.parse({\n status: succeeded ? FlowsActors_Status.COMPLETED : FlowsActors_Status.FAILED,\n output,\n ...(changeSet ? { artifacts: [buildChangeSetArtifact(durableTask._id, changeSet)] } : {}),\n });\n await this.executionsService.updateActorTask(durableTask._id, updatePayload, runSession);\n } catch (error) {\n // Do not turn a failed durable PATCH into a retry: the agent may already\n // have changed files and re-execution would duplicate an unclassified\n // effect. The PROCESSING row is deliberately visible for the explicit\n // restart-review hook, while the trace records why it was not terminal.\n this.logger.error('Failed to persist terminal application coding-task result', {\n taskId: durableTask._id,\n taskRef: task.taskRef,\n error: describeCaughtError(error),\n });\n await traceBestEffort('record-terminal-patch-failure', () => this.traceOperationFailure({\n sessionContext: runSession,\n step: runStep,\n type: 'application-coding-task-terminal-patch-failure',\n summary: `Failed to persist terminal result for application coding task ${task.taskRef}`,\n error,\n payload: output,\n }));\n return;\n }\n\n if (succeeded) {\n await traceBestEffort('record-success', () => this.traceOperationSuccess({\n sessionContext: runSession,\n step: runStep,\n type: 'application-coding-task-run-success',\n summary: `Recorded working result for application coding task ${task.taskRef}`,\n payload: output,\n }));\n return;\n }\n await traceBestEffort('record-failure', () => this.traceOperationFailure({\n sessionContext: runSession,\n step: runStep,\n type: 'application-coding-task-run-failure',\n summary: `Application coding task ${task.taskRef} requires follow-up`,\n error: runError ?? captureError ?? verificationInfrastructureError ?? traceabilityErrors[0] ?? new Error(`Application coding task disposition: ${disposition}`),\n payload: output,\n }));\n }\n\n // ================================================================\n // Interactive lane — classifier, live relay, park & resume\n // ================================================================\n\n /**\n * Classify a coding agent's end-of-turn message through the dedicated\n * structured classifier agent. Throws on any fault; the ENGINE ladder wraps\n * that into `CLASSIFIER_UNAVAILABLE` and settles, so this never has to invent\n * a safe default of its own.\n */\n private async classifyCodingTurnEnd(input: {\n readonly finalMessage: string;\n readonly turnIndex: number;\n }): Promise<CodingAgent_EndOfTurnClassification> {\n const prompt = [\n 'A coding agent ended its turn with the message below. Classify what the message means so an '\n + 'autonomous runner can decide whether to continue automatically, or to surface a question to '\n + 'the operator.',\n '',\n '# Agent end-of-turn message',\n input.finalMessage,\n ].join('\\n');\n const invocation: FlowsActors_Agent_Invocation<any, any> = {\n agentRef: APPLICATION_CODING_TURN_CLASSIFIER_AGENT_REF,\n initiator: {},\n invocationContext: [],\n input: { prompt, schema: CodingTurnEndClassificationOutputSchema },\n output: { object: {} },\n executionContext: {},\n artifactBindings: [],\n };\n const response = await this.agentsService.invokeAgent(invocation);\n const raw = (response.output as { object?: unknown } | undefined)?.object;\n const parsed = CodingTurnEndClassificationOutputSchema.safeParse(raw);\n if (!parsed.success) {\n // A malformed classifier answer is a classifier fault: let the ladder fail\n // open rather than guess which situation the model meant.\n throw new Error('Coding turn-end classifier returned an unparseable result.');\n }\n return parsed.data.classification;\n }\n\n /** Fan one live frame out to a task's SSE subscribers. Best-effort, never throws into the run. */\n private publishCodingSessionFrame(taskId: string, frame: CodingSessionLiveFrame): void {\n const listeners = this.codingSessionSubscribers.get(taskId);\n if (!listeners) return;\n for (const listener of listeners) {\n try {\n listener(frame);\n } catch {\n // A subscriber must never be able to fail the run it observes.\n }\n }\n }\n\n /**\n * Subscribe to a task's live coding frames. Returns an unsubscribe function.\n *\n * Frames flow only while a run is ACTIVE for that task; a subscriber that\n * attaches after the run parked or finished simply receives nothing further,\n * which is why the SSE endpoint sends the current pending question up front.\n */\n public subscribeToCodingSession(taskId: string, listener: (frame: CodingSessionLiveFrame) => void): () => void {\n let listeners = this.codingSessionSubscribers.get(taskId);\n if (!listeners) {\n listeners = new Set();\n this.codingSessionSubscribers.set(taskId, listeners);\n }\n listeners.add(listener);\n return () => {\n const set = this.codingSessionSubscribers.get(taskId);\n if (!set) return;\n set.delete(listener);\n if (set.size === 0) this.codingSessionSubscribers.delete(taskId);\n };\n }\n\n /** The questions currently awaiting an operator answer, for status/UX. */\n public listPendingCodingQuestions(): Array<{ taskId: string; taskRef: string; question: string; parkedAt: string; resumable: boolean }> {\n return [...this.parkedCodingSessions.values()].map((parked) => ({\n taskId: parked.durableTask._id,\n taskRef: parked.task.taskRef,\n question: parked.suspension.question,\n parkedAt: parked.parkedAt,\n resumable: parked.suspension.resumable,\n }));\n }\n\n /**\n * Record a run that parked on a question: persist the non-terminal durable row\n * (status PROCESSING, disposition AWAITING_OPERATOR_INPUT, question on the\n * output) and retain the answerable state in memory for the resume door.\n *\n * Deliberately skips change-set assessment and verification: a parked run's\n * edits are partial by definition, and assessing them as a final change set is\n * exactly the \"read a suspended turn as complete\" mistake the suspension field\n * exists to prevent.\n */\n private async recordParkedApplicationCodingTask(params: {\n task: ApplicationCodingTaskContract;\n verificationPlans: readonly ApplicationCodingTaskVerificationPlan[];\n durableTask: DispatchedTaskRow;\n baseline: GitWorktreeSnapshot;\n suspension: CodingAgent_SessionSuspension;\n output: Partial<CodingAgent_RunTaskOutput>;\n usage: CodingAgent_Usage | undefined;\n codingSessionEventCount: number;\n retainedCodingSessionFrames: Array<{ readonly kind: string; readonly payload: unknown }>;\n startedAtMs: number;\n runSession: CompanionExecutionSessionContext | undefined;\n runStep: ReturnType<CompanionTraceabilityService['createStep']> | undefined;\n traceBestEffort: (operation: string, write: () => Promise<void>) => Promise<void>;\n }): Promise<void> {\n const { task, durableTask, baseline, suspension, output, verificationPlans } = params;\n\n this.parkedCodingSessions.set(durableTask._id, {\n durableTask,\n task,\n verificationPlans,\n baseline,\n suspension,\n parkedAt: new Date().toISOString(),\n });\n\n const durableOutput = {\n succeeded: false,\n disposition: ApplicationCodingTaskDisposition.AWAITING_OPERATOR_INPUT,\n durationMs: Date.now() - params.startedAtMs,\n // The question the operator must answer, front and centre.\n pendingQuestion: suspension.question,\n suspension,\n agentOutputTail: (output.finalMessage ?? '').slice(-OUTPUT_TAIL_CHARS),\n ...(output.stopReason ? { agentStopReason: output.stopReason } : {}),\n ...(output.turnCount ? { turnCount: output.turnCount } : {}),\n ...(output.continuations && output.continuations.length > 0 ? { continuations: output.continuations } : {}),\n ...(params.codingSessionEventCount > 0 ? { codingSessionEventCount: params.codingSessionEventCount } : {}),\n ...(params.retainedCodingSessionFrames.length > 0 ? { codingSessionFrames: params.retainedCodingSessionFrames } : {}),\n ...(params.usage ? { usage: params.usage } : {}),\n ...(output.deniedPermissionCount !== undefined ? { deniedPermissionCount: output.deniedPermissionCount } : {}),\n ...(output.permissionDecisions && output.permissionDecisions.length > 0 ? { permissionDecisions: output.permissionDecisions } : {}),\n };\n\n // Status stays PROCESSING: the task is genuinely still in flight, waiting on\n // the operator. It is not COMPLETED (nothing was accepted) and not FAILED\n // (nothing went wrong) — the disposition carries the real state.\n const updatePayload = CompanionUpdateActorTaskRequestSchema.parse({\n status: FlowsActors_Status.PROCESSING,\n output: durableOutput,\n });\n await this.executionsService.updateActorTask(durableTask._id, updatePayload, params.runSession);\n\n await params.traceBestEffort('record-awaiting-input', () => this.traceOperationStart({\n sessionContext: params.runSession,\n step: params.runStep,\n type: 'application-coding-task-awaiting-input',\n summary: `Application coding task ${task.taskRef} is awaiting an operator answer`,\n payload: { taskId: durableTask._id, question: suspension.question, resumable: suspension.resumable },\n }));\n }\n\n /** The in-process answerable state for a parked task, if this process is the one that parked it. */\n public getParkedCodingSessionState(taskId: string): ParkedCodingSessionState | null {\n return this.parkedCodingSessions.get(taskId) ?? null;\n }\n\n /**\n * Load the DURABLE facts needed to RECONSTRUCT a parked task's answerable state\n * after the in-process map has lost it (a companion restart).\n *\n * Returns the build-plan `taskRef` and the persisted `suspension` — enough for\n * the build-dispatch layer to re-compose the task contract and rebuild a\n * {@link ParkedCodingSessionState}. `null` when the row is not a parked coding\n * task (wrong actor, no suspension, or not found).\n */\n public async loadPersistedParkedCodingTask(\n taskId: string,\n sessionContext?: CompanionExecutionSessionContext,\n ): Promise<{ taskRef: string; suspension: CodingAgent_SessionSuspension; durableTask: DispatchedTaskRow } | null> {\n let durableTask: DispatchedTaskRow;\n try {\n durableTask = await this.executionsService.getActorTask(taskId, sessionContext) as DispatchedTaskRow;\n } catch {\n return null;\n }\n const row = durableTask as { actors?: { actorRef?: string }; input?: unknown; output?: unknown };\n if (row.actors?.actorRef !== APPLICATION_CODING_AGENT_REF) return null;\n const taskRef = isRecordValue(row.input) && typeof row.input.taskRef === 'string' ? row.input.taskRef : null;\n const suspensionRaw = isRecordValue(row.output) ? row.output.suspension : undefined;\n const parsedSuspension = CodingAgent_SessionSuspensionSchema.safeParse(suspensionRaw);\n if (!taskRef || !parsedSuspension.success) return null;\n return { taskRef, suspension: parsedSuspension.data, durableTask };\n }\n\n /**\n * Answer a parked coding task's question and resume the SAME agent session.\n *\n * The IN-PROCESS door: it answers a task THIS process parked. For a task whose\n * in-process state was lost to a restart, the caller reconstructs a\n * {@link ParkedCodingSessionState} (from the build plan) and uses\n * {@link resumeParkedCodingTask} directly.\n */\n public async respondToApplicationCodingTaskQuestion(\n taskId: string,\n answer: string,\n ): Promise<ApplicationCodingTaskRunAdmission> {\n // A missing answer is a VALIDATION 400 regardless of whether a task is parked\n // — it is a malformed request, not a state conflict.\n this.admitTypedInput(() => {\n if (answer.trim().length === 0) throw new Error('empty answer');\n return answer;\n }, 'An answer is required to resume a parked coding task.');\n const parked = this.parkedCodingSessions.get(taskId);\n if (!parked) {\n throw this.buildDispatchConflictError(\n `No coding task is awaiting an answer under id ${taskId} in this process. `\n + 'A companion restart drops in-flight answerable state; re-dispatch the task instead.',\n );\n }\n return this.resumeParkedCodingTask(parked, answer);\n }\n\n /**\n * Run a resume against an EXPLICIT parked state — from the in-process map or\n * reconstructed from the build plan after a restart.\n *\n * Runs under the worktree mutation lock exactly like a fresh dispatch (a resume\n * mutates the same worktree) and re-enters the turn ladder through\n * `session/load`, so the agent continues with its full context. The mutation\n * scope and verification plan are the parked contract's; a resume is held to the\n * same bounds as the first run.\n */\n public async resumeParkedCodingTask(\n parked: ParkedCodingSessionState,\n answer: string,\n ): Promise<ApplicationCodingTaskRunAdmission> {\n const trimmedAnswer = this.admitTypedInput(() => {\n const value = answer.trim();\n if (value.length === 0) throw new Error('empty answer');\n return value;\n }, 'An answer is required to resume a parked coding task.');\n const taskId = parked.durableTask._id;\n if (!parked.suspension.resumable) {\n throw this.buildDispatchConflictError(\n `Coding task ${taskId} parked on a question, but its agent does not support session resume, `\n + 'so the answer cannot be delivered to the same session. Re-dispatch the task with the answer folded into the objective.',\n );\n }\n if (this.activeRun) {\n throw this.buildDispatchConflictError(\n `A coding-agent run is already active (task ${this.activeRun.taskId}). Answers are serialized behind the same worktree lock.`,\n );\n }\n\n // Taken out of the answerable set for the duration of the resume; a resume\n // that parks again re-registers it through the same suspension branch.\n this.parkedCodingSessions.delete(taskId);\n\n const admission = createDeferred<ApplicationCodingTaskRunAdmission>();\n const resumeRun = withDedicatedFileLock(\n this.getWorkspaceMutationLockPath(),\n async () => {\n this.activeRun = { taskId, startedAt: new Date().toISOString(), abortController: new AbortController() };\n const settlement = createDeferred<void>();\n this.applicationCodingTaskSettlements.set(taskId, { promise: settlement.promise, resolve: () => settlement.resolve(undefined) });\n admission.resolve({\n taskId,\n status: FlowsActors_Status.PROCESSING,\n taskRef: parked.task.taskRef,\n baselineHeadSha: parked.baseline.headSha,\n baselineDirtyFileCount: Object.keys(parked.baseline.files).length,\n });\n try {\n await this.executeApplicationCodingTask(\n parked.task,\n renderApplicationCodingTaskAgentPrompt(parked.task),\n parked.verificationPlans,\n parked.durableTask,\n parked.baseline,\n { continuationOfSessionId: parked.suspension.sessionId, answerPrompt: trimmedAnswer },\n );\n } finally {\n this.activeRun = null;\n this.applicationCodingTaskSettlements.get(taskId)?.resolve();\n }\n },\n { retries: { retries: 0 } },\n );\n resumeRun.catch((error: unknown) => {\n admission.reject(this.mapLockError(error));\n this.logDebug('Application coding-task resume run terminated with error', {\n taskId,\n error: describeCaughtError(error),\n });\n });\n\n return admission.promise;\n }\n\n private buildApplicationCodingTaskTraceSummary(task: ApplicationCodingTaskContract): Record<string, unknown> {\n return {\n taskRef: task.taskRef,\n objectiveRef: task.objectiveRef,\n candidateRef: task.candidateRef,\n mutationScope: task.mutationScope,\n contextPlanRef: task.contextPlan.planRef,\n selectedSourceRefs: task.contextSelection.selectedSources.map((source) => source.sourceRef),\n verificationRef: task.verificationIntent.verificationRef,\n requiredChecks: task.verificationIntent.requiredChecks,\n installedSkillRefs: task.installedSkillRefs,\n };\n }\n\n // ================================================================\n // Verification hook (P-29c — enum vocabulary, never a command string)\n // ================================================================\n\n private buildVerificationPlan(kind: VerificationKind, requestedPath?: string): VerificationPlan {\n if (kind === VerificationKind.VITEST_PATH) {\n const sanitized = this.sanitizeRelativePath(requestedPath ?? '');\n const absoluteTestPath = join(this.companionContext.saasRoot, sanitized);\n const packageDir = this.findNearestPackageDir(dirname(absoluteTestPath));\n return {\n kind,\n path: sanitized,\n command: 'pnpm',\n args: ['exec', 'vitest', 'run', relative(packageDir, absoluteTestPath)],\n cwd: packageDir,\n };\n }\n\n // TYPECHECK — optional path points at a workspace package directory.\n const sanitized = requestedPath ? this.sanitizeRelativePath(requestedPath) : null;\n return {\n kind,\n path: sanitized,\n command: 'pnpm',\n args: ['exec', 'tsc', '--noEmit'],\n cwd: sanitized ? join(this.companionContext.saasRoot, sanitized) : this.companionContext.saasRoot,\n };\n }\n\n /**\n * The FK-resolution sweep, sourced from the `resources-registry` introspection\n * behavior — a FRESH subprocess import of the app's shared-lib, never the\n * companion's boot-time cache, so it judges exactly the bytes the mutation\n * left on disk. Fails the check when any `.isForeignKey()` field has no\n * registered relationship edge: invisible to every typecheck in the plan and\n * to the backend boot, fatal to the app's frontend at first page load\n * (`frontend_fk_resolution_failed` — wonder-crm, 2026-08-27).\n */\n private async runForeignKeyResolutionVerification(): Promise<VerificationOutcome> {\n const backendServiceKey = Object.entries(this.companionContext.servicesByKey)\n .find(([, service]) => !service.frontendType)?.[0];\n if (!backendServiceKey) {\n throw new Error('No backend service is available to run the frontend-fk-resolution verification.');\n }\n const result = await this.introspectionService.requestInfo({\n serviceKey: backendServiceKey,\n behavior: 'resources-registry',\n });\n if (!result.success) {\n throw new Error(`resources-registry introspection failed: ${JSON.stringify(result)}`);\n }\n const unresolved = (result.data as { unresolvableForeignKeyFields?: Array<{ resourceType: string; fieldName: string }> })\n .unresolvableForeignKeyFields ?? [];\n const success = unresolved.length === 0;\n return {\n kind: VerificationKind.FRONTEND_FK_RESOLUTION,\n path: null,\n success,\n message: success\n ? 'every isForeignKey() field resolves through a registered relationship'\n : `${unresolved.length} FK field(s) cannot be resolved to a resource type: `\n + unresolved.map(({ resourceType, fieldName }) => `${resourceType}.${fieldName}`).join(', ')\n + ' — declare a relationship with the corresponding foreignKeyField.',\n stdoutTail: '',\n stderrTail: '',\n };\n }\n\n /**\n * The settings-rail content sweep — the SHELL_PLACEMENT counterpart of the FK sweep,\n * and it exists for the same reason: the defect it catches is invisible to a typecheck.\n *\n * A placement naming a `destinationRef` the engine catalog does not ship is not a type\n * error. `resolveSettingsHubConfig` DROPS it, and the section silently never renders —\n * so a coding task that typo'd a ref passes `check:app-typecheck`, reports verified, and\n * leaves the application missing a settings section nobody is told about.\n *\n * WARNINGS do not fail the check. Only errors do: the verifier reports both severities,\n * and failing a coding task on an advisory would train the lane to ignore its own gate.\n */\n private async runSettingsPlacementContentVerification(): Promise<VerificationOutcome> {\n // Mirrors the FK sweep's resolution, on the other side of the same predicate: that\n // one wants a backend service, this one a FRONTEND service, because the settings rail\n // is authored in the frontend workspace and only that subprocess can import it.\n const frontendServiceKey = Object.entries(this.companionContext.servicesByKey)\n .find(([, service]) => service.frontendType)?.[0];\n if (!frontendServiceKey) {\n throw new Error('No frontend service is available to run the settings-placement-content verification.');\n }\n const result = await this.introspectionService.requestInfo({\n serviceKey: frontendServiceKey,\n behavior: 'settings-placement-content',\n });\n if (!result.success) {\n throw new Error(`settings-placement-content introspection failed: ${JSON.stringify(result)}`);\n }\n const data = result.data as {\n authored?: boolean;\n errors?: Array<{ severity: string; code: string; message: string }>;\n };\n const blocking = (data.errors ?? []).filter((error) => error.severity !== 'warning');\n const success = blocking.length === 0;\n return {\n kind: VerificationKind.SETTINGS_PLACEMENT_CONTENT,\n path: null,\n success,\n message: success\n ? (data.authored === false\n // Not a silent pass: an application with no authored rail has nothing to\n // verify, and saying so is the difference between \"checked and clean\" and\n // \"there was nothing to check\".\n ? 'no settings rail is authored — nothing to verify'\n : 'every authored placement names a destination the engine ships')\n : `${blocking.length} settings-placement error(s): `\n + blocking.map((error) => `${error.code}: ${error.message}`).join(' | '),\n stdoutTail: '',\n stderrTail: '',\n };\n }\n\n /**\n * Run a resolved verification plan set and return one outcome per check.\n *\n * Extracted from the coding-task dispatch so the SAME executor serves a second caller: the\n * `DETERMINISTIC_CLI` playbook tier, which verifies an already-built application and dispatches no\n * agent (issue #147). The alternative was a second loop that re-derived which kinds branch away\n * from the argv path — and the two would drift the first time a `VerificationKind` was added,\n * silently, because a missed kind falls through to a typecheck that passes.\n *\n * A thrown error is an INFRASTRUCTURE failure, not a failing check: the subprocess could not be\n * run at all. It is recorded as a failed outcome so the caller sees which check was affected, and\n * surfaced separately so a caller can tell \"the application is broken\" from \"we could not ask\".\n */\n private async executeVerificationPlans(\n plans: readonly ApplicationCodingTaskVerificationPlan[],\n ): Promise<{\n verification: Array<{ checkRef: string; outcome: VerificationOutcome }>;\n infrastructureError: unknown;\n }> {\n const verification: Array<{ checkRef: string; outcome: VerificationOutcome }> = [];\n let infrastructureError: unknown = null;\n for (const plan of plans) {\n try {\n verification.push({\n checkRef: plan.checkRef,\n // The FK-resolution check is not a CLI command: it runs in the companion's\n // introspection subprocess (fresh working-tree import), so it branches before\n // the argv-plan path.\n outcome: plan.kind === VerificationKind.FRONTEND_FK_RESOLUTION\n ? await this.runForeignKeyResolutionVerification()\n : plan.kind === VerificationKind.SETTINGS_PLACEMENT_CONTENT\n ? await this.runSettingsPlacementContentVerification()\n : await this.runVerification(this.buildVerificationPlan(plan.kind, plan.path ?? undefined)),\n });\n } catch (error) {\n infrastructureError ??= error;\n verification.push({\n checkRef: plan.checkRef,\n outcome: {\n kind: plan.kind,\n path: plan.path,\n success: false,\n message: describeCaughtError(error),\n stdoutTail: '',\n stderrTail: '',\n },\n });\n }\n }\n return { verification, infrastructureError };\n }\n\n /**\n * Run named verification checks against the application, outside any agent dispatch.\n *\n * The public door for the `DETERMINISTIC_CLI` tier. Check refs resolve through the same closed\n * `APPLICATION_CODING_TASK_VERIFICATION_CATALOG` a coding task uses, so an unknown ref is refused\n * here rather than becoming an unrun check that reports success by absence.\n *\n * Deliberately takes NO worktree lock and captures NO change set: this reads the application, and\n * pretending otherwise would serialize verification against the single-flight coding lane for no\n * reason.\n */\n public async runApplicationVerificationChecks(\n checkRefs: readonly string[],\n ): Promise<{\n verification: Array<{ checkRef: string; outcome: VerificationOutcome }>;\n infrastructureError: unknown;\n }> {\n return this.executeVerificationPlans(resolveApplicationCodingTaskVerificationPlans(checkRefs));\n }\n\n private async runVerification(plan: VerificationPlan): Promise<VerificationOutcome> {\n try {\n const result = await executeBoundedSubprocess({\n command: plan.command,\n args: plan.args,\n cwd: plan.cwd,\n env: buildVerificationEnv(),\n timeoutMs: VERIFICATION_TIMEOUT_MS,\n maxCapturedBytes: VERIFICATION_MAX_CAPTURED_BYTES,\n });\n return {\n kind: plan.kind,\n path: plan.path,\n success: true,\n message: `${plan.command} ${plan.args.join(' ')} passed`,\n stdoutTail: result.stdout.slice(-OUTPUT_TAIL_CHARS),\n stderrTail: result.stderr.slice(-OUTPUT_TAIL_CHARS),\n };\n } catch (error) {\n const details = (error as { details?: { stdout?: string; stderr?: string } }).details;\n return {\n kind: plan.kind,\n path: plan.path,\n success: false,\n message: describeCaughtError(error),\n stdoutTail: (details?.stdout ?? '').slice(-OUTPUT_TAIL_CHARS),\n stderrTail: (details?.stderr ?? '').slice(-OUTPUT_TAIL_CHARS),\n };\n }\n }\n\n /**\n * Run one admission-time validation and convert ANY refusal into a typed\n * VALIDATION error, preserving the original message as context.\n *\n * Deliberately a wrapper rather than N rewritten throw sites: the pure\n * resolver in the models layer has no error builder and should not grow one,\n * and a future admission check gets the same classification by being placed\n * here rather than by remembering to.\n */\n private admitTypedInput<T>(validate: () => T, message: string): T {\n try {\n return validate();\n } catch (error) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n message,\n validationError: describeCaughtError(error),\n },\n });\n }\n }\n\n /**\n * Sanitize an app-root-relative path from the wire: rejects absolute\n * paths, `..` escapes, backslashes, NUL bytes, and flag-lookalikes\n * (leading `-` would be parsed as an argv flag by the fixed commands).\n */\n private sanitizeRelativePath(requestedPath: string): string {\n const candidate = requestedPath.trim();\n const reject = (reason: string): never => {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n message: `Invalid verification path: ${reason}`,\n requestedPath,\n },\n });\n };\n\n if (!candidate) reject('path is empty');\n if (candidate.includes('\\0')) reject('path contains a NUL byte');\n if (candidate.includes('\\\\')) reject('use forward slashes');\n if (isAbsolute(candidate)) reject('path must be relative to the application root');\n if (candidate.startsWith('-')) reject('path must not start with a dash');\n const normalized = normalize(candidate);\n if (normalized.split(sep).includes('..')) reject('path must not escape the application root');\n\n const absolute = join(this.companionContext.saasRoot, normalized);\n const relativeFromRoot = relative(this.companionContext.saasRoot, absolute);\n if (relativeFromRoot.startsWith('..') || isAbsolute(relativeFromRoot)) {\n reject('path resolves outside the application root');\n }\n return normalized;\n }\n\n /** Nearest ancestor dir (within the app root) holding a package.json. */\n private findNearestPackageDir(startDir: string): string {\n let current = startDir;\n const root = this.companionContext.saasRoot;\n while (current.startsWith(root)) {\n if (existsSync(join(current, 'package.json'))) {\n return current;\n }\n const parent = dirname(current);\n if (parent === current) break;\n current = parent;\n }\n return root;\n }\n\n // ================================================================\n // Error + traceability helpers (service-owned wrappers, P-13 pattern)\n // ================================================================\n\n private buildDispatchConflictError(message: string): unknown {\n return this.errorBuilder.buildError(ErrorType.CONFLICT, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFLICT,\n context: { message },\n });\n }\n\n /** Map proper-lockfile ELOCKED contention onto the 409 vocabulary. */\n private mapLockError(error: unknown): unknown {\n if ((error as { code?: string })?.code === 'ELOCKED') {\n return this.buildDispatchConflictError(\n 'The workspace-mutation lock is held by another process (companion run or CLI). '\n + 'Dispatch is single-flight across processes (P-20); retry after the active run completes. '\n + 'If you are a dispatched coding-agent run: dispatching from a dispatched run is forbidden (P-35).',\n );\n }\n return error;\n }\n\n private createOperationTraceStep(\n sessionContext: CompanionExecutionSessionContext | undefined,\n label: string,\n ) {\n return sessionContext\n ? this.traceabilityService.createStep(sessionContext, {\n kind: 'coding-agent-dispatch',\n label,\n })\n : undefined;\n }\n\n private async traceOperationStart(input: {\n sessionContext?: CompanionExecutionSessionContext;\n step?: ReturnType<CompanionTraceabilityService['createStep']>;\n type: string;\n summary: string;\n payload?: unknown;\n artifactFileName?: string;\n artifactContent?: unknown;\n }): Promise<void> {\n if (!input.sessionContext) return;\n\n await this.traceabilityService.traceEvent({\n session: input.sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG,\n type: input.type,\n summary: input.summary,\n ...(input.payload !== undefined ? { payload: input.payload } : {}),\n ...(input.step ? { step: input.step } : {}),\n });\n if (input.artifactFileName && input.artifactContent !== undefined) {\n await this.traceabilityService.writeArtifact({\n session: input.sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG_VERBOSE,\n fileName: input.artifactFileName,\n content: input.artifactContent,\n ...(input.step ? { step: input.step } : {}),\n });\n }\n }\n\n private async traceOperationSuccess(input: {\n sessionContext?: CompanionExecutionSessionContext;\n step?: ReturnType<CompanionTraceabilityService['createStep']>;\n type: string;\n summary: string;\n payload?: unknown;\n artifactFileName?: string;\n artifactContent?: unknown;\n }): Promise<void> {\n if (!input.sessionContext) return;\n\n if (input.artifactFileName && input.artifactContent !== undefined) {\n await this.traceabilityService.writeArtifact({\n session: input.sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG_VERBOSE,\n fileName: input.artifactFileName,\n content: input.artifactContent,\n ...(input.step ? { step: input.step } : {}),\n });\n }\n await this.traceabilityService.traceEvent({\n session: input.sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG,\n type: input.type,\n summary: input.summary,\n ...(input.payload !== undefined ? { payload: input.payload } : {}),\n ...(input.step ? { step: input.step } : {}),\n });\n }\n\n private async traceOperationFailure(input: {\n sessionContext?: CompanionExecutionSessionContext;\n step?: ReturnType<CompanionTraceabilityService['createStep']>;\n type: string;\n summary: string;\n error: unknown;\n payload?: unknown;\n }): Promise<void> {\n if (!input.sessionContext) return;\n\n await this.traceabilityService.traceEvent({\n session: input.sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG,\n type: input.type,\n summary: input.summary,\n payload: {\n ...(input.payload && typeof input.payload === 'object'\n ? input.payload as Record<string, unknown>\n : { input: input.payload }),\n error: buildOutputErrorPayload(input.error),\n },\n ...(input.step ? { step: input.step } : {}),\n });\n }\n\n private async traceOperationArtifact(\n sessionContext: CompanionExecutionSessionContext | undefined,\n step: ReturnType<CompanionTraceabilityService['createStep']> | undefined,\n fileName: string,\n content: unknown,\n ): Promise<void> {\n if (!sessionContext) return;\n await this.traceabilityService.writeArtifact({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG_VERBOSE,\n fileName,\n content,\n ...(step ? { step } : {}),\n });\n }\n}\n\ninterface VerificationPlan {\n kind: VerificationKind;\n path: string | null;\n command: string;\n args: string[];\n cwd: string;\n}\n\n/**\n * Change-set artifact persisted on the task row (P-19: file list + stats\n * + head SHAs + attribution classes). `fullDiffText` is deliberately\n * stripped — the raw diff lives in the traceability artifact only.\n *\n * Persisted as `FlowsActors_IO_PartKind.STRUCTURED` with the capture in\n * `content.data`. History: on 2026-07-03 this was temporarily JSON-encoded\n * into a TEXT artifact because the zod-to-mongoose converter flattened\n * nested discriminated unions (`artifacts[]` on the task row) onto their\n * FIRST variant, making `content.text` a required Mongoose path for every\n * artifact. The converter now merges nested union variants into an\n * all-optional superset schema, so the natural STRUCTURED shape persists\n * again (requires a saas-backend-lib dist carrying that fix).\n */\nfunction buildChangeSetArtifact(taskId: string, changeSet: GitChangeSetCapture): ArtifactInstance {\n const { fullDiffText: _fullDiffText, ...structuredCapture } = changeSet;\n return {\n ref: `coding-agent-change-set-${taskId}`,\n type: FlowsActors_IO_PartKind.STRUCTURED,\n name: 'coding-agent-change-set',\n description: 'Read-only git change-set capture with per-file attribution (P-19)',\n origin: { taskId },\n content: { data: structuredCapture },\n createdAt: new Date().toISOString(),\n };\n}\n\n/** Same minimal allowlist the CLI spawn uses (P-18). */\nfunction buildVerificationEnv(): NodeJS.ProcessEnv {\n // Same minimal identity allowlist the CLI spawn uses (P-18) — incl.\n // USER/LOGNAME so a verification hook that shells out to per-user\n // tooling behaves like the agent run. Kept in lockstep with\n // `ClaudeCliCompanionService`'s allowlist.\n const env: NodeJS.ProcessEnv = {};\n for (const key of ['PATH', 'HOME', 'USER', 'LOGNAME', 'SHELL', 'TERM']) {\n const value = process.env[key];\n if (value !== undefined) env[key] = value;\n }\n return env;\n}\n\nfunction buildOutputErrorPayload(error: unknown): unknown {\n if (isWildoBackendError(error)) return error;\n if (error instanceof Error) {\n return {\n message: error.message,\n name: error.name,\n ...(error.stack ? { stack: error.stack } : {}),\n };\n }\n return { message: String(error) };\n}\n\nfunction createDeferred<T>(): {\n promise: Promise<T>;\n resolve: (value: T) => void;\n reject: (error: unknown) => void;\n} {\n let settled = false;\n let resolveFn!: (value: T) => void;\n let rejectFn!: (error: unknown) => void;\n const promise = new Promise<T>((resolve, reject) => {\n resolveFn = resolve;\n rejectFn = reject;\n });\n return {\n promise,\n resolve: (value) => {\n if (settled) return;\n settled = true;\n resolveFn(value);\n },\n reject: (error) => {\n if (settled) return;\n settled = true;\n rejectFn(error);\n },\n };\n}\n"]}
|