@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,204 @@
1
+ /**
2
+ * listener.mjs - the long-polling loop. It makes outbound HTTPS requests to
3
+ * the site and nothing else: no port is opened.
4
+ *
5
+ * The loop runs only while at least one device is pinned locally. It ends,
6
+ * and does not poll again until the person starts it, when:
7
+ *
8
+ * - no device is pinned (pair --off, pair --revoke, or the site stopped
9
+ * listing the last one);
10
+ * - the site answers 404, meaning the feature or this user's permission
11
+ * is off ("site-off");
12
+ * - the site refuses the usage token ("unauthorized").
13
+ *
14
+ * A poll hands out requests without removing them from the site's queue. The
15
+ * ids of the answer just processed go back in the next poll's `ack` (at most
16
+ * 10, kept on disk until a poll that carried them was answered), and a request
17
+ * that arrives twice is dropped by its sequence number in the handler.
18
+ *
19
+ * Each poll declares whether this machine is unattended. The site's list of
20
+ * active devices is used only to forget devices; a device missing from it is
21
+ * forgotten here at once and requests naming it are dropped, and a device is
22
+ * never added from it.
23
+ *
24
+ * @module pipeline/scripts/remote/listener
25
+ */
26
+
27
+ import { handleRequest } from "./handler.mjs";
28
+ import { NonceWindow } from "./nonces.mjs";
29
+ import {
30
+ acceptableAcks,
31
+ audit,
32
+ readDevices,
33
+ readPendingAck,
34
+ removeDevice,
35
+ writePendingAck,
36
+ } from "./store.mjs";
37
+
38
+ export const POLL_WAIT_MS = 20_000;
39
+ export const MIN_POLL_GAP_MS = 2_000;
40
+ export const MAX_BACKOFF_MS = 60_000;
41
+ export const MAX_ITEMS_PER_POLL = 10;
42
+ export const REPLY_BATCH = 5;
43
+ const RATE_LIMIT_PAUSE_MS = 30_000;
44
+
45
+ const realSleep = (ms) => new Promise((resolve) => globalThis.setTimeout(resolve, ms));
46
+
47
+ export const backoffMs = (failures) =>
48
+ Math.min(MAX_BACKOFF_MS, MIN_POLL_GAP_MS * 2 ** Math.min(failures, 10));
49
+
50
+ /**
51
+ * @param {object} o
52
+ * @param {object} o.env
53
+ * @param {{post: Function}} o.client
54
+ * @param {object} o.executor verb implementations (verbs.mjs createExecutor)
55
+ * @param {() => boolean} o.unattended
56
+ * @param {() => boolean} [o.shouldStop] checked before every poll
57
+ * @param {string} [o.version]
58
+ * @param {(ms: number) => Promise<void>} [o.sleep]
59
+ * @param {() => number} [o.now]
60
+ * @returns {Promise<"stopped"|"no-devices"|"site-off"|"no-permission"|"unauthorized">}
61
+ */
62
+ export async function runListener({
63
+ env,
64
+ client,
65
+ executor,
66
+ unattended,
67
+ nonces = new NonceWindow(),
68
+ shouldStop = () => false,
69
+ version = "",
70
+ sleep = realSleep,
71
+ now = Date.now,
72
+ }) {
73
+ let failures = 0;
74
+ let pendingAck = readPendingAck(env);
75
+ for (;;) {
76
+ if (shouldStop()) return "stopped";
77
+ const pinned = new Set(Object.keys(readDevices(env).devices));
78
+ if (pinned.size === 0) return "no-devices";
79
+ for (const id of executor.handles?.devices?.() ?? []) {
80
+ if (!pinned.has(id)) executor.handles.drop(id);
81
+ }
82
+
83
+ const startedAt = now();
84
+ let answer;
85
+ try {
86
+ answer = await client.post(
87
+ "poll",
88
+ {
89
+ unattended: unattended(),
90
+ nonce: nonces.issue(),
91
+ ...(pendingAck.length > 0 ? { ack: pendingAck } : {}),
92
+ wait: POLL_WAIT_MS,
93
+ version,
94
+ },
95
+ { waitMs: POLL_WAIT_MS },
96
+ );
97
+ } catch (err) {
98
+ if (err?.name !== "SiteError") throw err;
99
+ audit(env, { outcome: "dropped", reason: `site-${err.code}` });
100
+ await sleep(backoffMs(failures++));
101
+ continue;
102
+ }
103
+
104
+ if (answer.status === 404 || answer.status === 401) {
105
+ const why = await whyRefused(client);
106
+ if (why === "transient") {
107
+ audit(env, { outcome: "dropped", reason: "status-404" });
108
+ await sleep(backoffMs(failures++));
109
+ continue;
110
+ }
111
+ audit(env, { outcome: "site-off", reason: why });
112
+ return why === "site-off" ? "site-off" : why;
113
+ }
114
+ if (answer.status === 429) {
115
+ await sleep(RATE_LIMIT_PAUSE_MS);
116
+ continue;
117
+ }
118
+ if (answer.status !== 200 || !answer.json) {
119
+ audit(env, { outcome: "dropped", reason: `status-${answer.status}` });
120
+ await sleep(backoffMs(failures++));
121
+ continue;
122
+ }
123
+ failures = 0;
124
+
125
+ const { replies, ids } = await processAnswer(answer.json, {
126
+ env,
127
+ executor,
128
+ unattended,
129
+ now,
130
+ nonces,
131
+ });
132
+ pendingAck = acceptableAcks(ids);
133
+ writePendingAck(env, pendingAck);
134
+ if (Object.keys(readDevices(env).devices).length === 0) return "no-devices";
135
+ const outcome = await relayReplies(client, replies, env);
136
+ if (outcome === "site-off") return "site-off";
137
+
138
+ const spent = now() - startedAt;
139
+ if (replies.length === 0 && spent < MIN_POLL_GAP_MS) await sleep(MIN_POLL_GAP_MS - spent);
140
+ }
141
+ }
142
+
143
+ async function processAnswer(json, ctx) {
144
+ const { env } = ctx;
145
+ if (Array.isArray(json.activeDevices) && json.activeDevices.every((d) => typeof d === "string")) {
146
+ const active = new Set(json.activeDevices);
147
+ for (const id of Object.keys(readDevices(env).devices)) {
148
+ if (!active.has(id)) {
149
+ removeDevice(env, id);
150
+ ctx.executor.handles?.drop(id);
151
+ audit(env, { device: id, outcome: "revoked", reason: "site" });
152
+ }
153
+ }
154
+ }
155
+ const items = Array.isArray(json.envelopes) ? json.envelopes.slice(0, MAX_ITEMS_PER_POLL) : [];
156
+ const replies = [];
157
+ const ids = [];
158
+ for (const item of items) {
159
+ if (typeof item?.id === "string") ids.push(item.id);
160
+ try {
161
+ const result = await handleRequest(item, ctx);
162
+ if (result.reply) replies.push(result.reply);
163
+ } catch {
164
+ audit(env, { device: item?.deviceId ?? "", outcome: "dropped", reason: "internal" });
165
+ }
166
+ }
167
+ return { replies, ids };
168
+ }
169
+
170
+ async function relayReplies(client, replies, env) {
171
+ for (let i = 0; i < replies.length; i += REPLY_BATCH) {
172
+ let answer;
173
+ try {
174
+ answer = await client.post("reply", { replies: replies.slice(i, i + REPLY_BATCH) });
175
+ } catch (err) {
176
+ if (err?.name !== "SiteError") throw err;
177
+ audit(env, { outcome: "dropped", reason: `reply-${err.code}` });
178
+ continue;
179
+ }
180
+ if (answer.status === 404) return "site-off";
181
+ if (answer.status !== 200) audit(env, { outcome: "dropped", reason: `reply-${answer.status}` });
182
+ }
183
+ return "ok";
184
+ }
185
+
186
+ /**
187
+ * A 404 from poll means the feature is off, the permission is off, or the token
188
+ * was not accepted, and the site gives the same answer for all three. machine/status
189
+ * tells them apart: "site-off", "no-permission", "unauthorized" (a 404 there too),
190
+ * or "transient" when it cannot say, in which case the listener keeps trying.
191
+ */
192
+ async function whyRefused(client) {
193
+ try {
194
+ const status = await client.post("machine/status", {});
195
+ if (status.status === 404 || status.status === 401) return "unauthorized";
196
+ if (status.status !== 200 || !status.json) return "transient";
197
+ if (status.json.enabled === false) return "site-off";
198
+ if (status.json.permitted === false) return "no-permission";
199
+ return "transient";
200
+ } catch (err) {
201
+ if (err?.name !== "SiteError") throw err;
202
+ return "transient";
203
+ }
204
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * lockout.mjs - this computer's own limit on failed pairing confirmations
3
+ * (wire specification 4.5). The confirmation number protects the person
4
+ * against the site, so the site's own limit cannot be the one that counts.
5
+ *
6
+ * - after any mismatch the person is warned and the pairing is discarded;
7
+ * - the next pairing is refused for a cooldown that grows fourfold with each
8
+ * consecutive mismatch: 1 minute, 4, 16, 64, ... at most 24 hours;
9
+ * - at most 5 mismatches in the 24 hours counted from the first; after the
10
+ * fifth, no pairing starts until 24 hours after that first one;
11
+ * - a match ends the run of consecutive mismatches (and its cooldown) but
12
+ * not the 24 hour count;
13
+ * - the state is a 0600 file: a restart does not clear it, and nothing the
14
+ * site says relaxes it.
15
+ *
16
+ * @module pipeline/scripts/remote/lockout
17
+ */
18
+
19
+ import { join } from "node:path";
20
+ import { updateJsonFileSync } from "../../lib/json-file-lock.mjs";
21
+ import { readRegularJson } from "../../lib/regular-file.mjs";
22
+ import { ensureDir, remoteDir } from "./store.mjs";
23
+
24
+ export const DAY_MS = 24 * 60 * 60 * 1000;
25
+ export const BASE_COOLDOWN_MS = 60 * 1000;
26
+ export const MAX_COOLDOWN_MS = DAY_MS;
27
+ export const MAX_PER_DAY = 5;
28
+
29
+ export const lockoutFile = (env) => join(remoteDir(env), "lockout.json");
30
+
31
+ const fresh = () => ({ consecutive: 0, cooldownUntil: 0, dayStart: 0, dayCount: 0 });
32
+
33
+ function normalise(doc) {
34
+ const out = fresh();
35
+ for (const key of Object.keys(out)) {
36
+ const v = doc?.[key];
37
+ if (Number.isFinite(v) && v >= 0) out[key] = v;
38
+ }
39
+ return out;
40
+ }
41
+
42
+ function rollDay(state, now) {
43
+ if (state.dayCount > 0 && now - state.dayStart >= DAY_MS) {
44
+ state.dayCount = 0;
45
+ state.dayStart = 0;
46
+ state.consecutive = 0;
47
+ }
48
+ }
49
+
50
+ function verdictOf(state, now) {
51
+ if (state.dayCount >= MAX_PER_DAY) {
52
+ return { allowed: false, reason: "daily_cap", waitMs: state.dayStart + DAY_MS - now };
53
+ }
54
+ if (now < state.cooldownUntil) {
55
+ return { allowed: false, reason: "cooldown", waitMs: state.cooldownUntil - now };
56
+ }
57
+ return { allowed: true, reason: "", waitMs: 0 };
58
+ }
59
+
60
+ const readState = (env) => normalise(readRegularJson(lockoutFile(env), null));
61
+
62
+ function mutate(env, fn) {
63
+ ensureDir(env);
64
+ let result;
65
+ updateJsonFileSync(
66
+ lockoutFile(env),
67
+ (doc) => {
68
+ const state = normalise(doc);
69
+ result = fn(state);
70
+ return state;
71
+ },
72
+ { fallback: null, mode: 0o600 },
73
+ );
74
+ return result;
75
+ }
76
+
77
+ /** Whether a pairing may start now; `waitMs` is how long it must still wait. */
78
+ export function lockoutVerdict(env, now = Date.now()) {
79
+ const state = readState(env);
80
+ rollDay(state, now);
81
+ return verdictOf(state, now);
82
+ }
83
+
84
+ /** Records a mismatch. Returns the cooldown it started and the verdict after it. */
85
+ export function recordMismatch(env, now = Date.now()) {
86
+ return mutate(env, (state) => {
87
+ rollDay(state, now);
88
+ if (state.dayCount === 0) state.dayStart = now;
89
+ state.dayCount += 1;
90
+ state.consecutive += 1;
91
+ const cooldownMs = Math.min(MAX_COOLDOWN_MS, BASE_COOLDOWN_MS * 4 ** (state.consecutive - 1));
92
+ state.cooldownUntil = now + cooldownMs;
93
+ return { cooldownMs, verdict: verdictOf(state, now) };
94
+ });
95
+ }
96
+
97
+ /** A match ends the run of consecutive mismatches; the 24 hour count stays. */
98
+ export function recordMatch(env) {
99
+ mutate(env, (state) => {
100
+ state.consecutive = 0;
101
+ state.cooldownUntil = 0;
102
+ });
103
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * nonces.mjs - the computer's freshness nonces (wire specification 6.5).
3
+ *
4
+ * Every poll carries a fresh 16-byte nonce this computer made. The phone
5
+ * binds the newest one into the signed verb, so a request the site holds back
6
+ * can only be accepted while its nonce is still in this window: issued less
7
+ * than 120 seconds ago and not yet used. Age is measured on two clocks and a
8
+ * nonce is refused when either says it is too old: the monotonic clock cannot
9
+ * be set back but stands still while the machine sleeps, the wall clock keeps
10
+ * running through sleep but can be set. The window keeps the last 8 issued and
11
+ * lives in memory only; a restart voids every outstanding nonce.
12
+ *
13
+ * @module pipeline/scripts/remote/nonces
14
+ */
15
+
16
+ import { isFreshNonce, newFreshNonce } from "./wire.mjs";
17
+
18
+ export const NONCE_WINDOW_SIZE = 8;
19
+ export const NONCE_LIFETIME_MS = 120 * 1000;
20
+
21
+ /** Milliseconds on a clock that never runs backwards, so a changed system time cannot stretch a lifetime (it does not advance during sleep). */
22
+ export const monotonicNow = () => Number(process.hrtime.bigint() / 1_000_000n);
23
+
24
+ export class NonceWindow {
25
+ #issued = [];
26
+ #clock;
27
+ #wall;
28
+
29
+ constructor(clock = monotonicNow, wall = () => Date.now()) {
30
+ this.#clock = clock;
31
+ this.#wall = wall;
32
+ }
33
+
34
+ /** A new nonce, to go in the next poll body. */
35
+ issue() {
36
+ const value = newFreshNonce();
37
+ this.#issued.push({ value, at: this.#clock(), wallAt: this.#wall() });
38
+ if (this.#issued.length > NONCE_WINDOW_SIZE) this.#issued.shift();
39
+ return value;
40
+ }
41
+
42
+ /** Whether `value` was issued here, is still fresh and has not been used. */
43
+ holds(value) {
44
+ if (!isFreshNonce(value)) return false;
45
+ const now = this.#clock();
46
+ const wallNow = this.#wall();
47
+ return this.#issued.some(
48
+ (e) =>
49
+ e.value === value &&
50
+ now - e.at <= NONCE_LIFETIME_MS &&
51
+ wallNow - e.wallAt <= NONCE_LIFETIME_MS,
52
+ );
53
+ }
54
+
55
+ /** Spends `value`: true once, false for any later attempt. */
56
+ consume(value) {
57
+ if (!this.holds(value)) return false;
58
+ this.#issued = this.#issued.filter((e) => e.value !== value);
59
+ return true;
60
+ }
61
+ }