@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,364 @@
1
+ /**
2
+ * wire.mjs - the end-to-end wire format between a phone and this computer,
3
+ * written against the site's published specification (wire protocol version
4
+ * 3) and its test vectors, using node:crypto only.
5
+ *
6
+ * Nothing here talks to the site or touches the disk. The site relays the
7
+ * envelopes this module opens and seals and holds no key that opens one.
8
+ *
9
+ * @module pipeline/scripts/remote/wire
10
+ */
11
+
12
+ import {
13
+ createCipheriv,
14
+ createDecipheriv,
15
+ createECDH,
16
+ createHash,
17
+ createHmac,
18
+ hkdfSync,
19
+ randomBytes,
20
+ timingSafeEqual,
21
+ } from "node:crypto";
22
+
23
+ export const WIRE_VERSION = 3;
24
+ export const REQUEST_CT_MAX_BYTES = 4096;
25
+ export const REPLY_CT_MAX_BYTES = 16384;
26
+ export const PAD_BLOCK = 256;
27
+ export const SEQ_MAX = 0xffffffff;
28
+ export const PAIRING_SECRET_BYTES = 10;
29
+ export const PAIRING_CODE_CHARS = 16;
30
+ const TAG_BYTES = 16;
31
+ const NONCE_BYTES = 12;
32
+
33
+ export class WireError extends Error {
34
+ /** @param {"format"|"version"|"size"|"seq"|"replay"|"auth"|"key"|"code"} code */
35
+ constructor(code, message) {
36
+ super(message ?? code);
37
+ this.name = "WireError";
38
+ this.code = code;
39
+ }
40
+ }
41
+
42
+ const B64URL = /^[A-Za-z0-9_-]*$/;
43
+
44
+ export const b64uEncode = (bytes) => Buffer.from(bytes).toString("base64url");
45
+
46
+ /** Strict base64url: no padding, no other alphabet, no length that is 1 mod 4, canonical trailing bits. */
47
+ export function b64uDecode(text) {
48
+ if (typeof text !== "string" || !B64URL.test(text) || text.length % 4 === 1) {
49
+ throw new WireError("format", "base64url");
50
+ }
51
+ const out = Buffer.from(text, "base64url");
52
+ if (out.toString("base64url") !== text) throw new WireError("format", "base64url");
53
+ return out;
54
+ }
55
+
56
+ export const concat = (...parts) => Buffer.concat(parts.map((p) => Buffer.from(p)));
57
+
58
+ export function u32(n) {
59
+ const out = Buffer.alloc(4);
60
+ out.writeUInt32BE(n >>> 0);
61
+ return out;
62
+ }
63
+
64
+ export function u64(n) {
65
+ if (!Number.isSafeInteger(n) || n < 0) throw new WireError("format", "u64");
66
+ const out = Buffer.alloc(8);
67
+ out.writeBigUInt64BE(BigInt(n));
68
+ return out;
69
+ }
70
+
71
+ /** Each part as a 4-byte big-endian length followed by its bytes; strings are UTF-8. */
72
+ export function lp(...parts) {
73
+ const encoded = parts.map((p) =>
74
+ typeof p === "string" ? Buffer.from(p, "utf8") : Buffer.from(p),
75
+ );
76
+ return Buffer.concat(encoded.flatMap((p) => [u32(p.length), p]));
77
+ }
78
+
79
+ export const sha256 = (...parts) =>
80
+ createHash("sha256")
81
+ .update(concat(...parts))
82
+ .digest();
83
+ const hmac = (key, data) => createHmac("sha256", key).update(data).digest();
84
+
85
+ export function equalBytes(a, b) {
86
+ const x = Buffer.from(a);
87
+ const y = Buffer.from(b);
88
+ return x.length === y.length && timingSafeEqual(x, y);
89
+ }
90
+
91
+ function hkdf(ikm, salt, info, bytes) {
92
+ return Buffer.from(hkdfSync("sha256", ikm, salt, Buffer.from(info, "utf8"), bytes));
93
+ }
94
+
95
+ const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
96
+
97
+ export const newPairingSecret = () => randomBytes(PAIRING_SECRET_BYTES);
98
+
99
+ export function crockfordEncode(bytes) {
100
+ let bits = 0;
101
+ let value = 0;
102
+ let out = "";
103
+ for (const byte of bytes) {
104
+ value = (value << 8) | byte;
105
+ bits += 8;
106
+ while (bits >= 5) {
107
+ out += CROCKFORD[(value >>> (bits - 5)) & 31];
108
+ bits -= 5;
109
+ }
110
+ value &= (1 << bits) - 1;
111
+ }
112
+ if (bits > 0) out += CROCKFORD[(value << (5 - bits)) & 31];
113
+ return out;
114
+ }
115
+
116
+ /** The pairing code as shown to the person: 16 characters in groups of four. */
117
+ export function formatPairingCode(secret) {
118
+ if (secret.length !== PAIRING_SECRET_BYTES) throw new WireError("code");
119
+ return crockfordEncode(secret).replace(/(.{4})(?=.)/g, "$1-");
120
+ }
121
+
122
+ /** A typed code; I and L read as 1, O as 0, separators and spaces ignored. Null when it is not a code. */
123
+ export function parsePairingCode(text) {
124
+ const clean = String(text)
125
+ .toUpperCase()
126
+ .replace(/[\s-]/g, "")
127
+ .replace(/[IL]/g, "1")
128
+ .replace(/O/g, "0");
129
+ if (clean.length !== PAIRING_CODE_CHARS) return null;
130
+ let bits = 0;
131
+ let value = 0;
132
+ const out = [];
133
+ for (const ch of clean) {
134
+ const index = CROCKFORD.indexOf(ch);
135
+ if (index < 0) return null;
136
+ value = (value << 5) | index;
137
+ bits += 5;
138
+ if (bits >= 8) {
139
+ out.push((value >>> (bits - 8)) & 255);
140
+ bits -= 8;
141
+ }
142
+ value &= (1 << bits) - 1;
143
+ }
144
+ return out.length === PAIRING_SECRET_BYTES ? Buffer.from(out) : null;
145
+ }
146
+
147
+ /** The lookup token sent to the site and the key behind the confirmation number, which stays on the two devices. */
148
+ export function pairingKeys(secret) {
149
+ if (secret.length !== PAIRING_SECRET_BYTES) throw new WireError("code");
150
+ const salt = Buffer.from("mmc/3/pair", "utf8");
151
+ return {
152
+ lookup: b64uEncode(hkdf(secret, salt, "mmc/3/pair/lookup", 16)),
153
+ sasKey: hkdf(secret, salt, "mmc/3/pair/sas", 32),
154
+ };
155
+ }
156
+
157
+ /** Binds both public keys, the device, the passkey, the account, the machine and the site's rpId. */
158
+ export function transcriptHash(t) {
159
+ return sha256(
160
+ lp(
161
+ "mmc/3/transcript",
162
+ t.pairingId,
163
+ t.deviceId,
164
+ t.userId,
165
+ t.machineId,
166
+ t.rpId,
167
+ t.machinePub,
168
+ t.phonePub,
169
+ t.credentialId,
170
+ sha256(t.credentialPublicKey),
171
+ ),
172
+ );
173
+ }
174
+
175
+ const SAS_WORD_LIMIT = 4_294_000_000;
176
+ const SAS_MODULUS = 1_000_000;
177
+ export const SAS_DIGITS = 6;
178
+
179
+ /**
180
+ * The confirmation number both devices derive from the transcript and the
181
+ * pairing secret: 0 to 999999. Words at or above the largest multiple of 10^6
182
+ * below 2^32 are rejected so every number is equally likely.
183
+ */
184
+ export function sasNumber(sasKey, transcript) {
185
+ for (let counter = 0; ; counter++) {
186
+ const mac = hmac(sasKey, lp("mmc/3/sas", transcript, u32(counter)));
187
+ for (let i = 0; i < mac.length; i += 4) {
188
+ const word = mac.readUInt32BE(i);
189
+ if (word < SAS_WORD_LIMIT) return word % SAS_MODULUS;
190
+ }
191
+ }
192
+ }
193
+
194
+ /** The shape of the number the person types, and its text form (zero padded): the only place the digit count lives. */
195
+ export const SAS_PATTERN = /^[0-9]{6}$/;
196
+ export const sasText = (sasKey, transcript) =>
197
+ String(sasNumber(sasKey, transcript)).padStart(SAS_DIGITS, "0");
198
+
199
+ export function generateEcdhKeyPair() {
200
+ const ecdh = createECDH("prime256v1");
201
+ ecdh.generateKeys();
202
+ return { privateKey: ecdh.getPrivateKey(), publicRaw: ecdh.getPublicKey(null, "uncompressed") };
203
+ }
204
+
205
+ /** True when the 65 raw bytes are an uncompressed point on P-256. */
206
+ export function validPublicRaw(raw) {
207
+ if (!Buffer.isBuffer(raw) || raw.length !== 65 || raw[0] !== 4) return false;
208
+ try {
209
+ const probe = createECDH("prime256v1");
210
+ probe.generateKeys();
211
+ probe.computeSecret(raw);
212
+ return true;
213
+ } catch {
214
+ return false;
215
+ }
216
+ }
217
+
218
+ /** ECDH, then HKDF-SHA256 with the pairing transcript as salt: one AES-256-GCM key per direction and a run-tag key. */
219
+ export function deriveSessionKeys(privateKey, peerPublicRaw, transcript) {
220
+ if (!validPublicRaw(Buffer.from(peerPublicRaw))) throw new WireError("key", "public key");
221
+ const ecdh = createECDH("prime256v1");
222
+ ecdh.setPrivateKey(privateKey);
223
+ const shared = ecdh.computeSecret(Buffer.from(peerPublicRaw));
224
+ return {
225
+ p2m: hkdf(shared, transcript, "mmc/3/key/p2m", 32),
226
+ m2p: hkdf(shared, transcript, "mmc/3/key/m2p", 32),
227
+ tag: hkdf(shared, transcript, "mmc/3/key/runtag", 32),
228
+ };
229
+ }
230
+
231
+ const FRESH_NONCE = /^[A-Za-z0-9_-]{22}$/;
232
+
233
+ /** A computer nonce as it travels: 22 base64url characters of 16 bytes. */
234
+ export function isFreshNonce(value) {
235
+ if (typeof value !== "string" || !FRESH_NONCE.test(value)) return false;
236
+ try {
237
+ return b64uDecode(value).length === 16;
238
+ } catch {
239
+ return false;
240
+ }
241
+ }
242
+
243
+ export const newFreshNonce = () => b64uEncode(randomBytes(16));
244
+
245
+ function aad(h) {
246
+ if (h.dir === "p2m" ? !isFreshNonce(h.cn) : h.cn !== undefined && h.cn !== "") {
247
+ throw new WireError("format", "cn");
248
+ }
249
+ return lp("mmc/3/aad", h.dir, h.deviceId, h.machineId, h.verb, u64(h.seq), u64(h.re), h.cn ?? "");
250
+ }
251
+
252
+ function checkSeq(seq) {
253
+ if (!Number.isInteger(seq) || seq < 1 || seq > SEQ_MAX) throw new WireError("seq");
254
+ }
255
+
256
+ export const maxCiphertext = (dir) => (dir === "p2m" ? REQUEST_CT_MAX_BYTES : REPLY_CT_MAX_BYTES);
257
+
258
+ function frame(payload, maxCt) {
259
+ const json = Buffer.from(JSON.stringify(payload), "utf8");
260
+ const padded = Math.ceil((2 + json.length) / PAD_BLOCK) * PAD_BLOCK;
261
+ if (json.length > 0xffff || padded + TAG_BYTES > maxCt) throw new WireError("size");
262
+ const out = Buffer.alloc(padded);
263
+ out.writeUInt16BE(json.length, 0);
264
+ json.copy(out, 2);
265
+ return out;
266
+ }
267
+
268
+ function unframe(plain) {
269
+ if (plain.length < 2 || plain.length % PAD_BLOCK !== 0) throw new WireError("format", "frame");
270
+ const length = plain.readUInt16BE(0);
271
+ if (2 + length > plain.length) throw new WireError("format", "frame length");
272
+ for (let i = 2 + length; i < plain.length; i++) {
273
+ if (plain[i] !== 0) throw new WireError("format", "frame padding");
274
+ }
275
+ try {
276
+ return JSON.parse(
277
+ new TextDecoder("utf-8", { fatal: true }).decode(plain.subarray(2, 2 + length)),
278
+ );
279
+ } catch {
280
+ throw new WireError("format", "payload");
281
+ }
282
+ }
283
+
284
+ /** Encrypts a JSON payload under a fresh random 96-bit nonce; `nonce` exists for the published vectors only. */
285
+ export function seal(key, header, payload, nonce = randomBytes(NONCE_BYTES)) {
286
+ checkSeq(header.seq);
287
+ if (header.dir === "p2m" ? header.re !== 0 : !(header.re >= 1)) throw new WireError("seq", "re");
288
+ if (nonce.length !== NONCE_BYTES) throw new WireError("size");
289
+ const cipher = createCipheriv("aes-256-gcm", key, nonce, { authTagLength: TAG_BYTES });
290
+ cipher.setAAD(aad(header));
291
+ const body = Buffer.concat([
292
+ cipher.update(frame(payload, maxCiphertext(header.dir))),
293
+ cipher.final(),
294
+ ]);
295
+ const envelope = {
296
+ v: WIRE_VERSION,
297
+ seq: header.seq,
298
+ n: b64uEncode(nonce),
299
+ ct: b64uEncode(Buffer.concat([body, cipher.getAuthTag()])),
300
+ };
301
+ if (header.dir === "m2p") envelope.re = header.re;
302
+ else envelope.cn = header.cn;
303
+ return envelope;
304
+ }
305
+
306
+ /** Decrypts and authenticates an envelope against its header; any tamper, wrong key or wrong header is WireError("auth"). */
307
+ export function open(key, header, envelope) {
308
+ if (!envelope || typeof envelope !== "object" || envelope.v !== WIRE_VERSION) {
309
+ throw new WireError("version");
310
+ }
311
+ if (envelope.seq !== header.seq) throw new WireError("seq", "header mismatch");
312
+ const nonce = b64uDecode(envelope.n);
313
+ const ct = b64uDecode(envelope.ct);
314
+ if (
315
+ nonce.length !== NONCE_BYTES ||
316
+ ct.length < TAG_BYTES ||
317
+ ct.length > maxCiphertext(header.dir)
318
+ ) {
319
+ throw new WireError("size");
320
+ }
321
+ let plain;
322
+ try {
323
+ const decipher = createDecipheriv("aes-256-gcm", key, nonce, { authTagLength: TAG_BYTES });
324
+ decipher.setAAD(aad(header));
325
+ decipher.setAuthTag(ct.subarray(ct.length - TAG_BYTES));
326
+ plain = Buffer.concat([
327
+ decipher.update(ct.subarray(0, ct.length - TAG_BYTES)),
328
+ decipher.final(),
329
+ ]);
330
+ } catch {
331
+ throw new WireError("auth");
332
+ }
333
+ return unframe(plain);
334
+ }
335
+
336
+ /** 11 characters naming a handle without revealing it: HMAC-SHA256 under the tag key, first 8 bytes. */
337
+ export function runTag(tagKey, run) {
338
+ if (!run) return "";
339
+ return b64uEncode(hmac(tagKey, Buffer.from(run, "utf8")).subarray(0, 8));
340
+ }
341
+
342
+ /**
343
+ * The WebAuthn challenge of one verb: a server nonce plus a hash of the verb,
344
+ * the run tag, the sequence number, the payload ciphertext and this
345
+ * computer's freshness nonce.
346
+ */
347
+ export function verbChallenge(i) {
348
+ checkSeq(i.seq);
349
+ if (!isFreshNonce(i.envelope.cn)) throw new WireError("format", "cn");
350
+ const payload = sha256(b64uDecode(i.envelope.n), b64uDecode(i.envelope.ct));
351
+ return sha256(
352
+ lp(
353
+ "mmc/3/verb-challenge",
354
+ i.nonce,
355
+ i.deviceId,
356
+ i.machineId,
357
+ i.verb,
358
+ i.runTag,
359
+ u64(i.seq),
360
+ payload,
361
+ b64uDecode(i.envelope.cn),
362
+ ),
363
+ );
364
+ }
@@ -0,0 +1,83 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @file remote-listener.mjs - the background process behind remote control.
4
+ * Started by `pair` after a successful pairing; do not run it by hand.
5
+ *
6
+ * It long-polls the site over HTTPS (outbound only, no port is opened),
7
+ * verifies every request itself (remote/handler.mjs) and answers sealed to
8
+ * the paired phone. It ends when no device is pinned, when the site says the
9
+ * feature is off for this user, or when `pair --off` stops it. Stop it with
10
+ * `pair --off`; its state is under the autopilot root in remote/.
11
+ *
12
+ * Exit: 0 ended normally, 1 could not start.
13
+ */
14
+
15
+ import { loadPrefs, prefsPath } from "../lib/prefs-value.mjs";
16
+ import { resolveUsageToken } from "../lib/usage-token.mjs";
17
+ import { isUnattended } from "../lib/unattended.mjs";
18
+ import { exitOnHelp } from "../lib/cli-help.mjs";
19
+ import { invokedDirectly } from "../lib/invoked-directly.mjs";
20
+ import { runMain } from "../lib/fatal.mjs";
21
+ import { runListener } from "./remote/listener.mjs";
22
+ import { claimInstance, releaseInstance, stillOwner } from "./remote/lifecycle.mjs";
23
+ import { audit, readDevices } from "./remote/store.mjs";
24
+ import { SiteError, createSiteClient, siteFromPrefs } from "./remote/transport.mjs";
25
+ import { NonceWindow } from "./remote/nonces.mjs";
26
+ import { createExecutor } from "./remote/verbs.mjs";
27
+
28
+ exitOnHelp(import.meta.url);
29
+
30
+ const TOKEN_TTL_MS = 5 * 60 * 1000;
31
+
32
+ /** A token reader that asks the credential store at most once per TTL. */
33
+ export function cachedToken(prefs, env, read = resolveUsageToken) {
34
+ let value = "";
35
+ let at = 0;
36
+ return () => {
37
+ if (!value || Date.now() - at > TOKEN_TTL_MS) {
38
+ value = read(prefs?.global, { env });
39
+ at = Date.now();
40
+ }
41
+ return value;
42
+ };
43
+ }
44
+
45
+ export async function main(env = process.env, overrides = {}) {
46
+ const prefs = loadPrefs(prefsPath(env));
47
+ let site;
48
+ try {
49
+ site = overrides.site ?? siteFromPrefs(prefs);
50
+ } catch (err) {
51
+ audit(env, { outcome: "dropped", reason: err instanceof SiteError ? err.code : "site" });
52
+ return 1;
53
+ }
54
+ if (Object.keys(readDevices(env).devices).length === 0) return 0;
55
+ if (!claimInstance(env)) return 0;
56
+
57
+ const shutdown = () => {
58
+ releaseInstance(env);
59
+ audit(env, { outcome: "listener-stop", reason: "signal" });
60
+ process.exit(0);
61
+ };
62
+ process.once("SIGTERM", shutdown);
63
+ process.once("SIGINT", shutdown);
64
+
65
+ const client = createSiteClient({ site, token: cachedToken(prefs, env) });
66
+ const ended = await runListener({
67
+ env,
68
+ client,
69
+ executor: createExecutor(),
70
+ nonces: new NonceWindow(),
71
+ unattended: () => isUnattended(env),
72
+ shouldStop: () => !stillOwner(env),
73
+ });
74
+ audit(env, { outcome: "listener-stop", reason: ended });
75
+ releaseInstance(env);
76
+ return 0;
77
+ }
78
+
79
+ if (invokedDirectly(import.meta.url)) {
80
+ runMain("remote-listener", async () => {
81
+ process.exitCode = await main();
82
+ });
83
+ }
@@ -70,13 +70,14 @@
70
70
  * 10 promote kept the current policy; 2 usage error or no objective signal.
