@agimon-ai/doompi-task 0.0.1-alpha.71 → 0.0.1-alpha.73
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -3
- package/dist/_virtual/_rolldown/runtime.cjs +23 -1
- package/dist/api-contracts.cjs +7 -1
- package/dist/api-contracts.d.cts +1 -1
- package/dist/api-contracts.d.mts +1 -1
- package/dist/api-contracts.mjs +2 -1
- package/dist/commands.cjs +4 -1
- package/dist/commands.d.cts +2 -2
- package/dist/commands.d.mts +2 -2
- package/dist/commands.mjs +2 -1
- package/dist/config.cjs +19 -1
- package/dist/config.d.cts +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/config.mjs +2 -1
- package/dist/delegation-manager.cjs +10 -1
- package/dist/delegation-manager.d.cts +2 -2
- package/dist/delegation-manager.d.mts +2 -2
- package/dist/delegation-manager.mjs +3 -1
- package/dist/extensions/pi.cjs +49 -2
- package/dist/extensions/pi.cjs.map +1 -1
- package/dist/extensions/pi.d.cts +3 -4
- package/dist/extensions/pi.d.cts.map +1 -1
- package/dist/extensions/pi.d.mts +3 -4
- package/dist/extensions/pi.d.mts.map +1 -1
- package/dist/extensions/pi.mjs +44 -2
- package/dist/extensions/pi.mjs.map +1 -1
- package/dist/extensions/server.cjs +56 -1
- package/dist/extensions/server.cjs.map +1 -1
- package/dist/extensions/server.d.cts +3 -3
- package/dist/extensions/server.d.cts.map +1 -1
- package/dist/extensions/server.d.mts +3 -3
- package/dist/extensions/server.d.mts.map +1 -1
- package/dist/extensions/server.mjs +51 -1
- package/dist/extensions/server.mjs.map +1 -1
- package/dist/extensions/web.mjs +1013 -0
- package/dist/extensions/web.mjs.map +1 -0
- package/dist/index.cjs +106 -1
- package/dist/index.d.cts +15 -15
- package/dist/index.d.mts +15 -15
- package/dist/index.mjs +16 -1
- package/dist/logSinkTelemetry.cjs +6 -1
- package/dist/logSinkTelemetry.d.cts +2 -2
- package/dist/logSinkTelemetry.d.mts +2 -2
- package/dist/logSinkTelemetry.mjs +3 -1
- package/dist/src/constants/promptGuidelines.cjs +26 -0
- package/dist/src/constants/promptGuidelines.cjs.map +1 -0
- package/dist/src/constants/promptGuidelines.d.cts.map +1 -0
- package/dist/src/constants/promptGuidelines.d.mts.map +1 -0
- package/dist/src/constants/promptGuidelines.mjs +26 -0
- package/dist/src/constants/promptGuidelines.mjs.map +1 -0
- package/dist/src/constants/task.cjs +6 -0
- package/dist/src/constants/task.cjs.map +1 -0
- package/dist/src/constants/task.d.cts.map +1 -0
- package/dist/src/constants/task.d.mts.map +1 -0
- package/dist/src/constants/task.mjs +6 -0
- package/dist/src/constants/task.mjs.map +1 -0
- package/dist/src/extensions/(backend)/channel/_lib/task-graph.cjs +90 -0
- package/dist/src/extensions/(backend)/channel/_lib/task-graph.cjs.map +1 -0
- package/dist/src/extensions/(backend)/channel/_lib/task-graph.mjs +89 -0
- package/dist/src/extensions/(backend)/channel/_lib/task-graph.mjs.map +1 -0
- package/dist/src/extensions/(backend)/channel/task-graph.server.cjs +7 -0
- package/dist/src/extensions/(backend)/channel/task-graph.server.cjs.map +1 -0
- package/dist/src/extensions/(backend)/channel/task-graph.server.mjs +8 -0
- package/dist/src/extensions/(backend)/channel/task-graph.server.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.cli.cjs +317 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.cli.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.cli.d.cts +39 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.cli.d.cts.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.cli.d.mts +39 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.cli.d.mts.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.cli.mjs +317 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.cli.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.server.cjs +95 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.server.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.server.mjs +95 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/_lib/root.server.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.cli.cjs +30 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.cli.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.cli.d.cts +20 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.cli.d.cts.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.cli.d.mts +20 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.cli.d.mts.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.cli.mjs +29 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.cli.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.server.cjs +19 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.server.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.server.mjs +19 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/command/_lib/tasks.server.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/command/tasks.cli.cjs +8 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/command/tasks.cli.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/command/tasks.cli.mjs +9 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/command/tasks.cli.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/command/tasks.server.cjs +7 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/command/tasks.server.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/command/tasks.server.mjs +8 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/command/tasks.server.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-compact.cli.cjs +6 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-compact.cli.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-compact.cli.mjs +6 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-compact.cli.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-start.cli.cjs +6 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-start.cli.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-start.cli.mjs +6 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-start.cli.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-tree.cli.cjs +6 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-tree.cli.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-tree.cli.mjs +6 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/session-tree.cli.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/tool-execution-end.cli.cjs +6 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/tool-execution-end.cli.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/tool-execution-end.cli.mjs +6 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/_lib/tool-execution-end.cli.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-compact.cli.cjs +7 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-compact.cli.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-compact.cli.mjs +8 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-compact.cli.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-start.cli.cjs +7 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-start.cli.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-start.cli.mjs +8 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-start.cli.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-tree.cli.cjs +7 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-tree.cli.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-tree.cli.mjs +8 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/session-tree.cli.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.cli.cjs +7 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.cli.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.cli.mjs +8 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.cli.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/task-board.server.cjs +20 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/task-board.server.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/task-board.server.mjs +20 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/resource/_lib/task-board.server.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/resource/task-board.server.cjs +7 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/resource/task-board.server.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/resource/task-board.server.mjs +8 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/resource/task-board.server.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/root.cli.cjs +11 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/root.cli.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/root.cli.mjs +12 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/root.cli.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/root.server.cjs +7 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/root.server.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/root.server.mjs +8 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/root.server.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/task.cli.cjs +160 -0
- package/dist/{tools/task.cjs.map → src/extensions/workspaces/sessions/(backend)/tool/_lib/task.cli.cjs.map} +1 -1
- package/dist/{tools/task.d.cts → src/extensions/workspaces/sessions/(backend)/tool/_lib/task.cli.d.cts} +11 -8
- package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/task.cli.d.cts.map +1 -0
- package/dist/{tools/task.d.mts → src/extensions/workspaces/sessions/(backend)/tool/_lib/task.cli.d.mts} +11 -8
- package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/task.cli.d.mts.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/task.cli.mjs +157 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/task.cli.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/task.server.cjs +109 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/task.server.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/task.server.mjs +107 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/tool/_lib/task.server.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/tool/task.cli.cjs +7 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/tool/task.cli.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/tool/task.cli.mjs +8 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/tool/task.cli.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/tool/task.server.cjs +7 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/tool/task.server.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/tool/task.server.mjs +8 -0
- package/dist/src/extensions/workspaces/sessions/(backend)/tool/task.server.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/_shared/format.cli.cjs +333 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/_shared/format.cli.cjs.map +1 -0
- package/dist/{tui/format.d.mts → src/extensions/workspaces/sessions/(frontend)/_shared/format.cli.d.cts} +5 -5
- package/dist/src/extensions/workspaces/sessions/(frontend)/_shared/format.cli.d.cts.map +1 -0
- package/dist/{tui/format.d.cts → src/extensions/workspaces/sessions/(frontend)/_shared/format.cli.d.mts} +5 -5
- package/dist/src/extensions/workspaces/sessions/(frontend)/_shared/format.cli.d.mts.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/_shared/format.cli.mjs +322 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/_shared/format.cli.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/message/doom-task-notify.cli.cjs +9 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/message/doom-task-notify.cli.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/message/doom-task-notify.cli.mjs +9 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/message/doom-task-notify.cli.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/selectors.cjs +149 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/selectors.cjs.map +1 -0
- package/dist/{tui → src/extensions/workspaces/sessions/(frontend)/overlay/_lib}/selectors.d.cts +2 -2
- package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/selectors.d.cts.map +1 -0
- package/dist/{tui → src/extensions/workspaces/sessions/(frontend)/overlay/_lib}/selectors.d.mts +2 -2
- package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/selectors.d.mts.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/selectors.mjs +142 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/selectors.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/task-space.cli.cjs +358 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/task-space.cli.cjs.map +1 -0
- package/dist/{tui/taskSpace.d.cts → src/extensions/workspaces/sessions/(frontend)/overlay/_lib/task-space.cli.d.cts} +4 -3
- package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/task-space.cli.d.cts.map +1 -0
- package/dist/{tui/taskSpace.d.mts → src/extensions/workspaces/sessions/(frontend)/overlay/_lib/task-space.cli.d.mts} +4 -3
- package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/task-space.cli.d.mts.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/task-space.cli.mjs +355 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/task-space.cli.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/taskOverlay.cjs +165 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/taskOverlay.cjs.map +1 -0
- package/dist/{tui → src/extensions/workspaces/sessions/(frontend)/overlay/_lib}/taskOverlay.d.cts +6 -4
- package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/taskOverlay.d.cts.map +1 -0
- package/dist/{tui → src/extensions/workspaces/sessions/(frontend)/overlay/_lib}/taskOverlay.d.mts +6 -4
- package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/taskOverlay.d.mts.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/taskOverlay.mjs +164 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/overlay/_lib/taskOverlay.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/tool/_lib/task.cli.cjs +13 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/tool/_lib/task.cli.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/tool/_lib/task.cli.mjs +13 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/tool/_lib/task.cli.mjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/tool/task.cli.cjs +7 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/tool/task.cli.cjs.map +1 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/tool/task.cli.mjs +8 -0
- package/dist/src/extensions/workspaces/sessions/(frontend)/tool/task.cli.mjs.map +1 -0
- package/dist/src/models/task.cjs +29 -0
- package/dist/src/models/task.cjs.map +1 -0
- package/dist/{models → src/models}/task.d.cts +12 -2
- package/dist/src/models/task.d.cts.map +1 -0
- package/dist/{models → src/models}/task.d.mts +12 -2
- package/dist/src/models/task.d.mts.map +1 -0
- package/dist/src/models/task.mjs +26 -0
- package/dist/src/models/task.mjs.map +1 -0
- package/dist/src/models/taskGraph.cjs +67 -0
- package/dist/src/models/taskGraph.cjs.map +1 -0
- package/dist/src/models/taskGraph.d.cts.map +1 -0
- package/dist/src/models/taskGraph.d.mts.map +1 -0
- package/dist/src/models/taskGraph.mjs +63 -0
- package/dist/src/models/taskGraph.mjs.map +1 -0
- package/dist/src/schemas/apiContracts.cjs +51 -0
- package/dist/src/schemas/apiContracts.cjs.map +1 -0
- package/dist/{schemas → src/schemas}/apiContracts.d.cts.map +1 -1
- package/dist/{schemas → src/schemas}/apiContracts.d.mts.map +1 -1
- package/dist/src/schemas/apiContracts.mjs +49 -0
- package/dist/src/schemas/apiContracts.mjs.map +1 -0
- package/dist/src/schemas/task.cjs +130 -0
- package/dist/src/schemas/task.cjs.map +1 -0
- package/dist/src/schemas/task.d.cts.map +1 -0
- package/dist/src/schemas/task.d.mts.map +1 -0
- package/dist/src/schemas/task.mjs +117 -0
- package/dist/src/schemas/task.mjs.map +1 -0
- package/dist/src/services/config/index.cjs +88 -0
- package/dist/src/services/config/index.cjs.map +1 -0
- package/dist/src/services/config/index.d.cts.map +1 -0
- package/dist/src/services/config/index.d.mts.map +1 -0
- package/dist/src/services/config/index.mjs +72 -0
- package/dist/src/services/config/index.mjs.map +1 -0
- package/dist/src/services/contextContribution/index.cjs +51 -0
- package/dist/src/services/contextContribution/index.cjs.map +1 -0
- package/dist/src/services/contextContribution/index.mjs +46 -0
- package/dist/src/services/contextContribution/index.mjs.map +1 -0
- package/dist/src/services/delegation/index.cjs +629 -0
- package/dist/src/services/delegation/index.cjs.map +1 -0
- package/dist/src/services/delegation/index.d.cts.map +1 -0
- package/dist/src/services/delegation/index.d.mts.map +1 -0
- package/dist/src/services/delegation/index.mjs +623 -0
- package/dist/src/services/delegation/index.mjs.map +1 -0
- package/dist/src/services/delegationPlatform/index.cjs +23 -0
- package/dist/src/services/delegationPlatform/index.cjs.map +1 -0
- package/dist/src/services/delegationPlatform/index.mjs +21 -0
- package/dist/src/services/delegationPlatform/index.mjs.map +1 -0
- package/dist/src/services/invariants/index.cjs +64 -0
- package/dist/src/services/invariants/index.cjs.map +1 -0
- package/dist/src/services/invariants/index.d.cts.map +1 -0
- package/dist/src/services/invariants/index.d.mts.map +1 -0
- package/dist/src/services/invariants/index.mjs +62 -0
- package/dist/src/services/invariants/index.mjs.map +1 -0
- package/dist/src/services/logSinkTelemetry/index.cjs +43 -0
- package/dist/src/services/logSinkTelemetry/index.cjs.map +1 -0
- package/dist/src/services/logSinkTelemetry/index.d.cts.map +1 -0
- package/dist/src/services/logSinkTelemetry/index.d.mts.map +1 -0
- package/dist/src/services/logSinkTelemetry/index.mjs +41 -0
- package/dist/src/services/logSinkTelemetry/index.mjs.map +1 -0
- package/dist/src/services/paths/index.cjs +233 -0
- package/dist/src/services/paths/index.cjs.map +1 -0
- package/dist/src/services/paths/index.d.cts.map +1 -0
- package/dist/src/services/paths/index.d.mts.map +1 -0
- package/dist/src/services/paths/index.mjs +218 -0
- package/dist/src/services/paths/index.mjs.map +1 -0
- package/dist/src/services/processLiveness/index.cjs +20 -0
- package/dist/src/services/processLiveness/index.cjs.map +1 -0
- package/dist/src/services/processLiveness/index.d.cts.map +1 -0
- package/dist/src/services/processLiveness/index.d.mts.map +1 -0
- package/dist/src/services/processLiveness/index.mjs +20 -0
- package/dist/src/services/processLiveness/index.mjs.map +1 -0
- package/dist/src/services/reconcile/index.cjs +65 -0
- package/dist/src/services/reconcile/index.cjs.map +1 -0
- package/dist/src/services/reconcile/index.d.cts.map +1 -0
- package/dist/src/services/reconcile/index.d.mts.map +1 -0
- package/dist/src/services/reconcile/index.mjs +63 -0
- package/dist/src/services/reconcile/index.mjs.map +1 -0
- package/dist/src/services/reducer/index.cjs +350 -0
- package/dist/src/services/reducer/index.cjs.map +1 -0
- package/dist/src/services/reducer/index.d.cts.map +1 -0
- package/dist/src/services/reducer/index.d.mts.map +1 -0
- package/dist/src/services/reducer/index.mjs +345 -0
- package/dist/src/services/reducer/index.mjs.map +1 -0
- package/dist/src/services/taskNarration/index.cjs +32 -0
- package/dist/src/services/taskNarration/index.cjs.map +1 -0
- package/dist/src/services/taskNarration/index.mjs +32 -0
- package/dist/src/services/taskNarration/index.mjs.map +1 -0
- package/dist/src/services/taskResult/index.cjs +174 -0
- package/dist/src/services/taskResult/index.cjs.map +1 -0
- package/dist/src/services/taskResult/index.d.cts.map +1 -0
- package/dist/src/services/taskResult/index.d.mts.map +1 -0
- package/dist/src/services/taskResult/index.mjs +165 -0
- package/dist/src/services/taskResult/index.mjs.map +1 -0
- package/dist/src/services/taskStore/index.cjs +216 -0
- package/dist/src/services/taskStore/index.cjs.map +1 -0
- package/dist/src/services/taskStore/index.d.cts.map +1 -0
- package/dist/src/services/taskStore/index.d.mts.map +1 -0
- package/dist/src/services/taskStore/index.mjs +213 -0
- package/dist/src/services/taskStore/index.mjs.map +1 -0
- package/dist/src/types/delegation.cjs +7 -0
- package/dist/src/types/delegation.cjs.map +1 -0
- package/dist/{types → src/types}/delegation.d.cts.map +1 -1
- package/dist/{types → src/types}/delegation.d.mts.map +1 -1
- package/dist/src/types/delegation.mjs +7 -0
- package/dist/src/types/delegation.mjs.map +1 -0
- package/dist/src/types/telemetry.cjs +26 -0
- package/dist/src/types/telemetry.cjs.map +1 -0
- package/dist/src/types/telemetry.d.cts.map +1 -0
- package/dist/src/types/telemetry.d.mts.map +1 -0
- package/dist/src/types/telemetry.mjs +26 -0
- package/dist/src/types/telemetry.mjs.map +1 -0
- package/dist/src/types/webTasks.cjs +7 -0
- package/dist/src/types/webTasks.cjs.map +1 -0
- package/dist/src/types/webTasks.mjs +7 -0
- package/dist/src/types/webTasks.mjs.map +1 -0
- package/dist/store-invariants.cjs +5 -1
- package/dist/store-invariants.d.cts +1 -1
- package/dist/store-invariants.d.mts +1 -1
- package/dist/store-invariants.mjs +2 -1
- package/dist/store-paths.cjs +14 -1
- package/dist/store-paths.d.cts +1 -1
- package/dist/store-paths.d.mts +1 -1
- package/dist/store-paths.mjs +2 -1
- package/dist/store-process-liveness.cjs +3 -1
- package/dist/store-process-liveness.d.cts +1 -1
- package/dist/store-process-liveness.d.mts +1 -1
- package/dist/store-process-liveness.mjs +2 -1
- package/dist/store-reconcile.cjs +5 -1
- package/dist/store-reconcile.d.cts +1 -1
- package/dist/store-reconcile.d.mts +1 -1
- package/dist/store-reconcile.mjs +2 -1
- package/dist/store-reducer.cjs +8 -1
- package/dist/store-reducer.d.cts +1 -1
- package/dist/store-reducer.d.mts +1 -1
- package/dist/store-reducer.mjs +2 -1
- package/dist/store-task-graph.cjs +7 -1
- package/dist/store-task-graph.d.cts +1 -1
- package/dist/store-task-graph.d.mts +1 -1
- package/dist/store-task-graph.mjs +2 -1
- package/dist/store-task-store.cjs +3 -1
- package/dist/store-task-store.d.cts +1 -1
- package/dist/store-task-store.d.mts +1 -1
- package/dist/store-task-store.mjs +2 -1
- package/dist/store-types.cjs +6 -1
- package/dist/store-types.d.cts +1 -1
- package/dist/store-types.d.mts +1 -1
- package/dist/store-types.mjs +2 -1
- package/dist/tool-prompt-guidelines.cjs +3 -1
- package/dist/tool-prompt-guidelines.d.cts +1 -1
- package/dist/tool-prompt-guidelines.d.mts +1 -1
- package/dist/tool-prompt-guidelines.mjs +2 -1
- package/dist/tool-response-envelope.cjs +12 -1
- package/dist/tool-response-envelope.d.cts +1 -1
- package/dist/tool-response-envelope.d.mts +1 -1
- package/dist/tool-response-envelope.mjs +2 -1
- package/dist/tool-schema.cjs +17 -1
- package/dist/tool-schema.d.cts +2 -2
- package/dist/tool-schema.d.mts +2 -2
- package/dist/tool-schema.mjs +3 -1
- package/dist/tool-task-tool.cjs +6 -1
- package/dist/tool-task-tool.d.cts +2 -2
- package/dist/tool-task-tool.d.mts +2 -2
- package/dist/tool-task-tool.mjs +3 -1
- package/dist/tui-format.cjs +14 -1
- package/dist/tui-format.d.cts +1 -1
- package/dist/tui-format.d.mts +1 -1
- package/dist/tui-format.mjs +2 -1
- package/dist/tui-selectors.cjs +10 -1
- package/dist/tui-selectors.d.cts +1 -1
- package/dist/tui-selectors.d.mts +1 -1
- package/dist/tui-selectors.mjs +2 -1
- package/dist/tui-task-overlay.cjs +4 -1
- package/dist/tui-task-overlay.d.cts +2 -2
- package/dist/tui-task-overlay.d.mts +2 -2
- package/dist/tui-task-overlay.mjs +2 -1
- package/dist/tui-task-space.cjs +5 -1
- package/dist/tui-task-space.d.cts +1 -1
- package/dist/tui-task-space.d.mts +1 -1
- package/dist/tui-task-space.mjs +2 -1
- package/package.json +20 -19
- package/dist/constants/promptGuidelines.cjs +0 -2
- package/dist/constants/promptGuidelines.cjs.map +0 -1
- package/dist/constants/promptGuidelines.d.cts.map +0 -1
- package/dist/constants/promptGuidelines.d.mts.map +0 -1
- package/dist/constants/promptGuidelines.mjs +0 -2
- package/dist/constants/promptGuidelines.mjs.map +0 -1
- package/dist/constants/task.cjs +0 -2
- package/dist/constants/task.cjs.map +0 -1
- package/dist/constants/task.d.cts.map +0 -1
- package/dist/constants/task.d.mts.map +0 -1
- package/dist/constants/task.mjs +0 -2
- package/dist/constants/task.mjs.map +0 -1
- package/dist/controllers/tasksCommand.cjs +0 -2
- package/dist/controllers/tasksCommand.cjs.map +0 -1
- package/dist/controllers/tasksCommand.d.cts +0 -15
- package/dist/controllers/tasksCommand.d.cts.map +0 -1
- package/dist/controllers/tasksCommand.d.mts +0 -15
- package/dist/controllers/tasksCommand.d.mts.map +0 -1
- package/dist/controllers/tasksCommand.mjs +0 -2
- package/dist/controllers/tasksCommand.mjs.map +0 -1
- package/dist/controllers/webTasksChannel.cjs +0 -2
- package/dist/controllers/webTasksChannel.cjs.map +0 -1
- package/dist/controllers/webTasksChannel.mjs +0 -2
- package/dist/controllers/webTasksChannel.mjs.map +0 -1
- package/dist/models/task.cjs +0 -2
- package/dist/models/task.cjs.map +0 -1
- package/dist/models/task.d.cts.map +0 -1
- package/dist/models/task.d.mts.map +0 -1
- package/dist/models/task.mjs +0 -2
- package/dist/models/task.mjs.map +0 -1
- package/dist/models/taskGraph.cjs +0 -2
- package/dist/models/taskGraph.cjs.map +0 -1
- package/dist/models/taskGraph.d.cts.map +0 -1
- package/dist/models/taskGraph.d.mts.map +0 -1
- package/dist/models/taskGraph.mjs +0 -2
- package/dist/models/taskGraph.mjs.map +0 -1
- package/dist/schemas/apiContracts.cjs +0 -2
- package/dist/schemas/apiContracts.cjs.map +0 -1
- package/dist/schemas/apiContracts.mjs +0 -2
- package/dist/schemas/apiContracts.mjs.map +0 -1
- package/dist/schemas/task.cjs +0 -2
- package/dist/schemas/task.cjs.map +0 -1
- package/dist/schemas/task.d.cts.map +0 -1
- package/dist/schemas/task.d.mts.map +0 -1
- package/dist/schemas/task.mjs +0 -2
- package/dist/schemas/task.mjs.map +0 -1
- package/dist/services/config/index.cjs +0 -2
- package/dist/services/config/index.cjs.map +0 -1
- package/dist/services/config/index.d.cts.map +0 -1
- package/dist/services/config/index.d.mts.map +0 -1
- package/dist/services/config/index.mjs +0 -2
- package/dist/services/config/index.mjs.map +0 -1
- package/dist/services/contextContribution/index.cjs +0 -3
- package/dist/services/contextContribution/index.cjs.map +0 -1
- package/dist/services/contextContribution/index.mjs +0 -3
- package/dist/services/contextContribution/index.mjs.map +0 -1
- package/dist/services/delegation/index.cjs +0 -6
- package/dist/services/delegation/index.cjs.map +0 -1
- package/dist/services/delegation/index.d.cts.map +0 -1
- package/dist/services/delegation/index.d.mts.map +0 -1
- package/dist/services/delegation/index.mjs +0 -6
- package/dist/services/delegation/index.mjs.map +0 -1
- package/dist/services/delegationPlatform/index.cjs +0 -2
- package/dist/services/delegationPlatform/index.cjs.map +0 -1
- package/dist/services/delegationPlatform/index.mjs +0 -2
- package/dist/services/delegationPlatform/index.mjs.map +0 -1
- package/dist/services/invariants/index.cjs +0 -2
- package/dist/services/invariants/index.cjs.map +0 -1
- package/dist/services/invariants/index.d.cts.map +0 -1
- package/dist/services/invariants/index.d.mts.map +0 -1
- package/dist/services/invariants/index.mjs +0 -2
- package/dist/services/invariants/index.mjs.map +0 -1
- package/dist/services/logSinkTelemetry/index.cjs +0 -2
- package/dist/services/logSinkTelemetry/index.cjs.map +0 -1
- package/dist/services/logSinkTelemetry/index.d.cts.map +0 -1
- package/dist/services/logSinkTelemetry/index.d.mts.map +0 -1
- package/dist/services/logSinkTelemetry/index.mjs +0 -2
- package/dist/services/logSinkTelemetry/index.mjs.map +0 -1
- package/dist/services/paths/index.cjs +0 -2
- package/dist/services/paths/index.cjs.map +0 -1
- package/dist/services/paths/index.d.cts.map +0 -1
- package/dist/services/paths/index.d.mts.map +0 -1
- package/dist/services/paths/index.mjs +0 -2
- package/dist/services/paths/index.mjs.map +0 -1
- package/dist/services/processLiveness/index.cjs +0 -2
- package/dist/services/processLiveness/index.cjs.map +0 -1
- package/dist/services/processLiveness/index.d.cts.map +0 -1
- package/dist/services/processLiveness/index.d.mts.map +0 -1
- package/dist/services/processLiveness/index.mjs +0 -2
- package/dist/services/processLiveness/index.mjs.map +0 -1
- package/dist/services/reconcile/index.cjs +0 -2
- package/dist/services/reconcile/index.cjs.map +0 -1
- package/dist/services/reconcile/index.d.cts.map +0 -1
- package/dist/services/reconcile/index.d.mts.map +0 -1
- package/dist/services/reconcile/index.mjs +0 -2
- package/dist/services/reconcile/index.mjs.map +0 -1
- package/dist/services/reducer/index.cjs +0 -3
- package/dist/services/reducer/index.cjs.map +0 -1
- package/dist/services/reducer/index.d.cts.map +0 -1
- package/dist/services/reducer/index.d.mts.map +0 -1
- package/dist/services/reducer/index.mjs +0 -3
- package/dist/services/reducer/index.mjs.map +0 -1
- package/dist/services/taskNarration/index.cjs +0 -2
- package/dist/services/taskNarration/index.cjs.map +0 -1
- package/dist/services/taskNarration/index.mjs +0 -2
- package/dist/services/taskNarration/index.mjs.map +0 -1
- package/dist/services/taskResult/index.cjs +0 -7
- package/dist/services/taskResult/index.cjs.map +0 -1
- package/dist/services/taskResult/index.d.cts.map +0 -1
- package/dist/services/taskResult/index.d.mts.map +0 -1
- package/dist/services/taskResult/index.mjs +0 -7
- package/dist/services/taskResult/index.mjs.map +0 -1
- package/dist/services/taskStore/index.cjs +0 -2
- package/dist/services/taskStore/index.cjs.map +0 -1
- package/dist/services/taskStore/index.d.cts.map +0 -1
- package/dist/services/taskStore/index.d.mts.map +0 -1
- package/dist/services/taskStore/index.mjs +0 -2
- package/dist/services/taskStore/index.mjs.map +0 -1
- package/dist/tools/task.cjs +0 -3
- package/dist/tools/task.d.cts.map +0 -1
- package/dist/tools/task.d.mts.map +0 -1
- package/dist/tools/task.mjs +0 -3
- package/dist/tools/task.mjs.map +0 -1
- package/dist/tui/format.cjs +0 -4
- package/dist/tui/format.cjs.map +0 -1
- package/dist/tui/format.d.cts.map +0 -1
- package/dist/tui/format.d.mts.map +0 -1
- package/dist/tui/format.mjs +0 -4
- package/dist/tui/format.mjs.map +0 -1
- package/dist/tui/selectors.cjs +0 -2
- package/dist/tui/selectors.cjs.map +0 -1
- package/dist/tui/selectors.d.cts.map +0 -1
- package/dist/tui/selectors.d.mts.map +0 -1
- package/dist/tui/selectors.mjs +0 -2
- package/dist/tui/selectors.mjs.map +0 -1
- package/dist/tui/taskOverlay.cjs +0 -2
- package/dist/tui/taskOverlay.cjs.map +0 -1
- package/dist/tui/taskOverlay.d.cts.map +0 -1
- package/dist/tui/taskOverlay.d.mts.map +0 -1
- package/dist/tui/taskOverlay.mjs +0 -2
- package/dist/tui/taskOverlay.mjs.map +0 -1
- package/dist/tui/taskSpace.cjs +0 -5
- package/dist/tui/taskSpace.cjs.map +0 -1
- package/dist/tui/taskSpace.d.cts.map +0 -1
- package/dist/tui/taskSpace.d.mts.map +0 -1
- package/dist/tui/taskSpace.mjs +0 -5
- package/dist/tui/taskSpace.mjs.map +0 -1
- package/dist/types/delegation.cjs +0 -2
- package/dist/types/delegation.cjs.map +0 -1
- package/dist/types/delegation.mjs +0 -2
- package/dist/types/delegation.mjs.map +0 -1
- package/dist/types/telemetry.cjs +0 -2
- package/dist/types/telemetry.cjs.map +0 -1
- package/dist/types/telemetry.d.cts.map +0 -1
- package/dist/types/telemetry.d.mts.map +0 -1
- package/dist/types/telemetry.mjs +0 -2
- package/dist/types/telemetry.mjs.map +0 -1
- package/dist/types/webTasks.cjs +0 -2
- package/dist/types/webTasks.cjs.map +0 -1
- package/dist/types/webTasks.mjs +0 -2
- package/dist/types/webTasks.mjs.map +0 -1
- package/src/extensions/web.ts +0 -18
- package/src/web/components/TaskDetailDialog.tsx +0 -251
- package/src/web/components/TaskToolMessage.tsx +0 -120
- package/src/web/components/TasksActivitySection.tsx +0 -200
- package/src/web/lib/taskToolFormat.ts +0 -330
- package/src/web/stores/tasksStore.ts +0 -114
- package/src/web/tsconfig.json +0 -23
- /package/dist/{constants → src/constants}/promptGuidelines.d.cts +0 -0
- /package/dist/{constants → src/constants}/promptGuidelines.d.mts +0 -0
- /package/dist/{constants → src/constants}/task.d.cts +0 -0
- /package/dist/{constants → src/constants}/task.d.mts +0 -0
- /package/dist/{models → src/models}/taskGraph.d.cts +0 -0
- /package/dist/{models → src/models}/taskGraph.d.mts +0 -0
- /package/dist/{schemas → src/schemas}/apiContracts.d.cts +0 -0
- /package/dist/{schemas → src/schemas}/apiContracts.d.mts +0 -0
- /package/dist/{schemas → src/schemas}/task.d.cts +0 -0
- /package/dist/{schemas → src/schemas}/task.d.mts +0 -0
- /package/dist/{services → src/services}/config/index.d.cts +0 -0
- /package/dist/{services → src/services}/config/index.d.mts +0 -0
- /package/dist/{services → src/services}/delegation/index.d.cts +0 -0
- /package/dist/{services → src/services}/delegation/index.d.mts +0 -0
- /package/dist/{services → src/services}/invariants/index.d.cts +0 -0
- /package/dist/{services → src/services}/invariants/index.d.mts +0 -0
- /package/dist/{services → src/services}/logSinkTelemetry/index.d.cts +0 -0
- /package/dist/{services → src/services}/logSinkTelemetry/index.d.mts +0 -0
- /package/dist/{services → src/services}/paths/index.d.cts +0 -0
- /package/dist/{services → src/services}/paths/index.d.mts +0 -0
- /package/dist/{services → src/services}/processLiveness/index.d.cts +0 -0
- /package/dist/{services → src/services}/processLiveness/index.d.mts +0 -0
- /package/dist/{services → src/services}/reconcile/index.d.cts +0 -0
- /package/dist/{services → src/services}/reconcile/index.d.mts +0 -0
- /package/dist/{services → src/services}/reducer/index.d.cts +0 -0
- /package/dist/{services → src/services}/reducer/index.d.mts +0 -0
- /package/dist/{services → src/services}/taskResult/index.d.cts +0 -0
- /package/dist/{services → src/services}/taskResult/index.d.mts +0 -0
- /package/dist/{services → src/services}/taskStore/index.d.cts +0 -0
- /package/dist/{services → src/services}/taskStore/index.d.mts +0 -0
- /package/dist/{types → src/types}/delegation.d.cts +0 -0
- /package/dist/{types → src/types}/delegation.d.mts +0 -0
- /package/dist/{types → src/types}/telemetry.d.cts +0 -0
- /package/dist/{types → src/types}/telemetry.d.mts +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/services/delegation/index.ts"],"sourcesContent":["import {\n type DelegationAccepted as DelegationAcceptedPayload,\n DOOM_DELEGATION_ACCEPTED_EVENT,\n DOOM_DELEGATION_FINISHED_EVENT,\n DOOM_DELEGATION_STARTED_EVENT,\n DOOM_DELEGATION_UPDATED_EVENT,\n type DoomDelegationService,\n type DelegationResult,\n type DelegationStarted as DelegationStartedPayload,\n type DelegationUpdate,\n type InlineAgent,\n} from '@agimon-ai/doompi-core/delegation';\nimport type { Context } from '@deepseek-ai/cordis';\n\nimport { isBlocked, isTaskListComplete } from '../../models/taskGraph';\nimport { MAX_BRIEF_FILES } from '../../types/delegation';\nimport { TASK_EVENT, type TaskEventName, type TaskFailureReporter } from '../../types/telemetry';\nimport { reconcileOrphanedDelegations } from '../reconcile';\nimport type { TaskStore } from '../taskStore';\n\nexport { MAX_BRIEF_FILES };\nimport { isDelegationActive, type Task, type TaskDelegation, type TaskDocument } from '../../models/task';\n\nexport const NOTIFY_CUSTOM_TYPE = 'doom-task-notify';\nexport const BACKGROUND_WORK_PROVIDER = 'doom-task';\n\nconst DEFAULT_STARTED_TIMEOUT_MS = 5000;\nconst DEFAULT_RUN_TIMEOUT_MS = 20 * 60 * 1000;\nconst DEFAULT_CANCEL_TIMEOUT_MS = 10_000;\nconst MAX_RUN_TIMEOUT_GRACE_MS = 60_000;\nconst MAX_STORED_OUTPUT = 4000;\n/**\n * Cap on files rendered into a brief. Exported so the tool schema can state the\n * same number to the model rather than restating it and drifting.\n */\nconst MAX_BRIEF_NOTES = 1500;\nconst COMPLETED_STATE = 'completed';\nconst FAILED_STATE = 'failed';\nconst CANCELLED_STATE = 'cancelled';\nconst TIMED_OUT_STATUS = 'timed_out';\nconst DELETED_STATUS: Task['status'] = 'deleted';\n\nconst TASK_ID_ATTRIBUTE = 'task.id';\nconst REQUEST_ID_ATTRIBUTE = 'delegation.request_id';\n// `_name` suffix is load-bearing: the telemetry redactor drops string values\n// whose key has no safe meaning, and a bare `delegation.agent` is dropped.\nconst AGENT_ATTRIBUTE = 'delegation.agent_name';\nconst PID_ATTRIBUTE = 'delegation.pid';\nconst CONTEXT_PRESENT_ATTRIBUTE = 'delegation.context_present';\nconst CONTEXT_FILE_COUNT_ATTRIBUTE = 'delegation.context_file_count';\nconst CONTEXT_NOTES_LENGTH_ATTRIBUTE = 'delegation.context_notes_length';\nconst BRIEF_LENGTH_ATTRIBUTE = 'delegation.brief_length';\nconst TOOL_COUNT_ATTRIBUTE = 'delegation.tool_count';\nconst DURATION_MS_ATTRIBUTE = 'delegation.duration_ms';\nconst OUTCOME_ATTRIBUTE = 'delegation.outcome';\n\ntype SettlementState = typeof COMPLETED_STATE | typeof FAILED_STATE | typeof CANCELLED_STATE;\n\nexport const ERR_NO_RUNTIME =\n 'No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.';\nexport const ERR_CHILD_SESSION =\n 'assign is only available in the main session. Update this task directly instead of re-delegating it.';\nexport const ERR_CANCEL_UNACKNOWLEDGED = 'Subagent did not acknowledge the cancel request';\n\n/** Live progress from a running subagent. Kept in memory: persisting per-tool\n * ticks would rewrite the store file every second for no durable benefit. */\nexport interface DelegationProgress {\n agent: string;\n currentTool?: string;\n toolCount?: number;\n tokens?: number;\n /** Latest child-runtime duration baseline, excluding assignment wait. */\n durationMs?: number;\n /** Wall-clock time at which durationMs was observed or rebased. */\n durationObservedAt?: number;\n /** Assign-time context-pack shape, carried so the completion event can be\n * grouped by it without joining back to the assignment event. */\n contextFileCount?: number;\n contextNotesLength?: number;\n}\n\nexport type DelegationNotifier = (\n message: { customType: string; content: string; display: boolean },\n options?: { triggerTurn?: boolean; deliverAs?: 'steer' | 'followUp' | 'nextTurn' },\n) => void;\n\nexport interface DelegationPlatform {\n readonly environment: Readonly<Record<string, string | undefined>>;\n readonly processId: number;\n readonly createRequestId: () => string;\n readonly formatBriefPath: (entry: string, cwd: string) => string;\n}\n\nexport interface DelegationManagerOptions {\n store: TaskStore;\n cwd: string;\n platform: DelegationPlatform;\n notify?: DelegationNotifier;\n getSessionId?: () => string | undefined;\n onChange?: () => void;\n startedTimeoutMs?: number;\n /** How long a started run may go without reporting a result. */\n runTimeoutMs?: number;\n /** How long to wait for a cancelled run to report back before forcing it. */\n cancelTimeoutMs?: number;\n now?: () => string;\n nowMs?: () => number;\n /** Called when a completion notification could not be delivered. */\n onNotifyError: (error: unknown, taskId: number) => void;\n /** Where other swallowed delegation failures go. */\n report?: TaskFailureReporter;\n}\n\nexport interface AssignOptions {\n agent?: string;\n inlineAgent?: InlineAgent;\n instructions?: string;\n /** Paths the parent already located, rendered into the brief so the child\n * skips rediscovering them. */\n relevantFiles?: string[];\n /** Facts the parent already established, rendered into the brief so the child\n * does not re-derive them. */\n priorFindings?: string;\n model?: string;\n context?: 'fresh' | 'fork';\n signal?: AbortSignal;\n}\n\nexport interface DelegationOutcome {\n ok: boolean;\n message: string;\n}\n\n/** Result of the guarded store mutation that claims a task for delegation. */\ninterface AssignAttempt extends DelegationOutcome {\n task?: Task;\n}\n\ninterface PendingTask {\n readonly taskId: number;\n readonly sessionId?: string;\n}\n\nfunction truncate(value: string | undefined, limit = MAX_STORED_OUTPUT): string | undefined {\n if (!value) return undefined;\n return value.length <= limit ? value : `${value.slice(0, limit)}\\n… (truncated)`;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** The assign-time context pack, normalized once for the brief and the telemetry. */\ninterface BriefContext {\n files: string[];\n notes?: string;\n}\n\n/** Normalize the parent context with host-owned path semantics. */\nfunction briefContext(options: AssignOptions, cwd: string, platform: DelegationPlatform): BriefContext {\n const files = new Set<string>();\n for (const entry of options.relevantFiles ?? []) {\n if (files.size >= MAX_BRIEF_FILES) break;\n const normalized = platform.formatBriefPath(entry.trim(), cwd);\n if (normalized && normalized !== '.') files.add(normalized);\n }\n return { files: [...files], notes: truncate(options.priorFindings?.trim(), MAX_BRIEF_NOTES) };\n}\n\n/**\n * Build the brief handed to the subagent.\n *\n * Doom Team owns the child tool surface and the parent owns the task record.\n * Keeping those responsibilities explicit prevents a child from attempting to\n * call a task tool that is not loaded in its runtime, while still giving it a\n * reliable path to ask the parent for a decision.\n *\n * The context pack is the parent's verified discovery handed over. The whole\n * block is omitted when nothing was supplied: this brief is the child's whole\n * starting context, so an empty section header is pure token cost.\n */\nfunction buildBrief(task: Task, instructions: string | undefined, context: BriefContext): string {\n const sections = [`Task #${task.id}: ${task.subject}`];\n if (task.description) sections.push(task.description);\n if (instructions) sections.push(instructions);\n if (context.files.length > 0 || context.notes) {\n const contextLines = ['Parent context — consume before repository discovery:'];\n if (context.files.length > 0) {\n contextLines.push(`- Parent-verified files (read these first with direct reads): ${context.files.join(', ')}`);\n }\n if (context.notes) {\n contextLines.push(\n `- Established facts (do not re-derive unless direct evidence contradicts them): ${context.notes}`,\n );\n }\n contextLines.push(\n 'This pack satisfies initial repository/context exploration. Do not begin with repository-wide listing, find, or grep. Expand only after consuming the pack and naming a concrete missing dependency or invalid path; search narrowly for that item and state why.',\n );\n sections.push(contextLines.join('\\n'));\n }\n sections.push(\n 'Coordination: work directly without changing the task record; ask main through intercom only for blockers or decisions; report changed files and verification when done.',\n );\n return sections.join('\\n\\n');\n}\n\n/**\n * Owns the lifecycle of tasks delegated to subagents.\n *\n * Delegation rides Team's injected Cordis service rather than spawning\n * processes directly, so doom-task stays decoupled from the subagent runtime\n * and degrades to a clear error when that service is not loaded.\n *\n * Liveness rule: every entry in `pendingTasks` has a timer armed against it, so\n * a delegation always has a deadline no matter which phase it is in. Losing\n * that pairing is what previously left tasks running forever.\n */\nexport class DelegationManager {\n private readonly options: DelegationManagerOptions;\n private readonly progress = new Map<string, DelegationProgress>();\n private readonly pendingTasks = new Map<string, PendingTask>();\n private readonly settlingRequests = new Set<string>();\n private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();\n private readonly subscriptions: Array<() => void> = [];\n private service: DoomDelegationService | undefined;\n\n constructor(options: DelegationManagerOptions) {\n this.options = options;\n }\n\n private now(): string {\n return this.options.now?.() ?? new Date().toISOString();\n }\n\n private nowMs(): number {\n return this.options.nowMs?.() ?? Date.now();\n }\n\n private get runTimeoutMs(): number {\n return this.options.runTimeoutMs ?? DEFAULT_RUN_TIMEOUT_MS;\n }\n\n private report(event: TaskEventName, error: unknown, attributes?: Record<string, string | number | boolean>): void {\n this.options.report?.error(event, error, attributes);\n }\n\n /** True in a session that is itself a subagent child. */\n get isChildSession(): boolean {\n return Boolean(this.options.platform.environment.PI_SUBAGENT_CHILD);\n }\n\n /** Live progress for a task, for the overlay to render. */\n progressFor(task: Task): DelegationProgress | undefined {\n const requestId = task.delegation?.requestId;\n return requestId ? this.progress.get(requestId) : undefined;\n }\n\n /** Displayed runtime duration, rebased from the latest child observation. */\n static elapsedMs(progress: DelegationProgress, nowMs = Date.now()): number {\n const baseline = progress.durationMs ?? 0;\n const observedAt = progress.durationObservedAt ?? nowMs;\n return baseline + Math.max(0, nowMs - observedAt);\n }\n\n /** Rebind to the active Team service without stacking lifecycle listeners. */\n bind(ctx: Context, service: DoomDelegationService): () => void {\n this.unbind();\n this.service = service;\n this.subscriptions.push(\n ctx.on(DOOM_DELEGATION_ACCEPTED_EVENT, (event) => {\n this.handleAccepted(event);\n }),\n ctx.on(DOOM_DELEGATION_STARTED_EVENT, (event) => {\n this.handleStarted(event);\n }),\n ctx.on(DOOM_DELEGATION_UPDATED_EVENT, (event) => {\n this.handleUpdate(event);\n }),\n ctx.on(DOOM_DELEGATION_FINISHED_EVENT, (event) => {\n void this.handleResponse(event).catch((error: unknown) => {\n this.report(TASK_EVENT.delegationResponseFailed, error, { [REQUEST_ID_ATTRIBUTE]: event.requestId });\n });\n }),\n );\n return () => {\n if (this.service === service) this.unbind();\n };\n }\n\n /** Remove only the cross-package binding; task state and watchdogs remain live. */\n unbind(): void {\n for (const unsubscribe of this.subscriptions.splice(0)) unsubscribe();\n this.service = undefined;\n }\n\n /** Items still in flight, surfaced so auto-stop will not kill the harness. */\n listActiveWork(): Array<{ id: string; sessionId: string }> {\n return [...this.pendingTasks.entries()].flatMap(([requestId, pending]) =>\n pending.sessionId ? [{ id: `task-${pending.taskId}:${requestId}`, sessionId: pending.sessionId }] : [],\n );\n }\n\n /**\n * Return tasks nothing can finish to `pending`.\n *\n * The live request set is read inside the mutation so a delegation assigned\n * while the lock was contended is not mistaken for a leftover.\n */\n async reconcile(isCurrent: () => boolean = () => true): Promise<Task[]> {\n const { value } = await this.options.store.mutate((document) => {\n if (!isCurrent()) return { value: [] as Task[] };\n const result = reconcileOrphanedDelegations(document, this.now(), undefined, {\n pid: this.options.platform.processId,\n liveRequestIds: new Set(this.pendingTasks.keys()),\n });\n if (result.orphaned.length === 0) return { value: [] as Task[] };\n return { document: result.document, value: result.orphaned };\n });\n\n if (!isCurrent()) return [];\n for (const task of value) {\n this.options.report?.warn(TASK_EVENT.delegationOrphaned, new Error(task.delegation?.result?.error ?? ''), {\n [TASK_ID_ATTRIBUTE]: task.id,\n ...(task.delegation?.agent ? { [AGENT_ATTRIBUTE]: task.delegation.agent } : {}),\n ...(task.delegation?.pid === undefined ? {} : { [PID_ATTRIBUTE]: task.delegation.pid }),\n });\n }\n\n if (value.length > 0) this.options.onChange?.();\n return value;\n }\n\n async assign(taskId: number, options: AssignOptions): Promise<DelegationOutcome> {\n const agent = options.agent?.trim();\n if (!agent) return { ok: false, message: 'agent required for assign' };\n if (this.isChildSession) return { ok: false, message: ERR_CHILD_SESSION };\n if (options.signal?.aborted) return { ok: false, message: 'delegation cancelled before it started' };\n\n const requestId = this.options.platform.createRequestId();\n const startedAt = this.now();\n const sessionId = this.options.getSessionId?.();\n const context = briefContext(options, this.options.cwd, this.options.platform);\n\n const { value: outcome } = await this.options.store.mutate<AssignAttempt>((current) => {\n const index = current.tasks.findIndex((task) => task.id === taskId);\n if (index === -1) return { value: { ok: false, message: `#${taskId} not found` } };\n\n const task = current.tasks[index];\n if (task.status === DELETED_STATUS) return { value: { ok: false, message: `#${taskId} is deleted` } };\n if (task.status === COMPLETED_STATE) {\n return { value: { ok: false, message: `#${taskId} is already completed` } };\n }\n if (isDelegationActive(task)) {\n return { value: { ok: false, message: `#${taskId} is already delegated to ${task.delegation?.agent}` } };\n }\n if (isBlocked(current.tasks, task)) {\n const blockers = (task.blockedBy ?? []).map((id) => `#${id}`).join(', ');\n return { value: { ok: false, message: `#${taskId} is blocked by ${blockers}` } };\n }\n\n const delegation: TaskDelegation = {\n requestId,\n agent,\n state: 'requested',\n pid: this.options.platform.processId,\n startedAt,\n ...(sessionId ? { sessionId } : {}),\n ...(options.model ? { model: options.model } : {}),\n };\n\n const tasks = [...current.tasks];\n tasks[index] = { ...task, owner: agent, updatedAt: startedAt, delegation };\n return {\n document: { ...current, tasks },\n value: { ok: true, message: '', task: tasks[index] },\n };\n });\n\n if (!outcome.ok || !outcome.task) return { ok: false, message: outcome.message };\n\n const contextNotesLength = context.notes?.length ?? 0;\n this.pendingTasks.set(requestId, { taskId, sessionId });\n this.progress.set(requestId, { agent, contextFileCount: context.files.length, contextNotesLength });\n this.armStartedTimeout(requestId);\n this.options.onChange?.();\n const request = {\n requestId,\n taskId,\n agent,\n ...(options.inlineAgent ? { inlineAgent: options.inlineAgent } : {}),\n prompt: buildBrief(outcome.task, options.instructions, context),\n ...(options.context ? { context: options.context } : {}),\n cwd: this.options.cwd,\n artifacts: true,\n timeoutMs: this.runTimeoutMs,\n runMode: 'detached' as const,\n teamTask: { id: String(outcome.task.id), subject: outcome.task.subject },\n ...(options.model ? { model: options.model } : {}),\n };\n\n try {\n const service = this.service;\n if (!service) throw new Error(ERR_NO_RUNTIME);\n void service.request(request).catch((error: unknown) => {\n this.report(TASK_EVENT.delegationRequestFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n });\n this.settleDetached(requestId, FAILED_STATE, {\n status: FAILED_STATE,\n error: `Delegation request failed: ${messageOf(error)}`,\n });\n });\n } catch (error) {\n this.report(TASK_EVENT.delegationRequestFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n });\n const detail = messageOf(error);\n await this.settle(requestId, FAILED_STATE, {\n status: FAILED_STATE,\n error: `Delegation request failed: ${detail}`,\n });\n return { ok: false, message: `Could not dispatch #${taskId} to ${agent}: ${detail}` };\n }\n\n // Recorded only after the service accepted the request call, so it means a\n // brief actually entered Team's state machine rather than merely being assembled.\n this.options.report?.event(TASK_EVENT.delegationAssigned, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n [CONTEXT_PRESENT_ATTRIBUTE]: context.files.length > 0 || contextNotesLength > 0,\n [CONTEXT_FILE_COUNT_ATTRIBUTE]: context.files.length,\n [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: contextNotesLength,\n [BRIEF_LENGTH_ATTRIBUTE]: request.prompt.length,\n });\n\n return {\n ok: true,\n message: `Delegated #${taskId} to ${agent} in the background. It runs independently of this turn and will notify you when it finishes. Continue non-overlapping work, or end your turn.`,\n };\n }\n\n async cancel(taskId: number): Promise<DelegationOutcome> {\n const document = this.options.store.read();\n const task = document.tasks.find((candidate) => candidate.id === taskId);\n if (!task) return { ok: false, message: `#${taskId} not found` };\n if (!task.delegation || !isDelegationActive(task)) {\n return { ok: false, message: `#${taskId} has no running delegation` };\n }\n\n const { requestId } = task.delegation;\n this.service?.cancel({ requestId });\n // Only this session can force the outcome; a delegation owned elsewhere\n // gets the request and nothing more.\n this.armCancelTimeout(requestId);\n return { ok: true, message: `Cancelling delegation for #${taskId} (${task.delegation.agent})` };\n }\n\n /** Settle without awaiting, reporting rather than dropping a failure. */\n private settleDetached(\n requestId: string,\n state: SettlementState,\n result: TaskDelegation['result'],\n event: TaskEventName = TASK_EVENT.delegationSettleFailed,\n ): void {\n void this.settle(requestId, state, result).catch((error: unknown) => {\n this.report(event, error, { [REQUEST_ID_ATTRIBUTE]: requestId });\n });\n }\n\n /**\n * Fail a delegation that nobody acknowledged.\n *\n * Provider loss or a stalled Team runtime can still leave a dispatched\n * request silent. Without this acknowledgement deadline the task would sit\n * in `requested` forever.\n */\n private armStartedTimeout(requestId: string): void {\n this.armTimer(requestId, this.options.startedTimeoutMs ?? DEFAULT_STARTED_TIMEOUT_MS, () => {\n this.settleDetached(requestId, FAILED_STATE, { status: FAILED_STATE, error: ERR_NO_RUNTIME });\n });\n }\n\n /**\n * Bound a run that already started.\n *\n * The request carries the same budget, so in the normal case the runtime ends\n * the run itself and reports a richer result. The grace period biases toward\n * that answer; this timer only covers a runtime that goes silent, which is\n * precisely the case where no response event will ever arrive.\n */\n private armRunTimeout(requestId: string): void {\n const grace = Math.min(MAX_RUN_TIMEOUT_GRACE_MS, this.runTimeoutMs);\n this.armTimer(requestId, this.runTimeoutMs + grace, () => {\n const taskId = this.pendingTasks.get(requestId)?.taskId;\n const agent = this.progress.get(requestId)?.agent;\n const error = new Error(`Delegation produced no result within ${this.runTimeoutMs}ms`);\n this.options.report?.warn(TASK_EVENT.delegationTimedOut, error, {\n ...(taskId === undefined ? {} : { [TASK_ID_ATTRIBUTE]: taskId }),\n [REQUEST_ID_ATTRIBUTE]: requestId,\n ...(agent ? { [AGENT_ATTRIBUTE]: agent } : {}),\n });\n this.service?.cancel({ requestId, reason: error.message });\n this.settleDetached(requestId, FAILED_STATE, { status: TIMED_OUT_STATUS, error: error.message });\n });\n }\n\n /**\n * Guarantee a cancel reaches a terminal state.\n *\n * Calling the service is a request, not an outcome: a runtime that has\n * already forgotten the request answers nothing at all. The window still\n * favours a real response, which carries the run's partial output.\n */\n private armCancelTimeout(requestId: string): void {\n if (!this.pendingTasks.has(requestId)) return;\n this.armTimer(requestId, this.options.cancelTimeoutMs ?? DEFAULT_CANCEL_TIMEOUT_MS, () => {\n this.settleDetached(requestId, CANCELLED_STATE, {\n status: CANCELLED_STATE,\n error: ERR_CANCEL_UNACKNOWLEDGED,\n });\n });\n }\n\n private armTimer(requestId: string, delayMs: number, onFire: () => void): void {\n this.clearTimer(requestId);\n const timer = setTimeout(onFire, delayMs);\n timer.unref?.();\n this.timers.set(requestId, timer);\n }\n\n private clearTimer(requestId: string): void {\n const timer = this.timers.get(requestId);\n if (timer) clearTimeout(timer);\n this.timers.delete(requestId);\n }\n\n /** Runtime acknowledgement moves the request off the short extension-presence watchdog while launch is in flight. */\n private handleAccepted(event: DelegationAcceptedPayload): void {\n if (!this.pendingTasks.has(event.requestId)) return;\n this.armRunTimeout(event.requestId);\n }\n\n private handleStarted(event: DelegationStartedPayload): void {\n const { runId } = event;\n const taskId = this.pendingTasks.get(event.requestId)?.taskId;\n if (taskId === undefined) return;\n this.armRunTimeout(event.requestId);\n const existing = this.progress.get(event.requestId);\n if (existing) {\n this.progress.set(event.requestId, {\n ...existing,\n durationMs: existing.durationMs ?? 0,\n durationObservedAt: existing.durationObservedAt ?? this.nowMs(),\n });\n }\n\n void this.options.store\n .mutate((document) =>\n this.patchDelegation(document, event.requestId, (task, delegation) => ({\n ...task,\n status: task.status === COMPLETED_STATE ? task.status : 'in_progress',\n delegation: {\n ...delegation,\n state: 'running',\n startedAt: delegation.startedAt ?? this.now(),\n ...(runId ? { runId } : {}),\n },\n })),\n )\n .then(() => this.options.onChange?.())\n .catch((error: unknown) => {\n this.report(TASK_EVENT.delegationStartFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: event.requestId,\n });\n });\n }\n\n private handleUpdate(event: DelegationUpdate): void {\n const existing = this.progress.get(event.requestId);\n if (!existing) return;\n\n const observedAt = this.nowMs();\n const currentElapsed = DelegationManager.elapsedMs(existing, observedAt);\n const hasDuration = event.durationMs !== undefined;\n this.progress.set(event.requestId, {\n // Spread, not field-by-field: anything carried on progress that this\n // event does not report (the assign-time context shape) must survive the\n // first update, or the completion event reports it as absent.\n ...existing,\n currentTool: event.currentTool ?? existing.currentTool,\n toolCount:\n event.toolCount === undefined ? existing.toolCount : Math.max(existing.toolCount ?? 0, event.toolCount),\n tokens: event.tokens === undefined ? existing.tokens : Math.max(existing.tokens ?? 0, event.tokens),\n durationMs: hasDuration ? Math.max(currentElapsed, event.durationMs!) : existing.durationMs,\n durationObservedAt: hasDuration ? observedAt : existing.durationObservedAt,\n });\n this.options.onChange?.();\n }\n\n private async handleResponse(event: DelegationResult): Promise<void> {\n if (!this.pendingTasks.has(event.requestId)) return;\n\n const succeeded = event.status === COMPLETED_STATE && !event.error;\n const state = succeeded ? COMPLETED_STATE : event.status === CANCELLED_STATE ? CANCELLED_STATE : FAILED_STATE;\n await this.settle(event.requestId, state, {\n status: event.status,\n error: event.error,\n output: truncate(event.output),\n outputPath: event.outputPath,\n sessionFile: event.sessionFile,\n durationMs: event.durationMs,\n toolCount: event.toolCount,\n });\n }\n\n /**\n * Apply the terminal state of a delegation and tell the model about it.\n *\n * A cancelled run returns the task to `pending` (the work is still wanted,\n * just not by that agent); a failure marks it `failed` so it stays visible\n * rather than silently rejoining the backlog.\n *\n * The request is claimed in `settlingRequests` while it remains published as\n * active work. It is removed only after the terminal state and model notification\n * have been handed off, so an auto-stop observer cannot end the session between\n * receiving the result and delivering it to the model.\n */\n private async settle(requestId: string, state: SettlementState, result: TaskDelegation['result']): Promise<void> {\n const pending = this.pendingTasks.get(requestId);\n if (!pending || this.settlingRequests.has(requestId)) return;\n this.settlingRequests.add(requestId);\n this.clearTimer(requestId);\n const { taskId } = pending;\n const progress = this.progress.get(requestId);\n\n try {\n const endedAt = this.now();\n let task: Task | undefined;\n try {\n const { value } = await this.options.store.mutate((document) =>\n this.patchDelegation(document, requestId, (current, delegation) => ({\n ...current,\n status: state === COMPLETED_STATE ? COMPLETED_STATE : state === CANCELLED_STATE ? 'pending' : FAILED_STATE,\n updatedAt: endedAt,\n delegation: { ...delegation, state, endedAt, ...(result ? { result } : {}) },\n })),\n );\n task = value;\n } catch (error) {\n this.report(TASK_EVENT.delegationSettleFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n });\n }\n\n const agent = task?.delegation?.agent ?? progress?.agent ?? 'subagent';\n const subject = task?.subject ?? `#${taskId}`;\n\n // Repeats the assign-time context shape so the cost question (\"did packs\n // reduce child tool calls?\") is one grouping rather than a self-join.\n // A run that never started reports neither metric, keeping the medians clean.\n this.options.report?.event(TASK_EVENT.delegationCompleted, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n [OUTCOME_ATTRIBUTE]: state,\n [CONTEXT_PRESENT_ATTRIBUTE]: (progress?.contextFileCount ?? 0) > 0 || (progress?.contextNotesLength ?? 0) > 0,\n [CONTEXT_FILE_COUNT_ATTRIBUTE]: progress?.contextFileCount ?? 0,\n [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: progress?.contextNotesLength ?? 0,\n ...(result?.toolCount === undefined ? {} : { [TOOL_COUNT_ATTRIBUTE]: result.toolCount }),\n ...(result?.durationMs === undefined ? {} : { [DURATION_MS_ATTRIBUTE]: result.durationMs }),\n });\n const listComplete =\n state === COMPLETED_STATE && task !== undefined && isTaskListComplete(this.options.store.snapshot.tasks);\n this.notifyModel(state, taskId, subject, agent, result, listComplete);\n } finally {\n this.pendingTasks.delete(requestId);\n this.progress.delete(requestId);\n this.settlingRequests.delete(requestId);\n this.options.onChange?.();\n }\n }\n\n private notifyModel(\n state: SettlementState,\n taskId: number,\n subject: string,\n agent: string,\n result: TaskDelegation['result'],\n listComplete: boolean,\n ): void {\n const notify = this.options.notify;\n if (!notify) return;\n\n const headline =\n state === COMPLETED_STATE\n ? `Subagent ${agent} completed task #${taskId}: ${subject}`\n : state === CANCELLED_STATE\n ? `Subagent ${agent} was cancelled on task #${taskId}: ${subject} (returned to pending)`\n : `Subagent ${agent} failed task #${taskId}: ${subject}`;\n\n const lines = [headline];\n if (listComplete) {\n lines.push(\n '',\n 'All tasks are completed. Review the full task list once more, then close it with task {\"action\":\"clear\"}.',\n );\n }\n if (result?.error) lines.push(`Error: ${result.error}`);\n if (result?.output) lines.push('', result.output);\n if (result?.outputPath) lines.push('', `Full output: ${result.outputPath}`);\n\n try {\n notify(\n { customType: NOTIFY_CUSTOM_TYPE, content: lines.join('\\n'), display: true },\n { triggerTurn: true, deliverAs: 'steer' },\n );\n } catch (error) {\n // The delegation state is already committed to the store, so a failed\n // notification costs the model its wake-up, not the result. Report it\n // rather than rethrowing, which would strand the settled run.\n this.options.onNotifyError(error, taskId);\n }\n }\n\n /**\n * Rewrite the task carrying `requestId`, returning the updated task as the mutation value.\n *\n * Terminal delegations are left alone. The document here is the freshest one,\n * read under the store lock, which is the only place the check is meaningful:\n * a `started` event can land after a cancel already settled the run, and\n * without this guard its write would resurrect a delegation that nothing is\n * tracking any more.\n */\n private patchDelegation(\n document: TaskDocument,\n requestId: string,\n patch: (task: Task, delegation: TaskDelegation) => Task,\n ): { document?: TaskDocument; value: Task | undefined } {\n const index = document.tasks.findIndex((task) => task.delegation?.requestId === requestId);\n if (index === -1) return { value: undefined };\n\n const task = document.tasks[index];\n if (!isDelegationActive(task)) return { value: task };\n\n const updated = patch(task, task.delegation!);\n if (updated === task) return { value: task };\n const tasks = [...document.tasks];\n tasks[index] = updated;\n return { document: { ...document, tasks }, value: updated };\n }\n\n dispose(): void {\n this.unbind();\n this.reset();\n }\n\n /** Clear one Pi session's transient delegation state without losing service injection. */\n reset(): void {\n const changed = this.pendingTasks.size > 0 || this.progress.size > 0;\n for (const timer of this.timers.values()) clearTimeout(timer);\n this.timers.clear();\n this.pendingTasks.clear();\n this.settlingRequests.clear();\n this.progress.clear();\n if (changed) this.options.onChange?.();\n }\n}\n"],"mappings":"igBAuBA,MAAa,EAAqB,mBACrB,EAA2B,YAYlC,EAAkB,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AK,OAAO,MAAM,EAClB,KAAK,aAAa,MAAM,EACxB,KAAK,iBAAiB,MAAM,EAC5B,KAAK,SAAS,MAAM,EAChB,GAAS,KAAK,QAAQ,WAAW,CACvC,CACF"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("../../_virtual/_rolldown/runtime.cjs");let t=require("node:path");t=e.__toESM(t,1);let n=require("node:crypto");function r(e,n){if(!t.default.isAbsolute(e))return t.default.normalize(e);let r=t.default.relative(n,e);return r&&!r.startsWith(`..`)?r:e}function i(e=process.env){return{environment:e,processId:process.pid,createRequestId:n.randomUUID,formatBriefPath:r}}exports.createNodeDelegationPlatform=i;
|
|
2
|
-
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["path","randomUUID"],"sources":["../../../src/services/delegationPlatform/index.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport path from 'node:path';\n\nimport type { DelegationPlatform } from '../delegation';\n\nfunction formatBriefPath(entry: string, cwd: string): string {\n if (!path.isAbsolute(entry)) return path.normalize(entry);\n const relative = path.relative(cwd, entry);\n // Outside the run directory the original beats a `../../` chain.\n return relative && !relative.startsWith('..') ? relative : entry;\n}\n\n/** Supply Node-owned process and path facilities to the host-neutral manager. */\nexport function createNodeDelegationPlatform(\n environment: Readonly<Record<string, string | undefined>> = process.env,\n): DelegationPlatform {\n return {\n environment,\n processId: process.pid,\n createRequestId: randomUUID,\n formatBriefPath,\n };\n}\n"],"mappings":"iIAKA,SAAS,EAAgB,EAAe,EAAqB,CAC3D,GAAI,CAACA,EAAAA,QAAK,WAAW,CAAK,EAAG,OAAOA,EAAAA,QAAK,UAAU,CAAK,EACxD,IAAM,EAAWA,EAAAA,QAAK,SAAS,EAAK,CAAK,EAEzC,OAAO,GAAY,CAAC,EAAS,WAAW,IAAI,EAAI,EAAW,CAC7D,CAGA,SAAgB,EACd,EAA4D,QAAQ,IAChD,CACpB,MAAO,CACL,cACA,UAAW,QAAQ,IACnB,gBAAiBC,EAAAA,WACjB,iBACF,CACF"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import e from"node:path";import{randomUUID as t}from"node:crypto";function n(t,n){if(!e.isAbsolute(t))return e.normalize(t);let r=e.relative(n,t);return r&&!r.startsWith(`..`)?r:t}function r(e=process.env){return{environment:e,processId:process.pid,createRequestId:t,formatBriefPath:n}}export{r as createNodeDelegationPlatform};
|
|
2
|
-
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/services/delegationPlatform/index.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport path from 'node:path';\n\nimport type { DelegationPlatform } from '../delegation';\n\nfunction formatBriefPath(entry: string, cwd: string): string {\n if (!path.isAbsolute(entry)) return path.normalize(entry);\n const relative = path.relative(cwd, entry);\n // Outside the run directory the original beats a `../../` chain.\n return relative && !relative.startsWith('..') ? relative : entry;\n}\n\n/** Supply Node-owned process and path facilities to the host-neutral manager. */\nexport function createNodeDelegationPlatform(\n environment: Readonly<Record<string, string | undefined>> = process.env,\n): DelegationPlatform {\n return {\n environment,\n processId: process.pid,\n createRequestId: randomUUID,\n formatBriefPath,\n };\n}\n"],"mappings":"kEAKA,SAAS,EAAgB,EAAe,EAAqB,CAC3D,GAAI,CAAC,EAAK,WAAW,CAAK,EAAG,OAAO,EAAK,UAAU,CAAK,EACxD,IAAM,EAAW,EAAK,SAAS,EAAK,CAAK,EAEzC,OAAO,GAAY,CAAC,EAAS,WAAW,IAAI,EAAI,EAAW,CAC7D,CAGA,SAAgB,EACd,EAA4D,QAAQ,IAChD,CACpB,MAAO,CACL,cACA,UAAW,QAAQ,IACnB,gBAAiB,EACjB,iBACF,CACF"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
function e(e){let t=[],n=new Map;for(let r of e){let e=n.get(r.id);if(e===void 0){n.set(r.id,t.length),t.push(r);continue}let i=t[e];(!i.updatedAt||!r.updatedAt||r.updatedAt>=i.updatedAt)&&(t[e]=r)}return t}const t={pending:new Set([`in_progress`,`completed`,`failed`,`deleted`]),in_progress:new Set([`pending`,`completed`,`failed`,`deleted`]),failed:new Set([`pending`,`in_progress`,`completed`,`deleted`]),completed:new Set([`deleted`]),deleted:new Set};function n(e,n){return e===n||t[e].has(n)}exports.VALID_TRANSITIONS=t,exports.canonicalizeTasks=e,exports.isTransitionValid=n;
|
|
2
|
-
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../../../src/services/invariants/index.ts"],"sourcesContent":["import type { Task, TaskStatus } from '../../models/task';\n\n/**\n * Collapse a malformed snapshot to one row per task id.\n *\n * Normal writes replace tasks in place, but older or externally edited stores\n * can contain both a stale and a current copy. Prefer the copy with the newest\n * ISO update timestamp; equal or missing timestamps use the later array entry.\n * The winning row keeps the id's original position so repair does not reorder\n * an otherwise stable task list.\n */\nexport function canonicalizeTasks(tasks: readonly Task[]): Task[] {\n const canonical: Task[] = [];\n const indexById = new Map<number, number>();\n\n for (const task of tasks) {\n const existingIndex = indexById.get(task.id);\n if (existingIndex === undefined) {\n indexById.set(task.id, canonical.length);\n canonical.push(task);\n continue;\n }\n\n const existing = canonical[existingIndex];\n if (!existing.updatedAt || !task.updatedAt || task.updatedAt >= existing.updatedAt) {\n canonical[existingIndex] = task;\n }\n }\n\n return canonical;\n}\n\n/**\n * Allowed forward transitions per source status.\n *\n * `failed` is recoverable (a delegation can be retried) so it may return to\n * pending or in_progress. `completed` is one-way to `deleted`; `deleted` is a\n * terminal tombstone.\n */\nexport const VALID_TRANSITIONS: Record<TaskStatus, ReadonlySet<TaskStatus>> = {\n pending: new Set<TaskStatus>(['in_progress', 'completed', 'failed', 'deleted']),\n in_progress: new Set<TaskStatus>(['pending', 'completed', 'failed', 'deleted']),\n failed: new Set<TaskStatus>(['pending', 'in_progress', 'completed', 'deleted']),\n completed: new Set<TaskStatus>(['deleted']),\n deleted: new Set<TaskStatus>(),\n};\n\nexport function isTransitionValid(from: TaskStatus, to: TaskStatus): boolean {\n if (from === to) return true;\n return VALID_TRANSITIONS[from].has(to);\n}\n"],"mappings":"AAWA,SAAgB,EAAkB,EAAgC,CAChE,IAAM,EAAoB,CAAC,EACrB,EAAY,IAAI,IAEtB,IAAK,IAAM,KAAQ,EAAO,CACxB,IAAM,EAAgB,EAAU,IAAI,EAAK,EAAE,EAC3C,GAAI,IAAkB,IAAA,GAAW,CAC/B,EAAU,IAAI,EAAK,GAAI,EAAU,MAAM,EACvC,EAAU,KAAK,CAAI,EACnB,QACF,CAEA,IAAM,EAAW,EAAU,IACvB,CAAC,EAAS,WAAa,CAAC,EAAK,WAAa,EAAK,WAAa,EAAS,aACvE,EAAU,GAAiB,EAE/B,CAEA,OAAO,CACT,CASA,MAAa,EAAiE,CAC5E,QAAS,IAAI,IAAgB,CAAC,cAAe,YAAa,SAAU,SAAS,CAAC,EAC9E,YAAa,IAAI,IAAgB,CAAC,UAAW,YAAa,SAAU,SAAS,CAAC,EAC9E,OAAQ,IAAI,IAAgB,CAAC,UAAW,cAAe,YAAa,SAAS,CAAC,EAC9E,UAAW,IAAI,IAAgB,CAAC,SAAS,CAAC,EAC1C,QAAS,IAAI,GACf,EAEA,SAAgB,EAAkB,EAAkB,EAAyB,CAE3E,OADI,IAAS,GACN,EAAkB,EAAK,CAAC,IAAI,CAAE,CACvC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../../../src/services/invariants/index.ts"],"mappings":";;;;;;;;;;;wBAWgB,kBAAkB,gBAAgB,SAAS;;;;;;;;qBA4B9C,mBAAmB,OAAO,YAAY,YAAY;wBAQ/C,kBAAkB,MAAM,YAAY,IAAI"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/invariants/index.ts"],"mappings":";;;;;;;;;;;wBAWgB,kBAAkB,gBAAgB,SAAS;;;;;;;;qBA4B9C,mBAAmB,OAAO,YAAY,YAAY;wBAQ/C,kBAAkB,MAAM,YAAY,IAAI"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
function e(e){let t=[],n=new Map;for(let r of e){let e=n.get(r.id);if(e===void 0){n.set(r.id,t.length),t.push(r);continue}let i=t[e];(!i.updatedAt||!r.updatedAt||r.updatedAt>=i.updatedAt)&&(t[e]=r)}return t}const t={pending:new Set([`in_progress`,`completed`,`failed`,`deleted`]),in_progress:new Set([`pending`,`completed`,`failed`,`deleted`]),failed:new Set([`pending`,`in_progress`,`completed`,`deleted`]),completed:new Set([`deleted`]),deleted:new Set};function n(e,n){return e===n||t[e].has(n)}export{t as VALID_TRANSITIONS,e as canonicalizeTasks,n as isTransitionValid};
|
|
2
|
-
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/services/invariants/index.ts"],"sourcesContent":["import type { Task, TaskStatus } from '../../models/task';\n\n/**\n * Collapse a malformed snapshot to one row per task id.\n *\n * Normal writes replace tasks in place, but older or externally edited stores\n * can contain both a stale and a current copy. Prefer the copy with the newest\n * ISO update timestamp; equal or missing timestamps use the later array entry.\n * The winning row keeps the id's original position so repair does not reorder\n * an otherwise stable task list.\n */\nexport function canonicalizeTasks(tasks: readonly Task[]): Task[] {\n const canonical: Task[] = [];\n const indexById = new Map<number, number>();\n\n for (const task of tasks) {\n const existingIndex = indexById.get(task.id);\n if (existingIndex === undefined) {\n indexById.set(task.id, canonical.length);\n canonical.push(task);\n continue;\n }\n\n const existing = canonical[existingIndex];\n if (!existing.updatedAt || !task.updatedAt || task.updatedAt >= existing.updatedAt) {\n canonical[existingIndex] = task;\n }\n }\n\n return canonical;\n}\n\n/**\n * Allowed forward transitions per source status.\n *\n * `failed` is recoverable (a delegation can be retried) so it may return to\n * pending or in_progress. `completed` is one-way to `deleted`; `deleted` is a\n * terminal tombstone.\n */\nexport const VALID_TRANSITIONS: Record<TaskStatus, ReadonlySet<TaskStatus>> = {\n pending: new Set<TaskStatus>(['in_progress', 'completed', 'failed', 'deleted']),\n in_progress: new Set<TaskStatus>(['pending', 'completed', 'failed', 'deleted']),\n failed: new Set<TaskStatus>(['pending', 'in_progress', 'completed', 'deleted']),\n completed: new Set<TaskStatus>(['deleted']),\n deleted: new Set<TaskStatus>(),\n};\n\nexport function isTransitionValid(from: TaskStatus, to: TaskStatus): boolean {\n if (from === to) return true;\n return VALID_TRANSITIONS[from].has(to);\n}\n"],"mappings":"AAWA,SAAgB,EAAkB,EAAgC,CAChE,IAAM,EAAoB,CAAC,EACrB,EAAY,IAAI,IAEtB,IAAK,IAAM,KAAQ,EAAO,CACxB,IAAM,EAAgB,EAAU,IAAI,EAAK,EAAE,EAC3C,GAAI,IAAkB,IAAA,GAAW,CAC/B,EAAU,IAAI,EAAK,GAAI,EAAU,MAAM,EACvC,EAAU,KAAK,CAAI,EACnB,QACF,CAEA,IAAM,EAAW,EAAU,IACvB,CAAC,EAAS,WAAa,CAAC,EAAK,WAAa,EAAK,WAAa,EAAS,aACvE,EAAU,GAAiB,EAE/B,CAEA,OAAO,CACT,CASA,MAAa,EAAiE,CAC5E,QAAS,IAAI,IAAgB,CAAC,cAAe,YAAa,SAAU,SAAS,CAAC,EAC9E,YAAa,IAAI,IAAgB,CAAC,UAAW,YAAa,SAAU,SAAS,CAAC,EAC9E,OAAQ,IAAI,IAAgB,CAAC,UAAW,cAAe,YAAa,SAAS,CAAC,EAC9E,UAAW,IAAI,IAAgB,CAAC,SAAS,CAAC,EAC1C,QAAS,IAAI,GACf,EAEA,SAAgB,EAAkB,EAAkB,EAAyB,CAE3E,OADI,IAAS,GACN,EAAkB,EAAK,CAAC,IAAI,CAAE,CACvC"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("../../types/telemetry.cjs");let t=require("@agimon-ai/doompi-telemetry");function n(n={}){let r=(0,t.createDoomTelemetry)({serviceName:`doom-task`,packageName:`@agimon-ai/doompi-task`,cwd:n.cwd,workspaceRoot:n.workspaceRoot,env:n.env,telemetryFactory:n.telemetryFactory,warn:n.warn,enableLogs:!0,enableTraces:!0});return{recordError:(e,t,n)=>r.recordError(e,t,n),recordWarning:(e,t,n)=>r.recordWarning(e,t,n),recordEvent:(e,t)=>r.recordEvent(e,t),recordNotificationError:(t,n)=>r.recordError(e.TASK_EVENT.notificationFailed,t,{"task.id":n,"task.operation":`completion_notification`}),flush:()=>r.flush(),shutdown:()=>r.shutdown()}}function r(e){return{error:(t,n,r)=>void e.recordError(t,n,r),warn:(t,n,r)=>void e.recordWarning(t,n,r),event:(t,n)=>void e.recordEvent(t,n)}}exports.TASK_EVENT=e.TASK_EVENT,exports.createTaskErrorReporter=n,exports.toFailureReporter=r;
|
|
2
|
-
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["createDoomTelemetry","TASK_EVENT"],"sources":["../../../src/services/logSinkTelemetry/index.ts"],"sourcesContent":["import { createDoomTelemetry, type DoomTelemetry, type DoomTelemetryOptions } from '@agimon-ai/doompi-telemetry';\n\nimport { TASK_EVENT, type TaskErrorAttributes, type TaskFailureReporter } from '../../types/telemetry';\n\nexport {\n TASK_EVENT,\n type TaskErrorAttributes,\n type TaskErrorSink,\n type TaskEventName,\n type TaskEventSink,\n type TaskFailureReporter,\n} from '../../types/telemetry';\n\nconst SERVICE_NAME = 'doom-task';\nconst PACKAGE_NAME = '@agimon-ai/doompi-task';\nconst NOTIFICATION_OPERATION = 'completion_notification';\n\nexport interface TaskErrorReporterOptions {\n cwd?: string;\n workspaceRoot?: string;\n env?: NodeJS.ProcessEnv;\n telemetryFactory?: NonNullable<DoomTelemetryOptions['telemetryFactory']>;\n warn?: (message: string) => void;\n}\n\nexport interface TaskErrorReporter {\n recordError(event: string, error: unknown, attributes?: TaskErrorAttributes): Promise<void>;\n recordWarning(event: string, error: unknown, attributes?: TaskErrorAttributes): Promise<void>;\n recordEvent(event: string, attributes?: TaskErrorAttributes): Promise<void>;\n recordNotificationError(error: unknown, taskId: number): Promise<void>;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nexport function createTaskErrorReporter(options: TaskErrorReporterOptions = {}): TaskErrorReporter {\n const telemetry: DoomTelemetry = createDoomTelemetry({\n serviceName: SERVICE_NAME,\n packageName: PACKAGE_NAME,\n cwd: options.cwd,\n workspaceRoot: options.workspaceRoot,\n env: options.env,\n telemetryFactory: options.telemetryFactory,\n warn: options.warn,\n enableLogs: true,\n enableTraces: true,\n });\n return {\n recordError: (event, error, attributes) => telemetry.recordError(event, error, attributes),\n recordWarning: (event, error, attributes) => telemetry.recordWarning(event, error, attributes),\n recordEvent: (event, attributes) => telemetry.recordEvent(event, attributes),\n recordNotificationError: (error, taskId) =>\n telemetry.recordError(TASK_EVENT.notificationFailed, error, {\n 'task.id': taskId,\n 'task.operation': NOTIFICATION_OPERATION,\n }),\n flush: () => telemetry.flush(),\n shutdown: () => telemetry.shutdown(),\n };\n}\n\nexport function toFailureReporter(reporter: TaskErrorReporter): TaskFailureReporter {\n return {\n error: (event, error, attributes) => void reporter.recordError(event, error, attributes),\n warn: (event, error, attributes) => void reporter.recordWarning(event, error, attributes),\n event: (event, attributes) => void reporter.recordEvent(event, attributes),\n };\n}\n"],"mappings":"0FAkCA,SAAgB,EAAwB,EAAoC,CAAC,EAAsB,CACjG,IAAM,GAAA,EAA2BA,EAAAA,oBAAAA,CAAoB,CACnD,YAAa,YACb,YAAa,yBACb,IAAK,EAAQ,IACb,cAAe,EAAQ,cACvB,IAAK,EAAQ,IACb,iBAAkB,EAAQ,iBAC1B,KAAM,EAAQ,KACd,WAAY,GACZ,aAAc,EAChB,CAAC,EACD,MAAO,CACL,aAAc,EAAO,EAAO,IAAe,EAAU,YAAY,EAAO,EAAO,CAAU,EACzF,eAAgB,EAAO,EAAO,IAAe,EAAU,cAAc,EAAO,EAAO,CAAU,EAC7F,aAAc,EAAO,IAAe,EAAU,YAAY,EAAO,CAAU,EAC3E,yBAA0B,EAAO,IAC/B,EAAU,YAAYC,EAAAA,WAAW,mBAAoB,EAAO,CAC1D,UAAW,EACX,iBAAkB,yBACpB,CAAC,EACH,UAAa,EAAU,MAAM,EAC7B,aAAgB,EAAU,SAAS,CACrC,CACF,CAEA,SAAgB,EAAkB,EAAkD,CAClF,MAAO,CACL,OAAQ,EAAO,EAAO,IAAe,KAAK,EAAS,YAAY,EAAO,EAAO,CAAU,EACvF,MAAO,EAAO,EAAO,IAAe,KAAK,EAAS,cAAc,EAAO,EAAO,CAAU,EACxF,OAAQ,EAAO,IAAe,KAAK,EAAS,YAAY,EAAO,CAAU,CAC3E,CACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../../../src/services/logSinkTelemetry/index.ts"],"mappings":";;;iBAiBiB;EACf;EACA;EACA,MAAM,OAAO;EACb,mBAAmB,YAAY;EAC/B,QAAQ;;iBAGO;EACf,YAAY,eAAe,gBAAgB,aAAa,sBAAsB;EAC9E,cAAc,eAAe,gBAAgB,aAAa,sBAAsB;EAChF,YAAY,eAAe,aAAa,sBAAsB;EAC9D,wBAAwB,gBAAgB,iBAAiB;EACzD,SAAS;EACT,YAAY;;wBAGE,wBAAwB,UAAS,2BAAgC;wBA0BjE,kBAAkB,UAAU,oBAAoB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/logSinkTelemetry/index.ts"],"mappings":";;;iBAiBiB;EACf;EACA;EACA,MAAM,OAAO;EACb,mBAAmB,YAAY;EAC/B,QAAQ;;iBAGO;EACf,YAAY,eAAe,gBAAgB,aAAa,sBAAsB;EAC9E,cAAc,eAAe,gBAAgB,aAAa,sBAAsB;EAChF,YAAY,eAAe,aAAa,sBAAsB;EAC9D,wBAAwB,gBAAgB,iBAAiB;EACzD,SAAS;EACT,YAAY;;wBAGE,wBAAwB,UAAS,2BAAgC;wBA0BjE,kBAAkB,UAAU,oBAAoB"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{TASK_EVENT as e}from"../../types/telemetry.mjs";import{createDoomTelemetry as t}from"@agimon-ai/doompi-telemetry";function n(n={}){let r=t({serviceName:`doom-task`,packageName:`@agimon-ai/doompi-task`,cwd:n.cwd,workspaceRoot:n.workspaceRoot,env:n.env,telemetryFactory:n.telemetryFactory,warn:n.warn,enableLogs:!0,enableTraces:!0});return{recordError:(e,t,n)=>r.recordError(e,t,n),recordWarning:(e,t,n)=>r.recordWarning(e,t,n),recordEvent:(e,t)=>r.recordEvent(e,t),recordNotificationError:(t,n)=>r.recordError(e.notificationFailed,t,{"task.id":n,"task.operation":`completion_notification`}),flush:()=>r.flush(),shutdown:()=>r.shutdown()}}function r(e){return{error:(t,n,r)=>void e.recordError(t,n,r),warn:(t,n,r)=>void e.recordWarning(t,n,r),event:(t,n)=>void e.recordEvent(t,n)}}export{e as TASK_EVENT,n as createTaskErrorReporter,r as toFailureReporter};
|
|
2
|
-
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/services/logSinkTelemetry/index.ts"],"sourcesContent":["import { createDoomTelemetry, type DoomTelemetry, type DoomTelemetryOptions } from '@agimon-ai/doompi-telemetry';\n\nimport { TASK_EVENT, type TaskErrorAttributes, type TaskFailureReporter } from '../../types/telemetry';\n\nexport {\n TASK_EVENT,\n type TaskErrorAttributes,\n type TaskErrorSink,\n type TaskEventName,\n type TaskEventSink,\n type TaskFailureReporter,\n} from '../../types/telemetry';\n\nconst SERVICE_NAME = 'doom-task';\nconst PACKAGE_NAME = '@agimon-ai/doompi-task';\nconst NOTIFICATION_OPERATION = 'completion_notification';\n\nexport interface TaskErrorReporterOptions {\n cwd?: string;\n workspaceRoot?: string;\n env?: NodeJS.ProcessEnv;\n telemetryFactory?: NonNullable<DoomTelemetryOptions['telemetryFactory']>;\n warn?: (message: string) => void;\n}\n\nexport interface TaskErrorReporter {\n recordError(event: string, error: unknown, attributes?: TaskErrorAttributes): Promise<void>;\n recordWarning(event: string, error: unknown, attributes?: TaskErrorAttributes): Promise<void>;\n recordEvent(event: string, attributes?: TaskErrorAttributes): Promise<void>;\n recordNotificationError(error: unknown, taskId: number): Promise<void>;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nexport function createTaskErrorReporter(options: TaskErrorReporterOptions = {}): TaskErrorReporter {\n const telemetry: DoomTelemetry = createDoomTelemetry({\n serviceName: SERVICE_NAME,\n packageName: PACKAGE_NAME,\n cwd: options.cwd,\n workspaceRoot: options.workspaceRoot,\n env: options.env,\n telemetryFactory: options.telemetryFactory,\n warn: options.warn,\n enableLogs: true,\n enableTraces: true,\n });\n return {\n recordError: (event, error, attributes) => telemetry.recordError(event, error, attributes),\n recordWarning: (event, error, attributes) => telemetry.recordWarning(event, error, attributes),\n recordEvent: (event, attributes) => telemetry.recordEvent(event, attributes),\n recordNotificationError: (error, taskId) =>\n telemetry.recordError(TASK_EVENT.notificationFailed, error, {\n 'task.id': taskId,\n 'task.operation': NOTIFICATION_OPERATION,\n }),\n flush: () => telemetry.flush(),\n shutdown: () => telemetry.shutdown(),\n };\n}\n\nexport function toFailureReporter(reporter: TaskErrorReporter): TaskFailureReporter {\n return {\n error: (event, error, attributes) => void reporter.recordError(event, error, attributes),\n warn: (event, error, attributes) => void reporter.recordWarning(event, error, attributes),\n event: (event, attributes) => void reporter.recordEvent(event, attributes),\n };\n}\n"],"mappings":"yHAkCA,SAAgB,EAAwB,EAAoC,CAAC,EAAsB,CACjG,IAAM,EAA2B,EAAoB,CACnD,YAAa,YACb,YAAa,yBACb,IAAK,EAAQ,IACb,cAAe,EAAQ,cACvB,IAAK,EAAQ,IACb,iBAAkB,EAAQ,iBAC1B,KAAM,EAAQ,KACd,WAAY,GACZ,aAAc,EAChB,CAAC,EACD,MAAO,CACL,aAAc,EAAO,EAAO,IAAe,EAAU,YAAY,EAAO,EAAO,CAAU,EACzF,eAAgB,EAAO,EAAO,IAAe,EAAU,cAAc,EAAO,EAAO,CAAU,EAC7F,aAAc,EAAO,IAAe,EAAU,YAAY,EAAO,CAAU,EAC3E,yBAA0B,EAAO,IAC/B,EAAU,YAAY,EAAW,mBAAoB,EAAO,CAC1D,UAAW,EACX,iBAAkB,yBACpB,CAAC,EACH,UAAa,EAAU,MAAM,EAC7B,aAAgB,EAAU,SAAS,CACrC,CACF,CAEA,SAAgB,EAAkB,EAAkD,CAClF,MAAO,CACL,OAAQ,EAAO,EAAO,IAAe,KAAK,EAAS,YAAY,EAAO,EAAO,CAAU,EACvF,MAAO,EAAO,EAAO,IAAe,KAAK,EAAS,cAAc,EAAO,EAAO,CAAU,EACxF,OAAQ,EAAO,IAAe,KAAK,EAAS,YAAY,EAAO,CAAU,CAC3E,CACF"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("../../_virtual/_rolldown/runtime.cjs");let t=require("node:fs");t=e.__toESM(t,1);let n=require("node:path");n=e.__toESM(n,1);let r=require("node:child_process"),i=require("node:os");i=e.__toESM(i,1);let a=require("@agimon-ai/doompi-core/child-process");const o=`DOOM_TASK_STORE`,s=`doom-task`,c=`tasks.json`,l=`utf8`,u=`ENOENT`;function d(e,t){try{let n=(0,r.execFileSync)(`git`,e,{cwd:t,encoding:l,stdio:[`ignore`,`pipe`,`ignore`]}).trim();return n.length>0?n:void 0}catch{return}}async function f(e,t){return new Promise(n=>{(0,r.execFile)(`git`,e,{cwd:t,encoding:l},(e,t)=>{if(e){n(void 0);return}let r=t.trim();n(r.length>0?r:void 0)})})}function p(e){let t=e.PI_CODING_AGENT_DIR?.trim();return t===`~`?i.default.homedir():t?.startsWith(`~/`)?n.default.join(i.default.homedir(),t.slice(2)):t?n.default.resolve(t):n.default.join(i.default.homedir(),`.pi`,`agent`)}function m(e,t){let r=n.default.relative(n.default.resolve(e),n.default.resolve(t));return r===``||!r.startsWith(`..`)&&!n.default.isAbsolute(r)}function h(e,t=process.env){if(!t[a.SUBAGENT_CHILD_ENV])return e;let n=t[a.SUBAGENT_PARENT_SESSION_ENV]?.trim();if(!n)throw Error(`${a.SUBAGENT_PARENT_SESSION_ENV} is required in a subagent child`);return n}function g(e=process.cwd(),t=process.env,r=`standalone`){let i=t[o]?.trim();if(i)return n.default.resolve(i);let a=r.trim();if(!a)throw Error(`doom-task session id cannot be blank`);return n.default.join(p(t),s,a,c)}function _(e=process.env){return!!e[o]?.trim()}function v(e=process.cwd()){let t=d([`rev-parse`,`--path-format=absolute`,`--git-common-dir`],e);return t?n.default.join(t,s):void 0}async function y(e=process.cwd()){let t=await f([`rev-parse`,`--path-format=absolute`,`--git-common-dir`],e);return t?n.default.join(t,s):void 0}function b(e,r=process.cwd()){let i={removed:[],errors:[]},a=v(r);if(!a||n.default.basename(a)!==s||m(a,e))return i;try{if(!t.default.existsSync(a))return i;t.default.rmSync(a,{recursive:!0,force:!0}),i.removed.push(a)}catch(e){i.errors.push(`Could not remove legacy task store ${a}: ${String(e)}`)}return i}async function x(e,r=process.cwd()){let i={removed:[],errors:[]},a=await y(r);if(!a||n.default.basename(a)!==s||m(a,e))return i;try{await t.default.promises.access(a),await t.default.promises.rm(a,{recursive:!0,force:!0}),i.removed.push(a)}catch(e){e.code!==u&&i.errors.push(`Could not remove legacy task store ${a}: ${String(e)}`)}return i}function S(e,r,i=Date.now()){let a={removed:[],errors:[]},o=n.default.dirname(e),s=n.default.dirname(o),d;try{d=t.default.readdirSync(s)}catch(e){return e.code===u||a.errors.push(`Could not read task store directory ${s}: ${String(e)}`),a}for(let e of d){let u=n.default.join(s,e),d=n.default.join(u,c);if(u!==o&&t.default.existsSync(d))try{if(t.default.existsSync(w(d))||(JSON.parse(t.default.readFileSync(d,l)),i-t.default.statSync(d).mtimeMs<=r))continue;t.default.rmSync(u,{recursive:!0,force:!0}),a.removed.push(u)}catch(e){a.errors.push(`Could not sweep task store ${d}: ${String(e)}`)}}return a}async function C(e,r,i=Date.now()){let a={removed:[],errors:[]},o=n.default.dirname(e),s=n.default.dirname(o),d;try{d=await t.default.promises.readdir(s)}catch(e){return e.code===u||a.errors.push(`Could not read task store directory ${s}: ${String(e)}`),a}for(let e of d){let d=n.default.join(s,e),f=n.default.join(d,c);if(d!==o)try{await t.default.promises.access(f);try{await t.default.promises.access(w(f));continue}catch(e){if(e.code!==u)throw e}if(JSON.parse(await t.default.promises.readFile(f,l)),i-(await t.default.promises.stat(f)).mtimeMs<=r)continue;await t.default.promises.rm(d,{recursive:!0,force:!0}),a.removed.push(d)}catch(e){if(e.code===u)continue;a.errors.push(`Could not sweep task store ${f}: ${String(e)}`)}}return a}function w(e){return`${e}.lock`}function T(e,t=process.pid){return`${e}.tmp.${t}`}exports.STORE_PATH_ENV=o,exports.hasStorePathOverride=_,exports.lockPathFor=w,exports.removeLegacyStoreDirectory=b,exports.removeLegacyStoreDirectoryAsync=x,exports.resolveLegacyStoreDirectory=v,exports.resolveLegacyStoreDirectoryAsync=y,exports.resolveSessionKey=h,exports.resolveStorePath=g,exports.sweepStoreFiles=S,exports.sweepStoreFilesAsync=C,exports.tempPathFor=T;
|
|
2
|
-
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["execFileSync","os","path","SUBAGENT_CHILD_ENV","SUBAGENT_PARENT_SESSION_ENV","fs"],"sources":["../../../src/services/paths/index.ts"],"sourcesContent":["import { execFile, execFileSync } from 'node:child_process';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\n\nimport { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from '@agimon-ai/doompi-core/child-process';\n\nexport const STORE_PATH_ENV = 'DOOM_TASK_STORE';\n\nconst STORE_DIR_NAME = 'doom-task';\nconst STORE_FILE_NAME = 'tasks.json';\nconst DEFAULT_CONFIG_DIR_NAME = '.pi';\nconst AGENT_DIR_NAME = 'agent';\nconst PI_CODING_AGENT_DIR_ENV = 'PI_CODING_AGENT_DIR';\nconst HOME_ALIAS = '~';\nconst HOME_ALIAS_PREFIX = '~/';\nconst FILE_ENCODING = 'utf8';\nconst NOT_FOUND_ERROR_CODE = 'ENOENT';\n\nfunction git(args: string[], cwd: string): string | undefined {\n try {\n const output = execFileSync('git', args, {\n cwd,\n encoding: FILE_ENCODING,\n stdio: ['ignore', 'pipe', 'ignore'],\n });\n const trimmed = output.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function gitAsync(args: string[], cwd: string): Promise<string | undefined> {\n return new Promise((resolve) => {\n execFile('git', args, { cwd, encoding: FILE_ENCODING }, (error, stdout) => {\n if (error) {\n resolve(undefined);\n return;\n }\n const trimmed = stdout.trim();\n resolve(trimmed.length > 0 ? trimmed : undefined);\n });\n });\n}\n\nfunction resolveAgentDirectory(env: Readonly<Record<string, string | undefined>>): string {\n const configured = env[PI_CODING_AGENT_DIR_ENV]?.trim();\n if (configured === HOME_ALIAS) return os.homedir();\n if (configured?.startsWith(HOME_ALIAS_PREFIX)) {\n return path.join(os.homedir(), configured.slice(HOME_ALIAS_PREFIX.length));\n }\n return configured ? path.resolve(configured) : path.join(os.homedir(), DEFAULT_CONFIG_DIR_NAME, AGENT_DIR_NAME);\n}\n\nfunction isWithin(root: string, candidate: string): boolean {\n const relative = path.relative(path.resolve(root), path.resolve(candidate));\n return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));\n}\n\n/** Resolve the tree root without relying on extension startup order. */\nexport function resolveSessionKey(\n rootSessionId: string,\n env: Readonly<Record<string, string | undefined>> = process.env,\n): string {\n if (!env[SUBAGENT_CHILD_ENV]) return rootSessionId;\n const parentSessionId = env[SUBAGENT_PARENT_SESSION_ENV]?.trim();\n if (!parentSessionId) throw new Error(`${SUBAGENT_PARENT_SESSION_ENV} is required in a subagent child`);\n return parentSessionId;\n}\n\n/** Resolve one root session tree to a task document under the Pi agent directory. */\nexport function resolveStorePath(\n _cwd: string = process.cwd(),\n env: Readonly<Record<string, string | undefined>> = process.env,\n sessionKey: string = 'standalone',\n): string {\n const override = env[STORE_PATH_ENV]?.trim();\n if (override) return path.resolve(override);\n\n const trimmedSessionKey = sessionKey.trim();\n if (!trimmedSessionKey) throw new Error('doom-task session id cannot be blank');\n return path.join(resolveAgentDirectory(env), STORE_DIR_NAME, trimmedSessionKey, STORE_FILE_NAME);\n}\n\n/** Whether a deliberate unscoped task-store override is active. */\nexport function hasStorePathOverride(env: Readonly<Record<string, string | undefined>> = process.env): boolean {\n return Boolean(env[STORE_PATH_ENV]?.trim());\n}\n\n/** Exact legacy Git-directory store, if the current working tree has one. */\nexport function resolveLegacyStoreDirectory(cwd: string = process.cwd()): string | undefined {\n const commonDirectory = git(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n return commonDirectory ? path.join(commonDirectory, STORE_DIR_NAME) : undefined;\n}\n\nexport async function resolveLegacyStoreDirectoryAsync(cwd: string = process.cwd()): Promise<string | undefined> {\n const commonDirectory = await gitAsync(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n return commonDirectory ? path.join(commonDirectory, STORE_DIR_NAME) : undefined;\n}\n\nexport interface StoreSweepResult {\n removed: string[];\n errors: string[];\n}\n\n/** Remove only the validated legacy Git store unless it contains the active override. */\nexport function removeLegacyStoreDirectory(currentStorePath: string, cwd: string = process.cwd()): StoreSweepResult {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const target = resolveLegacyStoreDirectory(cwd);\n if (!target || path.basename(target) !== STORE_DIR_NAME || isWithin(target, currentStorePath)) return result;\n\n try {\n if (!fs.existsSync(target)) return result;\n fs.rmSync(target, { recursive: true, force: true });\n result.removed.push(target);\n } catch (error) {\n result.errors.push(`Could not remove legacy task store ${target}: ${String(error)}`);\n }\n return result;\n}\n\nexport async function removeLegacyStoreDirectoryAsync(\n currentStorePath: string,\n cwd: string = process.cwd(),\n): Promise<StoreSweepResult> {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const target = await resolveLegacyStoreDirectoryAsync(cwd);\n if (!target || path.basename(target) !== STORE_DIR_NAME || isWithin(target, currentStorePath)) return result;\n\n try {\n await fs.promises.access(target);\n await fs.promises.rm(target, { recursive: true, force: true });\n result.removed.push(target);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== NOT_FOUND_ERROR_CODE) {\n result.errors.push(`Could not remove legacy task store ${target}: ${String(error)}`);\n }\n }\n return result;\n}\n\n/** Delete expired sibling session stores while preserving active or unreadable stores. */\nexport function sweepStoreFiles(currentStorePath: string, ttlMs: number, now: number = Date.now()): StoreSweepResult {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const currentSessionDirectory = path.dirname(currentStorePath);\n const storeDirectory = path.dirname(currentSessionDirectory);\n let entries: string[];\n try {\n entries = fs.readdirSync(storeDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return result;\n result.errors.push(`Could not read task store directory ${storeDirectory}: ${String(error)}`);\n return result;\n }\n\n for (const entry of entries) {\n const sessionDirectory = path.join(storeDirectory, entry);\n const candidate = path.join(sessionDirectory, STORE_FILE_NAME);\n if (sessionDirectory === currentSessionDirectory || !fs.existsSync(candidate)) continue;\n try {\n if (fs.existsSync(lockPathFor(candidate))) continue;\n JSON.parse(fs.readFileSync(candidate, FILE_ENCODING));\n if (now - fs.statSync(candidate).mtimeMs <= ttlMs) continue;\n fs.rmSync(sessionDirectory, { recursive: true, force: true });\n result.removed.push(sessionDirectory);\n } catch (error) {\n result.errors.push(`Could not sweep task store ${candidate}: ${String(error)}`);\n }\n }\n return result;\n}\n\nexport async function sweepStoreFilesAsync(\n currentStorePath: string,\n ttlMs: number,\n now: number = Date.now(),\n): Promise<StoreSweepResult> {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const currentSessionDirectory = path.dirname(currentStorePath);\n const storeDirectory = path.dirname(currentSessionDirectory);\n let entries: string[];\n try {\n entries = await fs.promises.readdir(storeDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return result;\n result.errors.push(`Could not read task store directory ${storeDirectory}: ${String(error)}`);\n return result;\n }\n\n for (const entry of entries) {\n const sessionDirectory = path.join(storeDirectory, entry);\n const candidate = path.join(sessionDirectory, STORE_FILE_NAME);\n if (sessionDirectory === currentSessionDirectory) continue;\n try {\n await fs.promises.access(candidate);\n try {\n await fs.promises.access(lockPathFor(candidate));\n continue;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== NOT_FOUND_ERROR_CODE) throw error;\n }\n JSON.parse(await fs.promises.readFile(candidate, FILE_ENCODING));\n if (now - (await fs.promises.stat(candidate)).mtimeMs <= ttlMs) continue;\n await fs.promises.rm(sessionDirectory, { recursive: true, force: true });\n result.removed.push(sessionDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) continue;\n result.errors.push(`Could not sweep task store ${candidate}: ${String(error)}`);\n }\n }\n return result;\n}\n\nexport function lockPathFor(storePath: string): string {\n return `${storePath}.lock`;\n}\n\nexport function tempPathFor(storePath: string, pid: number = process.pid): string {\n return `${storePath}.tmp.${pid}`;\n}\n"],"mappings":"8QAOA,MAAa,EAAiB,kBAExB,EAAiB,YACjB,EAAkB,aAMlB,EAAgB,OAChB,EAAuB,SAE7B,SAAS,EAAI,EAAgB,EAAiC,CAC5D,GAAI,CAMF,IAAM,GAAA,EALSA,EAAAA,aAAAA,CAAa,MAAO,EAAM,CACvC,MACA,SAAU,EACV,MAAO,CAAC,SAAU,OAAQ,QAAQ,CACpC,CACqB,CAAC,CAAC,KAAK,EAC5B,OAAO,EAAQ,OAAS,EAAI,EAAU,IAAA,EACxC,MAAQ,CACN,MACF,CACF,CAEA,eAAe,EAAS,EAAgB,EAA0C,CAChF,OAAO,IAAI,QAAS,GAAY,EAC9B,EAAA,EAAA,S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OAAO,CACT,CAEA,SAAgB,EAAY,EAA2B,CACrD,MAAO,GAAG,EAAU,MACtB,CAEA,SAAgB,EAAY,EAAmB,EAAc,QAAQ,IAAa,CAChF,MAAO,GAAG,EAAU,OAAO,GAC7B"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../../../src/services/paths/index.ts"],"mappings":";qBAOa;;wBAsDG,kBACd,uBACA,MAAK,SAAS;;wBASA,iBACd,eACA,MAAK,SAAS,qCACd;;wBAWc,qBAAqB,MAAK,SAAS;;wBAKnC,4BAA4B;wBAKtB,iCAAiC,eAA8B;iBAKpE;EACf;EACA;;;wBAIc,2BAA2B,0BAA0B,eAA8B;wBAe7E,gCACpB,0BACA,eACC,QAAQ;;wBAkBK,gBAAgB,0BAA0B,eAAe,eAA2B;wBA8B9E,qBACpB,0BACA,eACA,eACC,QAAQ;wBAqCK,YAAY;wBAIZ,YAAY,mBAAmB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/paths/index.ts"],"mappings":";qBAOa;;wBAsDG,kBACd,uBACA,MAAK,SAAS;;wBASA,iBACd,eACA,MAAK,SAAS,qCACd;;wBAWc,qBAAqB,MAAK,SAAS;;wBAKnC,4BAA4B;wBAKtB,iCAAiC,eAA8B;iBAKpE;EACf;EACA;;;wBAIc,2BAA2B,0BAA0B,eAA8B;wBAe7E,gCACpB,0BACA,eACC,QAAQ;;wBAkBK,gBAAgB,0BAA0B,eAAe,eAA2B;wBA8B9E,qBACpB,0BACA,eACA,eACC,QAAQ;wBAqCK,YAAY;wBAIZ,YAAY,mBAAmB"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import e from"node:fs";import t from"node:path";import{execFile as n,execFileSync as r}from"node:child_process";import i from"node:os";import{SUBAGENT_CHILD_ENV as a,SUBAGENT_PARENT_SESSION_ENV as o}from"@agimon-ai/doompi-core/child-process";const s=`DOOM_TASK_STORE`,c=`doom-task`,l=`tasks.json`,u=`utf8`,d=`ENOENT`;function f(e,t){try{let n=r(`git`,e,{cwd:t,encoding:u,stdio:[`ignore`,`pipe`,`ignore`]}).trim();return n.length>0?n:void 0}catch{return}}async function p(e,t){return new Promise(r=>{n(`git`,e,{cwd:t,encoding:u},(e,t)=>{if(e){r(void 0);return}let n=t.trim();r(n.length>0?n:void 0)})})}function m(e){let n=e.PI_CODING_AGENT_DIR?.trim();return n===`~`?i.homedir():n?.startsWith(`~/`)?t.join(i.homedir(),n.slice(2)):n?t.resolve(n):t.join(i.homedir(),`.pi`,`agent`)}function h(e,n){let r=t.relative(t.resolve(e),t.resolve(n));return r===``||!r.startsWith(`..`)&&!t.isAbsolute(r)}function g(e,t=process.env){if(!t[a])return e;let n=t[o]?.trim();if(!n)throw Error(`${o} is required in a subagent child`);return n}function _(e=process.cwd(),n=process.env,r=`standalone`){let i=n[s]?.trim();if(i)return t.resolve(i);let a=r.trim();if(!a)throw Error(`doom-task session id cannot be blank`);return t.join(m(n),c,a,l)}function v(e=process.env){return!!e[s]?.trim()}function y(e=process.cwd()){let n=f([`rev-parse`,`--path-format=absolute`,`--git-common-dir`],e);return n?t.join(n,c):void 0}async function b(e=process.cwd()){let n=await p([`rev-parse`,`--path-format=absolute`,`--git-common-dir`],e);return n?t.join(n,c):void 0}function x(n,r=process.cwd()){let i={removed:[],errors:[]},a=y(r);if(!a||t.basename(a)!==c||h(a,n))return i;try{if(!e.existsSync(a))return i;e.rmSync(a,{recursive:!0,force:!0}),i.removed.push(a)}catch(e){i.errors.push(`Could not remove legacy task store ${a}: ${String(e)}`)}return i}async function S(n,r=process.cwd()){let i={removed:[],errors:[]},a=await b(r);if(!a||t.basename(a)!==c||h(a,n))return i;try{await e.promises.access(a),await e.promises.rm(a,{recursive:!0,force:!0}),i.removed.push(a)}catch(e){e.code!==d&&i.errors.push(`Could not remove legacy task store ${a}: ${String(e)}`)}return i}function C(n,r,i=Date.now()){let a={removed:[],errors:[]},o=t.dirname(n),s=t.dirname(o),c;try{c=e.readdirSync(s)}catch(e){return e.code===d||a.errors.push(`Could not read task store directory ${s}: ${String(e)}`),a}for(let n of c){let c=t.join(s,n),d=t.join(c,l);if(c!==o&&e.existsSync(d))try{if(e.existsSync(T(d))||(JSON.parse(e.readFileSync(d,u)),i-e.statSync(d).mtimeMs<=r))continue;e.rmSync(c,{recursive:!0,force:!0}),a.removed.push(c)}catch(e){a.errors.push(`Could not sweep task store ${d}: ${String(e)}`)}}return a}async function w(n,r,i=Date.now()){let a={removed:[],errors:[]},o=t.dirname(n),s=t.dirname(o),c;try{c=await e.promises.readdir(s)}catch(e){return e.code===d||a.errors.push(`Could not read task store directory ${s}: ${String(e)}`),a}for(let n of c){let c=t.join(s,n),f=t.join(c,l);if(c!==o)try{await e.promises.access(f);try{await e.promises.access(T(f));continue}catch(e){if(e.code!==d)throw e}if(JSON.parse(await e.promises.readFile(f,u)),i-(await e.promises.stat(f)).mtimeMs<=r)continue;await e.promises.rm(c,{recursive:!0,force:!0}),a.removed.push(c)}catch(e){if(e.code===d)continue;a.errors.push(`Could not sweep task store ${f}: ${String(e)}`)}}return a}function T(e){return`${e}.lock`}function E(e,t=process.pid){return`${e}.tmp.${t}`}export{s as STORE_PATH_ENV,v as hasStorePathOverride,T as lockPathFor,x as removeLegacyStoreDirectory,S as removeLegacyStoreDirectoryAsync,y as resolveLegacyStoreDirectory,b as resolveLegacyStoreDirectoryAsync,g as resolveSessionKey,_ as resolveStorePath,C as sweepStoreFiles,w as sweepStoreFilesAsync,E as tempPathFor};
|
|
2
|
-
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/services/paths/index.ts"],"sourcesContent":["import { execFile, execFileSync } from 'node:child_process';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\n\nimport { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from '@agimon-ai/doompi-core/child-process';\n\nexport const STORE_PATH_ENV = 'DOOM_TASK_STORE';\n\nconst STORE_DIR_NAME = 'doom-task';\nconst STORE_FILE_NAME = 'tasks.json';\nconst DEFAULT_CONFIG_DIR_NAME = '.pi';\nconst AGENT_DIR_NAME = 'agent';\nconst PI_CODING_AGENT_DIR_ENV = 'PI_CODING_AGENT_DIR';\nconst HOME_ALIAS = '~';\nconst HOME_ALIAS_PREFIX = '~/';\nconst FILE_ENCODING = 'utf8';\nconst NOT_FOUND_ERROR_CODE = 'ENOENT';\n\nfunction git(args: string[], cwd: string): string | undefined {\n try {\n const output = execFileSync('git', args, {\n cwd,\n encoding: FILE_ENCODING,\n stdio: ['ignore', 'pipe', 'ignore'],\n });\n const trimmed = output.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function gitAsync(args: string[], cwd: string): Promise<string | undefined> {\n return new Promise((resolve) => {\n execFile('git', args, { cwd, encoding: FILE_ENCODING }, (error, stdout) => {\n if (error) {\n resolve(undefined);\n return;\n }\n const trimmed = stdout.trim();\n resolve(trimmed.length > 0 ? trimmed : undefined);\n });\n });\n}\n\nfunction resolveAgentDirectory(env: Readonly<Record<string, string | undefined>>): string {\n const configured = env[PI_CODING_AGENT_DIR_ENV]?.trim();\n if (configured === HOME_ALIAS) return os.homedir();\n if (configured?.startsWith(HOME_ALIAS_PREFIX)) {\n return path.join(os.homedir(), configured.slice(HOME_ALIAS_PREFIX.length));\n }\n return configured ? path.resolve(configured) : path.join(os.homedir(), DEFAULT_CONFIG_DIR_NAME, AGENT_DIR_NAME);\n}\n\nfunction isWithin(root: string, candidate: string): boolean {\n const relative = path.relative(path.resolve(root), path.resolve(candidate));\n return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));\n}\n\n/** Resolve the tree root without relying on extension startup order. */\nexport function resolveSessionKey(\n rootSessionId: string,\n env: Readonly<Record<string, string | undefined>> = process.env,\n): string {\n if (!env[SUBAGENT_CHILD_ENV]) return rootSessionId;\n const parentSessionId = env[SUBAGENT_PARENT_SESSION_ENV]?.trim();\n if (!parentSessionId) throw new Error(`${SUBAGENT_PARENT_SESSION_ENV} is required in a subagent child`);\n return parentSessionId;\n}\n\n/** Resolve one root session tree to a task document under the Pi agent directory. */\nexport function resolveStorePath(\n _cwd: string = process.cwd(),\n env: Readonly<Record<string, string | undefined>> = process.env,\n sessionKey: string = 'standalone',\n): string {\n const override = env[STORE_PATH_ENV]?.trim();\n if (override) return path.resolve(override);\n\n const trimmedSessionKey = sessionKey.trim();\n if (!trimmedSessionKey) throw new Error('doom-task session id cannot be blank');\n return path.join(resolveAgentDirectory(env), STORE_DIR_NAME, trimmedSessionKey, STORE_FILE_NAME);\n}\n\n/** Whether a deliberate unscoped task-store override is active. */\nexport function hasStorePathOverride(env: Readonly<Record<string, string | undefined>> = process.env): boolean {\n return Boolean(env[STORE_PATH_ENV]?.trim());\n}\n\n/** Exact legacy Git-directory store, if the current working tree has one. */\nexport function resolveLegacyStoreDirectory(cwd: string = process.cwd()): string | undefined {\n const commonDirectory = git(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n return commonDirectory ? path.join(commonDirectory, STORE_DIR_NAME) : undefined;\n}\n\nexport async function resolveLegacyStoreDirectoryAsync(cwd: string = process.cwd()): Promise<string | undefined> {\n const commonDirectory = await gitAsync(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n return commonDirectory ? path.join(commonDirectory, STORE_DIR_NAME) : undefined;\n}\n\nexport interface StoreSweepResult {\n removed: string[];\n errors: string[];\n}\n\n/** Remove only the validated legacy Git store unless it contains the active override. */\nexport function removeLegacyStoreDirectory(currentStorePath: string, cwd: string = process.cwd()): StoreSweepResult {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const target = resolveLegacyStoreDirectory(cwd);\n if (!target || path.basename(target) !== STORE_DIR_NAME || isWithin(target, currentStorePath)) return result;\n\n try {\n if (!fs.existsSync(target)) return result;\n fs.rmSync(target, { recursive: true, force: true });\n result.removed.push(target);\n } catch (error) {\n result.errors.push(`Could not remove legacy task store ${target}: ${String(error)}`);\n }\n return result;\n}\n\nexport async function removeLegacyStoreDirectoryAsync(\n currentStorePath: string,\n cwd: string = process.cwd(),\n): Promise<StoreSweepResult> {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const target = await resolveLegacyStoreDirectoryAsync(cwd);\n if (!target || path.basename(target) !== STORE_DIR_NAME || isWithin(target, currentStorePath)) return result;\n\n try {\n await fs.promises.access(target);\n await fs.promises.rm(target, { recursive: true, force: true });\n result.removed.push(target);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== NOT_FOUND_ERROR_CODE) {\n result.errors.push(`Could not remove legacy task store ${target}: ${String(error)}`);\n }\n }\n return result;\n}\n\n/** Delete expired sibling session stores while preserving active or unreadable stores. */\nexport function sweepStoreFiles(currentStorePath: string, ttlMs: number, now: number = Date.now()): StoreSweepResult {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const currentSessionDirectory = path.dirname(currentStorePath);\n const storeDirectory = path.dirname(currentSessionDirectory);\n let entries: string[];\n try {\n entries = fs.readdirSync(storeDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return result;\n result.errors.push(`Could not read task store directory ${storeDirectory}: ${String(error)}`);\n return result;\n }\n\n for (const entry of entries) {\n const sessionDirectory = path.join(storeDirectory, entry);\n const candidate = path.join(sessionDirectory, STORE_FILE_NAME);\n if (sessionDirectory === currentSessionDirectory || !fs.existsSync(candidate)) continue;\n try {\n if (fs.existsSync(lockPathFor(candidate))) continue;\n JSON.parse(fs.readFileSync(candidate, FILE_ENCODING));\n if (now - fs.statSync(candidate).mtimeMs <= ttlMs) continue;\n fs.rmSync(sessionDirectory, { recursive: true, force: true });\n result.removed.push(sessionDirectory);\n } catch (error) {\n result.errors.push(`Could not sweep task store ${candidate}: ${String(error)}`);\n }\n }\n return result;\n}\n\nexport async function sweepStoreFilesAsync(\n currentStorePath: string,\n ttlMs: number,\n now: number = Date.now(),\n): Promise<StoreSweepResult> {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const currentSessionDirectory = path.dirname(currentStorePath);\n const storeDirectory = path.dirname(currentSessionDirectory);\n let entries: string[];\n try {\n entries = await fs.promises.readdir(storeDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return result;\n result.errors.push(`Could not read task store directory ${storeDirectory}: ${String(error)}`);\n return result;\n }\n\n for (const entry of entries) {\n const sessionDirectory = path.join(storeDirectory, entry);\n const candidate = path.join(sessionDirectory, STORE_FILE_NAME);\n if (sessionDirectory === currentSessionDirectory) continue;\n try {\n await fs.promises.access(candidate);\n try {\n await fs.promises.access(lockPathFor(candidate));\n continue;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== NOT_FOUND_ERROR_CODE) throw error;\n }\n JSON.parse(await fs.promises.readFile(candidate, FILE_ENCODING));\n if (now - (await fs.promises.stat(candidate)).mtimeMs <= ttlMs) continue;\n await fs.promises.rm(sessionDirectory, { recursive: true, force: true });\n result.removed.push(sessionDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) continue;\n result.errors.push(`Could not sweep task store ${candidate}: ${String(error)}`);\n }\n }\n return result;\n}\n\nexport function lockPathFor(storePath: string): string {\n return `${storePath}.lock`;\n}\n\nexport function tempPathFor(storePath: string, pid: number = process.pid): string {\n return `${storePath}.tmp.${pid}`;\n}\n"],"mappings":"kPAOA,MAAa,EAAiB,kBAExB,EAAiB,YACjB,EAAkB,aAMlB,EAAgB,OAChB,EAAuB,SAE7B,SAAS,EAAI,EAAgB,EAAiC,CAC5D,GAAI,CAMF,IAAM,EALS,EAAa,MAAO,EAAM,CACvC,MACA,SAAU,EACV,MAAO,CAAC,SAAU,OAAQ,QAAQ,CACpC,CACqB,CAAC,CAAC,KAAK,EAC5B,OAAO,EAAQ,OAAS,EAAI,EAAU,IAAA,EAC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EAA2B,CAAE,QAAS,CAAC,EAAG,OAAQ,CAAC,CAAE,EACrD,EAA0B,EAAK,QAAQ,CAAgB,EACvD,EAAiB,EAAK,QAAQ,CAAuB,EACvD,EACJ,GAAI,CACF,EAAU,MAAM,EAAG,SAAS,QAAQ,CAAc,CACpD,OAAS,EAAO,CAGd,OAFK,EAAgC,OAAS,GAC9C,EAAO,OAAO,KAAK,uCAAuC,EAAe,IAAI,OAAO,CAAK,GAAG,EADjB,CAG7E,CAEA,IAAK,IAAM,KAAS,EAAS,CAC3B,IAAM,EAAmB,EAAK,KAAK,EAAgB,CAAK,EAClD,EAAY,EAAK,KAAK,EAAkB,CAAe,EACzD,OAAqB,EACzB,GAAI,CACF,MAAM,EAAG,SAAS,OAAO,CAAS,EAClC,GAAI,CACF,MAAM,EAAG,SAAS,OAAO,EAAY,CAAS,CAAC,EAC/C,QACF,OAAS,EAAO,CACd,GAAK,EAAgC,OAAS,EAAsB,MAAM,CAC5E,CAEA,GADA,KAAK,MAAM,MAAM,EAAG,SAAS,SAAS,EAAW,CAAa,CAAC,EAC3D,GAAO,MAAM,EAAG,SAAS,KAAK,CAAS,EAAA,CAAG,SAAW,EAAO,SAChE,MAAM,EAAG,SAAS,GAAG,EAAkB,CAAE,UAAW,GAAM,MAAO,EAAK,CAAC,EACvE,EAAO,QAAQ,KAAK,CAAgB,CACtC,OAAS,EAAO,CACd,GAAK,EAAgC,OAAS,EAAsB,SACpE,EAAO,OAAO,KAAK,8BAA8B,EAAU,IAAI,OAAO,CAAK,GAAG,CAChF,CACF,CACA,OAAO,CACT,CAEA,SAAgB,EAAY,EAA2B,CACrD,MAAO,GAAG,EAAU,MACtB,CAEA,SAAgB,EAAY,EAAmB,EAAc,QAAQ,IAAa,CAChF,MAAO,GAAG,EAAU,OAAO,GAC7B"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../../../src/services/processLiveness/index.ts"],"sourcesContent":["/**\n * Is a process still running?\n *\n * Signal 0 performs the permission and existence check without delivering a\n * signal. EPERM means the process exists but belongs to another user, which\n * still counts as alive.\n */\nexport function isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'EPERM';\n }\n}\n"],"mappings":"AAOA,SAAgB,EAAe,EAAsB,CACnD,GAAI,CAEF,OADA,QAAQ,KAAK,EAAK,CAAC,EACZ,EACT,OAAS,EAAO,CACd,OAAQ,EAAgC,OAAS,OACnD,CACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../../../src/services/processLiveness/index.ts"],"mappings":";;;;;;;;wBAOgB,eAAe"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/processLiveness/index.ts"],"mappings":";;;;;;;;wBAOgB,eAAe"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/services/processLiveness/index.ts"],"sourcesContent":["/**\n * Is a process still running?\n *\n * Signal 0 performs the permission and existence check without delivering a\n * signal. EPERM means the process exists but belongs to another user, which\n * still counts as alive.\n */\nexport function isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === 'EPERM';\n }\n}\n"],"mappings":"AAOA,SAAgB,EAAe,EAAsB,CACnD,GAAI,CAEF,OADA,QAAQ,KAAK,EAAK,CAAC,EACZ,EACT,OAAS,EAAO,CACd,OAAQ,EAAgC,OAAS,OACnD,CACF"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("../processLiveness/index.cjs"),t=require("../../models/task.cjs"),n=`Delegation orphaned by harness restart`,r=`Delegation orphaned by session restart`;function i(i,a=new Date().toISOString(),o=e.isProcessAlive,s){let c=[],l=i.tasks.map(e=>{if(!t.isDelegationActive(e))return e;let i=e.delegation?.pid;if(i===void 0)return e;let l=s!==void 0&&i===s.pid&&!s.liveRequestIds.has(e.delegation.requestId);if(!l&&o(i))return e;let u={...e,status:`pending`,updatedAt:a,delegation:{...e.delegation,state:`failed`,endedAt:a,result:{status:`failed`,error:l?r:n}}};return c.push(u),u});return c.length===0?{document:i,orphaned:c}:{document:{...i,tasks:l},orphaned:c}}exports.ERR_ORPHANED_BY_RESTART=n,exports.ERR_ORPHANED_BY_SESSION=r,exports.reconcileOrphanedDelegations=i;
|
|
2
|
-
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["isProcessAlive","isDelegationActive"],"sources":["../../../src/services/reconcile/index.ts"],"sourcesContent":["import { isDelegationActive, type Task, type TaskDocument } from '../../models/task';\nimport { isProcessAlive } from '../processLiveness';\n\nexport const ERR_ORPHANED_BY_RESTART = 'Delegation orphaned by harness restart';\nexport const ERR_ORPHANED_BY_SESSION = 'Delegation orphaned by session restart';\n\nexport interface ReconcileResult {\n document: TaskDocument;\n orphaned: Task[];\n}\n\n/** The delegations this process can still settle, used to spot its own leftovers. */\nexport interface ReconcileSelf {\n pid: number;\n liveRequestIds: ReadonlySet<string>;\n}\n\n/**\n * Recover tasks that no longer have anyone able to finish them.\n *\n * A subagent run dies with the harness that spawned it, but the store file\n * outlives both, so a crash leaves tasks stuck in `in_progress` forever. Two\n * kinds of delegation qualify as dead:\n *\n * - the owning pid is gone, so nothing is left to report a result;\n * - the owning pid is *this* process, yet the request is absent from the live\n * set. Settling requires an in-memory record, so an in-process session\n * restart (which clears that map without writing to the store) leaves rows\n * nothing can ever resolve. Checking pid liveness alone misses these, because\n * the pid is our own and very much alive.\n *\n * Delegations owned by a different, still-running pid belong to a parallel\n * session and are left untouched.\n */\nexport function reconcileOrphanedDelegations(\n document: TaskDocument,\n now: string = new Date().toISOString(),\n isAlive: (pid: number) => boolean = isProcessAlive,\n self?: ReconcileSelf,\n): ReconcileResult {\n const orphaned: Task[] = [];\n\n const tasks = document.tasks.map((task) => {\n if (!isDelegationActive(task)) return task;\n const pid = task.delegation?.pid;\n if (pid === undefined) return task;\n\n const ownedByThisSession = self !== undefined && pid === self.pid;\n const abandonedHere = ownedByThisSession && !self.liveRequestIds.has(task.delegation!.requestId);\n if (!abandonedHere && isAlive(pid)) return task;\n\n const recovered: Task = {\n ...task,\n status: 'pending',\n updatedAt: now,\n delegation: {\n ...task.delegation!,\n state: 'failed',\n endedAt: now,\n result: {\n status: 'failed',\n error: abandonedHere ? ERR_ORPHANED_BY_SESSION : ERR_ORPHANED_BY_RESTART,\n },\n },\n };\n orphaned.push(recovered);\n return recovered;\n });\n\n if (orphaned.length === 0) return { document, orphaned };\n return { document: { ...document, tasks }, orphaned };\n}\n"],"mappings":"mFAGa,EAA0B,yCAC1B,EAA0B,yCA8BvC,SAAgB,EACd,EACA,EAAc,IAAI,KAAK,CAAA,CAAE,YAAY,EACrC,EAAoCA,EAAAA,eACpC,EACiB,CACjB,IAAM,EAAmB,CAAC,EAEpB,EAAQ,EAAS,MAAM,IAAK,GAAS,CACzC,GAAI,CAACC,EAAAA,mBAAmB,CAAI,EAAG,OAAO,EACtC,IAAM,EAAM,EAAK,YAAY,IAC7B,GAAI,IAAQ,IAAA,GAAW,OAAO,EAG9B,IAAM,EADqB,IAAS,IAAA,IAAa,IAAQ,EAAK,KAClB,CAAC,EAAK,eAAe,IAAI,EAAK,WAAY,SAAS,EAC/F,GAAI,CAAC,GAAiB,EAAQ,CAAG,EAAG,OAAO,EAE3C,IAAM,EAAkB,CACtB,GAAG,EACH,OAAQ,UACR,UAAW,EACX,WAAY,CACV,GAAG,EAAK,WACR,MAAO,SACP,QAAS,EACT,OAAQ,CACN,OAAQ,SACR,MAAO,EAAgB,EAA0B,CACnD,CACF,CACF,EAEA,OADA,EAAS,KAAK,CAAS,EAChB,CACT,CAAC,EAGD,OADI,EAAS,SAAW,EAAU,CAAE,WAAU,UAAS,EAChD,CAAE,SAAU,CAAE,GAAG,EAAU,OAAM,EAAG,UAAS,CACtD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../../../src/services/reconcile/index.ts"],"mappings":";;qBAGa;qBACA;iBAEI;EACf,UAAU;EACV,UAAU;;;iBAIK;EACf;EACA,gBAAgB;;;;;;;;;;;;;;;;;;;wBAoBF,6BACd,UAAU,cACV,cACA,WAAU,yBACV,OAAO,gBACN"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/reconcile/index.ts"],"mappings":";;qBAGa;qBACA;iBAEI;EACf,UAAU;EACV,UAAU;;;iBAIK;EACf;EACA,gBAAgB;;;;;;;;;;;;;;;;;;;wBAoBF,6BACd,UAAU,cACV,cACA,WAAU,yBACV,OAAO,gBACN"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{isProcessAlive as e}from"../processLiveness/index.mjs";import{isDelegationActive as t}from"../../models/task.mjs";const n=`Delegation orphaned by harness restart`,r=`Delegation orphaned by session restart`;function i(i,a=new Date().toISOString(),o=e,s){let c=[],l=i.tasks.map(e=>{if(!t(e))return e;let i=e.delegation?.pid;if(i===void 0)return e;let l=s!==void 0&&i===s.pid&&!s.liveRequestIds.has(e.delegation.requestId);if(!l&&o(i))return e;let u={...e,status:`pending`,updatedAt:a,delegation:{...e.delegation,state:`failed`,endedAt:a,result:{status:`failed`,error:l?r:n}}};return c.push(u),u});return c.length===0?{document:i,orphaned:c}:{document:{...i,tasks:l},orphaned:c}}export{n as ERR_ORPHANED_BY_RESTART,r as ERR_ORPHANED_BY_SESSION,i as reconcileOrphanedDelegations};
|
|
2
|
-
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/services/reconcile/index.ts"],"sourcesContent":["import { isDelegationActive, type Task, type TaskDocument } from '../../models/task';\nimport { isProcessAlive } from '../processLiveness';\n\nexport const ERR_ORPHANED_BY_RESTART = 'Delegation orphaned by harness restart';\nexport const ERR_ORPHANED_BY_SESSION = 'Delegation orphaned by session restart';\n\nexport interface ReconcileResult {\n document: TaskDocument;\n orphaned: Task[];\n}\n\n/** The delegations this process can still settle, used to spot its own leftovers. */\nexport interface ReconcileSelf {\n pid: number;\n liveRequestIds: ReadonlySet<string>;\n}\n\n/**\n * Recover tasks that no longer have anyone able to finish them.\n *\n * A subagent run dies with the harness that spawned it, but the store file\n * outlives both, so a crash leaves tasks stuck in `in_progress` forever. Two\n * kinds of delegation qualify as dead:\n *\n * - the owning pid is gone, so nothing is left to report a result;\n * - the owning pid is *this* process, yet the request is absent from the live\n * set. Settling requires an in-memory record, so an in-process session\n * restart (which clears that map without writing to the store) leaves rows\n * nothing can ever resolve. Checking pid liveness alone misses these, because\n * the pid is our own and very much alive.\n *\n * Delegations owned by a different, still-running pid belong to a parallel\n * session and are left untouched.\n */\nexport function reconcileOrphanedDelegations(\n document: TaskDocument,\n now: string = new Date().toISOString(),\n isAlive: (pid: number) => boolean = isProcessAlive,\n self?: ReconcileSelf,\n): ReconcileResult {\n const orphaned: Task[] = [];\n\n const tasks = document.tasks.map((task) => {\n if (!isDelegationActive(task)) return task;\n const pid = task.delegation?.pid;\n if (pid === undefined) return task;\n\n const ownedByThisSession = self !== undefined && pid === self.pid;\n const abandonedHere = ownedByThisSession && !self.liveRequestIds.has(task.delegation!.requestId);\n if (!abandonedHere && isAlive(pid)) return task;\n\n const recovered: Task = {\n ...task,\n status: 'pending',\n updatedAt: now,\n delegation: {\n ...task.delegation!,\n state: 'failed',\n endedAt: now,\n result: {\n status: 'failed',\n error: abandonedHere ? ERR_ORPHANED_BY_SESSION : ERR_ORPHANED_BY_RESTART,\n },\n },\n };\n orphaned.push(recovered);\n return recovered;\n });\n\n if (orphaned.length === 0) return { document, orphaned };\n return { document: { ...document, tasks }, orphaned };\n}\n"],"mappings":"yHAGA,MAAa,EAA0B,yCAC1B,EAA0B,yCA8BvC,SAAgB,EACd,EACA,EAAc,IAAI,KAAK,CAAA,CAAE,YAAY,EACrC,EAAoC,EACpC,EACiB,CACjB,IAAM,EAAmB,CAAC,EAEpB,EAAQ,EAAS,MAAM,IAAK,GAAS,CACzC,GAAI,CAAC,EAAmB,CAAI,EAAG,OAAO,EACtC,IAAM,EAAM,EAAK,YAAY,IAC7B,GAAI,IAAQ,IAAA,GAAW,OAAO,EAG9B,IAAM,EADqB,IAAS,IAAA,IAAa,IAAQ,EAAK,KAClB,CAAC,EAAK,eAAe,IAAI,EAAK,WAAY,SAAS,EAC/F,GAAI,CAAC,GAAiB,EAAQ,CAAG,EAAG,OAAO,EAE3C,IAAM,EAAkB,CACtB,GAAG,EACH,OAAQ,UACR,UAAW,EACX,WAAY,CACV,GAAG,EAAK,WACR,MAAO,SACP,QAAS,EACT,OAAQ,CACN,OAAQ,SACR,MAAO,EAAgB,EAA0B,CACnD,CACF,CACF,EAEA,OADA,EAAS,KAAK,CAAS,EAChB,CACT,CAAC,EAGD,OADI,EAAS,SAAW,EAAU,CAAE,WAAU,UAAS,EAChD,CAAE,SAAU,CAAE,GAAG,EAAU,OAAM,EAAG,UAAS,CACtD"}
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
const e=require("../../models/taskGraph.cjs"),t=require("../../models/task.cjs"),n=require("../invariants/index.cjs"),r=/^[A-Za-z][A-Za-z0-9_-]{0,31}$/;function i(e){switch(e.kind){case`error`:case`list`:case`get`:return!1;case`upsert`:return e.items.some(e=>e.kind===`created`||e.kind===`updated`);case`delete`:case`clear`:return!0}}function a(e){return e.items.filter(e=>e.kind===`failed`).map(e=>`item[${e.index}]: ${e.message}`).join(`
|
|
2
|
-
`)}function o(e){return e.kind===`upsert`?e.items[0]:void 0}function s(e,t){return{document:e,op:{kind:`error`,message:t}}}function c(e,t){let n=e??[],r=t??[];return n.length===r.length&&n.every((e,t)=>e===r[t])}function l(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function u(e,t){return e.subject!==t.subject||e.status!==t.status||e.description!==t.description||e.activeForm!==t.activeForm||e.owner!==t.owner||!c(e.blockedBy,t.blockedBy)||!l(e.metadata,t.metadata)}function d(e,t,n=e.nextId){return{...e,tasks:t,nextId:n}}function f(e,t){let n={...e};for(let[e,r]of Object.entries(t))r===null?delete n[e]:n[e]=r;return Object.keys(n).length?n:void 0}function p(e,t){if(t.subject!==void 0&&(e.subject=t.subject),t.description!==void 0&&(e.description=t.description),t.activeForm!==void 0&&(e.activeForm=t.activeForm),t.owner!==void 0&&(e.owner=t.owner),t.metadata!==void 0){let n=f(e.metadata,t.metadata);n===void 0?delete e.metadata:e.metadata=n}}function m(e,t,n){if(typeof n==`number`)return{ok:!0,id:n};if(!r.test(n))return{ok:!1,message:`${t}: "${n}" is not a valid ref; pass an existing task id as a number`};let i=e.refIds.get(n);if(i!==void 0)return{ok:!0,id:i};let a=e.failedRefs.get(n);return a===void 0?{ok:!1,message:`${t}: unknown ref "${n}" — a ref must be declared by an earlier entry in the same call`}:{ok:!1,message:`${t}: ref "${n}" refers to item[${a}], which failed`}}function h(e){return{ok:!1,message:e}}function g(e,t){if(t.ref!==void 0){if(t.id!==void 0)return`ref is only valid when creating a task; drop the id, or drop the ref`;if(!r.test(t.ref))return`ref "${t.ref}" is invalid: a ref must start with a letter and contain only letters, digits, - or _`;if(e.refIds.get(t.ref)!==void 0||e.failedRefs.has(t.ref))return`duplicate ref "${t.ref}": it was already declared by an earlier entry`}}function _(e,t,n,r){if(t.subject===void 0)return h(`subject is required when the entry has no id`);if(!t.subject.trim())return h(`subject must not be blank`);if(t.addBlockedBy!==void 0||t.removeBlockedBy!==void 0)return h(`addBlockedBy / removeBlockedBy are only for an entry with an id; a new task uses blockedBy`);if(t.status===`deleted`)return h(`cannot create a task with status deleted; create it, then use action delete`);if(e.tasks.filter(e=>e.status!==`deleted`).length>=e.maxTasks)return h(`task limit of ${e.maxTasks} reached; delete completed tasks first before creating new tasks`);let i=[];for(let n of t.blockedBy??[]){let t=m(e,`blockedBy`,n);if(!t.ok)return h(t.message);let r=e.tasks.find(e=>e.id===t.id);if(!r)return h(`blockedBy: #${t.id} not found`);if(r.status===`deleted`)return h(`blockedBy: #${t.id} is deleted`);i.includes(t.id)||i.push(t.id)}let a={id:e.nextId,subject:t.subject,status:t.status??`pending`,createdAt:r,updatedAt:r};return p(a,t),i.length&&(a.blockedBy=i),e.nextId+=1,e.tasks.push(a),t.ref&&e.refIds.set(t.ref,a.id),{ok:!0,outcome:{index:n,kind:`created`,id:a.id,subject:a.subject,status:a.status,...t.ref?{ref:t.ref}:{},...i.length?{blockedBy:i}:{}}}}function v(t,r,i,a){let o=r.id,s=t.tasks.findIndex(e=>e.id===o);if(s===-1)return h(`#${o} not found`);if(r.blockedBy!==void 0)return h(`blockedBy is only for a new entry; use addBlockedBy / removeBlockedBy on an entry that has an id`);if(!(r.subject!==void 0||r.description!==void 0||r.activeForm!==void 0||r.status!==void 0||r.owner!==void 0||r.metadata!==void 0||r.addBlockedBy?.length||r.removeBlockedBy?.length))return h(`nothing to change: provide at least one of subject, description, activeForm, status, owner, metadata, addBlockedBy, or removeBlockedBy`);let c=t.tasks[s];if(r.subject!==void 0&&!r.subject.trim())return h(`subject must not be blank`);let l=c.status;if(r.status!==void 0){if(!n.isTransitionValid(c.status,r.status))return h(`illegal transition ${c.status} -> ${r.status}`);l=r.status}let d=c.blockedBy?[...c.blockedBy]:[];for(let e of r.removeBlockedBy??[]){let n=m(t,`removeBlockedBy`,e);if(!n.ok)return h(n.message);d=d.filter(e=>e!==n.id)}for(let e of r.addBlockedBy??[]){let n=m(t,`addBlockedBy`,e);if(!n.ok)return h(n.message);if(n.id===o)return h(`cannot block #${o} on itself`);let r=t.tasks.find(e=>e.id===n.id);if(!r)return h(`addBlockedBy: #${n.id} not found`);if(r.status===`deleted`)return h(`addBlockedBy: #${n.id} is deleted`);d.includes(n.id)||d.push(n.id)}let f={...c,status:l};p(f,r),d.length?f.blockedBy=d:delete f.blockedBy;let g=[...t.tasks];if(g[s]=f,r.addBlockedBy?.length&&e.detectCycle(g,o,d))return h(`addBlockedBy would create a cycle in the blockedBy graph`);let _=u(c,f);return _&&(f.updatedAt=a),t.tasks=g,{ok:!0,outcome:_?{index:i,kind:`updated`,id:o,fromStatus:c.status,toStatus:l}:{index:i,kind:`unchanged`,id:o,status:l}}}function y(e,t,n,i){let a={tasks:[...e.tasks],nextId:e.nextId,maxTasks:i,refIds:new Map,failedRefs:new Map},o=[],s=0;for(let[e,i]of t.entries()){let t=g(a,i),c=t?h(t):i.id===void 0?_(a,i,e,n):v(a,i,e,n);if(c.ok){o.push(c.outcome),s+=1;continue}i.ref&&r.test(i.ref)&&!a.refIds.has(i.ref)&&a.failedRefs.set(i.ref,e),o.push({index:e,kind:`failed`,message:c.message,...i.id===void 0?{}:{id:i.id},...i.ref?{ref:i.ref}:{}})}return{document:s>0?d(e,a.tasks,a.nextId):e,op:{kind:`upsert`,items:o,applied:s,failed:o.length-s}}}function b(e,n,r,i=new Date().toISOString(),a=15){switch(n){case`upsert`:{let t=r.tasks;return!Array.isArray(t)||t.length===0?s(e,`upsert requires a non-empty tasks array, e.g. {"action":"upsert","tasks":[{"subject":"Write tests"}]}`):t.length>100?s(e,`upsert accepts at most 100 entries per call (received ${t.length})`):y(e,t,i,a)}case`list`:return{document:e,op:{kind:`list`,includeDeleted:r.includeDeleted===!0,...r.status===void 0?{}:{statusFilter:r.status}}};case`get`:{if(r.id===void 0)return s(e,`id required for get`);let t=e.tasks.find(e=>e.id===r.id);return t?{document:e,op:{kind:`get`,task:t}}:s(e,`#${r.id} not found`)}case`delete`:{if(r.id===void 0)return s(e,`id required for delete`);let n=e.tasks.findIndex(e=>e.id===r.id);if(n===-1)return s(e,`#${r.id} not found`);let a=e.tasks[n];if(a.status===`deleted`)return s(e,`#${a.id} is already deleted`);if(t.isDelegationActive(a))return s(e,`#${a.id} has a running delegation — cancel it before deleting`);let o=[...e.tasks];return o[n]={...a,status:t.DELETED_STATUS,updatedAt:i},{document:d(e,o),op:{kind:`delete`,id:a.id,subject:a.subject}}}case`clear`:{let n=e.tasks.filter(t.isDelegationActive);if(n.length>0)return s(e,`cannot clear while delegations are running (${n.map(e=>`#${e.id}`).join(`, `)}) — cancel them first`);let r=e.tasks.length;return{document:d(e,[],1),op:{kind:`clear`,count:r}}}}}exports.MAX_UPSERT_ITEMS=100,exports.REF_PATTERN=r,exports.applyTaskMutation=b,exports.formatUpsertFailure=a,exports.isCommittingOp=i,exports.singleItemOutcome=o;
|
|
3
|
-
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["isTransitionValid","detectCycle","isDelegationActive","DELETED_STATUS"],"sources":["../../../src/services/reducer/index.ts"],"sourcesContent":["import {\n DELETED_STATUS,\n type DepToken,\n isDelegationActive,\n type Task,\n type TaskAction,\n type TaskDocument,\n type TaskItemMutation,\n type TaskMutationParams,\n type TaskStatus,\n type UpsertItemOutcome,\n} from '../../models/task';\nimport { detectCycle } from '../../models/taskGraph';\nimport { isTransitionValid } from '../invariants';\n\n/** Default board capacity when a caller does not provide a configured limit. */\nconst DEFAULT_REDUCER_MAX_TASKS = 15;\n\n/** Bounds the work one call can do, and with it the size of one committed write. */\nexport const MAX_UPSERT_ITEMS = 100;\n\n/**\n * A ref must start with a letter, which makes it structurally unconfusable with\n * a stringified id. That is why resolving a dependency token is just a `typeof`\n * check with no coercion heuristics.\n */\nexport const REF_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,31}$/;\n\n/**\n * Reducer outcome. Closed tagged union: adding an action requires extending\n * this union and the response formatter, which the compiler enforces.\n *\n * `upsert` carries one outcome per request item. It is returned even when every\n * item failed — `error` is reserved for whole-call faults — so the tool layer\n * still has the per-item messages to report.\n */\nexport type Op =\n | { kind: 'upsert'; items: UpsertItemOutcome[]; applied: number; failed: number }\n | { kind: 'delete'; id: number; subject: string }\n | { kind: 'list'; statusFilter?: TaskStatus; includeDeleted: boolean }\n | { kind: 'get'; task: Task }\n | { kind: 'clear'; count: number }\n | { kind: 'error'; message: string };\n\nexport interface ApplyResult {\n document: TaskDocument;\n op: Op;\n}\n\n/** Actions the reducer owns. `assign`/`cancel` are handled by the delegation manager. */\nexport type ReducerAction = Exclude<TaskAction, 'assign' | 'cancel'>;\n\n/**\n * Does this op represent state that must reach disk?\n *\n * The exhaustive switch is the point: a future `Op` variant cannot be added\n * without declaring its persistence intent, so nothing silently starts or stops\n * bumping `rev`.\n */\nexport function isCommittingOp(op: Op): boolean {\n switch (op.kind) {\n case 'error':\n case 'list':\n case 'get':\n return false;\n case 'upsert':\n return op.items.some((item) => item.kind === 'created' || item.kind === 'updated');\n case 'delete':\n case 'clear':\n return true;\n }\n}\n\n/** Joined per-item failures, for the thrown error when an upsert applied nothing. */\nexport function formatUpsertFailure(op: Extract<Op, { kind: 'upsert' }>): string {\n return op.items\n .filter((item) => item.kind === 'failed')\n .map((item) => `item[${item.index}]: ${item.message}`)\n .join('\\n');\n}\n\n/** The single item's outcome, for callers that only ever send a batch of one. */\nexport function singleItemOutcome(op: Op): UpsertItemOutcome | undefined {\n return op.kind === 'upsert' ? op.items[0] : undefined;\n}\n\nfunction errorResult(document: TaskDocument, message: string): ApplyResult {\n return { document, op: { kind: 'error', message } };\n}\n\nfunction sameNumberList(a: number[] | undefined, b: number[] | undefined): boolean {\n const x = a ?? [];\n const y = b ?? [];\n return x.length === y.length && x.every((value, index) => value === y[index]);\n}\n\nfunction sameRecord(a: Record<string, unknown> | undefined, b: Record<string, unknown> | undefined): boolean {\n return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);\n}\n\n/**\n * Did this update change anything? A no-effect update (status re-set to its\n * current value, fields re-sent unchanged) reports \"No change\" rather than\n * \"Updated #N\" — without the distinction a model can loop re-issuing the same\n * call believing it never landed.\n */\nfunction taskChanged(before: Task, after: Task): boolean {\n return (\n before.subject !== after.subject ||\n before.status !== after.status ||\n before.description !== after.description ||\n before.activeForm !== after.activeForm ||\n before.owner !== after.owner ||\n !sameNumberList(before.blockedBy, after.blockedBy) ||\n !sameRecord(before.metadata, after.metadata)\n );\n}\n\nfunction withTasks(document: TaskDocument, tasks: Task[], nextId = document.nextId): TaskDocument {\n return { ...document, tasks, nextId };\n}\n\n/** Merge incoming metadata over a base; a `null` value deletes its key. */\nfunction mergeMetadata(\n base: Record<string, unknown> | undefined,\n incoming: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n const merged: Record<string, unknown> = { ...base };\n for (const [key, value] of Object.entries(incoming)) {\n if (value === null) delete merged[key];\n else merged[key] = value;\n }\n return Object.keys(merged).length ? merged : undefined;\n}\n\n/** Copy the optional scalar fields an item may set onto a task, in place. */\nfunction assignScalars(target: Task, item: TaskItemMutation): void {\n if (item.subject !== undefined) target.subject = item.subject;\n if (item.description !== undefined) target.description = item.description;\n if (item.activeForm !== undefined) target.activeForm = item.activeForm;\n if (item.owner !== undefined) target.owner = item.owner;\n if (item.metadata !== undefined) {\n const merged = mergeMetadata(target.metadata, item.metadata);\n if (merged === undefined) delete target.metadata;\n else target.metadata = merged;\n }\n}\n\n/**\n * Working state threaded item to item, so entry N observes every effect of\n * entries 1..N-1. `refIds` and `failedRefs` are what make the cascade work:\n * refs resolve backward only, so an entry that names a failed sibling is always\n * processed after the failure that killed it.\n */\ninterface UpsertContext {\n tasks: Task[];\n nextId: number;\n maxTasks: number;\n refIds: Map<string, number>;\n failedRefs: Map<string, number>;\n}\n\ntype Resolved = { ok: true; id: number } | { ok: false; message: string };\n\nfunction resolveDep(context: UpsertContext, field: string, token: DepToken): Resolved {\n if (typeof token === 'number') return { ok: true, id: token };\n if (!REF_PATTERN.test(token)) {\n return { ok: false, message: `${field}: \"${token}\" is not a valid ref; pass an existing task id as a number` };\n }\n const id = context.refIds.get(token);\n if (id !== undefined) return { ok: true, id };\n const failedAt = context.failedRefs.get(token);\n if (failedAt !== undefined) {\n return { ok: false, message: `${field}: ref \"${token}\" refers to item[${failedAt}], which failed` };\n }\n return {\n ok: false,\n message: `${field}: unknown ref \"${token}\" — a ref must be declared by an earlier entry in the same call`,\n };\n}\n\ntype ItemResult = { ok: true; outcome: UpsertItemOutcome } | { ok: false; message: string };\n\nfunction fail(message: string): ItemResult {\n return { ok: false, message };\n}\n\n/** Structural checks that apply to every entry, whichever kind it is. */\nfunction checkShape(context: UpsertContext, item: TaskItemMutation): string | undefined {\n if (item.ref !== undefined) {\n if (item.id !== undefined) return 'ref is only valid when creating a task; drop the id, or drop the ref';\n if (!REF_PATTERN.test(item.ref)) {\n return `ref \"${item.ref}\" is invalid: a ref must start with a letter and contain only letters, digits, - or _`;\n }\n const owner = context.refIds.get(item.ref) !== undefined || context.failedRefs.has(item.ref);\n if (owner) return `duplicate ref \"${item.ref}\": it was already declared by an earlier entry`;\n }\n return undefined;\n}\n\nfunction applyCreateItem(context: UpsertContext, item: TaskItemMutation, index: number, now: string): ItemResult {\n if (item.subject === undefined) return fail('subject is required when the entry has no id');\n if (!item.subject.trim()) return fail('subject must not be blank');\n if (item.addBlockedBy !== undefined || item.removeBlockedBy !== undefined) {\n return fail('addBlockedBy / removeBlockedBy are only for an entry with an id; a new task uses blockedBy');\n }\n // A task created as a tombstone is invisible to every view and can never\n // leave `deleted`, so it would be a write-only black hole.\n if (item.status === DELETED_STATUS) {\n return fail('cannot create a task with status deleted; create it, then use action delete');\n }\n\n const taskCount = context.tasks.filter((task) => task.status !== DELETED_STATUS).length;\n if (taskCount >= context.maxTasks) {\n return fail(`task limit of ${context.maxTasks} reached; delete completed tasks first before creating new tasks`);\n }\n\n const blockedBy: number[] = [];\n for (const token of item.blockedBy ?? []) {\n const resolved = resolveDep(context, 'blockedBy', token);\n if (!resolved.ok) return fail(resolved.message);\n const dep = context.tasks.find((task) => task.id === resolved.id);\n if (!dep) return fail(`blockedBy: #${resolved.id} not found`);\n if (dep.status === DELETED_STATUS) return fail(`blockedBy: #${resolved.id} is deleted`);\n if (!blockedBy.includes(resolved.id)) blockedBy.push(resolved.id);\n }\n\n // No cycle check is needed: the id is freshly allocated, so nothing already\n // in the document can point at it yet.\n const created: Task = {\n id: context.nextId,\n subject: item.subject,\n status: item.status ?? 'pending',\n createdAt: now,\n updatedAt: now,\n };\n assignScalars(created, item);\n if (blockedBy.length) created.blockedBy = blockedBy;\n\n context.nextId += 1;\n context.tasks.push(created);\n if (item.ref) context.refIds.set(item.ref, created.id);\n\n return {\n ok: true,\n outcome: {\n index,\n kind: 'created',\n id: created.id,\n subject: created.subject,\n status: created.status,\n ...(item.ref ? { ref: item.ref } : {}),\n ...(blockedBy.length ? { blockedBy } : {}),\n },\n };\n}\n\nfunction applyUpdateItem(context: UpsertContext, item: TaskItemMutation, index: number, now: string): ItemResult {\n const id = item.id as number;\n const at = context.tasks.findIndex((task) => task.id === id);\n if (at === -1) return fail(`#${id} not found`);\n if (item.blockedBy !== undefined) {\n return fail('blockedBy is only for a new entry; use addBlockedBy / removeBlockedBy on an entry that has an id');\n }\n\n const hasMutation =\n item.subject !== undefined ||\n item.description !== undefined ||\n item.activeForm !== undefined ||\n item.status !== undefined ||\n item.owner !== undefined ||\n item.metadata !== undefined ||\n Boolean(item.addBlockedBy?.length) ||\n Boolean(item.removeBlockedBy?.length);\n if (!hasMutation) {\n return fail(\n 'nothing to change: provide at least one of subject, description, activeForm, status, owner, metadata, addBlockedBy, or removeBlockedBy',\n );\n }\n\n const current = context.tasks[at];\n\n // The Task Space overlay commits free text from an inline editor, so a blank\n // subject reaches the reducer as a real update rather than as a missing\n // field. Persisting it would leave an unidentifiable row.\n if (item.subject !== undefined && !item.subject.trim()) return fail('subject must not be blank');\n\n let newStatus = current.status;\n if (item.status !== undefined) {\n if (!isTransitionValid(current.status, item.status)) {\n return fail(`illegal transition ${current.status} -> ${item.status}`);\n }\n newStatus = item.status;\n }\n\n let newBlockedBy = current.blockedBy ? [...current.blockedBy] : [];\n for (const token of item.removeBlockedBy ?? []) {\n const resolved = resolveDep(context, 'removeBlockedBy', token);\n if (!resolved.ok) return fail(resolved.message);\n // Removing an id that is not there is a well-defined no-op, so unlike the\n // add path this deliberately skips the existence check.\n newBlockedBy = newBlockedBy.filter((dep) => dep !== resolved.id);\n }\n for (const token of item.addBlockedBy ?? []) {\n const resolved = resolveDep(context, 'addBlockedBy', token);\n if (!resolved.ok) return fail(resolved.message);\n if (resolved.id === id) return fail(`cannot block #${id} on itself`);\n const dep = context.tasks.find((task) => task.id === resolved.id);\n if (!dep) return fail(`addBlockedBy: #${resolved.id} not found`);\n if (dep.status === DELETED_STATUS) return fail(`addBlockedBy: #${resolved.id} is deleted`);\n if (!newBlockedBy.includes(resolved.id)) newBlockedBy.push(resolved.id);\n }\n\n const updated: Task = { ...current, status: newStatus };\n assignScalars(updated, item);\n if (newBlockedBy.length) updated.blockedBy = newBlockedBy;\n else delete updated.blockedBy;\n\n // The candidate is written before the check because `detectCycle` unions the\n // node's stored edges with the ones passed in: checking against the old array\n // would resurrect an edge `removeBlockedBy` just stripped and reject a\n // remove+add that legitimately breaks a cycle.\n const candidate = [...context.tasks];\n candidate[at] = updated;\n if (item.addBlockedBy?.length && detectCycle(candidate, id, newBlockedBy)) {\n return fail('addBlockedBy would create a cycle in the blockedBy graph');\n }\n\n const changed = taskChanged(current, updated);\n if (changed) updated.updatedAt = now;\n context.tasks = candidate;\n\n return {\n ok: true,\n outcome: changed\n ? { index, kind: 'updated', id, fromStatus: current.status, toStatus: newStatus }\n : { index, kind: 'unchanged', id, status: newStatus },\n };\n}\n\n/**\n * Apply every entry in request order, threading the document.\n *\n * Each entry lands completely or not at all: a create whose dependencies fail\n * is not kept dependency-free, because handing back an unblocked task the\n * caller asked to be blocked is a lie it may immediately act on.\n */\nfunction applyUpsert(document: TaskDocument, items: TaskItemMutation[], now: string, maxTasks: number): ApplyResult {\n const context: UpsertContext = {\n tasks: [...document.tasks],\n nextId: document.nextId,\n maxTasks,\n refIds: new Map(),\n failedRefs: new Map(),\n };\n const outcomes: UpsertItemOutcome[] = [];\n let applied = 0;\n\n for (const [index, item] of items.entries()) {\n const shapeError = checkShape(context, item);\n const result = shapeError\n ? fail(shapeError)\n : item.id === undefined\n ? applyCreateItem(context, item, index, now)\n : applyUpdateItem(context, item, index, now);\n\n if (result.ok) {\n outcomes.push(result.outcome);\n applied += 1;\n continue;\n }\n // A ref whose owner failed must not read as a typo to the entries that\n // depend on it, so the dead ref is recorded rather than left unknown.\n if (item.ref && REF_PATTERN.test(item.ref) && !context.refIds.has(item.ref)) {\n context.failedRefs.set(item.ref, index);\n }\n outcomes.push({\n index,\n kind: 'failed',\n message: result.message,\n ...(item.id === undefined ? {} : { id: item.id }),\n ...(item.ref ? { ref: item.ref } : {}),\n });\n }\n\n return {\n // Nothing applied means nothing to write: returning the original object by\n // reference keeps the caller's write-skip path identical to a hard error.\n document: applied > 0 ? withTasks(document, context.tasks, context.nextId) : document,\n op: { kind: 'upsert', items: outcomes, applied, failed: outcomes.length - applied },\n };\n}\n\n/**\n * Pure reducer: (document, action, params) -> (document, op).\n *\n * All validation is in-line: structural guards plus state-aware checks\n * (transition legality, dangling or deleted blockedBy, self-block, cycles,\n * in-flight delegations). The caller owns persistence and formatting.\n */\nexport function applyTaskMutation(\n document: TaskDocument,\n action: ReducerAction,\n params: TaskMutationParams,\n now: string = new Date().toISOString(),\n maxTasks = DEFAULT_REDUCER_MAX_TASKS,\n): ApplyResult {\n switch (action) {\n case 'upsert': {\n const items = params.tasks;\n if (!Array.isArray(items) || items.length === 0) {\n return errorResult(\n document,\n 'upsert requires a non-empty tasks array, e.g. {\"action\":\"upsert\",\"tasks\":[{\"subject\":\"Write tests\"}]}',\n );\n }\n if (items.length > MAX_UPSERT_ITEMS) {\n return errorResult(\n document,\n `upsert accepts at most ${MAX_UPSERT_ITEMS} entries per call (received ${items.length})`,\n );\n }\n return applyUpsert(document, items, now, maxTasks);\n }\n\n case 'list': {\n return {\n document,\n op: {\n kind: 'list',\n includeDeleted: params.includeDeleted === true,\n ...(params.status !== undefined ? { statusFilter: params.status } : {}),\n },\n };\n }\n\n case 'get': {\n if (params.id === undefined) return errorResult(document, 'id required for get');\n const task = document.tasks.find((candidate) => candidate.id === params.id);\n if (!task) return errorResult(document, `#${params.id} not found`);\n return { document, op: { kind: 'get', task } };\n }\n\n case 'delete': {\n if (params.id === undefined) return errorResult(document, 'id required for delete');\n const index = document.tasks.findIndex((task) => task.id === params.id);\n if (index === -1) return errorResult(document, `#${params.id} not found`);\n const current = document.tasks[index];\n if (current.status === DELETED_STATUS) return errorResult(document, `#${current.id} is already deleted`);\n if (isDelegationActive(current)) {\n return errorResult(document, `#${current.id} has a running delegation — cancel it before deleting`);\n }\n\n const tasks = [...document.tasks];\n tasks[index] = { ...current, status: DELETED_STATUS, updatedAt: now };\n return {\n document: withTasks(document, tasks),\n op: { kind: 'delete', id: current.id, subject: current.subject },\n };\n }\n\n case 'clear': {\n const active = document.tasks.filter(isDelegationActive);\n if (active.length > 0) {\n const ids = active.map((task) => `#${task.id}`).join(', ');\n return errorResult(document, `cannot clear while delegations are running (${ids}) — cancel them first`);\n }\n const count = document.tasks.length;\n return {\n document: withTasks(document, [], 1),\n op: { kind: 'clear', count },\n };\n }\n }\n}\n"],"mappings":"sHA0Ba,EAAc,gCAiC3B,SAAgB,EAAe,EAAiB,CAC9C,OAAQ,EAAG,KAAX,CACE,IAAK,QACL,IAAK,OACL,IAAK,MACH,MAAO,GACT,IAAK,SACH,OAAO,EAAG,MAAM,KAAM,GAAS,EAAK,OAAS,WAAa,EAAK,OAAS,SAAS,EACnF,IAAK,SACL,IAAK,QACH,MAAO,EACX,CACF,CAGA,SAAgB,EAAoB,EAA6C,CAC/E,OAAO,EAAG,MACP,OAAQ,GAAS,EAAK,OAAS,QAAQ,CAAC,CACxC,IAAK,GAAS,QAAQ,EAAK,MAAM,KAAK,EAAK,SAAS,CAAC,CACrD,KAAK;CAAI,CACd,CAGA,SAAgB,EAAkB,EAAuC,CACvE,OAAO,EAAG,OAAS,SAAW,EAAG,MAAM,GAAK,IAAA,EAC9C,CAEA,SAAS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B;EAAiB;;EAC7D;EAAgB;EAAY;;EAC5B;EAAc,eAAe;EAAY;;EACzC;EAAa,MAAM;;EACnB;EAAe;;EACf;EAAe;;iBAEJ;EACf,UAAU;EACV,IAAI;;;YAIM,gBAAgB,QAAQ;;;;;;;;wBASpB,eAAe,IAAI;;wBAenB,oBAAoB,IAAI,QAAQ;EAAM;;;wBAQtC,kBAAkB,IAAI,KAAK;;;;;;;;wBA8T3B,kBACd,UAAU,cACV,QAAQ,eACR,QAAQ,oBACR,cACA,oBACC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/reducer/index.ts"],"mappings":";;;qBAmBa;;;;;;qBAOA,aAAW;;;;;;;;;YAUZ;EACN;EAAgB,OAAO;EAAqB;EAAiB;;EAC7D;EAAgB;EAAY;;EAC5B;EAAc,eAAe;EAAY;;EACzC;EAAa,MAAM;;EACnB;EAAe;;EACf;EAAe;;iBAEJ;EACf,UAAU;EACV,IAAI;;;YAIM,gBAAgB,QAAQ;;;;;;;;wBASpB,eAAe,IAAI;;wBAenB,oBAAoB,IAAI,QAAQ;EAAM;;;wBAQtC,kBAAkB,IAAI,KAAK;;;;;;;;wBA8T3B,kBACd,UAAU,cACV,QAAQ,eACR,QAAQ,oBACR,cACA,oBACC"}
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{detectCycle as e}from"../../models/taskGraph.mjs";import{DELETED_STATUS as t,isDelegationActive as n}from"../../models/task.mjs";import{isTransitionValid as r}from"../invariants/index.mjs";const i=100,a=/^[A-Za-z][A-Za-z0-9_-]{0,31}$/;function o(e){switch(e.kind){case`error`:case`list`:case`get`:return!1;case`upsert`:return e.items.some(e=>e.kind===`created`||e.kind===`updated`);case`delete`:case`clear`:return!0}}function s(e){return e.items.filter(e=>e.kind===`failed`).map(e=>`item[${e.index}]: ${e.message}`).join(`
|
|
2
|
-
`)}function c(e){return e.kind===`upsert`?e.items[0]:void 0}function l(e,t){return{document:e,op:{kind:`error`,message:t}}}function u(e,t){let n=e??[],r=t??[];return n.length===r.length&&n.every((e,t)=>e===r[t])}function d(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function f(e,t){return e.subject!==t.subject||e.status!==t.status||e.description!==t.description||e.activeForm!==t.activeForm||e.owner!==t.owner||!u(e.blockedBy,t.blockedBy)||!d(e.metadata,t.metadata)}function p(e,t,n=e.nextId){return{...e,tasks:t,nextId:n}}function m(e,t){let n={...e};for(let[e,r]of Object.entries(t))r===null?delete n[e]:n[e]=r;return Object.keys(n).length?n:void 0}function h(e,t){if(t.subject!==void 0&&(e.subject=t.subject),t.description!==void 0&&(e.description=t.description),t.activeForm!==void 0&&(e.activeForm=t.activeForm),t.owner!==void 0&&(e.owner=t.owner),t.metadata!==void 0){let n=m(e.metadata,t.metadata);n===void 0?delete e.metadata:e.metadata=n}}function g(e,t,n){if(typeof n==`number`)return{ok:!0,id:n};if(!a.test(n))return{ok:!1,message:`${t}: "${n}" is not a valid ref; pass an existing task id as a number`};let r=e.refIds.get(n);if(r!==void 0)return{ok:!0,id:r};let i=e.failedRefs.get(n);return i===void 0?{ok:!1,message:`${t}: unknown ref "${n}" — a ref must be declared by an earlier entry in the same call`}:{ok:!1,message:`${t}: ref "${n}" refers to item[${i}], which failed`}}function _(e){return{ok:!1,message:e}}function v(e,t){if(t.ref!==void 0){if(t.id!==void 0)return`ref is only valid when creating a task; drop the id, or drop the ref`;if(!a.test(t.ref))return`ref "${t.ref}" is invalid: a ref must start with a letter and contain only letters, digits, - or _`;if(e.refIds.get(t.ref)!==void 0||e.failedRefs.has(t.ref))return`duplicate ref "${t.ref}": it was already declared by an earlier entry`}}function y(e,t,n,r){if(t.subject===void 0)return _(`subject is required when the entry has no id`);if(!t.subject.trim())return _(`subject must not be blank`);if(t.addBlockedBy!==void 0||t.removeBlockedBy!==void 0)return _(`addBlockedBy / removeBlockedBy are only for an entry with an id; a new task uses blockedBy`);if(t.status===`deleted`)return _(`cannot create a task with status deleted; create it, then use action delete`);if(e.tasks.filter(e=>e.status!==`deleted`).length>=e.maxTasks)return _(`task limit of ${e.maxTasks} reached; delete completed tasks first before creating new tasks`);let i=[];for(let n of t.blockedBy??[]){let t=g(e,`blockedBy`,n);if(!t.ok)return _(t.message);let r=e.tasks.find(e=>e.id===t.id);if(!r)return _(`blockedBy: #${t.id} not found`);if(r.status===`deleted`)return _(`blockedBy: #${t.id} is deleted`);i.includes(t.id)||i.push(t.id)}let a={id:e.nextId,subject:t.subject,status:t.status??`pending`,createdAt:r,updatedAt:r};return h(a,t),i.length&&(a.blockedBy=i),e.nextId+=1,e.tasks.push(a),t.ref&&e.refIds.set(t.ref,a.id),{ok:!0,outcome:{index:n,kind:`created`,id:a.id,subject:a.subject,status:a.status,...t.ref?{ref:t.ref}:{},...i.length?{blockedBy:i}:{}}}}function b(t,n,i,a){let o=n.id,s=t.tasks.findIndex(e=>e.id===o);if(s===-1)return _(`#${o} not found`);if(n.blockedBy!==void 0)return _(`blockedBy is only for a new entry; use addBlockedBy / removeBlockedBy on an entry that has an id`);if(!(n.subject!==void 0||n.description!==void 0||n.activeForm!==void 0||n.status!==void 0||n.owner!==void 0||n.metadata!==void 0||n.addBlockedBy?.length||n.removeBlockedBy?.length))return _(`nothing to change: provide at least one of subject, description, activeForm, status, owner, metadata, addBlockedBy, or removeBlockedBy`);let c=t.tasks[s];if(n.subject!==void 0&&!n.subject.trim())return _(`subject must not be blank`);let l=c.status;if(n.status!==void 0){if(!r(c.status,n.status))return _(`illegal transition ${c.status} -> ${n.status}`);l=n.status}let u=c.blockedBy?[...c.blockedBy]:[];for(let e of n.removeBlockedBy??[]){let n=g(t,`removeBlockedBy`,e);if(!n.ok)return _(n.message);u=u.filter(e=>e!==n.id)}for(let e of n.addBlockedBy??[]){let n=g(t,`addBlockedBy`,e);if(!n.ok)return _(n.message);if(n.id===o)return _(`cannot block #${o} on itself`);let r=t.tasks.find(e=>e.id===n.id);if(!r)return _(`addBlockedBy: #${n.id} not found`);if(r.status===`deleted`)return _(`addBlockedBy: #${n.id} is deleted`);u.includes(n.id)||u.push(n.id)}let d={...c,status:l};h(d,n),u.length?d.blockedBy=u:delete d.blockedBy;let p=[...t.tasks];if(p[s]=d,n.addBlockedBy?.length&&e(p,o,u))return _(`addBlockedBy would create a cycle in the blockedBy graph`);let m=f(c,d);return m&&(d.updatedAt=a),t.tasks=p,{ok:!0,outcome:m?{index:i,kind:`updated`,id:o,fromStatus:c.status,toStatus:l}:{index:i,kind:`unchanged`,id:o,status:l}}}function x(e,t,n,r){let i={tasks:[...e.tasks],nextId:e.nextId,maxTasks:r,refIds:new Map,failedRefs:new Map},o=[],s=0;for(let[e,r]of t.entries()){let t=v(i,r),c=t?_(t):r.id===void 0?y(i,r,e,n):b(i,r,e,n);if(c.ok){o.push(c.outcome),s+=1;continue}r.ref&&a.test(r.ref)&&!i.refIds.has(r.ref)&&i.failedRefs.set(r.ref,e),o.push({index:e,kind:`failed`,message:c.message,...r.id===void 0?{}:{id:r.id},...r.ref?{ref:r.ref}:{}})}return{document:s>0?p(e,i.tasks,i.nextId):e,op:{kind:`upsert`,items:o,applied:s,failed:o.length-s}}}function S(e,r,i,a=new Date().toISOString(),o=15){switch(r){case`upsert`:{let t=i.tasks;return!Array.isArray(t)||t.length===0?l(e,`upsert requires a non-empty tasks array, e.g. {"action":"upsert","tasks":[{"subject":"Write tests"}]}`):t.length>100?l(e,`upsert accepts at most 100 entries per call (received ${t.length})`):x(e,t,a,o)}case`list`:return{document:e,op:{kind:`list`,includeDeleted:i.includeDeleted===!0,...i.status===void 0?{}:{statusFilter:i.status}}};case`get`:{if(i.id===void 0)return l(e,`id required for get`);let t=e.tasks.find(e=>e.id===i.id);return t?{document:e,op:{kind:`get`,task:t}}:l(e,`#${i.id} not found`)}case`delete`:{if(i.id===void 0)return l(e,`id required for delete`);let r=e.tasks.findIndex(e=>e.id===i.id);if(r===-1)return l(e,`#${i.id} not found`);let o=e.tasks[r];if(o.status===`deleted`)return l(e,`#${o.id} is already deleted`);if(n(o))return l(e,`#${o.id} has a running delegation — cancel it before deleting`);let s=[...e.tasks];return s[r]={...o,status:t,updatedAt:a},{document:p(e,s),op:{kind:`delete`,id:o.id,subject:o.subject}}}case`clear`:{let t=e.tasks.filter(n);if(t.length>0)return l(e,`cannot clear while delegations are running (${t.map(e=>`#${e.id}`).join(`, `)}) — cancel them first`);let r=e.tasks.length;return{document:p(e,[],1),op:{kind:`clear`,count:r}}}}}export{i as MAX_UPSERT_ITEMS,a as REF_PATTERN,S as applyTaskMutation,s as formatUpsertFailure,o as isCommittingOp,c as singleItemOutcome};
|
|
3
|
-
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/services/reducer/index.ts"],"sourcesContent":["import {\n DELETED_STATUS,\n type DepToken,\n isDelegationActive,\n type Task,\n type TaskAction,\n type TaskDocument,\n type TaskItemMutation,\n type TaskMutationParams,\n type TaskStatus,\n type UpsertItemOutcome,\n} from '../../models/task';\nimport { detectCycle } from '../../models/taskGraph';\nimport { isTransitionValid } from '../invariants';\n\n/** Default board capacity when a caller does not provide a configured limit. */\nconst DEFAULT_REDUCER_MAX_TASKS = 15;\n\n/** Bounds the work one call can do, and with it the size of one committed write. */\nexport const MAX_UPSERT_ITEMS = 100;\n\n/**\n * A ref must start with a letter, which makes it structurally unconfusable with\n * a stringified id. That is why resolving a dependency token is just a `typeof`\n * check with no coercion heuristics.\n */\nexport const REF_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,31}$/;\n\n/**\n * Reducer outcome. Closed tagged union: adding an action requires extending\n * this union and the response formatter, which the compiler enforces.\n *\n * `upsert` carries one outcome per request item. It is returned even when every\n * item failed — `error` is reserved for whole-call faults — so the tool layer\n * still has the per-item messages to report.\n */\nexport type Op =\n | { kind: 'upsert'; items: UpsertItemOutcome[]; applied: number; failed: number }\n | { kind: 'delete'; id: number; subject: string }\n | { kind: 'list'; statusFilter?: TaskStatus; includeDeleted: boolean }\n | { kind: 'get'; task: Task }\n | { kind: 'clear'; count: number }\n | { kind: 'error'; message: string };\n\nexport interface ApplyResult {\n document: TaskDocument;\n op: Op;\n}\n\n/** Actions the reducer owns. `assign`/`cancel` are handled by the delegation manager. */\nexport type ReducerAction = Exclude<TaskAction, 'assign' | 'cancel'>;\n\n/**\n * Does this op represent state that must reach disk?\n *\n * The exhaustive switch is the point: a future `Op` variant cannot be added\n * without declaring its persistence intent, so nothing silently starts or stops\n * bumping `rev`.\n */\nexport function isCommittingOp(op: Op): boolean {\n switch (op.kind) {\n case 'error':\n case 'list':\n case 'get':\n return false;\n case 'upsert':\n return op.items.some((item) => item.kind === 'created' || item.kind === 'updated');\n case 'delete':\n case 'clear':\n return true;\n }\n}\n\n/** Joined per-item failures, for the thrown error when an upsert applied nothing. */\nexport function formatUpsertFailure(op: Extract<Op, { kind: 'upsert' }>): string {\n return op.items\n .filter((item) => item.kind === 'failed')\n .map((item) => `item[${item.index}]: ${item.message}`)\n .join('\\n');\n}\n\n/** The single item's outcome, for callers that only ever send a batch of one. */\nexport function singleItemOutcome(op: Op): UpsertItemOutcome | undefined {\n return op.kind === 'upsert' ? op.items[0] : undefined;\n}\n\nfunction errorResult(document: TaskDocument, message: string): ApplyResult {\n return { document, op: { kind: 'error', message } };\n}\n\nfunction sameNumberList(a: number[] | undefined, b: number[] | undefined): boolean {\n const x = a ?? [];\n const y = b ?? [];\n return x.length === y.length && x.every((value, index) => value === y[index]);\n}\n\nfunction sameRecord(a: Record<string, unknown> | undefined, b: Record<string, unknown> | undefined): boolean {\n return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);\n}\n\n/**\n * Did this update change anything? A no-effect update (status re-set to its\n * current value, fields re-sent unchanged) reports \"No change\" rather than\n * \"Updated #N\" — without the distinction a model can loop re-issuing the same\n * call believing it never landed.\n */\nfunction taskChanged(before: Task, after: Task): boolean {\n return (\n before.subject !== after.subject ||\n before.status !== after.status ||\n before.description !== after.description ||\n before.activeForm !== after.activeForm ||\n before.owner !== after.owner ||\n !sameNumberList(before.blockedBy, after.blockedBy) ||\n !sameRecord(before.metadata, after.metadata)\n );\n}\n\nfunction withTasks(document: TaskDocument, tasks: Task[], nextId = document.nextId): TaskDocument {\n return { ...document, tasks, nextId };\n}\n\n/** Merge incoming metadata over a base; a `null` value deletes its key. */\nfunction mergeMetadata(\n base: Record<string, unknown> | undefined,\n incoming: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n const merged: Record<string, unknown> = { ...base };\n for (const [key, value] of Object.entries(incoming)) {\n if (value === null) delete merged[key];\n else merged[key] = value;\n }\n return Object.keys(merged).length ? merged : undefined;\n}\n\n/** Copy the optional scalar fields an item may set onto a task, in place. */\nfunction assignScalars(target: Task, item: TaskItemMutation): void {\n if (item.subject !== undefined) target.subject = item.subject;\n if (item.description !== undefined) target.description = item.description;\n if (item.activeForm !== undefined) target.activeForm = item.activeForm;\n if (item.owner !== undefined) target.owner = item.owner;\n if (item.metadata !== undefined) {\n const merged = mergeMetadata(target.metadata, item.metadata);\n if (merged === undefined) delete target.metadata;\n else target.metadata = merged;\n }\n}\n\n/**\n * Working state threaded item to item, so entry N observes every effect of\n * entries 1..N-1. `refIds` and `failedRefs` are what make the cascade work:\n * refs resolve backward only, so an entry that names a failed sibling is always\n * processed after the failure that killed it.\n */\ninterface UpsertContext {\n tasks: Task[];\n nextId: number;\n maxTasks: number;\n refIds: Map<string, number>;\n failedRefs: Map<string, number>;\n}\n\ntype Resolved = { ok: true; id: number } | { ok: false; message: string };\n\nfunction resolveDep(context: UpsertContext, field: string, token: DepToken): Resolved {\n if (typeof token === 'number') return { ok: true, id: token };\n if (!REF_PATTERN.test(token)) {\n return { ok: false, message: `${field}: \"${token}\" is not a valid ref; pass an existing task id as a number` };\n }\n const id = context.refIds.get(token);\n if (id !== undefined) return { ok: true, id };\n const failedAt = context.failedRefs.get(token);\n if (failedAt !== undefined) {\n return { ok: false, message: `${field}: ref \"${token}\" refers to item[${failedAt}], which failed` };\n }\n return {\n ok: false,\n message: `${field}: unknown ref \"${token}\" — a ref must be declared by an earlier entry in the same call`,\n };\n}\n\ntype ItemResult = { ok: true; outcome: UpsertItemOutcome } | { ok: false; message: string };\n\nfunction fail(message: string): ItemResult {\n return { ok: false, message };\n}\n\n/** Structural checks that apply to every entry, whichever kind it is. */\nfunction checkShape(context: UpsertContext, item: TaskItemMutation): string | undefined {\n if (item.ref !== undefined) {\n if (item.id !== undefined) return 'ref is only valid when creating a task; drop the id, or drop the ref';\n if (!REF_PATTERN.test(item.ref)) {\n return `ref \"${item.ref}\" is invalid: a ref must start with a letter and contain only letters, digits, - or _`;\n }\n const owner = context.refIds.get(item.ref) !== undefined || context.failedRefs.has(item.ref);\n if (owner) return `duplicate ref \"${item.ref}\": it was already declared by an earlier entry`;\n }\n return undefined;\n}\n\nfunction applyCreateItem(context: UpsertContext, item: TaskItemMutation, index: number, now: string): ItemResult {\n if (item.subject === undefined) return fail('subject is required when the entry has no id');\n if (!item.subject.trim()) return fail('subject must not be blank');\n if (item.addBlockedBy !== undefined || item.removeBlockedBy !== undefined) {\n return fail('addBlockedBy / removeBlockedBy are only for an entry with an id; a new task uses blockedBy');\n }\n // A task created as a tombstone is invisible to every view and can never\n // leave `deleted`, so it would be a write-only black hole.\n if (item.status === DELETED_STATUS) {\n return fail('cannot create a task with status deleted; create it, then use action delete');\n }\n\n const taskCount = context.tasks.filter((task) => task.status !== DELETED_STATUS).length;\n if (taskCount >= context.maxTasks) {\n return fail(`task limit of ${context.maxTasks} reached; delete completed tasks first before creating new tasks`);\n }\n\n const blockedBy: number[] = [];\n for (const token of item.blockedBy ?? []) {\n const resolved = resolveDep(context, 'blockedBy', token);\n if (!resolved.ok) return fail(resolved.message);\n const dep = context.tasks.find((task) => task.id === resolved.id);\n if (!dep) return fail(`blockedBy: #${resolved.id} not found`);\n if (dep.status === DELETED_STATUS) return fail(`blockedBy: #${resolved.id} is deleted`);\n if (!blockedBy.includes(resolved.id)) blockedBy.push(resolved.id);\n }\n\n // No cycle check is needed: the id is freshly allocated, so nothing already\n // in the document can point at it yet.\n const created: Task = {\n id: context.nextId,\n subject: item.subject,\n status: item.status ?? 'pending',\n createdAt: now,\n updatedAt: now,\n };\n assignScalars(created, item);\n if (blockedBy.length) created.blockedBy = blockedBy;\n\n context.nextId += 1;\n context.tasks.push(created);\n if (item.ref) context.refIds.set(item.ref, created.id);\n\n return {\n ok: true,\n outcome: {\n index,\n kind: 'created',\n id: created.id,\n subject: created.subject,\n status: created.status,\n ...(item.ref ? { ref: item.ref } : {}),\n ...(blockedBy.length ? { blockedBy } : {}),\n },\n };\n}\n\nfunction applyUpdateItem(context: UpsertContext, item: TaskItemMutation, index: number, now: string): ItemResult {\n const id = item.id as number;\n const at = context.tasks.findIndex((task) => task.id === id);\n if (at === -1) return fail(`#${id} not found`);\n if (item.blockedBy !== undefined) {\n return fail('blockedBy is only for a new entry; use addBlockedBy / removeBlockedBy on an entry that has an id');\n }\n\n const hasMutation =\n item.subject !== undefined ||\n item.description !== undefined ||\n item.activeForm !== undefined ||\n item.status !== undefined ||\n item.owner !== undefined ||\n item.metadata !== undefined ||\n Boolean(item.addBlockedBy?.length) ||\n Boolean(item.removeBlockedBy?.length);\n if (!hasMutation) {\n return fail(\n 'nothing to change: provide at least one of subject, description, activeForm, status, owner, metadata, addBlockedBy, or removeBlockedBy',\n );\n }\n\n const current = context.tasks[at];\n\n // The Task Space overlay commits free text from an inline editor, so a blank\n // subject reaches the reducer as a real update rather than as a missing\n // field. Persisting it would leave an unidentifiable row.\n if (item.subject !== undefined && !item.subject.trim()) return fail('subject must not be blank');\n\n let newStatus = current.status;\n if (item.status !== undefined) {\n if (!isTransitionValid(current.status, item.status)) {\n return fail(`illegal transition ${current.status} -> ${item.status}`);\n }\n newStatus = item.status;\n }\n\n let newBlockedBy = current.blockedBy ? [...current.blockedBy] : [];\n for (const token of item.removeBlockedBy ?? []) {\n const resolved = resolveDep(context, 'removeBlockedBy', token);\n if (!resolved.ok) return fail(resolved.message);\n // Removing an id that is not there is a well-defined no-op, so unlike the\n // add path this deliberately skips the existence check.\n newBlockedBy = newBlockedBy.filter((dep) => dep !== resolved.id);\n }\n for (const token of item.addBlockedBy ?? []) {\n const resolved = resolveDep(context, 'addBlockedBy', token);\n if (!resolved.ok) return fail(resolved.message);\n if (resolved.id === id) return fail(`cannot block #${id} on itself`);\n const dep = context.tasks.find((task) => task.id === resolved.id);\n if (!dep) return fail(`addBlockedBy: #${resolved.id} not found`);\n if (dep.status === DELETED_STATUS) return fail(`addBlockedBy: #${resolved.id} is deleted`);\n if (!newBlockedBy.includes(resolved.id)) newBlockedBy.push(resolved.id);\n }\n\n const updated: Task = { ...current, status: newStatus };\n assignScalars(updated, item);\n if (newBlockedBy.length) updated.blockedBy = newBlockedBy;\n else delete updated.blockedBy;\n\n // The candidate is written before the check because `detectCycle` unions the\n // node's stored edges with the ones passed in: checking against the old array\n // would resurrect an edge `removeBlockedBy` just stripped and reject a\n // remove+add that legitimately breaks a cycle.\n const candidate = [...context.tasks];\n candidate[at] = updated;\n if (item.addBlockedBy?.length && detectCycle(candidate, id, newBlockedBy)) {\n return fail('addBlockedBy would create a cycle in the blockedBy graph');\n }\n\n const changed = taskChanged(current, updated);\n if (changed) updated.updatedAt = now;\n context.tasks = candidate;\n\n return {\n ok: true,\n outcome: changed\n ? { index, kind: 'updated', id, fromStatus: current.status, toStatus: newStatus }\n : { index, kind: 'unchanged', id, status: newStatus },\n };\n}\n\n/**\n * Apply every entry in request order, threading the document.\n *\n * Each entry lands completely or not at all: a create whose dependencies fail\n * is not kept dependency-free, because handing back an unblocked task the\n * caller asked to be blocked is a lie it may immediately act on.\n */\nfunction applyUpsert(document: TaskDocument, items: TaskItemMutation[], now: string, maxTasks: number): ApplyResult {\n const context: UpsertContext = {\n tasks: [...document.tasks],\n nextId: document.nextId,\n maxTasks,\n refIds: new Map(),\n failedRefs: new Map(),\n };\n const outcomes: UpsertItemOutcome[] = [];\n let applied = 0;\n\n for (const [index, item] of items.entries()) {\n const shapeError = checkShape(context, item);\n const result = shapeError\n ? fail(shapeError)\n : item.id === undefined\n ? applyCreateItem(context, item, index, now)\n : applyUpdateItem(context, item, index, now);\n\n if (result.ok) {\n outcomes.push(result.outcome);\n applied += 1;\n continue;\n }\n // A ref whose owner failed must not read as a typo to the entries that\n // depend on it, so the dead ref is recorded rather than left unknown.\n if (item.ref && REF_PATTERN.test(item.ref) && !context.refIds.has(item.ref)) {\n context.failedRefs.set(item.ref, index);\n }\n outcomes.push({\n index,\n kind: 'failed',\n message: result.message,\n ...(item.id === undefined ? {} : { id: item.id }),\n ...(item.ref ? { ref: item.ref } : {}),\n });\n }\n\n return {\n // Nothing applied means nothing to write: returning the original object by\n // reference keeps the caller's write-skip path identical to a hard error.\n document: applied > 0 ? withTasks(document, context.tasks, context.nextId) : document,\n op: { kind: 'upsert', items: outcomes, applied, failed: outcomes.length - applied },\n };\n}\n\n/**\n * Pure reducer: (document, action, params) -> (document, op).\n *\n * All validation is in-line: structural guards plus state-aware checks\n * (transition legality, dangling or deleted blockedBy, self-block, cycles,\n * in-flight delegations). The caller owns persistence and formatting.\n */\nexport function applyTaskMutation(\n document: TaskDocument,\n action: ReducerAction,\n params: TaskMutationParams,\n now: string = new Date().toISOString(),\n maxTasks = DEFAULT_REDUCER_MAX_TASKS,\n): ApplyResult {\n switch (action) {\n case 'upsert': {\n const items = params.tasks;\n if (!Array.isArray(items) || items.length === 0) {\n return errorResult(\n document,\n 'upsert requires a non-empty tasks array, e.g. {\"action\":\"upsert\",\"tasks\":[{\"subject\":\"Write tests\"}]}',\n );\n }\n if (items.length > MAX_UPSERT_ITEMS) {\n return errorResult(\n document,\n `upsert accepts at most ${MAX_UPSERT_ITEMS} entries per call (received ${items.length})`,\n );\n }\n return applyUpsert(document, items, now, maxTasks);\n }\n\n case 'list': {\n return {\n document,\n op: {\n kind: 'list',\n includeDeleted: params.includeDeleted === true,\n ...(params.status !== undefined ? { statusFilter: params.status } : {}),\n },\n };\n }\n\n case 'get': {\n if (params.id === undefined) return errorResult(document, 'id required for get');\n const task = document.tasks.find((candidate) => candidate.id === params.id);\n if (!task) return errorResult(document, `#${params.id} not found`);\n return { document, op: { kind: 'get', task } };\n }\n\n case 'delete': {\n if (params.id === undefined) return errorResult(document, 'id required for delete');\n const index = document.tasks.findIndex((task) => task.id === params.id);\n if (index === -1) return errorResult(document, `#${params.id} not found`);\n const current = document.tasks[index];\n if (current.status === DELETED_STATUS) return errorResult(document, `#${current.id} is already deleted`);\n if (isDelegationActive(current)) {\n return errorResult(document, `#${current.id} has a running delegation — cancel it before deleting`);\n }\n\n const tasks = [...document.tasks];\n tasks[index] = { ...current, status: DELETED_STATUS, updatedAt: now };\n return {\n document: withTasks(document, tasks),\n op: { kind: 'delete', id: current.id, subject: current.subject },\n };\n }\n\n case 'clear': {\n const active = document.tasks.filter(isDelegationActive);\n if (active.length > 0) {\n const ids = active.map((task) => `#${task.id}`).join(', ');\n return errorResult(document, `cannot clear while delegations are running (${ids}) — cancel them first`);\n }\n const count = document.tasks.length;\n return {\n document: withTasks(document, [], 1),\n op: { kind: 'clear', count },\n };\n }\n }\n}\n"],"mappings":"oMAgBA,MAGa,EAAmB,IAOnB,EAAc,gCAiC3B,SAAgB,EAAe,EAAiB,CAC9C,OAAQ,EAAG,KAAX,CACE,IAAK,QACL,IAAK,OACL,IAAK,MACH,MAAO,GACT,IAAK,SACH,OAAO,EAAG,MAAM,KAAM,GAAS,EAAK,OAAS,WAAa,EAAK,OAAS,SAAS,EACnF,IAAK,SACL,IAAK,QACH,MAAO,EACX,CACF,CAGA,SAAgB,EAAoB,EAA6C,CAC/E,OAAO,EAAG,MACP,OAAQ,GAAS,EAAK,OAAS,QAAQ,CAAC,CACxC,IAAK,GAAS,QAAQ,EAAK,MAAM,KAAK,EAAK,SAAS,CAAC,CACrD,KAAK;CAAI,CACd,CAGA,SAAgB,EAAkB,EAAuC,CACvE,OAAO,EAAG,OAAS,SAAW,EAAG,M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AAU,GAAI,CAAE,KAAM,MAAO,MAAK,CAAE,EAD3B,EAAY,EAAU,IAAI,EAAO,GAAG,WAAW,CAEnE,CAEA,IAAK,SAAU,CACb,GAAI,EAAO,KAAO,IAAA,GAAW,OAAO,EAAY,EAAU,wBAAwB,EAClF,IAAM,EAAQ,EAAS,MAAM,UAAW,GAAS,EAAK,KAAO,EAAO,EAAE,EACtE,GAAI,IAAU,GAAI,OAAO,EAAY,EAAU,IAAI,EAAO,GAAG,WAAW,EACxE,IAAM,EAAU,EAAS,MAAM,GAC/B,GAAI,EAAQ,SAAA,UAA2B,OAAO,EAAY,EAAU,IAAI,EAAQ,GAAG,oBAAoB,EACvG,GAAI,EAAmB,CAAO,EAC5B,OAAO,EAAY,EAAU,IAAI,EAAQ,GAAG,sDAAsD,EAGpG,IAAM,EAAQ,CAAC,GAAG,EAAS,KAAK,EAEhC,MADA,GAAM,GAAS,CAAE,GAAG,EAAS,OAAQ,EAAgB,UAAW,CAAI,EAC7D,CACL,SAAU,EAAU,EAAU,CAAK,EACnC,GAAI,CAAE,KAAM,SAAU,GAAI,EAAQ,GAAI,QAAS,EAAQ,OAAQ,CACjE,CACF,CAEA,IAAK,QAAS,CACZ,IAAM,EAAS,EAAS,MAAM,OAAO,CAAkB,EACvD,GAAI,EAAO,OAAS,EAElB,OAAO,EAAY,EAAU,+CADjB,EAAO,IAAK,GAAS,IAAI,EAAK,IAAI,CAAC,CAAC,KAAK,IACyB,EAAE,sBAAsB,EAExG,IAAM,EAAQ,EAAS,MAAM,OAC7B,MAAO,CACL,SAAU,EAAU,EAAU,CAAC,EAAG,CAAC,EACnC,GAAI,CAAE,KAAM,QAAS,OAAM,CAC7B,CACF,CACF,CACF"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=`completed`,t=`cancelled`;function n(e){return e.tasks.filter(e=>e.status!==`deleted`)}function r(e,t){return`${e} ${t.map(e=>`Task ${e.id}: ${e.subject}`).join(`. `)}.`}function i(i,a,o){let s=new Map(a.tasks.map(e=>[e.id,e])),c=n(o).filter(e=>!s.has(e.id));if(c.length>0){let e=n(a).length===0?`Task list created.`:`Task list updated.`;i.narrate(r(e,c))}for(let n of o.tasks){let r=s.get(n.id);r&&(r.status!==e&&n.status===e&&i.narrate(`Task completed: ${n.subject}.`),r.delegation?.state!==t&&n.delegation?.state===t&&i.narrate(`Task cancelled: ${n.subject}.`))}}exports.narrateTaskCommit=i;
|
|
2
|
-
//# sourceMappingURL=index.cjs.map
|