@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,126 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# note-command-use.sh - UserPromptSubmit hook: count which /multi-agent
|
|
3
|
+
# commands are typed, by name only.
|
|
4
|
+
#
|
|
5
|
+
# A prompt counts when its first token is `/multi-agent:<name>`, or when it is
|
|
6
|
+
# `/multi-agent <name>` and <name> is a shipped command. <name> is looked up in
|
|
7
|
+
# the shipped command list (lib/usage-names.generated.mjs, SHIPPED_COMMANDS);
|
|
8
|
+
# the line appended to <log root>/cmd-calls.log is that shipped name, or the
|
|
9
|
+
# constant `other` for a colon-form name that is not on the list. Nothing else
|
|
10
|
+
# of the prompt is read past its first two tokens, and nothing else is stored:
|
|
11
|
+
# no arguments, no text, no length, no time. The log is folded into
|
|
12
|
+
# cmd-counts.json under a lock by note-command-use.mjs when a report is built.
|
|
13
|
+
#
|
|
14
|
+
# It starts no node process and parses no JSON beyond a depth-aware scan of the
|
|
15
|
+
# first 8 KiB of the payload for the top-level `hook_event_name` and `prompt`
|
|
16
|
+
# keys (a `prompt` inside any nested object is never read; the depth is kept
|
|
17
|
+
# across the lines of a payload that is not on one line). Off, with nothing
|
|
18
|
+
# read or written, unless the marker file <log root>/cmd-counting-on exists, is
|
|
19
|
+
# not a symlink, and is not older than the preferences file; the marker is
|
|
20
|
+
# written with a real parser by note-command-use.mjs (syncCommandSentinel) only
|
|
21
|
+
# while usageLog.enabled is true and usageLog.optOut is not, and removed
|
|
22
|
+
# otherwise. One short append is atomic, so concurrent prompts need no lock; the
|
|
23
|
+
# fold takes the counter lock.
|
|
24
|
+
#
|
|
25
|
+
# Never blocks the prompt: no output, exit 0 on every path. The log stops
|
|
26
|
+
# growing at 1 MiB until the next report folds it.
|
|
27
|
+
|
|
28
|
+
set -u
|
|
29
|
+
|
|
30
|
+
PREFS="${MULTI_AGENT_PREFS:-$HOME/.claude/multi-agent-preferences.json}"
|
|
31
|
+
DIR="${LOGS_ROOT:-$HOME/.claude/logs/multi-agent}"
|
|
32
|
+
MARKER="$DIR/cmd-counting-on"
|
|
33
|
+
[ -f "$MARKER" ] || exit 0
|
|
34
|
+
[ -L "$MARKER" ] && exit 0
|
|
35
|
+
[ -f "$PREFS" ] || exit 0
|
|
36
|
+
[ "$PREFS" -nt "$MARKER" ] && exit 0
|
|
37
|
+
|
|
38
|
+
HERE="$(cd "$(dirname "$0")" 2>/dev/null && pwd)" || exit 0
|
|
39
|
+
LIST="$HERE/../lib/usage-names.generated.mjs"
|
|
40
|
+
[ -f "$LIST" ] || exit 0
|
|
41
|
+
|
|
42
|
+
HEAD="$(head -c 8192 2>/dev/null)" || exit 0
|
|
43
|
+
|
|
44
|
+
TOKENS="$(printf '%s' "$HEAD" | awk '
|
|
45
|
+
BEGIN { d = 0; st = 0 }
|
|
46
|
+
{
|
|
47
|
+
s = $0; n = length(s); i = 1
|
|
48
|
+
while (i <= n) {
|
|
49
|
+
c = substr(s, i, 1)
|
|
50
|
+
if (c == "\"") {
|
|
51
|
+
j = i + 1; str = ""
|
|
52
|
+
while (j <= n) {
|
|
53
|
+
ch = substr(s, j, 1)
|
|
54
|
+
if (ch == "\\") { str = str substr(s, j, 2); j += 2; continue }
|
|
55
|
+
if (ch == "\"") break
|
|
56
|
+
str = str ch; j++
|
|
57
|
+
}
|
|
58
|
+
if (d == 1) {
|
|
59
|
+
if (st == 0) { key = str; st = 1 }
|
|
60
|
+
else if (st == 2) {
|
|
61
|
+
if (key == "hook_event_name") event = str
|
|
62
|
+
else if (key == "prompt" && !seen) {
|
|
63
|
+
seen = 1
|
|
64
|
+
first = str; rest = ""
|
|
65
|
+
if (match(str, /[ \\]/)) {
|
|
66
|
+
first = substr(str, 1, RSTART - 1)
|
|
67
|
+
if (substr(str, RSTART, 1) == " ") rest = substr(str, RSTART + 1)
|
|
68
|
+
}
|
|
69
|
+
second = rest
|
|
70
|
+
if (match(rest, /[ \\]/)) second = substr(rest, 1, RSTART - 1)
|
|
71
|
+
}
|
|
72
|
+
st = 3
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
i = j + 1; continue
|
|
76
|
+
}
|
|
77
|
+
if (c == ":" && d == 1) st = 2
|
|
78
|
+
else if (c == "," && d == 1) st = 0
|
|
79
|
+
else if (c == "{" || c == "[") d++
|
|
80
|
+
else if (c == "}" || c == "]") d--
|
|
81
|
+
i++
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
END { print event; print first; print second }')" || exit 0
|
|
85
|
+
|
|
86
|
+
{
|
|
87
|
+
IFS= read -r EVENT
|
|
88
|
+
IFS= read -r FIRST
|
|
89
|
+
IFS= read -r SECOND
|
|
90
|
+
} <<EOF
|
|
91
|
+
$TOKENS
|
|
92
|
+
EOF
|
|
93
|
+
|
|
94
|
+
[ "$EVENT" = "UserPromptSubmit" ] || exit 0
|
|
95
|
+
|
|
96
|
+
NAME="" COLON=0
|
|
97
|
+
case "$FIRST" in
|
|
98
|
+
/multi-agent:*) NAME="${FIRST#/multi-agent:}"; COLON=1 ;;
|
|
99
|
+
/multi-agent) NAME="$SECOND" ;;
|
|
100
|
+
*) exit 0 ;;
|
|
101
|
+
esac
|
|
102
|
+
printf '%s' "$NAME" | grep -Eq '^[a-z0-9-]{1,40}$' || exit 0
|
|
103
|
+
|
|
104
|
+
SHIPPED="$(awk -v n="$NAME" '
|
|
105
|
+
/SHIPPED_COMMANDS = / { on = 1; next }
|
|
106
|
+
on && /^\]\)/ { exit }
|
|
107
|
+
on { gsub(/^[ \t]*"|",?[ \t]*$/, ""); if ($0 == n) { print "yes"; exit } }
|
|
108
|
+
' "$LIST" 2>/dev/null)"
|
|
109
|
+
|
|
110
|
+
if [ "$SHIPPED" = "yes" ]; then
|
|
111
|
+
COUNTED="$NAME"
|
|
112
|
+
elif [ "$COLON" = "1" ]; then
|
|
113
|
+
COUNTED="other"
|
|
114
|
+
else
|
|
115
|
+
exit 0
|
|
116
|
+
fi
|
|
117
|
+
|
|
118
|
+
LOG="$DIR/cmd-calls.log"
|
|
119
|
+
( umask 077; mkdir -p "$DIR" ) 2>/dev/null || exit 0
|
|
120
|
+
[ -L "$LOG" ] && exit 0
|
|
121
|
+
if [ -f "$LOG" ]; then
|
|
122
|
+
SIZE="$(wc -c < "$LOG" 2>/dev/null | tr -d ' ')"
|
|
123
|
+
[ "${SIZE:-0}" -ge 1048576 ] 2>/dev/null && exit 0
|
|
124
|
+
fi
|
|
125
|
+
( umask 077; printf '%s\n' "$COUNTED" >> "$LOG" ) 2>/dev/null
|
|
126
|
+
exit 0
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# note-mcp-call.sh - PostToolUse hook on MCP tools (mcp__.*), registered async.
|
|
3
|
+
#
|
|
4
|
+
# Counts a successful MCP call for the usage record's `tools` field by appending
|
|
5
|
+
# one short line, `<session id> <tool name>`, to <log root>/mcp-calls.log. It
|
|
6
|
+
# starts no node process and parses no JSON: it reads the first 8 KiB of the
|
|
7
|
+
# payload (the host writes session_id, hook_event_name and tool_name before the
|
|
8
|
+
# tool's input and response, so a large tool_response is never read), takes the
|
|
9
|
+
# first occurrence of each of the three keys, and appends. The report folds the
|
|
10
|
+
# log into per-session counts (note-mcp-failure.mjs foldCalls).
|
|
11
|
+
#
|
|
12
|
+
# Off, with nothing read or written, unless the marker file
|
|
13
|
+
# <log root>/mcp-counting-on exists and the preferences file is not newer than
|
|
14
|
+
# it. A shell script cannot parse the preferences reliably, so it never tries:
|
|
15
|
+
# the marker is written (and its time renewed) by note-mcp-failure.mjs
|
|
16
|
+
# syncCountingSentinel with a real parser, only while usageLog.enabled is true
|
|
17
|
+
# and neither usageLog.optOut nor mcpFailures.enabled false is set, and removed
|
|
18
|
+
# otherwise. Any change to the preferences makes the marker older than them, so
|
|
19
|
+
# an edit that opts out stops the hook at once, and counting resumes when the
|
|
20
|
+
# next report or failure hook renews the marker.
|
|
21
|
+
#
|
|
22
|
+
# The log stops growing at 2 MiB until the next report folds it. Exits 0 on every
|
|
23
|
+
# path with no output: bookkeeping never holds a tool call.
|
|
24
|
+
|
|
25
|
+
set -u
|
|
26
|
+
|
|
27
|
+
PREFS="${MULTI_AGENT_PREFS:-$HOME/.claude/multi-agent-preferences.json}"
|
|
28
|
+
DIR="${LOGS_ROOT:-$HOME/.claude/logs/multi-agent}"
|
|
29
|
+
MARKER="$DIR/mcp-counting-on"
|
|
30
|
+
[ -f "$MARKER" ] || exit 0
|
|
31
|
+
[ -L "$MARKER" ] && exit 0
|
|
32
|
+
[ -f "$PREFS" ] || exit 0
|
|
33
|
+
[ "$PREFS" -nt "$MARKER" ] && exit 0
|
|
34
|
+
|
|
35
|
+
HEAD="$(head -c 8192 2>/dev/null)" || exit 0
|
|
36
|
+
SID="" EVENT="" TOOL=""
|
|
37
|
+
while IFS='=' read -r key value; do
|
|
38
|
+
case "$key" in
|
|
39
|
+
session_id) SID="$value" ;;
|
|
40
|
+
hook_event_name) EVENT="$value" ;;
|
|
41
|
+
tool_name) TOOL="$value" ;;
|
|
42
|
+
esac
|
|
43
|
+
done <<EOF
|
|
44
|
+
$(printf '%s' "$HEAD" | awk '
|
|
45
|
+
{
|
|
46
|
+
s = $0; n = length(s); d = 0; st = 0; i = 1
|
|
47
|
+
while (i <= n) {
|
|
48
|
+
c = substr(s, i, 1)
|
|
49
|
+
if (c == "\"") {
|
|
50
|
+
j = i + 1; str = ""
|
|
51
|
+
while (j <= n) {
|
|
52
|
+
ch = substr(s, j, 1)
|
|
53
|
+
if (ch == "\\") { str = str substr(s, j, 2); j += 2; continue }
|
|
54
|
+
if (ch == "\"") break
|
|
55
|
+
str = str ch; j++
|
|
56
|
+
}
|
|
57
|
+
if (d == 1) {
|
|
58
|
+
if (st == 0) { key = str; st = 1 }
|
|
59
|
+
else if (st == 2) {
|
|
60
|
+
if ((key == "session_id" || key == "hook_event_name" || key == "tool_name") && !(key in seen)) {
|
|
61
|
+
seen[key] = 1; print key "=" str
|
|
62
|
+
}
|
|
63
|
+
st = 3
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
i = j + 1; continue
|
|
67
|
+
}
|
|
68
|
+
if (c == ":" && d == 1) st = 2
|
|
69
|
+
else if (c == "," && d == 1) st = 0
|
|
70
|
+
else if (c == "{" || c == "[") d++
|
|
71
|
+
else if (c == "}" || c == "]") d--
|
|
72
|
+
i++
|
|
73
|
+
}
|
|
74
|
+
}')
|
|
75
|
+
EOF
|
|
76
|
+
|
|
77
|
+
[ "$EVENT" = "PostToolUse" ] || exit 0
|
|
78
|
+
printf '%s' "$SID" | grep -Eq '^[A-Za-z0-9_-]{8,64}$' || exit 0
|
|
79
|
+
printf '%s' "$TOOL" | grep -Eq '^mcp__[A-Za-z0-9_-]{1,100}$' || exit 0
|
|
80
|
+
|
|
81
|
+
LOG="$DIR/mcp-calls.log"
|
|
82
|
+
( umask 077; mkdir -p "$DIR" ) 2>/dev/null || exit 0
|
|
83
|
+
[ -L "$LOG" ] && exit 0
|
|
84
|
+
if [ -f "$LOG" ]; then
|
|
85
|
+
SIZE="$(wc -c < "$LOG" 2>/dev/null | tr -d ' ')"
|
|
86
|
+
[ "${SIZE:-0}" -ge 2097152 ] 2>/dev/null && exit 0
|
|
87
|
+
fi
|
|
88
|
+
( umask 077; printf '%s %s\n' "$SID" "$TOOL" >> "$LOG" ) 2>/dev/null
|
|
89
|
+
exit 0
|
|
@@ -16,7 +16,14 @@
|
|
|
16
16
|
* "validation", then an HTTP status, then fixed wording
|
|
17
17
|
* patterns; the text itself is never stored
|
|
18
18
|
*
|
|
19
|
-
*
|
|
19
|
+
* Successful calls are counted by note-mcp-call.sh, a shell hook that appends one
|
|
20
|
+
* short line (`<session id> <tool name>`) to <log dir>/mcp-calls.log and starts no
|
|
21
|
+
* node process. This module folds that log into <log dir>/mcp-calls.json at
|
|
22
|
+
* report time (foldCalls): `<server>:<tool>` (lowercase, a name that fits
|
|
23
|
+
* CALL_KEY) and a count per host session, owner-only. Nothing else about a call is
|
|
24
|
+
* read or kept.
|
|
25
|
+
*
|
|
26
|
+
A name part outside NAME_PART (a strict charset and length) or carrying a
|
|
20
27
|
* credential pattern drops the whole call. The tool's arguments, its output
|
|
21
28
|
* and the error text are never written. No server is probed: the counter
|
|
22
29
|
* only sees the calls the session already made.
|
|
@@ -44,6 +51,15 @@
|
|
|
44
51
|
* @module pipeline/scripts/note-mcp-failure
|
|
45
52
|
*/
|
|
46
53
|
|
|
54
|
+
import {
|
|
55
|
+
closeSync,
|
|
56
|
+
constants,
|
|
57
|
+
openSync,
|
|
58
|
+
readdirSync,
|
|
59
|
+
renameSync,
|
|
60
|
+
unlinkSync,
|
|
61
|
+
writeSync,
|
|
62
|
+
} from "node:fs";
|
|
47
63
|
import { join } from "node:path";
|
|
48
64
|
|
|
49
65
|
import { parseArgs } from "../lib/args.mjs";
|
|
@@ -51,14 +67,23 @@ import { exitOnHelp } from "../lib/cli-help.mjs";
|
|
|
51
67
|
import { installFatalHandlers } from "../lib/fatal.mjs";
|
|
52
68
|
import { claimHookEvent } from "../lib/hook-once.mjs";
|
|
53
69
|
import { invokedDirectly } from "../lib/invoked-directly.mjs";
|
|
70
|
+
import { lockTimeoutFrom, updateJsonFileSync } from "../lib/json-file-lock.mjs";
|
|
54
71
|
import { findPrefs, globalPref } from "../lib/prefs-value.mjs";
|
|
55
72
|
import { redact } from "../lib/redact.mjs";
|
|
56
73
|
import { readRegularFile } from "../lib/regular-file.mjs";
|
|
74
|
+
import { mkdirSafe } from "../lib/safe-write.mjs";
|
|
57
75
|
import { DEADLINE_MS, MAX_LOG_BYTES, appendLogRow, logDir } from "./note-skill-use.mjs";
|
|
76
|
+
import { syncCommandSentinel } from "./note-command-use.mjs";
|
|
58
77
|
|
|
59
78
|
exitOnHelp(import.meta.url);
|
|
60
79
|
|
|
61
80
|
export const LOG_FILE = "mcp-failures.jsonl";
|
|
81
|
+
export const CALLS_FILE = "mcp-calls.json";
|
|
82
|
+
export const CALLS_LOG = "mcp-calls.log";
|
|
83
|
+
export const CALLS_MAX_NAMES = 200;
|
|
84
|
+
export const CALLS_MAX_COUNT = 1_000_000;
|
|
85
|
+
const CALL_KEY = /^[A-Za-z0-9_-]{1,40}:[a-z0-9_]{1,64}$/;
|
|
86
|
+
export const COUNTING_SENTINEL = "mcp-counting-on";
|
|
62
87
|
export const ROW_VERSION = "1.0.0";
|
|
63
88
|
export const WINDOW_HOURS = 24;
|
|
64
89
|
export const REPEAT_AT = 5;
|
|
@@ -218,6 +243,251 @@ export function record(payload, env = process.env) {
|
|
|
218
243
|
return appendLogRow(LOG_FILE, row, env) ? row : null;
|
|
219
244
|
}
|
|
220
245
|
|
|
246
|
+
/** Where the success counter lives: the same log directory the failure log uses. */
|
|
247
|
+
export const mcpCallsPath = (env = process.env) => join(logDir(env), CALLS_FILE);
|
|
248
|
+
|
|
249
|
+
const SESSION_ID = /^[A-Za-z0-9_-]{8,64}$/;
|
|
250
|
+
export const CALLS_MAX_SESSIONS = 20;
|
|
251
|
+
|
|
252
|
+
const plain = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {});
|
|
253
|
+
|
|
254
|
+
function newestFirst(map, keep) {
|
|
255
|
+
return Object.fromEntries(
|
|
256
|
+
Object.entries(map)
|
|
257
|
+
.sort((a, b) => (Date.parse(b[1]?.t) || 0) - (Date.parse(a[1]?.t) || 0))
|
|
258
|
+
.slice(0, keep),
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** The counter document, tolerant of a missing, damaged or older file. */
|
|
263
|
+
export function readCalls(env = process.env) {
|
|
264
|
+
let doc = null;
|
|
265
|
+
try {
|
|
266
|
+
doc = JSON.parse(readRegularFile(mcpCallsPath(env), { maxBytes: 4 * 1024 * 1024 }));
|
|
267
|
+
} catch {
|
|
268
|
+
/* missing or damaged: nothing counted yet */
|
|
269
|
+
}
|
|
270
|
+
return { v: 2, sessions: plain(doc?.sessions), bases: plain(doc?.bases) };
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* The counter turned into a run's own numbers: the host session's total minus
|
|
275
|
+
* what the session had counted when the run was first reported. The base is
|
|
276
|
+
* written the first time a run is seen (`establish`), so an earlier run in the
|
|
277
|
+
* same session is not counted again. Only the 20 newest sessions and runs are
|
|
278
|
+
* kept.
|
|
279
|
+
*
|
|
280
|
+
* @returns {Record<string, number>} `<server>:<tool>` to calls for this run
|
|
281
|
+
*/
|
|
282
|
+
export function runCalls({ runId, sessionId, env = process.env, establish = false }) {
|
|
283
|
+
if (!runId || !SESSION_ID.test(String(sessionId ?? ""))) return {};
|
|
284
|
+
const delta = (doc) => {
|
|
285
|
+
const total = doc.sessions[sessionId]?.calls ?? {};
|
|
286
|
+
const base = doc.bases[runId]?.sid === sessionId ? (doc.bases[runId].calls ?? {}) : {};
|
|
287
|
+
const out = {};
|
|
288
|
+
for (const [name, n] of Object.entries(total)) {
|
|
289
|
+
const d = Number(n) - (Number(base[name]) || 0);
|
|
290
|
+
if (Number.isInteger(d) && d > 0) out[name] = d;
|
|
291
|
+
}
|
|
292
|
+
return out;
|
|
293
|
+
};
|
|
294
|
+
if (!establish) return delta(readCalls(env));
|
|
295
|
+
let result = {};
|
|
296
|
+
try {
|
|
297
|
+
updateJsonFileSync(
|
|
298
|
+
mcpCallsPath(env),
|
|
299
|
+
(current) => {
|
|
300
|
+
const doc = {
|
|
301
|
+
v: 2,
|
|
302
|
+
sessions: { ...plain(current?.sessions) },
|
|
303
|
+
bases: { ...plain(current?.bases) },
|
|
304
|
+
};
|
|
305
|
+
if (doc.bases[runId]?.sid !== sessionId) {
|
|
306
|
+
doc.bases[runId] = {
|
|
307
|
+
sid: sessionId,
|
|
308
|
+
t: new Date().toISOString(),
|
|
309
|
+
calls: { ...(doc.sessions[sessionId]?.calls ?? {}) },
|
|
310
|
+
};
|
|
311
|
+
doc.bases = newestFirst(doc.bases, CALLS_MAX_SESSIONS);
|
|
312
|
+
}
|
|
313
|
+
result = delta(doc);
|
|
314
|
+
return doc;
|
|
315
|
+
},
|
|
316
|
+
{ fallback: {}, mode: 0o600, timeoutMs: Math.min(lockTimeoutFrom(env), DEADLINE_MS) },
|
|
317
|
+
);
|
|
318
|
+
} catch {
|
|
319
|
+
result = delta(readCalls(env));
|
|
320
|
+
}
|
|
321
|
+
return result;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** True when successful calls are counted: the failure-log switches, plus usage reporting on. */
|
|
325
|
+
export function callCountEnabled(env = process.env) {
|
|
326
|
+
return captureEnabled(env) && globalPref("usageLog.enabled", false, env) === true;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** `<server>:<tool>` for a tool name, or null when it is not one to count. */
|
|
330
|
+
export function callKeyOf(toolName) {
|
|
331
|
+
const names = splitToolName(toolName);
|
|
332
|
+
if (!names) return null;
|
|
333
|
+
const key = `${names.server}:${names.tool.toLowerCase()}`;
|
|
334
|
+
return CALL_KEY.test(key) ? key : null;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* Keep the marker the PostToolUse hook tests before it writes anything. The
|
|
339
|
+
* hook is a shell script with no JSON parser, so it cannot read the opt-out
|
|
340
|
+
* from the preferences reliably; it appends only while this file exists and the
|
|
341
|
+
* preferences are not newer than it. The file is created (or its time renewed)
|
|
342
|
+
* here, with the real parser, when counting is on, and removed when it is off.
|
|
343
|
+
* Never throws.
|
|
344
|
+
*/
|
|
345
|
+
export function syncCountingSentinel(env = process.env) {
|
|
346
|
+
syncCommandSentinel(env);
|
|
347
|
+
try {
|
|
348
|
+
const dir = logDir(env);
|
|
349
|
+
const file = join(dir, COUNTING_SENTINEL);
|
|
350
|
+
if (!callCountEnabled(env)) {
|
|
351
|
+
try {
|
|
352
|
+
unlinkSync(file);
|
|
353
|
+
} catch {
|
|
354
|
+
/* not there */
|
|
355
|
+
}
|
|
356
|
+
discardCounted(env);
|
|
357
|
+
return false;
|
|
358
|
+
}
|
|
359
|
+
mkdirSafe(dir, { mode: 0o700, env });
|
|
360
|
+
const fd = openSync(
|
|
361
|
+
file,
|
|
362
|
+
constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW,
|
|
363
|
+
0o600,
|
|
364
|
+
);
|
|
365
|
+
try {
|
|
366
|
+
writeSync(fd, "on\n");
|
|
367
|
+
} finally {
|
|
368
|
+
closeSync(fd);
|
|
369
|
+
}
|
|
370
|
+
return true;
|
|
371
|
+
} catch {
|
|
372
|
+
return false;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** Where the hook appends. */
|
|
377
|
+
export const mcpCallsLogPath = (env = process.env) => join(logDir(env), CALLS_LOG);
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* Fold what note-mcp-call.sh appended into the per-session counter. Everything
|
|
381
|
+
* happens under the counter file's lock: the log is renamed (so the hook starts
|
|
382
|
+
* a fresh file), the renamed file and any leftover of an interrupted fold are
|
|
383
|
+
* read, their lines added to the counter, the files deleted and the counter
|
|
384
|
+
* written. Folds that run at the same time therefore take turns and never read
|
|
385
|
+
* the same lines; a line written by a hook that had the old file open in the
|
|
386
|
+
* instant of the rename is lost, which is the same kind of undercount as a call
|
|
387
|
+
* made before the run was reported. Lines that do not fit `<session id> <mcp
|
|
388
|
+
* tool name>` are skipped. Off, and the lines discarded, when the counter is
|
|
389
|
+
* off. Never throws.
|
|
390
|
+
*
|
|
391
|
+
* @returns {number} lines counted
|
|
392
|
+
*/
|
|
393
|
+
export function foldCalls(env = process.env) {
|
|
394
|
+
let counted = 0;
|
|
395
|
+
try {
|
|
396
|
+
const dir = logDir(env);
|
|
397
|
+
const log = join(dir, CALLS_LOG);
|
|
398
|
+
const isPart = (f) => f === CALLS_LOG || f.startsWith(`${CALLS_LOG}.proc.`);
|
|
399
|
+
if (!readdirSync(dir).some(isPart)) return 0;
|
|
400
|
+
const enabled = callCountEnabled(env);
|
|
401
|
+
mkdirSafe(dir, { mode: 0o700, env });
|
|
402
|
+
updateJsonFileSync(
|
|
403
|
+
mcpCallsPath(env),
|
|
404
|
+
(current) => {
|
|
405
|
+
const mine = `${log}.proc.${process.pid}`;
|
|
406
|
+
try {
|
|
407
|
+
renameSync(log, mine);
|
|
408
|
+
} catch {
|
|
409
|
+
/* no new lines */
|
|
410
|
+
}
|
|
411
|
+
const files = readdirSync(dir)
|
|
412
|
+
.filter((f) => f.startsWith(`${CALLS_LOG}.proc.`))
|
|
413
|
+
.map((f) => join(dir, f));
|
|
414
|
+
const bySession = new Map();
|
|
415
|
+
for (const file of files) {
|
|
416
|
+
let text = "";
|
|
417
|
+
try {
|
|
418
|
+
if (enabled) text = readRegularFile(file, { maxBytes: 4 * 1024 * 1024, within: [dir] });
|
|
419
|
+
} catch {
|
|
420
|
+
/* unreadable: dropped with the file */
|
|
421
|
+
}
|
|
422
|
+
for (const line of text.split("\n")) {
|
|
423
|
+
const [sid, tool, extra] = line.split(" ");
|
|
424
|
+
if (extra !== undefined || !SESSION_ID.test(sid ?? "")) continue;
|
|
425
|
+
const key = callKeyOf(tool);
|
|
426
|
+
if (!key) continue;
|
|
427
|
+
const calls = bySession.get(sid) ?? new Map();
|
|
428
|
+
calls.set(key, (calls.get(key) ?? 0) + 1);
|
|
429
|
+
bySession.set(sid, calls);
|
|
430
|
+
}
|
|
431
|
+
try {
|
|
432
|
+
unlinkSync(file);
|
|
433
|
+
} catch {
|
|
434
|
+
/* already gone */
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
if (!bySession.size) return undefined;
|
|
438
|
+
const sessions = { ...plain(current?.sessions) };
|
|
439
|
+
const bases = { ...plain(current?.bases) };
|
|
440
|
+
for (const [sid, add] of bySession) {
|
|
441
|
+
const calls = { ...plain(plain(sessions[sid]).calls) };
|
|
442
|
+
for (const [key, n] of add) {
|
|
443
|
+
if (!Object.hasOwn(calls, key) && Object.keys(calls).length >= CALLS_MAX_NAMES)
|
|
444
|
+
continue;
|
|
445
|
+
const prior = Number.isInteger(calls[key]) && calls[key] > 0 ? calls[key] : 0;
|
|
446
|
+
calls[key] = Math.min(prior + n, CALLS_MAX_COUNT);
|
|
447
|
+
counted += n;
|
|
448
|
+
}
|
|
449
|
+
sessions[sid] = { t: new Date().toISOString(), calls };
|
|
450
|
+
}
|
|
451
|
+
return { v: 2, sessions: newestFirst(sessions, CALLS_MAX_SESSIONS), bases };
|
|
452
|
+
},
|
|
453
|
+
{ fallback: {}, mode: 0o600, timeoutMs: Math.min(lockTimeoutFrom(env), DEADLINE_MS) },
|
|
454
|
+
);
|
|
455
|
+
} catch {
|
|
456
|
+
/* the counter is bookkeeping */
|
|
457
|
+
}
|
|
458
|
+
return counted;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* Forget every call counted so far: the hook's log and any leftover of a fold,
|
|
463
|
+
* and the counter's sessions and per-run bases. Called when counting is off, so
|
|
464
|
+
* what was seen while it was off can never be sent after it is turned back on.
|
|
465
|
+
* Never throws.
|
|
466
|
+
*/
|
|
467
|
+
export function discardCounted(env = process.env) {
|
|
468
|
+
try {
|
|
469
|
+
const dir = logDir(env);
|
|
470
|
+
for (const f of readdirSync(dir)) {
|
|
471
|
+
if (f === CALLS_LOG || f.startsWith(`${CALLS_LOG}.proc.`)) {
|
|
472
|
+
try {
|
|
473
|
+
unlinkSync(join(dir, f));
|
|
474
|
+
} catch {
|
|
475
|
+
/* already gone */
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
if (readdirSync(dir).includes(CALLS_FILE)) {
|
|
480
|
+
updateJsonFileSync(mcpCallsPath(env), () => ({ v: 2, sessions: {}, bases: {} }), {
|
|
481
|
+
fallback: {},
|
|
482
|
+
mode: 0o600,
|
|
483
|
+
timeoutMs: Math.min(lockTimeoutFrom(env), DEADLINE_MS),
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
} catch {
|
|
487
|
+
/* nothing counted, nothing to forget */
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
|
|
221
491
|
/**
|
|
222
492
|
* Every readable row of the log and its previous generation, oldest first. A
|
|
223
493
|
* generation that is not a regular file, resolves outside the log directory,
|
|
@@ -346,6 +616,7 @@ async function hookMain() {
|
|
|
346
616
|
return;
|
|
347
617
|
}
|
|
348
618
|
if (!claimHookEvent("note-mcp-failure", payload)) return;
|
|
619
|
+
syncCountingSentinel();
|
|
349
620
|
record(payload);
|
|
350
621
|
}
|
|
351
622
|
|
|
@@ -67,7 +67,7 @@ OUT="$OUT_DIR/session-notes.jsonl"
|
|
|
67
67
|
|
|
68
68
|
TRANSCRIPT="$TRANSCRIPT" REPO_SLUG="$REPO_SLUG" OUT="$OUT" DRY="$DRY" JSON="$JSON" \
|
|
69
69
|
python3 - <<'PY'
|
|
70
|
-
import json, os, re, sys
|
|
70
|
+
import json, os, re, sys, time
|
|
71
71
|
from collections import Counter
|
|
72
72
|
from datetime import datetime, timezone
|
|
73
73
|
|
|
@@ -177,8 +177,67 @@ if os.environ.get("DRY") == "1":
|
|
|
177
177
|
sys.exit(0)
|
|
178
178
|
|
|
179
179
|
out = os.environ["OUT"]
|
|
180
|
-
os.makedirs(os.path.dirname(out), exist_ok=True)
|
|
181
|
-
|
|
180
|
+
os.makedirs(os.path.dirname(out), mode=0o700, exist_ok=True)
|
|
181
|
+
MAX_LOG_BYTES = 1024 * 1024
|
|
182
|
+
LOCK_STALE_S = 10
|
|
183
|
+
LOCK_WAIT_S = 0.2
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def full():
|
|
187
|
+
try:
|
|
188
|
+
return os.path.getsize(out) > MAX_LOG_BYTES
|
|
189
|
+
except OSError:
|
|
190
|
+
return False
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def rotate_locked():
|
|
194
|
+
"""Move a full log to .1 under <out>.lock, the lock note-skill-use.mjs takes
|
|
195
|
+
for the same file, and re-read the size once it is held, so a second writer
|
|
196
|
+
that saw the same full log does not move the fresh one over .1."""
|
|
197
|
+
if not full():
|
|
198
|
+
return
|
|
199
|
+
lock = out + ".lock"
|
|
200
|
+
deadline = time.time() + LOCK_WAIT_S
|
|
201
|
+
held = False
|
|
202
|
+
while True:
|
|
203
|
+
try:
|
|
204
|
+
lock_fd = os.open(lock, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
|
|
205
|
+
os.close(lock_fd)
|
|
206
|
+
held = True
|
|
207
|
+
break
|
|
208
|
+
except FileExistsError:
|
|
209
|
+
try:
|
|
210
|
+
if time.time() - os.lstat(lock).st_mtime > LOCK_STALE_S:
|
|
211
|
+
os.unlink(lock)
|
|
212
|
+
continue
|
|
213
|
+
except OSError:
|
|
214
|
+
pass
|
|
215
|
+
if time.time() > deadline:
|
|
216
|
+
break
|
|
217
|
+
time.sleep(0.005)
|
|
218
|
+
except OSError:
|
|
219
|
+
break
|
|
220
|
+
if not held:
|
|
221
|
+
return
|
|
222
|
+
try:
|
|
223
|
+
if full():
|
|
224
|
+
os.replace(out, out + ".1")
|
|
225
|
+
except OSError:
|
|
226
|
+
pass
|
|
227
|
+
finally:
|
|
228
|
+
try:
|
|
229
|
+
os.unlink(lock)
|
|
230
|
+
except OSError:
|
|
231
|
+
pass
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
rotate_locked()
|
|
235
|
+
fd = os.open(out, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, 0o600)
|
|
236
|
+
try:
|
|
237
|
+
os.fchmod(fd, 0o600)
|
|
238
|
+
except OSError:
|
|
239
|
+
pass
|
|
240
|
+
with os.fdopen(fd, "a", encoding="utf-8") as fh:
|
|
182
241
|
fh.write(json.dumps(row, ensure_ascii=False) + "\n")
|
|
183
242
|
|
|
184
243
|
print(json.dumps({"status": "written", "path": out, "errors": errors,
|
|
@@ -42,7 +42,16 @@
|
|
|
42
42
|
* @module pipeline/scripts/note-skill-use
|
|
43
43
|
*/
|
|
44
44
|
|
|
45
|
-
import {
|
|
45
|
+
import {
|
|
46
|
+
closeSync,
|
|
47
|
+
constants,
|
|
48
|
+
existsSync,
|
|
49
|
+
fchmodSync,
|
|
50
|
+
fstatSync,
|
|
51
|
+
openSync,
|
|
52
|
+
readFileSync,
|
|
53
|
+
statSync,
|
|
54
|
+
} from "node:fs";
|
|
46
55
|
import { homedir } from "node:os";
|
|
47
56
|
import { basename, dirname, join, resolve } from "node:path";
|
|
48
57
|
|
|
@@ -213,6 +222,45 @@ function takeLock(lock, opts, now = Date.now()) {
|
|
|
213
222
|
return false;
|
|
214
223
|
}
|
|
215
224
|
|
|
225
|
+
/**
|
|
226
|
+
* Run `fn` while holding <file>.lock, the lock every writer of the local logs
|
|
227
|
+
* takes before a rotation. Waits up to LOCK_WAIT_MS; when the lock stays busy
|
|
228
|
+
* `fn` is not run and undefined is returned, since the holder is rotating.
|
|
229
|
+
*/
|
|
230
|
+
export function withRotationLock(file, opts, fn) {
|
|
231
|
+
const lock = `${file}.lock`;
|
|
232
|
+
let held = takeLock(lock, opts);
|
|
233
|
+
for (let waited = 0; !held && waited < LOCK_WAIT_MS; waited += LOCK_POLL_MS) {
|
|
234
|
+
pause(LOCK_POLL_MS);
|
|
235
|
+
held = takeLock(lock, opts);
|
|
236
|
+
}
|
|
237
|
+
if (!held) return undefined;
|
|
238
|
+
try {
|
|
239
|
+
return fn();
|
|
240
|
+
} finally {
|
|
241
|
+
unlinkSafe(lock, opts);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Make an existing log owner-only. A log created by an older version, or by a
|
|
247
|
+
* shell redirect under a permissive umask, can be 0644; the first write after
|
|
248
|
+
* this change tightens it. Opened without following a link, so a link planted
|
|
249
|
+
* at the name is left alone. Never throws.
|
|
250
|
+
*/
|
|
251
|
+
export function tightenMode(file) {
|
|
252
|
+
let fd;
|
|
253
|
+
try {
|
|
254
|
+
fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
255
|
+
const st = fstatSync(fd);
|
|
256
|
+
if (st.isFile() && (st.mode & 0o077) !== 0) fchmodSync(fd, 0o600);
|
|
257
|
+
} catch {
|
|
258
|
+
/* absent, a link, or not ours to change */
|
|
259
|
+
} finally {
|
|
260
|
+
if (fd !== undefined) closeSync(fd);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
216
264
|
/**
|
|
217
265
|
* Move a full log to .1. One writer rotates at a time, under an O_EXCL lock,
|
|
218
266
|
* and re-reads the size once it holds it, so a writer that saw the full log
|
|
@@ -275,10 +323,18 @@ function rotateIfFull(file, opts) {
|
|
|
275
323
|
* write failure, a linked directory on the way included.
|
|
276
324
|
*/
|
|
277
325
|
export function appendLogRow(name, row, env = process.env) {
|
|
278
|
-
|
|
326
|
+
return appendRowIn(logDir(env), name, row, env);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* appendLogRow for a log that lives in another directory (the per-repo
|
|
331
|
+
* session notes): the same cap, generation, lock and link refusal.
|
|
332
|
+
*/
|
|
333
|
+
export function appendRowIn(dir, name, row, env = process.env) {
|
|
279
334
|
mkdirSafe(dir, { mode: 0o700, env });
|
|
280
335
|
const file = join(dir, name);
|
|
281
336
|
if (!rotateIfFull(file, { env })) return false;
|
|
337
|
+
tightenMode(file);
|
|
282
338
|
try {
|
|
283
339
|
appendFileSafe(file, JSON.stringify(row) + "\n", { mode: 0o600, env });
|
|
284
340
|
return true;
|