@mmerterden/multi-agent-pipeline 23.3.0 → 23.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +73 -0
- package/README.md +27 -8
- package/README.tr.md +28 -9
- package/SECURITY.md +16 -0
- package/docs/adr/0008-installer-modularization-and-secret-leak-defense.md +1 -1
- package/docs/adr/0010-own-code-graph.md +299 -8
- package/docs/architecture.md +3 -3
- package/docs/ecosystem.md +10 -10
- package/docs/engineering.md +4 -4
- package/docs/facts.json +8 -8
- package/docs/features.md +5 -5
- package/docs/performance.md +17 -17
- package/install/_dev-only-files.mjs +9 -0
- package/install/_platform-filter.mjs +2 -55
- package/install/claude.mjs +28 -2
- package/install/codex.mjs +1 -3
- package/install/copilot.mjs +4 -8
- package/install/templates/claude-hooks.json +32 -1
- package/manifest.json +236 -167
- package/package.json +11 -3
- package/pipeline/commands/multi-agent/SKILL.md +1 -1
- package/pipeline/commands/multi-agent/design-check/SKILL.md +3 -2
- package/pipeline/commands/multi-agent/diff-explain/SKILL.md +3 -3
- package/pipeline/commands/multi-agent/graph/SKILL.md +57 -24
- package/pipeline/commands/multi-agent/pair/SKILL.md +92 -0
- package/pipeline/commands/multi-agent/prune-prompts/SKILL.md +1 -1
- package/pipeline/commands/multi-agent/search/SKILL.md +7 -1
- package/pipeline/commands/multi-agent/status/SKILL.md +4 -0
- package/pipeline/commands/multi-agent/sync/SKILL.md +3 -3
- package/pipeline/contract/CHANGELOG.md +63 -0
- package/pipeline/contract/README.md +1 -0
- package/pipeline/contract/build.mjs +13 -1
- package/pipeline/contract/fixtures/error-invalid-request.json +1 -1
- package/pipeline/contract/fixtures/error-unauthorized.json +1 -1
- package/pipeline/contract/fixtures/runs-awaiting-question.json +4 -1
- package/pipeline/contract/fixtures/runs-empty.json +1 -1
- package/pipeline/contract/fixtures/runs-failed.json +4 -1
- package/pipeline/contract/fixtures/runs-old-schema.json +3 -0
- package/pipeline/contract/fixtures/runs-pr-opened-redacted.json +4 -1
- package/pipeline/contract/fixtures/runs-pr-opened.json +4 -1
- package/pipeline/contract/fixtures/runs-running.json +4 -1
- package/pipeline/contract/manifest.json +41 -15
- package/pipeline/contract/types/index.d.ts +81 -3
- package/pipeline/lib/detach-self.mjs +95 -0
- package/pipeline/lib/public-mcp-servers.mjs +33 -0
- package/pipeline/lib/rotated-log.mjs +93 -0
- package/pipeline/lib/stack-detect.sh +1 -1
- package/pipeline/lib/tls-trust.mjs +29 -0
- package/pipeline/lib/usage-lifecycle.mjs +9 -11
- package/pipeline/lib/usage-names.generated.mjs +613 -0
- package/pipeline/lib/usage-run-key.mjs +235 -0
- package/pipeline/lib/usage-vocab.mjs +210 -0
- package/pipeline/multi-agent-refs/analysis/intake.md +2 -2
- package/pipeline/multi-agent-refs/analysis/render.md +1 -1
- package/pipeline/multi-agent-refs/channels/generator.md +4 -5
- package/pipeline/multi-agent-refs/cross-cli-contract.md +3 -3
- package/pipeline/multi-agent-refs/design-check/init-inventory.md +11 -1
- package/pipeline/multi-agent-refs/design-check/scope-and-ledger.md +1 -1
- package/pipeline/multi-agent-refs/features/code-graph.md +146 -11
- package/pipeline/multi-agent-refs/features/code-intelligence.md +16 -14
- package/pipeline/multi-agent-refs/features/dev-critic.md +7 -7
- package/pipeline/multi-agent-refs/features/model-fallback.md +6 -4
- package/pipeline/multi-agent-refs/features/remote-control.md +253 -0
- package/pipeline/multi-agent-refs/features/review-delta.md +1 -1
- package/pipeline/multi-agent-refs/features/review-file-set.md +3 -3
- package/pipeline/multi-agent-refs/features/review-multi-repo.md +1 -1
- package/pipeline/multi-agent-refs/features/session-brief.md +42 -0
- package/pipeline/multi-agent-refs/features/skill-conformance.md +3 -3
- package/pipeline/multi-agent-refs/features/usage-reporting.md +255 -27
- package/pipeline/multi-agent-refs/help/en.md +3 -2
- package/pipeline/multi-agent-refs/help/tr.md +3 -2
- package/pipeline/multi-agent-refs/knowledge.md +1 -1
- package/pipeline/multi-agent-refs/orchestrator/dispatcher.md +2 -2
- package/pipeline/multi-agent-refs/phases/operations.md +2 -2
- package/pipeline/multi-agent-refs/phases/phase-0-init.md +13 -12
- package/pipeline/multi-agent-refs/phases/phase-1-plan.md +4 -4
- package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -0
- package/pipeline/multi-agent-refs/phases/phase-5-report.md +1 -1
- package/pipeline/multi-agent-refs/platform-parity.md +2 -2
- package/pipeline/multi-agent-refs/wiki-capture.md +3 -17
- package/pipeline/office/index.html +1309 -236
- package/pipeline/office/toolkit.json +1 -1
- package/pipeline/rules/outside-the-pipeline.md +1 -1
- package/pipeline/schemas/activity.schema.json +23 -0
- package/pipeline/schemas/agent-state.schema.json +6 -1
- package/pipeline/schemas/code-graph-calls.schema.json +254 -0
- package/pipeline/schemas/code-graph-docs.schema.json +223 -0
- package/pipeline/schemas/code-graph-infra.schema.json +227 -0
- package/pipeline/schemas/code-graph.schema.json +2 -2
- package/pipeline/schemas/examples/design-check-config.json +27 -0
- package/pipeline/schemas/learning-curve.schema.json +67 -0
- package/pipeline/schemas/mcp-health.schema.json +96 -0
- package/pipeline/schemas/office-jobs.json +69 -2
- package/pipeline/schemas/office-jobs.schema.json +8 -1
- package/pipeline/schemas/phases.json +5 -0
- package/pipeline/schemas/phases.schema.json +8 -0
- package/pipeline/schemas/prefs.schema.json +46 -12
- package/pipeline/schemas/runs-index.schema.json +17 -0
- package/pipeline/schemas/toolkit-path-params.json +78 -8
- package/pipeline/scripts/README.md +1 -0
- package/pipeline/scripts/_code-graph.mjs +184 -103
- package/pipeline/scripts/_contract-core.mjs +1 -1
- package/pipeline/scripts/_contract-routes-office.mjs +33 -0
- package/pipeline/scripts/_diff-impact.mjs +21 -2
- package/pipeline/scripts/_graph-sidecars.mjs +372 -0
- package/pipeline/scripts/_http-post.mjs +103 -115
- package/pipeline/scripts/_safe-read.mjs +57 -0
- package/pipeline/scripts/_skill-practices.mjs +26 -0
- package/pipeline/scripts/_strip-code.mjs +380 -0
- package/pipeline/scripts/activity-snapshot.mjs +13 -1
- package/pipeline/scripts/aggregate-metrics.mjs +3 -5
- package/pipeline/scripts/build-stack-plugins.mjs +1 -47
- package/pipeline/scripts/call-graph/index.mjs +78 -0
- package/pipeline/scripts/call-graph/lang/cpp.mjs +308 -0
- package/pipeline/scripts/call-graph/lang/csharp.mjs +130 -0
- package/pipeline/scripts/call-graph/lang/go.mjs +303 -0
- package/pipeline/scripts/call-graph/lang/java.mjs +370 -0
- package/pipeline/scripts/call-graph/lang/kotlin.mjs +397 -0
- package/pipeline/scripts/call-graph/lang/python.mjs +399 -0
- package/pipeline/scripts/call-graph/lang/rust.mjs +345 -0
- package/pipeline/scripts/call-graph/lang/shared.mjs +230 -0
- package/pipeline/scripts/call-graph/lang/swift.mjs +432 -0
- package/pipeline/scripts/call-graph/lang/typescript.mjs +692 -0
- package/pipeline/scripts/call-graph/lex.mjs +396 -0
- package/pipeline/scripts/call-graph/platform.mjs +86 -0
- package/pipeline/scripts/call-graph/profiles.mjs +89 -0
- package/pipeline/scripts/call-graph/resolve.mjs +1125 -0
- package/pipeline/scripts/call-graph/scan.mjs +267 -0
- package/pipeline/scripts/code-graph-rules/android.json +7 -2
- package/pipeline/scripts/code-graph-rules/cpp.json +99 -0
- package/pipeline/scripts/code-graph-rules/csharp.json +102 -0
- package/pipeline/scripts/code-graph-rules/go.json +2 -1
- package/pipeline/scripts/code-graph-rules/ios.json +3 -1
- package/pipeline/scripts/code-graph-rules/java.json +76 -0
- package/pipeline/scripts/code-graph-rules/node.json +7 -2
- package/pipeline/scripts/code-graph-rules/python.json +6 -2
- package/pipeline/scripts/code-graph-rules/rust.json +105 -0
- package/pipeline/scripts/contract-server.mjs +3 -0
- package/pipeline/scripts/design-check-config.mjs +205 -0
- package/pipeline/scripts/feedback-send.mjs +26 -26
- package/pipeline/scripts/gate-ledger.mjs +2 -1
- package/pipeline/scripts/gen-facts.mjs +1 -2
- package/pipeline/scripts/gen-usage-names.mjs +124 -0
- package/pipeline/scripts/graph-affected.mjs +109 -20
- package/pipeline/scripts/graph-build.mjs +95 -15
- package/pipeline/scripts/graph-export.mjs +272 -0
- package/pipeline/scripts/graph-hint.mjs +15 -2
- package/pipeline/scripts/graph-query.mjs +305 -26
- package/pipeline/scripts/graph-report.mjs +187 -1
- package/pipeline/scripts/health-report.mjs +3 -4
- package/pipeline/scripts/infra/docs.mjs +317 -0
- package/pipeline/scripts/infra/extract.mjs +998 -0
- package/pipeline/scripts/infra/graph.mjs +245 -0
- package/pipeline/scripts/infra/yaml-lite.mjs +311 -0
- package/pipeline/scripts/job-launch.mjs +67 -2
- package/pipeline/scripts/learning-curve.mjs +288 -178
- package/pipeline/scripts/log-metric.sh +10 -1
- package/pipeline/scripts/mcp-health.mjs +309 -0
- package/pipeline/scripts/note-agent-event.mjs +3 -4
- package/pipeline/scripts/note-command-use.mjs +333 -0
- package/pipeline/scripts/note-command-use.sh +126 -0
- package/pipeline/scripts/note-mcp-call.sh +89 -0
- package/pipeline/scripts/note-mcp-failure.mjs +272 -1
- package/pipeline/scripts/note-session.sh +62 -3
- package/pipeline/scripts/note-skill-use.mjs +58 -2
- package/pipeline/scripts/office-build.mjs +115 -1
- package/pipeline/scripts/office-memory.mjs +14 -5
- package/pipeline/scripts/pair.mjs +333 -0
- package/pipeline/scripts/pre-push-check.sh +1 -1
- package/pipeline/scripts/remote/cbor.mjs +128 -0
- package/pipeline/scripts/remote/contract.mjs +98 -0
- package/pipeline/scripts/remote/handler.mjs +330 -0
- package/pipeline/scripts/remote/handles.mjs +57 -0
- package/pipeline/scripts/remote/lifecycle.mjs +186 -0
- package/pipeline/scripts/remote/listener.mjs +204 -0
- package/pipeline/scripts/remote/lockout.mjs +103 -0
- package/pipeline/scripts/remote/nonces.mjs +61 -0
- package/pipeline/scripts/remote/pairing.mjs +519 -0
- package/pipeline/scripts/remote/qr-encode.mjs +459 -0
- package/pipeline/scripts/remote/store.mjs +191 -0
- package/pipeline/scripts/remote/transport.mjs +211 -0
- package/pipeline/scripts/remote/verbs.json +70 -0
- package/pipeline/scripts/remote/verbs.mjs +217 -0
- package/pipeline/scripts/remote/webauthn.mjs +169 -0
- package/pipeline/scripts/remote/wire.mjs +364 -0
- package/pipeline/scripts/remote-listener.mjs +83 -0
- package/pipeline/scripts/route-learn.mjs +4 -4
- package/pipeline/scripts/run-kill.mjs +1 -1
- package/pipeline/scripts/run-write.mjs +13 -2
- package/pipeline/scripts/runs-index.mjs +30 -3
- package/pipeline/scripts/search-logs.sh +9 -0
- package/pipeline/scripts/session-brief.mjs +458 -0
- package/pipeline/scripts/session-brief.sh +130 -0
- package/pipeline/scripts/skill-usage.mjs +16 -5
- package/pipeline/scripts/test-gap-rules/cpp.json +25 -0
- package/pipeline/scripts/test-gap-rules/csharp.json +20 -0
- package/pipeline/scripts/test-gap-rules/java.json +20 -0
- package/pipeline/scripts/test-gap-rules/rust.json +14 -0
- package/pipeline/scripts/token-budget-report.mjs +3 -2
- package/pipeline/scripts/uninstall.mjs +29 -0
- package/pipeline/scripts/usage-access.mjs +16 -31
- package/pipeline/scripts/usage-health.mjs +31 -62
- package/pipeline/scripts/usage-register-beacon.mjs +11 -22
- package/pipeline/scripts/usage-register.mjs +39 -29
- package/pipeline/scripts/usage-report.mjs +579 -178
- package/pipeline/scripts/validate-code-graph.mjs +361 -111
- package/pipeline/scripts/write-state.mjs +39 -0
- package/pipeline/skills/.skill-manifest.json +21 -17
- package/pipeline/skills/.skills-index.json +13 -2
- package/pipeline/skills/shared/README.md +5 -4
- package/pipeline/skills/shared/core/multi-agent-design-check/SKILL.md +1 -1
- package/pipeline/skills/shared/core/multi-agent-diff-explain/SKILL.md +3 -3
- package/pipeline/skills/shared/core/multi-agent-graph/SKILL.md +55 -21
- package/pipeline/skills/shared/core/multi-agent-pair/SKILL.md +41 -0
- package/pipeline/skills/shared/core/multi-agent-prune-prompts/SKILL.md +1 -1
- package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +3 -3
- package/pipeline/skills/shared/external/app-store-optimization/SKILL.md +2 -3
- package/pipeline/skills/shared/external/app-store-optimization/references/keyword-research-methodology.md +2 -2
- package/pipeline/skills/shared/external/app-store-optimization/references/product-page-variants.md +2 -2
- package/pipeline/skills/shared/external/app-store-review/SKILL.md +11 -4
- package/pipeline/skills/shared/external/build-settings-audit/SKILL.md +1 -1
- package/pipeline/skills/shared/external/build-time-benchmark/SKILL.md +5 -5
- package/pipeline/skills/shared/external/build-time-fixes/SKILL.md +5 -5
- package/pipeline/skills/shared/external/build-time-optimizer/SKILL.md +6 -6
- package/pipeline/skills/shared/external/free-llm-apis/references/providers.md +1 -0
- package/pipeline/skills/shared/external/ios-coding-standard/references/STANDARD.md +2 -2
- package/pipeline/skills/shared/external/ios-haptics/references/core-haptics.md +1 -1
- package/pipeline/skills/shared/external/localization-reuse-map/references/publish-and-snapshot.md +1 -1
- package/pipeline/skills/shared/external/package-build-audit/SKILL.md +3 -3
- package/pipeline/skills/shared/external/reverse-engineer-own-app/SKILL.md +2 -3
- package/pipeline/skills/shared/external/swift-compile-hotspots/SKILL.md +2 -2
- package/pipeline/skills/shared/external/weatherkit/SKILL.md +5 -6
- package/pipeline/skills/skills-index.md +3 -2
- package/docs/FIGMA_PIPELINE.md +0 -137
- package/pipeline/lib/identifier-scan.mjs +0 -156
- package/pipeline/scripts/_renamed-skills.mjs +0 -164
- package/pipeline/scripts/publish-staged.mjs +0 -324
- package/pipeline/skills/renamed.json +0 -30
- package/pipeline/skills/shared/external/ios-coding-standard/scripts/check_structure.py +0 -765
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* @file mcp-health.mjs - how the MCP servers a session uses are doing, per
|
|
4
|
+
* server and tool: calls, failures and when the last failure happened.
|
|
5
|
+
*
|
|
6
|
+
* Nothing here measures anything of its own. Two local files the hooks already
|
|
7
|
+
* write are read and never changed:
|
|
8
|
+
*
|
|
9
|
+
* mcp-failures.jsonl one row per failed call (note-mcp-failure.mjs): server,
|
|
10
|
+
* tool, time and a closed error class. Read with its
|
|
11
|
+
* previous generation.
|
|
12
|
+
* mcp-calls.json successful calls per host session, folded from
|
|
13
|
+
* mcp-calls.log the hook's own log; the lines no report has folded yet
|
|
14
|
+
* are counted as recent
|
|
15
|
+
*
|
|
16
|
+
* Only the last WINDOW_DAYS count. A counter session is counted whole when its
|
|
17
|
+
* last fold falls inside the window, including calls made before the window
|
|
18
|
+
* began; a failure row is counted by its own time. A call that failed is a call, so `calls` is
|
|
19
|
+
* the successful calls plus every failed one; `failures` leaves out the errors
|
|
20
|
+
* that say nothing about the server (invalid input, a refusal by the user or
|
|
21
|
+
* the permission layer, an interrupt), the same split `doctor` uses.
|
|
22
|
+
* `lastFailure` is the time of the last of those failures, to the minute.
|
|
23
|
+
* Successful calls are counted only while usage counting is on (the call
|
|
24
|
+
* counter's switches, note-mcp-failure.mjs callCountEnabled), failures always.
|
|
25
|
+
* With counting off the counter files are not read at all. `callsCounted` says which: false when counting is off or neither counter file
|
|
26
|
+
* exists, and then `calls` holds only the failed calls and is not a call count.
|
|
27
|
+
*
|
|
28
|
+
* Names follow the usage record's rule: a server is named only when it is on
|
|
29
|
+
* the shipped public list (lib/public-mcp-servers.mjs), any other server is the
|
|
30
|
+
* constant `private` with its tools folded into one `private` row, and a tool is
|
|
31
|
+
* named only when it is on the shipped tool list of this product's own server
|
|
32
|
+
* (the generated TOOLKIT_TOOLS), any other is `other`. Names, counts and
|
|
33
|
+
* minutes only: never arguments, results or error text.
|
|
34
|
+
*
|
|
35
|
+
* Files are read through rotated-log.mjs (a generation that is not a regular
|
|
36
|
+
* file is never read; a link or special file where a log or counter belongs is
|
|
37
|
+
* named in `skipped`, like one over the size cap) and the bounded regular-file reader (no link followed,
|
|
38
|
+
* at most READ_MAX bytes each). A file over the cap is left out and named in
|
|
39
|
+
* `skipped`; the rest still answers. Sizes of the answer are bounded too:
|
|
40
|
+
* MAX_SERVERS servers with MAX_TOOLS_PER_SERVER tools each, the rest folded
|
|
41
|
+
* into `other`.
|
|
42
|
+
*
|
|
43
|
+
* Local only: it describes which servers this machine has registered.
|
|
44
|
+
*
|
|
45
|
+
* Usage:
|
|
46
|
+
* mcp-health.mjs [--json]
|
|
47
|
+
*
|
|
48
|
+
* Exit: 0 printed, 2 usage.
|
|
49
|
+
*
|
|
50
|
+
* @module pipeline/scripts/mcp-health
|
|
51
|
+
*/
|
|
52
|
+
|
|
53
|
+
import { lstatSync } from "node:fs";
|
|
54
|
+
import { join } from "node:path";
|
|
55
|
+
|
|
56
|
+
import { exitOnHelp } from "../lib/cli-help.mjs";
|
|
57
|
+
import { invokedDirectly } from "../lib/invoked-directly.mjs";
|
|
58
|
+
import { MCP_SERVER_ID } from "../lib/mcp-rename.mjs";
|
|
59
|
+
import { isPublicMcpServer } from "../lib/public-mcp-servers.mjs";
|
|
60
|
+
import { readRegularFile } from "../lib/regular-file.mjs";
|
|
61
|
+
import { rotatedPaths } from "../lib/rotated-log.mjs";
|
|
62
|
+
import { TOOLKIT_TOOLS } from "../lib/usage-names.generated.mjs";
|
|
63
|
+
import {
|
|
64
|
+
CALLER_SIDE,
|
|
65
|
+
CALLS_FILE,
|
|
66
|
+
CALLS_LOG,
|
|
67
|
+
ERROR_CLASSES,
|
|
68
|
+
LOG_FILE,
|
|
69
|
+
callKeyOf,
|
|
70
|
+
callCountEnabled,
|
|
71
|
+
} from "./note-mcp-failure.mjs";
|
|
72
|
+
import { logDir } from "./note-skill-use.mjs";
|
|
73
|
+
|
|
74
|
+
exitOnHelp(import.meta.url);
|
|
75
|
+
|
|
76
|
+
export const CONTRACT_VERSION = "1.0.0";
|
|
77
|
+
export const WINDOW_DAYS = 7;
|
|
78
|
+
const MAX_SERVERS = 5;
|
|
79
|
+
export const MAX_TOOLS_PER_SERVER = 20;
|
|
80
|
+
const MAX_COUNT = 1_000_000;
|
|
81
|
+
const READ_MAX = 4 * 1024 * 1024;
|
|
82
|
+
const DAY_MS = 86_400_000;
|
|
83
|
+
const TOOL_PART = /^[A-Za-z0-9_]{1,64}$/;
|
|
84
|
+
const SESSION_ID = /^[A-Za-z0-9_-]{8,64}$/;
|
|
85
|
+
const TOOLKIT_TOOL_SET = new Set(TOOLKIT_TOOLS);
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The server and tool as the document names them, or null for a value that is
|
|
89
|
+
* not a string. A server off the public list is private whatever its name looks
|
|
90
|
+
* like, and a tool is named only from the shipped list, so no pattern decides
|
|
91
|
+
* whether a failure is counted.
|
|
92
|
+
*/
|
|
93
|
+
function label(server, tool) {
|
|
94
|
+
if (typeof server !== "string" || typeof tool !== "string") return null;
|
|
95
|
+
if (!isPublicMcpServer(server)) return { server: "private", tool: "private" };
|
|
96
|
+
const named = server === MCP_SERVER_ID && TOOL_PART.test(tool) && TOOLKIT_TOOL_SET.has(tool);
|
|
97
|
+
return { server, tool: named ? tool : "other" };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const minute = (ms) => `${new Date(ms).toISOString().slice(0, 16)}:00Z`;
|
|
101
|
+
|
|
102
|
+
/** The file's text, or null with `skip` set when it exists and cannot be read within the bounds. */
|
|
103
|
+
function readBounded(path, dir, skip) {
|
|
104
|
+
try {
|
|
105
|
+
return readRegularFile(path, { maxBytes: READ_MAX, within: [dir], noFollow: true });
|
|
106
|
+
} catch (e) {
|
|
107
|
+
if (/ENOENT/.test(e?.message ?? "")) return null;
|
|
108
|
+
skip();
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function failureRows(dir, skip) {
|
|
114
|
+
const out = [];
|
|
115
|
+
const file = join(dir, LOG_FILE);
|
|
116
|
+
const regular = new Set(rotatedPaths(file));
|
|
117
|
+
for (const path of [`${file}.1`, file]) {
|
|
118
|
+
if (regular.has(path)) continue;
|
|
119
|
+
try {
|
|
120
|
+
lstatSync(path);
|
|
121
|
+
skip();
|
|
122
|
+
} catch {
|
|
123
|
+
/* not there */
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
for (const path of regular) {
|
|
127
|
+
const text = readBounded(path, dir, skip);
|
|
128
|
+
for (const line of (text ?? "").split("\n")) {
|
|
129
|
+
if (!line.startsWith("{")) continue;
|
|
130
|
+
try {
|
|
131
|
+
const r = JSON.parse(line);
|
|
132
|
+
const named = label(r?.server, r?.tool);
|
|
133
|
+
const at = Date.parse(r?.ts);
|
|
134
|
+
if (named && Number.isFinite(at)) {
|
|
135
|
+
const cls = ERROR_CLASSES.includes(r.errorClass) ? r.errorClass : "other";
|
|
136
|
+
out.push({ ...named, at, serverSide: !CALLER_SIDE.has(cls) });
|
|
137
|
+
}
|
|
138
|
+
} catch {
|
|
139
|
+
/* a torn line */
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return out;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function callCounts(dir, since, now, skip) {
|
|
147
|
+
const out = [];
|
|
148
|
+
let seen = false;
|
|
149
|
+
const add = (key, n) => {
|
|
150
|
+
const at = key.indexOf(":");
|
|
151
|
+
const named = at > 0 ? label(key.slice(0, at), key.slice(at + 1)) : null;
|
|
152
|
+
if (named && Number.isInteger(n) && n > 0) out.push({ ...named, n: Math.min(n, MAX_COUNT) });
|
|
153
|
+
};
|
|
154
|
+
const counter = readBounded(join(dir, CALLS_FILE), dir, () => skip("calls"));
|
|
155
|
+
if (counter !== null) {
|
|
156
|
+
seen = true;
|
|
157
|
+
try {
|
|
158
|
+
const sessions = JSON.parse(counter)?.sessions;
|
|
159
|
+
for (const s of Object.values(sessions && typeof sessions === "object" ? sessions : {})) {
|
|
160
|
+
const t = Date.parse(s?.t);
|
|
161
|
+
if (!(t >= since && t <= now) || !s?.calls || typeof s.calls !== "object") continue;
|
|
162
|
+
for (const [key, n] of Object.entries(s.calls)) add(key, n);
|
|
163
|
+
}
|
|
164
|
+
} catch {
|
|
165
|
+
/* a damaged counter counts nothing */
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const pending = readBounded(join(dir, CALLS_LOG), dir, () => skip("calls"));
|
|
169
|
+
if (pending !== null) seen = true;
|
|
170
|
+
const tally = new Map();
|
|
171
|
+
for (const line of (pending ?? "").split("\n")) {
|
|
172
|
+
const [sid, name, extra] = line.split(" ");
|
|
173
|
+
if (extra !== undefined || !SESSION_ID.test(sid ?? "")) continue;
|
|
174
|
+
const key = callKeyOf(name);
|
|
175
|
+
if (key) tally.set(key, (tally.get(key) ?? 0) + 1);
|
|
176
|
+
}
|
|
177
|
+
for (const [key, n] of tally) add(key, n);
|
|
178
|
+
return { out, seen };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function fold(into, tool, patch) {
|
|
182
|
+
const t = into.get(tool) ?? { tool, calls: 0, failures: 0, last: 0 };
|
|
183
|
+
t.calls = Math.min(t.calls + (patch.calls ?? 0), MAX_COUNT);
|
|
184
|
+
t.failures = Math.min(t.failures + (patch.failures ?? 0), MAX_COUNT);
|
|
185
|
+
t.last = Math.max(t.last, patch.last ?? 0);
|
|
186
|
+
into.set(tool, t);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const shown = (t) => ({
|
|
190
|
+
tool: t.tool,
|
|
191
|
+
calls: t.calls,
|
|
192
|
+
failures: t.failures,
|
|
193
|
+
lastFailure: t.last ? minute(t.last) : null,
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
function limitTools(map) {
|
|
197
|
+
const ranked = [...map.values()].sort(
|
|
198
|
+
(a, b) => b.failures - a.failures || b.calls - a.calls || (a.tool < b.tool ? -1 : 1),
|
|
199
|
+
);
|
|
200
|
+
if (ranked.length <= MAX_TOOLS_PER_SERVER) return ranked;
|
|
201
|
+
const keep = ranked.filter((t) => t.tool !== "other").slice(0, MAX_TOOLS_PER_SERVER - 1);
|
|
202
|
+
const rest = new Map();
|
|
203
|
+
for (const t of ranked) {
|
|
204
|
+
if (!keep.includes(t)) fold(rest, "other", t);
|
|
205
|
+
}
|
|
206
|
+
return [...keep, ...rest.values()];
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* @param {{env?: NodeJS.ProcessEnv, now?: number}} [opts]
|
|
211
|
+
*/
|
|
212
|
+
export function mcpHealth({ env = process.env, now = Date.now() } = {}) {
|
|
213
|
+
const dir = logDir(env);
|
|
214
|
+
const since = now - WINDOW_DAYS * DAY_MS;
|
|
215
|
+
const skipped = new Set();
|
|
216
|
+
const failures = failureRows(dir, () => skipped.add("failures")).filter(
|
|
217
|
+
(r) => r.at >= since && r.at <= now,
|
|
218
|
+
);
|
|
219
|
+
const countingOn = callCountEnabled(env);
|
|
220
|
+
const { out: counted, seen } = countingOn
|
|
221
|
+
? callCounts(dir, since, now, (what) => skipped.add(what))
|
|
222
|
+
: { out: [], seen: false };
|
|
223
|
+
const callsCounted = countingOn && seen;
|
|
224
|
+
|
|
225
|
+
const servers = new Map();
|
|
226
|
+
const slot = (server) => {
|
|
227
|
+
if (!servers.has(server)) servers.set(server, new Map());
|
|
228
|
+
return servers.get(server);
|
|
229
|
+
};
|
|
230
|
+
for (const c of counted) fold(slot(c.server), c.tool, { calls: c.n });
|
|
231
|
+
for (const f of failures) {
|
|
232
|
+
fold(slot(f.server), f.tool, {
|
|
233
|
+
calls: 1,
|
|
234
|
+
failures: f.serverSide ? 1 : 0,
|
|
235
|
+
last: f.serverSide ? f.at : 0,
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const rows = [...servers].map(([server, tools]) => {
|
|
240
|
+
const list = limitTools(tools);
|
|
241
|
+
return {
|
|
242
|
+
server,
|
|
243
|
+
calls: list.reduce((n, t) => n + t.calls, 0),
|
|
244
|
+
failures: list.reduce((n, t) => n + t.failures, 0),
|
|
245
|
+
lastFailure: list.reduce((m, t) => Math.max(m, t.last), 0),
|
|
246
|
+
tools: list.map(shown),
|
|
247
|
+
};
|
|
248
|
+
});
|
|
249
|
+
rows.sort(
|
|
250
|
+
(a, b) => b.failures - a.failures || b.calls - a.calls || (a.server < b.server ? -1 : 1),
|
|
251
|
+
);
|
|
252
|
+
const top = rows.slice(0, MAX_SERVERS).map((s) => ({
|
|
253
|
+
...s,
|
|
254
|
+
lastFailure: s.lastFailure ? minute(s.lastFailure) : null,
|
|
255
|
+
}));
|
|
256
|
+
return {
|
|
257
|
+
contractVersion: CONTRACT_VERSION,
|
|
258
|
+
generatedAt: new Date(now).toISOString(),
|
|
259
|
+
ok: true,
|
|
260
|
+
windowDays: WINDOW_DAYS,
|
|
261
|
+
callsCounted,
|
|
262
|
+
servers: top,
|
|
263
|
+
totals: {
|
|
264
|
+
calls: top.reduce((n, s) => n + s.calls, 0),
|
|
265
|
+
failures: top.reduce((n, s) => n + s.failures, 0),
|
|
266
|
+
},
|
|
267
|
+
skipped: [...skipped].sort(),
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* A reader that reuses one answer for ttlMs, so a panel polling every few
|
|
273
|
+
* seconds reads the logs about once a minute.
|
|
274
|
+
* @param {{ttlMs?: number, now?: () => number, compute?: () => object}} [opts]
|
|
275
|
+
*/
|
|
276
|
+
export function createMcpHealthCache({
|
|
277
|
+
ttlMs = 60_000,
|
|
278
|
+
now = Date.now,
|
|
279
|
+
compute = () => mcpHealth(),
|
|
280
|
+
} = {}) {
|
|
281
|
+
let at = -Infinity;
|
|
282
|
+
let doc = null;
|
|
283
|
+
return () => {
|
|
284
|
+
const t = now();
|
|
285
|
+
if (doc === null || t - at >= ttlMs || t < at) {
|
|
286
|
+
doc = compute();
|
|
287
|
+
at = t;
|
|
288
|
+
}
|
|
289
|
+
return doc;
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
if (invokedDirectly(import.meta.url)) {
|
|
294
|
+
const args = process.argv.slice(2);
|
|
295
|
+
if (args.some((a) => a !== "--json")) {
|
|
296
|
+
console.error("usage: mcp-health.mjs [--json]");
|
|
297
|
+
process.exit(2);
|
|
298
|
+
}
|
|
299
|
+
const doc = mcpHealth();
|
|
300
|
+
process.stdout.write(
|
|
301
|
+
args.includes("--json")
|
|
302
|
+
? JSON.stringify(doc) + "\n"
|
|
303
|
+
: doc.servers.length
|
|
304
|
+
? doc.servers
|
|
305
|
+
.map((s) => `${s.server}: ${s.calls} calls, ${s.failures} failures`)
|
|
306
|
+
.join("\n") + "\n"
|
|
307
|
+
: `no MCP calls recorded in the last ${doc.windowDays} days\n`,
|
|
308
|
+
);
|
|
309
|
+
}
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
* @module pipeline/scripts/note-agent-event
|
|
26
26
|
*/
|
|
27
27
|
|
|
28
|
-
import {
|
|
28
|
+
import { readFileSync } from "node:fs";
|
|
29
29
|
import { homedir } from "node:os";
|
|
30
30
|
import { join } from "node:path";
|
|
31
31
|
|
|
@@ -36,6 +36,7 @@ import { memoryExcluded } from "./_memory-policy.mjs";
|
|
|
36
36
|
import { checkedSlug, repoName } from "../lib/slug.mjs";
|
|
37
37
|
import { openScanner, stripPrivate } from "./_secret-scan.mjs";
|
|
38
38
|
import { exitOnHelp } from "../lib/cli-help.mjs";
|
|
39
|
+
import { appendRowIn } from "./note-skill-use.mjs";
|
|
39
40
|
|
|
40
41
|
exitOnHelp(import.meta.url);
|
|
41
42
|
|
|
@@ -125,9 +126,7 @@ export function record(payload, env = process.env) {
|
|
|
125
126
|
scan.close();
|
|
126
127
|
}
|
|
127
128
|
const out = join(env.HOME || homedir(), ".claude", "memory", "multi-agent", slug);
|
|
128
|
-
|
|
129
|
-
appendFileSync(join(out, "session-notes.jsonl"), JSON.stringify(row) + "\n", "utf8");
|
|
130
|
-
return row;
|
|
129
|
+
return appendRowIn(out, "session-notes.jsonl", row, env) ? row : null;
|
|
131
130
|
}
|
|
132
131
|
|
|
133
132
|
function main() {
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* note-command-use.mjs - count which /multi-agent commands are typed.
|
|
4
|
+
*
|
|
5
|
+
* note-command-use.sh, a UserPromptSubmit hook, appends one line to
|
|
6
|
+
* `cmd-calls.log` for a prompt whose first token is `/multi-agent:<name>` (or
|
|
7
|
+
* `/multi-agent <name>` for a shipped name): the shipped command name, or the
|
|
8
|
+
* constant `other`. This module folds those lines into a per-command counter
|
|
9
|
+
* and hands the counts to the usage report as the `cmds` field.
|
|
10
|
+
*
|
|
11
|
+
* Nothing else about a prompt is read or stored: no arguments, no text, no
|
|
12
|
+
* length, no time. A name is kept only when it is on the shipped command list
|
|
13
|
+
* (lib/usage-names.generated.mjs); any other name counts as `other`.
|
|
14
|
+
*
|
|
15
|
+
* The counter, `cmd-counts.json`, holds `pending` (counts not yet offered) and
|
|
16
|
+
* `inflight` (the batch a sender claimed and has not acknowledged). Everything
|
|
17
|
+
* that changes it, the fold of the log included, runs under the file's lock, so
|
|
18
|
+
* concurrent reports take turns: a claim moves the pending counts into one
|
|
19
|
+
* batch with an id; while that batch is out, no other claim is handed it; an
|
|
20
|
+
* acknowledgement with the batch id clears it, a release makes it available
|
|
21
|
+
* again, and a batch nobody answered for CLAIM_TTL_MS is offered again, with
|
|
22
|
+
* the same id and the same counts. A count is therefore sent once per accepted
|
|
23
|
+
* send, kept when a send fails, and a resend can be told from a new batch.
|
|
24
|
+
*
|
|
25
|
+
* Counting has its own switches: it is on only while usageLog.enabled is true,
|
|
26
|
+
* usageLog.optOut is not, and the preferences parse. The hook is a shell
|
|
27
|
+
* script that cannot parse them, so it works from a marker file
|
|
28
|
+
* (`cmd-counting-on`) written here with a real parser, and stops the moment
|
|
29
|
+
* the preferences are newer than the marker. When counting is off the log and
|
|
30
|
+
* the counter are emptied.
|
|
31
|
+
*
|
|
32
|
+
* @module pipeline/scripts/note-command-use
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
import {
|
|
36
|
+
closeSync,
|
|
37
|
+
constants,
|
|
38
|
+
openSync,
|
|
39
|
+
readdirSync,
|
|
40
|
+
renameSync,
|
|
41
|
+
unlinkSync,
|
|
42
|
+
writeSync,
|
|
43
|
+
} from "node:fs";
|
|
44
|
+
import { randomBytes } from "node:crypto";
|
|
45
|
+
import { join } from "node:path";
|
|
46
|
+
|
|
47
|
+
import { lockTimeoutFrom, updateJsonFileSync } from "../lib/json-file-lock.mjs";
|
|
48
|
+
import { findPrefs, globalPref } from "../lib/prefs-value.mjs";
|
|
49
|
+
import { readRegularFile } from "../lib/regular-file.mjs";
|
|
50
|
+
import { mkdirSafe } from "../lib/safe-write.mjs";
|
|
51
|
+
import { SHIPPED_COMMANDS } from "../lib/usage-names.generated.mjs";
|
|
52
|
+
import { DEADLINE_MS, logDir } from "./note-skill-use.mjs";
|
|
53
|
+
import { exitOnHelp } from "../lib/cli-help.mjs";
|
|
54
|
+
|
|
55
|
+
exitOnHelp(import.meta.url);
|
|
56
|
+
|
|
57
|
+
export const COMMAND_LOG = "cmd-calls.log";
|
|
58
|
+
export const COMMAND_FILE = "cmd-counts.json";
|
|
59
|
+
export const COMMAND_SENTINEL = "cmd-counting-on";
|
|
60
|
+
export const MAX_CMDS = SHIPPED_COMMANDS.length + 1;
|
|
61
|
+
export const MAX_CMD_COUNT = 9999;
|
|
62
|
+
export const CLAIM_TTL_MS = 10 * 60 * 1000;
|
|
63
|
+
const STORE_MAX = 1_000_000;
|
|
64
|
+
const OTHER = "other";
|
|
65
|
+
const SHIPPED = new Set(SHIPPED_COMMANDS);
|
|
66
|
+
|
|
67
|
+
const plain = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {});
|
|
68
|
+
const lockOpts = (env) => ({
|
|
69
|
+
fallback: {},
|
|
70
|
+
mode: 0o600,
|
|
71
|
+
timeoutMs: Math.min(lockTimeoutFrom(env), DEADLINE_MS),
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
/** True while commands are counted: reporting on, not opted out, preferences readable. */
|
|
75
|
+
export function commandCountEnabled(env = process.env) {
|
|
76
|
+
const found = findPrefs(env);
|
|
77
|
+
if (found && found.status !== "ok") return false;
|
|
78
|
+
if (globalPref("usageLog.optOut", false, env) === true) return false;
|
|
79
|
+
return globalPref("usageLog.enabled", false, env) === true;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The counted name for a log line: a shipped name, `other` for any well-formed other name, else null. */
|
|
83
|
+
function nameOf(line) {
|
|
84
|
+
if (!/^[a-z0-9-]{1,40}$/.test(line)) return null;
|
|
85
|
+
return SHIPPED.has(line) ? line : OTHER;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function counterPath(env) {
|
|
89
|
+
return join(logDir(env), COMMAND_FILE);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Read and delete the log files into `into`, a plain name-to-count object. Runs under the counter lock. */
|
|
93
|
+
function drainLogs(env, into, enabled) {
|
|
94
|
+
const dir = logDir(env);
|
|
95
|
+
const log = join(dir, COMMAND_LOG);
|
|
96
|
+
const mine = `${log}.proc.${process.pid}`;
|
|
97
|
+
try {
|
|
98
|
+
renameSync(log, mine);
|
|
99
|
+
} catch {
|
|
100
|
+
/* no new lines */
|
|
101
|
+
}
|
|
102
|
+
let names;
|
|
103
|
+
try {
|
|
104
|
+
names = readdirSync(dir).filter((f) => f.startsWith(`${COMMAND_LOG}.proc.`));
|
|
105
|
+
} catch {
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
for (const f of names) {
|
|
109
|
+
const file = join(dir, f);
|
|
110
|
+
let text = "";
|
|
111
|
+
try {
|
|
112
|
+
if (enabled) text = readRegularFile(file, { maxBytes: 4 * 1024 * 1024, within: [dir] });
|
|
113
|
+
} catch {
|
|
114
|
+
/* unreadable: dropped with the file */
|
|
115
|
+
}
|
|
116
|
+
for (const line of text.split("\n")) {
|
|
117
|
+
const name = nameOf(line);
|
|
118
|
+
if (name) into[name] = Math.min((into[name] ?? 0) + 1, STORE_MAX);
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
unlinkSync(file);
|
|
122
|
+
} catch {
|
|
123
|
+
/* already gone */
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function hasLogs(env) {
|
|
129
|
+
try {
|
|
130
|
+
return readdirSync(logDir(env)).some(
|
|
131
|
+
(f) => f === COMMAND_LOG || f.startsWith(`${COMMAND_LOG}.proc.`),
|
|
132
|
+
);
|
|
133
|
+
} catch {
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const merge = (a, b) => {
|
|
139
|
+
const out = { ...a };
|
|
140
|
+
for (const [k, v] of Object.entries(b)) out[k] = Math.min((out[k] ?? 0) + v, STORE_MAX);
|
|
141
|
+
return out;
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
const counts = (obj) =>
|
|
145
|
+
Object.entries(plain(obj))
|
|
146
|
+
.filter(([n, k]) => (n === OTHER || SHIPPED.has(n)) && Number.isInteger(k) && k > 0)
|
|
147
|
+
.sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
|
|
148
|
+
.slice(0, MAX_CMDS)
|
|
149
|
+
.map(([n, k]) => ({ n, k: Math.min(k, MAX_CMD_COUNT) }));
|
|
150
|
+
|
|
151
|
+
function normalize(current) {
|
|
152
|
+
const inflight = plain(current?.inflight);
|
|
153
|
+
const hasBatch = typeof inflight.id === "string" && Object.keys(plain(inflight.counts)).length;
|
|
154
|
+
return {
|
|
155
|
+
pending: { ...plain(current?.pending) },
|
|
156
|
+
inflight: hasBatch
|
|
157
|
+
? { id: inflight.id, at: Number(inflight.at) || 0, counts: { ...plain(inflight.counts) } }
|
|
158
|
+
: null,
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Run `change(state, enabled)` on the counter under its lock, after folding the log into `pending`. */
|
|
163
|
+
function withCounter(env, change) {
|
|
164
|
+
let result = null;
|
|
165
|
+
try {
|
|
166
|
+
const enabled = commandCountEnabled(env);
|
|
167
|
+
if (hasLogs(env) || enabled) mkdirSafe(logDir(env), { mode: 0o700, env });
|
|
168
|
+
updateJsonFileSync(
|
|
169
|
+
counterPath(env),
|
|
170
|
+
(current) => {
|
|
171
|
+
const state = normalize(current);
|
|
172
|
+
drainLogs(env, state.pending, enabled);
|
|
173
|
+
const out = change(state);
|
|
174
|
+
result = out.result;
|
|
175
|
+
return { v: 1, pending: state.pending, inflight: state.inflight, ...out.patch };
|
|
176
|
+
},
|
|
177
|
+
lockOpts(env),
|
|
178
|
+
);
|
|
179
|
+
} catch {
|
|
180
|
+
/* the counter is bookkeeping */
|
|
181
|
+
}
|
|
182
|
+
return result;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** What a send would carry now, without taking it: the pending counts and any batch in flight. */
|
|
186
|
+
export function peekCommands(env = process.env) {
|
|
187
|
+
if (!commandCountEnabled(env)) return [];
|
|
188
|
+
const out = withCounter(env, (state) => ({
|
|
189
|
+
result: counts(merge(state.pending, state.inflight?.counts ?? {})),
|
|
190
|
+
patch: {},
|
|
191
|
+
}));
|
|
192
|
+
return out ?? [];
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Split counts into the part one batch may carry (each count at most
|
|
197
|
+
* MAX_CMD_COUNT) and the rest, which stays for a later batch.
|
|
198
|
+
*/
|
|
199
|
+
function capped(all) {
|
|
200
|
+
const batch = {};
|
|
201
|
+
const rest = {};
|
|
202
|
+
for (const [n, k] of Object.entries(all)) {
|
|
203
|
+
batch[n] = Math.min(k, MAX_CMD_COUNT);
|
|
204
|
+
if (k > MAX_CMD_COUNT) rest[n] = k - MAX_CMD_COUNT;
|
|
205
|
+
}
|
|
206
|
+
return { batch, rest };
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Take the counts for one send. Returns { id, cmds }; `cmds` is empty and `id`
|
|
211
|
+
* null when counting is off, nothing is pending, or another sender's batch is
|
|
212
|
+
* in flight.
|
|
213
|
+
*
|
|
214
|
+
* `id` is the batch id sent to the server as `cb`: 16 lowercase hex characters
|
|
215
|
+
* from crypto.randomBytes, made when the pending counts become a batch. A batch
|
|
216
|
+
* that was released or never answered is handed out again unchanged, with its
|
|
217
|
+
* id and its counts, so the server can recognise the resend; whatever was typed
|
|
218
|
+
* since waits in `pending` for the next batch. No count in a batch is above
|
|
219
|
+
* MAX_CMD_COUNT; the remainder stays pending.
|
|
220
|
+
*/
|
|
221
|
+
export function claimCommands(env = process.env, now = Date.now()) {
|
|
222
|
+
const none = { id: null, cmds: [] };
|
|
223
|
+
if (!commandCountEnabled(env)) return none;
|
|
224
|
+
const out = withCounter(env, (state) => {
|
|
225
|
+
if (state.inflight) {
|
|
226
|
+
if (now - state.inflight.at < CLAIM_TTL_MS && state.inflight.at > 0) {
|
|
227
|
+
return { result: none, patch: {} };
|
|
228
|
+
}
|
|
229
|
+
const { batch, rest } = capped(state.inflight.counts);
|
|
230
|
+
const cmds = counts(batch);
|
|
231
|
+
if (cmds.length) {
|
|
232
|
+
return {
|
|
233
|
+
result: { id: state.inflight.id, cmds },
|
|
234
|
+
patch: {
|
|
235
|
+
pending: merge(state.pending, rest),
|
|
236
|
+
inflight: { id: state.inflight.id, at: now, counts: batch },
|
|
237
|
+
},
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
const { batch, rest } = capped(state.pending);
|
|
242
|
+
const cmds = counts(batch);
|
|
243
|
+
if (!cmds.length) return { result: none, patch: { pending: {}, inflight: null } };
|
|
244
|
+
const id = randomBytes(8).toString("hex");
|
|
245
|
+
return {
|
|
246
|
+
result: { id, cmds },
|
|
247
|
+
patch: { pending: rest, inflight: { id, at: now, counts: batch } },
|
|
248
|
+
};
|
|
249
|
+
});
|
|
250
|
+
return out ?? none;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** The batch `id` was accepted: forget it. Another claim's batch is left alone. */
|
|
254
|
+
export function ackCommands(id, env = process.env) {
|
|
255
|
+
if (typeof id !== "string") return;
|
|
256
|
+
withCounter(env, (state) => ({
|
|
257
|
+
result: null,
|
|
258
|
+
patch: { inflight: state.inflight?.id === id ? null : state.inflight },
|
|
259
|
+
}));
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** The send of batch `id` failed: make it available to the next claim at once. */
|
|
263
|
+
export function releaseCommands(id, env = process.env) {
|
|
264
|
+
if (typeof id !== "string") return;
|
|
265
|
+
withCounter(env, (state) => ({
|
|
266
|
+
result: null,
|
|
267
|
+
patch: {
|
|
268
|
+
inflight: state.inflight?.id === id ? { ...state.inflight, at: 0 } : state.inflight,
|
|
269
|
+
},
|
|
270
|
+
}));
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Forget every count: the hook's log, any leftover, the pending counts and the batch in flight. Never throws. */
|
|
274
|
+
export function discardCommands(env = process.env) {
|
|
275
|
+
try {
|
|
276
|
+
const dir = logDir(env);
|
|
277
|
+
const names = readdirSync(dir);
|
|
278
|
+
for (const f of names) {
|
|
279
|
+
if (f === COMMAND_LOG || f.startsWith(`${COMMAND_LOG}.proc.`)) {
|
|
280
|
+
try {
|
|
281
|
+
unlinkSync(join(dir, f));
|
|
282
|
+
} catch {
|
|
283
|
+
/* already gone */
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
if (names.includes(COMMAND_FILE)) {
|
|
288
|
+
updateJsonFileSync(
|
|
289
|
+
counterPath(env),
|
|
290
|
+
() => ({ v: 1, pending: {}, inflight: null }),
|
|
291
|
+
lockOpts(env),
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
} catch {
|
|
295
|
+
/* nothing counted, nothing to forget */
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Write the marker the hook tests (and renew its time), or remove it and
|
|
301
|
+
* discard the counts when counting is off. Never throws.
|
|
302
|
+
*
|
|
303
|
+
* @returns {boolean} whether counting is on
|
|
304
|
+
*/
|
|
305
|
+
export function syncCommandSentinel(env = process.env) {
|
|
306
|
+
try {
|
|
307
|
+
const dir = logDir(env);
|
|
308
|
+
const file = join(dir, COMMAND_SENTINEL);
|
|
309
|
+
if (!commandCountEnabled(env)) {
|
|
310
|
+
try {
|
|
311
|
+
unlinkSync(file);
|
|
312
|
+
} catch {
|
|
313
|
+
/* not there */
|
|
314
|
+
}
|
|
315
|
+
discardCommands(env);
|
|
316
|
+
return false;
|
|
317
|
+
}
|
|
318
|
+
mkdirSafe(dir, { mode: 0o700, env });
|
|
319
|
+
const fd = openSync(
|
|
320
|
+
file,
|
|
321
|
+
constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW,
|
|
322
|
+
0o600,
|
|
323
|
+
);
|
|
324
|
+
try {
|
|
325
|
+
writeSync(fd, "on\n");
|
|
326
|
+
} finally {
|
|
327
|
+
closeSync(fd);
|
|
328
|
+
}
|
|
329
|
+
return true;
|
|
330
|
+
} catch {
|
|
331
|
+
return false;
|
|
332
|
+
}
|
|
333
|
+
}
|