counterparts 0.3.0 → 0.3.2

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 (207) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/docs/module-map.md +2 -0
  3. package/package.json +2 -1
  4. package/src/adapters/claude-code/CONTRACT.md +2 -1
  5. package/src/adapters/claude-code/NOTES.md +90 -2
  6. package/src/adapters/claude-code/bin/hook.ts +17 -2
  7. package/src/adapters/claude-code/bin/runner.ts +4 -1
  8. package/src/adapters/claude-code/config.ts +23 -0
  9. package/src/adapters/claude-code/doctor.ts +148 -26
  10. package/src/adapters/claude-code/hooks.ts +37 -12
  11. package/src/adapters/claude-code/index.ts +2 -0
  12. package/src/adapters/claude-code/standdown.ts +12 -1
  13. package/src/adapters/claude-code/transcript.ts +79 -6
  14. package/src/adapters/cli/INTERFACE-GAPS.md +4 -0
  15. package/src/adapters/cli/commands.ts +209 -61
  16. package/src/adapters/cli/export.ts +27 -3
  17. package/src/adapters/cli/help.ts +22 -8
  18. package/src/adapters/cli/install.ts +3 -5
  19. package/src/adapters/cli/mechanisms.ts +295 -0
  20. package/src/adapters/cli/repair-dates.ts +3 -1
  21. package/src/adapters/cli/snapshot.ts +4 -27
  22. package/src/adapters/dashboard/CONTRACT.md +13 -9
  23. package/src/adapters/dashboard/INTERFACE-GAPS.md +4 -0
  24. package/src/adapters/dashboard/NOTES.md +3 -2
  25. package/src/adapters/dashboard/activity.ts +2 -1
  26. package/src/adapters/dashboard/bin/dashboard.ts +18 -3
  27. package/src/adapters/dashboard/upgrade.ts +23 -0
  28. package/src/adapters/dashboard/web/README.md +153 -0
  29. package/src/adapters/dashboard/web/actions.ts +631 -0
  30. package/src/adapters/dashboard/web/app.html +40 -1703
  31. package/src/adapters/dashboard/web/app.js +55 -0
  32. package/src/adapters/dashboard/web/mechanisms/association/index.js +15 -0
  33. package/src/adapters/dashboard/web/mechanisms/association/panel.js +17 -0
  34. package/src/adapters/dashboard/web/mechanisms/consolidation/index.js +15 -0
  35. package/src/adapters/dashboard/web/mechanisms/consolidation/panel.js +23 -0
  36. package/src/adapters/dashboard/web/mechanisms/decay/index.js +15 -0
  37. package/src/adapters/dashboard/web/mechanisms/decay/panel.js +45 -0
  38. package/src/adapters/dashboard/web/mechanisms/emotional/index.js +15 -0
  39. package/src/adapters/dashboard/web/mechanisms/episodic-semantic/index.js +15 -0
  40. package/src/adapters/dashboard/web/mechanisms/index.js +60 -0
  41. package/src/adapters/dashboard/web/mechanisms/interference/index.js +15 -0
  42. package/src/adapters/dashboard/web/mechanisms/picture.js +28 -0
  43. package/src/adapters/dashboard/web/mechanisms/prospective/index.js +15 -0
  44. package/src/adapters/dashboard/web/mechanisms/reconsolidation/index.js +15 -0
  45. package/src/adapters/dashboard/web/mechanisms/reconsolidation/panel.js +15 -0
  46. package/src/adapters/dashboard/web/mechanisms/regions.js +30 -0
  47. package/src/adapters/dashboard/web/mechanisms/retrieval/index.js +15 -0
  48. package/src/adapters/dashboard/web/mechanisms/retrieval/panel.js +20 -0
  49. package/src/adapters/dashboard/web/mechanisms/salience/index.js +15 -0
  50. package/src/adapters/dashboard/web/mechanisms/salience/panel.js +14 -0
  51. package/src/adapters/dashboard/web/mechanisms/schema/index.js +15 -0
  52. package/src/adapters/dashboard/web/narrate.ts +10 -10
  53. package/src/adapters/dashboard/web/pages/flow/flow.css +38 -0
  54. package/src/adapters/dashboard/web/pages/flow/index.js +117 -0
  55. package/src/adapters/dashboard/web/pages/flow/sections/blind.js +12 -0
  56. package/src/adapters/dashboard/web/pages/flow/sections/detail.js +45 -0
  57. package/src/adapters/dashboard/web/pages/flow/sections/diagram.js +291 -0
  58. package/src/adapters/dashboard/web/pages/flow/sections/feed.js +11 -0
  59. package/src/adapters/dashboard/web/pages/flow/sections/fired.js +41 -0
  60. package/src/adapters/dashboard/web/pages/flow/sections/heatmap.js +25 -0
  61. package/src/adapters/dashboard/web/pages/flow/sections/records.js +24 -0
  62. package/src/adapters/dashboard/web/pages/flow/sections/symmetry.js +17 -0
  63. package/src/adapters/dashboard/web/pages/flow/state.js +3 -0
  64. package/src/adapters/dashboard/web/pages/health/health.css +93 -0
  65. package/src/adapters/dashboard/web/pages/health/index.js +41 -0
  66. package/src/adapters/dashboard/web/pages/health/sections/archive.js +84 -0
  67. package/src/adapters/dashboard/web/pages/health/sections/checks.js +172 -0
  68. package/src/adapters/dashboard/web/pages/health/sections/cycle.js +37 -0
  69. package/src/adapters/dashboard/web/pages/health/sections/verify.js +54 -0
  70. package/src/adapters/dashboard/web/pages/home/brain.js +375 -0
  71. package/src/adapters/dashboard/web/pages/home/home.css +134 -0
  72. package/src/adapters/dashboard/web/pages/home/index.js +84 -0
  73. package/src/adapters/dashboard/web/pages/home/sections/explorer.js +206 -0
  74. package/src/adapters/dashboard/web/pages/home/sections/hero.js +22 -0
  75. package/src/adapters/dashboard/web/pages/home/sections/live-activity.js +25 -0
  76. package/src/adapters/dashboard/web/pages/home/sections/recent-chapters.js +13 -0
  77. package/src/adapters/dashboard/web/pages/home/sections/tiles.js +52 -0
  78. package/src/adapters/dashboard/web/pages/memories/index.js +75 -0
  79. package/src/adapters/dashboard/web/pages/memories/memories.css +143 -0
  80. package/src/adapters/dashboard/web/pages/memories/sections/constellation.js +178 -0
  81. package/src/adapters/dashboard/web/pages/memories/sections/kinds.js +42 -0
  82. package/src/adapters/dashboard/web/pages/memories/sections/list.js +114 -0
  83. package/src/adapters/dashboard/web/pages/memories/sections/search.js +102 -0
  84. package/src/adapters/dashboard/web/pages/memories/sections/tools.js +155 -0
  85. package/src/adapters/dashboard/web/pages/memories/state.js +22 -0
  86. package/src/adapters/dashboard/web/pages/self/diff.js +79 -0
  87. package/src/adapters/dashboard/web/pages/self/index.js +43 -0
  88. package/src/adapters/dashboard/web/pages/self/markdown.js +61 -0
  89. package/src/adapters/dashboard/web/pages/self/sections/journal.js +32 -0
  90. package/src/adapters/dashboard/web/pages/self/sections/page.js +149 -0
  91. package/src/adapters/dashboard/web/pages/self/sections/settling.js +150 -0
  92. package/src/adapters/dashboard/web/pages/self/sections/stories.js +47 -0
  93. package/src/adapters/dashboard/web/pages/self/sections/wake.js +74 -0
  94. package/src/adapters/dashboard/web/pages/self/self.css +182 -0
  95. package/src/adapters/dashboard/web/server.ts +305 -28
  96. package/src/adapters/dashboard/web/shared/absence.js +14 -0
  97. package/src/adapters/dashboard/web/shared/actions.js +48 -0
  98. package/src/adapters/dashboard/web/shared/api.js +17 -0
  99. package/src/adapters/dashboard/web/shared/base.css +34 -0
  100. package/src/adapters/dashboard/web/shared/canvas.js +68 -0
  101. package/src/adapters/dashboard/web/shared/colors.js +6 -0
  102. package/src/adapters/dashboard/web/shared/dom.js +4 -0
  103. package/src/adapters/dashboard/web/shared/event-modal.js +25 -0
  104. package/src/adapters/dashboard/web/shared/fonts/OFL-courier-prime.txt +93 -0
  105. package/src/adapters/dashboard/web/shared/fonts/OFL-outfit.txt +93 -0
  106. package/src/adapters/dashboard/web/shared/fonts/courier-prime-latin-400.woff2 +0 -0
  107. package/src/adapters/dashboard/web/shared/fonts/courier-prime-latin-700.woff2 +0 -0
  108. package/src/adapters/dashboard/web/shared/fonts/outfit-latin-wght.woff2 +0 -0
  109. package/src/adapters/dashboard/web/shared/format.js +31 -0
  110. package/src/adapters/dashboard/web/shared/layout.css +32 -0
  111. package/src/adapters/dashboard/web/shared/memory-modal.js +124 -0
  112. package/src/adapters/dashboard/web/shared/modal.css +24 -0
  113. package/src/adapters/dashboard/web/shared/modal.js +22 -0
  114. package/src/adapters/dashboard/web/shared/state.js +12 -0
  115. package/src/adapters/dashboard/web/shared/tip.css +4 -0
  116. package/src/adapters/dashboard/web/shared/tip.js +12 -0
  117. package/src/adapters/dashboard/web/shared/tokens.css +50 -0
  118. package/src/adapters/dashboard/web/shared/type.css +52 -0
  119. package/src/adapters/dashboard/web/shared/utilities.css +5 -0
  120. package/src/adapters/dashboard/web/shared/vendor/MIT-three.txt +21 -0
  121. package/src/adapters/dashboard/web/shared/vendor/three.module.min.js +6 -0
  122. package/src/adapters/dashboard/web/shared/widgets/bar.css +9 -0
  123. package/src/adapters/dashboard/web/shared/widgets/card.css +6 -0
  124. package/src/adapters/dashboard/web/shared/widgets/chapters.js +15 -0
  125. package/src/adapters/dashboard/web/shared/widgets/chart.css +4 -0
  126. package/src/adapters/dashboard/web/shared/widgets/confirm.css +31 -0
  127. package/src/adapters/dashboard/web/shared/widgets/confirm.js +52 -0
  128. package/src/adapters/dashboard/web/shared/widgets/feed.css +13 -0
  129. package/src/adapters/dashboard/web/shared/widgets/feed.js +41 -0
  130. package/src/adapters/dashboard/web/shared/widgets/light.css +4 -0
  131. package/src/adapters/dashboard/web/shared/widgets/light.js +15 -0
  132. package/src/adapters/dashboard/web/shared/widgets/rows.css +7 -0
  133. package/src/adapters/dashboard/web/shared/widgets/table.css +17 -0
  134. package/src/adapters/dashboard/web/shared/widgets/tiles.css +14 -0
  135. package/src/adapters/dashboard/web/shell/pages.js +15 -0
  136. package/src/adapters/dashboard/web/shell/pulse.js +86 -0
  137. package/src/adapters/dashboard/web/shell/tabs.js +49 -0
  138. package/src/adapters/dashboard/web/static.ts +76 -0
  139. package/src/adapters/dashboard/web/views/activity.ts +80 -0
  140. package/src/adapters/dashboard/web/views/archive-words.ts +57 -0
  141. package/src/adapters/dashboard/web/views/flow-view.ts +217 -0
  142. package/src/adapters/dashboard/web/views/health.ts +328 -0
  143. package/src/adapters/dashboard/web/views/mechanism-panel.ts +370 -0
  144. package/src/adapters/dashboard/web/views/mechanisms.ts +302 -0
  145. package/src/adapters/dashboard/web/views/memories.ts +342 -0
  146. package/src/adapters/dashboard/web/views/memory.ts +210 -0
  147. package/src/adapters/dashboard/web/views/meta.ts +64 -0
  148. package/src/adapters/dashboard/web/views/mind.ts +729 -0
  149. package/src/adapters/dashboard/web/views/overview.ts +282 -0
  150. package/src/adapters/dashboard/web/views/pulse.ts +19 -0
  151. package/src/adapters/dashboard/web/views/rows.ts +207 -0
  152. package/src/adapters/dashboard/web/views/search.ts +62 -0
  153. package/src/adapters/dashboard/web/views/shared.ts +161 -0
  154. package/src/adapters/dashboard/web/views.ts +34 -1724
  155. package/src/adapters/fired.ts +138 -31
  156. package/src/adapters/mcp/INTERFACE-GAPS.md +4 -1
  157. package/src/adapters/mcp/NOTES.md +43 -0
  158. package/src/adapters/mcp/bin/serve.ts +9 -1
  159. package/src/adapters/mcp/index.ts +7 -0
  160. package/src/adapters/mcp/server.ts +167 -6
  161. package/src/adapters/mcp/tools.ts +42 -0
  162. package/src/adapters/mcp/write-up.ts +1 -1
  163. package/src/adapters/sessions.ts +18 -1
  164. package/src/adapters/snapshots.ts +71 -39
  165. package/src/core/associate/INTERFACE-GAPS.md +8 -0
  166. package/src/core/counterpart.ts +86 -7
  167. package/src/core/encode/INTERFACE-GAPS.md +12 -0
  168. package/src/core/feelings-wheel.ts +218 -0
  169. package/src/core/handoff/INTERFACE-GAPS.md +2 -0
  170. package/src/core/mint.ts +14 -2
  171. package/src/core/prospective/INTERFACE-GAPS.md +14 -0
  172. package/src/core/prospective/windows.ts +10 -48
  173. package/src/core/recall/INTERFACE-GAPS.md +6 -0
  174. package/src/core/remember/INTERFACE-GAPS.md +10 -0
  175. package/src/core/schemas/INTERFACE-GAPS.md +8 -0
  176. package/src/core/schemas/NOTES.md +118 -1
  177. package/src/core/schemas/index.ts +330 -40
  178. package/src/core/schemas/tunables.ts +23 -0
  179. package/src/core/schemas/types.ts +64 -1
  180. package/src/core/self/CONTRACT.md +3 -0
  181. package/src/core/self/INTERFACE-GAPS.md +10 -0
  182. package/src/core/self/NOTES.md +33 -2
  183. package/src/core/self/calendar.ts +7 -78
  184. package/src/core/self/episodes.ts +52 -12
  185. package/src/core/self/index.ts +40 -12
  186. package/src/core/self/writer.ts +22 -22
  187. package/src/core/sleep/NOTES.md +36 -0
  188. package/src/core/sleep/cycle.ts +38 -3
  189. package/src/core/sleep/fade.ts +76 -0
  190. package/src/core/sleep/index.ts +4 -1
  191. package/src/core/sleep/prune.ts +8 -1
  192. package/src/core/sleep/tunables.ts +5 -0
  193. package/src/core/sleep/types.ts +24 -0
  194. package/src/core/store/CONTRACT.md +36 -7
  195. package/src/core/store/NOTES.md +197 -0
  196. package/src/core/store/errors.ts +22 -0
  197. package/src/core/store/feelings.ts +182 -0
  198. package/src/core/store/index.ts +339 -45
  199. package/src/core/store/operational.ts +240 -22
  200. package/src/core/store/owner-op-seam.ts +13 -3
  201. package/src/core/store/paths.ts +15 -1
  202. package/src/core/store/pre-migration.ts +258 -0
  203. package/src/core/store/prose.ts +8 -1
  204. package/src/core/store/render.ts +3 -0
  205. package/src/core/time.ts +374 -0
  206. package/src/core/types.ts +13 -0
  207. package/src/adapters/dashboard/web/brain.html +0 -463
