@mmerterden/multi-agent-pipeline 20.41.0 → 20.42.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.
Files changed (103) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +1 -1
  3. package/README.tr.md +1 -1
  4. package/docs/ecosystem.md +45 -8
  5. package/docs/facts.json +7 -7
  6. package/docs/features.md +9 -4
  7. package/install/claude.mjs +34 -1
  8. package/install/templates/claude-hooks.json +12 -1
  9. package/manifest.json +106 -86
  10. package/package.json +3 -2
  11. package/pipeline/commands/multi-agent/autopilot/SKILL.md +11 -0
  12. package/pipeline/commands/multi-agent/setup/SKILL.md +1 -1
  13. package/pipeline/lib/args.mjs +131 -4
  14. package/pipeline/lib/bg-launch.mjs +5 -2
  15. package/pipeline/lib/credential-store.sh +11 -1
  16. package/pipeline/lib/hook-once.mjs +134 -0
  17. package/pipeline/lib/isotonic.mjs +73 -0
  18. package/pipeline/lib/low-disk.mjs +153 -0
  19. package/pipeline/lib/mcp-schema-load.mjs +90 -0
  20. package/pipeline/lib/md2confluence-v3.py +8 -7
  21. package/pipeline/lib/model-dispatch.sh +26 -2
  22. package/pipeline/lib/normalize-text.mjs +135 -0
  23. package/pipeline/lib/outbound-gate.mjs +21 -3
  24. package/pipeline/lib/plan-todos.sh +17 -4
  25. package/pipeline/lib/redact.mjs +12 -3
  26. package/pipeline/lib/risky-settings.mjs +198 -0
  27. package/pipeline/lib/route-state.sh +1 -0
  28. package/pipeline/lib/secret-patterns.generated.mjs +6 -2
  29. package/pipeline/lib/session-usage.mjs +232 -0
  30. package/pipeline/lib/source-digest.mjs +211 -0
  31. package/pipeline/lib/tdd-evidence.mjs +250 -17
  32. package/pipeline/lib/untrusted-fence.mjs +132 -1
  33. package/pipeline/multi-agent-refs/analysis/locked.md +1 -1
  34. package/pipeline/multi-agent-refs/features/cost-analysis.md +37 -2
  35. package/pipeline/multi-agent-refs/features/doctor.md +51 -4
  36. package/pipeline/multi-agent-refs/features/model-fallback.md +25 -0
  37. package/pipeline/multi-agent-refs/features/plan-todos.md +4 -0
  38. package/pipeline/multi-agent-refs/features/unattended-gates.md +5 -3
  39. package/pipeline/multi-agent-refs/features/usage-reporting.md +4 -2
  40. package/pipeline/multi-agent-refs/help/en.md +1 -1
  41. package/pipeline/multi-agent-refs/help/tr.md +1 -1
  42. package/pipeline/multi-agent-refs/outside-the-pipeline.md +6 -0
  43. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +1 -1
  44. package/pipeline/multi-agent-refs/phases/phase-2-dev.md +4 -4
  45. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -2
  46. package/pipeline/multi-agent-refs/phases/phase-5-report.md +2 -0
  47. package/pipeline/multi-agent-refs/progress-contract.md +3 -1
  48. package/pipeline/office/toolkit.json +1 -1
  49. package/pipeline/rules/outside-the-pipeline.md +1 -1
  50. package/pipeline/schemas/doctor-report.schema.json +47 -0
  51. package/pipeline/schemas/plan-todos.schema.json +29 -1
  52. package/pipeline/schemas/prefs.schema.json +63 -0
  53. package/pipeline/schemas/route-config.schema.json +51 -0
  54. package/pipeline/schemas/secret-patterns.json +17 -1
  55. package/pipeline/schemas/toolkit-path-params.json +15 -1
  56. package/pipeline/scripts/_cost-advise.mjs +357 -0
  57. package/pipeline/scripts/_cost-budget.mjs +78 -0
  58. package/pipeline/scripts/_cost.mjs +29 -0
  59. package/pipeline/scripts/_decode_text.py +107 -0
  60. package/pipeline/scripts/_guard-probe.mjs +406 -0
  61. package/pipeline/scripts/_guard_rules.py +206 -0
  62. package/pipeline/scripts/_memory-policy.mjs +1 -25
  63. package/pipeline/scripts/_retrieval.mjs +148 -2
  64. package/pipeline/scripts/_secret-scan.mjs +6 -1
  65. package/pipeline/scripts/_stack-routing.mjs +1 -0
  66. package/pipeline/scripts/_test-gaming.mjs +346 -0
  67. package/pipeline/scripts/agent-guard.py +8 -1
  68. package/pipeline/scripts/argv-secret-scan.mjs +2 -1
  69. package/pipeline/scripts/autopilot-loop.mjs +407 -0
  70. package/pipeline/scripts/autopilot-runner.mjs +38 -25
  71. package/pipeline/scripts/capture-resume.sh +9 -1
  72. package/pipeline/scripts/cost-analyze.mjs +66 -4
  73. package/pipeline/scripts/cost-budget-check.mjs +5 -13
  74. package/pipeline/scripts/disk-cleaner.mjs +1418 -0
  75. package/pipeline/scripts/doctor.mjs +169 -44
  76. package/pipeline/scripts/evidence-gate.mjs +90 -0
  77. package/pipeline/scripts/gate-ledger.mjs +76 -21
  78. package/pipeline/scripts/gc-tmp.sh +5 -0
  79. package/pipeline/scripts/guard-probe-known-holes.json +3 -0
  80. package/pipeline/scripts/learnings-ledger.mjs +16 -12
  81. package/pipeline/scripts/note-agent-event.mjs +2 -0
  82. package/pipeline/scripts/note-mcp-failure.mjs +9 -2
  83. package/pipeline/scripts/note-skill-use.mjs +4 -1
  84. package/pipeline/scripts/pre-commit-check.sh +2 -2
  85. package/pipeline/scripts/pre-push-check.sh +8 -1
  86. package/pipeline/scripts/publish-staged.mjs +324 -0
  87. package/pipeline/scripts/route-learn.mjs +628 -0
  88. package/pipeline/scripts/run-scope-guard.mjs +55 -1
  89. package/pipeline/scripts/scan-agent-config.sh +1 -1
  90. package/pipeline/scripts/statusline.mjs +309 -0
  91. package/pipeline/scripts/test-integrity-gate.mjs +97 -2
  92. package/pipeline/scripts/triage-memory.mjs +12 -4
  93. package/pipeline/scripts/uninstall.mjs +1 -0
  94. package/pipeline/skills/.skill-manifest.json +8 -4
  95. package/pipeline/skills/.skills-index.json +14 -3
  96. package/pipeline/skills/shared/README.md +5 -4
  97. package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
  98. package/pipeline/skills/shared/external/disk-cleaner/SKILL.md +105 -0
  99. package/pipeline/skills/shared/external/disk-cleaner/evals/evals.json +62 -0
  100. package/pipeline/skills/shared/external/disk-cleaner/scripts/disk-cleaner.mjs +1418 -0
  101. package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
  102. package/pipeline/skills/skill-copies.json +4 -0
  103. package/pipeline/skills/skills-index.md +3 -2
