@adhdev/daemon-core 0.9.82-rc.35 → 0.9.82-rc.350
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 +116 -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 +53 -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 +324 -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 +77 -1
- package/dist/detection/ide-detector.d.ts +13 -0
- package/dist/detection/win32-ide-version.d.ts +37 -0
- package/dist/git/change-impact-config.d.ts +159 -0
- package/dist/git/git-commands.d.ts +11 -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 +23 -0
- package/dist/git/git-types.d.ts +2 -50
- package/dist/git/index.d.ts +2 -0
- package/dist/index.d.ts +52 -13
- package/dist/index.js +39739 -14302
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +41369 -16055
- 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 +174 -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 +55 -0
- package/dist/mesh/mesh-events-stale.d.ts +40 -0
- package/dist/mesh/mesh-events-utils.d.ts +62 -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 +164 -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 +419 -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 +218 -5
- package/dist/mesh/preview-freshness.d.ts +18 -0
- package/dist/mesh/refine-config.d.ts +216 -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/chat-message-normalization.d.ts +12 -0
- package/dist/providers/cli-provider-instance.d.ts +77 -3
- package/dist/providers/contracts.d.ts +139 -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 +14 -0
- package/dist/providers/provider-instance.d.ts +15 -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 +322 -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 +144 -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/status-monitor.d.ts +7 -7
- 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 +295 -13
- package/dist/sessions/registry.d.ts +6 -0
- package/dist/shared-types-extra.d.ts +2 -4
- package/dist/shared-types.d.ts +59 -2
- 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 +26 -0
- package/dist/system/load-better-sqlite3.d.ts +21 -0
- package/dist/types.d.ts +5 -0
- package/package.json +7 -3
- package/src/agent-stream/poller.ts +2 -3
- package/src/agent-stream/provider-adapter.ts +1 -1
- 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 +774 -1141
- 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 +4 -0
- package/src/cli-adapters/provider-cli-shared.ts +100 -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 +1823 -62
- package/src/commands/cli-manager.ts +304 -14
- package/src/commands/handler.ts +809 -2
- package/src/commands/mesh-coordinator.ts +332 -122
- package/src/commands/router.ts +7505 -1311
- 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 +388 -6
- 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/change-impact-config.ts +354 -0
- package/src/git/git-commands.ts +55 -14
- package/src/git/git-diff.ts +53 -0
- package/src/git/git-executor.ts +12 -0
- package/src/git/git-status.ts +574 -43
- package/src/git/git-types.ts +14 -62
- package/src/git/git-worktree.ts +8 -1
- package/src/git/index.ts +16 -0
- package/src/index.ts +146 -12
- 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 +623 -0
- package/src/mesh/mesh-delivery-policy.ts +315 -0
- package/src/mesh/mesh-events-coordinator.ts +2224 -0
- package/src/mesh/mesh-events-pending.ts +558 -0
- package/src/mesh/mesh-events-stale.ts +290 -0
- package/src/mesh/mesh-events-utils.ts +381 -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 +590 -102
- package/src/mesh/mesh-missions.ts +322 -0
- package/src/mesh/mesh-reconcile-loop.ts +989 -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 +1660 -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 +901 -141
- package/src/mesh/preview-freshness.ts +118 -0
- package/src/mesh/refine-config.ts +423 -0
- package/src/mesh/worktree-bootstrap-config.ts +331 -0
- package/src/providers/acp-provider-instance.ts +25 -9
- package/src/providers/approval-utils.d.ts +4 -0
- package/src/providers/approval-utils.ts +47 -5
- package/src/providers/chat-message-normalization.ts +45 -5
- package/src/providers/cli-provider-instance.ts +1041 -99
- package/src/providers/contracts.d.ts +55 -0
- package/src/providers/contracts.ts +150 -6
- package/src/providers/extension-provider-instance.ts +12 -7
- package/src/providers/external-sources.ts +218 -0
- package/src/providers/ide-provider-instance.ts +35 -12
- 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 +670 -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 +1065 -0
- package/src/providers/spec/fsm-evaluator.ts +255 -0
- package/src/providers/spec/fsm-loader.ts +120 -0
- package/src/providers/spec/fsm-types.ts +238 -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/status-monitor.d.ts +7 -7
- package/src/providers/status-monitor.ts +37 -22
- 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 +378 -14
- package/src/sessions/registry.ts +6 -0
- package/src/shared-types-extra.ts +2 -4
- package/src/shared-types.d.ts +8 -0
- package/src/shared-types.ts +64 -1
- package/src/status/builders.ts +26 -6
- package/src/status/normalize.ts +2 -0
- package/src/status/reporter.ts +19 -1
- package/src/status/snapshot.ts +95 -26
- package/src/system/host-memory.ts +29 -12
- package/src/system/load-better-sqlite3.ts +68 -0
- 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,335 @@
|
|
|
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';
|
|
7
|
+
import { LOG } from '../logging/logger.js';
|
|
5
8
|
|
|
6
9
|
export type MeshTaskStatus = 'pending' | 'assigned' | 'completed' | 'failed' | 'cancelled';
|
|
7
10
|
export type MeshActiveTaskStatus = Extract<MeshTaskStatus, 'pending' | 'assigned'>;
|
|
8
11
|
export type MeshHistoricalTaskStatus = Extract<MeshTaskStatus, 'completed' | 'failed' | 'cancelled'>;
|
|
12
|
+
export type MeshTaskMode = 'code_change' | 'validation' | 'live_debug_readonly' | 'launch_app' | 'convergence';
|
|
9
13
|
|
|
10
14
|
export const ACTIVE_MESH_QUEUE_STATUSES: MeshActiveTaskStatus[] = ['pending', 'assigned'];
|
|
11
15
|
export const HISTORICAL_MESH_QUEUE_STATUSES: MeshHistoricalTaskStatus[] = ['completed', 'failed', 'cancelled'];
|
|
16
|
+
export const MESH_TASK_MODES: MeshTaskMode[] = ['code_change', 'validation', 'live_debug_readonly', 'launch_app', 'convergence'];
|
|
17
|
+
|
|
18
|
+
export interface MeshTaskModeValidationResult {
|
|
19
|
+
valid: boolean;
|
|
20
|
+
taskMode?: MeshTaskMode;
|
|
21
|
+
violations: string[];
|
|
22
|
+
allowedOperations?: string[];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const LIVE_DEBUG_READONLY_FORBIDDEN: Array<{ label: string; pattern: RegExp }> = [
|
|
26
|
+
{ 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 },
|
|
27
|
+
{ label: 'checkpoint', pattern: /\b(checkpoint|mesh_checkpoint)\b/i },
|
|
28
|
+
{ 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 },
|
|
29
|
+
{ 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 },
|
|
30
|
+
{ 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 },
|
|
31
|
+
{ 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 },
|
|
32
|
+
];
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Negation cues that, when they appear shortly before a mutation keyword inside
|
|
36
|
+
* the same clause, mean the keyword is being *forbidden* or described rather
|
|
37
|
+
* than invoked (e.g. "do not git reset", "절대 push 하지 마세요"). Matched
|
|
38
|
+
* case-insensitively. The Korean cues intentionally include sub-string forms
|
|
39
|
+
* ("않", "금지", "말 것") so conjugated variants are caught.
|
|
40
|
+
*/
|
|
41
|
+
const NEGATION_CUES: string[] = [
|
|
42
|
+
"don't", 'do not', 'never', 'avoid', 'without', 'no longer', 'not', 'forbidden',
|
|
43
|
+
'하지 마', '하지 마세요', '말 것', '금지', '없음', '않',
|
|
44
|
+
];
|
|
45
|
+
|
|
46
|
+
/** How many whitespace-delimited tokens before a keyword we scan for negation. */
|
|
47
|
+
const NEGATION_WINDOW_TOKENS = 6;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Returns true if a negation cue appears within {@link NEGATION_WINDOW_TOKENS}
|
|
51
|
+
* tokens before `matchIndex`, staying inside the same clause — we stop at
|
|
52
|
+
* sentence/line/clause boundaries (newline, `.`/`!`/`?`, `;`) so a negation in a
|
|
53
|
+
* previous sentence does not suppress a real command in the next one.
|
|
54
|
+
*/
|
|
55
|
+
function hasNegationBefore(text: string, matchIndex: number): boolean {
|
|
56
|
+
const before = text.slice(0, matchIndex);
|
|
57
|
+
// Restrict to the current clause: cut at the last clause/sentence/line break.
|
|
58
|
+
const clauseStart = Math.max(
|
|
59
|
+
before.lastIndexOf('\n'),
|
|
60
|
+
before.lastIndexOf('. '),
|
|
61
|
+
before.lastIndexOf('! '),
|
|
62
|
+
before.lastIndexOf('? '),
|
|
63
|
+
before.lastIndexOf(';'),
|
|
64
|
+
);
|
|
65
|
+
const clause = before.slice(clauseStart + 1);
|
|
66
|
+
const lower = clause.toLowerCase();
|
|
67
|
+
// Whitespace tokens immediately preceding the keyword, within the window.
|
|
68
|
+
const tokens = clause.split(/\s+/).filter(Boolean);
|
|
69
|
+
const windowTokens = tokens.slice(Math.max(0, tokens.length - NEGATION_WINDOW_TOKENS));
|
|
70
|
+
const windowText = windowTokens.join(' ').toLowerCase();
|
|
71
|
+
for (const cue of NEGATION_CUES) {
|
|
72
|
+
const c = cue.toLowerCase();
|
|
73
|
+
// ASCII cues are word-ish phrases — match in the bounded window only.
|
|
74
|
+
// CJK cues have no spaces, so the window-join can miss them; for those
|
|
75
|
+
// fall back to scanning the whole clause (still clause-bounded).
|
|
76
|
+
if (/[^\x00-\x7f]/.test(c)) {
|
|
77
|
+
if (lower.includes(c)) return true;
|
|
78
|
+
} else if (windowText.includes(c)) {
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Korean (and other) negation often trails the verb it negates ("git reset 하지
|
|
87
|
+
* 마세요" = "do not git reset"). Returns true if a CJK negation cue appears
|
|
88
|
+
* shortly after `matchEnd`, within the same clause. Scoped to CJK cues only —
|
|
89
|
+
* trailing ASCII words rarely negate a preceding command and would over-match.
|
|
90
|
+
*/
|
|
91
|
+
function hasTrailingNegation(text: string, matchEnd: number): boolean {
|
|
92
|
+
const after = text.slice(matchEnd);
|
|
93
|
+
// Clause-bound the lookahead: stop at the next clause/line break.
|
|
94
|
+
const clauseEnd = (() => {
|
|
95
|
+
const stops = [after.indexOf('\n'), after.indexOf('. '), after.indexOf('; ')]
|
|
96
|
+
.filter(i => i >= 0);
|
|
97
|
+
return stops.length ? Math.min(...stops) : after.length;
|
|
98
|
+
})();
|
|
99
|
+
const clause = after.slice(0, clauseEnd).toLowerCase();
|
|
100
|
+
for (const cue of NEGATION_CUES) {
|
|
101
|
+
const c = cue.toLowerCase();
|
|
102
|
+
if (/[^\x00-\x7f]/.test(c) && clause.includes(c)) return true;
|
|
103
|
+
}
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Returns true when the keyword at [matchStart, matchEnd) looks like an actual
|
|
109
|
+
* command invocation rather than a plain-prose mention. Command context is:
|
|
110
|
+
* - inside a fenced code block (``` ... ```) or inline backticks (`...`)
|
|
111
|
+
* - on a shell-prompt line (starts with `$ ` or `> `)
|
|
112
|
+
* - at a command-call position: line start (leading whitespace allowed) or
|
|
113
|
+
* right after a shell connective (`&&`, `||`, `|`, `;`) or an imperative
|
|
114
|
+
* connective ("then"/"run"/"," ) that introduces a command.
|
|
115
|
+
* Plain mid-sentence prose mentions (no backticks, no command position) are not
|
|
116
|
+
* command context and are excluded from violations.
|
|
117
|
+
*/
|
|
118
|
+
function isMutationKeywordInCommandContext(text: string, matchStart: number, matchEnd: number): boolean {
|
|
119
|
+
if (isInsideBackticksOrFence(text, matchStart, matchEnd)) return true;
|
|
120
|
+
|
|
121
|
+
// The line containing the match, and the portion of it before the keyword.
|
|
122
|
+
const lineStart = text.lastIndexOf('\n', matchStart - 1) + 1;
|
|
123
|
+
const linePrefix = text.slice(lineStart, matchStart);
|
|
124
|
+
|
|
125
|
+
// Shell-prompt line: "$ ..." or "> ..." (leading whitespace allowed).
|
|
126
|
+
if (/^\s*[$>]\s/.test(text.slice(lineStart))) return true;
|
|
127
|
+
|
|
128
|
+
// Line start (only whitespace before the keyword on this line).
|
|
129
|
+
if (/^\s*$/.test(linePrefix)) return true;
|
|
130
|
+
|
|
131
|
+
// After a shell connective or imperative connective introducing a command.
|
|
132
|
+
// We look at what immediately precedes the keyword on the same line.
|
|
133
|
+
if (/(?:&&|\|\||\||;)\s*$/.test(linePrefix)) return true;
|
|
134
|
+
if (/(?:^|[\s,])(?:then|run|first)\s+$/i.test(linePrefix)) return true;
|
|
135
|
+
if (/,\s*$/.test(linePrefix)) return true;
|
|
136
|
+
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* True if [matchStart, matchEnd) lies inside an inline-backtick span or a fenced
|
|
142
|
+
* code block. Fenced blocks (```...```) take precedence; otherwise we count
|
|
143
|
+
* inline backticks before the match — an odd count means we are inside a span.
|
|
144
|
+
*/
|
|
145
|
+
function isInsideBackticksOrFence(text: string, matchStart: number, matchEnd: number): boolean {
|
|
146
|
+
// Fenced code blocks: count ``` fences before the match.
|
|
147
|
+
const fenceRe = /```/g;
|
|
148
|
+
let fenceCount = 0;
|
|
149
|
+
let m: RegExpExecArray | null;
|
|
150
|
+
while ((m = fenceRe.exec(text)) !== null) {
|
|
151
|
+
if (m.index >= matchStart) break;
|
|
152
|
+
fenceCount++;
|
|
153
|
+
}
|
|
154
|
+
if (fenceCount % 2 === 1) return true;
|
|
155
|
+
|
|
156
|
+
// Inline backticks: count single backticks before the match start, ignoring
|
|
157
|
+
// those that are part of a ``` fence (handled above). An odd count → inside.
|
|
158
|
+
let inlineCount = 0;
|
|
159
|
+
for (let i = 0; i < matchStart; i++) {
|
|
160
|
+
if (text[i] === '`') {
|
|
161
|
+
// Skip triple-fence backticks.
|
|
162
|
+
if (text[i + 1] === '`' && text[i + 2] === '`') {
|
|
163
|
+
i += 2;
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
inlineCount++;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return inlineCount % 2 === 1;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Decides whether a forbidden keyword match at [matchStart, matchEnd) should
|
|
174
|
+
* count as a real violation. A match counts only when it is in command context
|
|
175
|
+
* and not negated. Negation always wins (even inside a code block), per the
|
|
176
|
+
* conservative rule: code-block + negation → exclude; other code-block → keep.
|
|
177
|
+
*/
|
|
178
|
+
function isRealMutationMatch(text: string, matchStart: number, matchEnd: number): boolean {
|
|
179
|
+
if (hasNegationBefore(text, matchStart)) return false;
|
|
180
|
+
if (hasTrailingNegation(text, matchEnd)) return false;
|
|
181
|
+
return isMutationKeywordInCommandContext(text, matchStart, matchEnd);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Runs a global regex over `text` and returns true if any match is a real
|
|
186
|
+
* mutation (command context, not negated).
|
|
187
|
+
*/
|
|
188
|
+
function patternHasRealMutation(pattern: RegExp, text: string): boolean {
|
|
189
|
+
const re = new RegExp(pattern.source, pattern.flags.includes('g') ? pattern.flags : pattern.flags + 'g');
|
|
190
|
+
let match: RegExpExecArray | null;
|
|
191
|
+
while ((match = re.exec(text)) !== null) {
|
|
192
|
+
if (isRealMutationMatch(text, match.index, match.index + match[0].length)) return true;
|
|
193
|
+
if (match.index === re.lastIndex) re.lastIndex++; // avoid zero-width loop
|
|
194
|
+
}
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Git subcommands that mutate the working tree, index, refs, or remote.
|
|
200
|
+
* `stash` and `checkout` are intentionally absent here: they have read-only
|
|
201
|
+
* variants (`git stash list`/`show`, `git checkout-index`) and are classified
|
|
202
|
+
* token-by-token in {@link detectGitMutation} rather than by bare keyword.
|
|
203
|
+
*/
|
|
204
|
+
const GIT_MUTATION_SUBCOMMANDS = new Set([
|
|
205
|
+
'add', 'commit', 'push', 'reset', 'rebase', 'clean', 'switch', 'merge',
|
|
206
|
+
'tag', 'restore', 'rm', 'mv', 'cherry-pick', 'revert', 'pull', 'fetch',
|
|
207
|
+
'am', 'apply', 'gc', 'prune',
|
|
208
|
+
]);
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Read-only `git stash` variants. Any other `git stash <x>` (pop/apply/drop/
|
|
212
|
+
* push/save/clear, or bare `git stash` which defaults to push) is a mutation.
|
|
213
|
+
*/
|
|
214
|
+
const GIT_STASH_READONLY_SUBCOMMANDS = new Set(['list', 'show']);
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Detects a true git mutation in free-text task message, token-aware so that
|
|
218
|
+
* read-only diagnostics (`git stash list`, `git stash show --stat`,
|
|
219
|
+
* `git checkout-index`, `git status`, `git diff`, `git log`, ...) are allowed.
|
|
220
|
+
* Returns true only when a genuine mutating git invocation is present.
|
|
221
|
+
*/
|
|
222
|
+
function detectGitMutation(message: string): boolean {
|
|
223
|
+
const re = /\bgit\s+([a-z][a-z0-9-]*)/gi;
|
|
224
|
+
let match: RegExpExecArray | null;
|
|
225
|
+
while ((match = re.exec(message)) !== null) {
|
|
226
|
+
const sub = match[1].toLowerCase();
|
|
227
|
+
// Only treat a mutating `git <sub>` as a real violation when it appears
|
|
228
|
+
// as an actual command (code/command context) and is not negated. Plain
|
|
229
|
+
// prose mentions ("don't git reset", "we won't push") are ignored.
|
|
230
|
+
const isReal = () => isRealMutationMatch(message, match!.index, match!.index + match![0].length);
|
|
231
|
+
if (GIT_MUTATION_SUBCOMMANDS.has(sub)) {
|
|
232
|
+
if (isReal()) return true;
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
if (sub === 'stash') {
|
|
236
|
+
// Token following `git stash`; read-only only for list/show.
|
|
237
|
+
const after = message.slice(re.lastIndex).match(/^\s+([a-z][a-z0-9-]*)/i);
|
|
238
|
+
const next = after ? after[1].toLowerCase() : '';
|
|
239
|
+
if (!GIT_STASH_READONLY_SUBCOMMANDS.has(next) && isReal()) return true; // bare stash = push, or pop/apply/drop/...
|
|
240
|
+
} else if (sub === 'checkout') {
|
|
241
|
+
// `git checkout <ref/path>` mutates; `git checkout-index` is matched
|
|
242
|
+
// as its own token by the regex (sub === 'checkout-index') and is read-only.
|
|
243
|
+
if (isReal()) return true;
|
|
244
|
+
} else if (sub === 'submodule') {
|
|
245
|
+
// `git submodule update` mutates; `git submodule status` is read-only.
|
|
246
|
+
const after = message.slice(re.lastIndex).match(/^\s+([a-z][a-z0-9-]*)/i);
|
|
247
|
+
const next = after ? after[1].toLowerCase() : '';
|
|
248
|
+
if ((next === 'update' || next === 'add' || next === 'sync' || next === 'deinit') && isReal()) return true;
|
|
249
|
+
} else if (sub === 'worktree') {
|
|
250
|
+
const after = message.slice(re.lastIndex).match(/^\s+([a-z][a-z0-9-]*)/i);
|
|
251
|
+
const next = after ? after[1].toLowerCase() : '';
|
|
252
|
+
if ((next === 'add' || next === 'remove' || next === 'move' || next === 'prune') && isReal()) return true;
|
|
253
|
+
}
|
|
254
|
+
// checkout-index, stash-with-no-next-already-handled, status/diff/log/show/
|
|
255
|
+
// rev-parse/branch/submodule status fall through as read-only.
|
|
256
|
+
}
|
|
257
|
+
return false;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export function normalizeMeshTaskMode(value: unknown): MeshTaskMode | undefined {
|
|
261
|
+
if (typeof value !== 'string') return undefined;
|
|
262
|
+
const normalized = value.trim() as MeshTaskMode;
|
|
263
|
+
return (MESH_TASK_MODES as string[]).includes(normalized) ? normalized : undefined;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export function validateMeshTaskModeRequest(mode: unknown, message: string): MeshTaskModeValidationResult {
|
|
267
|
+
const taskMode = normalizeMeshTaskMode(mode);
|
|
268
|
+
if (!taskMode) {
|
|
269
|
+
return { valid: true, violations: [] };
|
|
270
|
+
}
|
|
271
|
+
if (taskMode !== 'live_debug_readonly') {
|
|
272
|
+
return { valid: true, taskMode, violations: [] };
|
|
273
|
+
}
|
|
274
|
+
const text = message || '';
|
|
275
|
+
// Only flag keywords that look like real commands (code/command context) and
|
|
276
|
+
// are not negated — descriptive/prohibitive prose ("don't run `npm publish`",
|
|
277
|
+
// "read-only, no deploy") must not trip the guardrail.
|
|
278
|
+
const violations = LIVE_DEBUG_READONLY_FORBIDDEN
|
|
279
|
+
.filter(rule => patternHasRealMutation(rule.pattern, text))
|
|
280
|
+
.map(rule => rule.label);
|
|
281
|
+
if (detectGitMutation(text)) {
|
|
282
|
+
violations.push('git_mutation');
|
|
283
|
+
}
|
|
284
|
+
return {
|
|
285
|
+
valid: violations.length === 0,
|
|
286
|
+
taskMode,
|
|
287
|
+
violations,
|
|
288
|
+
allowedOperations: [
|
|
289
|
+
'process/log/window/port/session inspection',
|
|
290
|
+
'read-only filesystem listing/reading',
|
|
291
|
+
'status probes and keep-running handle reporting',
|
|
292
|
+
'diagnostic summaries without source edits, commits, checkpoints, pushes, deploys, resets, rebases, or destructive cleanups',
|
|
293
|
+
],
|
|
294
|
+
};
|
|
295
|
+
}
|
|
12
296
|
|
|
13
297
|
export interface MeshWorkQueueEntry {
|
|
14
298
|
id: string;
|
|
15
299
|
meshId: string;
|
|
16
300
|
message: string;
|
|
17
301
|
status: MeshTaskStatus;
|
|
302
|
+
taskMode?: MeshTaskMode;
|
|
18
303
|
/** If specified, only this node can claim the task (used by legacy mesh_send_task) */
|
|
19
304
|
targetNodeId?: string;
|
|
20
305
|
/** If specified, only this runtime session can claim the task */
|
|
21
306
|
targetSessionId?: string;
|
|
307
|
+
/** If specified, a node must expose all tags before it can claim the task. */
|
|
308
|
+
requiredTags?: string[];
|
|
309
|
+
/**
|
|
310
|
+
* M1: ids of tasks that must reach 'completed' before this task is claimable.
|
|
311
|
+
* Forward references (ids not yet enqueued) are allowed for batch flows and
|
|
312
|
+
* simply keep the task waiting until the referenced task exists and completes.
|
|
313
|
+
*/
|
|
314
|
+
dependsOn?: string[];
|
|
315
|
+
/** M1/M3: mission this task belongs to (joins mesh_missions). */
|
|
316
|
+
missionId?: string;
|
|
317
|
+
/**
|
|
318
|
+
* M1: why this task is held back (e.g. "dependency_failed:<taskId>").
|
|
319
|
+
* Only set by the system on dependency failure under the 'block' policy;
|
|
320
|
+
* waiting-on-dependency state is computed at view time, not stored.
|
|
321
|
+
*/
|
|
322
|
+
blockedReason?: string;
|
|
22
323
|
/** The node that actually claimed and is executing the task */
|
|
23
324
|
assignedNodeId?: string;
|
|
24
325
|
/** The session currently executing the task */
|
|
25
326
|
assignedSessionId?: string;
|
|
327
|
+
/**
|
|
328
|
+
* Provider type of the session that claimed the task. Recorded so the queue
|
|
329
|
+
* can enforce per-(node, provider) maxParallel caps (RepoMeshNodePolicy
|
|
330
|
+
* providerRoles) by counting active assignments grouped by node + provider.
|
|
331
|
+
*/
|
|
332
|
+
assignedProviderType?: string;
|
|
26
333
|
/** Human/operator reason for terminal cancellation. */
|
|
27
334
|
cancelReason?: string;
|
|
28
335
|
cancelledAt?: string;
|
|
@@ -30,6 +337,8 @@ export interface MeshWorkQueueEntry {
|
|
|
30
337
|
requeueReason?: string;
|
|
31
338
|
requeuedAt?: string;
|
|
32
339
|
requeueCount?: number;
|
|
340
|
+
/** Max automatic requeue attempts. When requeueCount reaches this, task is auto-failed. */
|
|
341
|
+
maxRetries?: number;
|
|
33
342
|
/** Last automatic queue session spin-up attempt, for mesh_view_queue/debug visibility. */
|
|
34
343
|
autoLaunch?: {
|
|
35
344
|
status: 'skipped' | 'started' | 'failed' | 'completed';
|
|
@@ -41,54 +350,211 @@ export interface MeshWorkQueueEntry {
|
|
|
41
350
|
};
|
|
42
351
|
/** ISO timestamp when the task was dispatched (assigned) to a node/session. Used for precise matching on completion. */
|
|
43
352
|
dispatchTimestamp?: string;
|
|
353
|
+
/**
|
|
354
|
+
* (3) The ORIGINATING coordinator session that enqueued this task. Stamped onto the
|
|
355
|
+
* worker at dispatch (meshCoordinatorSessionId) so the task's completion routes back to
|
|
356
|
+
* the exact coordinator session — even when several coordinator sessions share one
|
|
357
|
+
* daemon. Rides in the queue payload JSON (no column migration); absent on legacy rows
|
|
358
|
+
* → daemon-level routing fallback (backward + version-skew safe).
|
|
359
|
+
*/
|
|
360
|
+
sourceCoordinatorSessionId?: string;
|
|
44
361
|
createdAt: string;
|
|
45
362
|
updatedAt: string;
|
|
46
363
|
}
|
|
47
364
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
365
|
+
export interface MeshQueueMutationOptions {
|
|
366
|
+
ownerRole?: RepoMeshDaemonRole;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
export function normalizeMeshCapabilityTags(value: unknown): string[] {
|
|
370
|
+
if (!Array.isArray(value)) return [];
|
|
371
|
+
const seen = new Set<string>();
|
|
372
|
+
return value
|
|
373
|
+
.map(tag => typeof tag === 'string' ? tag.trim() : '')
|
|
374
|
+
.filter(Boolean)
|
|
375
|
+
.filter(tag => {
|
|
376
|
+
if (seen.has(tag)) return false;
|
|
377
|
+
seen.add(tag);
|
|
378
|
+
return true;
|
|
379
|
+
});
|
|
51
380
|
}
|
|
52
381
|
|
|
53
|
-
function
|
|
54
|
-
const
|
|
55
|
-
|
|
382
|
+
function firstProviderPriority(policy: unknown): string | undefined {
|
|
383
|
+
const raw = policy && typeof policy === 'object' && !Array.isArray(policy)
|
|
384
|
+
? (policy as Record<string, unknown>).providerPriority
|
|
385
|
+
: undefined;
|
|
386
|
+
if (!Array.isArray(raw)) return undefined;
|
|
387
|
+
return raw.find(type => typeof type === 'string' && type.trim())?.trim();
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
function readNodeOverride(node: { userOverrides?: unknown } | undefined, key: 'platform' | 'arch'): string | null {
|
|
391
|
+
const overrides = node?.userOverrides;
|
|
392
|
+
if (!overrides || typeof overrides !== 'object' || Array.isArray(overrides)) return null;
|
|
393
|
+
const value = (overrides as Record<string, unknown>)[key];
|
|
394
|
+
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
|
56
395
|
}
|
|
57
396
|
|
|
58
397
|
/**
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
398
|
+
* Live, self-reported platform/arch the owning daemon stamped onto the node from
|
|
399
|
+
* its own process.platform/process.arch via the git_status envelope. Kept on a
|
|
400
|
+
* field DISTINCT from userOverrides so capability-tag derivation can prefer an
|
|
401
|
+
* explicit operator override while still self-healing auto-detected nodes — and
|
|
402
|
+
* so the value reflects the node's real OS rather than the coordinator's.
|
|
62
403
|
*/
|
|
63
|
-
function
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
for (let i = 0; i < 10; i++) {
|
|
67
|
-
try { fd = openSync(lockPath, 'wx'); break; } catch {
|
|
68
|
-
const deadline = Date.now() + 30;
|
|
69
|
-
while (Date.now() < deadline) { /* spin */ }
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
try { return fn(); } finally {
|
|
73
|
-
if (fd !== -1) try { closeSync(fd); } catch { /* noop */ }
|
|
74
|
-
try { unlinkSync(lockPath); } catch { /* already removed */ }
|
|
75
|
-
}
|
|
404
|
+
function readNodeReporter(node: { reportedPlatform?: unknown; reportedArch?: unknown } | undefined, key: 'platform' | 'arch'): string | null {
|
|
405
|
+
const value = key === 'platform' ? node?.reportedPlatform : node?.reportedArch;
|
|
406
|
+
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
|
76
407
|
}
|
|
77
408
|
|
|
78
|
-
function
|
|
79
|
-
|
|
80
|
-
|
|
409
|
+
export function buildMeshNodeCapabilityTags(
|
|
410
|
+
node: { capabilities?: unknown; policy?: unknown; isLocalWorktree?: unknown; worktreeBranch?: unknown; userOverrides?: unknown; reportedPlatform?: unknown; reportedArch?: unknown } | undefined,
|
|
411
|
+
providerType?: string,
|
|
412
|
+
): string[] {
|
|
413
|
+
const provider = typeof providerType === 'string' && providerType.trim()
|
|
414
|
+
? providerType.trim()
|
|
415
|
+
: firstProviderPriority(node?.policy);
|
|
416
|
+
const worktreeBranch = typeof node?.worktreeBranch === 'string' && node.worktreeBranch.trim()
|
|
417
|
+
? node.worktreeBranch.trim()
|
|
418
|
+
: null;
|
|
419
|
+
// Per-node platform/arch precedence (highest → lowest):
|
|
420
|
+
// 1. userOverrides.platform/arch — an EXPLICIT operator override always wins.
|
|
421
|
+
// 2. reportedPlatform/reportedArch — the live OS the owning daemon
|
|
422
|
+
// self-reported (its own process.platform/process.arch via the git_status
|
|
423
|
+
// envelope), persisted to the node record on each direct probe. This is
|
|
424
|
+
// why a Windows member advertises os=win32 even though the COORDINATOR
|
|
425
|
+
// computing these tags runs on darwin — without it the consumer reads the
|
|
426
|
+
// persistent node (operator userOverrides empty) and would fall straight
|
|
427
|
+
// through to the coordinator's own process.platform, mislabeling every
|
|
428
|
+
// node os=darwin. We prefer this LIVE value over any stale auto-stamp.
|
|
429
|
+
// 3. process.platform/process.arch — last-resort fallback, correct only for
|
|
430
|
+
// the local coordinator node / local worktree nodes that have not yet
|
|
431
|
+
// been probed (their workspace lives on THIS machine anyway).
|
|
432
|
+
// Vocabulary is raw process.platform/process.arch ("darwin"/"win32"/"linux",
|
|
433
|
+
// "arm64"/"x64") on both the advertiser and the required_tags matcher, which
|
|
434
|
+
// compares with plain string equality (nodeSatisfiesRequiredTags) — so this
|
|
435
|
+
// keeps the win32/darwin/linux vocabulary the matcher already expects.
|
|
436
|
+
const os = readNodeOverride(node, 'platform') ?? readNodeReporter(node, 'platform') ?? process.platform;
|
|
437
|
+
const arch = readNodeOverride(node, 'arch') ?? readNodeReporter(node, 'arch') ?? process.arch;
|
|
438
|
+
return normalizeMeshCapabilityTags([
|
|
439
|
+
...(Array.isArray(node?.capabilities) ? node.capabilities : []),
|
|
440
|
+
`os=${os}`,
|
|
441
|
+
`arch=${arch}`,
|
|
442
|
+
...(provider ? [`provider=${provider}`] : []),
|
|
443
|
+
// Worktree nodes automatically expose a "worktree=<branch>" tag so that
|
|
444
|
+
// mesh_enqueue_task with required_tags: ["worktree=<branch>"] routes
|
|
445
|
+
// only to the matching worktree node.
|
|
446
|
+
...(node?.isLocalWorktree === true && worktreeBranch ? [`worktree=${worktreeBranch}`] : []),
|
|
447
|
+
// Convergence routing: advertise how this node can land its work onto base.
|
|
448
|
+
// - converge=refine: local worktree nodes (on ANY machine — refine_mesh_node
|
|
449
|
+
// now forwards to the owning daemon) can run the Refinery merge → push →
|
|
450
|
+
// cleanup against their own checkout, so they accept code_change tasks.
|
|
451
|
+
// - converge=fast_forward: non-worktree nodes (the machine itself) can only
|
|
452
|
+
// ff/push an already-converged branch; they are NOT a destination for
|
|
453
|
+
// code_change work (a worktree is created first, and that worktree node
|
|
454
|
+
// receives the task instead). Reuses the ordinary required-tags filter —
|
|
455
|
+
// the load-balancing scheduler auto-injects converge=refine for code_change
|
|
456
|
+
// so such work is hard-filtered onto refine-capable nodes.
|
|
457
|
+
...(node?.isLocalWorktree === true ? ['converge=refine'] : ['converge=fast_forward']),
|
|
458
|
+
]);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
export function nodeSatisfiesRequiredTags(requiredTags: unknown, capabilityTags: unknown): boolean {
|
|
462
|
+
const required = normalizeMeshCapabilityTags(requiredTags);
|
|
463
|
+
if (required.length === 0) return true;
|
|
464
|
+
const available = new Set(normalizeMeshCapabilityTags(capabilityTags));
|
|
465
|
+
return required.every(tag => available.has(tag));
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* Convergence-aware required-tags resolution (load-balancing scheduler, opt-in).
|
|
470
|
+
*
|
|
471
|
+
* When the mesh enables policy.autoConvergeCodeChange, a `converge=refine` required
|
|
472
|
+
* tag is merged into a code_change task's required tags at enqueue time, so the
|
|
473
|
+
* scheduler hard-filters the task onto refine-capable worktree nodes only (on any
|
|
474
|
+
* machine — refine_mesh_node forwards to the owning daemon). Because the tag is
|
|
475
|
+
* persisted on the queue entry, BOTH the eligibility scan (maybeAutoLaunchOneQueueSession)
|
|
476
|
+
* and the claim transaction (claimNextQueueTask → nodeSatisfiesRequiredTags) enforce
|
|
477
|
+
* it consistently.
|
|
478
|
+
*
|
|
479
|
+
* Strict backward compatibility — the injection is skipped (returns the explicit tags
|
|
480
|
+
* unchanged) when ANY of:
|
|
481
|
+
* - the mesh does not opt in (autoConvergeCodeChange !== true), or
|
|
482
|
+
* - the task is not code_change (validation / live_debug_readonly / launch_app /
|
|
483
|
+
* convergence carry no merge cost and may run anywhere), or
|
|
484
|
+
* - the task is explicitly targeted (targetNodeId): the operator chose the node, so
|
|
485
|
+
* we do not second-guess it by filtering on convergence capability.
|
|
486
|
+
* Idempotent: normalizeMeshCapabilityTags dedupes, so re-injection is a no-op.
|
|
487
|
+
*/
|
|
488
|
+
export function resolveConvergeRequiredTags(
|
|
489
|
+
meshId: string,
|
|
490
|
+
taskMode: MeshTaskMode | undefined,
|
|
491
|
+
explicitRequiredTags: string[],
|
|
492
|
+
opts?: { targetNodeId?: string },
|
|
493
|
+
): string[] {
|
|
494
|
+
if (taskMode !== 'code_change') return explicitRequiredTags;
|
|
495
|
+
if (typeof opts?.targetNodeId === 'string' && opts.targetNodeId.trim()) return explicitRequiredTags;
|
|
496
|
+
let optedIn = false;
|
|
81
497
|
try {
|
|
82
|
-
|
|
83
|
-
return JSON.parse(content) as MeshWorkQueueEntry[];
|
|
498
|
+
optedIn = resolveAutoConvergeCodeChange(getMesh(meshId)?.policy as any);
|
|
84
499
|
} catch {
|
|
85
|
-
|
|
500
|
+
optedIn = false;
|
|
86
501
|
}
|
|
502
|
+
if (!optedIn) return explicitRequiredTags;
|
|
503
|
+
return normalizeMeshCapabilityTags([...explicitRequiredTags, MESH_CONVERGE_REFINE_TAG]);
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
function withQueueLock<T>(_meshId: string, fn: () => T): T {
|
|
507
|
+
return MeshRuntimeStore.getInstance().transaction(fn);
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
function readQueue(meshId: string): MeshWorkQueueEntry[] {
|
|
511
|
+
return MeshRuntimeStore.getInstance().getQueueEntries(meshId);
|
|
87
512
|
}
|
|
88
513
|
|
|
89
514
|
function writeQueue(meshId: string, queue: MeshWorkQueueEntry[]): void {
|
|
90
|
-
|
|
91
|
-
|
|
515
|
+
MeshRuntimeStore.getInstance().replaceQueue(meshId, queue);
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
function normalizeDependsOn(value: unknown): string[] {
|
|
519
|
+
if (!Array.isArray(value)) return [];
|
|
520
|
+
const seen = new Set<string>();
|
|
521
|
+
return value
|
|
522
|
+
.map(id => typeof id === 'string' ? id.trim() : '')
|
|
523
|
+
.filter(Boolean)
|
|
524
|
+
.filter(id => {
|
|
525
|
+
if (seen.has(id)) return false;
|
|
526
|
+
seen.add(id);
|
|
527
|
+
return true;
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/**
|
|
532
|
+
* M1: detect dependency cycles before enqueue. Walks the dependency graph of
|
|
533
|
+
* existing queue entries plus the new task's edges. Fail-closed: a cycle
|
|
534
|
+
* rejects the enqueue entirely. Synchronous and bounded by queue size.
|
|
535
|
+
*/
|
|
536
|
+
export function assertNoDependencyCycle(meshId: string, newTaskId: string, dependsOn: string[]): void {
|
|
537
|
+
if (dependsOn.length === 0) return;
|
|
538
|
+
if (dependsOn.includes(newTaskId)) {
|
|
539
|
+
throw new Error(`dependency_cycle_detected: task '${newTaskId}' cannot depend on itself`);
|
|
540
|
+
}
|
|
541
|
+
const adjacency = new Map<string, string[]>();
|
|
542
|
+
for (const entry of readQueue(meshId)) {
|
|
543
|
+
adjacency.set(entry.id, normalizeDependsOn(entry.dependsOn));
|
|
544
|
+
}
|
|
545
|
+
adjacency.set(newTaskId, dependsOn);
|
|
546
|
+
// DFS from the new task: if we can reach newTaskId again, the edges form a cycle.
|
|
547
|
+
const stack = [...dependsOn];
|
|
548
|
+
const visited = new Set<string>();
|
|
549
|
+
while (stack.length > 0) {
|
|
550
|
+
const current = stack.pop()!;
|
|
551
|
+
if (current === newTaskId) {
|
|
552
|
+
throw new Error(`dependency_cycle_detected: task '${newTaskId}' is part of a dependency cycle via '${dependsOn.join(', ')}'`);
|
|
553
|
+
}
|
|
554
|
+
if (visited.has(current)) continue;
|
|
555
|
+
visited.add(current);
|
|
556
|
+
stack.push(...(adjacency.get(current) ?? []));
|
|
557
|
+
}
|
|
92
558
|
}
|
|
93
559
|
|
|
94
560
|
/**
|
|
@@ -97,22 +563,125 @@ function writeQueue(meshId: string, queue: MeshWorkQueueEntry[]): void {
|
|
|
97
563
|
export function enqueueTask(
|
|
98
564
|
meshId: string,
|
|
99
565
|
message: string,
|
|
100
|
-
opts?: {
|
|
566
|
+
opts?: {
|
|
567
|
+
targetNodeId?: string;
|
|
568
|
+
targetSessionId?: string;
|
|
569
|
+
taskMode?: MeshTaskMode | string;
|
|
570
|
+
requiredTags?: string[];
|
|
571
|
+
/** M1: tasks that must complete before this one is claimable. */
|
|
572
|
+
dependsOn?: string[];
|
|
573
|
+
/** M1/M3: mission this task belongs to. */
|
|
574
|
+
missionId?: string;
|
|
575
|
+
/** Explicit task id for batch/template flows (M5). Random UUID when omitted. */
|
|
576
|
+
id?: string;
|
|
577
|
+
/** (3) Originating coordinator session id (for session-anchored completion routing). */
|
|
578
|
+
sourceCoordinatorSessionId?: string;
|
|
579
|
+
} & MeshQueueMutationOptions,
|
|
101
580
|
): MeshWorkQueueEntry {
|
|
581
|
+
requireMeshHostQueueOwner(opts);
|
|
582
|
+
const modeValidation = validateMeshTaskModeRequest(opts?.taskMode, message);
|
|
583
|
+
if (!modeValidation.valid) {
|
|
584
|
+
throw new Error(`live_debug_readonly_guardrail_violation: forbidden operations (${modeValidation.violations.join(', ')})`);
|
|
585
|
+
}
|
|
586
|
+
const id = typeof opts?.id === 'string' && opts.id.trim() ? opts.id.trim() : randomUUID();
|
|
587
|
+
const dependsOn = normalizeDependsOn(opts?.dependsOn);
|
|
102
588
|
return withQueueLock(meshId, () => {
|
|
103
|
-
|
|
589
|
+
if (MeshRuntimeStore.getInstance().findQueueEntryById(meshId, id)) {
|
|
590
|
+
throw new Error(`duplicate_task_id: task '${id}' already exists in mesh '${meshId}'`);
|
|
591
|
+
}
|
|
592
|
+
assertNoDependencyCycle(meshId, id, dependsOn);
|
|
593
|
+
const callerTags = normalizeMeshCapabilityTags(opts?.requiredTags);
|
|
594
|
+
// Convergence routing (opt-in): auto-inject converge=refine for code_change
|
|
595
|
+
// tasks so they hard-filter onto refine-capable worktree nodes. No-op unless
|
|
596
|
+
// the mesh opts in; explicit target_node_id / required_tags are preserved.
|
|
597
|
+
// Routing is otherwise governed solely by the caller's required_tags (hard
|
|
598
|
+
// filter through nodeSatisfiesRequiredTags) — no role/taskMode auto-routing.
|
|
599
|
+
const resolvedRequiredTags = resolveConvergeRequiredTags(
|
|
600
|
+
meshId,
|
|
601
|
+
modeValidation.taskMode,
|
|
602
|
+
callerTags,
|
|
603
|
+
{ targetNodeId: opts?.targetNodeId },
|
|
604
|
+
);
|
|
104
605
|
const entry: MeshWorkQueueEntry = {
|
|
105
|
-
id
|
|
606
|
+
id,
|
|
106
607
|
meshId,
|
|
107
608
|
message,
|
|
108
609
|
status: 'pending',
|
|
610
|
+
taskMode: modeValidation.taskMode,
|
|
109
611
|
targetNodeId: opts?.targetNodeId,
|
|
110
612
|
targetSessionId: opts?.targetSessionId,
|
|
613
|
+
requiredTags: resolvedRequiredTags,
|
|
614
|
+
...(dependsOn.length > 0 ? { dependsOn } : {}),
|
|
615
|
+
...(typeof opts?.missionId === 'string' && opts.missionId.trim() ? { missionId: opts.missionId.trim() } : {}),
|
|
616
|
+
...(typeof opts?.sourceCoordinatorSessionId === 'string' && opts.sourceCoordinatorSessionId.trim()
|
|
617
|
+
? { sourceCoordinatorSessionId: opts.sourceCoordinatorSessionId.trim() }
|
|
618
|
+
: {}),
|
|
111
619
|
createdAt: new Date().toISOString(),
|
|
112
620
|
updatedAt: new Date().toISOString(),
|
|
113
621
|
};
|
|
114
|
-
|
|
115
|
-
|
|
622
|
+
MeshRuntimeStore.getInstance().insertQueueEntry(entry);
|
|
623
|
+
return entry;
|
|
624
|
+
});
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
/**
|
|
628
|
+
* Record a direct-dispatch task (mesh_send_task) as an already-assigned queue
|
|
629
|
+
* entry so it is attributable to a mission.
|
|
630
|
+
*
|
|
631
|
+
* Direct dispatch normally bypasses the queue entirely — the task lives only in
|
|
632
|
+
* the ledger + mesh_direct_dispatches table, neither of which carries a
|
|
633
|
+
* missionId, so {@link summarizeMissionTasks}/{@link computeMeshTaskStats}
|
|
634
|
+
* (which both scan the queue for `task.missionId`) count it as 0. When a
|
|
635
|
+
* mission is attached, we materialise the same queue entry shape an enqueued
|
|
636
|
+
* task would have, but pre-assigned to the dispatched node/session and stamped
|
|
637
|
+
* with the dispatch timestamp. The terminal event path (updateSessionTaskStatus
|
|
638
|
+
* → findAssignedBySession) then flips it to completed/failed exactly like a
|
|
639
|
+
* pulled task, so mission total + completed aggregates work with no extra wiring.
|
|
640
|
+
*
|
|
641
|
+
* Intentionally separate from {@link enqueueTask}: enqueue creates `pending`
|
|
642
|
+
* work for the queue to assign, whereas this records work already dispatched
|
|
643
|
+
* out-of-band. They share the missionId stamping rule and mode validation.
|
|
644
|
+
*/
|
|
645
|
+
export function recordDirectDispatchTask(
|
|
646
|
+
meshId: string,
|
|
647
|
+
message: string,
|
|
648
|
+
opts: {
|
|
649
|
+
id: string;
|
|
650
|
+
missionId: string;
|
|
651
|
+
assignedNodeId?: string;
|
|
652
|
+
assignedSessionId?: string;
|
|
653
|
+
taskMode?: MeshTaskMode | string;
|
|
654
|
+
dispatchedAt?: string;
|
|
655
|
+
},
|
|
656
|
+
): MeshWorkQueueEntry | null {
|
|
657
|
+
const missionId = typeof opts.missionId === 'string' ? opts.missionId.trim() : '';
|
|
658
|
+
if (!missionId) return null;
|
|
659
|
+
const taskId = typeof opts.id === 'string' ? opts.id.trim() : '';
|
|
660
|
+
if (!taskId) return null;
|
|
661
|
+
const modeValidation = validateMeshTaskModeRequest(opts.taskMode, message);
|
|
662
|
+
if (!modeValidation.valid) {
|
|
663
|
+
throw new Error(`live_debug_readonly_guardrail_violation: forbidden operations (${modeValidation.violations.join(', ')})`);
|
|
664
|
+
}
|
|
665
|
+
const now = opts.dispatchedAt && opts.dispatchedAt.trim() ? opts.dispatchedAt : new Date().toISOString();
|
|
666
|
+
return withQueueLock(meshId, () => {
|
|
667
|
+
if (MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId)) {
|
|
668
|
+
// Already materialised (e.g. retry of the same dispatch) — leave it untouched.
|
|
669
|
+
return null;
|
|
670
|
+
}
|
|
671
|
+
const entry: MeshWorkQueueEntry = {
|
|
672
|
+
id: taskId,
|
|
673
|
+
meshId,
|
|
674
|
+
message,
|
|
675
|
+
status: 'assigned',
|
|
676
|
+
...(modeValidation.taskMode ? { taskMode: modeValidation.taskMode } : {}),
|
|
677
|
+
missionId,
|
|
678
|
+
...(opts.assignedNodeId ? { targetNodeId: opts.assignedNodeId, assignedNodeId: opts.assignedNodeId } : {}),
|
|
679
|
+
...(opts.assignedSessionId ? { targetSessionId: opts.assignedSessionId, assignedSessionId: opts.assignedSessionId } : {}),
|
|
680
|
+
dispatchTimestamp: now,
|
|
681
|
+
createdAt: now,
|
|
682
|
+
updatedAt: now,
|
|
683
|
+
};
|
|
684
|
+
MeshRuntimeStore.getInstance().insertQueueEntry(entry);
|
|
116
685
|
return entry;
|
|
117
686
|
});
|
|
118
687
|
}
|
|
@@ -121,43 +690,83 @@ export function enqueueTask(
|
|
|
121
690
|
* Get all tasks in the queue, optionally filtered by status.
|
|
122
691
|
*/
|
|
123
692
|
export function getQueue(meshId: string, opts?: { status?: MeshTaskStatus[] }): MeshWorkQueueEntry[] {
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
return queue;
|
|
693
|
+
return MeshRuntimeStore.getInstance().getQueueEntries(meshId, opts?.status?.length ? opts.status : undefined);
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
export function getMeshQueueRevision(meshId: string): string {
|
|
697
|
+
return MeshRuntimeStore.getInstance().getQueueRevision(meshId);
|
|
130
698
|
}
|
|
131
699
|
|
|
132
700
|
/**
|
|
133
701
|
* Find the next pending task that this node is allowed to claim, and mark it as assigned.
|
|
702
|
+
*
|
|
703
|
+
* `opts.providerType` is stamped onto the claimed entry (assignedProviderType) so
|
|
704
|
+
* per-(node, provider) caps can be counted. `opts.providerMaxParallel`, when set,
|
|
705
|
+
* is the enforced per-(node, provider) cap from RepoMeshNodePolicy.providerRoles:
|
|
706
|
+
* a task is not assigned to this (node, provider) once it already has that many
|
|
707
|
+
* active assignments. This composes with the global/taskMode caps (stricter wins).
|
|
134
708
|
*/
|
|
135
|
-
export function claimNextTask(
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
709
|
+
export function claimNextTask(
|
|
710
|
+
meshId: string,
|
|
711
|
+
nodeId: string,
|
|
712
|
+
sessionId: string,
|
|
713
|
+
capabilityTags?: string[],
|
|
714
|
+
opts?: { providerType?: string; providerMaxParallel?: number },
|
|
715
|
+
): MeshWorkQueueEntry | null {
|
|
716
|
+
return MeshRuntimeStore.getInstance().claimNextQueueTask(meshId, nodeId, sessionId, capabilityTags, opts);
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
// ─── M1: Dependency Failure Propagation ─────────
|
|
720
|
+
|
|
721
|
+
export type DependencyFailurePolicy = 'block' | 'cancel';
|
|
722
|
+
|
|
723
|
+
function resolveDependencyFailurePolicy(meshId: string): DependencyFailurePolicy {
|
|
724
|
+
try {
|
|
725
|
+
const policy = (getMesh(meshId)?.policy ?? {}) as Record<string, unknown>;
|
|
726
|
+
return policy.onDependencyFailure === 'cancel' ? 'cancel' : 'block';
|
|
727
|
+
} catch {
|
|
728
|
+
return 'block';
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/**
|
|
733
|
+
* Apply the mesh's onDependencyFailure policy to pending dependents of a task
|
|
734
|
+
* that just reached a failed/cancelled terminal state.
|
|
735
|
+
*
|
|
736
|
+
* - 'block' (default): dependents stay pending with blockedReason
|
|
737
|
+
* "dependency_failed:<taskId>" so an operator can requeue/cancel them.
|
|
738
|
+
* - 'cancel': dependents are cancelled (cascading to their own dependents).
|
|
739
|
+
*
|
|
740
|
+
* Must be called inside the queue lock of the triggering transition.
|
|
741
|
+
*/
|
|
742
|
+
function propagateDependencyFailure(meshId: string, failedTaskId: string): void {
|
|
743
|
+
const policy = resolveDependencyFailurePolicy(meshId);
|
|
744
|
+
const store = MeshRuntimeStore.getInstance();
|
|
745
|
+
const frontier = [failedTaskId];
|
|
746
|
+
const seen = new Set<string>(frontier);
|
|
747
|
+
while (frontier.length > 0) {
|
|
748
|
+
const currentId = frontier.pop()!;
|
|
749
|
+
const dependents = store.getQueueEntries(meshId, ['pending'])
|
|
750
|
+
.filter(entry => Array.isArray(entry.dependsOn) && entry.dependsOn.includes(currentId));
|
|
751
|
+
for (const dependent of dependents) {
|
|
752
|
+
if (seen.has(dependent.id)) continue;
|
|
753
|
+
seen.add(dependent.id);
|
|
754
|
+
if (policy === 'cancel') {
|
|
755
|
+
dependent.status = 'cancelled';
|
|
756
|
+
dependent.cancelledAt = new Date().toISOString();
|
|
757
|
+
dependent.cancelReason = `dependency_failed:${currentId}`;
|
|
758
|
+
store.updateQueueEntry(dependent);
|
|
759
|
+
frontier.push(dependent.id); // cascade to transitive dependents
|
|
760
|
+
} else {
|
|
761
|
+
dependent.blockedReason = `dependency_failed:${currentId}`;
|
|
762
|
+
store.updateQueueEntry(dependent);
|
|
763
|
+
}
|
|
148
764
|
}
|
|
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
|
-
});
|
|
765
|
+
}
|
|
159
766
|
}
|
|
160
767
|
|
|
768
|
+
const DEPENDENCY_FAILURE_TERMINALS = new Set<MeshTaskStatus>(['failed', 'cancelled']);
|
|
769
|
+
|
|
161
770
|
/**
|
|
162
771
|
* Update the status of a specific task.
|
|
163
772
|
* Used when a session completes, fails, or stalls.
|
|
@@ -166,15 +775,16 @@ export function updateTaskStatus(
|
|
|
166
775
|
meshId: string,
|
|
167
776
|
taskId: string,
|
|
168
777
|
status: MeshTaskStatus,
|
|
778
|
+
opts?: MeshQueueMutationOptions,
|
|
169
779
|
): MeshWorkQueueEntry | null {
|
|
780
|
+
requireMeshHostQueueOwner(opts);
|
|
170
781
|
return withQueueLock(meshId, () => {
|
|
171
|
-
const
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
return queue[idx];
|
|
782
|
+
const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
|
|
783
|
+
if (!entry) return null;
|
|
784
|
+
entry.status = status;
|
|
785
|
+
MeshRuntimeStore.getInstance().updateQueueEntry(entry);
|
|
786
|
+
if (DEPENDENCY_FAILURE_TERMINALS.has(status)) propagateDependencyFailure(meshId, taskId);
|
|
787
|
+
return entry;
|
|
178
788
|
});
|
|
179
789
|
}
|
|
180
790
|
|
|
@@ -184,14 +794,12 @@ export function recordTaskAutoLaunch(
|
|
|
184
794
|
autoLaunch: Omit<NonNullable<MeshWorkQueueEntry['autoLaunch']>, 'updatedAt'>,
|
|
185
795
|
): MeshWorkQueueEntry | null {
|
|
186
796
|
return withQueueLock(meshId, () => {
|
|
187
|
-
const
|
|
188
|
-
|
|
189
|
-
if (idx === -1) return null;
|
|
797
|
+
const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
|
|
798
|
+
if (!entry) return null;
|
|
190
799
|
const now = new Date().toISOString();
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
return queue[idx];
|
|
800
|
+
entry.autoLaunch = { ...autoLaunch, updatedAt: now };
|
|
801
|
+
MeshRuntimeStore.getInstance().updateQueueEntry(entry);
|
|
802
|
+
return entry;
|
|
195
803
|
});
|
|
196
804
|
}
|
|
197
805
|
|
|
@@ -201,19 +809,19 @@ export function recordTaskAutoLaunch(
|
|
|
201
809
|
export function cancelTask(
|
|
202
810
|
meshId: string,
|
|
203
811
|
taskId: string,
|
|
204
|
-
opts?: { reason?: string },
|
|
812
|
+
opts?: { reason?: string } & MeshQueueMutationOptions,
|
|
205
813
|
): MeshWorkQueueEntry | null {
|
|
814
|
+
requireMeshHostQueueOwner(opts);
|
|
206
815
|
return withQueueLock(meshId, () => {
|
|
207
|
-
const
|
|
208
|
-
|
|
209
|
-
if (idx === -1) return null;
|
|
816
|
+
const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
|
|
817
|
+
if (!entry) return null;
|
|
210
818
|
const now = new Date().toISOString();
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
return
|
|
819
|
+
entry.status = 'cancelled';
|
|
820
|
+
entry.cancelledAt = now;
|
|
821
|
+
if (opts?.reason) entry.cancelReason = opts.reason;
|
|
822
|
+
MeshRuntimeStore.getInstance().updateQueueEntry(entry);
|
|
823
|
+
propagateDependencyFailure(meshId, taskId);
|
|
824
|
+
return entry;
|
|
217
825
|
});
|
|
218
826
|
}
|
|
219
827
|
|
|
@@ -221,6 +829,11 @@ export function cancelTask(
|
|
|
221
829
|
* Return a queue task to pending for retry. By default, dead session targeting
|
|
222
830
|
* and assigned ownership are cleared so stale assignments do not strand again.
|
|
223
831
|
*/
|
|
832
|
+
export type RequeueResult =
|
|
833
|
+
| { status: 'requeued'; entry: MeshWorkQueueEntry }
|
|
834
|
+
| { status: 'failed_max_retries'; entry: MeshWorkQueueEntry; maxRetries: number; requeueCount: number }
|
|
835
|
+
| { status: 'not_found' };
|
|
836
|
+
|
|
224
837
|
export function requeueTask(
|
|
225
838
|
meshId: string,
|
|
226
839
|
taskId: string,
|
|
@@ -230,15 +843,34 @@ export function requeueTask(
|
|
|
230
843
|
targetSessionId?: string;
|
|
231
844
|
clearTargetNode?: boolean;
|
|
232
845
|
clearTargetSession?: boolean;
|
|
233
|
-
|
|
846
|
+
/**
|
|
847
|
+
* Override the retry cap for this call. Use only for explicit operator actions.
|
|
848
|
+
* If true, the task is requeued even when requeueCount >= maxRetries.
|
|
849
|
+
*/
|
|
850
|
+
force?: boolean;
|
|
851
|
+
/** Per-task retry cap override. Falls back to mesh policy maxTaskRetries (default 1). */
|
|
852
|
+
maxRetries?: number;
|
|
853
|
+
} & MeshQueueMutationOptions,
|
|
234
854
|
): MeshWorkQueueEntry | null {
|
|
855
|
+
requireMeshHostQueueOwner(opts);
|
|
235
856
|
return withQueueLock(meshId, () => {
|
|
236
|
-
const
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
const
|
|
240
|
-
|
|
857
|
+
const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
|
|
858
|
+
if (!entry) return null;
|
|
859
|
+
const currentCount = entry.requeueCount || 0;
|
|
860
|
+
const maxRetries = opts?.maxRetries ?? entry.maxRetries ?? 1;
|
|
861
|
+
if (!opts?.force && currentCount >= maxRetries) {
|
|
862
|
+
// Auto-fail: cap exceeded without explicit force override.
|
|
863
|
+
entry.status = 'failed';
|
|
864
|
+
entry.cancelReason = `max_retries_exceeded: requeued ${currentCount} time(s), limit is ${maxRetries}`;
|
|
865
|
+
entry.updatedAt = new Date().toISOString();
|
|
866
|
+
MeshRuntimeStore.getInstance().updateQueueEntry(entry);
|
|
867
|
+
propagateDependencyFailure(meshId, taskId);
|
|
868
|
+
return entry;
|
|
869
|
+
}
|
|
241
870
|
entry.status = 'pending';
|
|
871
|
+
// Operator requeue clears a dependency-failure block — the operator is
|
|
872
|
+
// explicitly overriding the held-back state.
|
|
873
|
+
delete entry.blockedReason;
|
|
242
874
|
delete entry.assignedNodeId;
|
|
243
875
|
delete entry.assignedSessionId;
|
|
244
876
|
delete entry.cancelledAt;
|
|
@@ -247,11 +879,10 @@ export function requeueTask(
|
|
|
247
879
|
if (typeof opts?.targetNodeId === 'string') entry.targetNodeId = opts.targetNodeId;
|
|
248
880
|
if (opts?.clearTargetSession !== false) delete entry.targetSessionId;
|
|
249
881
|
if (typeof opts?.targetSessionId === 'string') entry.targetSessionId = opts.targetSessionId;
|
|
250
|
-
entry.
|
|
251
|
-
entry.
|
|
252
|
-
entry.requeueCount = (entry.requeueCount || 0) + 1;
|
|
882
|
+
entry.requeuedAt = new Date().toISOString();
|
|
883
|
+
entry.requeueCount = currentCount + 1;
|
|
253
884
|
if (opts?.reason) entry.requeueReason = opts.reason;
|
|
254
|
-
|
|
885
|
+
MeshRuntimeStore.getInstance().updateQueueEntry(entry);
|
|
255
886
|
return entry;
|
|
256
887
|
});
|
|
257
888
|
}
|
|
@@ -263,28 +894,58 @@ export function updateSessionTaskStatus(
|
|
|
263
894
|
meshId: string,
|
|
264
895
|
sessionId: string,
|
|
265
896
|
status: MeshTaskStatus,
|
|
266
|
-
opts?: { occurredAt?: string },
|
|
897
|
+
opts?: { occurredAt?: string; taskId?: string },
|
|
267
898
|
): MeshWorkQueueEntry | null {
|
|
268
899
|
return withQueueLock(meshId, () => {
|
|
269
|
-
const
|
|
270
|
-
const
|
|
271
|
-
const
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
const
|
|
277
|
-
|
|
278
|
-
if (
|
|
900
|
+
const store = MeshRuntimeStore.getInstance();
|
|
901
|
+
const occurredAtIso = opts?.occurredAt ? new Date(opts.occurredAt).toISOString() : undefined;
|
|
902
|
+
const entry = store.findAssignedBySession(meshId, sessionId, occurredAtIso, opts?.taskId);
|
|
903
|
+
if (!entry) {
|
|
904
|
+
// C2: the silent null here is exactly what stranded a finished task as
|
|
905
|
+
// `assigned` for 19 minutes. If the session still has an assigned row we
|
|
906
|
+
// failed to resolve, surface it loudly instead of dropping the completion.
|
|
907
|
+
const assignedRows = store.getActiveAssignmentDetails(meshId)
|
|
908
|
+
.filter(r => r.sessionId === sessionId);
|
|
909
|
+
if (assignedRows.length > 0) {
|
|
910
|
+
LOG.warn('MeshQueue', `No assigned queue row matched completion for mesh ${meshId} session ${sessionId} `
|
|
911
|
+
+ `(taskId=${opts?.taskId ?? 'none'}, occurredAt=${occurredAtIso ?? 'none'}); `
|
|
912
|
+
+ `${assignedRows.length} assigned row(s) exist: ${assignedRows.map(r => r.id).join(',')}`);
|
|
913
|
+
}
|
|
914
|
+
return null;
|
|
279
915
|
}
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
return queue[bestIdx];
|
|
916
|
+
entry.status = status;
|
|
917
|
+
store.updateQueueEntry(entry);
|
|
918
|
+
if (DEPENDENCY_FAILURE_TERMINALS.has(status)) propagateDependencyFailure(meshId, entry.id);
|
|
919
|
+
return entry;
|
|
285
920
|
});
|
|
286
921
|
}
|
|
287
922
|
|
|
923
|
+
/**
|
|
924
|
+
* M1-3: true when at least one pending task is waiting on the given task.
|
|
925
|
+
* Used by the completion event path to decide whether to wake the queue.
|
|
926
|
+
*/
|
|
927
|
+
export function hasPendingDependents(meshId: string, taskId: string): boolean {
|
|
928
|
+
return MeshRuntimeStore.getInstance().getQueueEntries(meshId, ['pending'])
|
|
929
|
+
.some(entry => Array.isArray(entry.dependsOn) && entry.dependsOn.includes(taskId));
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
/**
|
|
933
|
+
* M1-4: view-time dependency state for a task — unmet dependency ids and
|
|
934
|
+
* whether the task is currently claimable from a dependency standpoint.
|
|
935
|
+
* Not stored (truth stays in task statuses).
|
|
936
|
+
*/
|
|
937
|
+
export function describeTaskDependencyState(
|
|
938
|
+
entry: Pick<MeshWorkQueueEntry, 'dependsOn' | 'blockedReason'>,
|
|
939
|
+
statusById: Map<string, MeshTaskStatus | string>,
|
|
940
|
+
): { waitingOn: string[]; dependenciesSatisfied: boolean } {
|
|
941
|
+
const deps = Array.isArray(entry.dependsOn) ? entry.dependsOn : [];
|
|
942
|
+
const waitingOn = deps.filter(depId => statusById.get(depId) !== 'completed');
|
|
943
|
+
return {
|
|
944
|
+
waitingOn,
|
|
945
|
+
dependenciesSatisfied: waitingOn.length === 0 && !entry.blockedReason,
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
|
|
288
949
|
export interface MeshWorkQueueStats {
|
|
289
950
|
total: number;
|
|
290
951
|
active: number;
|
|
@@ -310,14 +971,16 @@ export interface MeshWorkQueueStats {
|
|
|
310
971
|
* Return aggregate queue statistics for the given mesh.
|
|
311
972
|
*/
|
|
312
973
|
export function getMeshQueueStats(meshId: string): MeshWorkQueueStats {
|
|
313
|
-
const
|
|
314
|
-
const
|
|
315
|
-
const
|
|
316
|
-
const
|
|
317
|
-
const
|
|
318
|
-
const
|
|
974
|
+
const rows = MeshRuntimeStore.getInstance().getQueueStatsByStatus(meshId);
|
|
975
|
+
const counts: Record<string, number> = {};
|
|
976
|
+
for (const r of rows) counts[r.status] = r.count;
|
|
977
|
+
const pending = counts['pending'] ?? 0;
|
|
978
|
+
const assigned = counts['assigned'] ?? 0;
|
|
979
|
+
const completed = counts['completed'] ?? 0;
|
|
980
|
+
const failed = counts['failed'] ?? 0;
|
|
981
|
+
const cancelled = counts['cancelled'] ?? 0;
|
|
319
982
|
return {
|
|
320
|
-
total:
|
|
983
|
+
total: pending + assigned + completed + failed + cancelled,
|
|
321
984
|
active: pending + assigned,
|
|
322
985
|
historical: completed + failed + cancelled,
|
|
323
986
|
pending,
|
|
@@ -325,22 +988,119 @@ export function getMeshQueueStats(meshId: string): MeshWorkQueueStats {
|
|
|
325
988
|
completed,
|
|
326
989
|
failed,
|
|
327
990
|
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
|
-
})),
|
|
991
|
+
activeCounts: { pending, assigned },
|
|
992
|
+
historicalCounts: { completed, failed, cancelled },
|
|
993
|
+
activeAssignments: MeshRuntimeStore.getInstance().getActiveAssignmentDetails(meshId),
|
|
345
994
|
};
|
|
346
995
|
}
|
|
996
|
+
|
|
997
|
+
export function __replaceMeshQueueForTests(meshId: string, queue: MeshWorkQueueEntry[]): void {
|
|
998
|
+
MeshRuntimeStore.getInstance().transaction(() => {
|
|
999
|
+
MeshRuntimeStore.getInstance().replaceQueue(meshId, queue);
|
|
1000
|
+
});
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
export function __clearMeshQueueForTests(meshId: string): void {
|
|
1004
|
+
MeshRuntimeStore.getInstance().deleteQueue(meshId);
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
export function __clearDirectDispatchesForTests(meshId: string): void {
|
|
1008
|
+
MeshRuntimeStore.getInstance().deleteDirectDispatches(meshId);
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
export function __resetMeshRuntimeStoreForTests(): void {
|
|
1012
|
+
MeshRuntimeStore.resetForTests();
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
// ── Direct Dispatch Tracking ─────────────────────────────────────────────────
|
|
1016
|
+
// Persists direct (non-queue) task dispatches so buildMeshActiveWork can read
|
|
1017
|
+
// active work from MeshRuntimeStore instead of scanning ledger JSONL entries.
|
|
1018
|
+
|
|
1019
|
+
export type DirectDispatchRecord = ReturnType<MeshRuntimeStore['getActiveDirectDispatches']>[number];
|
|
1020
|
+
|
|
1021
|
+
export function insertDirectDispatch(
|
|
1022
|
+
meshId: string,
|
|
1023
|
+
data: {
|
|
1024
|
+
taskId: string;
|
|
1025
|
+
nodeId?: string;
|
|
1026
|
+
sessionId?: string;
|
|
1027
|
+
providerType?: string;
|
|
1028
|
+
message: string;
|
|
1029
|
+
taskMode?: string;
|
|
1030
|
+
via: string;
|
|
1031
|
+
dispatchedToIdleSession?: boolean;
|
|
1032
|
+
dispatchedAt: string;
|
|
1033
|
+
},
|
|
1034
|
+
): void {
|
|
1035
|
+
try {
|
|
1036
|
+
MeshRuntimeStore.getInstance().insertDirectDispatch({ ...data, meshId });
|
|
1037
|
+
} catch (e: any) {
|
|
1038
|
+
process.stderr.write(`[adhdev-mesh] insertDirectDispatch failed for task ${data.taskId}: ${e?.message || e}\n`);
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
export function getActiveDirectDispatches(meshId: string): DirectDispatchRecord[] {
|
|
1043
|
+
try {
|
|
1044
|
+
return MeshRuntimeStore.getInstance().getActiveDirectDispatches(meshId);
|
|
1045
|
+
} catch {
|
|
1046
|
+
return [];
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
export function updateDirectDispatchStatus(
|
|
1051
|
+
meshId: string,
|
|
1052
|
+
sessionId: string,
|
|
1053
|
+
status: 'acked' | 'completed' | 'failed' | 'stale',
|
|
1054
|
+
): void {
|
|
1055
|
+
try {
|
|
1056
|
+
MeshRuntimeStore.getInstance().updateDirectDispatchStatus(meshId, sessionId, status);
|
|
1057
|
+
} catch { /* best-effort */ }
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
export function cleanupTerminalDirectDispatches(olderThanMs = 7 * 24 * 60 * 60_000): void {
|
|
1061
|
+
try {
|
|
1062
|
+
MeshRuntimeStore.getInstance().cleanupTerminalDirectDispatches(olderThanMs);
|
|
1063
|
+
} catch { /* best-effort */ }
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
export function markStaleDirectDispatches(meshId: string, olderThanMs = 60 * 60_000): void {
|
|
1067
|
+
try {
|
|
1068
|
+
MeshRuntimeStore.getInstance().markStaleDirectDispatches(meshId, olderThanMs);
|
|
1069
|
+
} catch { /* best-effort */ }
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
/**
|
|
1073
|
+
* Delete specific direct dispatch rows by taskId. Returns the number of rows deleted.
|
|
1074
|
+
* Used by the staleDirect prune path to evict orphaned/terminal dispatch records from the
|
|
1075
|
+
* active staleDirect surface while leaving the append-only mesh ledger (audit history) intact.
|
|
1076
|
+
*/
|
|
1077
|
+
export function deleteDirectDispatchesByTaskId(meshId: string, taskIds: string[]): number {
|
|
1078
|
+
try {
|
|
1079
|
+
return MeshRuntimeStore.getInstance().deleteDirectDispatchesByTaskId(meshId, taskIds);
|
|
1080
|
+
} catch {
|
|
1081
|
+
return 0;
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
export type MeshToolCallRateResult = { rateLimitExceeded: boolean; callsInWindow: number; advisory: string | null };
|
|
1086
|
+
|
|
1087
|
+
/**
|
|
1088
|
+
* Record a coordinator tool call and return a rate-limit advisory when the
|
|
1089
|
+
* call rate for that tool exceeds the allowed threshold.
|
|
1090
|
+
*
|
|
1091
|
+
* Defaults: 10-second sliding window, max 5 calls before advisory is raised.
|
|
1092
|
+
* Returns { rateLimitExceeded: false } on any store error so callers are not blocked.
|
|
1093
|
+
*/
|
|
1094
|
+
export function recordMeshToolCall(opts: {
|
|
1095
|
+
meshId: string;
|
|
1096
|
+
tool: string;
|
|
1097
|
+
sessionId?: string | null;
|
|
1098
|
+
windowMs?: number;
|
|
1099
|
+
maxCalls?: number;
|
|
1100
|
+
}): MeshToolCallRateResult {
|
|
1101
|
+
try {
|
|
1102
|
+
return MeshRuntimeStore.getInstance().recordMeshToolCall(opts);
|
|
1103
|
+
} catch {
|
|
1104
|
+
return { rateLimitExceeded: false, callsInWindow: 0, advisory: null };
|
|
1105
|
+
}
|
|
1106
|
+
}
|