@adhdev/daemon-core 0.9.82-rc.32 → 0.9.82-rc.320
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/boot/daemon-lifecycle.d.ts +8 -0
- package/dist/boot/process-hardening.d.ts +50 -0
- package/dist/build-info.d.ts +37 -0
- package/dist/chat/source-machine.d.ts +166 -0
- package/dist/chat/source-resolver.d.ts +104 -0
- package/dist/chat/subscription-updates.d.ts +1 -0
- package/dist/cli-adapter-types.d.ts +46 -2
- package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
- package/dist/cli-adapters/cli-state-engine.d.ts +198 -0
- package/dist/cli-adapters/provider-cli-adapter.d.ts +115 -64
- package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
- package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
- package/dist/cli-adapters/provider-cli-shared.d.ts +38 -0
- package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
- package/dist/cli-adapters/resolve-executable.d.ts +14 -0
- package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
- package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
- package/dist/cli-adapters/terminal-screen.d.ts +4 -11
- package/dist/commands/cli-manager.d.ts +2 -1
- package/dist/commands/handler.d.ts +110 -0
- package/dist/commands/mesh-coordinator.d.ts +85 -1
- package/dist/commands/router.d.ts +229 -1
- package/dist/commands/upgrade-helper.d.ts +12 -0
- package/dist/config/chat-history.d.ts +9 -0
- package/dist/config/config.d.ts +5 -0
- package/dist/config/mesh-config.d.ts +72 -1
- package/dist/detection/ide-detector.d.ts +13 -0
- package/dist/detection/win32-ide-version.d.ts +37 -0
- package/dist/git/git-commands.d.ts +9 -1
- package/dist/git/git-diff.d.ts +6 -0
- package/dist/git/git-executor.d.ts +11 -0
- package/dist/git/git-status.d.ts +9 -0
- package/dist/git/git-types.d.ts +2 -50
- package/dist/index.d.ts +51 -12
- package/dist/index.js +36031 -12365
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +40382 -16833
- package/dist/index.mjs.map +1 -1
- package/dist/installer.d.ts +1 -4
- package/dist/ipc/local-ipc-server.d.ts +91 -0
- package/dist/launch.d.ts +1 -1
- package/dist/logging/async-batch-writer.d.ts +10 -0
- package/dist/logging/log-redactor.d.ts +24 -0
- package/dist/logging/log-tail-reader.d.ts +46 -0
- package/dist/mesh/contracts.d.ts +164 -0
- package/dist/mesh/coordinator-prompt.d.ts +36 -0
- package/dist/mesh/coordinator-registry.d.ts +59 -0
- package/dist/mesh/mesh-active-work.d.ts +108 -0
- package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
- package/dist/mesh/mesh-events-coordinator.d.ts +169 -0
- package/dist/mesh/mesh-events-pending.d.ts +45 -0
- package/dist/mesh/mesh-events-stale.d.ts +40 -0
- package/dist/mesh/mesh-events-utils.d.ts +47 -0
- package/dist/mesh/mesh-events.d.ts +6 -49
- package/dist/mesh/mesh-fast-forward.d.ts +81 -0
- package/dist/mesh/mesh-host-ownership.d.ts +9 -0
- package/dist/mesh/mesh-init.d.ts +86 -0
- package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -3
- package/dist/mesh/mesh-ledger.d.ts +77 -1
- package/dist/mesh/mesh-missions.d.ts +116 -0
- package/dist/mesh/mesh-reconcile-loop.d.ts +7 -0
- package/dist/mesh/mesh-refine-batch.d.ts +68 -0
- package/dist/mesh/mesh-refine-status.d.ts +62 -0
- package/dist/mesh/mesh-review-inbox.d.ts +90 -0
- package/dist/mesh/mesh-routing.d.ts +70 -0
- package/dist/mesh/mesh-runtime-store.d.ts +401 -0
- package/dist/mesh/mesh-task-stats.d.ts +49 -0
- package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
- package/dist/mesh/mesh-work-queue.d.ts +226 -5
- package/dist/mesh/preview-freshness.d.ts +18 -0
- package/dist/mesh/refine-config.d.ts +215 -0
- package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
- package/dist/providers/acp-provider-instance.d.ts +2 -0
- package/dist/providers/approval-utils.d.ts +13 -0
- package/dist/providers/cli-provider-instance.d.ts +61 -3
- package/dist/providers/contracts.d.ts +130 -6
- package/dist/providers/external-sources.d.ts +71 -0
- package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
- package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
- package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
- package/dist/providers/native-history/dispatcher.d.ts +27 -0
- package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
- package/dist/providers/native-history/index.d.ts +13 -0
- package/dist/providers/provider-instance-manager.d.ts +13 -0
- package/dist/providers/provider-instance.d.ts +13 -1
- package/dist/providers/provider-loader.d.ts +26 -4
- package/dist/providers/provider-trust.d.ts +31 -0
- package/dist/providers/read-chat-contract.d.ts +29 -0
- package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
- package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +85 -0
- package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
- package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
- package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
- package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
- package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
- package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
- package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
- package/dist/providers/sdk/v1/index.d.ts +30 -0
- package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
- package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
- package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
- package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
- package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
- package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
- package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
- package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
- package/dist/providers/spec/adapter.d.ts +69 -0
- package/dist/providers/spec/cli-adapter.d.ts +217 -0
- package/dist/providers/spec/evaluator.d.ts +23 -0
- package/dist/providers/spec/fsm-driver.d.ts +278 -0
- package/dist/providers/spec/fsm-evaluator.d.ts +72 -0
- package/dist/providers/spec/fsm-loader.d.ts +14 -0
- package/dist/providers/spec/fsm-types.d.ts +128 -0
- package/dist/providers/spec/native-history-executor.d.ts +41 -0
- package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
- package/dist/providers/spec/route.d.ts +4 -0
- package/dist/providers/spec/types.d.ts +180 -0
- package/dist/providers/transcript-v2.d.ts +176 -0
- package/dist/providers/types/interactive-prompt.d.ts +84 -0
- package/dist/providers/working-dir.d.ts +17 -0
- package/dist/repo-mesh-types.d.ts +365 -13
- package/dist/sessions/registry.d.ts +6 -0
- package/dist/shared-types-extra.d.ts +2 -4
- package/dist/shared-types.d.ts +42 -1
- package/dist/status/normalize.d.ts +1 -1
- package/dist/status/normalize.js +1 -0
- package/dist/status/normalize.js.map +1 -1
- package/dist/status/normalize.mjs +1 -0
- package/dist/status/normalize.mjs.map +1 -1
- package/dist/status/reporter.d.ts +2 -0
- package/dist/status/snapshot.d.ts +1 -0
- package/dist/types.d.ts +5 -0
- package/package.json +7 -3
- package/src/agent-stream/poller.ts +2 -3
- package/src/boot/daemon-lifecycle.ts +55 -12
- package/src/boot/process-hardening.ts +89 -0
- package/src/build-info.ts +73 -0
- package/src/chat/source-machine.ts +534 -0
- package/src/chat/source-resolver.ts +0 -0
- package/src/chat/subscription-updates.ts +20 -1
- package/src/cli-adapter-types.d.ts +1 -0
- package/src/cli-adapter-types.ts +47 -2
- package/src/cli-adapters/cli-script-runner.ts +421 -0
- package/src/cli-adapters/cli-state-engine.ts +1215 -0
- package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
- package/src/cli-adapters/provider-cli-adapter.ts +710 -1140
- package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
- package/src/cli-adapters/provider-cli-parse.ts +13 -0
- package/src/cli-adapters/provider-cli-runtime.ts +56 -7
- package/src/cli-adapters/provider-cli-shared.d.ts +2 -0
- package/src/cli-adapters/provider-cli-shared.ts +85 -11
- package/src/cli-adapters/pty-transport.ts +2 -1
- package/src/cli-adapters/raw-terminal-io.ts +252 -0
- package/src/cli-adapters/resolve-executable.ts +90 -0
- package/src/cli-adapters/session-host-transport.ts +2 -1
- package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -29
- package/src/cli-adapters/terminal-backends/types.ts +10 -3
- package/src/cli-adapters/terminal-screen.ts +16 -81
- package/src/commands/chat-commands.ts +1822 -61
- package/src/commands/cli-manager.ts +286 -14
- package/src/commands/handler.ts +809 -2
- package/src/commands/mesh-coordinator.ts +332 -122
- package/src/commands/router.ts +6370 -704
- package/src/commands/stream-commands.ts +8 -0
- package/src/commands/upgrade-helper.ts +81 -30
- package/src/config/chat-history.ts +483 -24
- package/src/config/config.ts +12 -0
- package/src/config/mesh-config.ts +391 -4
- package/src/config/recent-activity.ts +8 -2
- package/src/daemon/dev-auto-implement.ts +3 -2
- package/src/daemon/dev-cli-debug.ts +10 -1
- package/src/detection/cli-detector.ts +28 -9
- package/src/detection/ide-detector.ts +55 -16
- package/src/detection/win32-ide-version.ts +106 -0
- package/src/git/git-commands.ts +42 -12
- package/src/git/git-diff.ts +53 -0
- package/src/git/git-executor.ts +12 -0
- package/src/git/git-status.ts +408 -43
- package/src/git/git-types.ts +14 -62
- package/src/git/git-worktree.ts +8 -1
- package/src/index.ts +151 -11
- package/src/installer.d.ts +1 -1
- package/src/installer.ts +8 -6
- package/src/ipc/local-ipc-server.ts +278 -0
- package/src/launch.d.ts +1 -1
- package/src/launch.ts +37 -28
- package/src/logging/async-batch-writer.ts +55 -0
- package/src/logging/log-redactor.ts +100 -0
- package/src/logging/log-tail-reader.ts +220 -0
- package/src/logging/logger.ts +2 -1
- package/src/mesh/contracts.ts +329 -0
- package/src/mesh/coordinator-prompt.ts +235 -31
- package/src/mesh/coordinator-registry.ts +121 -0
- package/src/mesh/mesh-active-work.ts +469 -0
- package/src/mesh/mesh-delivery-policy.ts +315 -0
- package/src/mesh/mesh-events-coordinator.ts +2102 -0
- package/src/mesh/mesh-events-pending.ts +508 -0
- package/src/mesh/mesh-events-stale.ts +290 -0
- package/src/mesh/mesh-events-utils.ts +254 -0
- package/src/mesh/mesh-events.ts +30 -1035
- package/src/mesh/mesh-fast-forward.ts +839 -0
- package/src/mesh/mesh-host-ownership.ts +73 -0
- package/src/mesh/mesh-init.ts +260 -0
- package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
- package/src/mesh/mesh-ledger.ts +589 -102
- package/src/mesh/mesh-missions.ts +248 -0
- package/src/mesh/mesh-reconcile-loop.ts +496 -0
- package/src/mesh/mesh-refine-batch.ts +197 -0
- package/src/mesh/mesh-refine-status.ts +231 -0
- package/src/mesh/mesh-review-inbox.ts +307 -0
- package/src/mesh/mesh-routing.ts +291 -0
- package/src/mesh/mesh-runtime-store.ts +1578 -0
- package/src/mesh/mesh-task-stats.ts +154 -0
- package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
- package/src/mesh/mesh-work-queue.ts +780 -139
- package/src/mesh/preview-freshness.ts +118 -0
- package/src/mesh/refine-config.ts +403 -0
- package/src/mesh/worktree-bootstrap-config.ts +326 -0
- package/src/providers/acp-provider-instance.ts +19 -4
- package/src/providers/approval-utils.d.ts +4 -0
- package/src/providers/approval-utils.ts +47 -5
- package/src/providers/chat-message-normalization.ts +4 -11
- package/src/providers/cli-provider-instance.ts +958 -91
- package/src/providers/contracts.d.ts +55 -0
- package/src/providers/contracts.ts +141 -6
- package/src/providers/extension-provider-instance.ts +5 -1
- package/src/providers/external-sources.ts +218 -0
- package/src/providers/ide-provider-instance.ts +25 -6
- package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
- package/src/providers/native-history/claude-cli-transcript.ts +396 -0
- package/src/providers/native-history/codex-cli-transcript.ts +479 -0
- package/src/providers/native-history/dispatcher.ts +340 -0
- package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
- package/src/providers/native-history/index.ts +30 -0
- package/src/providers/provider-instance-manager.ts +30 -0
- package/src/providers/provider-instance.ts +10 -1
- package/src/providers/provider-loader.ts +662 -50
- package/src/providers/provider-schema.ts +87 -14
- package/src/providers/provider-trust.ts +114 -0
- package/src/providers/read-chat-contract.ts +76 -16
- package/src/providers/sdk/README.md +49 -0
- package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
- package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
- package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
- package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
- package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
- package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
- package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
- package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
- package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
- package/src/providers/sdk/v1/index.ts +152 -0
- package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
- package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
- package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
- package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
- package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
- package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
- package/src/providers/sdk/v1/types/cli/index.ts +365 -0
- package/src/providers/sdk/v1/types/common/index.ts +229 -0
- package/src/providers/sdk/v1/validators/index.ts +19 -0
- package/src/providers/sdk/v1/validators/manifest.ts +110 -0
- package/src/providers/sdk/v1/validators/taint.ts +309 -0
- package/src/providers/spec/adapter.ts +168 -0
- package/src/providers/spec/cli-adapter.ts +986 -0
- package/src/providers/spec/evaluator.ts +345 -0
- package/src/providers/spec/fsm-driver.ts +909 -0
- package/src/providers/spec/fsm-evaluator.ts +255 -0
- package/src/providers/spec/fsm-loader.ts +112 -0
- package/src/providers/spec/fsm-types.ts +222 -0
- package/src/providers/spec/native-history-executor.ts +1136 -0
- package/src/providers/spec/pre-launch-trust.ts +104 -0
- package/src/providers/spec/route.ts +51 -0
- package/src/providers/spec/types.ts +226 -0
- package/src/providers/transcript-v2.ts +567 -0
- package/src/providers/types/interactive-prompt.ts +536 -0
- package/src/providers/version-archive.ts +64 -24
- package/src/providers/working-dir.ts +23 -0
- package/src/repo-mesh-types.ts +494 -13
- package/src/sessions/registry.ts +6 -0
- package/src/shared-types-extra.ts +2 -4
- package/src/shared-types.ts +45 -1
- package/src/status/builders.ts +26 -6
- package/src/status/normalize.ts +2 -0
- package/src/status/reporter.ts +15 -0
- package/src/status/snapshot.ts +84 -25
- package/src/system/host-memory.ts +29 -12
- package/src/types.ts +5 -0
- package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
- package/dist/mesh/mesh-sync.d.ts +0 -53
- package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
- package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
- package/src/mesh/mesh-sync.ts +0 -111
|
@@ -1,28 +1,160 @@
|
|
|
1
|
-
import { existsSync, writeFileSync, readFileSync, openSync, closeSync, unlinkSync } from 'fs';
|
|
2
|
-
import { join } from 'path';
|
|
3
1
|
import { randomUUID } from 'crypto';
|
|
4
|
-
import {
|
|
2
|
+
import { requireMeshHostQueueOwner } from './mesh-host-ownership.js';
|
|
3
|
+
import type { RepoMeshDaemonRole, LocalMeshNodeEntry } from '../repo-mesh-types.js';
|
|
4
|
+
import { MESH_CONVERGE_REFINE_TAG, resolveAutoConvergeCodeChange, resolveTaskAffinityRole } from '../repo-mesh-types.js';
|
|
5
|
+
import { MeshRuntimeStore } from './mesh-runtime-store.js';
|
|
6
|
+
import { getMesh } from '../config/mesh-config.js';
|
|
5
7
|
|
|
6
8
|
export type MeshTaskStatus = 'pending' | 'assigned' | 'completed' | 'failed' | 'cancelled';
|
|
7
9
|
export type MeshActiveTaskStatus = Extract<MeshTaskStatus, 'pending' | 'assigned'>;
|
|
8
10
|
export type MeshHistoricalTaskStatus = Extract<MeshTaskStatus, 'completed' | 'failed' | 'cancelled'>;
|
|
11
|
+
export type MeshTaskMode = 'code_change' | 'validation' | 'live_debug_readonly' | 'launch_app' | 'convergence';
|
|
9
12
|
|
|
10
13
|
export const ACTIVE_MESH_QUEUE_STATUSES: MeshActiveTaskStatus[] = ['pending', 'assigned'];
|
|
11
14
|
export const HISTORICAL_MESH_QUEUE_STATUSES: MeshHistoricalTaskStatus[] = ['completed', 'failed', 'cancelled'];
|
|
15
|
+
export const MESH_TASK_MODES: MeshTaskMode[] = ['code_change', 'validation', 'live_debug_readonly', 'launch_app', 'convergence'];
|
|
16
|
+
|
|
17
|
+
export interface MeshTaskModeValidationResult {
|
|
18
|
+
valid: boolean;
|
|
19
|
+
taskMode?: MeshTaskMode;
|
|
20
|
+
violations: string[];
|
|
21
|
+
allowedOperations?: string[];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const LIVE_DEBUG_READONLY_FORBIDDEN: Array<{ label: string; pattern: RegExp }> = [
|
|
25
|
+
{ label: 'source_edit', pattern: /\b(edit|modify|patch|apply\s+patch|write\s+(?:to\s+)?(?:file|source)|overwrite|delete\s+file|remove\s+file|create\s+file|touch\s+file)\b/i },
|
|
26
|
+
{ label: 'checkpoint', pattern: /\b(checkpoint|mesh_checkpoint)\b/i },
|
|
27
|
+
{ label: 'deploy_or_version_bump', pattern: /\b(deploy|wrangler\s+deploy|version[-\s]?bump|npm\s+version|release|npm\s+publish|yarn\s+publish|pnpm\s+publish)\b/i },
|
|
28
|
+
{ label: 'destructive_shell', pattern: /\b(rm\s+-rf|mv\s+\S+\s+\S+|truncate\s|tee\s+\S+|sed\s+-i|shred\b)\b/i },
|
|
29
|
+
{ label: 'package_install', pattern: /\b(npm\s+(?:install|i|add|link|uninstall|remove)|yarn\s+(?:add|remove|link)|pnpm\s+(?:add|remove|link)|pip\s+install|brew\s+install|apt\s+install|cargo\s+install)\b/i },
|
|
30
|
+
{ label: 'container_mutation', pattern: /\b(docker\s+(?:build|run|exec|push|tag|rmi|rm|create|start|stop|kill)|kubectl\s+(?:apply|delete|patch|replace|create|scale))\b/i },
|
|
31
|
+
];
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Git subcommands that mutate the working tree, index, refs, or remote.
|
|
35
|
+
* `stash` and `checkout` are intentionally absent here: they have read-only
|
|
36
|
+
* variants (`git stash list`/`show`, `git checkout-index`) and are classified
|
|
37
|
+
* token-by-token in {@link detectGitMutation} rather than by bare keyword.
|
|
38
|
+
*/
|
|
39
|
+
const GIT_MUTATION_SUBCOMMANDS = new Set([
|
|
40
|
+
'add', 'commit', 'push', 'reset', 'rebase', 'clean', 'switch', 'merge',
|
|
41
|
+
'tag', 'restore', 'rm', 'mv', 'cherry-pick', 'revert', 'pull', 'fetch',
|
|
42
|
+
'am', 'apply', 'gc', 'prune',
|
|
43
|
+
]);
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Read-only `git stash` variants. Any other `git stash <x>` (pop/apply/drop/
|
|
47
|
+
* push/save/clear, or bare `git stash` which defaults to push) is a mutation.
|
|
48
|
+
*/
|
|
49
|
+
const GIT_STASH_READONLY_SUBCOMMANDS = new Set(['list', 'show']);
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Detects a true git mutation in free-text task message, token-aware so that
|
|
53
|
+
* read-only diagnostics (`git stash list`, `git stash show --stat`,
|
|
54
|
+
* `git checkout-index`, `git status`, `git diff`, `git log`, ...) are allowed.
|
|
55
|
+
* Returns true only when a genuine mutating git invocation is present.
|
|
56
|
+
*/
|
|
57
|
+
function detectGitMutation(message: string): boolean {
|
|
58
|
+
const re = /\bgit\s+([a-z][a-z0-9-]*)/gi;
|
|
59
|
+
let match: RegExpExecArray | null;
|
|
60
|
+
while ((match = re.exec(message)) !== null) {
|
|
61
|
+
const sub = match[1].toLowerCase();
|
|
62
|
+
if (GIT_MUTATION_SUBCOMMANDS.has(sub)) return true;
|
|
63
|
+
if (sub === 'stash') {
|
|
64
|
+
// Token following `git stash`; read-only only for list/show.
|
|
65
|
+
const after = message.slice(re.lastIndex).match(/^\s+([a-z][a-z0-9-]*)/i);
|
|
66
|
+
const next = after ? after[1].toLowerCase() : '';
|
|
67
|
+
if (!GIT_STASH_READONLY_SUBCOMMANDS.has(next)) return true; // bare stash = push, or pop/apply/drop/...
|
|
68
|
+
} else if (sub === 'checkout') {
|
|
69
|
+
// `git checkout <ref/path>` mutates; `git checkout-index` is matched
|
|
70
|
+
// as its own token by the regex (sub === 'checkout-index') and is read-only.
|
|
71
|
+
return true;
|
|
72
|
+
} else if (sub === 'submodule') {
|
|
73
|
+
// `git submodule update` mutates; `git submodule status` is read-only.
|
|
74
|
+
const after = message.slice(re.lastIndex).match(/^\s+([a-z][a-z0-9-]*)/i);
|
|
75
|
+
const next = after ? after[1].toLowerCase() : '';
|
|
76
|
+
if (next === 'update' || next === 'add' || next === 'sync' || next === 'deinit') return true;
|
|
77
|
+
} else if (sub === 'worktree') {
|
|
78
|
+
const after = message.slice(re.lastIndex).match(/^\s+([a-z][a-z0-9-]*)/i);
|
|
79
|
+
const next = after ? after[1].toLowerCase() : '';
|
|
80
|
+
if (next === 'add' || next === 'remove' || next === 'move' || next === 'prune') return true;
|
|
81
|
+
}
|
|
82
|
+
// checkout-index, stash-with-no-next-already-handled, status/diff/log/show/
|
|
83
|
+
// rev-parse/branch/submodule status fall through as read-only.
|
|
84
|
+
}
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function normalizeMeshTaskMode(value: unknown): MeshTaskMode | undefined {
|
|
89
|
+
if (typeof value !== 'string') return undefined;
|
|
90
|
+
const normalized = value.trim() as MeshTaskMode;
|
|
91
|
+
return (MESH_TASK_MODES as string[]).includes(normalized) ? normalized : undefined;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function validateMeshTaskModeRequest(mode: unknown, message: string): MeshTaskModeValidationResult {
|
|
95
|
+
const taskMode = normalizeMeshTaskMode(mode);
|
|
96
|
+
if (!taskMode) {
|
|
97
|
+
return { valid: true, violations: [] };
|
|
98
|
+
}
|
|
99
|
+
if (taskMode !== 'live_debug_readonly') {
|
|
100
|
+
return { valid: true, taskMode, violations: [] };
|
|
101
|
+
}
|
|
102
|
+
const text = message || '';
|
|
103
|
+
const violations = LIVE_DEBUG_READONLY_FORBIDDEN
|
|
104
|
+
.filter(rule => rule.pattern.test(text))
|
|
105
|
+
.map(rule => rule.label);
|
|
106
|
+
if (detectGitMutation(text)) {
|
|
107
|
+
violations.push('git_mutation');
|
|
108
|
+
}
|
|
109
|
+
return {
|
|
110
|
+
valid: violations.length === 0,
|
|
111
|
+
taskMode,
|
|
112
|
+
violations,
|
|
113
|
+
allowedOperations: [
|
|
114
|
+
'process/log/window/port/session inspection',
|
|
115
|
+
'read-only filesystem listing/reading',
|
|
116
|
+
'status probes and keep-running handle reporting',
|
|
117
|
+
'diagnostic summaries without source edits, commits, checkpoints, pushes, deploys, resets, rebases, or destructive cleanups',
|
|
118
|
+
],
|
|
119
|
+
};
|
|
120
|
+
}
|
|
12
121
|
|
|
13
122
|
export interface MeshWorkQueueEntry {
|
|
14
123
|
id: string;
|
|
15
124
|
meshId: string;
|
|
16
125
|
message: string;
|
|
17
126
|
status: MeshTaskStatus;
|
|
127
|
+
taskMode?: MeshTaskMode;
|
|
18
128
|
/** If specified, only this node can claim the task (used by legacy mesh_send_task) */
|
|
19
129
|
targetNodeId?: string;
|
|
20
130
|
/** If specified, only this runtime session can claim the task */
|
|
21
131
|
targetSessionId?: string;
|
|
132
|
+
/** If specified, a node must expose all tags before it can claim the task. */
|
|
133
|
+
requiredTags?: string[];
|
|
134
|
+
/**
|
|
135
|
+
* M1: ids of tasks that must reach 'completed' before this task is claimable.
|
|
136
|
+
* Forward references (ids not yet enqueued) are allowed for batch flows and
|
|
137
|
+
* simply keep the task waiting until the referenced task exists and completes.
|
|
138
|
+
*/
|
|
139
|
+
dependsOn?: string[];
|
|
140
|
+
/** M1/M3: mission this task belongs to (joins mesh_missions). */
|
|
141
|
+
missionId?: string;
|
|
142
|
+
/**
|
|
143
|
+
* M1: why this task is held back (e.g. "dependency_failed:<taskId>").
|
|
144
|
+
* Only set by the system on dependency failure under the 'block' policy;
|
|
145
|
+
* waiting-on-dependency state is computed at view time, not stored.
|
|
146
|
+
*/
|
|
147
|
+
blockedReason?: string;
|
|
22
148
|
/** The node that actually claimed and is executing the task */
|
|
23
149
|
assignedNodeId?: string;
|
|
24
150
|
/** The session currently executing the task */
|
|
25
151
|
assignedSessionId?: string;
|
|
152
|
+
/**
|
|
153
|
+
* Provider type of the session that claimed the task. Recorded so the queue
|
|
154
|
+
* can enforce per-(node, provider) maxParallel caps (RepoMeshNodePolicy
|
|
155
|
+
* providerRoles) by counting active assignments grouped by node + provider.
|
|
156
|
+
*/
|
|
157
|
+
assignedProviderType?: string;
|
|
26
158
|
/** Human/operator reason for terminal cancellation. */
|
|
27
159
|
cancelReason?: string;
|
|
28
160
|
cancelledAt?: string;
|
|
@@ -30,6 +162,8 @@ export interface MeshWorkQueueEntry {
|
|
|
30
162
|
requeueReason?: string;
|
|
31
163
|
requeuedAt?: string;
|
|
32
164
|
requeueCount?: number;
|
|
165
|
+
/** Max automatic requeue attempts. When requeueCount reaches this, task is auto-failed. */
|
|
166
|
+
maxRetries?: number;
|
|
33
167
|
/** Last automatic queue session spin-up attempt, for mesh_view_queue/debug visibility. */
|
|
34
168
|
autoLaunch?: {
|
|
35
169
|
status: 'skipped' | 'started' | 'failed' | 'completed';
|
|
@@ -45,50 +179,268 @@ export interface MeshWorkQueueEntry {
|
|
|
45
179
|
updatedAt: string;
|
|
46
180
|
}
|
|
47
181
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
return join(getLedgerDir(), `${safe}.queue.json`);
|
|
182
|
+
export interface MeshQueueMutationOptions {
|
|
183
|
+
ownerRole?: RepoMeshDaemonRole;
|
|
51
184
|
}
|
|
52
185
|
|
|
53
|
-
function
|
|
54
|
-
|
|
55
|
-
|
|
186
|
+
export function normalizeMeshCapabilityTags(value: unknown): string[] {
|
|
187
|
+
if (!Array.isArray(value)) return [];
|
|
188
|
+
const seen = new Set<string>();
|
|
189
|
+
return value
|
|
190
|
+
.map(tag => typeof tag === 'string' ? tag.trim() : '')
|
|
191
|
+
.filter(Boolean)
|
|
192
|
+
.filter(tag => {
|
|
193
|
+
if (seen.has(tag)) return false;
|
|
194
|
+
seen.add(tag);
|
|
195
|
+
return true;
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function firstProviderPriority(policy: unknown): string | undefined {
|
|
200
|
+
const raw = policy && typeof policy === 'object' && !Array.isArray(policy)
|
|
201
|
+
? (policy as Record<string, unknown>).providerPriority
|
|
202
|
+
: undefined;
|
|
203
|
+
if (!Array.isArray(raw)) return undefined;
|
|
204
|
+
return raw.find(type => typeof type === 'string' && type.trim())?.trim();
|
|
56
205
|
}
|
|
57
206
|
|
|
58
207
|
/**
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
208
|
+
* Synthetic `role=<x>` capability tags advertised by a node's policy.providerRoles.
|
|
209
|
+
*
|
|
210
|
+
* When a specific `providerType` is being evaluated, only that provider's declared
|
|
211
|
+
* role is emitted — so role-based routing (requiredTags: ["role=validation"]) gates
|
|
212
|
+
* the *selected* provider through the ordinary capability-tag filter. When no
|
|
213
|
+
* provider is selected (node-level eligibility scan), every declared role is emitted
|
|
214
|
+
* so the node passes the filter if ANY of its providers could satisfy the role; the
|
|
215
|
+
* per-provider tag set then narrows it during provider selection.
|
|
216
|
+
*
|
|
217
|
+
* Roles are lowercased and deduped. Missing/empty providerRoles emits nothing, so a
|
|
218
|
+
* node that never declares roles advertises no `role=` tags and is therefore only
|
|
219
|
+
* matched by role-unconstrained tasks (full backward compatibility).
|
|
62
220
|
*/
|
|
63
|
-
function
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
221
|
+
function roleCapabilityTags(policy: unknown, providerType: string | undefined): string[] {
|
|
222
|
+
const roles = policy && typeof policy === 'object' && !Array.isArray(policy)
|
|
223
|
+
? (policy as Record<string, unknown>).providerRoles
|
|
224
|
+
: undefined;
|
|
225
|
+
if (!Array.isArray(roles)) return [];
|
|
226
|
+
const wantedProvider = typeof providerType === 'string' && providerType.trim()
|
|
227
|
+
? providerType.trim().toLowerCase()
|
|
228
|
+
: '';
|
|
229
|
+
const out: string[] = [];
|
|
230
|
+
for (const entry of roles) {
|
|
231
|
+
if (!entry || typeof entry !== 'object') continue;
|
|
232
|
+
const type = typeof (entry as any).providerType === 'string'
|
|
233
|
+
? (entry as any).providerType.trim().toLowerCase()
|
|
234
|
+
: '';
|
|
235
|
+
const role = typeof (entry as any).role === 'string'
|
|
236
|
+
? (entry as any).role.trim().toLowerCase()
|
|
237
|
+
: '';
|
|
238
|
+
if (!role) continue;
|
|
239
|
+
// When narrowing to a selected provider, only emit that provider's role.
|
|
240
|
+
if (wantedProvider && type && type !== wantedProvider) continue;
|
|
241
|
+
out.push(`role=${role}`);
|
|
71
242
|
}
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
243
|
+
return out;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export function buildMeshNodeCapabilityTags(
|
|
247
|
+
node: { capabilities?: unknown; policy?: unknown; isLocalWorktree?: unknown; worktreeBranch?: unknown } | undefined,
|
|
248
|
+
providerType?: string,
|
|
249
|
+
): string[] {
|
|
250
|
+
const provider = typeof providerType === 'string' && providerType.trim()
|
|
251
|
+
? providerType.trim()
|
|
252
|
+
: firstProviderPriority(node?.policy);
|
|
253
|
+
const worktreeBranch = typeof node?.worktreeBranch === 'string' && node.worktreeBranch.trim()
|
|
254
|
+
? node.worktreeBranch.trim()
|
|
255
|
+
: null;
|
|
256
|
+
return normalizeMeshCapabilityTags([
|
|
257
|
+
...(Array.isArray(node?.capabilities) ? node.capabilities : []),
|
|
258
|
+
`os=${process.platform}`,
|
|
259
|
+
`arch=${process.arch}`,
|
|
260
|
+
...(provider ? [`provider=${provider}`] : []),
|
|
261
|
+
// Worktree nodes automatically expose a "worktree=<branch>" tag so that
|
|
262
|
+
// mesh_enqueue_task with required_tags: ["worktree=<branch>"] routes
|
|
263
|
+
// only to the matching worktree node.
|
|
264
|
+
...(node?.isLocalWorktree === true && worktreeBranch ? [`worktree=${worktreeBranch}`] : []),
|
|
265
|
+
// Convergence routing: advertise how this node can land its work onto base.
|
|
266
|
+
// - converge=refine: local worktree nodes (on ANY machine — refine_mesh_node
|
|
267
|
+
// now forwards to the owning daemon) can run the Refinery merge → push →
|
|
268
|
+
// cleanup against their own checkout, so they accept code_change tasks.
|
|
269
|
+
// - converge=fast_forward: non-worktree nodes (the machine itself) can only
|
|
270
|
+
// ff/push an already-converged branch; they are NOT a destination for
|
|
271
|
+
// code_change work (a worktree is created first, and that worktree node
|
|
272
|
+
// receives the task instead). Reuses the ordinary required-tags filter —
|
|
273
|
+
// the load-balancing scheduler auto-injects converge=refine for code_change
|
|
274
|
+
// so such work is hard-filtered onto refine-capable nodes.
|
|
275
|
+
...(node?.isLocalWorktree === true ? ['converge=refine'] : ['converge=fast_forward']),
|
|
276
|
+
// Role-based routing: advertise role=<x> for each (node, provider) role
|
|
277
|
+
// declared in policy.providerRoles. Narrowed to the selected provider when
|
|
278
|
+
// one is given so the chosen provider must match a task's required role;
|
|
279
|
+
// when no provider is selected, all declared roles are advertised for the
|
|
280
|
+
// node-level eligibility scan. Reuses the ordinary required-tags filter —
|
|
281
|
+
// no separate role field/gate.
|
|
282
|
+
...roleCapabilityTags(node?.policy, providerType),
|
|
283
|
+
]);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export function nodeSatisfiesRequiredTags(requiredTags: unknown, capabilityTags: unknown): boolean {
|
|
287
|
+
const required = normalizeMeshCapabilityTags(requiredTags);
|
|
288
|
+
if (required.length === 0) return true;
|
|
289
|
+
const available = new Set(normalizeMeshCapabilityTags(capabilityTags));
|
|
290
|
+
return required.every(tag => available.has(tag));
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Convergence-aware required-tags resolution (load-balancing scheduler, opt-in).
|
|
295
|
+
*
|
|
296
|
+
* When the mesh enables policy.autoConvergeCodeChange, a `converge=refine` required
|
|
297
|
+
* tag is merged into a code_change task's required tags at enqueue time, so the
|
|
298
|
+
* scheduler hard-filters the task onto refine-capable worktree nodes only (on any
|
|
299
|
+
* machine — refine_mesh_node forwards to the owning daemon). Because the tag is
|
|
300
|
+
* persisted on the queue entry, BOTH the eligibility scan (maybeAutoLaunchOneQueueSession)
|
|
301
|
+
* and the claim transaction (claimNextQueueTask → nodeSatisfiesRequiredTags) enforce
|
|
302
|
+
* it consistently.
|
|
303
|
+
*
|
|
304
|
+
* Strict backward compatibility — the injection is skipped (returns the explicit tags
|
|
305
|
+
* unchanged) when ANY of:
|
|
306
|
+
* - the mesh does not opt in (autoConvergeCodeChange !== true), or
|
|
307
|
+
* - the task is not code_change (validation / live_debug_readonly / launch_app /
|
|
308
|
+
* convergence carry no merge cost and may run anywhere), or
|
|
309
|
+
* - the task is explicitly targeted (targetNodeId): the operator chose the node, so
|
|
310
|
+
* we do not second-guess it by filtering on convergence capability.
|
|
311
|
+
* Idempotent: normalizeMeshCapabilityTags dedupes, so re-injection is a no-op.
|
|
312
|
+
*/
|
|
313
|
+
export function resolveConvergeRequiredTags(
|
|
314
|
+
meshId: string,
|
|
315
|
+
taskMode: MeshTaskMode | undefined,
|
|
316
|
+
explicitRequiredTags: string[],
|
|
317
|
+
opts?: { targetNodeId?: string },
|
|
318
|
+
): string[] {
|
|
319
|
+
if (taskMode !== 'code_change') return explicitRequiredTags;
|
|
320
|
+
if (typeof opts?.targetNodeId === 'string' && opts.targetNodeId.trim()) return explicitRequiredTags;
|
|
321
|
+
let optedIn = false;
|
|
322
|
+
try {
|
|
323
|
+
optedIn = resolveAutoConvergeCodeChange(getMesh(meshId)?.policy as any);
|
|
324
|
+
} catch {
|
|
325
|
+
optedIn = false;
|
|
75
326
|
}
|
|
327
|
+
if (!optedIn) return explicitRequiredTags;
|
|
328
|
+
return normalizeMeshCapabilityTags([...explicitRequiredTags, MESH_CONVERGE_REFINE_TAG]);
|
|
76
329
|
}
|
|
77
330
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
331
|
+
/**
|
|
332
|
+
* Whether any node in the mesh advertises the given `role=<role>` capability tag.
|
|
333
|
+
* Reuses buildMeshNodeCapabilityTags (node-level scan: every declared providerRole is
|
|
334
|
+
* advertised) so the membership test matches the exact tag the claim/eligibility filter
|
|
335
|
+
* would see. Used to keep task-affinity SOFT — if no node can satisfy the role, the
|
|
336
|
+
* injection is skipped so the task falls back to ordinary least_loaded eligibility
|
|
337
|
+
* rather than being blocked.
|
|
338
|
+
*/
|
|
339
|
+
function meshHasNodeAdvertisingRole(nodes: LocalMeshNodeEntry[] | undefined, role: string): boolean {
|
|
340
|
+
if (!Array.isArray(nodes) || nodes.length === 0) return false;
|
|
341
|
+
const wanted = `role=${role}`;
|
|
342
|
+
return nodes.some(node => buildMeshNodeCapabilityTags(node as any).includes(wanted));
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Declarative task_mode → role affinity resolution (precedent: resolveConvergeRequiredTags).
|
|
347
|
+
*
|
|
348
|
+
* At enqueue time, auto-inject a `role=<role>` required tag derived from the task's
|
|
349
|
+
* taskMode via the mesh's policy.taskAffinity (falling back to DEFAULT_TASKMODE_ROLE_MAP),
|
|
350
|
+
* so the task hard-filters onto nodes advertising that role through the ordinary
|
|
351
|
+
* required-tags path (nodeSatisfiesRequiredTags) — no claim/scheduler change needed.
|
|
352
|
+
*
|
|
353
|
+
* Strict precedence / backward compatibility — the injection is skipped (returns the
|
|
354
|
+
* explicit tags unchanged) when ANY of:
|
|
355
|
+
* - the caller pinned an explicit targetNodeId (operator chose the node), or
|
|
356
|
+
* - the caller supplied their own non-empty required_tags (caller's routing wins), or
|
|
357
|
+
* - affinity resolves to no role (policy disabled, blank override, or unknown mode), or
|
|
358
|
+
* - SOFT fallback: no node in the mesh advertises the resolved role=<role> — injecting
|
|
359
|
+
* would block the task with zero eligible nodes, so we skip it and let least_loaded
|
|
360
|
+
* eligibility take over (a warning is logged so the misconfiguration is visible).
|
|
361
|
+
* Idempotent: normalizeMeshCapabilityTags dedupes.
|
|
362
|
+
*/
|
|
363
|
+
export function resolveTaskAffinityRequiredTags(
|
|
364
|
+
meshId: string,
|
|
365
|
+
taskMode: MeshTaskMode | undefined,
|
|
366
|
+
explicitRequiredTags: string[],
|
|
367
|
+
opts?: { targetNodeId?: string; callerSpecifiedRequiredTags?: boolean },
|
|
368
|
+
): string[] {
|
|
369
|
+
// Caller pinned the node, or brought their own required_tags → respect it verbatim.
|
|
370
|
+
if (typeof opts?.targetNodeId === 'string' && opts.targetNodeId.trim()) return explicitRequiredTags;
|
|
371
|
+
if (opts?.callerSpecifiedRequiredTags === true) return explicitRequiredTags;
|
|
372
|
+
|
|
373
|
+
let mesh;
|
|
81
374
|
try {
|
|
82
|
-
|
|
83
|
-
return JSON.parse(content) as MeshWorkQueueEntry[];
|
|
375
|
+
mesh = getMesh(meshId);
|
|
84
376
|
} catch {
|
|
85
|
-
return
|
|
377
|
+
return explicitRequiredTags;
|
|
378
|
+
}
|
|
379
|
+
const role = resolveTaskAffinityRole(taskMode, mesh?.policy?.taskAffinity);
|
|
380
|
+
if (!role) return explicitRequiredTags;
|
|
381
|
+
|
|
382
|
+
// SOFT affinity: only hard-filter when the role actually exists in the mesh.
|
|
383
|
+
if (!meshHasNodeAdvertisingRole(mesh?.nodes, role)) {
|
|
384
|
+
try {
|
|
385
|
+
console.warn(`[mesh] task_affinity: no node advertises role=${role} for taskMode=${taskMode} in mesh ${meshId}; skipping injection (least_loaded fallback)`);
|
|
386
|
+
} catch { /* logging is best-effort */ }
|
|
387
|
+
return explicitRequiredTags;
|
|
86
388
|
}
|
|
389
|
+
return normalizeMeshCapabilityTags([...explicitRequiredTags, `role=${role}`]);
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function withQueueLock<T>(_meshId: string, fn: () => T): T {
|
|
393
|
+
return MeshRuntimeStore.getInstance().transaction(fn);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
function readQueue(meshId: string): MeshWorkQueueEntry[] {
|
|
397
|
+
return MeshRuntimeStore.getInstance().getQueueEntries(meshId);
|
|
87
398
|
}
|
|
88
399
|
|
|
89
400
|
function writeQueue(meshId: string, queue: MeshWorkQueueEntry[]): void {
|
|
90
|
-
|
|
91
|
-
|
|
401
|
+
MeshRuntimeStore.getInstance().replaceQueue(meshId, queue);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function normalizeDependsOn(value: unknown): string[] {
|
|
405
|
+
if (!Array.isArray(value)) return [];
|
|
406
|
+
const seen = new Set<string>();
|
|
407
|
+
return value
|
|
408
|
+
.map(id => typeof id === 'string' ? id.trim() : '')
|
|
409
|
+
.filter(Boolean)
|
|
410
|
+
.filter(id => {
|
|
411
|
+
if (seen.has(id)) return false;
|
|
412
|
+
seen.add(id);
|
|
413
|
+
return true;
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* M1: detect dependency cycles before enqueue. Walks the dependency graph of
|
|
419
|
+
* existing queue entries plus the new task's edges. Fail-closed: a cycle
|
|
420
|
+
* rejects the enqueue entirely. Synchronous and bounded by queue size.
|
|
421
|
+
*/
|
|
422
|
+
export function assertNoDependencyCycle(meshId: string, newTaskId: string, dependsOn: string[]): void {
|
|
423
|
+
if (dependsOn.length === 0) return;
|
|
424
|
+
if (dependsOn.includes(newTaskId)) {
|
|
425
|
+
throw new Error(`dependency_cycle_detected: task '${newTaskId}' cannot depend on itself`);
|
|
426
|
+
}
|
|
427
|
+
const adjacency = new Map<string, string[]>();
|
|
428
|
+
for (const entry of readQueue(meshId)) {
|
|
429
|
+
adjacency.set(entry.id, normalizeDependsOn(entry.dependsOn));
|
|
430
|
+
}
|
|
431
|
+
adjacency.set(newTaskId, dependsOn);
|
|
432
|
+
// DFS from the new task: if we can reach newTaskId again, the edges form a cycle.
|
|
433
|
+
const stack = [...dependsOn];
|
|
434
|
+
const visited = new Set<string>();
|
|
435
|
+
while (stack.length > 0) {
|
|
436
|
+
const current = stack.pop()!;
|
|
437
|
+
if (current === newTaskId) {
|
|
438
|
+
throw new Error(`dependency_cycle_detected: task '${newTaskId}' is part of a dependency cycle via '${dependsOn.join(', ')}'`);
|
|
439
|
+
}
|
|
440
|
+
if (visited.has(current)) continue;
|
|
441
|
+
visited.add(current);
|
|
442
|
+
stack.push(...(adjacency.get(current) ?? []));
|
|
443
|
+
}
|
|
92
444
|
}
|
|
93
445
|
|
|
94
446
|
/**
|
|
@@ -97,22 +449,133 @@ function writeQueue(meshId: string, queue: MeshWorkQueueEntry[]): void {
|
|
|
97
449
|
export function enqueueTask(
|
|
98
450
|
meshId: string,
|
|
99
451
|
message: string,
|
|
100
|
-
opts?: {
|
|
452
|
+
opts?: {
|
|
453
|
+
targetNodeId?: string;
|
|
454
|
+
targetSessionId?: string;
|
|
455
|
+
taskMode?: MeshTaskMode | string;
|
|
456
|
+
requiredTags?: string[];
|
|
457
|
+
/** M1: tasks that must complete before this one is claimable. */
|
|
458
|
+
dependsOn?: string[];
|
|
459
|
+
/** M1/M3: mission this task belongs to. */
|
|
460
|
+
missionId?: string;
|
|
461
|
+
/** Explicit task id for batch/template flows (M5). Random UUID when omitted. */
|
|
462
|
+
id?: string;
|
|
463
|
+
} & MeshQueueMutationOptions,
|
|
101
464
|
): MeshWorkQueueEntry {
|
|
465
|
+
requireMeshHostQueueOwner(opts);
|
|
466
|
+
const modeValidation = validateMeshTaskModeRequest(opts?.taskMode, message);
|
|
467
|
+
if (!modeValidation.valid) {
|
|
468
|
+
throw new Error(`live_debug_readonly_guardrail_violation: forbidden operations (${modeValidation.violations.join(', ')})`);
|
|
469
|
+
}
|
|
470
|
+
const id = typeof opts?.id === 'string' && opts.id.trim() ? opts.id.trim() : randomUUID();
|
|
471
|
+
const dependsOn = normalizeDependsOn(opts?.dependsOn);
|
|
102
472
|
return withQueueLock(meshId, () => {
|
|
103
|
-
|
|
473
|
+
if (MeshRuntimeStore.getInstance().findQueueEntryById(meshId, id)) {
|
|
474
|
+
throw new Error(`duplicate_task_id: task '${id}' already exists in mesh '${meshId}'`);
|
|
475
|
+
}
|
|
476
|
+
assertNoDependencyCycle(meshId, id, dependsOn);
|
|
477
|
+
// Did the caller bring their own routing tags? Affinity auto-injection is
|
|
478
|
+
// suppressed when so (caller's required_tags win), matching the spec — measured
|
|
479
|
+
// against the ORIGINAL caller tags, before convergence augmentation below.
|
|
480
|
+
const callerTags = normalizeMeshCapabilityTags(opts?.requiredTags);
|
|
481
|
+
const callerSpecifiedRequiredTags = callerTags.length > 0;
|
|
482
|
+
// Convergence routing (opt-in): auto-inject converge=refine for code_change
|
|
483
|
+
// tasks so they hard-filter onto refine-capable worktree nodes. No-op unless
|
|
484
|
+
// the mesh opts in; explicit target_node_id / required_tags are preserved.
|
|
485
|
+
let resolvedRequiredTags = resolveConvergeRequiredTags(
|
|
486
|
+
meshId,
|
|
487
|
+
modeValidation.taskMode,
|
|
488
|
+
callerTags,
|
|
489
|
+
{ targetNodeId: opts?.targetNodeId },
|
|
490
|
+
);
|
|
491
|
+
// Declarative task_mode → role affinity (precedent: convergence routing above):
|
|
492
|
+
// inject role=<role> for the task's taskMode unless the caller pinned a node or
|
|
493
|
+
// supplied their own required_tags. SOFT — skipped when no node advertises the
|
|
494
|
+
// role (least_loaded fallback). Built-in default mapping applies even without a
|
|
495
|
+
// taskAffinity config block; { enabled:false } disables it.
|
|
496
|
+
resolvedRequiredTags = resolveTaskAffinityRequiredTags(
|
|
497
|
+
meshId,
|
|
498
|
+
modeValidation.taskMode,
|
|
499
|
+
resolvedRequiredTags,
|
|
500
|
+
{ targetNodeId: opts?.targetNodeId, callerSpecifiedRequiredTags },
|
|
501
|
+
);
|
|
104
502
|
const entry: MeshWorkQueueEntry = {
|
|
105
|
-
id
|
|
503
|
+
id,
|
|
106
504
|
meshId,
|
|
107
505
|
message,
|
|
108
506
|
status: 'pending',
|
|
507
|
+
taskMode: modeValidation.taskMode,
|
|
109
508
|
targetNodeId: opts?.targetNodeId,
|
|
110
509
|
targetSessionId: opts?.targetSessionId,
|
|
510
|
+
requiredTags: resolvedRequiredTags,
|
|
511
|
+
...(dependsOn.length > 0 ? { dependsOn } : {}),
|
|
512
|
+
...(typeof opts?.missionId === 'string' && opts.missionId.trim() ? { missionId: opts.missionId.trim() } : {}),
|
|
111
513
|
createdAt: new Date().toISOString(),
|
|
112
514
|
updatedAt: new Date().toISOString(),
|
|
113
515
|
};
|
|
114
|
-
|
|
115
|
-
|
|
516
|
+
MeshRuntimeStore.getInstance().insertQueueEntry(entry);
|
|
517
|
+
return entry;
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/**
|
|
522
|
+
* Record a direct-dispatch task (mesh_send_task) as an already-assigned queue
|
|
523
|
+
* entry so it is attributable to a mission.
|
|
524
|
+
*
|
|
525
|
+
* Direct dispatch normally bypasses the queue entirely — the task lives only in
|
|
526
|
+
* the ledger + mesh_direct_dispatches table, neither of which carries a
|
|
527
|
+
* missionId, so {@link summarizeMissionTasks}/{@link computeMeshTaskStats}
|
|
528
|
+
* (which both scan the queue for `task.missionId`) count it as 0. When a
|
|
529
|
+
* mission is attached, we materialise the same queue entry shape an enqueued
|
|
530
|
+
* task would have, but pre-assigned to the dispatched node/session and stamped
|
|
531
|
+
* with the dispatch timestamp. The terminal event path (updateSessionTaskStatus
|
|
532
|
+
* → findAssignedBySession) then flips it to completed/failed exactly like a
|
|
533
|
+
* pulled task, so mission total + completed aggregates work with no extra wiring.
|
|
534
|
+
*
|
|
535
|
+
* Intentionally separate from {@link enqueueTask}: enqueue creates `pending`
|
|
536
|
+
* work for the queue to assign, whereas this records work already dispatched
|
|
537
|
+
* out-of-band. They share the missionId stamping rule and mode validation.
|
|
538
|
+
*/
|
|
539
|
+
export function recordDirectDispatchTask(
|
|
540
|
+
meshId: string,
|
|
541
|
+
message: string,
|
|
542
|
+
opts: {
|
|
543
|
+
id: string;
|
|
544
|
+
missionId: string;
|
|
545
|
+
assignedNodeId?: string;
|
|
546
|
+
assignedSessionId?: string;
|
|
547
|
+
taskMode?: MeshTaskMode | string;
|
|
548
|
+
dispatchedAt?: string;
|
|
549
|
+
},
|
|
550
|
+
): MeshWorkQueueEntry | null {
|
|
551
|
+
const missionId = typeof opts.missionId === 'string' ? opts.missionId.trim() : '';
|
|
552
|
+
if (!missionId) return null;
|
|
553
|
+
const taskId = typeof opts.id === 'string' ? opts.id.trim() : '';
|
|
554
|
+
if (!taskId) return null;
|
|
555
|
+
const modeValidation = validateMeshTaskModeRequest(opts.taskMode, message);
|
|
556
|
+
if (!modeValidation.valid) {
|
|
557
|
+
throw new Error(`live_debug_readonly_guardrail_violation: forbidden operations (${modeValidation.violations.join(', ')})`);
|
|
558
|
+
}
|
|
559
|
+
const now = opts.dispatchedAt && opts.dispatchedAt.trim() ? opts.dispatchedAt : new Date().toISOString();
|
|
560
|
+
return withQueueLock(meshId, () => {
|
|
561
|
+
if (MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId)) {
|
|
562
|
+
// Already materialised (e.g. retry of the same dispatch) — leave it untouched.
|
|
563
|
+
return null;
|
|
564
|
+
}
|
|
565
|
+
const entry: MeshWorkQueueEntry = {
|
|
566
|
+
id: taskId,
|
|
567
|
+
meshId,
|
|
568
|
+
message,
|
|
569
|
+
status: 'assigned',
|
|
570
|
+
...(modeValidation.taskMode ? { taskMode: modeValidation.taskMode } : {}),
|
|
571
|
+
missionId,
|
|
572
|
+
...(opts.assignedNodeId ? { targetNodeId: opts.assignedNodeId, assignedNodeId: opts.assignedNodeId } : {}),
|
|
573
|
+
...(opts.assignedSessionId ? { targetSessionId: opts.assignedSessionId, assignedSessionId: opts.assignedSessionId } : {}),
|
|
574
|
+
dispatchTimestamp: now,
|
|
575
|
+
createdAt: now,
|
|
576
|
+
updatedAt: now,
|
|
577
|
+
};
|
|
578
|
+
MeshRuntimeStore.getInstance().insertQueueEntry(entry);
|
|
116
579
|
return entry;
|
|
117
580
|
});
|
|
118
581
|
}
|
|
@@ -121,43 +584,83 @@ export function enqueueTask(
|
|
|
121
584
|
* Get all tasks in the queue, optionally filtered by status.
|
|
122
585
|
*/
|
|
123
586
|
export function getQueue(meshId: string, opts?: { status?: MeshTaskStatus[] }): MeshWorkQueueEntry[] {
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
return queue;
|
|
587
|
+
return MeshRuntimeStore.getInstance().getQueueEntries(meshId, opts?.status?.length ? opts.status : undefined);
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
export function getMeshQueueRevision(meshId: string): string {
|
|
591
|
+
return MeshRuntimeStore.getInstance().getQueueRevision(meshId);
|
|
130
592
|
}
|
|
131
593
|
|
|
132
594
|
/**
|
|
133
595
|
* Find the next pending task that this node is allowed to claim, and mark it as assigned.
|
|
596
|
+
*
|
|
597
|
+
* `opts.providerType` is stamped onto the claimed entry (assignedProviderType) so
|
|
598
|
+
* per-(node, provider) caps can be counted. `opts.providerMaxParallel`, when set,
|
|
599
|
+
* is the enforced per-(node, provider) cap from RepoMeshNodePolicy.providerRoles:
|
|
600
|
+
* a task is not assigned to this (node, provider) once it already has that many
|
|
601
|
+
* active assignments. This composes with the global/taskMode caps (stricter wins).
|
|
134
602
|
*/
|
|
135
|
-
export function claimNextTask(
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
603
|
+
export function claimNextTask(
|
|
604
|
+
meshId: string,
|
|
605
|
+
nodeId: string,
|
|
606
|
+
sessionId: string,
|
|
607
|
+
capabilityTags?: string[],
|
|
608
|
+
opts?: { providerType?: string; providerMaxParallel?: number },
|
|
609
|
+
): MeshWorkQueueEntry | null {
|
|
610
|
+
return MeshRuntimeStore.getInstance().claimNextQueueTask(meshId, nodeId, sessionId, capabilityTags, opts);
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
// ─── M1: Dependency Failure Propagation ─────────
|
|
614
|
+
|
|
615
|
+
export type DependencyFailurePolicy = 'block' | 'cancel';
|
|
616
|
+
|
|
617
|
+
function resolveDependencyFailurePolicy(meshId: string): DependencyFailurePolicy {
|
|
618
|
+
try {
|
|
619
|
+
const policy = (getMesh(meshId)?.policy ?? {}) as Record<string, unknown>;
|
|
620
|
+
return policy.onDependencyFailure === 'cancel' ? 'cancel' : 'block';
|
|
621
|
+
} catch {
|
|
622
|
+
return 'block';
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* Apply the mesh's onDependencyFailure policy to pending dependents of a task
|
|
628
|
+
* that just reached a failed/cancelled terminal state.
|
|
629
|
+
*
|
|
630
|
+
* - 'block' (default): dependents stay pending with blockedReason
|
|
631
|
+
* "dependency_failed:<taskId>" so an operator can requeue/cancel them.
|
|
632
|
+
* - 'cancel': dependents are cancelled (cascading to their own dependents).
|
|
633
|
+
*
|
|
634
|
+
* Must be called inside the queue lock of the triggering transition.
|
|
635
|
+
*/
|
|
636
|
+
function propagateDependencyFailure(meshId: string, failedTaskId: string): void {
|
|
637
|
+
const policy = resolveDependencyFailurePolicy(meshId);
|
|
638
|
+
const store = MeshRuntimeStore.getInstance();
|
|
639
|
+
const frontier = [failedTaskId];
|
|
640
|
+
const seen = new Set<string>(frontier);
|
|
641
|
+
while (frontier.length > 0) {
|
|
642
|
+
const currentId = frontier.pop()!;
|
|
643
|
+
const dependents = store.getQueueEntries(meshId, ['pending'])
|
|
644
|
+
.filter(entry => Array.isArray(entry.dependsOn) && entry.dependsOn.includes(currentId));
|
|
645
|
+
for (const dependent of dependents) {
|
|
646
|
+
if (seen.has(dependent.id)) continue;
|
|
647
|
+
seen.add(dependent.id);
|
|
648
|
+
if (policy === 'cancel') {
|
|
649
|
+
dependent.status = 'cancelled';
|
|
650
|
+
dependent.cancelledAt = new Date().toISOString();
|
|
651
|
+
dependent.cancelReason = `dependency_failed:${currentId}`;
|
|
652
|
+
store.updateQueueEntry(dependent);
|
|
653
|
+
frontier.push(dependent.id); // cascade to transitive dependents
|
|
654
|
+
} else {
|
|
655
|
+
dependent.blockedReason = `dependency_failed:${currentId}`;
|
|
656
|
+
store.updateQueueEntry(dependent);
|
|
657
|
+
}
|
|
148
658
|
}
|
|
149
|
-
|
|
150
|
-
const entry = queue[targetIdx];
|
|
151
|
-
entry.status = 'assigned';
|
|
152
|
-
entry.assignedNodeId = nodeId;
|
|
153
|
-
entry.assignedSessionId = sessionId;
|
|
154
|
-
entry.dispatchTimestamp = new Date().toISOString();
|
|
155
|
-
entry.updatedAt = new Date().toISOString();
|
|
156
|
-
writeQueue(meshId, queue);
|
|
157
|
-
return entry;
|
|
158
|
-
});
|
|
659
|
+
}
|
|
159
660
|
}
|
|
160
661
|
|
|
662
|
+
const DEPENDENCY_FAILURE_TERMINALS = new Set<MeshTaskStatus>(['failed', 'cancelled']);
|
|
663
|
+
|
|
161
664
|
/**
|
|
162
665
|
* Update the status of a specific task.
|
|
163
666
|
* Used when a session completes, fails, or stalls.
|
|
@@ -166,15 +669,16 @@ export function updateTaskStatus(
|
|
|
166
669
|
meshId: string,
|
|
167
670
|
taskId: string,
|
|
168
671
|
status: MeshTaskStatus,
|
|
672
|
+
opts?: MeshQueueMutationOptions,
|
|
169
673
|
): MeshWorkQueueEntry | null {
|
|
674
|
+
requireMeshHostQueueOwner(opts);
|
|
170
675
|
return withQueueLock(meshId, () => {
|
|
171
|
-
const
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
return queue[idx];
|
|
676
|
+
const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
|
|
677
|
+
if (!entry) return null;
|
|
678
|
+
entry.status = status;
|
|
679
|
+
MeshRuntimeStore.getInstance().updateQueueEntry(entry);
|
|
680
|
+
if (DEPENDENCY_FAILURE_TERMINALS.has(status)) propagateDependencyFailure(meshId, taskId);
|
|
681
|
+
return entry;
|
|
178
682
|
});
|
|
179
683
|
}
|
|
180
684
|
|
|
@@ -184,14 +688,12 @@ export function recordTaskAutoLaunch(
|
|
|
184
688
|
autoLaunch: Omit<NonNullable<MeshWorkQueueEntry['autoLaunch']>, 'updatedAt'>,
|
|
185
689
|
): MeshWorkQueueEntry | null {
|
|
186
690
|
return withQueueLock(meshId, () => {
|
|
187
|
-
const
|
|
188
|
-
|
|
189
|
-
if (idx === -1) return null;
|
|
691
|
+
const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
|
|
692
|
+
if (!entry) return null;
|
|
190
693
|
const now = new Date().toISOString();
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
return queue[idx];
|
|
694
|
+
entry.autoLaunch = { ...autoLaunch, updatedAt: now };
|
|
695
|
+
MeshRuntimeStore.getInstance().updateQueueEntry(entry);
|
|
696
|
+
return entry;
|
|
195
697
|
});
|
|
196
698
|
}
|
|
197
699
|
|
|
@@ -201,19 +703,19 @@ export function recordTaskAutoLaunch(
|
|
|
201
703
|
export function cancelTask(
|
|
202
704
|
meshId: string,
|
|
203
705
|
taskId: string,
|
|
204
|
-
opts?: { reason?: string },
|
|
706
|
+
opts?: { reason?: string } & MeshQueueMutationOptions,
|
|
205
707
|
): MeshWorkQueueEntry | null {
|
|
708
|
+
requireMeshHostQueueOwner(opts);
|
|
206
709
|
return withQueueLock(meshId, () => {
|
|
207
|
-
const
|
|
208
|
-
|
|
209
|
-
if (idx === -1) return null;
|
|
710
|
+
const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
|
|
711
|
+
if (!entry) return null;
|
|
210
712
|
const now = new Date().toISOString();
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
return
|
|
713
|
+
entry.status = 'cancelled';
|
|
714
|
+
entry.cancelledAt = now;
|
|
715
|
+
if (opts?.reason) entry.cancelReason = opts.reason;
|
|
716
|
+
MeshRuntimeStore.getInstance().updateQueueEntry(entry);
|
|
717
|
+
propagateDependencyFailure(meshId, taskId);
|
|
718
|
+
return entry;
|
|
217
719
|
});
|
|
218
720
|
}
|
|
219
721
|
|
|
@@ -221,6 +723,11 @@ export function cancelTask(
|
|
|
221
723
|
* Return a queue task to pending for retry. By default, dead session targeting
|
|
222
724
|
* and assigned ownership are cleared so stale assignments do not strand again.
|
|
223
725
|
*/
|
|
726
|
+
export type RequeueResult =
|
|
727
|
+
| { status: 'requeued'; entry: MeshWorkQueueEntry }
|
|
728
|
+
| { status: 'failed_max_retries'; entry: MeshWorkQueueEntry; maxRetries: number; requeueCount: number }
|
|
729
|
+
| { status: 'not_found' };
|
|
730
|
+
|
|
224
731
|
export function requeueTask(
|
|
225
732
|
meshId: string,
|
|
226
733
|
taskId: string,
|
|
@@ -230,15 +737,34 @@ export function requeueTask(
|
|
|
230
737
|
targetSessionId?: string;
|
|
231
738
|
clearTargetNode?: boolean;
|
|
232
739
|
clearTargetSession?: boolean;
|
|
233
|
-
|
|
740
|
+
/**
|
|
741
|
+
* Override the retry cap for this call. Use only for explicit operator actions.
|
|
742
|
+
* If true, the task is requeued even when requeueCount >= maxRetries.
|
|
743
|
+
*/
|
|
744
|
+
force?: boolean;
|
|
745
|
+
/** Per-task retry cap override. Falls back to mesh policy maxTaskRetries (default 1). */
|
|
746
|
+
maxRetries?: number;
|
|
747
|
+
} & MeshQueueMutationOptions,
|
|
234
748
|
): MeshWorkQueueEntry | null {
|
|
749
|
+
requireMeshHostQueueOwner(opts);
|
|
235
750
|
return withQueueLock(meshId, () => {
|
|
236
|
-
const
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
const
|
|
240
|
-
|
|
751
|
+
const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
|
|
752
|
+
if (!entry) return null;
|
|
753
|
+
const currentCount = entry.requeueCount || 0;
|
|
754
|
+
const maxRetries = opts?.maxRetries ?? entry.maxRetries ?? 1;
|
|
755
|
+
if (!opts?.force && currentCount >= maxRetries) {
|
|
756
|
+
// Auto-fail: cap exceeded without explicit force override.
|
|
757
|
+
entry.status = 'failed';
|
|
758
|
+
entry.cancelReason = `max_retries_exceeded: requeued ${currentCount} time(s), limit is ${maxRetries}`;
|
|
759
|
+
entry.updatedAt = new Date().toISOString();
|
|
760
|
+
MeshRuntimeStore.getInstance().updateQueueEntry(entry);
|
|
761
|
+
propagateDependencyFailure(meshId, taskId);
|
|
762
|
+
return entry;
|
|
763
|
+
}
|
|
241
764
|
entry.status = 'pending';
|
|
765
|
+
// Operator requeue clears a dependency-failure block — the operator is
|
|
766
|
+
// explicitly overriding the held-back state.
|
|
767
|
+
delete entry.blockedReason;
|
|
242
768
|
delete entry.assignedNodeId;
|
|
243
769
|
delete entry.assignedSessionId;
|
|
244
770
|
delete entry.cancelledAt;
|
|
@@ -247,11 +773,10 @@ export function requeueTask(
|
|
|
247
773
|
if (typeof opts?.targetNodeId === 'string') entry.targetNodeId = opts.targetNodeId;
|
|
248
774
|
if (opts?.clearTargetSession !== false) delete entry.targetSessionId;
|
|
249
775
|
if (typeof opts?.targetSessionId === 'string') entry.targetSessionId = opts.targetSessionId;
|
|
250
|
-
entry.
|
|
251
|
-
entry.
|
|
252
|
-
entry.requeueCount = (entry.requeueCount || 0) + 1;
|
|
776
|
+
entry.requeuedAt = new Date().toISOString();
|
|
777
|
+
entry.requeueCount = currentCount + 1;
|
|
253
778
|
if (opts?.reason) entry.requeueReason = opts.reason;
|
|
254
|
-
|
|
779
|
+
MeshRuntimeStore.getInstance().updateQueueEntry(entry);
|
|
255
780
|
return entry;
|
|
256
781
|
});
|
|
257
782
|
}
|
|
@@ -266,25 +791,42 @@ export function updateSessionTaskStatus(
|
|
|
266
791
|
opts?: { occurredAt?: string },
|
|
267
792
|
): MeshWorkQueueEntry | null {
|
|
268
793
|
return withQueueLock(meshId, () => {
|
|
269
|
-
const
|
|
270
|
-
const
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
const time = new Date(queue[i].dispatchTimestamp || queue[i].updatedAt).getTime();
|
|
277
|
-
if (hasOccurredAt && Number.isFinite(time) && time > occurredAtTime) continue;
|
|
278
|
-
if (time > bestTime) { bestTime = time; bestIdx = i; }
|
|
279
|
-
}
|
|
280
|
-
if (bestIdx === -1) return null;
|
|
281
|
-
queue[bestIdx].status = status;
|
|
282
|
-
queue[bestIdx].updatedAt = new Date().toISOString();
|
|
283
|
-
writeQueue(meshId, queue);
|
|
284
|
-
return queue[bestIdx];
|
|
794
|
+
const occurredAtIso = opts?.occurredAt ? new Date(opts.occurredAt).toISOString() : undefined;
|
|
795
|
+
const entry = MeshRuntimeStore.getInstance().findAssignedBySession(meshId, sessionId, occurredAtIso);
|
|
796
|
+
if (!entry) return null;
|
|
797
|
+
entry.status = status;
|
|
798
|
+
MeshRuntimeStore.getInstance().updateQueueEntry(entry);
|
|
799
|
+
if (DEPENDENCY_FAILURE_TERMINALS.has(status)) propagateDependencyFailure(meshId, entry.id);
|
|
800
|
+
return entry;
|
|
285
801
|
});
|
|
286
802
|
}
|
|
287
803
|
|
|
804
|
+
/**
|
|
805
|
+
* M1-3: true when at least one pending task is waiting on the given task.
|
|
806
|
+
* Used by the completion event path to decide whether to wake the queue.
|
|
807
|
+
*/
|
|
808
|
+
export function hasPendingDependents(meshId: string, taskId: string): boolean {
|
|
809
|
+
return MeshRuntimeStore.getInstance().getQueueEntries(meshId, ['pending'])
|
|
810
|
+
.some(entry => Array.isArray(entry.dependsOn) && entry.dependsOn.includes(taskId));
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
/**
|
|
814
|
+
* M1-4: view-time dependency state for a task — unmet dependency ids and
|
|
815
|
+
* whether the task is currently claimable from a dependency standpoint.
|
|
816
|
+
* Not stored (truth stays in task statuses).
|
|
817
|
+
*/
|
|
818
|
+
export function describeTaskDependencyState(
|
|
819
|
+
entry: Pick<MeshWorkQueueEntry, 'dependsOn' | 'blockedReason'>,
|
|
820
|
+
statusById: Map<string, MeshTaskStatus | string>,
|
|
821
|
+
): { waitingOn: string[]; dependenciesSatisfied: boolean } {
|
|
822
|
+
const deps = Array.isArray(entry.dependsOn) ? entry.dependsOn : [];
|
|
823
|
+
const waitingOn = deps.filter(depId => statusById.get(depId) !== 'completed');
|
|
824
|
+
return {
|
|
825
|
+
waitingOn,
|
|
826
|
+
dependenciesSatisfied: waitingOn.length === 0 && !entry.blockedReason,
|
|
827
|
+
};
|
|
828
|
+
}
|
|
829
|
+
|
|
288
830
|
export interface MeshWorkQueueStats {
|
|
289
831
|
total: number;
|
|
290
832
|
active: number;
|
|
@@ -310,14 +852,16 @@ export interface MeshWorkQueueStats {
|
|
|
310
852
|
* Return aggregate queue statistics for the given mesh.
|
|
311
853
|
*/
|
|
312
854
|
export function getMeshQueueStats(meshId: string): MeshWorkQueueStats {
|
|
313
|
-
const
|
|
314
|
-
const
|
|
315
|
-
const
|
|
316
|
-
const
|
|
317
|
-
const
|
|
318
|
-
const
|
|
855
|
+
const rows = MeshRuntimeStore.getInstance().getQueueStatsByStatus(meshId);
|
|
856
|
+
const counts: Record<string, number> = {};
|
|
857
|
+
for (const r of rows) counts[r.status] = r.count;
|
|
858
|
+
const pending = counts['pending'] ?? 0;
|
|
859
|
+
const assigned = counts['assigned'] ?? 0;
|
|
860
|
+
const completed = counts['completed'] ?? 0;
|
|
861
|
+
const failed = counts['failed'] ?? 0;
|
|
862
|
+
const cancelled = counts['cancelled'] ?? 0;
|
|
319
863
|
return {
|
|
320
|
-
total:
|
|
864
|
+
total: pending + assigned + completed + failed + cancelled,
|
|
321
865
|
active: pending + assigned,
|
|
322
866
|
historical: completed + failed + cancelled,
|
|
323
867
|
pending,
|
|
@@ -325,22 +869,119 @@ export function getMeshQueueStats(meshId: string): MeshWorkQueueStats {
|
|
|
325
869
|
completed,
|
|
326
870
|
failed,
|
|
327
871
|
cancelled,
|
|
328
|
-
activeCounts: {
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
},
|
|
332
|
-
historicalCounts: {
|
|
333
|
-
completed,
|
|
334
|
-
failed,
|
|
335
|
-
cancelled,
|
|
336
|
-
},
|
|
337
|
-
activeAssignments: queue
|
|
338
|
-
.filter(q => q.status === 'assigned')
|
|
339
|
-
.map(q => ({
|
|
340
|
-
id: q.id,
|
|
341
|
-
nodeId: q.assignedNodeId,
|
|
342
|
-
sessionId: q.assignedSessionId,
|
|
343
|
-
message: q.message,
|
|
344
|
-
})),
|
|
872
|
+
activeCounts: { pending, assigned },
|
|
873
|
+
historicalCounts: { completed, failed, cancelled },
|
|
874
|
+
activeAssignments: MeshRuntimeStore.getInstance().getActiveAssignmentDetails(meshId),
|
|
345
875
|
};
|
|
346
876
|
}
|
|
877
|
+
|
|
878
|
+
export function __replaceMeshQueueForTests(meshId: string, queue: MeshWorkQueueEntry[]): void {
|
|
879
|
+
MeshRuntimeStore.getInstance().transaction(() => {
|
|
880
|
+
MeshRuntimeStore.getInstance().replaceQueue(meshId, queue);
|
|
881
|
+
});
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
export function __clearMeshQueueForTests(meshId: string): void {
|
|
885
|
+
MeshRuntimeStore.getInstance().deleteQueue(meshId);
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
export function __clearDirectDispatchesForTests(meshId: string): void {
|
|
889
|
+
MeshRuntimeStore.getInstance().deleteDirectDispatches(meshId);
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
export function __resetMeshRuntimeStoreForTests(): void {
|
|
893
|
+
MeshRuntimeStore.resetForTests();
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
// ── Direct Dispatch Tracking ─────────────────────────────────────────────────
|
|
897
|
+
// Persists direct (non-queue) task dispatches so buildMeshActiveWork can read
|
|
898
|
+
// active work from MeshRuntimeStore instead of scanning ledger JSONL entries.
|
|
899
|
+
|
|
900
|
+
export type DirectDispatchRecord = ReturnType<MeshRuntimeStore['getActiveDirectDispatches']>[number];
|
|
901
|
+
|
|
902
|
+
export function insertDirectDispatch(
|
|
903
|
+
meshId: string,
|
|
904
|
+
data: {
|
|
905
|
+
taskId: string;
|
|
906
|
+
nodeId?: string;
|
|
907
|
+
sessionId?: string;
|
|
908
|
+
providerType?: string;
|
|
909
|
+
message: string;
|
|
910
|
+
taskMode?: string;
|
|
911
|
+
via: string;
|
|
912
|
+
dispatchedToIdleSession?: boolean;
|
|
913
|
+
dispatchedAt: string;
|
|
914
|
+
},
|
|
915
|
+
): void {
|
|
916
|
+
try {
|
|
917
|
+
MeshRuntimeStore.getInstance().insertDirectDispatch({ ...data, meshId });
|
|
918
|
+
} catch (e: any) {
|
|
919
|
+
process.stderr.write(`[adhdev-mesh] insertDirectDispatch failed for task ${data.taskId}: ${e?.message || e}\n`);
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
export function getActiveDirectDispatches(meshId: string): DirectDispatchRecord[] {
|
|
924
|
+
try {
|
|
925
|
+
return MeshRuntimeStore.getInstance().getActiveDirectDispatches(meshId);
|
|
926
|
+
} catch {
|
|
927
|
+
return [];
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
export function updateDirectDispatchStatus(
|
|
932
|
+
meshId: string,
|
|
933
|
+
sessionId: string,
|
|
934
|
+
status: 'acked' | 'completed' | 'failed' | 'stale',
|
|
935
|
+
): void {
|
|
936
|
+
try {
|
|
937
|
+
MeshRuntimeStore.getInstance().updateDirectDispatchStatus(meshId, sessionId, status);
|
|
938
|
+
} catch { /* best-effort */ }
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
export function cleanupTerminalDirectDispatches(olderThanMs = 7 * 24 * 60 * 60_000): void {
|
|
942
|
+
try {
|
|
943
|
+
MeshRuntimeStore.getInstance().cleanupTerminalDirectDispatches(olderThanMs);
|
|
944
|
+
} catch { /* best-effort */ }
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
export function markStaleDirectDispatches(meshId: string, olderThanMs = 60 * 60_000): void {
|
|
948
|
+
try {
|
|
949
|
+
MeshRuntimeStore.getInstance().markStaleDirectDispatches(meshId, olderThanMs);
|
|
950
|
+
} catch { /* best-effort */ }
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
/**
|
|
954
|
+
* Delete specific direct dispatch rows by taskId. Returns the number of rows deleted.
|
|
955
|
+
* Used by the staleDirect prune path to evict orphaned/terminal dispatch records from the
|
|
956
|
+
* active staleDirect surface while leaving the append-only mesh ledger (audit history) intact.
|
|
957
|
+
*/
|
|
958
|
+
export function deleteDirectDispatchesByTaskId(meshId: string, taskIds: string[]): number {
|
|
959
|
+
try {
|
|
960
|
+
return MeshRuntimeStore.getInstance().deleteDirectDispatchesByTaskId(meshId, taskIds);
|
|
961
|
+
} catch {
|
|
962
|
+
return 0;
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
export type MeshToolCallRateResult = { rateLimitExceeded: boolean; callsInWindow: number; advisory: string | null };
|
|
967
|
+
|
|
968
|
+
/**
|
|
969
|
+
* Record a coordinator tool call and return a rate-limit advisory when the
|
|
970
|
+
* call rate for that tool exceeds the allowed threshold.
|
|
971
|
+
*
|
|
972
|
+
* Defaults: 10-second sliding window, max 5 calls before advisory is raised.
|
|
973
|
+
* Returns { rateLimitExceeded: false } on any store error so callers are not blocked.
|
|
974
|
+
*/
|
|
975
|
+
export function recordMeshToolCall(opts: {
|
|
976
|
+
meshId: string;
|
|
977
|
+
tool: string;
|
|
978
|
+
sessionId?: string | null;
|
|
979
|
+
windowMs?: number;
|
|
980
|
+
maxCalls?: number;
|
|
981
|
+
}): MeshToolCallRateResult {
|
|
982
|
+
try {
|
|
983
|
+
return MeshRuntimeStore.getInstance().recordMeshToolCall(opts);
|
|
984
|
+
} catch {
|
|
985
|
+
return { rateLimitExceeded: false, callsInWindow: 0, advisory: null };
|
|
986
|
+
}
|
|
987
|
+
}
|