71
71
  */
72
72
 
73
- import { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
73
+ import { appendFileSync, copyFileSync, mkdirSync } from "node:fs";
74
74
  import { homedir } from "node:os";
75
75
  import { join } from "node:path";
76
76
 
77
77
  import { ArgsError, parseArgs, unknownSubcommand } from "../lib/args.mjs";
78
78
  import { exitOnHelp } from "../lib/cli-help.mjs";
79
79
  import { invokedDirectly } from "../lib/invoked-directly.mjs";
80
+ import { readRotatedLines, rotatedExists } from "../lib/rotated-log.mjs";
80
81
  import { applyIsotonic, fitIsotonic } from "../lib/isotonic.mjs";
81
82
  import { withFileLockSync, writeJsonAtomicSync } from "../lib/json-file-lock.mjs";
82
83
  import { loadGlobalPrefs, prefsPath } from "../lib/prefs-value.mjs";
@@ -364,10 +365,9 @@ const storeDir = (env = process.env) =>
364
365
  env.ROUTE_LEARN_DIR || join(env.HOME || homedir(), ".claude", "state", "route-learn");
365
366
 
366
367
  function readRows(file) {
367
- if (!existsSync(file)) return [];
368
+ if (!rotatedExists(file)) return [];
368
369
  const out = [];
369
- for (const line of readFileSync(file, "utf8").split("\n")) {
370
- if (!line.trim()) continue;
370
+ for (const line of readRotatedLines(file)) {
371
371
  try {
372
372
  out.push(JSON.parse(line));
373
373
  } catch {
@@ -135,7 +135,7 @@ export function killPreview(taskId) {
135
135
  };
136
136
  }
137
137
 
138
- function stopSession(sessionId) {
138
+ export function stopSession(sessionId) {
139
139
  try {
140
140
  execFileSync(resolveClaudeBin(), ["stop", sessionId], {
141
141
  stdio: ["ignore", "ignore", "ignore"],
@@ -59,6 +59,7 @@ import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
59
59
  import { exitOnHelp } from "../lib/cli-help.mjs";
60
60
  import { invokedDirectly } from "../lib/invoked-directly.mjs";
61
61
  import { unattendedRunRoot } from "../lib/pr-request-location.mjs";
62
+ import { tightenMode, withRotationLock } from "./note-skill-use.mjs";
62
63
  import {
63
64
  appendFileSafe,
64
65
  createExclusive,
@@ -278,8 +279,17 @@ export function abandon(state, reason, opts = {}) {
278
279
  export function rotate(path, maxBytes, opts = {}) {
279
280
  const st = statSafe(path, opts);
280
281
  if (!st || st.size < maxBytes) return false;
281
- renameSafe(path, `${basename(path)}.1`, opts);
282
- return true;
282
+ // Under the same lock the other log writers take, and with the size read
283
+ // again once it is held: a second writer that saw the same full file must not
284
+ // move the fresh one over the generation the first just made.
285
+ return (
286
+ withRotationLock(path, opts, () => {
287
+ const again = statSafe(path, opts);
288
+ if (!again || again.size < maxBytes) return false;
289
+ renameSafe(path, `${basename(path)}.1`, opts);
290
+ return true;
291
+ }) ?? false
292
+ );
283
293
  }
284
294
 
285
295
  const REASONS = {
@@ -336,6 +346,7 @@ export function main(argv, { env = process.env, input = stdin } = {}) {
336
346
  case "append":
337
347
  mkdirSafe(dirname(path), opts);
338
348
  appendFileSafe(path, input(), opts);
349
+ tightenMode(path);
339
350
  return 0;
340
351
  case "read": {
341
352
  const max = bytes("--max-bytes");
@@ -46,7 +46,7 @@
46
46
  * @module pipeline/scripts/runs-index
47
47
  */
48
48
 
49
- import { existsSync, readFileSync, realpathSync } from "node:fs";
49
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
50
50
  import { readRegularFile } from "../lib/regular-file.mjs";
51
51
  import { join } from "node:path";
52
52
  import { costUsd } from "./_cost.mjs";
@@ -82,7 +82,7 @@ const PHASE_WAITING_FROM = PHASE_CONTRACT.thresholds.waitingFromPhase;
82
82
  */
83
83
  const LAST_PHASE = PHASE_CONTRACT.phases[PHASE_CONTRACT.phases.length - 1].id;
84
84
 
85
- export const CONTRACT_VERSION = "1.4.0";
85
+ export const CONTRACT_VERSION = "1.5.0";
86
86
 
87
87
  const STATE_MAX_BYTES = 16 * 1024 * 1024;
88
88
 
@@ -414,6 +414,28 @@ function groupOf(state) {
414
414
  return "stopped";
415
415
  }
416
416
 
417
+ /**
418
+ * When a run in the waiting group began to wait. The state's own `waitingSince`
419
+ * (stamped when the run parked) is exact; a state written before that field
420
+ * existed falls back to the file's modification time, which any rewrite moves,
421
+ * so it is reported as approximate. Null for a run outside the waiting group
422
+ * and for one whose state cannot be read.
423
+ *
424
+ * @returns {{at: string|null, source: "state"|"file-time"|null}}
425
+ */
426
+ function waitingSinceOf(state, statePath, group) {
427
+ const none = { at: null, source: null };
428
+ if (group !== "waiting" || !state || typeof state !== "object") return none;
429
+ const own = Date.parse(state.waitingSince || "");
430
+ if (Number.isFinite(own)) return { at: new Date(own).toISOString(), source: "state" };
431
+ if (!statePath) return none;
432
+ try {
433
+ return { at: statSync(statePath).mtime.toISOString(), source: "file-time" };
434
+ } catch {
435
+ return none;
436
+ }
437
+ }
438
+
417
439
  /**
418
440
  * The question a run stopped on, in the shape answer-question.mjs accepts an
419
441
  * answer to, or null. Only a run with `waitingFor: "question"` has one: a stale
@@ -460,6 +482,8 @@ export function buildIndex() {
460
482
  const currentPhase = Number.isFinite(Number(state?.currentPhase))
461
483
  ? Number(state.currentPhase)
462
484
  : null;
485
+ const group = groupOf(state);
486
+ const waited = waitingSinceOf(state, statePath, group);
463
487
  return {
464
488
  taskId: run.taskId,
465
489
  project: run.project ?? run.projectHint ?? null,
@@ -500,7 +524,10 @@ export function buildIndex() {
500
524
  sessionId: typeof state?.sessionId === "string" ? state.sessionId : null,
501
525
  waitingFor: typeof state?.waitingFor === "string" ? state.waitingFor : null,
502
526
  pendingQuestion: questionOf(state),
503
- group: groupOf(state),
527
+ waitingSince: waited.at,
528
+ waitingSinceSource: waited.source,
529
+ finishedAt: typeof state?.finishedAt === "string" ? state.finishedAt : null,
530
+ group,
504
531
  phases: phases.phases,
505
532
  tokens: phases.tokens,
506
533
  estUsd: phases.estUsd,
@@ -21,6 +21,8 @@
21
21
  # --json JSON output (for automation)
22
22
  # --tsv Tab-separated output (for pipelines)
23
23
  # --limit N Max tasks to return (default 20)
24
+ # -- End of flags: everything after it is the query, even
25
+ # a word that starts with a dash
24
26
  # --help Show this help
25
27
  #
26
28
  # Exit codes:
@@ -72,6 +74,13 @@ while [ $# -gt 0 ]; do
72
74
  --tsv) TSV=1; shift ;;
73
75
  --semantic) SEMANTIC=1; shift ;;
74
76
  --limit) need_value "$@"; LIMIT="$2"; shift 2 ;;
77
+ --)
78
+ shift
79
+ while [ $# -gt 0 ]; do
80
+ if [ -z "$QUERY" ]; then QUERY="$1"; else QUERY="$QUERY $1"; fi
81
+ shift
82
+ done
83
+ ;;
75
84
  --help|-h)
76
85
  awk 'NR==1{next} /^[^#]/{exit} {sub(/^# ?/,""); print}' "$0"
77
86
  exit 0