@caupulican/pi-adaptative 0.90.11 → 0.91.2
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/CHANGELOG.md +46 -0
- package/README.md +8 -10
- package/dist/bundled-resources/skills/icm-architect/LICENSE +21 -0
- package/dist/bundled-resources/skills/icm-architect/SKILL.md +112 -0
- package/dist/bundled-resources/skills/icm-architect/assets/templates/CLAUDE.md +27 -0
- package/dist/bundled-resources/skills/icm-architect/assets/templates/CONTEXT.md +14 -0
- package/dist/bundled-resources/skills/icm-architect/assets/templates/node.md +29 -0
- package/dist/bundled-resources/skills/icm-architect/assets/templates/object.md +43 -0
- package/dist/bundled-resources/skills/icm-architect/assets/templates/process.md +38 -0
- package/dist/bundled-resources/skills/icm-architect/assets/templates/questionnaire.md +9 -0
- package/dist/bundled-resources/skills/icm-architect/assets/templates/schema.md +24 -0
- package/dist/bundled-resources/skills/icm-architect/assets/templates/stage-CONTEXT.md +21 -0
- package/dist/bundled-resources/skills/icm-architect/references/core.md +92 -0
- package/dist/bundled-resources/skills/icm-architect/references/forms.md +182 -0
- package/dist/bundled-resources/skills/icm-architect/references/system-map.md +122 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +2 -1
- package/dist/cli/args.js.map +1 -1
- package/dist/core/agent-paths.d.ts +2 -2
- package/dist/core/agent-paths.d.ts.map +1 -1
- package/dist/core/agent-paths.js +1 -0
- package/dist/core/agent-paths.js.map +1 -1
- package/dist/core/agent-session.d.ts +12 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +44 -11
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.js +2 -0
- package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
- package/dist/core/background-tool-task-controller.d.ts +9 -0
- package/dist/core/background-tool-task-controller.d.ts.map +1 -1
- package/dist/core/background-tool-task-controller.js +23 -0
- package/dist/core/background-tool-task-controller.js.map +1 -1
- package/dist/core/bash-executor.js +3 -3
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/context/local-graph-memory-provider.d.ts +9 -0
- package/dist/core/context/local-graph-memory-provider.d.ts.map +1 -0
- package/dist/core/context/local-graph-memory-provider.js +122 -0
- package/dist/core/context/local-graph-memory-provider.js.map +1 -0
- package/dist/core/context/tool-output-packer.d.ts +2 -2
- package/dist/core/context/tool-output-packer.d.ts.map +1 -1
- package/dist/core/context/tool-output-packer.js +3 -3
- package/dist/core/context/tool-output-packer.js.map +1 -1
- package/dist/core/context-gc.d.ts.map +1 -1
- package/dist/core/context-gc.js +2 -0
- package/dist/core/context-gc.js.map +1 -1
- package/dist/core/default-tool-surface.d.ts.map +1 -1
- package/dist/core/default-tool-surface.js +5 -0
- package/dist/core/default-tool-surface.js.map +1 -1
- package/dist/core/delegation/worker-agent-control-coordinator.d.ts +1 -0
- package/dist/core/delegation/worker-agent-control-coordinator.d.ts.map +1 -1
- package/dist/core/delegation/worker-agent-control-coordinator.js +16 -8
- package/dist/core/delegation/worker-agent-control-coordinator.js.map +1 -1
- package/dist/core/delegation/worker-agent-control.d.ts +2 -0
- package/dist/core/delegation/worker-agent-control.d.ts.map +1 -1
- package/dist/core/delegation/worker-agent-control.js.map +1 -1
- package/dist/core/delegation/worker-context-inheritance-policy.d.ts +3 -3
- package/dist/core/delegation/worker-context-inheritance-policy.js +4 -4
- package/dist/core/delegation/worker-context-inheritance-policy.js.map +1 -1
- package/dist/core/delegation/worker-delegation-controller.d.ts +1 -5
- package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
- package/dist/core/delegation/worker-delegation-controller.js +19 -9
- package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
- package/dist/core/delegation/worker-tree-budget-coordinator.d.ts +2 -0
- package/dist/core/delegation/worker-tree-budget-coordinator.d.ts.map +1 -1
- package/dist/core/delegation/worker-tree-budget-coordinator.js +6 -0
- package/dist/core/delegation/worker-tree-budget-coordinator.js.map +1 -1
- package/dist/core/extensions/extension-session-scope.d.ts +17 -0
- package/dist/core/extensions/extension-session-scope.d.ts.map +1 -0
- package/dist/core/extensions/extension-session-scope.js +135 -0
- package/dist/core/extensions/extension-session-scope.js.map +1 -0
- package/dist/core/extensions/index.d.ts +1 -0
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js +1 -0
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +1 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/wrapper.d.ts +2 -1
- package/dist/core/extensions/wrapper.d.ts.map +1 -1
- package/dist/core/extensions/wrapper.js +10 -4
- package/dist/core/extensions/wrapper.js.map +1 -1
- package/dist/core/foreground-terminal-handoff-controller.d.ts +0 -1
- package/dist/core/foreground-terminal-handoff-controller.d.ts.map +1 -1
- package/dist/core/foreground-terminal-handoff-controller.js +1 -2
- package/dist/core/foreground-terminal-handoff-controller.js.map +1 -1
- package/dist/core/goals/goal-continuation-controller.d.ts +7 -1
- package/dist/core/goals/goal-continuation-controller.d.ts.map +1 -1
- package/dist/core/goals/goal-continuation-controller.js +16 -0
- package/dist/core/goals/goal-continuation-controller.js.map +1 -1
- package/dist/core/goals/goal-runtime-snapshot.d.ts +3 -0
- package/dist/core/goals/goal-runtime-snapshot.d.ts.map +1 -1
- package/dist/core/goals/goal-runtime-snapshot.js +8 -1
- package/dist/core/goals/goal-runtime-snapshot.js.map +1 -1
- package/dist/core/goals/goal-session-controller.d.ts +2 -0
- package/dist/core/goals/goal-session-controller.d.ts.map +1 -1
- package/dist/core/goals/goal-session-controller.js +1 -0
- package/dist/core/goals/goal-session-controller.js.map +1 -1
- package/dist/core/goals/goal-tool-core.d.ts +18 -0
- package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
- package/dist/core/goals/goal-tool-core.js +62 -0
- package/dist/core/goals/goal-tool-core.js.map +1 -1
- package/dist/core/goals/natural-language-goal.d.ts.map +1 -1
- package/dist/core/goals/natural-language-goal.js +4 -2
- package/dist/core/goals/natural-language-goal.js.map +1 -1
- package/dist/core/human-input-controller.d.ts +3 -34
- package/dist/core/human-input-controller.d.ts.map +1 -1
- package/dist/core/human-input-controller.js +3 -161
- package/dist/core/human-input-controller.js.map +1 -1
- package/dist/core/keybindings.d.ts +5 -0
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +2 -0
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/learning/reflection-turn-analysis.d.ts.map +1 -1
- package/dist/core/learning/reflection-turn-analysis.js +10 -1
- package/dist/core/learning/reflection-turn-analysis.js.map +1 -1
- package/dist/core/memory/providers/file-store.d.ts.map +1 -1
- package/dist/core/memory/providers/file-store.js +4 -0
- package/dist/core/memory/providers/file-store.js.map +1 -1
- package/dist/core/memory-controller.d.ts +3 -0
- package/dist/core/memory-controller.d.ts.map +1 -1
- package/dist/core/memory-controller.js +18 -0
- package/dist/core/memory-controller.js.map +1 -1
- package/dist/core/model-capability.d.ts.map +1 -1
- package/dist/core/model-capability.js +1 -0
- package/dist/core/model-capability.js.map +1 -1
- package/dist/core/orchestration/work-state-projection.d.ts +4 -0
- package/dist/core/orchestration/work-state-projection.d.ts.map +1 -1
- package/dist/core/orchestration/work-state-projection.js +11 -0
- package/dist/core/orchestration/work-state-projection.js.map +1 -1
- package/dist/core/pipelines/context.d.ts +6 -0
- package/dist/core/pipelines/context.d.ts.map +1 -0
- package/dist/core/pipelines/context.js +102 -0
- package/dist/core/pipelines/context.js.map +1 -0
- package/dist/core/pipelines/discover.d.ts +11 -0
- package/dist/core/pipelines/discover.d.ts.map +1 -0
- package/dist/core/pipelines/discover.js +147 -0
- package/dist/core/pipelines/discover.js.map +1 -0
- package/dist/core/pipelines/increment.d.ts +24 -0
- package/dist/core/pipelines/increment.d.ts.map +1 -0
- package/dist/core/pipelines/increment.js +121 -0
- package/dist/core/pipelines/increment.js.map +1 -0
- package/dist/core/pipelines/index.d.ts +8 -0
- package/dist/core/pipelines/index.d.ts.map +1 -0
- package/dist/core/pipelines/index.js +8 -0
- package/dist/core/pipelines/index.js.map +1 -0
- package/dist/core/pipelines/parse-contract.d.ts +10 -0
- package/dist/core/pipelines/parse-contract.d.ts.map +1 -0
- package/dist/core/pipelines/parse-contract.js +105 -0
- package/dist/core/pipelines/parse-contract.js.map +1 -0
- package/dist/core/pipelines/run-state.d.ts +26 -0
- package/dist/core/pipelines/run-state.d.ts.map +1 -0
- package/dist/core/pipelines/run-state.js +135 -0
- package/dist/core/pipelines/run-state.js.map +1 -0
- package/dist/core/pipelines/session-pipeline-run.d.ts +6 -0
- package/dist/core/pipelines/session-pipeline-run.d.ts.map +1 -0
- package/dist/core/pipelines/session-pipeline-run.js +18 -0
- package/dist/core/pipelines/session-pipeline-run.js.map +1 -0
- package/dist/core/pipelines/types.d.ts +91 -0
- package/dist/core/pipelines/types.d.ts.map +1 -0
- package/dist/core/pipelines/types.js +44 -0
- package/dist/core/pipelines/types.js.map +1 -0
- package/dist/core/reflection-controller.d.ts +2 -0
- package/dist/core/reflection-controller.d.ts.map +1 -1
- package/dist/core/reflection-controller.js +53 -30
- package/dist/core/reflection-controller.js.map +1 -1
- package/dist/core/resource-loader.d.ts +21 -0
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +45 -18
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/runtime-builder.d.ts +3 -0
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +49 -1
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +3 -0
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-role.d.ts.map +1 -1
- package/dist/core/session-role.js +2 -0
- package/dist/core/session-role.js.map +1 -1
- package/dist/core/settings-manager.d.ts +12 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +43 -9
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/system-prompt-builder.js +1 -1
- package/dist/core/system-prompt-builder.js.map +1 -1
- package/dist/core/system-prompt.d.ts +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +30 -22
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tasks/task-projection.d.ts +2 -0
- package/dist/core/tasks/task-projection.d.ts.map +1 -1
- package/dist/core/tasks/task-projection.js +1 -0
- package/dist/core/tasks/task-projection.js.map +1 -1
- package/dist/core/tasks/task-state.d.ts +1 -1
- package/dist/core/tasks/task-state.d.ts.map +1 -1
- package/dist/core/tasks/task-state.js +10 -3
- package/dist/core/tasks/task-state.js.map +1 -1
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +11 -3
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/delegate.d.ts.map +1 -1
- package/dist/core/tools/delegate.js +9 -3
- package/dist/core/tools/delegate.js.map +1 -1
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +47 -5
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/goal.d.ts +16 -1
- package/dist/core/tools/goal.d.ts.map +1 -1
- package/dist/core/tools/goal.js +14 -2
- package/dist/core/tools/goal.js.map +1 -1
- package/dist/core/tools/index.d.ts +1 -1
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +1 -1
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts +5 -0
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +33 -2
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/core/tools/pipeline.d.ts +35 -0
- package/dist/core/tools/pipeline.d.ts.map +1 -0
- package/dist/core/tools/pipeline.js +203 -0
- package/dist/core/tools/pipeline.js.map +1 -0
- package/dist/core/tools/skill-audit.d.ts.map +1 -1
- package/dist/core/tools/skill-audit.js +2 -1
- package/dist/core/tools/skill-audit.js.map +1 -1
- package/dist/core/tools/skill.d.ts.map +1 -1
- package/dist/core/tools/skill.js +2 -1
- package/dist/core/tools/skill.js.map +1 -1
- package/dist/core/tools/skillify.d.ts.map +1 -1
- package/dist/core/tools/skillify.js +3 -1
- package/dist/core/tools/skillify.js.map +1 -1
- package/dist/core/tools/task-steps.d.ts +1 -1
- package/dist/core/tools/task-steps.d.ts.map +1 -1
- package/dist/core/tools/task-steps.js +9 -0
- package/dist/core/tools/task-steps.js.map +1 -1
- package/dist/core/tools/tool-task.d.ts.map +1 -1
- package/dist/core/tools/tool-task.js +5 -1
- package/dist/core/tools/tool-task.js.map +1 -1
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +1 -0
- package/dist/core/tools/write.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +3 -0
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +66 -0
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/skill-invocation-message.js +1 -1
- package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +6 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +20 -1
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/tool-group.d.ts +4 -0
- package/dist/modes/interactive/components/tool-group.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-group.js +96 -7
- package/dist/modes/interactive/components/tool-group.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +8 -10
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/key-handlers.d.ts +1 -0
- package/dist/modes/interactive/key-handlers.d.ts.map +1 -1
- package/dist/modes/interactive/key-handlers.js +2 -1
- package/dist/modes/interactive/key-handlers.js.map +1 -1
- package/dist/modes/interactive/settings-selector-flow.d.ts.map +1 -1
- package/dist/modes/interactive/settings-selector-flow.js +12 -0
- package/dist/modes/interactive/settings-selector-flow.js.map +1 -1
- package/docs/extensions.md +8 -5
- package/docs/harness-architecture.md +3 -4
- package/docs/keybindings.md +3 -2
- package/docs/quickstart.md +4 -4
- package/docs/sdk.md +3 -1
- package/docs/settings.md +16 -2
- package/docs/task-steps.md +1 -0
- package/docs/usage.md +6 -7
- package/docs/worker-profiles.md +1 -1
- package/docs/worktree-sync.md +1 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/minimal-mode.ts +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/examples/sdk/07-context-files.ts +5 -2
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"goal-continuation-controller.js","sourceRoot":"","sources":["../../../src/core/goals/goal-continuation-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,6BAA6B,EAAE,MAAM,sBAAsB,CAAC;AAsCrE,MAAM,UAAU,wBAAwB,CAAC,IAiDxC;IACA,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;QACjB,OAAO;YACN,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,oBAAoB;YAChC,OAAO,EAAE,2BAA2B;YACpC,kBAAkB,EAAE,EAAE;YACtB,qBAAqB,EAAE,EAAE;YACzB,uBAAuB,EA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CAAC,UAAU,IAAI,IAAI,CAAC,QAAQ,CAAC,aAAa,EAAE,CAAC;QACxF,OAAO;YACN,GAAG,YAAY;YACf,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,qBAAqB;YACjC,OAAO,EAAE,mDAAmD,IAAI,CAAC,QAAQ,CAAC,aAAa,SAAS;SAChG,CAAC;IACH,CAAC;IAED,OAAO;QACN,GAAG,YAAY;QACf,MAAM,EAAE,UAAU;QAClB,UAAU,EAAE,aAAa;QACzB,OAAO,EAAE,yCAAyC;KAClD,CAAC;AACH,CAAC","sourcesContent":["import { getUnprovenGoalRequirementIds } from \"./goal-acceptance.ts\";\nimport type { GoalState } from \"./goal-state.ts\";\n\nexport type GoalContinuationAction = \"continue\" | \"ask-user\" | \"finalize\" | \"stop\" | \"waiting\";\nexport type GoalContinuationReasonCode =\n\t| \"goal_active\"\n\t| \"goal_completed\"\n\t| \"goal_paused\"\n\t| \"goal_blocked\"\n\t| \"goal_usage_limited\"\n\t| \"goal_budget_limited\"\n\t| \"goal_cancelled\"\n\t| \"stall_limit_reached\"\n\t| \"goal_completion_required\"\n\t| \"acceptance_evidence_required\"\n\t| \"blocked_requirements_present\"\n\t| \"missing_goal_state\"\n\t| \"worker_in_flight\"\n\t| \"worker_wait_timeout\"\n\t| \"lane_sync_conflict\"\n\t| \"lane_sync_required\";\n\nexport interface GoalContinuationDecision {\n\taction: GoalContinuationAction;\n\treasonCode: GoalContinuationReasonCode;\n\tmessage: string;\n\tgoalId?: string;\n\tstallTurns?: number;\n\tmaxStallTurns?: number;\n\topenRequirementIds: readonly string[];\n\tblockedRequirementIds: readonly string[];\n\tsatisfiedRequirementIds: readonly string[];\n}\n\nexport interface GoalContinuationSettings {\n\tmaxStallTurns: number;\n}\n\nexport function evaluateGoalContinuation(args: {\n\tstate?: GoalState;\n\tsettings: GoalContinuationSettings;\n\t/**\n\t * LaneIds currently queued/running AND tagged with THIS goal's id (see `LaneRecord.goalId`).\n\t * When an open requirement is bound (`Requirement.boundLaneId`) to one of these lanes, the\n\t * goal is WAITING on that worker rather than stalled or ready for another pass: the loop must not\n\t * submit a hollow continuation prompt (which would waste a turn while no parent work can advance),\n\t * and the idle scheduler must not race a re-dispatch against the same open requirement. Optional\n\t * so every pre-existing (in-flight-unaware) caller keeps compiling and behaving unchanged.\n\t */\n\tinFlightGoalLaneIds?: ReadonlySet<string>;\n\t/**\n\t * Current time as an ISO string, paired with `maxWorkerWaitMs` to detect a bound in-flight\n\t * requirement that has hung past its deadline (see below). Optional so every pre-existing\n\t * caller that omits it keeps behaving byte-identically -- the goal waits indefinitely, exactly\n\t * as before this field existed.\n\t */\n\tnow?: string;\n\t/**\n\t * Maximum milliseconds a bound in-flight requirement (`Requirement.boundAt`) may wait before\n\t * this escalates to `action:\"ask-user\"`/`reasonCode:\"worker_wait_timeout\"` instead of\n\t * `\"waiting\"` -- a worker that is alive-but-hung past its deadline must not wait forever. Only\n\t * takes effect when BOTH `now` and this are supplied; escalation fires only once EVERY\n\t * bound-in-flight open requirement has individually passed `boundAt + maxWorkerWaitMs`, so a\n\t * goal with a mix of fresh and stale bindings keeps waiting on the fresh one.\n\t */\n\tmaxWorkerWaitMs?: number;\n\t/**\n\t * Bound lanes (`Requirement.boundLaneId` -- SAME id-space as `inFlightGoalLaneIds`, not the raw\n\t * worktree-sync `laneKey`) whose worktree-sync lane has a rebase stopped on conflicts\n\t * (`LaneFacts.rebaseInProgress`). The caller (`goal-runtime-snapshot.ts`) is responsible for\n\t * translating live per-worktree-lane status into this id-space by matching each status entry's\n\t * own `boundLaneId` against the requirement -- this function stays pure and never resolves a\n\t * worktree laneKey itself, exactly like `inFlightGoalLaneIds` never resolves a tmux job id.\n\t * Checked BEFORE the waiting branch (see `lane_sync_conflict` below): a stalled-but-conflicted\n\t * worker must get the resolve directive, not silently wait forever. Optional so every\n\t * pre-existing caller keeps compiling and behaving byte-identically when omitted or empty.\n\t */\n\tlaneSyncConflictLaneKeys?: ReadonlySet<string>;\n\t/**\n\t * Bound lanes (`Requirement.boundLaneId`, same id-space note as {@link laneSyncConflictLaneKeys})\n\t * whose worktree-sync lane is stale and must sync with current main before further work\n\t * (`sync_required`, i.e. NOT already covered by `laneSyncConflictLaneKeys` -- a lane with a\n\t * rebase in progress is reported as a conflict, never double-counted here). Checked BEFORE the\n\t * waiting branch, same precedence rationale as above. Optional so every pre-existing caller keeps\n\t * compiling and behaving byte-identically when omitted or empty.\n\t */\n\tsyncRequiredLaneKeys?: ReadonlySet<string>;\n}): GoalContinuationDecision {\n\tif (!args.state) {\n\t\treturn {\n\t\t\taction: \"ask-user\",\n\t\t\treasonCode: \"missing_goal_state\",\n\t\t\tmessage: \"No goal state is present.\",\n\t\t\topenRequirementIds: [],\n\t\t\tblockedRequirementIds: [],\n\t\t\tsatisfiedRequirementIds: [],\n\t\t};\n\t}\n\n\tconst state = args.state;\n\tconst openRequirementIds: string[] = [];\n\tconst blockedRequirementIds: string[] = [];\n\tconst satisfiedRequirementIds: string[] = [];\n\n\tfor (const req of state.requirements) {\n\t\tif (req.status === \"open\") openRequirementIds.push(req.id);\n\t\telse if (req.status === \"blocked\") blockedRequirementIds.push(req.id);\n\t\telse if (req.status === \"satisfied\") satisfiedRequirementIds.push(req.id);\n\t}\n\n\tconst baseDecision = {\n\t\tgoalId: state.goalId,\n\t\tstallTurns: state.stallTurns,\n\t\tmaxStallTurns: args.settings.maxStallTurns,\n\t\topenRequirementIds,\n\t\tblockedRequirementIds,\n\t\tsatisfiedRequirementIds,\n\t};\n\n\tif (state.status === \"completed\") {\n\t\treturn {\n\t\t\t...baseDecision,\n\t\t\taction: \"finalize\",\n\t\t\treasonCode: \"goal_completed\",\n\t\t\tmessage: \"The goal is marked as completed.\",\n\t\t};\n\t}\n\n\tif (state.status === \"paused\") {\n\t\treturn {\n\t\t\t...baseDecision,\n\t\t\taction: \"stop\",\n\t\t\treasonCode: \"goal_paused\",\n\t\t\tmessage: \"The goal is paused by the owner.\",\n\t\t};\n\t}\n\n\tif (state.status === \"blocked\") {\n\t\treturn {\n\t\t\t...baseDecision,\n\t\t\taction: \"ask-user\",\n\t\t\treasonCode: \"goal_blocked\",\n\t\t\tmessage: \"The goal is explicitly blocked.\",\n\t\t};\n\t}\n\n\t// Semantic Circuit Breaker: check if any requirement has been repeatedly blocked.\n\t// If a requirement has failed verification / been blocked 3 or more times, the\n\t// subagent loop is stuck. Forcefully retire the goal to prevent infinite orchestrator looping.\n\tconst MAX_REQUIREMENT_BLOCKS = 3;\n\tfor (const reqId of blockedRequirementIds) {\n\t\tconst blockCount = state.events.filter((e) => e.type === \"block_requirement\" && e.id === reqId).length;\n\n\t\tif (blockCount >= MAX_REQUIREMENT_BLOCKS) {\n\t\t\treturn {\n\t\t\t\t...baseDecision,\n\t\t\t\taction: \"stop\",\n\t\t\t\treasonCode: \"stall_limit_reached\",\n\t\t\t\tmessage: `Circuit Breaker: Requirement '${reqId}' has been blocked ${blockCount} times (e.g. repeated verification failures). The task is stuck in a loop and requires human intervention.`,\n\t\t\t};\n\t\t}\n\t}\n\n\tif (state.status === \"usage_limited\") {\n\t\treturn {\n\t\t\t...baseDecision,\n\t\t\taction: \"ask-user\",\n\t\t\treasonCode: \"goal_usage_limited\",\n\t\t\tmessage: \"The goal stopped after the active provider reached a usage limit.\",\n\t\t};\n\t}\n\n\tif (state.status === \"budget_limited\") {\n\t\treturn {\n\t\t\t...baseDecision,\n\t\t\taction: \"stop\",\n\t\t\treasonCode: \"goal_budget_limited\",\n\t\t\tmessage: \"The goal exhausted its configured budget.\",\n\t\t};\n\t}\n\n\tif (state.status === \"cancelled\") {\n\t\treturn {\n\t\t\t...baseDecision,\n\t\t\taction: \"stop\",\n\t\t\treasonCode: \"goal_cancelled\",\n\t\t\tmessage: \"The goal has been cancelled.\",\n\t\t};\n\t}\n\n\tif (openRequirementIds.length === 0) {\n\t\tif (blockedRequirementIds.length > 0) {\n\t\t\treturn {\n\t\t\t\t...baseDecision,\n\t\t\t\taction: \"ask-user\",\n\t\t\t\treasonCode: \"blocked_requirements_present\",\n\t\t\t\tmessage: \"All remaining legacy goal requirements are blocked.\",\n\t\t\t};\n\t\t}\n\t\tif (state.requirements.length === 0) {\n\t\t\treturn {\n\t\t\t\t...baseDecision,\n\t\t\t\taction: \"continue\",\n\t\t\t\treasonCode: \"goal_active\",\n\t\t\t\tmessage: \"The compact goal record is active.\",\n\t\t\t};\n\t\t}\n\t\tconst unprovenRequirementIds = getUnprovenGoalRequirementIds(state);\n\t\tif (unprovenRequirementIds.length > 0) {\n\t\t\treturn {\n\t\t\t\t...baseDecision,\n\t\t\t\taction: \"continue\",\n\t\t\t\treasonCode: \"acceptance_evidence_required\",\n\t\t\t\tmessage: `Requirement(s) ${unprovenRequirementIds.join(\", \")} still need trusted acceptance evidence.`,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\t...baseDecision,\n\t\t\taction: \"continue\",\n\t\t\treasonCode: \"goal_completion_required\",\n\t\t\tmessage: \"All requirements are proven. Mark the goal complete only after confirming no required work remains.\",\n\t\t};\n\t}\n\n\t// Worktree-sync directives take precedence over the \"waiting\" branch below: a worker whose bound\n\t// lane is conflicted or stale is NOT merely in-flight-and-quiet -- it needs an explicit directive\n\t// (resolve conflicts, or sync) delivered through the continuation prompt, and a stalled-but-stale\n\t// worker must never be left waiting indefinitely for a sync it was never told to run. Conflict is\n\t// checked first: a lane with a rebase already stopped on conflicts cannot usefully be told to\n\t// \"sync\" again (that lane's `sync_required` flag is never set while `rebaseInProgress` is true --\n\t// see `goal-runtime-snapshot.ts` -- so the two sets below are disjoint by construction, not by a\n\t// priority check here).\n\tconst laneSyncConflictLaneKeys = args.laneSyncConflictLaneKeys;\n\tconst conflictedRequirements = laneSyncConflictLaneKeys\n\t\t? state.requirements.filter(\n\t\t\t\t(requirement) =>\n\t\t\t\t\trequirement.status === \"open\" &&\n\t\t\t\t\trequirement.boundLaneId !== undefined &&\n\t\t\t\t\tlaneSyncConflictLaneKeys.has(requirement.boundLaneId),\n\t\t\t)\n\t\t: [];\n\tif (conflictedRequirements.length > 0) {\n\t\treturn {\n\t\t\t...baseDecision,\n\t\t\taction: \"continue\",\n\t\t\treasonCode: \"lane_sync_conflict\",\n\t\t\tmessage: `Requirement(s) ${conflictedRequirements.map((requirement) => requirement.id).join(\", \")} are bound to a worktree-sync lane with a rebase stopped on conflicts; resolve via worktree_sync action:\"continue\" (or \"abort_sync\") before this goal can progress further.`,\n\t\t};\n\t}\n\n\tconst syncRequiredLaneKeys = args.syncRequiredLaneKeys;\n\tconst syncRequiredRequirements = syncRequiredLaneKeys\n\t\t? state.requirements.filter(\n\t\t\t\t(requirement) =>\n\t\t\t\t\trequirement.status === \"open\" &&\n\t\t\t\t\trequirement.boundLaneId !== undefined &&\n\t\t\t\t\tsyncRequiredLaneKeys.has(requirement.boundLaneId),\n\t\t\t)\n\t\t: [];\n\tif (syncRequiredRequirements.length > 0) {\n\t\treturn {\n\t\t\t...baseDecision,\n\t\t\taction: \"continue\",\n\t\t\treasonCode: \"lane_sync_required\",\n\t\t\tmessage: `Requirement(s) ${syncRequiredRequirements.map((requirement) => requirement.id).join(\", \")} are bound to a worktree-sync lane that must rebase current main before further work; deliver worktree_sync action:\"sync\" to the bound worker, or run it directly for an idle lane.`,\n\t\t};\n\t}\n\n\t// A worker is dispatched (queued/running) against an open requirement this goal owns — wait\n\t// for it rather than submit a hollow pass or let the stall counter judge the goal unproductive.\n\t// Checked BEFORE the stall check so an in-flight worker always wins over an accumulated stall\n\t// count: the goal isn't stalled, it's actively being worked by something other than this loop.\n\tconst inFlightGoalLaneIds = args.inFlightGoalLaneIds;\n\tconst boundInFlightRequirements = inFlightGoalLaneIds\n\t\t? state.requirements.filter(\n\t\t\t\t(requirement) =>\n\t\t\t\t\trequirement.status === \"open\" &&\n\t\t\t\t\trequirement.boundLaneId !== undefined &&\n\t\t\t\t\tinFlightGoalLaneIds.has(requirement.boundLaneId),\n\t\t\t)\n\t\t: [];\n\n\tif (boundInFlightRequirements.length > 0) {\n\t\t// Never-hang backstop: a worker alive-but-hung past its deadline must escalate to the owner\n\t\t// instead of waiting forever. Only evaluated when the caller supplies BOTH a clock reading and\n\t\t// a deadline; escalates only once EVERY bound-in-flight requirement has individually timed out,\n\t\t// so one fresh binding keeps the goal legitimately waiting.\n\t\tif (args.now !== undefined && args.maxWorkerWaitMs !== undefined) {\n\t\t\tconst nowMs = Date.parse(args.now);\n\t\t\tconst maxWorkerWaitMs = args.maxWorkerWaitMs;\n\t\t\tconst allTimedOut =\n\t\t\t\tNumber.isFinite(nowMs) &&\n\t\t\t\tboundInFlightRequirements.every((requirement) => {\n\t\t\t\t\tif (requirement.boundAt === undefined) return false;\n\t\t\t\t\tconst boundAtMs = Date.parse(requirement.boundAt);\n\t\t\t\t\treturn Number.isFinite(boundAtMs) && boundAtMs + maxWorkerWaitMs <= nowMs;\n\t\t\t\t});\n\t\t\tif (allTimedOut) {\n\t\t\t\treturn {\n\t\t\t\t\t...baseDecision,\n\t\t\t\t\taction: \"ask-user\",\n\t\t\t\t\treasonCode: \"worker_wait_timeout\",\n\t\t\t\t\tmessage: `A dispatched worker has not completed within the maximum wait of ${maxWorkerWaitMs}ms; escalating to the owner instead of waiting indefinitely.`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\t...baseDecision,\n\t\t\taction: \"waiting\",\n\t\t\treasonCode: \"worker_in_flight\",\n\t\t\tmessage: \"A worker is dispatched against an open requirement; waiting for it to finish before continuing.\",\n\t\t};\n\t}\n\n\tif (args.settings.maxStallTurns > 0 && state.stallTurns >= args.settings.maxStallTurns) {\n\t\treturn {\n\t\t\t...baseDecision,\n\t\t\taction: \"ask-user\",\n\t\t\treasonCode: \"stall_limit_reached\",\n\t\t\tmessage: `The goal has reached the maximum stall limit of ${args.settings.maxStallTurns} turns.`,\n\t\t};\n\t}\n\n\treturn {\n\t\t...baseDecision,\n\t\taction: \"continue\",\n\t\treasonCode: \"goal_active\",\n\t\tmessage: \"The goal is active and making progress.\",\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"goal-continuation-controller.js","sourceRoot":"","sources":["../../../src/core/goals/goal-continuation-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,6BAA6B,EAAE,MAAM,sBAAsB,CAAC;AAuCrE,MAAM,UAAU,wBAAwB,CAAC,IAuDxC;IACA,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;QACjB,OAAO;YACN,MAAM,EAAE,UAAU;YAClB,UAAU,EAAE,oBAAoB;YAChC,OAAO,EAAE,2BAA2B;YACpC,kBAAkB,EAAE,EAAE;YACtB,qBAAqB,EAAE,EAAE;YACzB,uBAAuB,EAAE,EAAE;SAC3B,CAAC;IACH,CAAC;IAED,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;IACzB,MAAM,kBAAkB,GAAa,EAAE,CAAC;IACxC,MAAM,qBAAqB,GAAa,EAAE,CAAC;IAC3C,MAAM,uBAAuB,GAAa,EAAE,CAAC;IAE7C,KAAK,MAAM,GAAG,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;QACtC,IAAI,GAAG,CAAC,MAAM,KAAK,MAAM;YAAE,kBAAkB,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;aACtD,IAAI,GAAG,CAAC,MAAM,KAAK,SAAS;YAAE,qBAAqB,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;aACjE,IAAI,GAAG,CAAC,MAAM,KAAK,WAAW;YAAE,uBAAuB,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAC3E,CAAC;IAED,MAAM,YAAY,GAAG;QACpB,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,aAAa,EAAE,IAAI,CAAC,QAAQ,CAAC,aAAa;QAC1C,kBAAkB;QAClB,qBAAqB;QACrB,uBAAuB;KACvB,CAAC;IAEF,IAAI,KAAK,CAAC,MAAM,KAAK,WAAW,EAAE,C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AO;QACN,GAAG,YAAY;QACf,MAAM,EAAE,UAAU;QAClB,UAAU,EAAE,aAAa;QACzB,OAAO,EAAE,yCAAyC;KAClD,CAAC;AACH,CAAC","sourcesContent":["import { getUnprovenGoalRequirementIds } from \"./goal-acceptance.ts\";\nimport type { GoalState } from \"./goal-state.ts\";\n\nexport type GoalContinuationAction = \"continue\" | \"ask-user\" | \"finalize\" | \"stop\" | \"waiting\";\nexport type GoalContinuationReasonCode =\n\t| \"goal_active\"\n\t| \"goal_completed\"\n\t| \"goal_paused\"\n\t| \"goal_blocked\"\n\t| \"goal_usage_limited\"\n\t| \"goal_budget_limited\"\n\t| \"goal_cancelled\"\n\t| \"stall_limit_reached\"\n\t| \"goal_completion_required\"\n\t| \"acceptance_evidence_required\"\n\t| \"blocked_requirements_present\"\n\t| \"missing_goal_state\"\n\t| \"worker_in_flight\"\n\t| \"tool_task_in_flight\"\n\t| \"worker_wait_timeout\"\n\t| \"lane_sync_conflict\"\n\t| \"lane_sync_required\";\n\nexport interface GoalContinuationDecision {\n\taction: GoalContinuationAction;\n\treasonCode: GoalContinuationReasonCode;\n\tmessage: string;\n\tgoalId?: string;\n\tstallTurns?: number;\n\tmaxStallTurns?: number;\n\topenRequirementIds: readonly string[];\n\tblockedRequirementIds: readonly string[];\n\tsatisfiedRequirementIds: readonly string[];\n}\n\nexport interface GoalContinuationSettings {\n\tmaxStallTurns: number;\n}\n\nexport function evaluateGoalContinuation(args: {\n\tstate?: GoalState;\n\tsettings: GoalContinuationSettings;\n\t/**\n\t * LaneIds currently queued/running AND tagged with THIS goal's id (see `LaneRecord.goalId`).\n\t * When an open requirement is bound (`Requirement.boundLaneId`) to one of these lanes, the\n\t * goal is WAITING on that worker rather than stalled or ready for another pass: the loop must not\n\t * submit a hollow continuation prompt (which would waste a turn while no parent work can advance),\n\t * and the idle scheduler must not race a re-dispatch against the same open requirement. Optional\n\t * so every pre-existing (in-flight-unaware) caller keeps compiling and behaving unchanged.\n\t */\n\tinFlightGoalLaneIds?: ReadonlySet<string>;\n\t/**\n\t * Current time as an ISO string, paired with `maxWorkerWaitMs` to detect a bound in-flight\n\t * requirement that has hung past its deadline (see below). Optional so every pre-existing\n\t * caller that omits it keeps behaving byte-identically -- the goal waits indefinitely, exactly\n\t * as before this field existed.\n\t */\n\tnow?: string;\n\t/**\n\t * Maximum milliseconds a bound in-flight requirement (`Requirement.boundAt`) may wait before\n\t * this escalates to `action:\"ask-user\"`/`reasonCode:\"worker_wait_timeout\"` instead of\n\t * `\"waiting\"` -- a worker that is alive-but-hung past its deadline must not wait forever. Only\n\t * takes effect when BOTH `now` and this are supplied; escalation fires only once EVERY\n\t * bound-in-flight open requirement has individually passed `boundAt + maxWorkerWaitMs`, so a\n\t * goal with a mix of fresh and stale bindings keeps waiting on the fresh one.\n\t */\n\tmaxWorkerWaitMs?: number;\n\t/**\n\t * Bound lanes (`Requirement.boundLaneId` -- SAME id-space as `inFlightGoalLaneIds`, not the raw\n\t * worktree-sync `laneKey`) whose worktree-sync lane has a rebase stopped on conflicts\n\t * (`LaneFacts.rebaseInProgress`). The caller (`goal-runtime-snapshot.ts`) is responsible for\n\t * translating live per-worktree-lane status into this id-space by matching each status entry's\n\t * own `boundLaneId` against the requirement -- this function stays pure and never resolves a\n\t * worktree laneKey itself, exactly like `inFlightGoalLaneIds` never resolves a tmux job id.\n\t * Checked BEFORE the waiting branch (see `lane_sync_conflict` below): a stalled-but-conflicted\n\t * worker must get the resolve directive, not silently wait forever. Optional so every\n\t * pre-existing caller keeps compiling and behaving byte-identically when omitted or empty.\n\t */\n\tlaneSyncConflictLaneKeys?: ReadonlySet<string>;\n\t/**\n\t * Bound lanes (`Requirement.boundLaneId`, same id-space note as {@link laneSyncConflictLaneKeys})\n\t * whose worktree-sync lane is stale and must sync with current main before further work\n\t * (`sync_required`, i.e. NOT already covered by `laneSyncConflictLaneKeys` -- a lane with a\n\t * rebase in progress is reported as a conflict, never double-counted here). Checked BEFORE the\n\t * waiting branch, same precedence rationale as above. Optional so every pre-existing caller keeps\n\t * compiling and behaving byte-identically when omitted or empty.\n\t */\n\tsyncRequiredLaneKeys?: ReadonlySet<string>;\n\t/**\n\t * Background tool_task ids that are still running and cited by this goal's evidence or by\n\t * linked open task_steps. The loop must wait for those terminals the same way it waits on\n\t * a bound worker — a handoff stub is not completion.\n\t */\n\tinFlightToolTaskIds?: ReadonlySet<string>;\n}): GoalContinuationDecision {\n\tif (!args.state) {\n\t\treturn {\n\t\t\taction: \"ask-user\",\n\t\t\treasonCode: \"missing_goal_state\",\n\t\t\tmessage: \"No goal state is present.\",\n\t\t\topenRequirementIds: [],\n\t\t\tblockedRequirementIds: [],\n\t\t\tsatisfiedRequirementIds: [],\n\t\t};\n\t}\n\n\tconst state = args.state;\n\tconst openRequirementIds: string[] = [];\n\tconst blockedRequirementIds: string[] = [];\n\tconst satisfiedRequirementIds: string[] = [];\n\n\tfor (const req of state.requirements) {\n\t\tif (req.status === \"open\") openRequirementIds.push(req.id);\n\t\telse if (req.status === \"blocked\") blockedRequirementIds.push(req.id);\n\t\telse if (req.status === \"satisfied\") satisfiedRequirementIds.push(req.id);\n\t}\n\n\tconst baseDecision = {\n\t\tgoalId: state.goalId,\n\t\tstallTurns: state.stallTurns,\n\t\tmaxStallTurns: args.settings.maxStallTurns,\n\t\topenRequirementIds,\n\t\tblockedRequirementIds,\n\t\tsatisfiedRequirementIds,\n\t};\n\n\tif (state.status === \"completed\") {\n\t\treturn {\n\t\t\t...baseDecision,\n\t\t\taction: \"finalize\",\n\t\t\treasonCode: \"goal_completed\",\n\t\t\tmessage: \"The goal is marked as completed.\",\n\t\t};\n\t}\n\n\tif (state.status === \"paused\") {\n\t\treturn {\n\t\t\t...baseDecision,\n\t\t\taction: \"stop\",\n\t\t\treasonCode: \"goal_paused\",\n\t\t\tmessage: \"The goal is paused by the owner.\",\n\t\t};\n\t}\n\n\tif (state.status === \"blocked\") {\n\t\treturn {\n\t\t\t...baseDecision,\n\t\t\taction: \"ask-user\",\n\t\t\treasonCode: \"goal_blocked\",\n\t\t\tmessage: \"The goal is explicitly blocked.\",\n\t\t};\n\t}\n\n\t// Semantic Circuit Breaker: check if any requirement has been repeatedly blocked.\n\t// If a requirement has failed verification / been blocked 3 or more times, the\n\t// subagent loop is stuck. Forcefully retire the goal to prevent infinite orchestrator looping.\n\tconst MAX_REQUIREMENT_BLOCKS = 3;\n\tfor (const reqId of blockedRequirementIds) {\n\t\tconst blockCount = state.events.filter((e) => e.type === \"block_requirement\" && e.id === reqId).length;\n\n\t\tif (blockCount >= MAX_REQUIREMENT_BLOCKS) {\n\t\t\treturn {\n\t\t\t\t...baseDecision,\n\t\t\t\taction: \"stop\",\n\t\t\t\treasonCode: \"stall_limit_reached\",\n\t\t\t\tmessage: `Circuit Breaker: Requirement '${reqId}' has been blocked ${blockCount} times (e.g. repeated verification failures). The task is stuck in a loop and requires human intervention.`,\n\t\t\t};\n\t\t}\n\t}\n\n\tif (state.status === \"usage_limited\") {\n\t\treturn {\n\t\t\t...baseDecision,\n\t\t\taction: \"ask-user\",\n\t\t\treasonCode: \"goal_usage_limited\",\n\t\t\tmessage: \"The goal stopped after the active provider reached a usage limit.\",\n\t\t};\n\t}\n\n\tif (state.status === \"budget_limited\") {\n\t\treturn {\n\t\t\t...baseDecision,\n\t\t\taction: \"stop\",\n\t\t\treasonCode: \"goal_budget_limited\",\n\t\t\tmessage: \"The goal exhausted its configured budget.\",\n\t\t};\n\t}\n\n\tif (state.status === \"cancelled\") {\n\t\treturn {\n\t\t\t...baseDecision,\n\t\t\taction: \"stop\",\n\t\t\treasonCode: \"goal_cancelled\",\n\t\t\tmessage: \"The goal has been cancelled.\",\n\t\t};\n\t}\n\n\tif (openRequirementIds.length === 0) {\n\t\tif (blockedRequirementIds.length > 0) {\n\t\t\treturn {\n\t\t\t\t...baseDecision,\n\t\t\t\taction: \"ask-user\",\n\t\t\t\treasonCode: \"blocked_requirements_present\",\n\t\t\t\tmessage: \"All remaining legacy goal requirements are blocked.\",\n\t\t\t};\n\t\t}\n\t\tif (state.requirements.length === 0) {\n\t\t\treturn {\n\t\t\t\t...baseDecision,\n\t\t\t\taction: \"continue\",\n\t\t\t\treasonCode: \"goal_active\",\n\t\t\t\tmessage: \"The compact goal record is active.\",\n\t\t\t};\n\t\t}\n\t\tconst unprovenRequirementIds = getUnprovenGoalRequirementIds(state);\n\t\tif (unprovenRequirementIds.length > 0) {\n\t\t\treturn {\n\t\t\t\t...baseDecision,\n\t\t\t\taction: \"continue\",\n\t\t\t\treasonCode: \"acceptance_evidence_required\",\n\t\t\t\tmessage: `Requirement(s) ${unprovenRequirementIds.join(\", \")} still need trusted acceptance evidence.`,\n\t\t\t};\n\t\t}\n\t\tif (args.inFlightToolTaskIds && args.inFlightToolTaskIds.size > 0) {\n\t\t\treturn {\n\t\t\t\t...baseDecision,\n\t\t\t\taction: \"waiting\",\n\t\t\t\treasonCode: \"tool_task_in_flight\",\n\t\t\t\tmessage: `Background tool_task(s) ${[...args.inFlightToolTaskIds].join(\", \")} are still running; wait once via tool_task before completing.`,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\t...baseDecision,\n\t\t\taction: \"continue\",\n\t\t\treasonCode: \"goal_completion_required\",\n\t\t\tmessage: \"All requirements are proven. Mark the goal complete only after confirming no required work remains.\",\n\t\t};\n\t}\n\n\t// Worktree-sync directives take precedence over the \"waiting\" branch below: a worker whose bound\n\t// lane is conflicted or stale is NOT merely in-flight-and-quiet -- it needs an explicit directive\n\t// (resolve conflicts, or sync) delivered through the continuation prompt, and a stalled-but-stale\n\t// worker must never be left waiting indefinitely for a sync it was never told to run. Conflict is\n\t// checked first: a lane with a rebase already stopped on conflicts cannot usefully be told to\n\t// \"sync\" again (that lane's `sync_required` flag is never set while `rebaseInProgress` is true --\n\t// see `goal-runtime-snapshot.ts` -- so the two sets below are disjoint by construction, not by a\n\t// priority check here).\n\tconst laneSyncConflictLaneKeys = args.laneSyncConflictLaneKeys;\n\tconst conflictedRequirements = laneSyncConflictLaneKeys\n\t\t? state.requirements.filter(\n\t\t\t\t(requirement) =>\n\t\t\t\t\trequirement.status === \"open\" &&\n\t\t\t\t\trequirement.boundLaneId !== undefined &&\n\t\t\t\t\tlaneSyncConflictLaneKeys.has(requirement.boundLaneId),\n\t\t\t)\n\t\t: [];\n\tif (conflictedRequirements.length > 0) {\n\t\treturn {\n\t\t\t...baseDecision,\n\t\t\taction: \"continue\",\n\t\t\treasonCode: \"lane_sync_conflict\",\n\t\t\tmessage: `Requirement(s) ${conflictedRequirements.map((requirement) => requirement.id).join(\", \")} are bound to a worktree-sync lane with a rebase stopped on conflicts; resolve via worktree_sync action:\"continue\" (or \"abort_sync\") before this goal can progress further.`,\n\t\t};\n\t}\n\n\tconst syncRequiredLaneKeys = args.syncRequiredLaneKeys;\n\tconst syncRequiredRequirements = syncRequiredLaneKeys\n\t\t? state.requirements.filter(\n\t\t\t\t(requirement) =>\n\t\t\t\t\trequirement.status === \"open\" &&\n\t\t\t\t\trequirement.boundLaneId !== undefined &&\n\t\t\t\t\tsyncRequiredLaneKeys.has(requirement.boundLaneId),\n\t\t\t)\n\t\t: [];\n\tif (syncRequiredRequirements.length > 0) {\n\t\treturn {\n\t\t\t...baseDecision,\n\t\t\taction: \"continue\",\n\t\t\treasonCode: \"lane_sync_required\",\n\t\t\tmessage: `Requirement(s) ${syncRequiredRequirements.map((requirement) => requirement.id).join(\", \")} are bound to a worktree-sync lane that must rebase current main before further work; deliver worktree_sync action:\"sync\" to the bound worker, or run it directly for an idle lane.`,\n\t\t};\n\t}\n\n\t// A worker is dispatched (queued/running) against an open requirement this goal owns — wait\n\t// for it rather than submit a hollow pass or let the stall counter judge the goal unproductive.\n\t// Checked BEFORE the stall check so an in-flight worker always wins over an accumulated stall\n\t// count: the goal isn't stalled, it's actively being worked by something other than this loop.\n\tconst inFlightGoalLaneIds = args.inFlightGoalLaneIds;\n\tconst boundInFlightRequirements = inFlightGoalLaneIds\n\t\t? state.requirements.filter(\n\t\t\t\t(requirement) =>\n\t\t\t\t\trequirement.status === \"open\" &&\n\t\t\t\t\trequirement.boundLaneId !== undefined &&\n\t\t\t\t\tinFlightGoalLaneIds.has(requirement.boundLaneId),\n\t\t\t)\n\t\t: [];\n\n\tif (boundInFlightRequirements.length > 0) {\n\t\t// Never-hang backstop: a worker alive-but-hung past its deadline must escalate to the owner\n\t\t// instead of waiting forever. Only evaluated when the caller supplies BOTH a clock reading and\n\t\t// a deadline; escalates only once EVERY bound-in-flight requirement has individually timed out,\n\t\t// so one fresh binding keeps the goal legitimately waiting.\n\t\tif (args.now !== undefined && args.maxWorkerWaitMs !== undefined) {\n\t\t\tconst nowMs = Date.parse(args.now);\n\t\t\tconst maxWorkerWaitMs = args.maxWorkerWaitMs;\n\t\t\tconst allTimedOut =\n\t\t\t\tNumber.isFinite(nowMs) &&\n\t\t\t\tboundInFlightRequirements.every((requirement) => {\n\t\t\t\t\tif (requirement.boundAt === undefined) return false;\n\t\t\t\t\tconst boundAtMs = Date.parse(requirement.boundAt);\n\t\t\t\t\treturn Number.isFinite(boundAtMs) && boundAtMs + maxWorkerWaitMs <= nowMs;\n\t\t\t\t});\n\t\t\tif (allTimedOut) {\n\t\t\t\treturn {\n\t\t\t\t\t...baseDecision,\n\t\t\t\t\taction: \"ask-user\",\n\t\t\t\t\treasonCode: \"worker_wait_timeout\",\n\t\t\t\t\tmessage: `A dispatched worker has not completed within the maximum wait of ${maxWorkerWaitMs}ms; escalating to the owner instead of waiting indefinitely.`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\t...baseDecision,\n\t\t\taction: \"waiting\",\n\t\t\treasonCode: \"worker_in_flight\",\n\t\t\tmessage: \"A worker is dispatched against an open requirement; waiting for it to finish before continuing.\",\n\t\t};\n\t}\n\n\tif (args.inFlightToolTaskIds && args.inFlightToolTaskIds.size > 0) {\n\t\treturn {\n\t\t\t...baseDecision,\n\t\t\taction: \"waiting\",\n\t\t\treasonCode: \"tool_task_in_flight\",\n\t\t\tmessage: `Background tool_task(s) ${[...args.inFlightToolTaskIds].join(\", \")} are still running; wait once via tool_task before continuing or completing.`,\n\t\t};\n\t}\n\n\tif (args.settings.maxStallTurns > 0 && state.stallTurns >= args.settings.maxStallTurns) {\n\t\treturn {\n\t\t\t...baseDecision,\n\t\t\taction: \"ask-user\",\n\t\t\treasonCode: \"stall_limit_reached\",\n\t\t\tmessage: `The goal has reached the maximum stall limit of ${args.settings.maxStallTurns} turns.`,\n\t\t};\n\t}\n\n\treturn {\n\t\t...baseDecision,\n\t\taction: \"continue\",\n\t\treasonCode: \"goal_active\",\n\t\tmessage: \"The goal is active and making progress.\",\n\t};\n}\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { SessionManager } from "@caupulican/pi-agent-core/node";
|
|
2
2
|
import type { EvidenceBundle, LearningDecision, WorkerClaim } from "../autonomy/contracts.ts";
|
|
3
3
|
import type { LaneRecord } from "../autonomy/lane-tracker.ts";
|
|
4
|
+
import type { BackgroundToolTaskRef } from "../background-tool-task-controller.ts";
|
|
4
5
|
import type { TaskRuntimeProjection } from "../orchestration/task-runtime.ts";
|
|
5
6
|
import { type SessionWorkStateProjection } from "../orchestration/work-state-projection.ts";
|
|
6
7
|
import type { OpenTaskStepProjection } from "../tasks/task-projection.ts";
|
|
@@ -116,5 +117,7 @@ export declare function buildGoalRuntimeSnapshot(args: {
|
|
|
116
117
|
worktreeLaneStatus?: readonly GoalRuntimeWorktreeLaneStatus[];
|
|
117
118
|
/** Durable worker DAG projection, supplied only when the delegate capability has been loaded. */
|
|
118
119
|
taskRuntime?: TaskRuntimeProjection;
|
|
120
|
+
/** Live background tool_task records for this session. */
|
|
121
|
+
backgroundToolTasks?: readonly BackgroundToolTaskRef[];
|
|
119
122
|
}): GoalRuntimeSnapshot;
|
|
120
123
|
//# sourceMappingURL=goal-runtime-snapshot.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"goal-runtime-snapshot.d.ts","sourceRoot":"","sources":["../../../src/core/goals/goal-runtime-snapshot.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAC9F,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;
|
|
1
|
+
{"version":3,"file":"goal-runtime-snapshot.d.ts","sourceRoot":"","sources":["../../../src/core/goals/goal-runtime-snapshot.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAC9F,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAGnF,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAC9E,OAAO,EAA2B,KAAK,0BAA0B,EAAE,MAAM,2CAA2C,CAAC;AAIrH,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAC1E,OAAO,EAA4B,KAAK,wBAAwB,EAAE,MAAM,mCAAmC,CAAC;AAE5G,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAGjD,MAAM,WAAW,2BAA2B;IAC3C,aAAa,EAAE,MAAM,CAAC;CACtB;AAED;;;;;GAKG;AACH,MAAM,MAAM,uBAAuB,GAAG,sBAAsB,CAAC;AAE7D;;;;;;;;GAQG;AACH,MAAM,WAAW,6BAA6B;IAC7C,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE,OAAO,CAAC;IACf,KAAK,EAAE,OAAO,CAAC;IACf,YAAY,EAAE,OAAO,CAAC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AAG,mBAAmB,CAoGtB"}
|
|
@@ -21,7 +21,12 @@ export function buildGoalRuntimeSnapshot(args) {
|
|
|
21
21
|
// Reuses the SAME branch-scoped primitive as goal-state resolution (getLatestCustomEntryOnBranch),
|
|
22
22
|
// so the task-steps summary below can never leak a sibling branch's checklist either.
|
|
23
23
|
const taskStepsState = getLatestTaskStepsStateSnapshot(args.sessionManager);
|
|
24
|
-
const workState = projectSessionWorkState({
|
|
24
|
+
const workState = projectSessionWorkState({
|
|
25
|
+
goalState,
|
|
26
|
+
taskStepsState,
|
|
27
|
+
taskRuntime: args.taskRuntime,
|
|
28
|
+
backgroundToolTasks: args.backgroundToolTasks,
|
|
29
|
+
});
|
|
25
30
|
const openTaskSteps = workState.openTaskSteps;
|
|
26
31
|
let inFlightGoalLaneIds;
|
|
27
32
|
if (goalState && args.laneRecords) {
|
|
@@ -85,6 +90,7 @@ export function buildGoalRuntimeSnapshot(args) {
|
|
|
85
90
|
}
|
|
86
91
|
const now = (args.now ?? (() => new Date().toISOString()))();
|
|
87
92
|
const maxWorkerWaitMs = args.maxWorkerWaitMs ?? DEFAULT_GOAL_WORKER_WAIT_MS;
|
|
93
|
+
const inFlightToolTaskIds = new Set(workState.runningToolTaskIds);
|
|
88
94
|
const continuation = evaluateGoalContinuation({
|
|
89
95
|
state: goalState,
|
|
90
96
|
settings: { maxStallTurns: args.settings.maxStallTurns },
|
|
@@ -93,6 +99,7 @@ export function buildGoalRuntimeSnapshot(args) {
|
|
|
93
99
|
maxWorkerWaitMs,
|
|
94
100
|
laneSyncConflictLaneKeys: laneSyncConflictLaneKeys.size > 0 ? laneSyncConflictLaneKeys : undefined,
|
|
95
101
|
syncRequiredLaneKeys: syncRequiredLaneKeys.size > 0 ? syncRequiredLaneKeys : undefined,
|
|
102
|
+
...(inFlightToolTaskIds.size > 0 ? { inFlightToolTaskIds } : {}),
|
|
96
103
|
});
|
|
97
104
|
return {
|
|
98
105
|
goalState,
|
|
@@ -1 +1 @@
|
|
|
1
|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AAG,CAAC,CAAC,CAAC,CAAC,wBAAwB,CAAC,CAAC,CAAC,SAAS;QAClG,oBAAoB,EAAE,oBAAoB,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,SAAS;KACtF,CAAC,CAAC;IAEH,OAAO;QACN,SAAS;QACT,oBAAoB;QACpB,YAAY;QACZ,iBAAiB;QACjB,YAAY;QACZ,aAAa;QACb,SAAS;QACT,GAAG,CAAC,yBAAyB,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,yBAAyB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACjF,CAAC;AACH,CAAC","sourcesContent":["import type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { EvidenceBundle, LearningDecision, WorkerClaim } from \"../autonomy/contracts.ts\";\nimport type { LaneRecord } from \"../autonomy/lane-tracker.ts\";\nimport { getWorkerClaimSnapshots } from \"../delegation/session-worker-claim.ts\";\nimport { getLearningDecisionSnapshots } from \"../learning/session-learning-decision.ts\";\nimport type { TaskRuntimeProjection } from \"../orchestration/task-runtime.ts\";\nimport { projectSessionWorkState, type SessionWorkStateProjection } from \"../orchestration/work-state-projection.ts\";\nimport { getLatestEvidenceBundleSnapshot } from \"../research/session-evidence-bundle.ts\";\nimport { getActiveSessionBranchEntries } from \"../session-snapshot.ts\";\nimport { getLatestTaskStepsStateSnapshot } from \"../tasks/session-task-state.ts\";\nimport type { OpenTaskStepProjection } from \"../tasks/task-projection.ts\";\nimport { evaluateGoalContinuation, type GoalContinuationDecision } from \"./goal-continuation-controller.ts\";\nimport { DEFAULT_GOAL_WORKER_WAIT_MS } from \"./goal-continuation-defaults.ts\";\nimport type { GoalState } from \"./goal-state.ts\";\nimport { getLatestGoalStateSnapshot } from \"./session-goal-state.ts\";\n\nexport interface GoalRuntimeSnapshotSettings {\n\tmaxStallTurns: number;\n}\n\n/**\n * A read-only projection of one OPEN (non-terminal) task_steps step, included in the goal\n * runtime snapshot purely for cross-visibility. This is NOT a shared state machine: the goal\n * loop never writes back to task state through this snapshot, and the task store stays the\n * single source of truth for its own steps.\n */\nexport type GoalRuntimeOpenTaskStep = OpenTaskStepProjection;\n\n/**\n * Live, per-worktree-sync-lane status for one lane bound to a dispatched worker, as the caller\n * (runtime-builder / whatever host process has live git-engine access) derives it. `boundLaneId` is\n * the host `LaneRecord.laneId` the lane's registration was correlated to\n * (`LaneRegistration.boundLaneId`, same id-space as `Requirement.boundLaneId`) -- `undefined` for a\n * lane never bound to a dispatch. `fresh`/`stale` mirror `LaneFacts`; `syncRequired` is the\n * staleness-propagation verdict (`WorktreeSyncPolicy`-derived); `rebaseInProgress` marks a sync that\n * stopped on conflicts (a rebase left in progress) -- see `core/worktree-sync/git-engine.ts`.\n */\nexport interface GoalRuntimeWorktreeLaneStatus {\n\tlaneKey: string;\n\tboundLaneId?: string;\n\tfresh: boolean;\n\tstale: boolean;\n\tsyncRequired: boolean;\n\trebaseInProgress: boolean;\n}\n\n/**\n * Per-requirement projection of {@link GoalRuntimeWorktreeLaneStatus}, joined via\n * `requirement.boundLaneId === status.boundLaneId` -- read-only cross-visibility for snapshot\n * consumers (e.g. a future continuation-prompt render), mirroring `openTaskSteps`'s role. This is\n * NOT what feeds `evaluateGoalContinuation` (that reads the raw `boundLaneId`-keyed sets directly);\n * it exists purely so a requirement's worktree state is visible without re-deriving the join.\n */\nexport interface GoalRuntimeRequirementWorktreeState {\n\trequirementId: string;\n\tlaneKey: string;\n\tfresh: boolean;\n\tstale: boolean;\n\tsyncRequired: boolean;\n\trebaseInProgress: boolean;\n}\n\nexport interface GoalRuntimeSnapshot {\n\tgoalState?: GoalState;\n\tlatestEvidenceBundle?: EvidenceBundle;\n\tworkerClaims: readonly WorkerClaim[];\n\tlearningDecisions: readonly LearningDecision[];\n\tcontinuation: GoalContinuationDecision;\n\t/**\n\t * Open (non-terminal) task_steps steps on the active branch, latest-wins. Read-only.\n\t * Optional (like `goalState`/`latestEvidenceBundle`) so hand-built snapshots in existing\n\t * tests/call sites that predate this field keep compiling unchanged; `buildGoalRuntimeSnapshot`\n\t * itself always populates a concrete array (possibly empty).\n\t */\n\topenTaskSteps?: readonly GoalRuntimeOpenTaskStep[];\n\t/** Canonical read model joining requirements, foreground steps, and delegated DAG tasks. */\n\tworkState?: SessionWorkStateProjection;\n\t/**\n\t * Per-requirement worktree-sync state, present only for requirements whose `boundLaneId` matches\n\t * a `worktreeLaneStatus` entry supplied to the builder. Optional (like `openTaskSteps`) so every\n\t * pre-existing caller/test keeps compiling unchanged; omitted entirely (not an empty array) when\n\t * the builder was never given `worktreeLaneStatus`, since \"no data supplied\" and \"data supplied,\n\t * nothing bound\" are genuinely different states worth distinguishing.\n\t */\n\trequirementWorktreeStates?: readonly GoalRuntimeRequirementWorktreeState[];\n}\n\n/**\n * Branch-scoped: every resolver here reads from ONE source (the active branch), so the goal\n * state, evidence bundle, worker claims, learning decisions, and open task steps in the\n * returned snapshot are never a mix of the current branch and a sibling branch's history.\n */\nexport function buildGoalRuntimeSnapshot(args: {\n\tsessionManager: Pick<SessionManager, \"getLatestCustomEntryOnBranch\" | \"getBranch\">;\n\tsettings: GoalRuntimeSnapshotSettings;\n\t/**\n\t * Live lane records (queued/running/terminal), independent of branch scoping. Used ONLY to (a)\n\t * detect a worker in flight against the active goal's open requirement (\"waiting\" — see\n\t * `evaluateGoalContinuation`'s `inFlightGoalLaneIds`), and (b) surface this goal's cumulative\n\t * worker/subagent spend (advisory — see `GoalState.continuationWorkerSpendUsd`). Optional so\n\t * every pre-existing caller (hand-built snapshots, tests) that predates lane-awareness keeps\n\t * compiling and behaving byte-identically: omitting it disables both the \"waiting\" branch and the\n\t * worker-spend overlay, and never changes any OTHER continuation outcome.\n\t */\n\tlaneRecords?: readonly LaneRecord[];\n\t/**\n\t * Current time as an ISO-string factory, threaded into `evaluateGoalContinuation`'s never-hang\n\t * wait-timeout check (`now`/`maxWorkerWaitMs` — see there) alongside `maxWorkerWaitMs` below.\n\t * Defaults to the real wall clock. A factory (not a plain string) so a caller/test can inject a\n\t * fixed clock without freezing global `Date`.\n\t */\n\tnow?: () => string;\n\t/**\n\t * Maximum milliseconds a bound in-flight requirement may wait before the continuation escalates\n\t * to `worker_wait_timeout` instead of `\"waiting\"` forever (see `evaluateGoalContinuation`).\n\t * Defaults to `DEFAULT_GOAL_WORKER_WAIT_MS`.\n\t */\n\tmaxWorkerWaitMs?: number;\n\t/**\n\t * Live per-lane worktree-sync status, independent of branch scoping -- exactly like `laneRecords`,\n\t * this builder performs NO I/O of its own; the caller derives this array (e.g. from\n\t * `core/worktree-sync/git-engine.ts`'s live status) and supplies it ready-made. Used to (a) build\n\t * `requirementWorktreeStates` (per-requirement projection, matched via `boundLaneId`) and (b)\n\t * derive the `laneSyncConflictLaneKeys`/`syncRequiredLaneKeys` sets threaded into\n\t * `evaluateGoalContinuation`. Optional so every pre-existing caller (predating worktree-sync\n\t * awareness) keeps compiling and behaving byte-identically: omitting it disables both, and never\n\t * changes any OTHER continuation outcome.\n\t */\n\tworktreeLaneStatus?: readonly GoalRuntimeWorktreeLaneStatus[];\n\t/** Durable worker DAG projection, supplied only when the delegate capability has been loaded. */\n\ttaskRuntime?: TaskRuntimeProjection;\n}): GoalRuntimeSnapshot {\n\tconst branchEntries = getActiveSessionBranchEntries(args.sessionManager);\n\tlet goalState = getLatestGoalStateSnapshot(args.sessionManager);\n\tconst latestEvidenceBundle = getLatestEvidenceBundleSnapshot(branchEntries);\n\tconst workerClaims = getWorkerClaimSnapshots(branchEntries);\n\tconst learningDecisions = getLearningDecisionSnapshots(branchEntries);\n\n\t// Reuses the SAME branch-scoped primitive as goal-state resolution (getLatestCustomEntryOnBranch),\n\t// so the task-steps summary below can never leak a sibling branch's checklist either.\n\tconst taskStepsState = getLatestTaskStepsStateSnapshot(args.sessionManager);\n\tconst workState = projectSessionWorkState({ goalState, taskStepsState, taskRuntime: args.taskRuntime });\n\tconst openTaskSteps = workState.openTaskSteps;\n\n\tlet inFlightGoalLaneIds: ReadonlySet<string> | undefined;\n\tif (goalState && args.laneRecords) {\n\t\tconst goalId = goalState.goalId;\n\t\tconst inFlight = new Set<string>();\n\t\t// Live-derived, not durably persisted: the goal-state event log has no reducer branch that\n\t\t// writes `continuationWorkerSpendUsd` (see its doc comment on `GoalState`), so every read\n\t\t// re-sums THIS goal's own lane records instead of trusting a stale/zero persisted value.\n\t\t// `costUsd` is set today for in-process worker/research lane completions (LaneTracker.complete);\n\t\t// it is NOT yet set for tmux-worker completions (`ManagedLaneEvent` carries no cost claim), so\n\t\t// this sum is accurate for in-process lanes and a documented undercount for tmux workers until\n\t\t// `reportSpawnedUsage` threads a goalId/lane correlation through. Forward-compatible: the moment\n\t\t// tmux-worker costUsd is populated, this same sum picks it up with no further change here.\n\t\tlet workerSpendUsd = 0;\n\t\tfor (const record of args.laneRecords) {\n\t\t\tif (record.goalId !== goalId) continue;\n\t\t\tif (record.status === \"queued\" || record.status === \"running\") inFlight.add(record.laneId);\n\t\t\tworkerSpendUsd += record.costUsd ?? 0;\n\t\t}\n\t\tinFlightGoalLaneIds = inFlight;\n\t\tgoalState = { ...goalState, continuationWorkerSpendUsd: workerSpendUsd };\n\t}\n\n\t// Worktree-sync surfacing: (a) a per-requirement projection (matched via `boundLaneId`, purely for\n\t// snapshot consumers -- never read by `evaluateGoalContinuation` itself), and (b) the\n\t// `boundLaneId`-keyed sets `evaluateGoalContinuation` actually matches against\n\t// `Requirement.boundLaneId`, same id-space and matching pattern as `inFlightGoalLaneIds` above.\n\t// Disjoint by construction: a lane with `rebaseInProgress` feeds the conflict set only, never both.\n\tlet requirementWorktreeStates: GoalRuntimeRequirementWorktreeState[] | undefined;\n\tconst laneSyncConflictLaneKeys = new Set<string>();\n\tconst syncRequiredLaneKeys = new Set<string>();\n\tif (args.worktreeLaneStatus) {\n\t\tfor (const status of args.worktreeLaneStatus) {\n\t\t\tif (status.boundLaneId === undefined) continue;\n\t\t\tif (status.rebaseInProgress) laneSyncConflictLaneKeys.add(status.boundLaneId);\n\t\t\telse if (status.syncRequired) syncRequiredLaneKeys.add(status.boundLaneId);\n\t\t}\n\t\tif (goalState) {\n\t\t\tconst states: GoalRuntimeRequirementWorktreeState[] = [];\n\t\t\tfor (const requirement of goalState.requirements) {\n\t\t\t\tif (requirement.boundLaneId === undefined) continue;\n\t\t\t\tconst status = args.worktreeLaneStatus.find(\n\t\t\t\t\t(candidate) => candidate.boundLaneId === requirement.boundLaneId,\n\t\t\t\t);\n\t\t\t\tif (!status) continue;\n\t\t\t\tstates.push({\n\t\t\t\t\trequirementId: requirement.id,\n\t\t\t\t\tlaneKey: status.laneKey,\n\t\t\t\t\tfresh: status.fresh,\n\t\t\t\t\tstale: status.stale,\n\t\t\t\t\tsyncRequired: status.syncRequired,\n\t\t\t\t\trebaseInProgress: status.rebaseInProgress,\n\t\t\t\t});\n\t\t\t}\n\t\t\trequirementWorktreeStates = states;\n\t\t}\n\t}\n\n\tconst now = (args.now ?? (() => new Date().toISOString()))();\n\tconst maxWorkerWaitMs = args.maxWorkerWaitMs ?? DEFAULT_GOAL_WORKER_WAIT_MS;\n\tconst continuation = evaluateGoalContinuation({\n\t\tstate: goalState,\n\t\tsettings: { maxStallTurns: args.settings.maxStallTurns },\n\t\tinFlightGoalLaneIds,\n\t\tnow,\n\t\tmaxWorkerWaitMs,\n\t\tlaneSyncConflictLaneKeys: laneSyncConflictLaneKeys.size > 0 ? laneSyncConflictLaneKeys : undefined,\n\t\tsyncRequiredLaneKeys: syncRequiredLaneKeys.size > 0 ? syncRequiredLaneKeys : undefined,\n\t});\n\n\treturn {\n\t\tgoalState,\n\t\tlatestEvidenceBundle,\n\t\tworkerClaims,\n\t\tlearningDecisions,\n\t\tcontinuation,\n\t\topenTaskSteps,\n\t\tworkState,\n\t\t...(requirementWorktreeStates !== undefined ? { requirementWorktreeStates } : {}),\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"goal-runtime-snapshot.js","sourceRoot":"","sources":["../../../src/core/goals/goal-runtime-snapshot.ts"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f,wBAAwB,EAAE,wBAAwB,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,wBAAwB,CAAC,CAAC,CAAC,SAAS;QAClG,oBAAoB,EAAE,oBAAoB,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,SAAS;QACtF,GAAG,CAAC,mBAAmB,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,mBAAmB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAChE,CAAC,CAAC;IAEH,OAAO;QACN,SAAS;QACT,oBAAoB;QACpB,YAAY;QACZ,iBAAiB;QACjB,YAAY;QACZ,aAAa;QACb,SAAS;QACT,GAAG,CAAC,yBAAyB,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,yBAAyB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACjF,CAAC;AACH,CAAC","sourcesContent":["import type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { EvidenceBundle, LearningDecision, WorkerClaim } from \"../autonomy/contracts.ts\";\nimport type { LaneRecord } from \"../autonomy/lane-tracker.ts\";\nimport type { BackgroundToolTaskRef } from \"../background-tool-task-controller.ts\";\nimport { getWorkerClaimSnapshots } from \"../delegation/session-worker-claim.ts\";\nimport { getLearningDecisionSnapshots } from \"../learning/session-learning-decision.ts\";\nimport type { TaskRuntimeProjection } from \"../orchestration/task-runtime.ts\";\nimport { projectSessionWorkState, type SessionWorkStateProjection } from \"../orchestration/work-state-projection.ts\";\nimport { getLatestEvidenceBundleSnapshot } from \"../research/session-evidence-bundle.ts\";\nimport { getActiveSessionBranchEntries } from \"../session-snapshot.ts\";\nimport { getLatestTaskStepsStateSnapshot } from \"../tasks/session-task-state.ts\";\nimport type { OpenTaskStepProjection } from \"../tasks/task-projection.ts\";\nimport { evaluateGoalContinuation, type GoalContinuationDecision } from \"./goal-continuation-controller.ts\";\nimport { DEFAULT_GOAL_WORKER_WAIT_MS } from \"./goal-continuation-defaults.ts\";\nimport type { GoalState } from \"./goal-state.ts\";\nimport { getLatestGoalStateSnapshot } from \"./session-goal-state.ts\";\n\nexport interface GoalRuntimeSnapshotSettings {\n\tmaxStallTurns: number;\n}\n\n/**\n * A read-only projection of one OPEN (non-terminal) task_steps step, included in the goal\n * runtime snapshot purely for cross-visibility. This is NOT a shared state machine: the goal\n * loop never writes back to task state through this snapshot, and the task store stays the\n * single source of truth for its own steps.\n */\nexport type GoalRuntimeOpenTaskStep = OpenTaskStepProjection;\n\n/**\n * Live, per-worktree-sync-lane status for one lane bound to a dispatched worker, as the caller\n * (runtime-builder / whatever host process has live git-engine access) derives it. `boundLaneId` is\n * the host `LaneRecord.laneId` the lane's registration was correlated to\n * (`LaneRegistration.boundLaneId`, same id-space as `Requirement.boundLaneId`) -- `undefined` for a\n * lane never bound to a dispatch. `fresh`/`stale` mirror `LaneFacts`; `syncRequired` is the\n * staleness-propagation verdict (`WorktreeSyncPolicy`-derived); `rebaseInProgress` marks a sync that\n * stopped on conflicts (a rebase left in progress) -- see `core/worktree-sync/git-engine.ts`.\n */\nexport interface GoalRuntimeWorktreeLaneStatus {\n\tlaneKey: string;\n\tboundLaneId?: string;\n\tfresh: boolean;\n\tstale: boolean;\n\tsyncRequired: boolean;\n\trebaseInProgress: boolean;\n}\n\n/**\n * Per-requirement projection of {@link GoalRuntimeWorktreeLaneStatus}, joined via\n * `requirement.boundLaneId === status.boundLaneId` -- read-only cross-visibility for snapshot\n * consumers (e.g. a future continuation-prompt render), mirroring `openTaskSteps`'s role. This is\n * NOT what feeds `evaluateGoalContinuation` (that reads the raw `boundLaneId`-keyed sets directly);\n * it exists purely so a requirement's worktree state is visible without re-deriving the join.\n */\nexport interface GoalRuntimeRequirementWorktreeState {\n\trequirementId: string;\n\tlaneKey: string;\n\tfresh: boolean;\n\tstale: boolean;\n\tsyncRequired: boolean;\n\trebaseInProgress: boolean;\n}\n\nexport interface GoalRuntimeSnapshot {\n\tgoalState?: GoalState;\n\tlatestEvidenceBundle?: EvidenceBundle;\n\tworkerClaims: readonly WorkerClaim[];\n\tlearningDecisions: readonly LearningDecision[];\n\tcontinuation: GoalContinuationDecision;\n\t/**\n\t * Open (non-terminal) task_steps steps on the active branch, latest-wins. Read-only.\n\t * Optional (like `goalState`/`latestEvidenceBundle`) so hand-built snapshots in existing\n\t * tests/call sites that predate this field keep compiling unchanged; `buildGoalRuntimeSnapshot`\n\t * itself always populates a concrete array (possibly empty).\n\t */\n\topenTaskSteps?: readonly GoalRuntimeOpenTaskStep[];\n\t/** Canonical read model joining requirements, foreground steps, and delegated DAG tasks. */\n\tworkState?: SessionWorkStateProjection;\n\t/**\n\t * Per-requirement worktree-sync state, present only for requirements whose `boundLaneId` matches\n\t * a `worktreeLaneStatus` entry supplied to the builder. Optional (like `openTaskSteps`) so every\n\t * pre-existing caller/test keeps compiling unchanged; omitted entirely (not an empty array) when\n\t * the builder was never given `worktreeLaneStatus`, since \"no data supplied\" and \"data supplied,\n\t * nothing bound\" are genuinely different states worth distinguishing.\n\t */\n\trequirementWorktreeStates?: readonly GoalRuntimeRequirementWorktreeState[];\n}\n\n/**\n * Branch-scoped: every resolver here reads from ONE source (the active branch), so the goal\n * state, evidence bundle, worker claims, learning decisions, and open task steps in the\n * returned snapshot are never a mix of the current branch and a sibling branch's history.\n */\nexport function buildGoalRuntimeSnapshot(args: {\n\tsessionManager: Pick<SessionManager, \"getLatestCustomEntryOnBranch\" | \"getBranch\">;\n\tsettings: GoalRuntimeSnapshotSettings;\n\t/**\n\t * Live lane records (queued/running/terminal), independent of branch scoping. Used ONLY to (a)\n\t * detect a worker in flight against the active goal's open requirement (\"waiting\" — see\n\t * `evaluateGoalContinuation`'s `inFlightGoalLaneIds`), and (b) surface this goal's cumulative\n\t * worker/subagent spend (advisory — see `GoalState.continuationWorkerSpendUsd`). Optional so\n\t * every pre-existing caller (hand-built snapshots, tests) that predates lane-awareness keeps\n\t * compiling and behaving byte-identically: omitting it disables both the \"waiting\" branch and the\n\t * worker-spend overlay, and never changes any OTHER continuation outcome.\n\t */\n\tlaneRecords?: readonly LaneRecord[];\n\t/**\n\t * Current time as an ISO-string factory, threaded into `evaluateGoalContinuation`'s never-hang\n\t * wait-timeout check (`now`/`maxWorkerWaitMs` — see there) alongside `maxWorkerWaitMs` below.\n\t * Defaults to the real wall clock. A factory (not a plain string) so a caller/test can inject a\n\t * fixed clock without freezing global `Date`.\n\t */\n\tnow?: () => string;\n\t/**\n\t * Maximum milliseconds a bound in-flight requirement may wait before the continuation escalates\n\t * to `worker_wait_timeout` instead of `\"waiting\"` forever (see `evaluateGoalContinuation`).\n\t * Defaults to `DEFAULT_GOAL_WORKER_WAIT_MS`.\n\t */\n\tmaxWorkerWaitMs?: number;\n\t/**\n\t * Live per-lane worktree-sync status, independent of branch scoping -- exactly like `laneRecords`,\n\t * this builder performs NO I/O of its own; the caller derives this array (e.g. from\n\t * `core/worktree-sync/git-engine.ts`'s live status) and supplies it ready-made. Used to (a) build\n\t * `requirementWorktreeStates` (per-requirement projection, matched via `boundLaneId`) and (b)\n\t * derive the `laneSyncConflictLaneKeys`/`syncRequiredLaneKeys` sets threaded into\n\t * `evaluateGoalContinuation`. Optional so every pre-existing caller (predating worktree-sync\n\t * awareness) keeps compiling and behaving byte-identically: omitting it disables both, and never\n\t * changes any OTHER continuation outcome.\n\t */\n\tworktreeLaneStatus?: readonly GoalRuntimeWorktreeLaneStatus[];\n\t/** Durable worker DAG projection, supplied only when the delegate capability has been loaded. */\n\ttaskRuntime?: TaskRuntimeProjection;\n\t/** Live background tool_task records for this session. */\n\tbackgroundToolTasks?: readonly BackgroundToolTaskRef[];\n}): GoalRuntimeSnapshot {\n\tconst branchEntries = getActiveSessionBranchEntries(args.sessionManager);\n\tlet goalState = getLatestGoalStateSnapshot(args.sessionManager);\n\tconst latestEvidenceBundle = getLatestEvidenceBundleSnapshot(branchEntries);\n\tconst workerClaims = getWorkerClaimSnapshots(branchEntries);\n\tconst learningDecisions = getLearningDecisionSnapshots(branchEntries);\n\n\t// Reuses the SAME branch-scoped primitive as goal-state resolution (getLatestCustomEntryOnBranch),\n\t// so the task-steps summary below can never leak a sibling branch's checklist either.\n\tconst taskStepsState = getLatestTaskStepsStateSnapshot(args.sessionManager);\n\tconst workState = projectSessionWorkState({\n\t\tgoalState,\n\t\ttaskStepsState,\n\t\ttaskRuntime: args.taskRuntime,\n\t\tbackgroundToolTasks: args.backgroundToolTasks,\n\t});\n\tconst openTaskSteps = workState.openTaskSteps;\n\n\tlet inFlightGoalLaneIds: ReadonlySet<string> | undefined;\n\tif (goalState && args.laneRecords) {\n\t\tconst goalId = goalState.goalId;\n\t\tconst inFlight = new Set<string>();\n\t\t// Live-derived, not durably persisted: the goal-state event log has no reducer branch that\n\t\t// writes `continuationWorkerSpendUsd` (see its doc comment on `GoalState`), so every read\n\t\t// re-sums THIS goal's own lane records instead of trusting a stale/zero persisted value.\n\t\t// `costUsd` is set today for in-process worker/research lane completions (LaneTracker.complete);\n\t\t// it is NOT yet set for tmux-worker completions (`ManagedLaneEvent` carries no cost claim), so\n\t\t// this sum is accurate for in-process lanes and a documented undercount for tmux workers until\n\t\t// `reportSpawnedUsage` threads a goalId/lane correlation through. Forward-compatible: the moment\n\t\t// tmux-worker costUsd is populated, this same sum picks it up with no further change here.\n\t\tlet workerSpendUsd = 0;\n\t\tfor (const record of args.laneRecords) {\n\t\t\tif (record.goalId !== goalId) continue;\n\t\t\tif (record.status === \"queued\" || record.status === \"running\") inFlight.add(record.laneId);\n\t\t\tworkerSpendUsd += record.costUsd ?? 0;\n\t\t}\n\t\tinFlightGoalLaneIds = inFlight;\n\t\tgoalState = { ...goalState, continuationWorkerSpendUsd: workerSpendUsd };\n\t}\n\n\t// Worktree-sync surfacing: (a) a per-requirement projection (matched via `boundLaneId`, purely for\n\t// snapshot consumers -- never read by `evaluateGoalContinuation` itself), and (b) the\n\t// `boundLaneId`-keyed sets `evaluateGoalContinuation` actually matches against\n\t// `Requirement.boundLaneId`, same id-space and matching pattern as `inFlightGoalLaneIds` above.\n\t// Disjoint by construction: a lane with `rebaseInProgress` feeds the conflict set only, never both.\n\tlet requirementWorktreeStates: GoalRuntimeRequirementWorktreeState[] | undefined;\n\tconst laneSyncConflictLaneKeys = new Set<string>();\n\tconst syncRequiredLaneKeys = new Set<string>();\n\tif (args.worktreeLaneStatus) {\n\t\tfor (const status of args.worktreeLaneStatus) {\n\t\t\tif (status.boundLaneId === undefined) continue;\n\t\t\tif (status.rebaseInProgress) laneSyncConflictLaneKeys.add(status.boundLaneId);\n\t\t\telse if (status.syncRequired) syncRequiredLaneKeys.add(status.boundLaneId);\n\t\t}\n\t\tif (goalState) {\n\t\t\tconst states: GoalRuntimeRequirementWorktreeState[] = [];\n\t\t\tfor (const requirement of goalState.requirements) {\n\t\t\t\tif (requirement.boundLaneId === undefined) continue;\n\t\t\t\tconst status = args.worktreeLaneStatus.find(\n\t\t\t\t\t(candidate) => candidate.boundLaneId === requirement.boundLaneId,\n\t\t\t\t);\n\t\t\t\tif (!status) continue;\n\t\t\t\tstates.push({\n\t\t\t\t\trequirementId: requirement.id,\n\t\t\t\t\tlaneKey: status.laneKey,\n\t\t\t\t\tfresh: status.fresh,\n\t\t\t\t\tstale: status.stale,\n\t\t\t\t\tsyncRequired: status.syncRequired,\n\t\t\t\t\trebaseInProgress: status.rebaseInProgress,\n\t\t\t\t});\n\t\t\t}\n\t\t\trequirementWorktreeStates = states;\n\t\t}\n\t}\n\n\tconst now = (args.now ?? (() => new Date().toISOString()))();\n\tconst maxWorkerWaitMs = args.maxWorkerWaitMs ?? DEFAULT_GOAL_WORKER_WAIT_MS;\n\tconst inFlightToolTaskIds = new Set(workState.runningToolTaskIds);\n\n\tconst continuation = evaluateGoalContinuation({\n\t\tstate: goalState,\n\t\tsettings: { maxStallTurns: args.settings.maxStallTurns },\n\t\tinFlightGoalLaneIds,\n\t\tnow,\n\t\tmaxWorkerWaitMs,\n\t\tlaneSyncConflictLaneKeys: laneSyncConflictLaneKeys.size > 0 ? laneSyncConflictLaneKeys : undefined,\n\t\tsyncRequiredLaneKeys: syncRequiredLaneKeys.size > 0 ? syncRequiredLaneKeys : undefined,\n\t\t...(inFlightToolTaskIds.size > 0 ? { inFlightToolTaskIds } : {}),\n\t});\n\n\treturn {\n\t\tgoalState,\n\t\tlatestEvidenceBundle,\n\t\tworkerClaims,\n\t\tlearningDecisions,\n\t\tcontinuation,\n\t\topenTaskSteps,\n\t\tworkState,\n\t\t...(requirementWorktreeStates !== undefined ? { requirementWorktreeStates } : {}),\n\t};\n}\n"]}
|
|
@@ -2,6 +2,7 @@ import type { SessionManager } from "@caupulican/pi-agent-core/session";
|
|
|
2
2
|
import type { AssistantMessage } from "@caupulican/pi-ai";
|
|
3
3
|
import type { GoalContinuationLoopOptions, GoalContinuationLoopResult, GoalContinuationOnceOptions, GoalContinuationOnceResult, PromptOptions } from "../agent-session-contracts.ts";
|
|
4
4
|
import type { LaneRecord } from "../autonomy/lane-tracker.ts";
|
|
5
|
+
import type { BackgroundToolTaskRef } from "../background-tool-task-controller.ts";
|
|
5
6
|
import type { TaskRuntimeProjection } from "../orchestration/task-runtime.ts";
|
|
6
7
|
import { type GoalStateRevision } from "./goal-lifecycle.ts";
|
|
7
8
|
import { type GoalRuntimeSnapshot, type GoalRuntimeSnapshotSettings } from "./goal-runtime-snapshot.ts";
|
|
@@ -12,6 +13,7 @@ export interface GoalSessionControllerDeps {
|
|
|
12
13
|
getModelProvider(): string | undefined;
|
|
13
14
|
getLaneRecords(): readonly LaneRecord[];
|
|
14
15
|
getTaskRuntimeSnapshot(): TaskRuntimeProjection | undefined;
|
|
16
|
+
getBackgroundToolTasks(): readonly BackgroundToolTaskRef[];
|
|
15
17
|
synchronizeGoalState(state: GoalState): void;
|
|
16
18
|
scheduleGoalAutoContinueFromIdle(): void;
|
|
17
19
|
prompt(text: string, options?: PromptOptions): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"goal-session-controller.d.ts","sourceRoot":"","sources":["../../../src/core/goals/goal-session-controller.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mCAAmC,CAAC;AACxE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,KAAK,EACX,2BAA2B,EAC3B,0BAA0B,EAC1B,2BAA2B,EAC3B,0BAA0B,EAC1B,aAAa,EACb,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;
|
|
1
|
+
{"version":3,"file":"goal-session-controller.d.ts","sourceRoot":"","sources":["../../../src/core/goals/goal-session-controller.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mCAAmC,CAAC;AACxE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,KAAK,EACX,2BAA2B,EAC3B,0BAA0B,EAC1B,2BAA2B,EAC3B,0BAA0B,EAC1B,aAAa,EACb,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAGnF,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAE9E,OAAO,EAAE,KAAK,iBAAiB,EAA4C,MAAM,qBAAqB,CAAC;AACvG,OAAO,EAEN,KAAK,mBAAmB,EACxB,KAAK,2BAA2B,EAChC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAkB,KAAK,SAAS,EAAiD,MAAM,iBAAiB,CAAC;AAEhH,OAAO,EAAE,KAAK,0BAA0B,EAAyB,MAAM,4BAA4B,CAAC;AAOpG,MAAM,WAAW,yBAAyB;IACzC,iBAAiB,IAAI,cAAc,CAAC;IACpC,gBAAgB,IAAI,MAAM,GAAG,SAAS,CAAC;IACvC,cAAc,IAAI,SAAS,U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AAQ,EAAE,2BAA2B,GAAG,mBAAmB,CAQ7E;IAED,YAAY,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAEtF;IAED,YAAY,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAEtF;IAED,kBAAkB,IAAI,IAAI,CAEzB;IAED,OAAO,CAAC,yBAAyB;IASjC,OAAO,CAAC,iBAAiB;IAIzB,OAAO,CAAC,cAAc;CAOtB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"goal-session-controller.js","sourceRoot":"","sources":["../../../src/core/goals/goal-session-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,uCAAuC,CAAC;AAWxE,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,wCAAwC,CAAC;AAExE,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EAA0B,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACvG,OAAO,EACN,wBAAwB,GAGxB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,cAAc,EAAkB,qBAAqB,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAChH,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAmC,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACpG,OAAO,EACN,yBAAyB,EACzB,uBAAuB,EACvB,0BAA0B,GAC1B,MAAM,yBAAyB,CAAC;AAkBjC;;;;;;;;;;GAUG;AACH,MAAM,kCAAkC,GAAG,KAAK,CAAC;AAEjD,MAAM,wBAAwB,GAAkB,MAAM,CAAC,oBAAoB,CAAC,CAAC;AAsB7E;;;GAGG;AACH,MAAM,OAAO,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AAC;QAC9B,MAAM,OAAO,GAAG,kBAAkB,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC;QACxF,IAAI,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,KAAK;YAAE,OAAO,KAAK,CAAC;QACxC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,KAAK,EAAE,oBAAoB,CAAC,KAAK,CAAC,CAAC,CAAC;QAC3D,OAAO,IAAI,CAAC;IACb,CAAC;CACD","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { classifyFailure } from \"@caupulican/pi-agent-core/reliability\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/session\";\nimport type { AssistantMessage } from \"@caupulican/pi-ai\";\nimport type {\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tGoalContinuationOnceOptions,\n\tGoalContinuationOnceResult,\n\tPromptOptions,\n} from \"../agent-session-contracts.ts\";\nimport type { LaneRecord } from \"../autonomy/lane-tracker.ts\";\nimport { GoalLoopController } from \"../goal-loop-controller.ts\";\nimport { budgetedTokens } from \"../orchestration/capability-gateway.ts\";\nimport type { TaskRuntimeProjection } from \"../orchestration/task-runtime.ts\";\nimport { GoalBudgetExhaustedError } from \"./goal-execution-errors.ts\";\nimport { type GoalStateRevision, getGoalStateRevision, stopGoalFromSystem } from \"./goal-lifecycle.ts\";\nimport {\n\tbuildGoalRuntimeSnapshot,\n\ttype GoalRuntimeSnapshot,\n\ttype GoalRuntimeSnapshotSettings,\n} from \"./goal-runtime-snapshot.ts\";\nimport { applyGoalEvent, type GoalState, isGoalExecutionActive, isGoalUnfinishedStatus } from \"./goal-state.ts\";\nimport { applyGoalAction } from \"./goal-tool-core.ts\";\nimport { type ExplicitGoalStartAuthority, parseExplicitChatGoal } from \"./natural-language-goal.ts\";\nimport {\n\tappendGoalClearedSnapshot,\n\tappendGoalStateSnapshot,\n\tgetLatestGoalStateSnapshot,\n} from \"./session-goal-state.ts\";\n\nexport interface GoalSessionControllerDeps {\n\tgetSessionManager(): SessionManager;\n\tgetModelProvider(): string | undefined;\n\tgetLaneRecords(): readonly LaneRecord[];\n\tgetTaskRuntimeSnapshot(): TaskRuntimeProjection | undefined;\n\tsynchronizeGoalState(state: GoalState): void;\n\tscheduleGoalAutoContinueFromIdle(): void;\n\tprompt(text: string, options?: PromptOptions): Promise<void>;\n\temitWarning(message: string): void;\n}\n\nexport type ChatGoalAdmission =\n\t| { status: \"not_explicit\" }\n\t| { status: \"started\"; state: GoalState }\n\t| { status: \"unfinished_goal_exists\"; state: GoalState };\n\n/**\n * Smallest remaining goal budget worth handing to the provider as one more request's OUTPUT cap.\n * `admitProviderRequest` returns the goal's remaining TOTAL budget (input+output, cache-weighted) as\n * that cap — correct only because it also narrows further downstream against the model's real output\n * limit. When remaining drops below this floor (e.g. 200k budget, 199.4k used → 600 remaining), handing\n * 600 to the provider as maxTokens produces a request that pays the FULL input cost of the turn only to\n * get cut off mid-generation (`stopReason: \"length\"`) — a doomed, wasted turn. Below the floor, stop\n * the goal cleanly BEFORE sending instead of gambling on a truncated one. Above it, the remaining-total\n * value is a generous (imprecise but safe) protective ceiling — a modest final-turn overrun is\n * acceptable; a truncated turn is not.\n */\nconst MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS = 1_000;\n\nconst goalExecutionLeaseMarker: unique symbol = Symbol(\"goalExecutionLease\");\n\n/** Identity-bound attribution for one goal-owned foreground execution. */\nexport interface GoalExecutionLease {\n\treadonly goalId?: string;\n\treadonly [goalExecutionLeaseMarker]: true;\n}\n\ninterface MutableGoalExecutionLease extends GoalExecutionLease {\n\tgoalId?: string;\n\tadoptNewGoal: boolean;\n\tadoptionBaselineGoalId?: string;\n\tprovisionalTokenBudget?: number;\n\tpendingTokens: number;\n\tpendingSpendUsd: number;\n\t/** Set once this lease has admitted a provider request while its goal was still active. Lets a\n\t * later admission on the SAME still-held lease recognize \"the goal ended mid-turn\" (drain the\n\t * in-flight turn's wrap-up response) instead of \"a new turn is starting against a dead goal\"\n\t * (which stays denied). */\n\tadmittedWhileActive: boolean;\n}\n\n/**\n * Owns durable goal state, exact continuation accounting, and the raw continuation loop. The\n * AgentSession facade supplies process collaborators but no longer implements goal lifecycle rules.\n */\nexport class GoalSessionController {\n\tprivate readonly deps: GoalSessionControllerDeps;\n\tprivate readonly loop: GoalLoopController;\n\tprivate executionLease: MutableGoalExecutionLease | undefined;\n\tprivate startAuthority: ExplicitGoalStartAuthority | undefined;\n\n\tconstructor(deps: GoalSessionControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis.loop = new GoalLoopController({\n\t\t\tgetGoalRuntimeSnapshot: (settings) => this.getRuntimeSnapshot(settings),\n\t\t\tprompt: (text, options) => this.deps.prompt(text, options),\n\t\t\trecordGoalContinuationPass: (pass) => this.recordContinuationPass(pass),\n\t\t\trecordGoalContinuationFailure: (error) => this.recordContinuationFailure(error),\n\t\t\tmarkGoalBudgetLimited: (reason) => this.markBudgetLimited(reason),\n\t\t});\n\t}\n\n\tsaveState(state: GoalState, expected?: GoalStateRevision): string {\n\t\tconst current = this.getState();\n\t\tif (\n\t\t\texpected &&\n\t\t\t(!current || current.goalId !== expected.goalId || (current.revision ?? 0) !== expected.revision)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`Goal state changed concurrently; expected ${expected.goalId}@${expected.revision}, found ${current ? `${current.goalId}@${current.revision ?? 0}` : \"none\"}. Retry against the latest state.`,\n\t\t\t);\n\t\t}\n\t\tconst entryId = appendGoalStateSnapshot(this.deps.getSessionManager(), state, current);\n\t\ttry {\n\t\t\tthis.deps.synchronizeGoalState(state);\n\t\t} catch (error) {\n\t\t\tthis.deps.emitWarning(\n\t\t\t\t`Goal state persisted but durable worker reconciliation failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\treturn entryId;\n\t}\n\n\tclearState(state: GoalState, now: string): string {\n\t\tconst current = this.getState();\n\t\tconst expected = getGoalStateRevision(state);\n\t\tif (!current || current.goalId !== expected.goalId || (current.revision ?? 0) !== expected.revision) {\n\t\t\tthrow new Error(\"Goal state changed concurrently; retry clear against the latest state.\");\n\t\t}\n\t\tif (state.status !== \"completed\" && state.status !== \"cancelled\") {\n\t\t\tthis.deps.synchronizeGoalState(applyGoalEvent(state, { type: \"cancel_goal\", now }));\n\t\t}\n\t\treturn appendGoalClearedSnapshot(this.deps.getSessionManager(), state, now);\n\t}\n\n\tgetState(): GoalState | undefined {\n\t\treturn getLatestGoalStateSnapshot(this.deps.getSessionManager());\n\t}\n\n\t/**\n\t * Promote high-confidence natural-language persistence into the same durable state written by the\n\t * goal tool. This is intentionally narrower than task detection: ordinary work never starts a\n\t * goal, and an unfinished goal is never replaced implicitly.\n\t */\n\tadmitExplicitChatGoal(text: string, now = new Date().toISOString()): ChatGoalAdmission {\n\t\tconst parsed = parseExplicitChatGoal(text);\n\t\tif (!parsed) return { status: \"not_explicit\" };\n\t\tconst current = this.getState();\n\t\tif (current && isGoalUnfinishedStatus(current.status)) {\n\t\t\treturn { status: \"unfinished_goal_exists\", state: current };\n\t\t}\n\t\tconst digest = createHash(\"sha256\")\n\t\t\t.update(`${now}\\0${current?.goalId ?? \"none\"}\\0${parsed.objective}`)\n\t\t\t.digest(\"hex\")\n\t\t\t.slice(0, 20);\n\t\tconst result = applyGoalAction(\n\t\t\tcurrent,\n\t\t\t{\n\t\t\t\taction: \"start\",\n\t\t\t\tgoalId: `chat-${digest}`,\n\t\t\t\tuserGoal: parsed.objective,\n\t\t\t\ttokenBudget: parsed.tokenBudget,\n\t\t\t},\n\t\t\tnow,\n\t\t);\n\t\tif (!result.ok) throw new Error(result.error);\n\t\tthis.saveState(result.state, current ? getGoalStateRevision(current) : undefined);\n\t\treturn { status: \"started\", state: result.state };\n\t}\n\n\t/** Attribute turn/wall-clock telemetry after usage has already been charged per response. */\n\trecordContinuationPass(pass: { turns: number; wallClockMs: number }): void {\n\t\tconst state = this.getState();\n\t\tif (!state) return;\n\t\tconst updated = applyGoalEvent(state, {\n\t\t\ttype: \"record_continuation_budget\",\n\t\t\tturns: pass.turns,\n\t\t\twallClockMs: pass.wallClockMs,\n\t\t\ttokens: 0,\n\t\t\tspendUsd: 0,\n\t\t\tnow: new Date().toISOString(),\n\t\t});\n\t\tthis.saveState(updated, getGoalStateRevision(state));\n\t}\n\n\t/** Begin one foreground execution whose provider usage belongs to the specified active goal. */\n\tbeginExecution(\n\t\tgoalId: string | undefined,\n\t\toptions: { adoptNewGoal?: boolean; provisionalTokenBudget?: number } = {},\n\t): GoalExecutionLease | undefined {\n\t\tif (!goalId && !options.adoptNewGoal) return undefined;\n\t\tif (this.executionLease) throw new Error(\"Goal execution attribution is already active\");\n\t\tconst state = this.getState();\n\t\tif (goalId && (!state || state.goalId !== goalId || !isGoalExecutionActive(state.status))) return undefined;\n\t\tconst lease: MutableGoalExecutionLease = {\n\t\t\t...(goalId ? { goalId } : {}),\n\t\t\t[goalExecutionLeaseMarker]: true,\n\t\t\tadoptNewGoal: options.adoptNewGoal === true,\n\t\t\t...(options.adoptNewGoal && state ? { adoptionBaselineGoalId: state.goalId } : {}),\n\t\t\t...(options.provisionalTokenBudget !== undefined\n\t\t\t\t? { provisionalTokenBudget: options.provisionalTokenBudget }\n\t\t\t\t: {}),\n\t\t\tpendingTokens: 0,\n\t\t\tpendingSpendUsd: 0,\n\t\t\tadmittedWhileActive: false,\n\t\t};\n\t\tthis.executionLease = lease;\n\t\treturn lease;\n\t}\n\n\tendExecution(lease: GoalExecutionLease | undefined): void {\n\t\tif (!lease) return;\n\t\tif (this.executionLease !== lease) throw new Error(\"Cannot end goal execution attribution owned by another run\");\n\t\tthis.flushPendingExecutionUsage(this.executionLease);\n\t\tthis.executionLease = undefined;\n\t}\n\n\t/** Charge one observed assistant response exactly once, including routed responses buffered from persistence. */\n\trecordExecutionUsage(message: AssistantMessage): void {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return;\n\t\tconst tokens = budgetedTokens({\n\t\t\tinputTokens: Math.max(0, message.usage.input),\n\t\t\toutputTokens: Math.max(0, message.usage.output),\n\t\t\tcacheReadTokens: Math.max(0, message.usage.cacheRead),\n\t\t\tcacheWriteTokens: Math.max(0, message.usage.cacheWrite),\n\t\t\ttotalTokens: Math.max(0, message.usage.totalTokens),\n\t\t});\n\t\tconst spendUsd = Math.max(0, message.usage.cost.total);\n\t\tif (tokens === 0 && spendUsd === 0) return;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state) {\n\t\t\tlease.pendingTokens += tokens;\n\t\t\tlease.pendingSpendUsd += spendUsd;\n\t\t\treturn;\n\t\t}\n\t\tthis.chargeExecutionUsage(lease, state, tokens, spendUsd);\n\t}\n\n\tprivate chargeExecutionUsage(\n\t\tlease: MutableGoalExecutionLease,\n\t\tstate: GoalState,\n\t\ttokens: number,\n\t\tspendUsd: number,\n\t): void {\n\t\tconst updated = applyGoalEvent(state, {\n\t\t\ttype: \"record_continuation_budget\",\n\t\t\tturns: 0,\n\t\t\twallClockMs: 0,\n\t\t\ttokens,\n\t\t\tspendUsd,\n\t\t\tnow: new Date().toISOString(),\n\t\t});\n\t\tthis.saveState(updated, getGoalStateRevision(state));\n\t\tlease.pendingTokens = 0;\n\t\tlease.pendingSpendUsd = 0;\n\t\tif (\n\t\t\tisGoalExecutionActive(updated.status) &&\n\t\t\tupdated.tokenBudget !== undefined &&\n\t\t\t(updated.tokensUsed ?? 0) >= updated.tokenBudget\n\t\t) {\n\t\t\tthis.markBudgetLimited(\n\t\t\t\t`token budget exhausted (${updated.tokensUsed ?? 0}/${updated.tokenBudget}) during goal execution`,\n\t\t\t);\n\t\t}\n\t}\n\n\tmarkProtocolFailureBlocked(errorMessage: string): boolean {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return false;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state || !isGoalExecutionActive(state.status)) return false;\n\t\tconst stopped = stopGoalFromSystem(\n\t\t\tstate,\n\t\t\t{ status: \"blocked\", reason: errorMessage.slice(0, 500) },\n\t\t\tnew Date().toISOString(),\n\t\t);\n\t\tif (!stopped.ok) return false;\n\t\tthis.saveState(stopped.state, getGoalStateRevision(state));\n\t\treturn true;\n\t}\n\n\tsetStartAuthority(authority: ExplicitGoalStartAuthority | undefined): void {\n\t\tthis.startAuthority = authority;\n\t}\n\n\tauthorizeStartFromTool(input: { tokenBudget?: number }): string | undefined {\n\t\tconst authority = this.startAuthority;\n\t\tif (!authority) return \"goal start requires explicit owner authorization in the current prompt.\";\n\t\tif (authority.tokenBudget === undefined && input.tokenBudget !== undefined) {\n\t\t\treturn \"tokenBudget requires an exact numeric token ceiling in the current owner prompt.\";\n\t\t}\n\t\tif (authority.tokenBudget !== undefined && input.tokenBudget !== authority.tokenBudget) {\n\t\t\treturn `tokenBudget must equal the owner-requested ceiling ${authority.tokenBudget}.`;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * True once the currently held execution lease's goal has crossed into `budget_limited` — set\n\t * synchronously by `chargeExecutionUsage` as soon as a just-charged response crosses the ceiling.\n\t * Wired to the agent's `shouldStopAfterTurn` hook so a mid-turn budget stop ends the loop\n\t * gracefully BEFORE the next provider request is even planned, instead of only being caught by\n\t * `admitProviderRequest`'s throw — which still exists as the backstop for a fresh turn or an\n\t * external admission starting against an already budget_limited goal, but would otherwise also\n\t * fire for a request this same lease was already mid-flight for, surfacing a synthetic error\n\t * message where a clean turn end belongs.\n\t */\n\thasExecutionLeaseCrossedBudgetLimit(): boolean {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return false;\n\t\treturn this.resolveExecutionState(lease)?.status === \"budget_limited\";\n\t}\n\n\t/** Reserve only remaining output capacity; actual provider usage is charged on response. */\n\tadmitProviderRequest(): number | undefined {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return undefined;\n\t\tthis.flushPendingExecutionUsage(lease);\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (state?.status === \"budget_limited\") {\n\t\t\tthrow new GoalBudgetExhaustedError(`goal_token_budget_exhausted: ${state.blockedReason ?? lease.goalId}`);\n\t\t}\n\t\tif (state && !isGoalExecutionActive(state.status)) {\n\t\t\tif (!lease.admittedWhileActive) {\n\t\t\t\t// A fresh turn/continuation is being started against a goal that is already done —\n\t\t\t\t// keep this denied so a dead goal cannot restart itself.\n\t\t\t\tthrow new Error(`goal_execution_not_active: ${state.goalId} is ${state.status}`);\n\t\t\t}\n\t\t\t// This lease already admitted at least one request while the goal was active, so the\n\t\t\t// goal ended mid-turn (e.g. the model itself just called `goal complete`/`block`). Let\n\t\t\t// the already-in-flight turn drain to its closing response instead of throwing an error\n\t\t\t// at the user right after a successful stop.\n\t\t\treturn undefined;\n\t\t}\n\t\tif (!state && lease.goalId !== undefined) {\n\t\t\tthrow new Error(`goal_execution_not_active: ${lease.goalId} no longer exists`);\n\t\t}\n\t\tlease.admittedWhileActive = true;\n\t\tconst tokenBudget = state?.tokenBudget ?? lease.provisionalTokenBudget;\n\t\tif (tokenBudget === undefined) return undefined;\n\t\tconst tokensUsed = state?.tokensUsed ?? lease.pendingTokens;\n\t\tconst remaining = Math.max(0, tokenBudget - tokensUsed);\n\t\tif (remaining < MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS) {\n\t\t\t// Below the floor, remaining is too small to hand to the provider as an output cap without\n\t\t\t// dooming the turn to a mid-generation truncation that still burns the full input cost.\n\t\t\t// Stop cleanly now instead of sending a request that cannot possibly complete.\n\t\t\tif (state) {\n\t\t\t\tthis.markBudgetLimited(\n\t\t\t\t\t`token budget nearly exhausted (${tokensUsed}/${tokenBudget}, ${remaining} remaining is below the ` +\n\t\t\t\t\t\t`${MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS}-token minimum viable turn) before provider request`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new GoalBudgetExhaustedError(\n\t\t\t\t`goal_token_budget_exhausted: ${remaining} tokens remain, below the ${MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS}-token minimum viable turn`,\n\t\t\t);\n\t\t}\n\t\treturn remaining;\n\t}\n\n\tprivate resolveExecutionState(lease: MutableGoalExecutionLease): GoalState | undefined {\n\t\tconst state = this.getState();\n\t\tif (!state) return undefined;\n\t\tif (lease.goalId === state.goalId) return state;\n\t\tif (lease.goalId !== undefined || !lease.adoptNewGoal) return undefined;\n\t\tif (lease.adoptionBaselineGoalId === state.goalId) return undefined;\n\t\tlease.goalId = state.goalId;\n\t\treturn state;\n\t}\n\n\tprivate flushPendingExecutionUsage(lease: MutableGoalExecutionLease): void {\n\t\tif (lease.pendingTokens === 0 && lease.pendingSpendUsd === 0) return;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state) {\n\t\t\t// A speculative adopt-new-goal lease (lease.goalId still undefined) that never actually\n\t\t\t// adopted a goal this turn has nowhere to attribute usage — that is normal, not a loss.\n\t\t\t// A lease that WAS bound to a real goal but can no longer resolve it is a genuine loss of\n\t\t\t// buffered spend; fail loudly instead of silently discarding it (matches the cursor-based\n\t\t\t// accounting this replaced, which stopped the goal on `goal_usage_cursor_lost`).\n\t\t\tif (lease.goalId !== undefined) {\n\t\t\t\tthis.deps.emitWarning(\n\t\t\t\t\t`Goal usage cursor is no longer resolvable for '${lease.goalId}'; ${lease.pendingTokens} pending tokens and $${lease.pendingSpendUsd.toFixed(6)} pending spend could not be attributed and were dropped.`,\n\t\t\t\t);\n\t\t\t\tthis.recordContinuationFailure(new Error(\"goal_usage_cursor_lost\"));\n\t\t\t}\n\t\t\tlease.pendingTokens = 0;\n\t\t\tlease.pendingSpendUsd = 0;\n\t\t\treturn;\n\t\t}\n\t\tthis.chargeExecutionUsage(lease, state, lease.pendingTokens, lease.pendingSpendUsd);\n\t}\n\n\tmarkToolUnavailable(): void {\n\t\tthis.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t\"goal_tool_unavailable: the active capability surface cannot update durable goal state\",\n\t\t);\n\t}\n\n\tmarkRunawayBlocked(info: { signature: string; repeats: number }): boolean {\n\t\treturn this.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t`runaway_tool_loop: repeated tool-call signature ${info.signature} ${info.repeats} times without progress`,\n\t\t);\n\t}\n\n\tmarkTerminalToolFailureBlocked(toolName: string): boolean {\n\t\treturn this.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t`terminal_tool_failure: ${toolName} reported an unrecoverable error and terminated the run`,\n\t\t);\n\t}\n\n\tgetRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot {\n\t\treturn buildGoalRuntimeSnapshot({\n\t\t\tsessionManager: this.deps.getSessionManager(),\n\t\t\tsettings,\n\t\t\tlaneRecords: this.deps.getLaneRecords(),\n\t\t\ttaskRuntime: this.deps.getTaskRuntimeSnapshot(),\n\t\t});\n\t}\n\n\tcontinueOnce(options: GoalContinuationOnceOptions): Promise<GoalContinuationOnceResult> {\n\t\treturn this.loop.continueGoalOnce(options);\n\t}\n\n\tcontinueLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\treturn this.loop.continueGoalLoop(options);\n\t}\n\n\trestoreAfterResume(): void {\n\t\tthis.deps.scheduleGoalAutoContinueFromIdle();\n\t}\n\n\tprivate recordContinuationFailure(error: unknown): void {\n\t\tconst state = this.getState();\n\t\tif (!state || !isGoalExecutionActive(state.status)) return;\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconst classified = classifyFailure({ message, provider: this.deps.getModelProvider() });\n\t\tconst status = classified.reason === \"billing_or_quota\" ? \"usage_limited\" : \"blocked\";\n\t\tthis.stopActiveGoal(status, `${classified.reason}: ${message}`);\n\t}\n\n\tprivate markBudgetLimited(reason: string): void {\n\t\tthis.stopActiveGoal(\"budget_limited\", reason);\n\t}\n\n\tprivate stopActiveGoal(status: \"blocked\" | \"usage_limited\" | \"budget_limited\", reason: string): boolean {\n\t\tconst state = this.getState();\n\t\tconst stopped = stopGoalFromSystem(state, { status, reason }, new Date().toISOString());\n\t\tif (!stopped.ok || !state) return false;\n\t\tthis.saveState(stopped.state, getGoalStateRevision(state));\n\t\treturn true;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"goal-session-controller.js","sourceRoot":"","sources":["../../../src/core/goals/goal-session-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,uCAAuC,CAAC;AAYxE,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,wCAAwC,CAAC;AAExE,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EAA0B,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACvG,OAAO,EACN,wBAAwB,GAGxB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,cAAc,EAAkB,qBAAqB,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAChH,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAmC,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACpG,OAAO,EACN,yBAAyB,EACzB,uBAAuB,EACvB,0BAA0B,GAC1B,MAAM,yBAAyB,CAAC;AAmBjC;;;;;;;;;;GAUG;AACH,MAAM,kCAAkC,GAAG,KAAK,CAAC;AAEjD,MAAM,wBAAwB,GAAkB,MAAM,CAAC,oBAAoB,CAAC,CAAC;AAsB7E;;;GAGG;AACH,MAAM,OAAO,qBAAqB;IAMjC,YAAY,IAA+B;QAC1C,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,IAAI,kBAAkB,CAAC;YAClC,sBAAsB,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,IAAI,CAAC,kBAAkB,CAAC,QAAQ,CAAC;YACvE,MAAM,EAAE,CAAC,IAAI,EAA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KAAK;YAAE,OAAO,KAAK,CAAC;QACxC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,KAAK,EAAE,oBAAoB,CAAC,KAAK,CAAC,CAAC,CAAC;QAC3D,OAAO,IAAI,CAAC;IACb,CAAC;CACD","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { classifyFailure } from \"@caupulican/pi-agent-core/reliability\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/session\";\nimport type { AssistantMessage } from \"@caupulican/pi-ai\";\nimport type {\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tGoalContinuationOnceOptions,\n\tGoalContinuationOnceResult,\n\tPromptOptions,\n} from \"../agent-session-contracts.ts\";\nimport type { LaneRecord } from \"../autonomy/lane-tracker.ts\";\nimport type { BackgroundToolTaskRef } from \"../background-tool-task-controller.ts\";\nimport { GoalLoopController } from \"../goal-loop-controller.ts\";\nimport { budgetedTokens } from \"../orchestration/capability-gateway.ts\";\nimport type { TaskRuntimeProjection } from \"../orchestration/task-runtime.ts\";\nimport { GoalBudgetExhaustedError } from \"./goal-execution-errors.ts\";\nimport { type GoalStateRevision, getGoalStateRevision, stopGoalFromSystem } from \"./goal-lifecycle.ts\";\nimport {\n\tbuildGoalRuntimeSnapshot,\n\ttype GoalRuntimeSnapshot,\n\ttype GoalRuntimeSnapshotSettings,\n} from \"./goal-runtime-snapshot.ts\";\nimport { applyGoalEvent, type GoalState, isGoalExecutionActive, isGoalUnfinishedStatus } from \"./goal-state.ts\";\nimport { applyGoalAction } from \"./goal-tool-core.ts\";\nimport { type ExplicitGoalStartAuthority, parseExplicitChatGoal } from \"./natural-language-goal.ts\";\nimport {\n\tappendGoalClearedSnapshot,\n\tappendGoalStateSnapshot,\n\tgetLatestGoalStateSnapshot,\n} from \"./session-goal-state.ts\";\n\nexport interface GoalSessionControllerDeps {\n\tgetSessionManager(): SessionManager;\n\tgetModelProvider(): string | undefined;\n\tgetLaneRecords(): readonly LaneRecord[];\n\tgetTaskRuntimeSnapshot(): TaskRuntimeProjection | undefined;\n\tgetBackgroundToolTasks(): readonly BackgroundToolTaskRef[];\n\tsynchronizeGoalState(state: GoalState): void;\n\tscheduleGoalAutoContinueFromIdle(): void;\n\tprompt(text: string, options?: PromptOptions): Promise<void>;\n\temitWarning(message: string): void;\n}\n\nexport type ChatGoalAdmission =\n\t| { status: \"not_explicit\" }\n\t| { status: \"started\"; state: GoalState }\n\t| { status: \"unfinished_goal_exists\"; state: GoalState };\n\n/**\n * Smallest remaining goal budget worth handing to the provider as one more request's OUTPUT cap.\n * `admitProviderRequest` returns the goal's remaining TOTAL budget (input+output, cache-weighted) as\n * that cap — correct only because it also narrows further downstream against the model's real output\n * limit. When remaining drops below this floor (e.g. 200k budget, 199.4k used → 600 remaining), handing\n * 600 to the provider as maxTokens produces a request that pays the FULL input cost of the turn only to\n * get cut off mid-generation (`stopReason: \"length\"`) — a doomed, wasted turn. Below the floor, stop\n * the goal cleanly BEFORE sending instead of gambling on a truncated one. Above it, the remaining-total\n * value is a generous (imprecise but safe) protective ceiling — a modest final-turn overrun is\n * acceptable; a truncated turn is not.\n */\nconst MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS = 1_000;\n\nconst goalExecutionLeaseMarker: unique symbol = Symbol(\"goalExecutionLease\");\n\n/** Identity-bound attribution for one goal-owned foreground execution. */\nexport interface GoalExecutionLease {\n\treadonly goalId?: string;\n\treadonly [goalExecutionLeaseMarker]: true;\n}\n\ninterface MutableGoalExecutionLease extends GoalExecutionLease {\n\tgoalId?: string;\n\tadoptNewGoal: boolean;\n\tadoptionBaselineGoalId?: string;\n\tprovisionalTokenBudget?: number;\n\tpendingTokens: number;\n\tpendingSpendUsd: number;\n\t/** Set once this lease has admitted a provider request while its goal was still active. Lets a\n\t * later admission on the SAME still-held lease recognize \"the goal ended mid-turn\" (drain the\n\t * in-flight turn's wrap-up response) instead of \"a new turn is starting against a dead goal\"\n\t * (which stays denied). */\n\tadmittedWhileActive: boolean;\n}\n\n/**\n * Owns durable goal state, exact continuation accounting, and the raw continuation loop. The\n * AgentSession facade supplies process collaborators but no longer implements goal lifecycle rules.\n */\nexport class GoalSessionController {\n\tprivate readonly deps: GoalSessionControllerDeps;\n\tprivate readonly loop: GoalLoopController;\n\tprivate executionLease: MutableGoalExecutionLease | undefined;\n\tprivate startAuthority: ExplicitGoalStartAuthority | undefined;\n\n\tconstructor(deps: GoalSessionControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis.loop = new GoalLoopController({\n\t\t\tgetGoalRuntimeSnapshot: (settings) => this.getRuntimeSnapshot(settings),\n\t\t\tprompt: (text, options) => this.deps.prompt(text, options),\n\t\t\trecordGoalContinuationPass: (pass) => this.recordContinuationPass(pass),\n\t\t\trecordGoalContinuationFailure: (error) => this.recordContinuationFailure(error),\n\t\t\tmarkGoalBudgetLimited: (reason) => this.markBudgetLimited(reason),\n\t\t});\n\t}\n\n\tsaveState(state: GoalState, expected?: GoalStateRevision): string {\n\t\tconst current = this.getState();\n\t\tif (\n\t\t\texpected &&\n\t\t\t(!current || current.goalId !== expected.goalId || (current.revision ?? 0) !== expected.revision)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`Goal state changed concurrently; expected ${expected.goalId}@${expected.revision}, found ${current ? `${current.goalId}@${current.revision ?? 0}` : \"none\"}. Retry against the latest state.`,\n\t\t\t);\n\t\t}\n\t\tconst entryId = appendGoalStateSnapshot(this.deps.getSessionManager(), state, current);\n\t\ttry {\n\t\t\tthis.deps.synchronizeGoalState(state);\n\t\t} catch (error) {\n\t\t\tthis.deps.emitWarning(\n\t\t\t\t`Goal state persisted but durable worker reconciliation failed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\treturn entryId;\n\t}\n\n\tclearState(state: GoalState, now: string): string {\n\t\tconst current = this.getState();\n\t\tconst expected = getGoalStateRevision(state);\n\t\tif (!current || current.goalId !== expected.goalId || (current.revision ?? 0) !== expected.revision) {\n\t\t\tthrow new Error(\"Goal state changed concurrently; retry clear against the latest state.\");\n\t\t}\n\t\tif (state.status !== \"completed\" && state.status !== \"cancelled\") {\n\t\t\tthis.deps.synchronizeGoalState(applyGoalEvent(state, { type: \"cancel_goal\", now }));\n\t\t}\n\t\treturn appendGoalClearedSnapshot(this.deps.getSessionManager(), state, now);\n\t}\n\n\tgetState(): GoalState | undefined {\n\t\treturn getLatestGoalStateSnapshot(this.deps.getSessionManager());\n\t}\n\n\t/**\n\t * Promote high-confidence natural-language persistence into the same durable state written by the\n\t * goal tool. This is intentionally narrower than task detection: ordinary work never starts a\n\t * goal, and an unfinished goal is never replaced implicitly.\n\t */\n\tadmitExplicitChatGoal(text: string, now = new Date().toISOString()): ChatGoalAdmission {\n\t\tconst parsed = parseExplicitChatGoal(text);\n\t\tif (!parsed) return { status: \"not_explicit\" };\n\t\tconst current = this.getState();\n\t\tif (current && isGoalUnfinishedStatus(current.status)) {\n\t\t\treturn { status: \"unfinished_goal_exists\", state: current };\n\t\t}\n\t\tconst digest = createHash(\"sha256\")\n\t\t\t.update(`${now}\\0${current?.goalId ?? \"none\"}\\0${parsed.objective}`)\n\t\t\t.digest(\"hex\")\n\t\t\t.slice(0, 20);\n\t\tconst result = applyGoalAction(\n\t\t\tcurrent,\n\t\t\t{\n\t\t\t\taction: \"start\",\n\t\t\t\tgoalId: `chat-${digest}`,\n\t\t\t\tuserGoal: parsed.objective,\n\t\t\t\ttokenBudget: parsed.tokenBudget,\n\t\t\t},\n\t\t\tnow,\n\t\t);\n\t\tif (!result.ok) throw new Error(result.error);\n\t\tthis.saveState(result.state, current ? getGoalStateRevision(current) : undefined);\n\t\treturn { status: \"started\", state: result.state };\n\t}\n\n\t/** Attribute turn/wall-clock telemetry after usage has already been charged per response. */\n\trecordContinuationPass(pass: { turns: number; wallClockMs: number }): void {\n\t\tconst state = this.getState();\n\t\tif (!state) return;\n\t\tconst updated = applyGoalEvent(state, {\n\t\t\ttype: \"record_continuation_budget\",\n\t\t\tturns: pass.turns,\n\t\t\twallClockMs: pass.wallClockMs,\n\t\t\ttokens: 0,\n\t\t\tspendUsd: 0,\n\t\t\tnow: new Date().toISOString(),\n\t\t});\n\t\tthis.saveState(updated, getGoalStateRevision(state));\n\t}\n\n\t/** Begin one foreground execution whose provider usage belongs to the specified active goal. */\n\tbeginExecution(\n\t\tgoalId: string | undefined,\n\t\toptions: { adoptNewGoal?: boolean; provisionalTokenBudget?: number } = {},\n\t): GoalExecutionLease | undefined {\n\t\tif (!goalId && !options.adoptNewGoal) return undefined;\n\t\tif (this.executionLease) throw new Error(\"Goal execution attribution is already active\");\n\t\tconst state = this.getState();\n\t\tif (goalId && (!state || state.goalId !== goalId || !isGoalExecutionActive(state.status))) return undefined;\n\t\tconst lease: MutableGoalExecutionLease = {\n\t\t\t...(goalId ? { goalId } : {}),\n\t\t\t[goalExecutionLeaseMarker]: true,\n\t\t\tadoptNewGoal: options.adoptNewGoal === true,\n\t\t\t...(options.adoptNewGoal && state ? { adoptionBaselineGoalId: state.goalId } : {}),\n\t\t\t...(options.provisionalTokenBudget !== undefined\n\t\t\t\t? { provisionalTokenBudget: options.provisionalTokenBudget }\n\t\t\t\t: {}),\n\t\t\tpendingTokens: 0,\n\t\t\tpendingSpendUsd: 0,\n\t\t\tadmittedWhileActive: false,\n\t\t};\n\t\tthis.executionLease = lease;\n\t\treturn lease;\n\t}\n\n\tendExecution(lease: GoalExecutionLease | undefined): void {\n\t\tif (!lease) return;\n\t\tif (this.executionLease !== lease) throw new Error(\"Cannot end goal execution attribution owned by another run\");\n\t\tthis.flushPendingExecutionUsage(this.executionLease);\n\t\tthis.executionLease = undefined;\n\t}\n\n\t/** Charge one observed assistant response exactly once, including routed responses buffered from persistence. */\n\trecordExecutionUsage(message: AssistantMessage): void {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return;\n\t\tconst tokens = budgetedTokens({\n\t\t\tinputTokens: Math.max(0, message.usage.input),\n\t\t\toutputTokens: Math.max(0, message.usage.output),\n\t\t\tcacheReadTokens: Math.max(0, message.usage.cacheRead),\n\t\t\tcacheWriteTokens: Math.max(0, message.usage.cacheWrite),\n\t\t\ttotalTokens: Math.max(0, message.usage.totalTokens),\n\t\t});\n\t\tconst spendUsd = Math.max(0, message.usage.cost.total);\n\t\tif (tokens === 0 && spendUsd === 0) return;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state) {\n\t\t\tlease.pendingTokens += tokens;\n\t\t\tlease.pendingSpendUsd += spendUsd;\n\t\t\treturn;\n\t\t}\n\t\tthis.chargeExecutionUsage(lease, state, tokens, spendUsd);\n\t}\n\n\tprivate chargeExecutionUsage(\n\t\tlease: MutableGoalExecutionLease,\n\t\tstate: GoalState,\n\t\ttokens: number,\n\t\tspendUsd: number,\n\t): void {\n\t\tconst updated = applyGoalEvent(state, {\n\t\t\ttype: \"record_continuation_budget\",\n\t\t\tturns: 0,\n\t\t\twallClockMs: 0,\n\t\t\ttokens,\n\t\t\tspendUsd,\n\t\t\tnow: new Date().toISOString(),\n\t\t});\n\t\tthis.saveState(updated, getGoalStateRevision(state));\n\t\tlease.pendingTokens = 0;\n\t\tlease.pendingSpendUsd = 0;\n\t\tif (\n\t\t\tisGoalExecutionActive(updated.status) &&\n\t\t\tupdated.tokenBudget !== undefined &&\n\t\t\t(updated.tokensUsed ?? 0) >= updated.tokenBudget\n\t\t) {\n\t\t\tthis.markBudgetLimited(\n\t\t\t\t`token budget exhausted (${updated.tokensUsed ?? 0}/${updated.tokenBudget}) during goal execution`,\n\t\t\t);\n\t\t}\n\t}\n\n\tmarkProtocolFailureBlocked(errorMessage: string): boolean {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return false;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state || !isGoalExecutionActive(state.status)) return false;\n\t\tconst stopped = stopGoalFromSystem(\n\t\t\tstate,\n\t\t\t{ status: \"blocked\", reason: errorMessage.slice(0, 500) },\n\t\t\tnew Date().toISOString(),\n\t\t);\n\t\tif (!stopped.ok) return false;\n\t\tthis.saveState(stopped.state, getGoalStateRevision(state));\n\t\treturn true;\n\t}\n\n\tsetStartAuthority(authority: ExplicitGoalStartAuthority | undefined): void {\n\t\tthis.startAuthority = authority;\n\t}\n\n\tauthorizeStartFromTool(input: { tokenBudget?: number }): string | undefined {\n\t\tconst authority = this.startAuthority;\n\t\tif (!authority) return \"goal start requires explicit owner authorization in the current prompt.\";\n\t\tif (authority.tokenBudget === undefined && input.tokenBudget !== undefined) {\n\t\t\treturn \"tokenBudget requires an exact numeric token ceiling in the current owner prompt.\";\n\t\t}\n\t\tif (authority.tokenBudget !== undefined && input.tokenBudget !== authority.tokenBudget) {\n\t\t\treturn `tokenBudget must equal the owner-requested ceiling ${authority.tokenBudget}.`;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * True once the currently held execution lease's goal has crossed into `budget_limited` — set\n\t * synchronously by `chargeExecutionUsage` as soon as a just-charged response crosses the ceiling.\n\t * Wired to the agent's `shouldStopAfterTurn` hook so a mid-turn budget stop ends the loop\n\t * gracefully BEFORE the next provider request is even planned, instead of only being caught by\n\t * `admitProviderRequest`'s throw — which still exists as the backstop for a fresh turn or an\n\t * external admission starting against an already budget_limited goal, but would otherwise also\n\t * fire for a request this same lease was already mid-flight for, surfacing a synthetic error\n\t * message where a clean turn end belongs.\n\t */\n\thasExecutionLeaseCrossedBudgetLimit(): boolean {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return false;\n\t\treturn this.resolveExecutionState(lease)?.status === \"budget_limited\";\n\t}\n\n\t/** Reserve only remaining output capacity; actual provider usage is charged on response. */\n\tadmitProviderRequest(): number | undefined {\n\t\tconst lease = this.executionLease;\n\t\tif (!lease) return undefined;\n\t\tthis.flushPendingExecutionUsage(lease);\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (state?.status === \"budget_limited\") {\n\t\t\tthrow new GoalBudgetExhaustedError(`goal_token_budget_exhausted: ${state.blockedReason ?? lease.goalId}`);\n\t\t}\n\t\tif (state && !isGoalExecutionActive(state.status)) {\n\t\t\tif (!lease.admittedWhileActive) {\n\t\t\t\t// A fresh turn/continuation is being started against a goal that is already done —\n\t\t\t\t// keep this denied so a dead goal cannot restart itself.\n\t\t\t\tthrow new Error(`goal_execution_not_active: ${state.goalId} is ${state.status}`);\n\t\t\t}\n\t\t\t// This lease already admitted at least one request while the goal was active, so the\n\t\t\t// goal ended mid-turn (e.g. the model itself just called `goal complete`/`block`). Let\n\t\t\t// the already-in-flight turn drain to its closing response instead of throwing an error\n\t\t\t// at the user right after a successful stop.\n\t\t\treturn undefined;\n\t\t}\n\t\tif (!state && lease.goalId !== undefined) {\n\t\t\tthrow new Error(`goal_execution_not_active: ${lease.goalId} no longer exists`);\n\t\t}\n\t\tlease.admittedWhileActive = true;\n\t\tconst tokenBudget = state?.tokenBudget ?? lease.provisionalTokenBudget;\n\t\tif (tokenBudget === undefined) return undefined;\n\t\tconst tokensUsed = state?.tokensUsed ?? lease.pendingTokens;\n\t\tconst remaining = Math.max(0, tokenBudget - tokensUsed);\n\t\tif (remaining < MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS) {\n\t\t\t// Below the floor, remaining is too small to hand to the provider as an output cap without\n\t\t\t// dooming the turn to a mid-generation truncation that still burns the full input cost.\n\t\t\t// Stop cleanly now instead of sending a request that cannot possibly complete.\n\t\t\tif (state) {\n\t\t\t\tthis.markBudgetLimited(\n\t\t\t\t\t`token budget nearly exhausted (${tokensUsed}/${tokenBudget}, ${remaining} remaining is below the ` +\n\t\t\t\t\t\t`${MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS}-token minimum viable turn) before provider request`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new GoalBudgetExhaustedError(\n\t\t\t\t`goal_token_budget_exhausted: ${remaining} tokens remain, below the ${MIN_VIABLE_GOAL_TURN_OUTPUT_TOKENS}-token minimum viable turn`,\n\t\t\t);\n\t\t}\n\t\treturn remaining;\n\t}\n\n\tprivate resolveExecutionState(lease: MutableGoalExecutionLease): GoalState | undefined {\n\t\tconst state = this.getState();\n\t\tif (!state) return undefined;\n\t\tif (lease.goalId === state.goalId) return state;\n\t\tif (lease.goalId !== undefined || !lease.adoptNewGoal) return undefined;\n\t\tif (lease.adoptionBaselineGoalId === state.goalId) return undefined;\n\t\tlease.goalId = state.goalId;\n\t\treturn state;\n\t}\n\n\tprivate flushPendingExecutionUsage(lease: MutableGoalExecutionLease): void {\n\t\tif (lease.pendingTokens === 0 && lease.pendingSpendUsd === 0) return;\n\t\tconst state = this.resolveExecutionState(lease);\n\t\tif (!state) {\n\t\t\t// A speculative adopt-new-goal lease (lease.goalId still undefined) that never actually\n\t\t\t// adopted a goal this turn has nowhere to attribute usage — that is normal, not a loss.\n\t\t\t// A lease that WAS bound to a real goal but can no longer resolve it is a genuine loss of\n\t\t\t// buffered spend; fail loudly instead of silently discarding it (matches the cursor-based\n\t\t\t// accounting this replaced, which stopped the goal on `goal_usage_cursor_lost`).\n\t\t\tif (lease.goalId !== undefined) {\n\t\t\t\tthis.deps.emitWarning(\n\t\t\t\t\t`Goal usage cursor is no longer resolvable for '${lease.goalId}'; ${lease.pendingTokens} pending tokens and $${lease.pendingSpendUsd.toFixed(6)} pending spend could not be attributed and were dropped.`,\n\t\t\t\t);\n\t\t\t\tthis.recordContinuationFailure(new Error(\"goal_usage_cursor_lost\"));\n\t\t\t}\n\t\t\tlease.pendingTokens = 0;\n\t\t\tlease.pendingSpendUsd = 0;\n\t\t\treturn;\n\t\t}\n\t\tthis.chargeExecutionUsage(lease, state, lease.pendingTokens, lease.pendingSpendUsd);\n\t}\n\n\tmarkToolUnavailable(): void {\n\t\tthis.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t\"goal_tool_unavailable: the active capability surface cannot update durable goal state\",\n\t\t);\n\t}\n\n\tmarkRunawayBlocked(info: { signature: string; repeats: number }): boolean {\n\t\treturn this.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t`runaway_tool_loop: repeated tool-call signature ${info.signature} ${info.repeats} times without progress`,\n\t\t);\n\t}\n\n\tmarkTerminalToolFailureBlocked(toolName: string): boolean {\n\t\treturn this.stopActiveGoal(\n\t\t\t\"blocked\",\n\t\t\t`terminal_tool_failure: ${toolName} reported an unrecoverable error and terminated the run`,\n\t\t);\n\t}\n\n\tgetRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot {\n\t\treturn buildGoalRuntimeSnapshot({\n\t\t\tsessionManager: this.deps.getSessionManager(),\n\t\t\tsettings,\n\t\t\tlaneRecords: this.deps.getLaneRecords(),\n\t\t\ttaskRuntime: this.deps.getTaskRuntimeSnapshot(),\n\t\t\tbackgroundToolTasks: this.deps.getBackgroundToolTasks(),\n\t\t});\n\t}\n\n\tcontinueOnce(options: GoalContinuationOnceOptions): Promise<GoalContinuationOnceResult> {\n\t\treturn this.loop.continueGoalOnce(options);\n\t}\n\n\tcontinueLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\treturn this.loop.continueGoalLoop(options);\n\t}\n\n\trestoreAfterResume(): void {\n\t\tthis.deps.scheduleGoalAutoContinueFromIdle();\n\t}\n\n\tprivate recordContinuationFailure(error: unknown): void {\n\t\tconst state = this.getState();\n\t\tif (!state || !isGoalExecutionActive(state.status)) return;\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconst classified = classifyFailure({ message, provider: this.deps.getModelProvider() });\n\t\tconst status = classified.reason === \"billing_or_quota\" ? \"usage_limited\" : \"blocked\";\n\t\tthis.stopActiveGoal(status, `${classified.reason}: ${message}`);\n\t}\n\n\tprivate markBudgetLimited(reason: string): void {\n\t\tthis.stopActiveGoal(\"budget_limited\", reason);\n\t}\n\n\tprivate stopActiveGoal(status: \"blocked\" | \"usage_limited\" | \"budget_limited\", reason: string): boolean {\n\t\tconst state = this.getState();\n\t\tconst stopped = stopGoalFromSystem(state, { status, reason }, new Date().toISOString());\n\t\tif (!stopped.ok || !state) return false;\n\t\tthis.saveState(stopped.state, getGoalStateRevision(state));\n\t\treturn true;\n\t}\n}\n"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type BackgroundToolTaskRef } from "../background-tool-task-controller.ts";
|
|
1
2
|
import { type GoalEvidenceKind, type GoalState } from "./goal-state.ts";
|
|
2
3
|
/**
|
|
3
4
|
* Agent-facing goal ledger actions.
|
|
@@ -59,6 +60,8 @@ export type GoalAction = {
|
|
|
59
60
|
action: "no_progress";
|
|
60
61
|
} | {
|
|
61
62
|
action: "complete";
|
|
63
|
+
} | {
|
|
64
|
+
action: "increment";
|
|
62
65
|
} | {
|
|
63
66
|
action: "block_goal";
|
|
64
67
|
reason: string;
|
|
@@ -81,6 +84,20 @@ export interface ApplyGoalActionOptions {
|
|
|
81
84
|
* completion ({@link completeGoalManually}) is never subject to this gate.
|
|
82
85
|
*/
|
|
83
86
|
requireVerifiedEvidenceForCompletion?: boolean;
|
|
87
|
+
/**
|
|
88
|
+
* Open (non-terminal) task_steps on this branch. Agent-facing complete refuses while any of
|
|
89
|
+
* these still reference a requirement of the goal being closed.
|
|
90
|
+
*/
|
|
91
|
+
openTaskSteps?: readonly OpenTaskStepRef[];
|
|
92
|
+
/** Live background tool_task records used to re-check kind:"tool" evidence at complete time. */
|
|
93
|
+
backgroundToolTasks?: readonly BackgroundToolTaskRef[];
|
|
94
|
+
/** Active ICM pipeline run; agent complete refuses while a joined or any active run remains. */
|
|
95
|
+
activePipeline?: {
|
|
96
|
+
runId: string;
|
|
97
|
+
pipelineName: string;
|
|
98
|
+
goalId?: string;
|
|
99
|
+
status: string;
|
|
100
|
+
};
|
|
84
101
|
}
|
|
85
102
|
/**
|
|
86
103
|
* Apply one agent-facing goal action to the current ledger state.
|
|
@@ -115,6 +132,7 @@ export interface OpenTaskStepRef {
|
|
|
115
132
|
id: string;
|
|
116
133
|
content: string;
|
|
117
134
|
requirementIds?: readonly string[];
|
|
135
|
+
evidence?: readonly string[];
|
|
118
136
|
}
|
|
119
137
|
/**
|
|
120
138
|
* Nudge lines for open task steps that reference any of `requirementIds` (deduped per
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"goal-tool-core.d.ts","sourceRoot":"","sources":["../../../src/core/goals/goal-tool-core.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"goal-tool-core.d.ts","sourceRoot":"","sources":["../../../src/core/goals/goal-tool-core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,qBAAqB,EAA0B,MAAM,uCAAuC,CAAC;AAI3G,OAAO,EAIN,KAAK,gBAAgB,EACrB,KAAK,SAAS,EAId,MAAM,iBAAiB,CAAC;AAQzB;;;;;;;;;GASG;AACH,MAAM,MAAM,UAAU,GACnB;IAAE,MAAM,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAAE,GAC3E;IAAE,MAAM,EAAE,iBAAiB,CAAC;IAAC,aAAa,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,YAAY,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,GACpG;IAAE,MAAM,EAAE,qBAAqB,CAAC;IAAC,aAAa,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,GACzF;IAAE,MAAM,EAAE,mBAAmB,CAAC;IAAC,aAAa,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GACtE;IAAE,MAAM,EAAE,oBAAoB,CAAC;IAAC,aAAa,EAAE,MAAM,CAAA;CAAE,GACvD;IACA,MAAM,EAAE,iBAAiB,CAAC;IAC1B,aAAa,EAAE,MAAM,CAAC;IACtB,YAAY,EAAE,MAAM,CAAC;IACrB;;;;;OAKG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;CACf,GACD;IACA,MAAM,EAAE,cAAc,CAAC;IACvB,UAAU,EAAE,MAAM,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X,OAAO,CAAC,EAAE,sBAAsB,GAC9B,gBAAgB,CA2DlB;AAuMD;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,SAAS,GAAG,SAAS,EAAE,GAAG,EAAE,MAAM,GAAG,gBAAgB,CAWlG;AAED,6EAA6E;AAC7E,wBAAgB,kBAAkB,CACjC,KAAK,EAAE,SAAS,EAChB,OAAO,CAAC,EAAE;IAAE,MAAM,CAAC,EAAE,UAAU,CAAC;IAAC,aAAa,CAAC,EAAE,SAAS,eAAe,EAAE,CAAA;CAAE,GAC3E,MAAM,CAeR;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,eAAe;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC,QAAQ,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC7B;AAuBD;;;GAGG;AACH,wBAAgB,mCAAmC,CAClD,KAAK,EAAE,SAAS,EAChB,cAAc,EAAE,SAAS,MAAM,EAAE,EACjC,aAAa,EAAE,SAAS,eAAe,EAAE,GACvC,MAAM,EAAE,CAcV;AAED;;;;;GAKG;AACH,wBAAgB,kCAAkC,CACjD,MAAM,EAAE,UAAU,EAClB,KAAK,EAAE,SAAS,EAChB,aAAa,EAAE,SAAS,eAAe,EAAE,GAAG,SAAS,GACnD,MAAM,EAAE,CAYV"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { findBackgroundToolTask } from "../background-tool-task-controller.js";
|
|
1
2
|
import { taskStepReferencesRequirement } from "../tasks/task-projection.js";
|
|
2
3
|
import { getUnprovenGoalRequirementIds } from "./goal-acceptance.js";
|
|
3
4
|
import { formatGoalRecord, projectGoalRecord } from "./goal-record.js";
|
|
@@ -54,6 +55,21 @@ export function applyGoalAction(current, action, now, options) {
|
|
|
54
55
|
error: `Goal '${current.goalId}' is ${current.status}. Lifecycle changes are owner/system controlled; use the /goal controls.`,
|
|
55
56
|
};
|
|
56
57
|
}
|
|
58
|
+
if (action.action === "increment") {
|
|
59
|
+
const firstOpen = current.requirements.find((requirement) => requirement.status === "open");
|
|
60
|
+
if (firstOpen) {
|
|
61
|
+
const used = new Set(current.requirements.flatMap((requirement) => requirement.evidenceIds));
|
|
62
|
+
const unused = current.evidence.filter((evidence) => !used.has(evidence.id)).map((evidence) => evidence.id);
|
|
63
|
+
if (unused.length === 0) {
|
|
64
|
+
return {
|
|
65
|
+
ok: false,
|
|
66
|
+
error: `Cannot increment goal: open requirement '${firstOpen.id}' has no unused evidence. Record evidence, then increment.`,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
return applyGoalAction(current, { action: "satisfy_requirement", requirementId: firstOpen.id, evidenceIds: unused }, now, options);
|
|
70
|
+
}
|
|
71
|
+
return applyGoalAction(current, { action: "complete" }, now, options);
|
|
72
|
+
}
|
|
57
73
|
const event = toGoalEvent(current, action, now, options);
|
|
58
74
|
if (!event.ok)
|
|
59
75
|
return event;
|
|
@@ -201,6 +217,8 @@ function toGoalEvent(state, action, now, options) {
|
|
|
201
217
|
return { ok: true, event: { type: "progress", now } };
|
|
202
218
|
case "no_progress":
|
|
203
219
|
return { ok: true, event: { type: "no_progress", now } };
|
|
220
|
+
case "increment":
|
|
221
|
+
return { ok: false, error: "increment must be expanded by applyGoalAction." };
|
|
204
222
|
case "complete": {
|
|
205
223
|
const unsatisfied = state.requirements.filter((requirement) => requirement.status !== "satisfied");
|
|
206
224
|
if (unsatisfied.length > 0) {
|
|
@@ -212,6 +230,30 @@ function toGoalEvent(state, action, now, options) {
|
|
|
212
230
|
};
|
|
213
231
|
}
|
|
214
232
|
const requireVerifiedEvidence = options?.requireVerifiedEvidenceForCompletion ?? true;
|
|
233
|
+
const linkedOpenSteps = findLinkedOpenTaskSteps(state, options?.openTaskSteps);
|
|
234
|
+
if (linkedOpenSteps.length > 0) {
|
|
235
|
+
return {
|
|
236
|
+
ok: false,
|
|
237
|
+
error: `Cannot complete goal: open task_steps still reference this goal (${linkedOpenSteps.join(", ")}). Update them via task_steps first.`,
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
const pendingToolTasks = findNonterminalCitedToolTasks(state, options?.backgroundToolTasks);
|
|
241
|
+
if (pendingToolTasks.length > 0) {
|
|
242
|
+
return {
|
|
243
|
+
ok: false,
|
|
244
|
+
error: `Cannot complete goal: cited tool_task(s) are not complete (${pendingToolTasks.join(", ")}). Wait once via tool_task, then record the terminal result.`,
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
const activePipeline = options?.activePipeline;
|
|
248
|
+
if (activePipeline && activePipeline.status === "active") {
|
|
249
|
+
const joined = !activePipeline.goalId || activePipeline.goalId === state.goalId;
|
|
250
|
+
if (joined) {
|
|
251
|
+
return {
|
|
252
|
+
ok: false,
|
|
253
|
+
error: `Cannot complete goal: pipeline '${activePipeline.pipelineName}' run '${activePipeline.runId}' is still active. Increment or abandon it first.`,
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
}
|
|
215
257
|
const unprovenRequirementIds = getUnprovenGoalRequirementIds(state);
|
|
216
258
|
if (requireVerifiedEvidence && unprovenRequirementIds.length > 0) {
|
|
217
259
|
return {
|
|
@@ -266,6 +308,26 @@ export function summarizeGoalState(state, options) {
|
|
|
266
308
|
}
|
|
267
309
|
return lines.join("\n");
|
|
268
310
|
}
|
|
311
|
+
function findLinkedOpenTaskSteps(state, openTaskSteps) {
|
|
312
|
+
if (!openTaskSteps || openTaskSteps.length === 0)
|
|
313
|
+
return [];
|
|
314
|
+
return openTaskSteps
|
|
315
|
+
.filter((step) => state.requirements.some((requirement) => taskStepReferencesRequirement(step, requirement)))
|
|
316
|
+
.map((step) => step.id);
|
|
317
|
+
}
|
|
318
|
+
function findNonterminalCitedToolTasks(state, backgroundToolTasks) {
|
|
319
|
+
if (!backgroundToolTasks || backgroundToolTasks.length === 0)
|
|
320
|
+
return [];
|
|
321
|
+
const pending = new Set();
|
|
322
|
+
for (const evidence of state.evidence) {
|
|
323
|
+
if (evidence.kind !== "tool" || !evidence.uri)
|
|
324
|
+
continue;
|
|
325
|
+
const task = findBackgroundToolTask(backgroundToolTasks, evidence.uri);
|
|
326
|
+
if (task && task.status !== "completed")
|
|
327
|
+
pending.add(task.taskId);
|
|
328
|
+
}
|
|
329
|
+
return [...pending];
|
|
330
|
+
}
|
|
269
331
|
/**
|
|
270
332
|
* Nudge lines for open task steps that reference any of `requirementIds` (deduped per
|
|
271
333
|
* requirement, one line naming every referencing step). Empty when there is nothing to say.
|