@@ -165,7 +165,7 @@ import {
165
165
  import { createInterface } from "node:readline";
166
166
  import { homedir } from "node:os";
167
167
  import { join, dirname, basename } from "node:path";
168
- import { bm25, recencyRank, rrf, tokens, recallConfig } from "./_retrieval.mjs";
168
+ import { bm25, mmr, multiQuery, recencyRank, rrf, tokens, recallConfig } from "./_retrieval.mjs";
169
169
  import { checkedSlug, repoName } from "../lib/slug.mjs";
170
170
  import {
171
171
  GLOBAL_LEDGER_SLUG,
@@ -943,15 +943,15 @@ function cmdBrief() {
943
943
  // pass no task text, and as the rollback path.
944
944
  ordered = capGlobalShare(newestFirst(pool), max);
945
945
  } else {
946
- const relevance = bm25(
947
- tokens(task),
948
- pool.map((r) => ({
949
- statement: r.statement || "",
950
- diagnosis: r.diagnosis || "",
951
- scope: r.scope === "global" ? "" : r.scope || "",
952
- })),
953
- { fieldWeights: { statement: 3, diagnosis: 2, scope: 1 } },
954
- );
946
+ const docs = pool.map((r) => ({
947
+ statement: r.statement || "",
948
+ diagnosis: r.diagnosis || "",
949
+ scope: r.scope === "global" ? "" : r.scope || "",
950
+ }));
951
+ const fieldWeights = { statement: 3, diagnosis: 2, scope: 1 };
952
+ const relevance = cfg.multiQuery
953
+ ? multiQuery(task, docs, { fieldWeights })
954
+ : bm25(tokens(task), docs, { fieldWeights });
955
955
  const fresh = recencyRank(pool, { halfLifeDays: cfg.halfLifeDays });
956
956
  const matched = new Set(relevance.filter((x) => x.score > 0).map((x) => x.index));
957
957
  // Entries recorded useful at least twice rank by their strength as well;
@@ -959,8 +959,12 @@ function cmdBrief() {
959
959
  const earned = pool
960
960
  .map((r, index) => ({ index, score: strengthOf.get(r) || 0 }))
961
961
  .sort((a, b) => b.score - a.score);
962
- const fused = rrf([relevance, fresh, earned], { k: [10, 60, 60], weights: [3, 1, 1] }).filter(
963
- (x) => matched.has(x.index),
962
+ const fused = mmr(
963
+ rrf([relevance, fresh, earned], { k: [10, 60, 60], weights: [3, 1, 1] }).filter((x) =>
964
+ matched.has(x.index),
965
+ ),
966
+ docs.map((d) => tokens(`${d.statement} ${d.diagnosis}`)),
967
+ { lambda: cfg.mmrLambda, limit: max },
964
968
  );
965
969
  ordered = capGlobalShare(
966
970
  fused.map((x) => pool[x.index]),
@@ -29,6 +29,7 @@ import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
29
29
  import { homedir } from "node:os";
30
30
  import { join } from "node:path";
31
31
 
32
+ import { claimHookEvent } from "../lib/hook-once.mjs";
32
33
  import { invokedDirectly } from "../lib/invoked-directly.mjs";
33
34
  import { findActiveRun } from "./_active-run.mjs";
34
35
  import { memoryExcluded } from "./_memory-policy.mjs";
@@ -143,6 +144,7 @@ function main() {
143
144
  } catch {
144
145
  return;
145
146
  }
147
+ if (!claimHookEvent("note-agent-event", payload)) return;
146
148
  record(payload);
147
149
  }
148
150
 
@@ -10,8 +10,9 @@
10
10
  * server the MCP server, from the tool name mcp__<server>__<tool>
11
11
  * tool the tool, from the same name
12
12
  * ts when the hook ran
13
- * errorClass one of ERROR_CLASSES, chosen from the error text: a JSON-RPC
14
- * code first, then a message that opens with "invalid" or
13
+ * errorClass one of ERROR_CLASSES: the host's interrupt flag first, then
14
+ * a refusal by the user or the permission layer, then a JSON-RPC
15
+ * code, then a message that opens with "invalid" or
15
16
  * "validation", then an HTTP status, then fixed wording
16
17
  * patterns; the text itself is never stored
17
18
  *
@@ -48,6 +49,7 @@ import { join } from "node:path";
48
49
  import { parseArgs } from "../lib/args.mjs";
49
50
  import { exitOnHelp } from "../lib/cli-help.mjs";
50
51
  import { installFatalHandlers } from "../lib/fatal.mjs";
52
+ import { claimHookEvent } from "../lib/hook-once.mjs";
51
53
  import { invokedDirectly } from "../lib/invoked-directly.mjs";
52
54
  import { findPrefs, globalPref } from "../lib/prefs-value.mjs";
53
55
  import { redact } from "../lib/redact.mjs";
@@ -120,6 +122,10 @@ function statusClass(status) {
120
122
  * the server failing, and invalid-input is not counted against a server.
121
123
  */
122
124
  const CLASS_PATTERNS = [
125
+ [
126
+ "disk-full",
127
+ /ENOSPC|no space left on device|disk (?:is )?full|not enough (?:free )?(?:disk )?space|out of disk space/i,
128
+ ],
123
129
  ["timeout", /timed out|deadline exceeded|ETIMEDOUT|timeout (?:error|exceeded|after)/i],
124
130
  ["rate-limit", /rate.?limit|too many requests/i],
125
131
  ["auth", /unauthori[sz]ed|forbidden|authenticat|expired token|token expired|invalid token/i],
@@ -339,6 +345,7 @@ async function hookMain() {
339
345
  } catch {
340
346
  return;
341
347
  }
348
+ if (!claimHookEvent("note-mcp-failure", payload)) return;
342
349
  record(payload);
343
350
  }
344
351
 
@@ -48,6 +48,7 @@ import { basename, dirname, join, resolve } from "node:path";
48
48
 
49
49
  import { exitOnHelp } from "../lib/cli-help.mjs";
50
50
  import { installFatalHandlers } from "../lib/fatal.mjs";
51
+ import { claimHookEvent } from "../lib/hook-once.mjs";
51
52
  import { invokedDirectly } from "../lib/invoked-directly.mjs";
52
53
  import { globalPref } from "../lib/prefs-value.mjs";
53
54
  import { redact } from "../lib/redact.mjs";
@@ -165,7 +166,8 @@ async function rowRepo(cwd, env) {
165
166
 
166
167
  /**
167
168
  * The log's size: 0 when nothing is there, null when a link, a FIFO, a
168
- * directory or anything but a regular file stands at the name.
169
+ * directory or anything but a regular file stands at the name. Any other
170
+ * stat error is thrown to the caller.
169
171
  */
170
172
  function logSize(file, opts) {
171
173
  try {
@@ -332,6 +334,7 @@ async function main() {
332
334
  } catch {
333
335
  return;
334
336
  }
337
+ if (!claimHookEvent("note-skill-use", payload)) return;
335
338
  await record(payload);
336
339
  }
337
340
 
@@ -96,10 +96,10 @@ SECRET_PATTERN_ERES=(
96
96
  '"type"[[:space:]]*:[[:space:]]*"service_account"'
97
97
  '(^|[^A-Za-z0-9_])eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}([^A-Za-z0-9_]|$)'
98
98
  '-----BEGIN [A-Z0-9 ]*PRIVATE KEY( BLOCK)?-----'
99
- '(^|[^A-Za-z0-9_])[a-z][a-z0-9+.-]*://[^[:space:]/:@]+:[^[:space:]/@]+@'
99
+ '(^|[^A-Za-z0-9_])[a-z][a-z0-9+.-]{0,31}://[^[:space:]/:@]{1,255}:[^[:space:]/@]+@'
100
100
  '(^|[^A-Za-z0-9_])Authorization:[[:space:]]*(Bearer|Basic)[[:space:]]+[A-Za-z0-9._~+/=-]{16,}'
101
101
  )
102
- SECRET_PATTERNS_ERE='((^|[^A-Za-z0-9_])gh[pousr]_[A-Za-z0-9]{36,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])github_pat_[A-Za-z0-9_]{50,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])xox[abprs]-[A-Za-z0-9-]{10,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])(AKIA|ASIA)[0-9A-Z]{16})|((^|[^A-Za-z0-9_])AIza[0-9A-Za-z_-]{35}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])sk-(proj-)?[A-Za-z0-9_-]{32,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])sk-ant-[A-Za-z0-9_-]{32,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])fig[a-z]_[A-Za-z0-9_-]{20,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])npm_[A-Za-z0-9]{36}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])glpat-[A-Za-z0-9_-]{20,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])[sr]k_live_[A-Za-z0-9]{20,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])pplx-[A-Za-z0-9]{32,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])hf_[A-Za-z0-9]{30,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])gsk_[A-Za-z0-9]{40,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])sk-or-v1-[A-Za-z0-9]{40,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])xapp-[0-9]+-[A-Za-z0-9]{8,}-[0-9]{8,}-[A-Za-z0-9]{32,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}([^A-Za-z0-9_-]|$))|((^|[^A-Za-z0-9_])SK[0-9a-f]{32}([^A-Za-z0-9_]|$))|("type"[[:space:]]*:[[:space:]]*"service_account")|((^|[^A-Za-z0-9_])eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}([^A-Za-z0-9_]|$))|(-----BEGIN [A-Z0-9 ]*PRIVATE KEY( BLOCK)?-----)|((^|[^A-Za-z0-9_])[a-z][a-z0-9+.-]*://[^[:space:]/:@]+:[^[:space:]/@]+@)'
102
+ SECRET_PATTERNS_ERE='((^|[^A-Za-z0-9_])gh[pousr]_[A-Za-z0-9]{36,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])github_pat_[A-Za-z0-9_]{50,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])xox[abprs]-[A-Za-z0-9-]{10,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])(AKIA|ASIA)[0-9A-Z]{16})|((^|[^A-Za-z0-9_])AIza[0-9A-Za-z_-]{35}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])sk-(proj-)?[A-Za-z0-9_-]{32,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])sk-ant-[A-Za-z0-9_-]{32,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])fig[a-z]_[A-Za-z0-9_-]{20,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])npm_[A-Za-z0-9]{36}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])glpat-[A-Za-z0-9_-]{20,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])[sr]k_live_[A-Za-z0-9]{20,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])pplx-[A-Za-z0-9]{32,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])hf_[A-Za-z0-9]{30,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])gsk_[A-Za-z0-9]{40,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])sk-or-v1-[A-Za-z0-9]{40,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])xapp-[0-9]+-[A-Za-z0-9]{8,}-[0-9]{8,}-[A-Za-z0-9]{32,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}([^A-Za-z0-9_-]|$))|((^|[^A-Za-z0-9_])SK[0-9a-f]{32}([^A-Za-z0-9_]|$))|("type"[[:space:]]*:[[:space:]]*"service_account")|((^|[^A-Za-z0-9_])eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}([^A-Za-z0-9_]|$))|(-----BEGIN [A-Z0-9 ]*PRIVATE KEY( BLOCK)?-----)|((^|[^A-Za-z0-9_])[a-z][a-z0-9+.-]{0,31}://[^[:space:]/:@]{1,255}:[^[:space:]/@]+@)'
103
103
  SECRET_PATTERNS_ERE_ICASE='(aws_?secret_?access_?key["'\'']?[[:space:]]*[:=][[:space:]]*["'\'']?[A-Za-z0-9/+=]{40}([^A-Za-z0-9/+=]|$))|(aws_?session_?token["'\'']?[[:space:]]*[:=][[:space:]]*["'\'']?[A-Za-z0-9/+=]{100,})|((^|[^A-Za-z0-9_])Authorization:[[:space:]]*(Bearer|Basic)[[:space:]]+[A-Za-z0-9._~+/=-]{16,})'
104
104
  # END GENERATED: secret-patterns
105
105
 
@@ -44,6 +44,8 @@
44
44
 
45
45
  set -uo pipefail
46
46
 
47
+ LOW_DISK="$(cd "$(dirname "${BASH_SOURCE[0]}")/../lib" 2>/dev/null && pwd)/low-disk.mjs"
48
+
47
49
  # Git runs the hook from the top of the worktree being pushed; the script itself
48
50
  # may live in a different checkout of the same repository. Measure the former.
49
51
  REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || (cd "$(dirname "$0")/../.." && pwd))"
@@ -114,12 +116,16 @@ echo "→ Running local CI gate (primary - GitHub Actions is not executing)"
114
116
  echo ""
115
117
 
116
118
  FAILED=0
119
+ # Every step's output is kept, so a failed gate can be checked for a full
120
+ # disk: a gate that dies with ENOSPC is not a code defect.
121
+ GATE_LOG="$(mktemp "${TMPDIR:-/tmp}/pre-push-gate-XXXXXX")"
122
+ trap 'rm -f "$GATE_LOG"' EXIT
117
123
 
118
124
  run_step() {
119
125
  local name="$1"
120
126
  shift
121
127
  echo "→ $name"
122
- if "$@"; then
128
+ if { "$@" 2>&1; } | tee -a "$GATE_LOG"; then
123
129
  echo " ✓ $name passed"
124
130
  else
125
131
  echo " ✗ $name FAILED" >&2
@@ -166,6 +172,7 @@ fi
166
172
  if [ "$FAILED" -gt 0 ]; then
167
173
  echo "" >&2
168
174
  echo "✗ $FAILED gate(s) failed. Fix before pushing." >&2
175
+ node "$LOW_DISK" --scan "$GATE_LOG" >&2 || true
169
176
  echo " To bypass (emergencies only): git push --no-verify" >&2
170
177
  exit 1
171
178
  fi
@@ -0,0 +1,324 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * publish-staged.mjs - publish an npm package so that `latest` only ever
4
+ * names a version the registry has been seen to serve and that installs.
5
+ *
6
+ * 1. pack `npm pack`, and the tarball's sha512 computed here; the two
7
+ * must agree
8
+ * 2. publish `npm publish <tarball> --tag candidate`. A version the
9
+ * registry already holds with these bytes is a resumed
10
+ * release and is not published again; with other bytes it
11
+ * is refused
12
+ * 3. visible poll the registry's packument until the version carries
13
+ * the local integrity and the candidate tag names it. Read
14
+ * over HTTP, never with `npm view`, whose cache answers
15
+ * before the registry does. A different integrity fails at
16
+ * once: waiting cannot fix it
17
+ * 4. tarball download the tarball the registry serves; its sha512 must
18
+ * be the local one
19
+ * 5. install `npm install <that tarball>` into an empty temp project,
20
+ * scripts off, and check the installed version and its bins
21
+ * 6. smoke `--smoke "<cmd>"`, run in that project, when given
22
+ * 7. promote `npm dist-tag add <name>@<version> latest`
23
+ * 8. latest poll until the registry's `latest` names the version
24
+ *
25
+ * A failure before step 2 publishes nothing (exit 1). A failure after it
26
+ * leaves the version on the candidate tag and `latest` where it was (exit 3);
27
+ * running the same command again resumes from step 3.
28
+ *
29
+ * Usage:
30
+ * publish-staged.mjs [--dir <package dir>] [--registry <url>] [--tag <dist-tag>]
31
+ * [--npm <npm bin>] [--userconfig <npmrc>] [--smoke "<cmd>"]
32
+ * [--timeout-s N] [--interval-ms N] [--dry-run] [--json]
33
+ *
34
+ * --tag never names `latest`: publishing there moves latest before any of the
35
+ * checks run, so it is refused (exit 2) in any letter case.
36
+ *
37
+ * --registry defaults to https://registry.npmjs.org, --tag to candidate,
38
+ * --timeout-s to 300 per poll and --interval-ms to 5000. --userconfig is
39
+ * passed to every npm call, so a token kept in a temporary npmrc never
40
+ * reaches argv. --dry-run stops after the pack.
41
+ *
42
+ * Exit: 0 promoted (or dry run packed); 1 nothing published; 2 usage error;
43
+ * 3 published to the candidate tag, not promoted.
44
+ */
45
+
46
+ import { spawnSync } from "node:child_process";
47
+ import { createHash } from "node:crypto";
48
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
49
+ import { tmpdir } from "node:os";
50
+ import { join, resolve } from "node:path";
51
+
52
+ import { ArgsError, parseArgs } from "../lib/args.mjs";
53
+ import { exitOnHelp } from "../lib/cli-help.mjs";
54
+ import { invokedDirectly } from "../lib/invoked-directly.mjs";
55
+
56
+ exitOnHelp(import.meta.url);
57
+
58
+ const DEFAULT_REGISTRY = "https://registry.npmjs.org";
59
+
60
+ /** The packument URL of a package; a scope's slash is encoded. */
61
+ export function packumentUrl(registry, name) {
62
+ return `${String(registry).replace(/\/+$/, "")}/${String(name).replace("/", "%2f")}`;
63
+ }
64
+
65
+ /** Why a staging tag cannot be used, or null: `latest` is the tag only promote may move. */
66
+ export function stagingTagRefusal(tag) {
67
+ const t = String(tag ?? "").trim();
68
+ if (!t) return "--tag needs a dist-tag name";
69
+ if (t.toLowerCase() === "latest")
70
+ return "--tag latest would move latest before the release is verified; stage on another tag";
71
+ return null;
72
+ }
73
+
74
+ export const integrityOf = (buf) => `sha512-${createHash("sha512").update(buf).digest("base64")}`;
75
+
76
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
77
+
78
+ function npmRunner(bin, userconfig) {
79
+ const viaNode = /\.(mjs|cjs|js)$/.test(bin);
80
+ return (args, cwd) => {
81
+ const argv = [...args, ...(userconfig ? ["--userconfig", userconfig] : [])];
82
+ const r = spawnSync(viaNode ? process.execPath : bin, viaNode ? [bin, ...argv] : argv, {
83
+ cwd,
84
+ encoding: "utf8",
85
+ env: process.env,
86
+ stdio: ["ignore", "pipe", "pipe"],
87
+ timeout: 10 * 60 * 1000,
88
+ });
89
+ return {
90
+ ok: r.status === 0,
91
+ stdout: r.stdout || "",
92
+ stderr: String(r.stderr || r.error?.message || "").trim(),
93
+ };
94
+ };
95
+ }
96
+
97
+ async function packument(registry, name) {
98
+ const res = await fetch(packumentUrl(registry, name), {
99
+ headers: { accept: "application/json" },
100
+ });
101
+ if (res.status === 404) return null;
102
+ if (!res.ok) throw new Error(`registry answered ${res.status}`);
103
+ return res.json();
104
+ }
105
+
106
+ async function poll(check, { timeoutMs, intervalMs }) {
107
+ const end = Date.now() + timeoutMs;
108
+ let last;
109
+ for (;;) {
110
+ try {
111
+ last = await check();
112
+ if (last.done) return last;
113
+ } catch (e) {
114
+ if (e.fatal) throw e;
115
+ last = { done: false, detail: e.message };
116
+ }
117
+ if (Date.now() >= end) return { ...last, done: false, timedOut: true };
118
+ await sleep(intervalMs);
119
+ }
120
+ }
121
+
122
+ /**
123
+ * The staged release. `steps` collects one {step, ok, detail} per step run.
124
+ *
125
+ * @returns {Promise<{code: number, report: object}>}
126
+ */
127
+ export async function publishStaged(opts) {
128
+ const refusal = stagingTagRefusal(opts.tag);
129
+ if (refusal) throw new ArgsError(refusal, { kind: "unexpected", token: "--tag" });
130
+ const dir = resolve(opts.dir);
131
+ const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
132
+ const npm = npmRunner(opts.npm, opts.userconfig);
133
+ const steps = [];
134
+ const report = {
135
+ name: pkg.name,
136
+ version: pkg.version,
137
+ tag: opts.tag,
138
+ registry: opts.registry,
139
+ integrity: null,
140
+ promoted: false,
141
+ steps,
142
+ };
143
+ const work = mkdtempSync(join(tmpdir(), "publish-staged-"));
144
+ const done = (code) => {
145
+ rmSync(work, { recursive: true, force: true });
146
+ return { code, report };
147
+ };
148
+ const step = (name, ok, detail) => {
149
+ steps.push({ step: name, ok, detail });
150
+ return ok;
151
+ };
152
+ const timing = { timeoutMs: opts.timeoutS * 1000, intervalMs: opts.intervalMs };
153
+
154
+ const packed = npm(["pack", "--json", "--pack-destination", work], dir);
155
+ let tarball;
156
+ try {
157
+ const entry = JSON.parse(packed.stdout)[0];
158
+ tarball = join(work, entry.filename);
159
+ const local = integrityOf(readFileSync(tarball));
160
+ report.integrity = local;
161
+ if (entry.integrity && entry.integrity !== local) {
162
+ step("pack", false, `npm reported ${entry.integrity}, the tarball hashes to ${local}`);
163
+ return done(1);
164
+ }
165
+ step("pack", true, `${entry.filename} ${statSync(tarball).size} bytes`);
166
+ } catch (e) {
167
+ step("pack", false, packed.ok ? `unreadable pack output: ${e.message}` : packed.stderr);
168
+ return done(1);
169
+ }
170
+ if (opts.dryRun) return done(0);
171
+
172
+ let existing;
173
+ try {
174
+ existing = (await packument(opts.registry, pkg.name))?.versions?.[pkg.version];
175
+ } catch (e) {
176
+ step("publish", false, `the registry could not be read before publishing: ${e.message}`);
177
+ return done(1);
178
+ }
179
+ if (existing) {
180
+ if (existing.dist?.integrity !== report.integrity) {
181
+ step("publish", false, `${pkg.version} is already on the registry with other bytes`);
182
+ return done(1);
183
+ }
184
+ step("publish", true, "already on the registry with these bytes");
185
+ } else {
186
+ const pub = npm(["publish", tarball, "--tag", opts.tag, "--registry", opts.registry], dir);
187
+ if (!step("publish", pub.ok, pub.ok ? `tag ${opts.tag}` : pub.stderr)) return done(1);
188
+ }
189
+
190
+ const visible = await poll(async () => {
191
+ const doc = await packument(opts.registry, pkg.name);
192
+ const v = doc?.versions?.[pkg.version];
193
+ if (v && v.dist?.integrity && v.dist.integrity !== report.integrity) {
194
+ throw Object.assign(new Error(`the registry serves ${v.dist.integrity}`), { fatal: true });
195
+ }
196
+ const tagged = doc?.["dist-tags"]?.[opts.tag] === pkg.version;
197
+ return {
198
+ done: Boolean(v) && tagged,
199
+ url: v?.dist?.tarball,
200
+ detail: v ? "tag not yet moved" : "version not yet listed",
201
+ };
202
+ }, timing).catch((e) => ({ done: false, detail: e.message }));
203
+ if (!visible.done) {
204
+ step("visible", false, visible.timedOut ? `timed out: ${visible.detail}` : visible.detail);
205
+ return done(3);
206
+ }
207
+ step("visible", true, `${opts.tag} -> ${pkg.version}`);
208
+
209
+ const served = join(work, "served.tgz");
210
+ try {
211
+ const res = await fetch(visible.url);
212
+ if (!res.ok) throw new Error(`tarball answered ${res.status}`);
213
+ writeFileSync(served, Buffer.from(await res.arrayBuffer()));
214
+ } catch (e) {
215
+ step("tarball", false, e.message);
216
+ return done(3);
217
+ }
218
+ const servedIntegrity = integrityOf(readFileSync(served));
219
+ if (!step("tarball", servedIntegrity === report.integrity, servedIntegrity)) return done(3);
220
+
221
+ const project = join(work, "install");
222
+ mkdirSync(project, { recursive: true });
223
+ writeFileSync(join(project, "package.json"), JSON.stringify({ private: true }));
224
+ const inst = npm(
225
+ ["install", served, "--ignore-scripts", "--no-audit", "--no-fund", "--no-package-lock"],
226
+ project,
227
+ );
228
+ if (!inst.ok) {
229
+ step("install", false, inst.stderr);
230
+ return done(3);
231
+ }
232
+ try {
233
+ const installed = join(project, "node_modules", pkg.name);
234
+ const got = JSON.parse(readFileSync(join(installed, "package.json"), "utf8"));
235
+ if (got.version !== pkg.version) throw new Error(`installed ${got.version}`);
236
+ const bins = typeof got.bin === "string" ? [got.bin] : Object.values(got.bin || {});
237
+ for (const b of bins) statSync(join(installed, b));
238
+ step("install", true, `${pkg.version}, ${bins.length} bin(s) present`);
239
+ } catch (e) {
240
+ step("install", false, e.message);
241
+ return done(3);
242
+ }
243
+
244
+ if (opts.smoke) {
245
+ const r = spawnSync("/bin/sh", ["-c", opts.smoke], {
246
+ cwd: project,
247
+ encoding: "utf8",
248
+ timeout: 5 * 60 * 1000,
249
+ });
250
+ const detail = `${opts.smoke}: exit ${r.status}${r.stderr ? ` ${r.stderr.trim().slice(0, 200)}` : ""}`;
251
+ if (!step("smoke", r.status === 0, detail)) return done(3);
252
+ }
253
+
254
+ const tagged = npm(
255
+ ["dist-tag", "add", `${pkg.name}@${pkg.version}`, "latest", "--registry", opts.registry],
256
+ dir,
257
+ );
258
+ if (!step("promote", tagged.ok, tagged.ok ? "latest" : tagged.stderr)) return done(3);
259
+ const latest = await poll(async () => {
260
+ const doc = await packument(opts.registry, pkg.name);
261
+ return { done: doc?.["dist-tags"]?.latest === pkg.version, detail: "latest not yet moved" };
262
+ }, timing);
263
+ if (!step("latest", latest.done, latest.done ? pkg.version : latest.detail)) return done(3);
264
+ report.promoted = true;
265
+ return done(0);
266
+ }
267
+
268
+ async function main() {
269
+ let flags;
270
+ try {
271
+ ({ flags } = parseArgs(process.argv.slice(2), {
272
+ unknown: "error",
273
+ positionals: false,
274
+ booleans: ["dry-run", "json"],
275
+ strings: ["dir", "registry", "tag", "npm", "userconfig", "smoke", "timeout-s", "interval-ms"],
276
+ }));
277
+ } catch (e) {
278
+ if (!(e instanceof ArgsError)) throw e;
279
+ process.stderr.write(`publish-staged: ${e.message}\n`);
280
+ process.exitCode = 2;
281
+ return;
282
+ }
283
+ const timeoutS = Number(flags["timeout-s"] ?? 300);
284
+ const intervalMs = Number(flags["interval-ms"] ?? 5000);
285
+ const refusal = stagingTagRefusal(flags.tag ?? "candidate");
286
+ if (refusal) {
287
+ process.stderr.write(`publish-staged: ${refusal}\n`);
288
+ process.exitCode = 2;
289
+ return;
290
+ }
291
+ if (!(timeoutS > 0) || !(intervalMs > 0)) {
292
+ process.stderr.write("publish-staged: --timeout-s and --interval-ms take positive numbers\n");
293
+ process.exitCode = 2;
294
+ return;
295
+ }
296
+ const { code, report } = await publishStaged({
297
+ dir: flags.dir ?? process.cwd(),
298
+ registry: flags.registry ?? DEFAULT_REGISTRY,
299
+ tag: flags.tag ?? "candidate",
300
+ npm: flags.npm ?? "npm",
301
+ userconfig: flags.userconfig ?? null,
302
+ smoke: flags.smoke ?? null,
303
+ timeoutS,
304
+ intervalMs,
305
+ dryRun: flags["dry-run"] === true,
306
+ });
307
+ if (flags.json) {
308
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
309
+ } else {
310
+ for (const s of report.steps) {
311
+ process.stdout.write(`${s.ok ? "ok " : "FAIL"} ${s.step.padEnd(8)} ${s.detail ?? ""}\n`);
312
+ }
313
+ process.stdout.write(
314
+ report.promoted
315
+ ? `${report.name}@${report.version} is latest\n`
316
+ : code === 3
317
+ ? `${report.name}@${report.version} stays on ${report.tag}; latest is unchanged\n`
318
+ : "",
319
+ );
320
+ }
321
+ process.exitCode = code;
322
+ }
323
+
324
+ if (invokedDirectly(import.meta.url)) await main();