@mmerterden/multi-agent-pipeline 23.3.0 → 23.4.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 (224) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +25 -6
  3. package/README.tr.md +26 -7
  4. package/docs/adr/0008-installer-modularization-and-secret-leak-defense.md +1 -1
  5. package/docs/adr/0010-own-code-graph.md +299 -8
  6. package/docs/architecture.md +3 -3
  7. package/docs/ecosystem.md +10 -10
  8. package/docs/engineering.md +4 -4
  9. package/docs/facts.json +8 -8
  10. package/docs/features.md +5 -5
  11. package/docs/performance.md +17 -17
  12. package/install/_dev-only-files.mjs +9 -0
  13. package/install/claude.mjs +28 -2
  14. package/install/templates/claude-hooks.json +32 -1
  15. package/manifest.json +223 -155
  16. package/package.json +11 -3
  17. package/pipeline/commands/multi-agent/SKILL.md +1 -1
  18. package/pipeline/commands/multi-agent/design-check/SKILL.md +2 -2
  19. package/pipeline/commands/multi-agent/diff-explain/SKILL.md +3 -3
  20. package/pipeline/commands/multi-agent/graph/SKILL.md +57 -24
  21. package/pipeline/commands/multi-agent/pair/SKILL.md +92 -0
  22. package/pipeline/commands/multi-agent/prune-prompts/SKILL.md +1 -1
  23. package/pipeline/commands/multi-agent/search/SKILL.md +7 -1
  24. package/pipeline/commands/multi-agent/status/SKILL.md +4 -0
  25. package/pipeline/commands/multi-agent/sync/SKILL.md +3 -3
  26. package/pipeline/contract/CHANGELOG.md +49 -0
  27. package/pipeline/contract/build.mjs +13 -1
  28. package/pipeline/contract/fixtures/error-invalid-request.json +1 -1
  29. package/pipeline/contract/fixtures/error-unauthorized.json +1 -1
  30. package/pipeline/contract/fixtures/runs-awaiting-question.json +4 -1
  31. package/pipeline/contract/fixtures/runs-empty.json +1 -1
  32. package/pipeline/contract/fixtures/runs-failed.json +4 -1
  33. package/pipeline/contract/fixtures/runs-old-schema.json +3 -0
  34. package/pipeline/contract/fixtures/runs-pr-opened-redacted.json +4 -1
  35. package/pipeline/contract/fixtures/runs-pr-opened.json +4 -1
  36. package/pipeline/contract/fixtures/runs-running.json +4 -1
  37. package/pipeline/contract/manifest.json +28 -15
  38. package/pipeline/contract/types/index.d.ts +55 -3
  39. package/pipeline/lib/detach-self.mjs +95 -0
  40. package/pipeline/lib/public-mcp-servers.mjs +33 -0
  41. package/pipeline/lib/rotated-log.mjs +93 -0
  42. package/pipeline/lib/tls-trust.mjs +29 -0
  43. package/pipeline/lib/usage-lifecycle.mjs +9 -11
  44. package/pipeline/lib/usage-names.generated.mjs +614 -0
  45. package/pipeline/lib/usage-run-key.mjs +235 -0
  46. package/pipeline/lib/usage-vocab.mjs +210 -0
  47. package/pipeline/multi-agent-refs/analysis/intake.md +2 -2
  48. package/pipeline/multi-agent-refs/analysis/render.md +1 -1
  49. package/pipeline/multi-agent-refs/channels/generator.md +4 -5
  50. package/pipeline/multi-agent-refs/cross-cli-contract.md +3 -3
  51. package/pipeline/multi-agent-refs/design-check/scope-and-ledger.md +1 -1
  52. package/pipeline/multi-agent-refs/features/code-graph.md +146 -11
  53. package/pipeline/multi-agent-refs/features/code-intelligence.md +16 -14
  54. package/pipeline/multi-agent-refs/features/dev-critic.md +7 -7
  55. package/pipeline/multi-agent-refs/features/model-fallback.md +6 -4
  56. package/pipeline/multi-agent-refs/features/remote-control.md +252 -0
  57. package/pipeline/multi-agent-refs/features/review-delta.md +1 -1
  58. package/pipeline/multi-agent-refs/features/review-file-set.md +3 -3
  59. package/pipeline/multi-agent-refs/features/review-multi-repo.md +1 -1
  60. package/pipeline/multi-agent-refs/features/session-brief.md +42 -0
  61. package/pipeline/multi-agent-refs/features/skill-conformance.md +3 -3
  62. package/pipeline/multi-agent-refs/features/usage-reporting.md +252 -24
  63. package/pipeline/multi-agent-refs/help/en.md +3 -2
  64. package/pipeline/multi-agent-refs/help/tr.md +3 -2
  65. package/pipeline/multi-agent-refs/knowledge.md +1 -1
  66. package/pipeline/multi-agent-refs/orchestrator/dispatcher.md +1 -1
  67. package/pipeline/multi-agent-refs/phases/operations.md +2 -2
  68. package/pipeline/multi-agent-refs/phases/phase-0-init.md +13 -12
  69. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +4 -4
  70. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -0
  71. package/pipeline/multi-agent-refs/phases/phase-5-report.md +1 -1
  72. package/pipeline/multi-agent-refs/platform-parity.md +2 -2
  73. package/pipeline/multi-agent-refs/wiki-capture.md +3 -17
  74. package/pipeline/office/index.html +1207 -233
  75. package/pipeline/office/toolkit.json +1 -1
  76. package/pipeline/rules/outside-the-pipeline.md +1 -1
  77. package/pipeline/schemas/activity.schema.json +23 -0
  78. package/pipeline/schemas/agent-state.schema.json +6 -1
  79. package/pipeline/schemas/code-graph-calls.schema.json +254 -0
  80. package/pipeline/schemas/code-graph-docs.schema.json +223 -0
  81. package/pipeline/schemas/code-graph-infra.schema.json +227 -0
  82. package/pipeline/schemas/code-graph.schema.json +2 -2
  83. package/pipeline/schemas/examples/design-check-config.json +27 -0
  84. package/pipeline/schemas/learning-curve.schema.json +67 -0
  85. package/pipeline/schemas/office-jobs.json +69 -2
  86. package/pipeline/schemas/office-jobs.schema.json +8 -1
  87. package/pipeline/schemas/phases.json +5 -0
  88. package/pipeline/schemas/phases.schema.json +8 -0
  89. package/pipeline/schemas/prefs.schema.json +46 -12
  90. package/pipeline/schemas/runs-index.schema.json +17 -0
  91. package/pipeline/schemas/toolkit-path-params.json +84 -8
  92. package/pipeline/scripts/README.md +1 -0
  93. package/pipeline/scripts/_code-graph.mjs +184 -103
  94. package/pipeline/scripts/_contract-core.mjs +1 -1
  95. package/pipeline/scripts/_contract-routes-office.mjs +21 -0
  96. package/pipeline/scripts/_diff-impact.mjs +21 -2
  97. package/pipeline/scripts/_graph-sidecars.mjs +372 -0
  98. package/pipeline/scripts/_http-post.mjs +103 -115
  99. package/pipeline/scripts/_safe-read.mjs +57 -0
  100. package/pipeline/scripts/_skill-practices.mjs +26 -0
  101. package/pipeline/scripts/_strip-code.mjs +380 -0
  102. package/pipeline/scripts/activity-snapshot.mjs +13 -1
  103. package/pipeline/scripts/aggregate-metrics.mjs +3 -5
  104. package/pipeline/scripts/call-graph/index.mjs +78 -0
  105. package/pipeline/scripts/call-graph/lang/cpp.mjs +308 -0
  106. package/pipeline/scripts/call-graph/lang/csharp.mjs +130 -0
  107. package/pipeline/scripts/call-graph/lang/go.mjs +303 -0
  108. package/pipeline/scripts/call-graph/lang/java.mjs +370 -0
  109. package/pipeline/scripts/call-graph/lang/kotlin.mjs +397 -0
  110. package/pipeline/scripts/call-graph/lang/python.mjs +399 -0
  111. package/pipeline/scripts/call-graph/lang/rust.mjs +345 -0
  112. package/pipeline/scripts/call-graph/lang/shared.mjs +230 -0
  113. package/pipeline/scripts/call-graph/lang/swift.mjs +432 -0
  114. package/pipeline/scripts/call-graph/lang/typescript.mjs +692 -0
  115. package/pipeline/scripts/call-graph/lex.mjs +396 -0
  116. package/pipeline/scripts/call-graph/platform.mjs +86 -0
  117. package/pipeline/scripts/call-graph/profiles.mjs +89 -0
  118. package/pipeline/scripts/call-graph/resolve.mjs +1125 -0
  119. package/pipeline/scripts/call-graph/scan.mjs +267 -0
  120. package/pipeline/scripts/code-graph-rules/android.json +7 -2
  121. package/pipeline/scripts/code-graph-rules/cpp.json +99 -0
  122. package/pipeline/scripts/code-graph-rules/csharp.json +102 -0
  123. package/pipeline/scripts/code-graph-rules/go.json +2 -1
  124. package/pipeline/scripts/code-graph-rules/ios.json +3 -1
  125. package/pipeline/scripts/code-graph-rules/java.json +76 -0
  126. package/pipeline/scripts/code-graph-rules/node.json +7 -2
  127. package/pipeline/scripts/code-graph-rules/python.json +6 -2
  128. package/pipeline/scripts/code-graph-rules/rust.json +105 -0
  129. package/pipeline/scripts/contract-server.mjs +1 -0
  130. package/pipeline/scripts/feedback-send.mjs +26 -26
  131. package/pipeline/scripts/gate-ledger.mjs +2 -1
  132. package/pipeline/scripts/gen-usage-names.mjs +124 -0
  133. package/pipeline/scripts/graph-affected.mjs +109 -20
  134. package/pipeline/scripts/graph-build.mjs +95 -15
  135. package/pipeline/scripts/graph-export.mjs +272 -0
  136. package/pipeline/scripts/graph-hint.mjs +15 -2
  137. package/pipeline/scripts/graph-query.mjs +305 -26
  138. package/pipeline/scripts/graph-report.mjs +187 -1
  139. package/pipeline/scripts/health-report.mjs +3 -4
  140. package/pipeline/scripts/infra/docs.mjs +317 -0
  141. package/pipeline/scripts/infra/extract.mjs +998 -0
  142. package/pipeline/scripts/infra/graph.mjs +245 -0
  143. package/pipeline/scripts/infra/yaml-lite.mjs +311 -0
  144. package/pipeline/scripts/job-launch.mjs +67 -2
  145. package/pipeline/scripts/learning-curve.mjs +288 -178
  146. package/pipeline/scripts/log-metric.sh +10 -1
  147. package/pipeline/scripts/note-agent-event.mjs +3 -4
  148. package/pipeline/scripts/note-command-use.mjs +333 -0
  149. package/pipeline/scripts/note-command-use.sh +126 -0
  150. package/pipeline/scripts/note-mcp-call.sh +89 -0
  151. package/pipeline/scripts/note-mcp-failure.mjs +272 -1
  152. package/pipeline/scripts/note-session.sh +62 -3
  153. package/pipeline/scripts/note-skill-use.mjs +58 -2
  154. package/pipeline/scripts/office-build.mjs +115 -1
  155. package/pipeline/scripts/office-memory.mjs +14 -5
  156. package/pipeline/scripts/pair.mjs +333 -0
  157. package/pipeline/scripts/pre-push-check.sh +1 -1
  158. package/pipeline/scripts/remote/cbor.mjs +128 -0
  159. package/pipeline/scripts/remote/contract.mjs +98 -0
  160. package/pipeline/scripts/remote/handler.mjs +317 -0
  161. package/pipeline/scripts/remote/handles.mjs +57 -0
  162. package/pipeline/scripts/remote/lifecycle.mjs +186 -0
  163. package/pipeline/scripts/remote/listener.mjs +204 -0
  164. package/pipeline/scripts/remote/lockout.mjs +103 -0
  165. package/pipeline/scripts/remote/nonces.mjs +61 -0
  166. package/pipeline/scripts/remote/pairing.mjs +519 -0
  167. package/pipeline/scripts/remote/qr-encode.mjs +459 -0
  168. package/pipeline/scripts/remote/store.mjs +188 -0
  169. package/pipeline/scripts/remote/transport.mjs +211 -0
  170. package/pipeline/scripts/remote/verbs.json +70 -0
  171. package/pipeline/scripts/remote/verbs.mjs +217 -0
  172. package/pipeline/scripts/remote/webauthn.mjs +169 -0
  173. package/pipeline/scripts/remote/wire.mjs +364 -0
  174. package/pipeline/scripts/remote-listener.mjs +83 -0
  175. package/pipeline/scripts/route-learn.mjs +4 -4
  176. package/pipeline/scripts/run-kill.mjs +1 -1
  177. package/pipeline/scripts/run-write.mjs +13 -2
  178. package/pipeline/scripts/runs-index.mjs +30 -3
  179. package/pipeline/scripts/search-logs.sh +9 -0
  180. package/pipeline/scripts/session-brief.mjs +458 -0
  181. package/pipeline/scripts/session-brief.sh +130 -0
  182. package/pipeline/scripts/test-gap-rules/cpp.json +25 -0
  183. package/pipeline/scripts/test-gap-rules/csharp.json +20 -0
  184. package/pipeline/scripts/test-gap-rules/java.json +20 -0
  185. package/pipeline/scripts/test-gap-rules/rust.json +14 -0
  186. package/pipeline/scripts/token-budget-report.mjs +3 -2
  187. package/pipeline/scripts/uninstall.mjs +29 -0
  188. package/pipeline/scripts/usage-access.mjs +16 -31
  189. package/pipeline/scripts/usage-health.mjs +31 -62
  190. package/pipeline/scripts/usage-register-beacon.mjs +11 -22
  191. package/pipeline/scripts/usage-register.mjs +39 -29
  192. package/pipeline/scripts/usage-report.mjs +579 -178
  193. package/pipeline/scripts/validate-code-graph.mjs +361 -111
  194. package/pipeline/scripts/write-state.mjs +39 -0
  195. package/pipeline/skills/.skill-manifest.json +21 -17
  196. package/pipeline/skills/.skills-index.json +13 -2
  197. package/pipeline/skills/shared/README.md +5 -4
  198. package/pipeline/skills/shared/core/multi-agent-design-check/SKILL.md +1 -1
  199. package/pipeline/skills/shared/core/multi-agent-diff-explain/SKILL.md +3 -3
  200. package/pipeline/skills/shared/core/multi-agent-graph/SKILL.md +55 -21
  201. package/pipeline/skills/shared/core/multi-agent-pair/SKILL.md +41 -0
  202. package/pipeline/skills/shared/core/multi-agent-prune-prompts/SKILL.md +1 -1
  203. package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +3 -3
  204. package/pipeline/skills/shared/external/app-store-optimization/SKILL.md +2 -3
  205. package/pipeline/skills/shared/external/app-store-optimization/references/keyword-research-methodology.md +2 -2
  206. package/pipeline/skills/shared/external/app-store-optimization/references/product-page-variants.md +2 -2
  207. package/pipeline/skills/shared/external/app-store-review/SKILL.md +11 -4
  208. package/pipeline/skills/shared/external/build-settings-audit/SKILL.md +1 -1
  209. package/pipeline/skills/shared/external/build-time-benchmark/SKILL.md +5 -5
  210. package/pipeline/skills/shared/external/build-time-fixes/SKILL.md +5 -5
  211. package/pipeline/skills/shared/external/build-time-optimizer/SKILL.md +6 -6
  212. package/pipeline/skills/shared/external/free-llm-apis/references/providers.md +1 -0
  213. package/pipeline/skills/shared/external/ios-coding-standard/references/STANDARD.md +2 -2
  214. package/pipeline/skills/shared/external/ios-haptics/references/core-haptics.md +1 -1
  215. package/pipeline/skills/shared/external/localization-reuse-map/references/publish-and-snapshot.md +1 -1
  216. package/pipeline/skills/shared/external/package-build-audit/SKILL.md +3 -3
  217. package/pipeline/skills/shared/external/reverse-engineer-own-app/SKILL.md +2 -3
  218. package/pipeline/skills/shared/external/swift-compile-hotspots/SKILL.md +2 -2
  219. package/pipeline/skills/shared/external/weatherkit/SKILL.md +5 -6
  220. package/pipeline/skills/skills-index.md +3 -2
  221. package/docs/FIGMA_PIPELINE.md +0 -137
  222. package/pipeline/lib/identifier-scan.mjs +0 -156
  223. package/pipeline/scripts/publish-staged.mjs +0 -324
  224. package/pipeline/skills/shared/external/ios-coding-standard/scripts/check_structure.py +0 -765