@@ -0,0 +1,182 @@
1
+ .story{border:1px solid var(--border);border-radius:var(--radius);background:var(--card);
2
+ padding:14px 16px;margin-bottom:10px}
3
+ .story h3{font-size:12px;color:var(--cyan);font-weight:400;letter-spacing:1px;margin-bottom:2px}
4
+ .story .about{color:var(--faint);font-size:10px;letter-spacing:.6px;text-transform:uppercase;margin-bottom:10px}
5
+ .story .said{font-size:11.5px;margin:5px 0;line-height:1.65}
6
+ .story .said .k{color:var(--dim);display:inline-block;min-width:88px;vertical-align:top}
7
+ .story .said .stmt{display:inline-block;max-width:calc(100% - 96px)}
8
+ .story .said .stmt.click{cursor:pointer}
9
+ .story .said .stmt.click:hover{color:var(--cyan)}
10
+ .beat .verdict.became{color:var(--amber);cursor:pointer}
11
+ .beat .verdict.became:hover{text-decoration:underline}
12
+ .beat{display:grid;grid-template-columns:52px 1fr 210px;gap:11px;align-items:start;
13
+ padding:9px 0;border-top:1px solid var(--border);font-size:11px}
14
+ .beat .day{color:var(--faint);font-size:10px}
15
+ .beat .who{color:var(--ink);line-height:1.5}
16
+ .beat .who em{color:var(--dim);font-style:normal;font-size:10px;display:block;margin-top:2px}
17
+ .beat .track{height:7px;background:var(--deep);border-radius:4px;overflow:hidden;position:relative;
18
+ border:1px solid rgba(0,229,255,.07)}
19
+ .beat .fill{height:100%;background:var(--teal)}
20
+ .beat.crossed .fill{background:var(--amber)}
21
+ .beat .barline{position:absolute;top:-2px;bottom:-2px;width:1px;background:var(--red);opacity:.7}
22
+ .beat .verdict{font-size:9.5px;color:var(--dim);margin-top:4px;letter-spacing:.4px;line-height:1.5;
23
+ overflow-wrap:anywhere}
24
+ .beat.crossed .verdict{color:var(--amber)}
25
+ @media(max-width:640px){.beat{grid-template-columns:44px 1fr}.beat>div:last-child{grid-column:1/-1}}
26
+
27
+ .lane{margin-bottom:12px}
28
+ .lane h4{font-size:10px;text-transform:uppercase;letter-spacing:2px;color:var(--purple);
29
+ font-weight:400;margin-bottom:6px}
30
+ .lane .item{font-size:11.5px;line-height:1.7;padding:4px 0 4px 14px;border-left:1px solid var(--border);
31
+ margin-bottom:2px;color:var(--ink)}
32
+ .lane .item .date{color:var(--faint)}
33
+ .wakehead{color:var(--dim);font-size:11px;margin-bottom:12px;line-height:1.65}
34
+
35
+ /* ── the self page: the heart of the tab ── */
36
+ .sp-card{background:var(--card);border:1px solid var(--glow);border-radius:6px;padding:20px 24px 16px;
37
+ margin:4px 0 8px;box-shadow:0 0 24px rgba(0,229,255,.06)}
38
+ .sp-head{display:flex;justify-content:space-between;align-items:baseline;gap:12px;flex-wrap:wrap}
39
+ h2.sp-title{margin:0 0 6px;font-size:19px;color:var(--cyan)}
40
+ .sp-chips{display:flex;gap:6px;flex-wrap:wrap}
41
+ .chip{display:inline-block;font-size:12px;color:var(--dim);border:1px solid var(--border);border-radius:11px;
42
+ padding:2px 9px;line-height:1.5;white-space:nowrap}
43
+ .chip.warn{color:var(--amber);border-color:rgba(255,215,64,.35)}
44
+ .chip.model{color:var(--purple);border-color:rgba(179,136,255,.3);font-family:var(--mono);font-size:11.5px}
45
+ .sp-reason{color:var(--dim);font-size:13px;margin:2px 0 10px}
46
+ .sp-body{max-width:46rem}
47
+ .md{color:var(--ink);font-size:15px;line-height:1.7}
48
+ .md p{margin:0 0 10px;text-wrap:pretty}
49
+ .md .md-h{font-family:var(--sans);font-weight:600;color:var(--purple);margin:16px 0 6px;font-size:14.5px;letter-spacing:.2px}
50
+ .md h3.md-h{font-size:16px;color:var(--cyan)}
51
+ .md .md-h:first-child{margin-top:4px}
52
+ .md ul,.md ol{margin:0 0 10px 1.3em;padding:0}
53
+ .md li{margin:3px 0;padding-left:2px}
54
+ .md li::marker{color:var(--cyan)}
55
+ .md code{font-family:var(--mono);font-size:.92em;background:var(--deep);padding:0 4px;border-radius:3px}
56
+ .md blockquote{border-left:2px solid var(--purple);padding-left:12px;color:var(--dim);margin:0 0 10px}
57
+ .md b{color:#e8eef5;font-weight:600}
58
+ .sp-once{margin:0 0 14px}
59
+
60
+ /* ── its history: a line of dots ── */
61
+ .tl{overflow-x:auto;margin:0 0 8px;padding-bottom:2px}
62
+ .tl-track{display:inline-flex;gap:0;position:relative;min-width:min-content}
63
+ .tl-track::before{content:"";position:absolute;left:44px;right:44px;top:15px;height:1px;background:var(--glow)}
64
+ .tl-step{position:relative;flex:0 0 auto;min-width:88px;min-height:56px;padding:8px 6px 6px;background:none;border:none;
65
+ color:var(--dim);cursor:pointer;display:flex;flex-direction:column;align-items:center;gap:4px;font-family:var(--sans)}
66
+ .tl-dot{width:13px;height:13px;border-radius:50%;background:var(--card);border:2px solid var(--glow);position:relative;z-index:1;
67
+ transition:transform .15s}
68
+ .tl-step.now .tl-dot{background:var(--cyan);border-color:var(--cyan)}
69
+ .tl-step:hover .tl-dot{transform:scale(1.25);border-color:var(--cyan)}
70
+ .tl-step.on .tl-dot{box-shadow:0 0 0 4px rgba(0,229,255,.22);border-color:var(--cyan)}
71
+ .tl-step.on{color:var(--ink)}
72
+ .tl-date{font-size:12.5px;white-space:nowrap}
73
+ .tl-who{font-size:11.5px;color:var(--faint);white-space:nowrap}
74
+ .tl-step.on .tl-who{color:var(--dim)}
75
+ .tl-vhead{display:flex;gap:10px;align-items:baseline;flex-wrap:wrap;margin-bottom:4px}
76
+ .tl-vhead b{color:var(--cyan);font-weight:600;font-size:14px}
77
+ .tl-meta{color:var(--dim);font-size:12.5px}
78
+ .tl-why{color:var(--ink);font-size:13.5px;margin-bottom:10px;font-style:italic}
79
+ .tl-toggle{display:inline-flex;border:1px solid var(--border);border-radius:4px;overflow:hidden;margin:2px 0 10px}
80
+ .tl-toggle .seg{background:none;border:none;color:var(--dim);padding:7px 12px;font-family:var(--sans);font-size:12.5px;cursor:pointer;min-height:44px}
81
+ .tl-toggle .seg+.seg{border-left:1px solid var(--border)}
82
+ .tl-toggle .seg.on{background:rgba(0,229,255,.1);color:var(--cyan)}
83
+ .diff{font-size:13.5px;line-height:1.65;border:1px solid var(--border);border-radius:4px;background:var(--deep);padding:6px 0;margin-top:6px}
84
+ .d-line{display:flex;gap:8px;padding:1px 12px 1px 8px;white-space:pre-wrap;overflow-wrap:anywhere;color:var(--dim)}
85
+ .d-sign{flex:0 0 12px;font-family:var(--mono);color:var(--faint)}
86
+ .d-line.add{background:rgba(0,191,165,.10);color:var(--ink)}
87
+ .d-line.add .d-sign{color:var(--teal)}
88
+ .d-line.del{background:rgba(255,82,82,.09);color:var(--dim)}
89
+ .d-line.del .d-sign{color:var(--red)}
90
+ .d-line ins{text-decoration:none;background:rgba(0,191,165,.32);color:#e8fffb;border-radius:2px}
91
+ .d-line del{text-decoration:line-through;text-decoration-color:rgba(255,82,82,.8);background:rgba(255,82,82,.22);color:#ffd6d6;border-radius:2px}
92
+ .d-fold{color:var(--faint);font-size:12px;padding:2px 12px 2px 28px;font-style:italic}
93
+ .d-add{color:var(--teal)} .d-del{color:#ff8a8a}
94
+
95
+ /* ── what it's settling into ── */
96
+ .self-cols{margin-top:6px}
97
+ .st-sum{display:flex;flex-wrap:wrap;gap:6px 16px;font-size:13.5px;color:var(--ink);margin-bottom:10px}
98
+ .st-sum span::before{content:"";display:inline-block;width:7px;height:7px;border-radius:50%;background:var(--cyan);margin-right:7px;vertical-align:1px}
99
+ .st-sum span:nth-child(2)::before{background:var(--amber)}
100
+ .st-sum span:nth-child(3)::before{background:var(--purple)}
101
+ .st-warn{border:1px solid rgba(255,82,82,.45);border-radius:4px;padding:8px 12px;font-size:13px;color:var(--ink);margin-bottom:10px}
102
+ .st-warn b{color:#ff8a8a;font-weight:500}
103
+ .st-none{color:var(--dim);font-size:13px;margin:6px 0 4px}
104
+ .st-none b{color:var(--amber);font-weight:400;margin-right:4px}
105
+ h4.st-h{font-family:var(--sans);font-size:13.5px;font-weight:600;color:var(--ink);margin:14px 0 6px}
106
+ h4.st-h small{font-weight:400;color:var(--dim);font-size:12px}
107
+ .st-row{display:flex;align-items:center;gap:10px;width:100%;text-align:left;background:none;border:none;
108
+ border-top:1px solid var(--border);padding:9px 2px;color:var(--ink);font-family:var(--sans);font-size:13px;line-height:1.5;min-height:44px}
109
+ .st-row.click,.st-story{cursor:pointer}
110
+ .st-row:hover{background:var(--hover)}
111
+ .st-text{flex:1;min-width:0}
112
+ .st-about{display:block;color:var(--faint);font-size:12px}
113
+ .st-group .extra{display:none}
114
+ .st-group.all .extra{display:flex}
115
+ .st-more{background:none;border:none;color:var(--cyan);font-family:var(--sans);font-size:12.5px;cursor:pointer;padding:8px 2px;min-height:44px}
116
+ .st-bar{flex:0 0 70px;height:6px;background:var(--deep);border:1px solid var(--border);border-radius:3px;overflow:hidden}
117
+ .st-bar span{display:block;height:100%;background:var(--purple)}
118
+ .st-tag{flex:0 0 auto;font-size:11.5px;border-radius:10px;padding:1px 8px}
119
+ .st-tag.changed{color:var(--amber);border:1px solid rgba(255,215,64,.35)}
120
+
121
+ .cand{border:1px solid var(--border);border-radius:5px;padding:10px 12px;margin-bottom:8px;cursor:pointer;background:rgba(6,10,16,.5)}
122
+ .cand:hover{border-color:var(--glow);box-shadow:var(--hovershadow)}
123
+ .cand.ready{border-color:rgba(0,229,255,.45)}
124
+ .cand-text{font-size:13.5px;line-height:1.5;color:var(--ink);margin-bottom:8px}
125
+ .cand-meters{display:grid;grid-template-columns:auto 1fr auto auto;gap:6px 10px;align-items:center}
126
+ .cm-lab{font-size:12px;color:var(--dim)}
127
+ .cm-track{position:relative;height:8px;background:var(--deep);border:1px solid var(--border);border-radius:4px;min-width:80px}
128
+ .cm-fill{position:absolute;left:0;top:0;bottom:0;background:var(--purple);border-radius:3px}
129
+ .cm-fill.ok{background:var(--teal)}
130
+ .cm-ghost{position:absolute;top:0;bottom:0;background:repeating-linear-gradient(90deg,rgba(179,136,255,.45) 0 3px,transparent 3px 6px)}
131
+ .cm-mark{position:absolute;top:-4px;bottom:-4px;width:2px;background:var(--cyan);border-radius:1px}
132
+ .cm-dots{display:flex;gap:5px}
133
+ .cm-dots .dd{width:11px;height:11px;border-radius:50%;border:1.5px solid var(--glow);background:transparent}
134
+ .cm-dots .dd.on{background:var(--cyan);border-color:var(--cyan)}
135
+ .cand-status{font-size:12px;color:var(--dim);margin-top:7px}
136
+ .cand.ready .cand-status{color:var(--cyan)}
137
+
138
+ /* ── the wake, folded ── */
139
+ .wk-sum{display:flex;justify-content:space-between;align-items:baseline;gap:10px;width:100%;background:none;border:none;
140
+ padding:0 0 8px;cursor:pointer;color:var(--ink);font-family:var(--sans);text-align:left;min-height:44px}
141
+ .wk-line{font-size:14.5px;color:var(--dim)}
142
+ .wk-line b{font-family:var(--mono);font-size:20px;color:var(--cyan);font-weight:700;margin-right:2px}
143
+ .wk-open{font-size:12.5px;color:var(--cyan);white-space:nowrap}
144
+ .wk-sum:hover .wk-open{text-decoration:underline}
145
+ .wk-bar{display:flex;height:14px;border-radius:4px;overflow:hidden;background:var(--deep);border:1px solid var(--border)}
146
+ .wk-seg{display:block;height:100%}
147
+ .wk-seg+.wk-seg{border-left:1px solid var(--card)}
148
+ .p-furn{background:#3a4552}.p-page{background:var(--cyan)}.p-craft{background:var(--purple)}
149
+ .p-threads{background:var(--amber)}.p-hints{background:var(--teal)}.p-horizon{background:#ff8a80}
150
+ .p-room{background:transparent;border:1px dashed var(--glow)}
151
+ .wk-legend{display:flex;flex-wrap:wrap;gap:4px 14px;margin:8px 0 2px;font-size:12.5px;color:var(--dim)}
152
+ .wk-key i{display:inline-block;width:9px;height:9px;border-radius:2px;margin-right:6px;vertical-align:0}
153
+ .wk-key em{font-style:normal;color:var(--faint);font-family:var(--mono);font-size:11.5px;margin-left:2px}
154
+ .wk-full{margin-top:12px;border-top:1px solid var(--border);padding-top:12px}
155
+ .wk-act{margin:10px 0 0}
156
+ .wk-act .act-btn{min-height:44px;padding:8px 14px;font-family:var(--sans);font-size:13px;color:var(--cyan);border-color:var(--glow)}
157
+ .wk-act .act-out{margin-top:8px}
158
+
159
+ /* ── the journal ── */
160
+ .jd{margin-bottom:14px}
161
+ .jd-h{display:flex;gap:10px;align-items:baseline;margin:0 0 6px;font-size:13.5px;color:var(--ink)}
162
+ .jd-h b{font-weight:600}
163
+ .jd-h span{color:var(--faint);font-size:12px}
164
+ .jc{border:1px solid var(--border);border-radius:5px;background:var(--card);margin-bottom:6px}
165
+ .jc summary{list-style:none;cursor:pointer;padding:10px 14px;display:block;min-height:44px}
166
+ .jc summary::-webkit-details-marker{display:none}
167
+ .jc summary:hover{background:var(--hover)}
168
+ .jc[open] summary{border-bottom:1px solid var(--border)}
169
+ .jc-top{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
170
+ .jc-title{color:var(--cyan);font-size:14px;font-weight:500}
171
+ .jc-first{display:block;color:var(--dim);font-size:13px;margin-top:3px;line-height:1.5}
172
+ .jc[open] .jc-first{display:none}
173
+ .jc-body{padding:12px 16px}
174
+ .jc-body .md{font-size:14px}
175
+ .jc-open{min-height:44px;font-family:var(--sans);font-size:12.5px;padding:6px 12px}
176
+
177
+ @media(max-width:640px){
178
+ .sp-card{padding:16px 14px 12px}
179
+ .md{font-size:14.5px}
180
+ .cand-meters{grid-template-columns:auto 1fr}
181
+ .tl-step{min-width:76px}
182
+ }
@@ -1,5 +1,6 @@
1
1
  /**
2
- * The local web dashboard's server — `node:http`, one page, JSON under `/api`.
2
+ * The local web dashboard's server — `node:http`, one page (and the static
3
+ * modules it is built from), JSON under `/api`.
3
4
  *
4
5
  * CONTRACT OQ1 asked terminal or local web and the build answered "terminal, for
5
6
  * now" with a named revision condition: *the moment the owner wants to click.*
@@ -35,29 +36,57 @@
35
36
  * ## The filesystem exception, named
36
37
  *
37
38
  * This is the ONE file in `adapters/dashboard/` that imports `node:fs`, and it
38
- * imports exactly `readFileSync`, to serve two static HTML files that ship
39
- * beside it. The directory-wide ban exists to mechanize "no memory body text is
40
- * persisted into dashboard state" — there is no state file because nothing here
41
- * can open one — and a read-only import preserves that exactly.
39
+ * imports exactly `readFileSync`, to serve the static files that ship beside
40
+ * it: the HTML page, and the page's own `.js`/`.css` modules under `web/`
41
+ * — only the paths `static.ts` resolves (a fixed set of folders, an allow-listed
42
+ * set of extensions, no traversal). The directory-wide ban exists to mechanize
43
+ * "no memory body text is persisted into dashboard state" — there is no state
44
+ * file because nothing here can open one — and a read-only import preserves
45
+ * that exactly.
42
46
  * `test/dashboard.test.ts` encodes the exception per-file and asserts the
43
47
  * binding, so it cannot quietly widen into a write.
48
+ *
49
+ * ## Looking, and managing (2026-09-25)
50
+ *
51
+ * `router()` is LOOKING: GET only, over the observer source, and it stays a
52
+ * pure function of that source. MANAGING — a note, a removal, a backup, … —
53
+ * is a POST to `/api/action/<name>`, handled by `actions.ts` through the
54
+ * console's own `run()`. That path is never handed the observer source, only
55
+ * the store's directory and the configuration's path, and it answers only a
56
+ * request that passes `checkActionRequest` (same origin, the per-launch token
57
+ * the page carries, JSON). A GET to an action path is refused here, so no
58
+ * link, image or prefetch can act.
44
59
  */
45
60
  import { readFileSync } from "node:fs";
46
61
  import { createServer } from "node:http";
47
- import type { Server } from "node:http";
62
+ import type { IncomingMessage, Server, ServerResponse } from "node:http";
48
63
  import { dirname, join } from "node:path";
49
64
  import { fileURLToPath } from "node:url";
50
65
 
51
- import { isStoreError, today as todayUtc } from "../../../core/store/index.js";
66
+ import { dataDir, isStoreError } from "../../../core/store/index.js";
52
67
  import { Dashboard } from "../index.js";
68
+ import { UPGRADE_PENDING_SENTENCE, upgradePending } from "../upgrade.js";
53
69
  import type { DashboardSource } from "../source.js";
70
+ import {
71
+ MAX_BODY_BYTES,
72
+ TOKEN_HEADER,
73
+ TOKEN_META,
74
+ checkActionRequest,
75
+ newActionToken,
76
+ runAction,
77
+ } from "./actions.js";
78
+ import type { ActionContext } from "./actions.js";
54
79
  import { firedPanel } from "./fired.js";
80
+ import { mechanismPanel } from "./views/mechanism-panel.js";
81
+ import { mechanismsView } from "./views/mechanisms.js";
82
+ import { resolveStatic } from "./static.js";
55
83
  import {
56
84
  activityView,
57
85
  eventDetail,
58
86
  flowView,
59
87
  healthView,
60
88
  memoriesView,
89
+ memoryListView,
61
90
  memoryDetail,
62
91
  metaView,
63
92
  mindView,
@@ -73,7 +102,6 @@ export const PORT_ENV = "COUNTERPARTS_DASHBOARD_PORT";
73
102
 
74
103
  const HERE = dirname(fileURLToPath(import.meta.url));
75
104
  const APP_PATH = join(HERE, "app.html");
76
- const BRAIN_PATH = join(HERE, "brain.html");
77
105
 
78
106
  const NO_STORE = { "cache-control": "no-store" } as const;
79
107
 
@@ -106,6 +134,8 @@ export interface Reply {
106
134
  readonly status: number;
107
135
  readonly headers: Record<string, string>;
108
136
  readonly body: string;
137
+ /** A binary static file (a font), sent instead of `body`. */
138
+ readonly bytes?: Uint8Array;
109
139
  }
110
140
 
111
141
  function json(body: unknown, status = 200): Reply {
@@ -116,14 +146,39 @@ function json(body: unknown, status = 200): Reply {
116
146
  };
117
147
  }
118
148
 
149
+ /**
150
+ * No page of this dashboard may be framed. The page can now ACT (a removal is
151
+ * two clicks and a typed id), and a page another site frames invisibly is how
152
+ * clicks get stolen — so every HTML reply says "never inside a frame", in the
153
+ * old header and the current one.
154
+ */
155
+ const NO_FRAMES = {
156
+ "x-frame-options": "DENY",
157
+ "content-security-policy": "frame-ancestors 'none'",
158
+ } as const;
159
+
119
160
  function html(body: string): Reply {
120
- return { status: 200, headers: { "content-type": "text/html; charset=utf-8", ...NO_STORE }, body };
161
+ return {
162
+ status: 200,
163
+ headers: { "content-type": "text/html; charset=utf-8", ...NO_STORE, ...NO_FRAMES },
164
+ body,
165
+ };
121
166
  }
122
167
 
123
- /** One of the two static pages. A missing file is a sentence, never a stack. */
124
- function page(file: string): Reply {
168
+ /**
169
+ * The static page. A missing file is a sentence, never a stack.
170
+ *
171
+ * `token`, when given, fills the page's `<meta name="counterparts-action-token">`
172
+ * — the per-launch secret every action must echo. It is hex, so it needs no
173
+ * escaping, and it is only ever sent to a request that passed the Host check.
174
+ */
175
+ function page(file: string, token?: string): Reply {
125
176
  try {
126
- return html(readFileSync(file, "utf8"));
177
+ const text = readFileSync(file, "utf8");
178
+ if (token === undefined || !/^[0-9a-f]+$/.test(token)) return html(text);
179
+ return html(
180
+ text.replace(`<meta name="${TOKEN_META}" content="">`, `<meta name="${TOKEN_META}" content="${token}">`),
181
+ );
127
182
  } catch {
128
183
  return json(
129
184
  { error: `the dashboard page is missing from the install (${file}). Reinstall, or run from a checkout.` },
@@ -132,6 +187,23 @@ function page(file: string): Reply {
132
187
  }
133
188
  }
134
189
 
190
+ /**
191
+ * One of the page's static modules, already resolved by `static.ts`. Read per
192
+ * request and never cached, like the HTML: a checkout edited under a running
193
+ * server shows the edit on reload. Anything unreadable is the ordinary 404.
194
+ */
195
+ function staticFile(path: string): Reply | null {
196
+ const found = resolveStatic(path, HERE);
197
+ if (found === null) return null;
198
+ const headers = { "content-type": found.contentType, ...NO_STORE };
199
+ try {
200
+ if (found.text) return { status: 200, headers, body: readFileSync(found.file, "utf8") };
201
+ return { status: 200, headers, body: "", bytes: readFileSync(found.file) };
202
+ } catch {
203
+ return json({ error: `not found: ${path}` }, 404);
204
+ }
205
+ }
206
+
135
207
  function intParam(url: URL, name: string, fallback: number): number {
136
208
  const raw = url.searchParams.get(name);
137
209
  if (raw === null) return fallback;
@@ -139,6 +211,10 @@ function intParam(url: URL, name: string, fallback: number): number {
139
211
  return Number.isFinite(parsed) ? parsed : fallback;
140
212
  }
141
213
 
214
+ function forbiddenHost(): Reply {
215
+ return json({ error: "forbidden: this dashboard answers only to localhost, 127.0.0.1 or [::1]" }, 403);
216
+ }
217
+
142
218
  /**
143
219
  * Resolve one request against an already-open observer source.
144
220
  *
@@ -146,17 +222,23 @@ function intParam(url: URL, name: string, fallback: number): number {
146
222
  * an instrument that crashes its own loop on a broken store is the one moment
147
223
  * the owner most needs it to render (scar E7).
148
224
  */
149
- export function router(url: URL, host: string | null, src: DashboardSource): Reply {
150
- if (!isAllowedHost(host)) {
151
- return json(
152
- { error: "forbidden: this dashboard answers only to localhost, 127.0.0.1 or [::1]" },
153
- 403,
154
- );
155
- }
225
+ export function router(
226
+ url: URL,
227
+ host: string | null,
228
+ src: DashboardSource,
229
+ opts: { readonly token?: string } = {},
230
+ ): Reply {
231
+ if (!isAllowedHost(host)) return forbiddenHost();
156
232
  const path = url.pathname;
157
233
  try {
158
- if (path === "/" || path === "/index.html") return page(APP_PATH);
159
- if (path === "/brain") return page(BRAIN_PATH);
234
+ // LOOKING NEVER ACTS: an action path reached by GET is refused, whatever
235
+ // follows it, before any view is computed.
236
+ if (path === ACTION_PREFIX.slice(0, -1) || path.startsWith(ACTION_PREFIX)) {
237
+ return json({ error: "an action is a POST from the dashboard's own page; nothing was done" }, 405);
238
+ }
239
+ if (path === "/" || path === "/index.html") return page(APP_PATH, opts.token);
240
+ // The brain lives on the home page now; an old bookmark lands there.
241
+ if (path === "/brain") return { status: 302, headers: { location: "/#home", ...NO_STORE }, body: "" };
160
242
  if (path === "/favicon.svg" || path === "/favicon.ico") {
161
243
  return {
162
244
  status: 200,
@@ -169,6 +251,16 @@ export function router(url: URL, host: string | null, src: DashboardSource): Rep
169
251
  if (path === "/api/pulse") return json(pulse(src));
170
252
  if (path === "/api/overview") return json(overviewView(src, intParam(url, "limit", 40)));
171
253
  if (path === "/api/memories") return json(memoriesView(src, { limit: intParam(url, "limit", 4000) }));
254
+ if (path === "/api/memories/list") {
255
+ const q = url.searchParams;
256
+ return json(memoryListView(src, {
257
+ state: q.get("state"),
258
+ kind: q.get("kind"),
259
+ band: q.get("band"),
260
+ offset: intParam(url, "offset", 0),
261
+ limit: intParam(url, "limit", 50),
262
+ }));
263
+ }
172
264
  if (path === "/api/memory") {
173
265
  const id = url.searchParams.get("id") ?? "";
174
266
  if (id.length === 0) return json({ error: "id is required" }, 400);
@@ -185,7 +277,12 @@ export function router(url: URL, host: string | null, src: DashboardSource): Rep
185
277
  return detail.found ? json(detail) : json({ error: `no such node: ${key}` }, 404);
186
278
  }
187
279
  if (path === "/api/health") return json(healthView(src));
188
- if (path === "/api/fired") return json(firedPanel(src, todayUtc()));
280
+ if (path === "/api/fired") return json(firedPanel(src, src.store.today()));
281
+ if (path === "/api/mechanisms") return json(mechanismsView(src));
282
+ if (path === "/api/mechanism") {
283
+ const panel = mechanismPanel(src, url.searchParams.get("id") ?? "");
284
+ return panel.found ? json(panel) : json({ error: `no such mechanism: ${panel.id}` }, 404);
285
+ }
189
286
  if (path === "/api/activity") {
190
287
  const sinceRaw = url.searchParams.get("sinceSeq");
191
288
  const opts: { limit: number; name?: string; sinceSeq?: number } = {
@@ -202,6 +299,8 @@ export function router(url: URL, host: string | null, src: DashboardSource): Rep
202
299
  const detail = eventDetail(src, seq);
203
300
  return detail.found ? json(detail) : json({ error: "no event with that seq in the kept window" }, 404);
204
301
  }
302
+ const asset = staticFile(path);
303
+ if (asset !== null) return asset;
205
304
  return json({ error: `not found: ${path}` }, 404);
206
305
  } catch (err) {
207
306
  // A store refusal reaches the page as its code and its detail — ids and
@@ -212,9 +311,40 @@ export function router(url: URL, host: string | null, src: DashboardSource): Rep
212
311
  }
213
312
  }
214
313
 
314
+ /** The whole page while the store waits for its upgrade: calm, self-contained, no script. */
315
+ const UPGRADE_PENDING_PAGE = `<!doctype html>
316
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
317
+ <title>counterparts</title>
318
+ <style>
319
+ :root{color-scheme:dark}
320
+ body{margin:0;min-height:100vh;display:grid;place-items:center;background:#04070c;color:#c5cdd8;
321
+ font:17px/1.6 system-ui,-apple-system,"Segoe UI",sans-serif;padding:16px;box-sizing:border-box}
322
+ main{max-width:34rem}
323
+ h1{font-size:13px;letter-spacing:.35em;text-transform:uppercase;color:#00e5ff;font-weight:600;margin:0 0 18px}
324
+ p{margin:0}
325
+ </style></head>
326
+ <body><main><h1>Counterparts</h1><p>${UPGRADE_PENDING_SENTENCE}</p></main></body></html>
327
+ `;
328
+
329
+ function upgradePendingReply(path: string): Reply {
330
+ if (path.startsWith("/api/")) {
331
+ return json({ error: "upgrade-pending", message: UPGRADE_PENDING_SENTENCE }, 503);
332
+ }
333
+ return { status: 200, headers: { "content-type": "text/html; charset=utf-8", ...NO_STORE }, body: UPGRADE_PENDING_PAGE };
334
+ }
335
+
336
+ /** Every management action is a POST under here: `/api/action/<name>`. */
337
+ export const ACTION_PREFIX = "/api/action/";
338
+
215
339
  export interface ServeOptions {
216
340
  /** The data dir. Always passed explicitly by every caller in this repo. */
217
341
  readonly dir?: string;
342
+ /**
343
+ * The host configuration this dashboard was opened through, when it was —
344
+ * handed to the actions that read one (`scope`, `rebrief`, and the embedder
345
+ * knob of `note`/`ask`), exactly as `--config` would be.
346
+ */
347
+ readonly config?: string;
218
348
  /** 0 asks the OS for a free port — what the visual loop uses. */
219
349
  readonly port?: number;
220
350
  }
@@ -223,7 +353,12 @@ export interface RunningDashboard {
223
353
  readonly port: number;
224
354
  readonly url: string;
225
355
  readonly dir: string;
356
+ /** This launch's action token (the page carries it; tests read it here). */
357
+ readonly token: string;
226
358
  readonly server: Server;
359
+ /** True while the store waits for its one-time upgrade (`upgradePending`):
360
+ * every page says so until a session has upgraded it and the store opens. */
361
+ readonly upgradePending: boolean;
227
362
  stop(): Promise<void>;
228
363
  }
229
364
 
@@ -239,15 +374,65 @@ function resolvePort(opts: ServeOptions): number {
239
374
  * for 0 — and closing it closes the store.
240
375
  */
241
376
  export function startDashboard(opts: ServeOptions = {}): Promise<RunningDashboard> {
242
- const dashboard = Dashboard.open({ ...(opts.dir === undefined ? {} : { dir: opts.dir }) });
243
- const src = dashboard.source;
244
- const dir = dashboard.store.dir;
377
+ const openOpts = opts.dir === undefined ? {} : { dir: opts.dir };
378
+ // A store waiting for its upgrade is not an error to the owner: the server
379
+ // still starts, says so on every page, and tries the store again on each
380
+ // request, so a reload after a session has upgraded it shows the dashboard.
381
+ let dashboard: Dashboard | null;
382
+ try {
383
+ dashboard = Dashboard.open(openOpts);
384
+ } catch (err) {
385
+ if (!upgradePending(err)) throw err;
386
+ dashboard = null;
387
+ }
388
+ const pendingAtStart = dashboard === null;
389
+ const current = (): Dashboard | null => {
390
+ if (dashboard !== null) return dashboard;
391
+ try {
392
+ dashboard = Dashboard.open(openOpts);
393
+ } catch (err) {
394
+ if (!upgradePending(err)) throw err;
395
+ }
396
+ return dashboard;
397
+ };
398
+ const dir = dashboard === null ? (opts.dir ?? dataDir()) : dashboard.store.dir;
399
+ const token = newActionToken();
400
+ // What an action is told about where to run: two strings, the store's
401
+ // directory and the configuration's path. NOT the source above.
402
+ const actionContext: ActionContext = {
403
+ dir,
404
+ ...(opts.config === undefined ? {} : { config: opts.config }),
405
+ };
406
+ let boundPort = 0;
245
407
 
246
408
  const server = createServer((req, res) => {
409
+ const method = req.method ?? "GET";
410
+ const rawPath = (req.url ?? "/").split("?")[0] ?? "/";
411
+ if (method === "POST" && rawPath.startsWith(ACTION_PREFIX)) {
412
+ if (dashboard === null) {
413
+ req.resume();
414
+ send(res, 503, { error: "upgrade-pending", message: UPGRADE_PENDING_SENTENCE });
415
+ return;
416
+ }
417
+ void handleAction(req, res, rawPath.slice(ACTION_PREFIX.length), token, boundPort, actionContext);
418
+ return;
419
+ }
247
420
  let reply: Reply;
421
+ if (method !== "GET" && method !== "HEAD") {
422
+ reply = json({ error: `${method} is not something this dashboard answers; nothing was done` }, 405);
423
+ res.writeHead(reply.status, { ...reply.headers, allow: "GET, HEAD" });
424
+ res.end(reply.body);
425
+ return;
426
+ }
248
427
  try {
249
428
  const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
250
- reply = router(url, req.headers.host ?? null, src);
429
+ const open = current();
430
+ reply =
431
+ open === null
432
+ ? isAllowedHost(req.headers.host ?? null)
433
+ ? upgradePendingReply(url.pathname)
434
+ : forbiddenHost()
435
+ : router(url, req.headers.host ?? null, open.source, { token });
251
436
  } catch (err) {
252
437
  reply = {
253
438
  status: 500,
@@ -256,7 +441,7 @@ export function startDashboard(opts: ServeOptions = {}): Promise<RunningDashboar
256
441
  };
257
442
  }
258
443
  res.writeHead(reply.status, reply.headers);
259
- res.end(reply.body);
444
+ res.end(reply.bytes ?? reply.body);
260
445
  });
261
446
 
262
447
  return new Promise<RunningDashboard>((ok, fail) => {
@@ -265,15 +450,18 @@ export function startDashboard(opts: ServeOptions = {}): Promise<RunningDashboar
265
450
  server.removeListener("error", fail);
266
451
  const address = server.address();
267
452
  const port = typeof address === "object" && address !== null ? address.port : resolvePort(opts);
453
+ boundPort = port;
268
454
  ok({
269
455
  port,
270
456
  url: `http://127.0.0.1:${port}`,
271
457
  dir,
458
+ token,
272
459
  server,
460
+ upgradePending: pendingAtStart,
273
461
  stop: () =>
274
462
  new Promise<void>((done) => {
275
463
  server.close(() => {
276
- dashboard.close();
464
+ dashboard?.close();
277
465
  done();
278
466
  });
279
467
  // Node keeps a server open while a keep-alive socket lives; the
@@ -285,3 +473,92 @@ export function startDashboard(opts: ServeOptions = {}): Promise<RunningDashboar
285
473
  });
286
474
  });
287
475
  }
476
+
477
+ function header(req: IncomingMessage, name: string): string | null {
478
+ const v = req.headers[name];
479
+ if (Array.isArray(v)) return v.length === 1 ? (v[0] ?? null) : null;
480
+ return typeof v === "string" ? v : null;
481
+ }
482
+
483
+ function send(res: ServerResponse, status: number, body: unknown): void {
484
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8", ...NO_STORE });
485
+ res.end(JSON.stringify(body));
486
+ }
487
+
488
+ /**
489
+ * One POST to `/api/action/<name>`: the guard, then the body (capped), then
490
+ * `actions.ts`. The guard runs BEFORE a byte of the body is read.
491
+ */
492
+ async function handleAction(
493
+ req: IncomingMessage,
494
+ res: ServerResponse,
495
+ name: string,
496
+ token: string,
497
+ boundPort: number,
498
+ ctx: ActionContext,
499
+ ): Promise<void> {
500
+ const refused = checkActionRequest(
501
+ {
502
+ method: req.method ?? "",
503
+ host: header(req, "host"),
504
+ origin: header(req, "origin"),
505
+ contentType: header(req, "content-type"),
506
+ token: header(req, TOKEN_HEADER),
507
+ fetchSite: header(req, "sec-fetch-site"),
508
+ },
509
+ token,
510
+ boundPort,
511
+ );
512
+ if (refused !== null) {
513
+ req.resume();
514
+ send(res, refused.status, { error: refused.error });
515
+ return;
516
+ }
517
+ let body: unknown;
518
+ try {
519
+ body = JSON.parse(await readBody(req));
520
+ } catch (err) {
521
+ const tooBig = err instanceof Error && err.message === "too-large";
522
+ send(res, tooBig ? 413 : 400, {
523
+ error: tooBig
524
+ ? `an action's body is at most ${String(MAX_BODY_BYTES)} bytes; nothing was done`
525
+ : "an action's body is JSON; nothing was done",
526
+ });
527
+ return;
528
+ }
529
+ try {
530
+ const result = await runAction(name, body, ctx);
531
+ send(res, result.status, result.body);
532
+ } catch (err) {
533
+ send(res, 500, { error: err instanceof Error ? err.message : String(err) });
534
+ }
535
+ }
536
+
537
+ function readBody(req: IncomingMessage): Promise<string> {
538
+ return new Promise((ok, fail) => {
539
+ const chunks: Buffer[] = [];
540
+ let size = 0;
541
+ let done = false;
542
+ req.on("data", (chunk: Buffer) => {
543
+ if (done) return;
544
+ size += chunk.length;
545
+ if (size > MAX_BODY_BYTES) {
546
+ done = true;
547
+ req.resume();
548
+ fail(new Error("too-large"));
549
+ return;
550
+ }
551
+ chunks.push(chunk);
552
+ });
553
+ req.on("end", () => {
554
+ if (done) return;
555
+ done = true;
556
+ ok(Buffer.concat(chunks).toString("utf8"));
557
+ });
558
+ req.on("error", (err) => {
559
+ if (done) return;
560
+ done = true;
561
+ fail(err);
562
+ });
563
+ });
564
+ }