@adhdev/daemon-core 0.9.82-rc.32 → 0.9.82-rc.321
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 +35378 -11873
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +38854 -15461
- 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 +204 -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 +277 -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 +6369 -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 +320 -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 +145 -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 +234 -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 +663 -142
- 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 +356 -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 } from '../repo-mesh-types.js';
|
|
4
|
+
import { MESH_CONVERGE_REFINE_TAG, resolveAutoConvergeCodeChange } 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,161 @@ export interface MeshWorkQueueEntry {
|
|
|
45
179
|
updatedAt: string;
|
|
46
180
|
}
|
|
47
181
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
182
|
+
export interface MeshQueueMutationOptions {
|
|
183
|
+
ownerRole?: RepoMeshDaemonRole;
|
|
184
|
+
}
|
|
185
|
+
|
|
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();
|
|
51
205
|
}
|
|
52
206
|
|
|
53
|
-
function
|
|
54
|
-
|
|
55
|
-
|
|
207
|
+
export function buildMeshNodeCapabilityTags(
|
|
208
|
+
node: { capabilities?: unknown; policy?: unknown; isLocalWorktree?: unknown; worktreeBranch?: unknown } | undefined,
|
|
209
|
+
providerType?: string,
|
|
210
|
+
): string[] {
|
|
211
|
+
const provider = typeof providerType === 'string' && providerType.trim()
|
|
212
|
+
? providerType.trim()
|
|
213
|
+
: firstProviderPriority(node?.policy);
|
|
214
|
+
const worktreeBranch = typeof node?.worktreeBranch === 'string' && node.worktreeBranch.trim()
|
|
215
|
+
? node.worktreeBranch.trim()
|
|
216
|
+
: null;
|
|
217
|
+
return normalizeMeshCapabilityTags([
|
|
218
|
+
...(Array.isArray(node?.capabilities) ? node.capabilities : []),
|
|
219
|
+
`os=${process.platform}`,
|
|
220
|
+
`arch=${process.arch}`,
|
|
221
|
+
...(provider ? [`provider=${provider}`] : []),
|
|
222
|
+
// Worktree nodes automatically expose a "worktree=<branch>" tag so that
|
|
223
|
+
// mesh_enqueue_task with required_tags: ["worktree=<branch>"] routes
|
|
224
|
+
// only to the matching worktree node.
|
|
225
|
+
...(node?.isLocalWorktree === true && worktreeBranch ? [`worktree=${worktreeBranch}`] : []),
|
|
226
|
+
// Convergence routing: advertise how this node can land its work onto base.
|
|
227
|
+
// - converge=refine: local worktree nodes (on ANY machine — refine_mesh_node
|
|
228
|
+
// now forwards to the owning daemon) can run the Refinery merge → push →
|
|
229
|
+
// cleanup against their own checkout, so they accept code_change tasks.
|
|
230
|
+
// - converge=fast_forward: non-worktree nodes (the machine itself) can only
|
|
231
|
+
// ff/push an already-converged branch; they are NOT a destination for
|
|
232
|
+
// code_change work (a worktree is created first, and that worktree node
|
|
233
|
+
// receives the task instead). Reuses the ordinary required-tags filter —
|
|
234
|
+
// the load-balancing scheduler auto-injects converge=refine for code_change
|
|
235
|
+
// so such work is hard-filtered onto refine-capable nodes.
|
|
236
|
+
...(node?.isLocalWorktree === true ? ['converge=refine'] : ['converge=fast_forward']),
|
|
237
|
+
]);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export function nodeSatisfiesRequiredTags(requiredTags: unknown, capabilityTags: unknown): boolean {
|
|
241
|
+
const required = normalizeMeshCapabilityTags(requiredTags);
|
|
242
|
+
if (required.length === 0) return true;
|
|
243
|
+
const available = new Set(normalizeMeshCapabilityTags(capabilityTags));
|
|
244
|
+
return required.every(tag => available.has(tag));
|
|
56
245
|
}
|
|
57
246
|
|
|
58
247
|
/**
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
248
|
+
* Convergence-aware required-tags resolution (load-balancing scheduler, opt-in).
|
|
249
|
+
*
|
|
250
|
+
* When the mesh enables policy.autoConvergeCodeChange, a `converge=refine` required
|
|
251
|
+
* tag is merged into a code_change task's required tags at enqueue time, so the
|
|
252
|
+
* scheduler hard-filters the task onto refine-capable worktree nodes only (on any
|
|
253
|
+
* machine — refine_mesh_node forwards to the owning daemon). Because the tag is
|
|
254
|
+
* persisted on the queue entry, BOTH the eligibility scan (maybeAutoLaunchOneQueueSession)
|
|
255
|
+
* and the claim transaction (claimNextQueueTask → nodeSatisfiesRequiredTags) enforce
|
|
256
|
+
* it consistently.
|
|
257
|
+
*
|
|
258
|
+
* Strict backward compatibility — the injection is skipped (returns the explicit tags
|
|
259
|
+
* unchanged) when ANY of:
|
|
260
|
+
* - the mesh does not opt in (autoConvergeCodeChange !== true), or
|
|
261
|
+
* - the task is not code_change (validation / live_debug_readonly / launch_app /
|
|
262
|
+
* convergence carry no merge cost and may run anywhere), or
|
|
263
|
+
* - the task is explicitly targeted (targetNodeId): the operator chose the node, so
|
|
264
|
+
* we do not second-guess it by filtering on convergence capability.
|
|
265
|
+
* Idempotent: normalizeMeshCapabilityTags dedupes, so re-injection is a no-op.
|
|
62
266
|
*/
|
|
63
|
-
function
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
try {
|
|
73
|
-
|
|
74
|
-
|
|
267
|
+
export function resolveConvergeRequiredTags(
|
|
268
|
+
meshId: string,
|
|
269
|
+
taskMode: MeshTaskMode | undefined,
|
|
270
|
+
explicitRequiredTags: string[],
|
|
271
|
+
opts?: { targetNodeId?: string },
|
|
272
|
+
): string[] {
|
|
273
|
+
if (taskMode !== 'code_change') return explicitRequiredTags;
|
|
274
|
+
if (typeof opts?.targetNodeId === 'string' && opts.targetNodeId.trim()) return explicitRequiredTags;
|
|
275
|
+
let optedIn = false;
|
|
276
|
+
try {
|
|
277
|
+
optedIn = resolveAutoConvergeCodeChange(getMesh(meshId)?.policy as any);
|
|
278
|
+
} catch {
|
|
279
|
+
optedIn = false;
|
|
75
280
|
}
|
|
281
|
+
if (!optedIn) return explicitRequiredTags;
|
|
282
|
+
return normalizeMeshCapabilityTags([...explicitRequiredTags, MESH_CONVERGE_REFINE_TAG]);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function withQueueLock<T>(_meshId: string, fn: () => T): T {
|
|
286
|
+
return MeshRuntimeStore.getInstance().transaction(fn);
|
|
76
287
|
}
|
|
77
288
|
|
|
78
289
|
function readQueue(meshId: string): MeshWorkQueueEntry[] {
|
|
79
|
-
|
|
80
|
-
if (!existsSync(path)) return [];
|
|
81
|
-
try {
|
|
82
|
-
const content = readFileSync(path, 'utf-8');
|
|
83
|
-
return JSON.parse(content) as MeshWorkQueueEntry[];
|
|
84
|
-
} catch {
|
|
85
|
-
return [];
|
|
86
|
-
}
|
|
290
|
+
return MeshRuntimeStore.getInstance().getQueueEntries(meshId);
|
|
87
291
|
}
|
|
88
292
|
|
|
89
293
|
function writeQueue(meshId: string, queue: MeshWorkQueueEntry[]): void {
|
|
90
|
-
|
|
91
|
-
|
|
294
|
+
MeshRuntimeStore.getInstance().replaceQueue(meshId, queue);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function normalizeDependsOn(value: unknown): string[] {
|
|
298
|
+
if (!Array.isArray(value)) return [];
|
|
299
|
+
const seen = new Set<string>();
|
|
300
|
+
return value
|
|
301
|
+
.map(id => typeof id === 'string' ? id.trim() : '')
|
|
302
|
+
.filter(Boolean)
|
|
303
|
+
.filter(id => {
|
|
304
|
+
if (seen.has(id)) return false;
|
|
305
|
+
seen.add(id);
|
|
306
|
+
return true;
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* M1: detect dependency cycles before enqueue. Walks the dependency graph of
|
|
312
|
+
* existing queue entries plus the new task's edges. Fail-closed: a cycle
|
|
313
|
+
* rejects the enqueue entirely. Synchronous and bounded by queue size.
|
|
314
|
+
*/
|
|
315
|
+
export function assertNoDependencyCycle(meshId: string, newTaskId: string, dependsOn: string[]): void {
|
|
316
|
+
if (dependsOn.length === 0) return;
|
|
317
|
+
if (dependsOn.includes(newTaskId)) {
|
|
318
|
+
throw new Error(`dependency_cycle_detected: task '${newTaskId}' cannot depend on itself`);
|
|
319
|
+
}
|
|
320
|
+
const adjacency = new Map<string, string[]>();
|
|
321
|
+
for (const entry of readQueue(meshId)) {
|
|
322
|
+
adjacency.set(entry.id, normalizeDependsOn(entry.dependsOn));
|
|
323
|
+
}
|
|
324
|
+
adjacency.set(newTaskId, dependsOn);
|
|
325
|
+
// DFS from the new task: if we can reach newTaskId again, the edges form a cycle.
|
|
326
|
+
const stack = [...dependsOn];
|
|
327
|
+
const visited = new Set<string>();
|
|
328
|
+
while (stack.length > 0) {
|
|
329
|
+
const current = stack.pop()!;
|
|
330
|
+
if (current === newTaskId) {
|
|
331
|
+
throw new Error(`dependency_cycle_detected: task '${newTaskId}' is part of a dependency cycle via '${dependsOn.join(', ')}'`);
|
|
332
|
+
}
|
|
333
|
+
if (visited.has(current)) continue;
|
|
334
|
+
visited.add(current);
|
|
335
|
+
stack.push(...(adjacency.get(current) ?? []));
|
|
336
|
+
}
|
|
92
337
|
}
|
|
93
338
|
|
|
94
339
|
/**
|
|
@@ -97,22 +342,120 @@ function writeQueue(meshId: string, queue: MeshWorkQueueEntry[]): void {
|
|
|
97
342
|
export function enqueueTask(
|
|
98
343
|
meshId: string,
|
|
99
344
|
message: string,
|
|
100
|
-
opts?: {
|
|
345
|
+
opts?: {
|
|
346
|
+
targetNodeId?: string;
|
|
347
|
+
targetSessionId?: string;
|
|
348
|
+
taskMode?: MeshTaskMode | string;
|
|
349
|
+
requiredTags?: string[];
|
|
350
|
+
/** M1: tasks that must complete before this one is claimable. */
|
|
351
|
+
dependsOn?: string[];
|
|
352
|
+
/** M1/M3: mission this task belongs to. */
|
|
353
|
+
missionId?: string;
|
|
354
|
+
/** Explicit task id for batch/template flows (M5). Random UUID when omitted. */
|
|
355
|
+
id?: string;
|
|
356
|
+
} & MeshQueueMutationOptions,
|
|
101
357
|
): MeshWorkQueueEntry {
|
|
358
|
+
requireMeshHostQueueOwner(opts);
|
|
359
|
+
const modeValidation = validateMeshTaskModeRequest(opts?.taskMode, message);
|
|
360
|
+
if (!modeValidation.valid) {
|
|
361
|
+
throw new Error(`live_debug_readonly_guardrail_violation: forbidden operations (${modeValidation.violations.join(', ')})`);
|
|
362
|
+
}
|
|
363
|
+
const id = typeof opts?.id === 'string' && opts.id.trim() ? opts.id.trim() : randomUUID();
|
|
364
|
+
const dependsOn = normalizeDependsOn(opts?.dependsOn);
|
|
102
365
|
return withQueueLock(meshId, () => {
|
|
103
|
-
|
|
366
|
+
if (MeshRuntimeStore.getInstance().findQueueEntryById(meshId, id)) {
|
|
367
|
+
throw new Error(`duplicate_task_id: task '${id}' already exists in mesh '${meshId}'`);
|
|
368
|
+
}
|
|
369
|
+
assertNoDependencyCycle(meshId, id, dependsOn);
|
|
370
|
+
const callerTags = normalizeMeshCapabilityTags(opts?.requiredTags);
|
|
371
|
+
// Convergence routing (opt-in): auto-inject converge=refine for code_change
|
|
372
|
+
// tasks so they hard-filter onto refine-capable worktree nodes. No-op unless
|
|
373
|
+
// the mesh opts in; explicit target_node_id / required_tags are preserved.
|
|
374
|
+
// Routing is otherwise governed solely by the caller's required_tags (hard
|
|
375
|
+
// filter through nodeSatisfiesRequiredTags) — no role/taskMode auto-routing.
|
|
376
|
+
const resolvedRequiredTags = resolveConvergeRequiredTags(
|
|
377
|
+
meshId,
|
|
378
|
+
modeValidation.taskMode,
|
|
379
|
+
callerTags,
|
|
380
|
+
{ targetNodeId: opts?.targetNodeId },
|
|
381
|
+
);
|
|
104
382
|
const entry: MeshWorkQueueEntry = {
|
|
105
|
-
id
|
|
383
|
+
id,
|
|
106
384
|
meshId,
|
|
107
385
|
message,
|
|
108
386
|
status: 'pending',
|
|
387
|
+
taskMode: modeValidation.taskMode,
|
|
109
388
|
targetNodeId: opts?.targetNodeId,
|
|
110
389
|
targetSessionId: opts?.targetSessionId,
|
|
390
|
+
requiredTags: resolvedRequiredTags,
|
|
391
|
+
...(dependsOn.length > 0 ? { dependsOn } : {}),
|
|
392
|
+
...(typeof opts?.missionId === 'string' && opts.missionId.trim() ? { missionId: opts.missionId.trim() } : {}),
|
|
111
393
|
createdAt: new Date().toISOString(),
|
|
112
394
|
updatedAt: new Date().toISOString(),
|
|
113
395
|
};
|
|
114
|
-
|
|
115
|
-
|
|
396
|
+
MeshRuntimeStore.getInstance().insertQueueEntry(entry);
|
|
397
|
+
return entry;
|
|
398
|
+
});
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* Record a direct-dispatch task (mesh_send_task) as an already-assigned queue
|
|
403
|
+
* entry so it is attributable to a mission.
|
|
404
|
+
*
|
|
405
|
+
* Direct dispatch normally bypasses the queue entirely — the task lives only in
|
|
406
|
+
* the ledger + mesh_direct_dispatches table, neither of which carries a
|
|
407
|
+
* missionId, so {@link summarizeMissionTasks}/{@link computeMeshTaskStats}
|
|
408
|
+
* (which both scan the queue for `task.missionId`) count it as 0. When a
|
|
409
|
+
* mission is attached, we materialise the same queue entry shape an enqueued
|
|
410
|
+
* task would have, but pre-assigned to the dispatched node/session and stamped
|
|
411
|
+
* with the dispatch timestamp. The terminal event path (updateSessionTaskStatus
|
|
412
|
+
* → findAssignedBySession) then flips it to completed/failed exactly like a
|
|
413
|
+
* pulled task, so mission total + completed aggregates work with no extra wiring.
|
|
414
|
+
*
|
|
415
|
+
* Intentionally separate from {@link enqueueTask}: enqueue creates `pending`
|
|
416
|
+
* work for the queue to assign, whereas this records work already dispatched
|
|
417
|
+
* out-of-band. They share the missionId stamping rule and mode validation.
|
|
418
|
+
*/
|
|
419
|
+
export function recordDirectDispatchTask(
|
|
420
|
+
meshId: string,
|
|
421
|
+
message: string,
|
|
422
|
+
opts: {
|
|
423
|
+
id: string;
|
|
424
|
+
missionId: string;
|
|
425
|
+
assignedNodeId?: string;
|
|
426
|
+
assignedSessionId?: string;
|
|
427
|
+
taskMode?: MeshTaskMode | string;
|
|
428
|
+
dispatchedAt?: string;
|
|
429
|
+
},
|
|
430
|
+
): MeshWorkQueueEntry | null {
|
|
431
|
+
const missionId = typeof opts.missionId === 'string' ? opts.missionId.trim() : '';
|
|
432
|
+
if (!missionId) return null;
|
|
433
|
+
const taskId = typeof opts.id === 'string' ? opts.id.trim() : '';
|
|
434
|
+
if (!taskId) return null;
|
|
435
|
+
const modeValidation = validateMeshTaskModeRequest(opts.taskMode, message);
|
|
436
|
+
if (!modeValidation.valid) {
|
|
437
|
+
throw new Error(`live_debug_readonly_guardrail_violation: forbidden operations (${modeValidation.violations.join(', ')})`);
|
|
438
|
+
}
|
|
439
|
+
const now = opts.dispatchedAt && opts.dispatchedAt.trim() ? opts.dispatchedAt : new Date().toISOString();
|
|
440
|
+
return withQueueLock(meshId, () => {
|
|
441
|
+
if (MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId)) {
|
|
442
|
+
// Already materialised (e.g. retry of the same dispatch) — leave it untouched.
|
|
443
|
+
return null;
|
|
444
|
+
}
|
|
445
|
+
const entry: MeshWorkQueueEntry = {
|
|
446
|
+
id: taskId,
|
|
447
|
+
meshId,
|
|
448
|
+
message,
|
|
449
|
+
status: 'assigned',
|
|
450
|
+
...(modeValidation.taskMode ? { taskMode: modeValidation.taskMode } : {}),
|
|
451
|
+
missionId,
|
|
452
|
+
...(opts.assignedNodeId ? { targetNodeId: opts.assignedNodeId, assignedNodeId: opts.assignedNodeId } : {}),
|
|
453
|
+
...(opts.assignedSessionId ? { targetSessionId: opts.assignedSessionId, assignedSessionId: opts.assignedSessionId } : {}),
|
|
454
|
+
dispatchTimestamp: now,
|
|
455
|
+
createdAt: now,
|
|
456
|
+
updatedAt: now,
|
|
457
|
+
};
|
|
458
|
+
MeshRuntimeStore.getInstance().insertQueueEntry(entry);
|
|
116
459
|
return entry;
|
|
117
460
|
});
|
|
118
461
|
}
|
|
@@ -121,43 +464,83 @@ export function enqueueTask(
|
|
|
121
464
|
* Get all tasks in the queue, optionally filtered by status.
|
|
122
465
|
*/
|
|
123
466
|
export function getQueue(meshId: string, opts?: { status?: MeshTaskStatus[] }): MeshWorkQueueEntry[] {
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
return queue;
|
|
467
|
+
return MeshRuntimeStore.getInstance().getQueueEntries(meshId, opts?.status?.length ? opts.status : undefined);
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
export function getMeshQueueRevision(meshId: string): string {
|
|
471
|
+
return MeshRuntimeStore.getInstance().getQueueRevision(meshId);
|
|
130
472
|
}
|
|
131
473
|
|
|
132
474
|
/**
|
|
133
475
|
* Find the next pending task that this node is allowed to claim, and mark it as assigned.
|
|
476
|
+
*
|
|
477
|
+
* `opts.providerType` is stamped onto the claimed entry (assignedProviderType) so
|
|
478
|
+
* per-(node, provider) caps can be counted. `opts.providerMaxParallel`, when set,
|
|
479
|
+
* is the enforced per-(node, provider) cap from RepoMeshNodePolicy.providerRoles:
|
|
480
|
+
* a task is not assigned to this (node, provider) once it already has that many
|
|
481
|
+
* active assignments. This composes with the global/taskMode caps (stricter wins).
|
|
134
482
|
*/
|
|
135
|
-
export function claimNextTask(
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
483
|
+
export function claimNextTask(
|
|
484
|
+
meshId: string,
|
|
485
|
+
nodeId: string,
|
|
486
|
+
sessionId: string,
|
|
487
|
+
capabilityTags?: string[],
|
|
488
|
+
opts?: { providerType?: string; providerMaxParallel?: number },
|
|
489
|
+
): MeshWorkQueueEntry | null {
|
|
490
|
+
return MeshRuntimeStore.getInstance().claimNextQueueTask(meshId, nodeId, sessionId, capabilityTags, opts);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
// ─── M1: Dependency Failure Propagation ─────────
|
|
494
|
+
|
|
495
|
+
export type DependencyFailurePolicy = 'block' | 'cancel';
|
|
496
|
+
|
|
497
|
+
function resolveDependencyFailurePolicy(meshId: string): DependencyFailurePolicy {
|
|
498
|
+
try {
|
|
499
|
+
const policy = (getMesh(meshId)?.policy ?? {}) as Record<string, unknown>;
|
|
500
|
+
return policy.onDependencyFailure === 'cancel' ? 'cancel' : 'block';
|
|
501
|
+
} catch {
|
|
502
|
+
return 'block';
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* Apply the mesh's onDependencyFailure policy to pending dependents of a task
|
|
508
|
+
* that just reached a failed/cancelled terminal state.
|
|
509
|
+
*
|
|
510
|
+
* - 'block' (default): dependents stay pending with blockedReason
|
|
511
|
+
* "dependency_failed:<taskId>" so an operator can requeue/cancel them.
|
|
512
|
+
* - 'cancel': dependents are cancelled (cascading to their own dependents).
|
|
513
|
+
*
|
|
514
|
+
* Must be called inside the queue lock of the triggering transition.
|
|
515
|
+
*/
|
|
516
|
+
function propagateDependencyFailure(meshId: string, failedTaskId: string): void {
|
|
517
|
+
const policy = resolveDependencyFailurePolicy(meshId);
|
|
518
|
+
const store = MeshRuntimeStore.getInstance();
|
|
519
|
+
const frontier = [failedTaskId];
|
|
520
|
+
const seen = new Set<string>(frontier);
|
|
521
|
+
while (frontier.length > 0) {
|
|
522
|
+
const currentId = frontier.pop()!;
|
|
523
|
+
const dependents = store.getQueueEntries(meshId, ['pending'])
|
|
524
|
+
.filter(entry => Array.isArray(entry.dependsOn) && entry.dependsOn.includes(currentId));
|
|
525
|
+
for (const dependent of dependents) {
|
|
526
|
+
if (seen.has(dependent.id)) continue;
|
|
527
|
+
seen.add(dependent.id);
|
|
528
|
+
if (policy === 'cancel') {
|
|
529
|
+
dependent.status = 'cancelled';
|
|
530
|
+
dependent.cancelledAt = new Date().toISOString();
|
|
531
|
+
dependent.cancelReason = `dependency_failed:${currentId}`;
|
|
532
|
+
store.updateQueueEntry(dependent);
|
|
533
|
+
frontier.push(dependent.id); // cascade to transitive dependents
|
|
534
|
+
} else {
|
|
535
|
+
dependent.blockedReason = `dependency_failed:${currentId}`;
|
|
536
|
+
store.updateQueueEntry(dependent);
|
|
537
|
+
}
|
|
148
538
|
}
|
|
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
|
-
});
|
|
539
|
+
}
|
|
159
540
|
}
|
|
160
541
|
|
|
542
|
+
const DEPENDENCY_FAILURE_TERMINALS = new Set<MeshTaskStatus>(['failed', 'cancelled']);
|
|
543
|
+
|
|
161
544
|
/**
|
|
162
545
|
* Update the status of a specific task.
|
|
163
546
|
* Used when a session completes, fails, or stalls.
|
|
@@ -166,15 +549,16 @@ export function updateTaskStatus(
|
|
|
166
549
|
meshId: string,
|
|
167
550
|
taskId: string,
|
|
168
551
|
status: MeshTaskStatus,
|
|
552
|
+
opts?: MeshQueueMutationOptions,
|
|
169
553
|
): MeshWorkQueueEntry | null {
|
|
554
|
+
requireMeshHostQueueOwner(opts);
|
|
170
555
|
return withQueueLock(meshId, () => {
|
|
171
|
-
const
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
return queue[idx];
|
|
556
|
+
const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
|
|
557
|
+
if (!entry) return null;
|
|
558
|
+
entry.status = status;
|
|
559
|
+
MeshRuntimeStore.getInstance().updateQueueEntry(entry);
|
|
560
|
+
if (DEPENDENCY_FAILURE_TERMINALS.has(status)) propagateDependencyFailure(meshId, taskId);
|
|
561
|
+
return entry;
|
|
178
562
|
});
|
|
179
563
|
}
|
|
180
564
|
|
|
@@ -184,14 +568,12 @@ export function recordTaskAutoLaunch(
|
|
|
184
568
|
autoLaunch: Omit<NonNullable<MeshWorkQueueEntry['autoLaunch']>, 'updatedAt'>,
|
|
185
569
|
): MeshWorkQueueEntry | null {
|
|
186
570
|
return withQueueLock(meshId, () => {
|
|
187
|
-
const
|
|
188
|
-
|
|
189
|
-
if (idx === -1) return null;
|
|
571
|
+
const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
|
|
572
|
+
if (!entry) return null;
|
|
190
573
|
const now = new Date().toISOString();
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
return queue[idx];
|
|
574
|
+
entry.autoLaunch = { ...autoLaunch, updatedAt: now };
|
|
575
|
+
MeshRuntimeStore.getInstance().updateQueueEntry(entry);
|
|
576
|
+
return entry;
|
|
195
577
|
});
|
|
196
578
|
}
|
|
197
579
|
|
|
@@ -201,19 +583,19 @@ export function recordTaskAutoLaunch(
|
|
|
201
583
|
export function cancelTask(
|
|
202
584
|
meshId: string,
|
|
203
585
|
taskId: string,
|
|
204
|
-
opts?: { reason?: string },
|
|
586
|
+
opts?: { reason?: string } & MeshQueueMutationOptions,
|
|
205
587
|
): MeshWorkQueueEntry | null {
|
|
588
|
+
requireMeshHostQueueOwner(opts);
|
|
206
589
|
return withQueueLock(meshId, () => {
|
|
207
|
-
const
|
|
208
|
-
|
|
209
|
-
if (idx === -1) return null;
|
|
590
|
+
const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
|
|
591
|
+
if (!entry) return null;
|
|
210
592
|
const now = new Date().toISOString();
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
return
|
|
593
|
+
entry.status = 'cancelled';
|
|
594
|
+
entry.cancelledAt = now;
|
|
595
|
+
if (opts?.reason) entry.cancelReason = opts.reason;
|
|
596
|
+
MeshRuntimeStore.getInstance().updateQueueEntry(entry);
|
|
597
|
+
propagateDependencyFailure(meshId, taskId);
|
|
598
|
+
return entry;
|
|
217
599
|
});
|
|
218
600
|
}
|
|
219
601
|
|
|
@@ -221,6 +603,11 @@ export function cancelTask(
|
|
|
221
603
|
* Return a queue task to pending for retry. By default, dead session targeting
|
|
222
604
|
* and assigned ownership are cleared so stale assignments do not strand again.
|
|
223
605
|
*/
|
|
606
|
+
export type RequeueResult =
|
|
607
|
+
| { status: 'requeued'; entry: MeshWorkQueueEntry }
|
|
608
|
+
| { status: 'failed_max_retries'; entry: MeshWorkQueueEntry; maxRetries: number; requeueCount: number }
|
|
609
|
+
| { status: 'not_found' };
|
|
610
|
+
|
|
224
611
|
export function requeueTask(
|
|
225
612
|
meshId: string,
|
|
226
613
|
taskId: string,
|
|
@@ -230,15 +617,34 @@ export function requeueTask(
|
|
|
230
617
|
targetSessionId?: string;
|
|
231
618
|
clearTargetNode?: boolean;
|
|
232
619
|
clearTargetSession?: boolean;
|
|
233
|
-
|
|
620
|
+
/**
|
|
621
|
+
* Override the retry cap for this call. Use only for explicit operator actions.
|
|
622
|
+
* If true, the task is requeued even when requeueCount >= maxRetries.
|
|
623
|
+
*/
|
|
624
|
+
force?: boolean;
|
|
625
|
+
/** Per-task retry cap override. Falls back to mesh policy maxTaskRetries (default 1). */
|
|
626
|
+
maxRetries?: number;
|
|
627
|
+
} & MeshQueueMutationOptions,
|
|
234
628
|
): MeshWorkQueueEntry | null {
|
|
629
|
+
requireMeshHostQueueOwner(opts);
|
|
235
630
|
return withQueueLock(meshId, () => {
|
|
236
|
-
const
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
const
|
|
240
|
-
|
|
631
|
+
const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
|
|
632
|
+
if (!entry) return null;
|
|
633
|
+
const currentCount = entry.requeueCount || 0;
|
|
634
|
+
const maxRetries = opts?.maxRetries ?? entry.maxRetries ?? 1;
|
|
635
|
+
if (!opts?.force && currentCount >= maxRetries) {
|
|
636
|
+
// Auto-fail: cap exceeded without explicit force override.
|
|
637
|
+
entry.status = 'failed';
|
|
638
|
+
entry.cancelReason = `max_retries_exceeded: requeued ${currentCount} time(s), limit is ${maxRetries}`;
|
|
639
|
+
entry.updatedAt = new Date().toISOString();
|
|
640
|
+
MeshRuntimeStore.getInstance().updateQueueEntry(entry);
|
|
641
|
+
propagateDependencyFailure(meshId, taskId);
|
|
642
|
+
return entry;
|
|
643
|
+
}
|
|
241
644
|
entry.status = 'pending';
|
|
645
|
+
// Operator requeue clears a dependency-failure block — the operator is
|
|
646
|
+
// explicitly overriding the held-back state.
|
|
647
|
+
delete entry.blockedReason;
|
|
242
648
|
delete entry.assignedNodeId;
|
|
243
649
|
delete entry.assignedSessionId;
|
|
244
650
|
delete entry.cancelledAt;
|
|
@@ -247,11 +653,10 @@ export function requeueTask(
|
|
|
247
653
|
if (typeof opts?.targetNodeId === 'string') entry.targetNodeId = opts.targetNodeId;
|
|
248
654
|
if (opts?.clearTargetSession !== false) delete entry.targetSessionId;
|
|
249
655
|
if (typeof opts?.targetSessionId === 'string') entry.targetSessionId = opts.targetSessionId;
|
|
250
|
-
entry.
|
|
251
|
-
entry.
|
|
252
|
-
entry.requeueCount = (entry.requeueCount || 0) + 1;
|
|
656
|
+
entry.requeuedAt = new Date().toISOString();
|
|
657
|
+
entry.requeueCount = currentCount + 1;
|
|
253
658
|
if (opts?.reason) entry.requeueReason = opts.reason;
|
|
254
|
-
|
|
659
|
+
MeshRuntimeStore.getInstance().updateQueueEntry(entry);
|
|
255
660
|
return entry;
|
|
256
661
|
});
|
|
257
662
|
}
|
|
@@ -266,25 +671,42 @@ export function updateSessionTaskStatus(
|
|
|
266
671
|
opts?: { occurredAt?: string },
|
|
267
672
|
): MeshWorkQueueEntry | null {
|
|
268
673
|
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];
|
|
674
|
+
const occurredAtIso = opts?.occurredAt ? new Date(opts.occurredAt).toISOString() : undefined;
|
|
675
|
+
const entry = MeshRuntimeStore.getInstance().findAssignedBySession(meshId, sessionId, occurredAtIso);
|
|
676
|
+
if (!entry) return null;
|
|
677
|
+
entry.status = status;
|
|
678
|
+
MeshRuntimeStore.getInstance().updateQueueEntry(entry);
|
|
679
|
+
if (DEPENDENCY_FAILURE_TERMINALS.has(status)) propagateDependencyFailure(meshId, entry.id);
|
|
680
|
+
return entry;
|
|
285
681
|
});
|
|
286
682
|
}
|
|
287
683
|
|
|
684
|
+
/**
|
|
685
|
+
* M1-3: true when at least one pending task is waiting on the given task.
|
|
686
|
+
* Used by the completion event path to decide whether to wake the queue.
|
|
687
|
+
*/
|
|
688
|
+
export function hasPendingDependents(meshId: string, taskId: string): boolean {
|
|
689
|
+
return MeshRuntimeStore.getInstance().getQueueEntries(meshId, ['pending'])
|
|
690
|
+
.some(entry => Array.isArray(entry.dependsOn) && entry.dependsOn.includes(taskId));
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
/**
|
|
694
|
+
* M1-4: view-time dependency state for a task — unmet dependency ids and
|
|
695
|
+
* whether the task is currently claimable from a dependency standpoint.
|
|
696
|
+
* Not stored (truth stays in task statuses).
|
|
697
|
+
*/
|
|
698
|
+
export function describeTaskDependencyState(
|
|
699
|
+
entry: Pick<MeshWorkQueueEntry, 'dependsOn' | 'blockedReason'>,
|
|
700
|
+
statusById: Map<string, MeshTaskStatus | string>,
|
|
701
|
+
): { waitingOn: string[]; dependenciesSatisfied: boolean } {
|
|
702
|
+
const deps = Array.isArray(entry.dependsOn) ? entry.dependsOn : [];
|
|
703
|
+
const waitingOn = deps.filter(depId => statusById.get(depId) !== 'completed');
|
|
704
|
+
return {
|
|
705
|
+
waitingOn,
|
|
706
|
+
dependenciesSatisfied: waitingOn.length === 0 && !entry.blockedReason,
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
|
|
288
710
|
export interface MeshWorkQueueStats {
|
|
289
711
|
total: number;
|
|
290
712
|
active: number;
|
|
@@ -310,14 +732,16 @@ export interface MeshWorkQueueStats {
|
|
|
310
732
|
* Return aggregate queue statistics for the given mesh.
|
|
311
733
|
*/
|
|
312
734
|
export function getMeshQueueStats(meshId: string): MeshWorkQueueStats {
|
|
313
|
-
const
|
|
314
|
-
const
|
|
315
|
-
const
|
|
316
|
-
const
|
|
317
|
-
const
|
|
318
|
-
const
|
|
735
|
+
const rows = MeshRuntimeStore.getInstance().getQueueStatsByStatus(meshId);
|
|
736
|
+
const counts: Record<string, number> = {};
|
|
737
|
+
for (const r of rows) counts[r.status] = r.count;
|
|
738
|
+
const pending = counts['pending'] ?? 0;
|
|
739
|
+
const assigned = counts['assigned'] ?? 0;
|
|
740
|
+
const completed = counts['completed'] ?? 0;
|
|
741
|
+
const failed = counts['failed'] ?? 0;
|
|
742
|
+
const cancelled = counts['cancelled'] ?? 0;
|
|
319
743
|
return {
|
|
320
|
-
total:
|
|
744
|
+
total: pending + assigned + completed + failed + cancelled,
|
|
321
745
|
active: pending + assigned,
|
|
322
746
|
historical: completed + failed + cancelled,
|
|
323
747
|
pending,
|
|
@@ -325,22 +749,119 @@ export function getMeshQueueStats(meshId: string): MeshWorkQueueStats {
|
|
|
325
749
|
completed,
|
|
326
750
|
failed,
|
|
327
751
|
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
|
-
})),
|
|
752
|
+
activeCounts: { pending, assigned },
|
|
753
|
+
historicalCounts: { completed, failed, cancelled },
|
|
754
|
+
activeAssignments: MeshRuntimeStore.getInstance().getActiveAssignmentDetails(meshId),
|
|
345
755
|
};
|
|
346
756
|
}
|
|
757
|
+
|
|
758
|
+
export function __replaceMeshQueueForTests(meshId: string, queue: MeshWorkQueueEntry[]): void {
|
|
759
|
+
MeshRuntimeStore.getInstance().transaction(() => {
|
|
760
|
+
MeshRuntimeStore.getInstance().replaceQueue(meshId, queue);
|
|
761
|
+
});
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
export function __clearMeshQueueForTests(meshId: string): void {
|
|
765
|
+
MeshRuntimeStore.getInstance().deleteQueue(meshId);
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
export function __clearDirectDispatchesForTests(meshId: string): void {
|
|
769
|
+
MeshRuntimeStore.getInstance().deleteDirectDispatches(meshId);
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
export function __resetMeshRuntimeStoreForTests(): void {
|
|
773
|
+
MeshRuntimeStore.resetForTests();
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
// ── Direct Dispatch Tracking ─────────────────────────────────────────────────
|
|
777
|
+
// Persists direct (non-queue) task dispatches so buildMeshActiveWork can read
|
|
778
|
+
// active work from MeshRuntimeStore instead of scanning ledger JSONL entries.
|
|
779
|
+
|
|
780
|
+
export type DirectDispatchRecord = ReturnType<MeshRuntimeStore['getActiveDirectDispatches']>[number];
|
|
781
|
+
|
|
782
|
+
export function insertDirectDispatch(
|
|
783
|
+
meshId: string,
|
|
784
|
+
data: {
|
|
785
|
+
taskId: string;
|
|
786
|
+
nodeId?: string;
|
|
787
|
+
sessionId?: string;
|
|
788
|
+
providerType?: string;
|
|
789
|
+
message: string;
|
|
790
|
+
taskMode?: string;
|
|
791
|
+
via: string;
|
|
792
|
+
dispatchedToIdleSession?: boolean;
|
|
793
|
+
dispatchedAt: string;
|
|
794
|
+
},
|
|
795
|
+
): void {
|
|
796
|
+
try {
|
|
797
|
+
MeshRuntimeStore.getInstance().insertDirectDispatch({ ...data, meshId });
|
|
798
|
+
} catch (e: any) {
|
|
799
|
+
process.stderr.write(`[adhdev-mesh] insertDirectDispatch failed for task ${data.taskId}: ${e?.message || e}\n`);
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
export function getActiveDirectDispatches(meshId: string): DirectDispatchRecord[] {
|
|
804
|
+
try {
|
|
805
|
+
return MeshRuntimeStore.getInstance().getActiveDirectDispatches(meshId);
|
|
806
|
+
} catch {
|
|
807
|
+
return [];
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
export function updateDirectDispatchStatus(
|
|
812
|
+
meshId: string,
|
|
813
|
+
sessionId: string,
|
|
814
|
+
status: 'acked' | 'completed' | 'failed' | 'stale',
|
|
815
|
+
): void {
|
|
816
|
+
try {
|
|
817
|
+
MeshRuntimeStore.getInstance().updateDirectDispatchStatus(meshId, sessionId, status);
|
|
818
|
+
} catch { /* best-effort */ }
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
export function cleanupTerminalDirectDispatches(olderThanMs = 7 * 24 * 60 * 60_000): void {
|
|
822
|
+
try {
|
|
823
|
+
MeshRuntimeStore.getInstance().cleanupTerminalDirectDispatches(olderThanMs);
|
|
824
|
+
} catch { /* best-effort */ }
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
export function markStaleDirectDispatches(meshId: string, olderThanMs = 60 * 60_000): void {
|
|
828
|
+
try {
|
|
829
|
+
MeshRuntimeStore.getInstance().markStaleDirectDispatches(meshId, olderThanMs);
|
|
830
|
+
} catch { /* best-effort */ }
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
/**
|
|
834
|
+
* Delete specific direct dispatch rows by taskId. Returns the number of rows deleted.
|
|
835
|
+
* Used by the staleDirect prune path to evict orphaned/terminal dispatch records from the
|
|
836
|
+
* active staleDirect surface while leaving the append-only mesh ledger (audit history) intact.
|
|
837
|
+
*/
|
|
838
|
+
export function deleteDirectDispatchesByTaskId(meshId: string, taskIds: string[]): number {
|
|
839
|
+
try {
|
|
840
|
+
return MeshRuntimeStore.getInstance().deleteDirectDispatchesByTaskId(meshId, taskIds);
|
|
841
|
+
} catch {
|
|
842
|
+
return 0;
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
export type MeshToolCallRateResult = { rateLimitExceeded: boolean; callsInWindow: number; advisory: string | null };
|
|
847
|
+
|
|
848
|
+
/**
|
|
849
|
+
* Record a coordinator tool call and return a rate-limit advisory when the
|
|
850
|
+
* call rate for that tool exceeds the allowed threshold.
|
|
851
|
+
*
|
|
852
|
+
* Defaults: 10-second sliding window, max 5 calls before advisory is raised.
|
|
853
|
+
* Returns { rateLimitExceeded: false } on any store error so callers are not blocked.
|
|
854
|
+
*/
|
|
855
|
+
export function recordMeshToolCall(opts: {
|
|
856
|
+
meshId: string;
|
|
857
|
+
tool: string;
|
|
858
|
+
sessionId?: string | null;
|
|
859
|
+
windowMs?: number;
|
|
860
|
+
maxCalls?: number;
|
|
861
|
+
}): MeshToolCallRateResult {
|
|
862
|
+
try {
|
|
863
|
+
return MeshRuntimeStore.getInstance().recordMeshToolCall(opts);
|
|
864
|
+
} catch {
|
|
865
|
+
return { rateLimitExceeded: false, callsInWindow: 0, advisory: null };
|
|
866
|
+
}
|
|
867
|
+
}
|