@@ -0,0 +1,211 @@
1
+ /**
2
+ * transport.mjs - the only way this computer talks to the site: outbound
3
+ * HTTPS POSTs of JSON, nothing else.
4
+ *
5
+ * - The site comes from the usage reporting settings and is trusted only
6
+ * under the same rule the usage clients apply (usage-endpoint.mjs): the
7
+ * reporting site's own host or a host named in usageLog.trustedHosts.
8
+ * The usage token is attached only after that check.
9
+ * - https only, including to loopback: there is no plain-http path. The
10
+ * programmatic API takes an extra CA certificate (`ca`) so a test can
11
+ * serve a self-signed certificate; no preference or option widens the
12
+ * set of hosts or schemes.
13
+ * - The trust store is lib/tls-trust.mjs, the same one the usage
14
+ * transport uses: bundled roots plus the file NODE_EXTRA_CA_CERTS names,
15
+ * passed as `ca` so SSL_CERT_FILE, SSL_CERT_DIR, --use-openssl-ca and
16
+ * NODE_USE_SYSTEM_CA add nothing.
17
+ * - A redirect is never followed: any 3xx answer is an error, and its
18
+ * Location is not read, so the token cannot be sent anywhere else.
19
+ * - A response larger than the call's cap is cut off, and a response that
20
+ * trickles in is cut off at a deadline for the whole answer and a
21
+ * shorter one for the body once the headers have arrived.
22
+ * - Node's https only. There is no fallback of any kind: a certificate or
23
+ * TLS error, a refused connection or a timeout fails that request, is
24
+ * reported as such and is not retried through another client. Every
25
+ * request sets rejectUnauthorized explicitly and uses its own agent, so
26
+ * NODE_TLS_REJECT_UNAUTHORIZED and proxy variables of the environment
27
+ * change nothing.
28
+ *
29
+ * The token is never part of an error message, a log line or an argument
30
+ * list; it travels in a request header only.
31
+ *
32
+ * @module pipeline/scripts/remote/transport
33
+ */
34
+
35
+ import https from "node:https";
36
+ import { trustedRoots } from "../../lib/tls-trust.mjs";
37
+ import {
38
+ DEFAULT_ENDPOINT,
39
+ canonicalEndpoint,
40
+ registerUrlAllowed,
41
+ } from "../../lib/usage-endpoint.mjs";
42
+
43
+ export const HEADERS_GRACE_MS = 8000;
44
+ export const BODY_DEADLINE_MS = 10000;
45
+ export const MAX_RESPONSE_BYTES = 256 * 1024;
46
+
47
+ export class SiteError extends Error {
48
+ /** @param {"untrusted-host"|"redirect"|"too-large"|"timeout"|"network"|"tls"|"bad-json"|"no-token"} code */
49
+ constructor(code, message) {
50
+ super(message ?? code);
51
+ this.name = "SiteError";
52
+ this.code = code;
53
+ }
54
+ }
55
+
56
+ /**
57
+ * The site's origin from the preferences, or a SiteError when it is not one a
58
+ * credential may be sent to. `usageLog.endpoint` names the reporting
59
+ * endpoint; its origin is the site.
60
+ */
61
+ export function siteFromPrefs(prefs) {
62
+ const usageLog = prefs?.global?.usageLog ?? {};
63
+ const endpoint = canonicalEndpoint(String(usageLog.endpoint || DEFAULT_ENDPOINT).trim());
64
+ let url;
65
+ try {
66
+ url = new URL(endpoint);
67
+ } catch {
68
+ throw new SiteError("untrusted-host", "the reporting endpoint is not a URL");
69
+ }
70
+ if (url.protocol !== "https:") {
71
+ throw new SiteError("untrusted-host", "the site must be reached over https");
72
+ }
73
+ if (url.username || url.password) throw new SiteError("untrusted-host", "credentials in the URL");
74
+ if (!registerUrlAllowed(url.origin, usageLog.trustedHosts || [])) {
75
+ throw new SiteError("untrusted-host", `${url.hostname} is not a trusted host`);
76
+ }
77
+ return {
78
+ trustedHosts: usageLog.trustedHosts || [],
79
+ origin: url.origin,
80
+ host: url.host,
81
+ rpId: url.hostname,
82
+ apiBase: `${url.origin}/api/remote`,
83
+ };
84
+ }
85
+
86
+ function viaNode(url, { headers, body, deadlineMs, maxBytes, ca, bodyDeadlineMs }) {
87
+ const trust = ca ? [...trustedRoots(), ...[].concat(ca)] : trustedRoots();
88
+ return new Promise((resolve, reject) => {
89
+ let settled = false;
90
+ const timers = {};
91
+ let bodyTimer;
92
+ const finish = (fn, value) => {
93
+ if (settled) return;
94
+ settled = true;
95
+ clearTimeout(timers.overall);
96
+ clearTimeout(bodyTimer);
97
+ fn(value);
98
+ };
99
+ const req = https.request(
100
+ url,
101
+ {
102
+ method: "POST",
103
+ headers: { ...headers, "Content-Length": Buffer.byteLength(body) },
104
+ agent: new https.Agent({
105
+ keepAlive: false,
106
+ rejectUnauthorized: true,
107
+ ca: trust,
108
+ }),
109
+ rejectUnauthorized: true,
110
+ ca: trust,
111
+ },
112
+ (res) => {
113
+ const status = res.statusCode ?? 0;
114
+ if (status >= 300 && status < 400) {
115
+ res.destroy();
116
+ finish(resolve, { status, body: "" });
117
+ return;
118
+ }
119
+ bodyTimer = setTimeout(() => {
120
+ req.destroy();
121
+ finish(reject, new SiteError("timeout", "the response body was too slow"));
122
+ }, bodyDeadlineMs);
123
+ const chunks = [];
124
+ let total = 0;
125
+ res.on("data", (chunk) => {
126
+ total += chunk.length;
127
+ if (total > maxBytes) {
128
+ req.destroy();
129
+ finish(reject, new SiteError("too-large", "the response is over its cap"));
130
+ return;
131
+ }
132
+ chunks.push(chunk);
133
+ });
134
+ res.on("end", () =>
135
+ finish(resolve, { status, body: Buffer.concat(chunks).toString("utf8") }),
136
+ );
137
+ res.on("error", (err) => finish(reject, err));
138
+ },
139
+ );
140
+ timers.overall = setTimeout(() => {
141
+ req.destroy();
142
+ finish(reject, new SiteError("timeout", "the request timed out"));
143
+ }, deadlineMs);
144
+ req.on("error", (err) => finish(reject, err));
145
+ req.end(body);
146
+ });
147
+ }
148
+
149
+ const TLS_ERROR = /CERT|SSL|TLS|SELF_SIGNED|UNABLE_TO_VERIFY|HOSTNAME_MISMATCH/i;
150
+
151
+ /**
152
+ * A client bound to one site and one token source. `token` is a function so
153
+ * the secret is read when a request is made and never held in a field.
154
+ */
155
+ export function createSiteClient({ site, token, ca, bodyDeadlineMs = BODY_DEADLINE_MS }) {
156
+ const apiBase = new URL(site.apiBase);
157
+ return {
158
+ site,
159
+ /**
160
+ * POST `body` (an object) to /api/remote/<path>. Resolves to
161
+ * { status, json } where json is the parsed object or null for an empty
162
+ * body; rejects with a SiteError for a redirect, an oversized or slow
163
+ * answer, a network failure or a body that is not JSON.
164
+ */
165
+ async post(path, body, { waitMs = 0, maxBytes = MAX_RESPONSE_BYTES } = {}) {
166
+ if (!/^[a-z/]+$/.test(path)) throw new SiteError("untrusted-host", "bad path");
167
+ const url = new URL(`${apiBase.pathname}/${path}`, apiBase.origin);
168
+ if (url.origin !== apiBase.origin) throw new SiteError("untrusted-host", "origin changed");
169
+ const secret = token();
170
+ if (!secret) throw new SiteError("no-token", "no usage token on this machine");
171
+ const payload = JSON.stringify(body);
172
+ const headers = {
173
+ "content-type": "application/json",
174
+ accept: "application/json",
175
+ "x-usage-token": secret,
176
+ };
177
+ const deadlineMs = waitMs + HEADERS_GRACE_MS;
178
+ let answer;
179
+ try {
180
+ answer = await viaNode(url, {
181
+ headers,
182
+ body: payload,
183
+ deadlineMs,
184
+ maxBytes,
185
+ ca,
186
+ bodyDeadlineMs,
187
+ });
188
+ } catch (err) {
189
+ if (err instanceof SiteError) throw err;
190
+ const code = String(err?.code ?? "");
191
+ throw new SiteError(TLS_ERROR.test(code) ? "tls" : "network", code || "request failed");
192
+ }
193
+ if (answer.status >= 300 && answer.status < 400) {
194
+ throw new SiteError(
195
+ "redirect",
196
+ "the site answered with a redirect, which is never followed",
197
+ );
198
+ }
199
+ if (answer.body === "") return { status: answer.status, json: null };
200
+ try {
201
+ const json = JSON.parse(answer.body);
202
+ if (!json || typeof json !== "object" || Array.isArray(json))
203
+ throw new Error("not an object");
204
+ return { status: answer.status, json };
205
+ } catch {
206
+ if (answer.status >= 400) return { status: answer.status, json: null };
207
+ throw new SiteError("bad-json", "the answer is not a JSON object");
208
+ }
209
+ },
210
+ };
211
+ }
@@ -0,0 +1,70 @@
1
+ {
2
+ "version": 2,
3
+ "activePhase": 1,
4
+ "limits": {
5
+ "requestCiphertextBytes": 4096,
6
+ "replyCiphertextBytes": 16384,
7
+ "envelopeTtlSeconds": 120
8
+ },
9
+ "verbs": {
10
+ "list_runs": {
11
+ "phase": 1,
12
+ "mutating": false,
13
+ "target": "none",
14
+ "args": {
15
+ "scope": {
16
+ "type": "enum",
17
+ "values": ["active", "recent"],
18
+ "required": false,
19
+ "default": "active"
20
+ },
21
+ "limit": { "type": "integer", "min": 1, "max": 20, "required": false, "default": 10 }
22
+ }
23
+ },
24
+ "run_status": {
25
+ "phase": 1,
26
+ "mutating": false,
27
+ "target": "run",
28
+ "args": {
29
+ "run": { "type": "string", "pattern": "^[A-Za-z0-9_-]{1,64}$", "required": true }
30
+ }
31
+ },
32
+ "answer_question": {
33
+ "phase": 1,
34
+ "mutating": true,
35
+ "target": "run",
36
+ "args": {
37
+ "run": { "type": "string", "pattern": "^[A-Za-z0-9_-]{1,64}$", "required": true },
38
+ "question": { "type": "string", "pattern": "^[A-Za-z0-9._-]{1,64}$", "required": true },
39
+ "answer": {
40
+ "type": "idlist",
41
+ "pattern": "^[A-Za-z0-9._-]{1,64}$",
42
+ "minItems": 1,
43
+ "maxItems": 8,
44
+ "required": true
45
+ }
46
+ }
47
+ },
48
+ "stop_run": {
49
+ "phase": 1,
50
+ "mutating": true,
51
+ "target": "run",
52
+ "args": {
53
+ "run": { "type": "string", "pattern": "^[A-Za-z0-9_-]{1,64}$", "required": true }
54
+ }
55
+ },
56
+ "start_run": {
57
+ "phase": 2,
58
+ "mutating": true,
59
+ "target": "none",
60
+ "args": {
61
+ "command": {
62
+ "type": "enum",
63
+ "values": ["review-only", "analysis", "test", "health", "doctor"],
64
+ "required": true
65
+ },
66
+ "ref": { "type": "string", "pattern": "^[A-Za-z0-9#._/-]{1,80}$", "required": false }
67
+ }
68
+ }
69
+ }
70
+ }
@@ -0,0 +1,217 @@
1
+ /**
2
+ * verbs.mjs - the phase 1 verbs, run against this machine's own run state.
3
+ *
4
+ * list_runs the runs index (runs-index.mjs), trimmed to a few fields
5
+ * run_status one run's state, phase and pending question
6
+ * answer_question answer-question.mjs answerStateFile(): the answer is a
7
+ * list of option ids the run's pending question offered
8
+ * (one for a single question), exactly as for the office
9
+ * and the terminal; there is no free text
10
+ * stop_run stops the run's session with `claude stop <session id>`
11
+ * and nothing else: the worktree and the branch stay
12
+ *
13
+ * No verb takes a path, a command or a shell string, and none runs through a
14
+ * shell. The only process started is `claude stop` with a session id that is
15
+ * a UUID. start_run is not implemented here; the contract gate refuses it
16
+ * before this module is reached.
17
+ *
18
+ * Run text that leaves the machine is minimised to what the phone shows (a
19
+ * title, a state, a phase, the pending question and its options) and passes
20
+ * through the repo's secret and path scrubber first. File contents, diffs,
21
+ * branch names, URLs and costs are never part of a result.
22
+ *
23
+ * Every function here is a verb implementation: it takes the validated
24
+ * arguments, returns a JSON-able result or throws an Error whose `code` is a
25
+ * fixed lowercase identifier (the phone sees that code and nothing else).
26
+ *
27
+ * @module pipeline/scripts/remote/verbs
28
+ */
29
+
30
+ import { answerStateFile } from "../answer-question.mjs";
31
+ import { KillError, runFor, sessionAlive, stopSession } from "../run-kill.mjs";
32
+ import { selectRuns } from "../runs-index.mjs";
33
+ import { HandleTable } from "./handles.mjs";
34
+ import { unattendedLogsRoot } from "../../lib/pr-request-location.mjs";
35
+ import { realpathSync } from "node:fs";
36
+ import { sep } from "node:path";
37
+ import { redact } from "../../lib/redact.mjs";
38
+ import { redactCredentials, scrub } from "../_redact.mjs";
39
+
40
+ const QUESTION_ID = /^[A-Za-z0-9._-]{1,64}$/;
41
+ const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
42
+ const TITLE_CHARS = 60;
43
+ const LABEL_CHARS = 60;
44
+ const STATE_CHARS = 32;
45
+ const QUESTION_CHARS = 1000;
46
+ const LIST_QUESTION_CHARS = 200;
47
+ const LIST_BUDGET_BYTES = 15_000;
48
+ const MAX_OPTIONS = 8;
49
+
50
+ const fail = (code) => Object.assign(new Error(code), { code });
51
+
52
+ /**
53
+ * Plain text for the phone: control characters and line breaks become spaces,
54
+ * format characters (bidirectional controls, zero-width characters) are
55
+ * removed before the secret and path scrubbers run so they cannot hide a
56
+ * credential, then the text is clipped to `max` characters.
57
+ */
58
+ const clean = (text, max) => {
59
+ const plain = String(text ?? "")
60
+ .replace(/[\p{Cc}\p{Zl}\p{Zp}]+/gu, " ")
61
+ .replace(/\p{Cf}+/gu, "");
62
+ const safe = scrub(redactCredentials(redact(plain)))
63
+ .replace(/\s+/g, " ")
64
+ .trim();
65
+ return Array.from(safe).slice(0, max).join("");
66
+ };
67
+
68
+ const plainLabel = (value) =>
69
+ typeof value === "string" || typeof value === "number" ? clean(String(value), STATE_CHARS) : "";
70
+
71
+ /** The options a run offers that the phone can name: ids that fit the wire pattern, at most 8. */
72
+ function offeredOptions(q) {
73
+ return (Array.isArray(q?.options) ? q.options : [])
74
+ .filter((o) => typeof o?.id === "string" && QUESTION_ID.test(o.id))
75
+ .slice(0, MAX_OPTIONS);
76
+ }
77
+
78
+ /** null, or { id, text, kind, options } as wire specification 3.2 defines it. */
79
+ function questionOf(record, textChars = QUESTION_CHARS) {
80
+ const q = record.pendingQuestion;
81
+ if (!q || !QUESTION_ID.test(String(q.id))) return null;
82
+ const options = offeredOptions(q);
83
+ if (options.length === 0) return null;
84
+ return {
85
+ id: String(q.id),
86
+ text: clean(q.text, textChars),
87
+ kind: q.kind === "multi-select" ? "multi" : "single",
88
+ options: options.map((o) => ({ id: o.id, label: clean(o.label, LABEL_CHARS) })),
89
+ };
90
+ }
91
+
92
+ /** Drops runs from the end until the list fits one sealed reply; says how many went. */
93
+ function fitToReply(runs) {
94
+ const kept = [...runs];
95
+ const size = () =>
96
+ Buffer.byteLength(JSON.stringify({ ok: true, result: { runs: kept, omitted: 99 } }));
97
+ while (kept.length > 0 && size() > LIST_BUDGET_BYTES) kept.pop();
98
+ const omitted = runs.length - kept.length;
99
+ return omitted > 0 ? { runs: kept, omitted } : { runs: kept };
100
+ }
101
+
102
+ function locate(handle, ctx, deps) {
103
+ const runId = deps.handles.resolve(ctx.deviceId, handle);
104
+ if (runId === null) throw fail("unknown_run");
105
+ try {
106
+ return deps.runFor(runId);
107
+ } catch (err) {
108
+ if (err instanceof KillError || err?.code === "not-found") throw fail("unknown_run");
109
+ throw err;
110
+ }
111
+ }
112
+
113
+ const realOr = (p) => {
114
+ try {
115
+ return realpathSync(p);
116
+ } catch {
117
+ return p;
118
+ }
119
+ };
120
+
121
+ /**
122
+ * A run counts as unattended when its own state says autopilot, or when it
123
+ * was launched in the background (its directory is under the unattended log
124
+ * root). A verb that changes such a run is refused even when this listener is
125
+ * attended: the stricter of the listener's mode and the run's mode applies.
126
+ */
127
+ export function runIsUnattended(record, state) {
128
+ if (state?.autopilot === true) return true;
129
+ const root = realOr(unattendedLogsRoot());
130
+ const dir = realOr(String(record?.dir ?? ""));
131
+ return dir === root || dir.startsWith(root + sep);
132
+ }
133
+
134
+ const defaults = { selectRuns, answerStateFile, runFor, sessionAlive, stopSession };
135
+
136
+ /**
137
+ * The verb implementations. `deps` replaces the run-state functions in tests;
138
+ * `handles` is the per-device handle table (handles.mjs). Each verb gets the
139
+ * validated arguments and { deviceId }.
140
+ *
141
+ * @param {Partial<typeof defaults> & {handles?: import("./handles.mjs").HandleTable}} [override]
142
+ */
143
+ export function createExecutor(override = {}) {
144
+ const deps = { handles: new HandleTable(), ...defaults, ...override };
145
+ return {
146
+ handles: deps.handles,
147
+
148
+ list_runs({ scope, limit }, ctx) {
149
+ const records = deps.selectRuns().records;
150
+ const picked =
151
+ scope === "active"
152
+ ? records.filter(
153
+ (r) => (r.group !== "done" && r.group !== "unknown") || r.processAlive === true,
154
+ )
155
+ : records;
156
+ const ordered = [...picked].sort((a, b) =>
157
+ String(b.startedAt ?? "").localeCompare(String(a.startedAt ?? "")),
158
+ );
159
+ const runs = ordered.slice(0, limit).map((r) => ({
160
+ handle: deps.handles.issue(ctx.deviceId, r.taskId),
161
+ title: clean(r.title ?? "", TITLE_CHARS),
162
+ state: plainLabel(r.status ?? r.group ?? ""),
163
+ phase: plainLabel(r.currentPhase),
164
+ question: questionOf(r, LIST_QUESTION_CHARS),
165
+ }));
166
+ return fitToReply(runs);
167
+ },
168
+
169
+ run_status({ run }, ctx) {
170
+ const { record } = locate(run, ctx, deps);
171
+ return {
172
+ run: {
173
+ handle: run,
174
+ title: clean(record.title ?? "", TITLE_CHARS),
175
+ state: plainLabel(record.status ?? record.group ?? ""),
176
+ phase: plainLabel(record.currentPhase),
177
+ question: questionOf(record),
178
+ },
179
+ };
180
+ },
181
+
182
+ answer_question({ run, question, answer }, ctx) {
183
+ const { record, state, statePath } = locate(run, ctx, deps);
184
+ if (runIsUnattended(record, state)) throw fail("unattended");
185
+ const asked = questionOf(record);
186
+ if (!asked || asked.id !== question || !statePath) throw fail("unknown_question");
187
+ const offered = new Set(offeredOptions(record.pendingQuestion).map((o) => o.id));
188
+ const fits =
189
+ answer.every((id) => offered.has(id)) &&
190
+ (asked.kind === "multi" ? answer.length >= 1 : answer.length === 1);
191
+ if (!fits) throw fail("bad_answer");
192
+ const r = deps.answerStateFile(statePath, answer, { questionId: question });
193
+ if (r.code === 0) return { run, question, answered: true };
194
+ throw fail(ANSWER_REFUSAL[r.reason] ?? "failed");
195
+ },
196
+
197
+ stop_run({ run }, ctx) {
198
+ const { record, state } = locate(run, ctx, deps);
199
+ if (runIsUnattended(record, state)) throw fail("unattended");
200
+ const sessionId = state?.sessionId;
201
+ if (typeof sessionId !== "string" || !SESSION_ID.test(sessionId)) throw fail("no_session");
202
+ if (deps.sessionAlive(sessionId) === false) throw fail("not_running");
203
+ if (!deps.stopSession(sessionId)) throw fail("stop_failed");
204
+ return { run, state: "stopped" };
205
+ },
206
+ };
207
+ }
208
+
209
+ const ANSWER_REFUSAL = {
210
+ "no-state": "unknown_question",
211
+ "not-waiting": "unknown_question",
212
+ "wrong-question": "unknown_question",
213
+ "state-moved": "state_moved",
214
+ "no-answer": "bad_answer",
215
+ arity: "bad_answer",
216
+ "not-an-option": "bad_answer",
217
+ };
@@ -0,0 +1,169 @@
1
+ /**
2
+ * webauthn.mjs - verification of one passkey assertion against the public
3
+ * key pinned at pairing, restricted on purpose:
4
+ *
5
+ * - ES256 (COSE -7) on P-256 only; the COSE key must be exactly
6
+ * {1:2, 3:-7, -1:1, -2:x, -3:y} with a valid curve point;
7
+ * - clientDataJSON: type webauthn.get, the expected challenge (constant
8
+ * time), the pinned origin exactly, crossOrigin absent or false, no
9
+ * topOrigin;
10
+ * - authenticator data: rpIdHash of the pinned rpId, user presence and
11
+ * user verification both set, no attested-credential block;
12
+ * - signature over authenticatorData || SHA-256(clientDataJSON), DER;
13
+ * - a counter that does not move forward is refused, except the all-zero
14
+ * counter of authenticators that keep none;
15
+ * - every input is length-capped before it is parsed.
16
+ *
17
+ * Challenge freshness is the caller's: the challenge is recomputed from the
18
+ * envelope by wire.mjs verbChallenge(), so it is single use by construction
19
+ * (the sequence number is part of it and only moves forward).
20
+ *
21
+ * @module pipeline/scripts/remote/webauthn
22
+ */
23
+
24
+ import { createPublicKey, verify } from "node:crypto";
25
+ import { CborError, decodeCborExact } from "./cbor.mjs";
26
+ import { equalBytes, sha256 } from "./wire.mjs";
27
+
28
+ export const MAX_CLIENT_DATA_BYTES = 2048;
29
+ export const MAX_AUTHENTICATOR_DATA_BYTES = 1024;
30
+ export const MAX_SIGNATURE_BYTES = 80;
31
+ export const MAX_COSE_BYTES = 256;
32
+
33
+ const FLAG_UP = 0x01;
34
+ const FLAG_UV = 0x04;
35
+ const FLAG_AT = 0x40;
36
+ const FLAG_ED = 0x80;
37
+ const COSE_ALG_ES256 = -7;
38
+
39
+ export class WebAuthnError extends Error {
40
+ /**
41
+ * @param {"input"|"client_data"|"type"|"challenge"|"origin"|"authenticator_data"|"rp_id"|"user_presence"|"user_verification"|"algorithm"|"key"|"counter"|"signature"} code
42
+ */
43
+ constructor(code, message) {
44
+ super(message ?? code);
45
+ this.name = "WebAuthnError";
46
+ this.code = code;
47
+ }
48
+ }
49
+
50
+ function checkSize(bytes, max, what) {
51
+ if (!(bytes instanceof Uint8Array) || bytes.length === 0 || bytes.length > max) {
52
+ throw new WebAuthnError("input", `${what} size`);
53
+ }
54
+ }
55
+
56
+ /** The public key of a COSE_Key, which must be exactly an ES256 P-256 key. */
57
+ export function publicKeyFromCose(coseBytes) {
58
+ checkSize(coseBytes, MAX_COSE_BYTES, "COSE key");
59
+ let cose;
60
+ try {
61
+ cose = decodeCborExact(coseBytes);
62
+ } catch (err) {
63
+ if (err instanceof CborError) throw new WebAuthnError("key", err.message);
64
+ throw err;
65
+ }
66
+ if (!(cose instanceof Map) || cose.size !== 5) throw new WebAuthnError("key");
67
+ if (cose.get(1) !== 2) throw new WebAuthnError("key", "kty");
68
+ if (cose.get(3) !== COSE_ALG_ES256) throw new WebAuthnError("algorithm");
69
+ if (cose.get(-1) !== 1) throw new WebAuthnError("key", "crv");
70
+ const x = cose.get(-2);
71
+ const y = cose.get(-3);
72
+ if (
73
+ !(x instanceof Uint8Array) ||
74
+ !(y instanceof Uint8Array) ||
75
+ x.length !== 32 ||
76
+ y.length !== 32
77
+ ) {
78
+ throw new WebAuthnError("key", "coordinates");
79
+ }
80
+ try {
81
+ return createPublicKey({
82
+ key: {
83
+ kty: "EC",
84
+ crv: "P-256",
85
+ x: Buffer.from(x).toString("base64url"),
86
+ y: Buffer.from(y).toString("base64url"),
87
+ },
88
+ format: "jwk",
89
+ });
90
+ } catch {
91
+ throw new WebAuthnError("key", "not on curve");
92
+ }
93
+ }
94
+
95
+ function checkClientData(raw, expectedChallenge, rp) {
96
+ checkSize(raw, MAX_CLIENT_DATA_BYTES, "clientDataJSON");
97
+ let data;
98
+ try {
99
+ data = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(raw));
100
+ } catch {
101
+ throw new WebAuthnError("client_data");
102
+ }
103
+ if (!data || typeof data !== "object" || Array.isArray(data))
104
+ throw new WebAuthnError("client_data");
105
+ if (data.type !== "webauthn.get") throw new WebAuthnError("type");
106
+ if (
107
+ typeof data.challenge !== "string" ||
108
+ !equalBytes(Buffer.from(data.challenge), Buffer.from(expectedChallenge))
109
+ ) {
110
+ throw new WebAuthnError("challenge");
111
+ }
112
+ if (
113
+ typeof data.origin !== "string" ||
114
+ !equalBytes(Buffer.from(data.origin), Buffer.from(rp.origin))
115
+ ) {
116
+ throw new WebAuthnError("origin");
117
+ }
118
+ if (data.crossOrigin !== undefined && data.crossOrigin !== false) {
119
+ throw new WebAuthnError("origin", "cross-origin");
120
+ }
121
+ if (data.topOrigin !== undefined) throw new WebAuthnError("origin", "top origin");
122
+ }
123
+
124
+ /**
125
+ * Verifies one assertion. `publicKeyCose` is the key pinned at pairing,
126
+ * `expectedChallenge` the base64url of the challenge the computer recomputed,
127
+ * `rp` the pinned { rpId, origin }. Returns the new counter.
128
+ *
129
+ * @returns {{ signCount: number }}
130
+ */
131
+ export function verifyAssertion({
132
+ clientDataJSON,
133
+ authenticatorData,
134
+ signature,
135
+ expectedChallenge,
136
+ rp,
137
+ publicKeyCose,
138
+ storedSignCount,
139
+ }) {
140
+ checkClientData(clientDataJSON, expectedChallenge, rp);
141
+ checkSize(signature, MAX_SIGNATURE_BYTES, "signature");
142
+ checkSize(authenticatorData, MAX_AUTHENTICATOR_DATA_BYTES, "authenticatorData");
143
+ if (authenticatorData.length < 37) throw new WebAuthnError("authenticator_data");
144
+ const rpIdHash = authenticatorData.subarray(0, 32);
145
+ const flags = authenticatorData[32];
146
+ const signCount = Buffer.from(authenticatorData.subarray(33, 37)).readUInt32BE(0);
147
+ if (!equalBytes(rpIdHash, sha256(Buffer.from(rp.rpId, "utf8")))) throw new WebAuthnError("rp_id");
148
+ if ((flags & FLAG_UP) === 0) throw new WebAuthnError("user_presence");
149
+ if ((flags & FLAG_UV) === 0) throw new WebAuthnError("user_verification");
150
+ if ((flags & FLAG_AT) !== 0) throw new WebAuthnError("authenticator_data", "attested data");
151
+ if (authenticatorData.length > 37 && (flags & FLAG_ED) === 0) {
152
+ throw new WebAuthnError("authenticator_data", "trailing bytes");
153
+ }
154
+
155
+ const key = publicKeyFromCose(publicKeyCose);
156
+ const signed = Buffer.concat([authenticatorData, sha256(clientDataJSON)]);
157
+ let ok;
158
+ try {
159
+ ok = verify("sha256", signed, { key, dsaEncoding: "der" }, signature);
160
+ } catch {
161
+ ok = false;
162
+ }
163
+ if (!ok) throw new WebAuthnError("signature");
164
+
165
+ if ((signCount !== 0 || storedSignCount !== 0) && signCount <= storedSignCount) {
166
+ throw new WebAuthnError("counter");
167
+ }
168
+ return { signCount };
169
+ }