@ddtcorex/dsh-maestro-core 0.10.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 (285) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +209 -0
  3. package/cordis.patch.yml +43 -0
  4. package/lib/bin.d.ts +2 -0
  5. package/lib/bin.js +3 -0
  6. package/lib/boot-guard.d.ts +33 -0
  7. package/lib/boot-guard.js +68 -0
  8. package/lib/boot-lock.d.ts +56 -0
  9. package/lib/boot-lock.js +155 -0
  10. package/lib/cli.d.ts +31 -0
  11. package/lib/cli.js +336 -0
  12. package/lib/client.js +2901 -0
  13. package/lib/config/index.d.ts +34 -0
  14. package/lib/config/index.js +62 -0
  15. package/lib/config/service.d.ts +18 -0
  16. package/lib/config/service.js +28 -0
  17. package/lib/config.d.ts +1 -0
  18. package/lib/config.js +19 -0
  19. package/lib/daemon-freshness.d.ts +48 -0
  20. package/lib/daemon-freshness.js +122 -0
  21. package/lib/debug-agent.d.ts +17 -0
  22. package/lib/debug-agent.js +144 -0
  23. package/lib/dsh-session.d.ts +26 -0
  24. package/lib/dsh-session.js +45 -0
  25. package/lib/guard/config.d.ts +82 -0
  26. package/lib/guard/config.js +211 -0
  27. package/lib/guard/decide.d.ts +30 -0
  28. package/lib/guard/decide.js +38 -0
  29. package/lib/guard/full-scan-tool.d.ts +6 -0
  30. package/lib/guard/full-scan-tool.js +65 -0
  31. package/lib/guard/index.d.ts +85 -0
  32. package/lib/guard/index.js +254 -0
  33. package/lib/guard/journal.d.ts +146 -0
  34. package/lib/guard/journal.js +398 -0
  35. package/lib/guard/migrate.d.ts +15 -0
  36. package/lib/guard/migrate.js +42 -0
  37. package/lib/guard/parse.d.ts +193 -0
  38. package/lib/guard/parse.js +1103 -0
  39. package/lib/guard/paths.d.ts +104 -0
  40. package/lib/guard/paths.js +254 -0
  41. package/lib/guard/permission-policy.d.ts +10 -0
  42. package/lib/guard/permission-policy.js +21 -0
  43. package/lib/guard/redact.d.ts +25 -0
  44. package/lib/guard/redact.js +52 -0
  45. package/lib/guard/rules.d.ts +65 -0
  46. package/lib/guard/rules.js +832 -0
  47. package/lib/guard/status-tool.d.ts +54 -0
  48. package/lib/guard/status-tool.js +195 -0
  49. package/lib/guard/tiers.d.ts +2 -0
  50. package/lib/guard/tiers.js +1 -0
  51. package/lib/guard/validators.d.ts +4 -0
  52. package/lib/guard/validators.js +45 -0
  53. package/lib/health-poller.d.ts +90 -0
  54. package/lib/health-poller.js +430 -0
  55. package/lib/index.d.ts +7 -0
  56. package/lib/index.js +7 -0
  57. package/lib/intents.d.ts +32 -0
  58. package/lib/intents.js +49 -0
  59. package/lib/notifier.d.ts +12 -0
  60. package/lib/notifier.js +62 -0
  61. package/lib/paths.d.ts +13 -0
  62. package/lib/paths.js +70 -0
  63. package/lib/plugin.d.ts +250 -0
  64. package/lib/plugin.js +1126 -0
  65. package/lib/preset.d.ts +73 -0
  66. package/lib/preset.js +158 -0
  67. package/lib/report.d.ts +11 -0
  68. package/lib/report.js +58 -0
  69. package/lib/restart-exec.d.ts +35 -0
  70. package/lib/restart-exec.js +60 -0
  71. package/lib/restart-guards.d.ts +39 -0
  72. package/lib/restart-guards.js +150 -0
  73. package/lib/restart-tool.d.ts +124 -0
  74. package/lib/restart-tool.js +539 -0
  75. package/lib/restart-web.d.ts +26 -0
  76. package/lib/restart-web.js +58 -0
  77. package/lib/resume-log.d.ts +24 -0
  78. package/lib/resume-log.js +18 -0
  79. package/lib/resume-tools.d.ts +131 -0
  80. package/lib/resume-tools.js +337 -0
  81. package/lib/resume.d.ts +33 -0
  82. package/lib/resume.js +221 -0
  83. package/lib/scan.d.ts +20 -0
  84. package/lib/scan.js +71 -0
  85. package/lib/self-kill-guard.d.ts +81 -0
  86. package/lib/self-kill-guard.js +208 -0
  87. package/lib/session-health.d.ts +89 -0
  88. package/lib/session-health.js +274 -0
  89. package/lib/session-log-file.d.ts +22 -0
  90. package/lib/session-log-file.js +74 -0
  91. package/lib/skill-provider.d.ts +6 -0
  92. package/lib/skill-provider.js +73 -0
  93. package/lib/snapshot.d.ts +59 -0
  94. package/lib/snapshot.js +358 -0
  95. package/lib/source.d.ts +19 -0
  96. package/lib/source.js +19 -0
  97. package/lib/store/index.d.ts +42 -0
  98. package/lib/store/index.js +340 -0
  99. package/lib/store/legacy.d.ts +17 -0
  100. package/lib/store/legacy.js +85 -0
  101. package/lib/supervisor.d.ts +119 -0
  102. package/lib/supervisor.js +741 -0
  103. package/lib/sync/backup-config.d.ts +55 -0
  104. package/lib/sync/backup-config.js +119 -0
  105. package/lib/sync/backup-service.d.ts +110 -0
  106. package/lib/sync/backup-service.js +440 -0
  107. package/lib/sync/bidirectional.d.ts +39 -0
  108. package/lib/sync/bidirectional.js +25 -0
  109. package/lib/sync/cli.d.ts +38 -0
  110. package/lib/sync/cli.js +536 -0
  111. package/lib/sync/config.d.ts +77 -0
  112. package/lib/sync/config.js +90 -0
  113. package/lib/sync/fingerprint.d.ts +29 -0
  114. package/lib/sync/fingerprint.js +65 -0
  115. package/lib/sync/hashing.d.ts +9 -0
  116. package/lib/sync/hashing.js +47 -0
  117. package/lib/sync/index.d.ts +6 -0
  118. package/lib/sync/index.js +634 -0
  119. package/lib/sync/machine-id.d.ts +29 -0
  120. package/lib/sync/machine-id.js +66 -0
  121. package/lib/sync/merge.d.ts +33 -0
  122. package/lib/sync/merge.js +88 -0
  123. package/lib/sync/peer-host.d.ts +22 -0
  124. package/lib/sync/peer-host.js +62 -0
  125. package/lib/sync/process-runner.d.ts +31 -0
  126. package/lib/sync/process-runner.js +161 -0
  127. package/lib/sync/remote-agent.d.ts +42 -0
  128. package/lib/sync/remote-agent.js +217 -0
  129. package/lib/sync/remote-cache.d.ts +18 -0
  130. package/lib/sync/remote-cache.js +60 -0
  131. package/lib/sync/remote-manifest.d.ts +8 -0
  132. package/lib/sync/remote-manifest.js +64 -0
  133. package/lib/sync/s3-object-store.d.ts +38 -0
  134. package/lib/sync/s3-object-store.js +126 -0
  135. package/lib/sync/session-merge.d.ts +18 -0
  136. package/lib/sync/session-merge.js +191 -0
  137. package/lib/sync/session-plan.d.ts +29 -0
  138. package/lib/sync/session-plan.js +213 -0
  139. package/lib/sync/sigv4.d.ts +20 -0
  140. package/lib/sync/sigv4.js +57 -0
  141. package/lib/sync/snapshot.d.ts +21 -0
  142. package/lib/sync/snapshot.js +176 -0
  143. package/lib/sync/ssh-mux.d.ts +12 -0
  144. package/lib/sync/ssh-mux.js +48 -0
  145. package/lib/sync/sync-plan.d.ts +24 -0
  146. package/lib/sync/sync-plan.js +366 -0
  147. package/lib/sync/sync-service.d.ts +177 -0
  148. package/lib/sync/sync-service.js +819 -0
  149. package/lib/sync/sync-types.d.ts +87 -0
  150. package/lib/sync/sync-types.js +1 -0
  151. package/lib/sync/transport.d.ts +75 -0
  152. package/lib/sync/transport.js +200 -0
  153. package/lib/sync/tunnel-restore.d.ts +77 -0
  154. package/lib/sync/tunnel-restore.js +142 -0
  155. package/lib/sync/validation.d.ts +10 -0
  156. package/lib/sync/validation.js +83 -0
  157. package/lib/tool-view.d.ts +62 -0
  158. package/lib/tool-view.js +70 -0
  159. package/lib/types/client/auto-reload.d.ts +8 -0
  160. package/lib/types/client/auto-reload.d.ts.map +1 -0
  161. package/lib/types/client/config/MaestroSettings.d.ts +25 -0
  162. package/lib/types/client/config/MaestroSettings.d.ts.map +1 -0
  163. package/lib/types/client/config/components/BrandMark.d.ts +50 -0
  164. package/lib/types/client/config/components/BrandMark.d.ts.map +1 -0
  165. package/lib/types/client/config/guard-view.d.ts +83 -0
  166. package/lib/types/client/config/guard-view.d.ts.map +1 -0
  167. package/lib/types/client/config/index.d.ts +20 -0
  168. package/lib/types/client/config/index.d.ts.map +1 -0
  169. package/lib/types/client/config/maestro-mark.d.ts +29 -0
  170. package/lib/types/client/config/maestro-mark.d.ts.map +1 -0
  171. package/lib/types/client/config/settings-nav-icon.d.ts +21 -0
  172. package/lib/types/client/config/settings-nav-icon.d.ts.map +1 -0
  173. package/lib/types/client/index.d.ts +16 -0
  174. package/lib/types/client/index.d.ts.map +1 -0
  175. package/lib/types/client/sync/R2SyncPanel.d.ts +6 -0
  176. package/lib/types/client/sync/R2SyncPanel.d.ts.map +1 -0
  177. package/lib/types/client/sync/SyncPanel.d.ts +12 -0
  178. package/lib/types/client/sync/SyncPanel.d.ts.map +1 -0
  179. package/lib/types/client/sync/confirm-dialog.d.ts +43 -0
  180. package/lib/types/client/sync/confirm-dialog.d.ts.map +1 -0
  181. package/lib/types/client/sync/index.d.ts +10 -0
  182. package/lib/types/client/sync/index.d.ts.map +1 -0
  183. package/lib/types/client/sync/ui.d.ts +79 -0
  184. package/lib/types/client/sync/ui.d.ts.map +1 -0
  185. package/lib/types/client/sync/use-backup.d.ts +50 -0
  186. package/lib/types/client/sync/use-backup.d.ts.map +1 -0
  187. package/lib/types/client/sync/use-sync.d.ts +88 -0
  188. package/lib/types/client/sync/use-sync.d.ts.map +1 -0
  189. package/package.json +89 -0
  190. package/skills/dsh-safe-restart/SKILL.md +206 -0
  191. package/skills/dsh-safe-restart/scripts/restart-dsh-web.sh +468 -0
  192. package/src/client/auto-reload.ts +104 -0
  193. package/src/client/config/MaestroSettings.tsx +892 -0
  194. package/src/client/config/components/BrandMark.tsx +94 -0
  195. package/src/client/config/guard-view.ts +187 -0
  196. package/src/client/config/index.tsx +109 -0
  197. package/src/client/config/maestro-mark.ts +37 -0
  198. package/src/client/config/settings-nav-icon.ts +68 -0
  199. package/src/client/index.tsx +33 -0
  200. package/src/client/sync/R2SyncPanel.tsx +260 -0
  201. package/src/client/sync/SyncPanel.tsx +422 -0
  202. package/src/client/sync/confirm-dialog.tsx +202 -0
  203. package/src/client/sync/index.tsx +336 -0
  204. package/src/client/sync/ui.tsx +313 -0
  205. package/src/client/sync/use-backup.ts +207 -0
  206. package/src/client/sync/use-sync.ts +502 -0
  207. package/src/host/bin.ts +3 -0
  208. package/src/host/boot-guard.ts +76 -0
  209. package/src/host/boot-lock.ts +155 -0
  210. package/src/host/cli.ts +288 -0
  211. package/src/host/config/index.ts +78 -0
  212. package/src/host/config/service.ts +40 -0
  213. package/src/host/config.ts +18 -0
  214. package/src/host/daemon-freshness.ts +143 -0
  215. package/src/host/debug-agent.ts +145 -0
  216. package/src/host/dsh-session.ts +56 -0
  217. package/src/host/dsh-skill.d.ts +44 -0
  218. package/src/host/guard/augment.d.ts +33 -0
  219. package/src/host/guard/config.ts +244 -0
  220. package/src/host/guard/decide.ts +40 -0
  221. package/src/host/guard/full-scan-tool.ts +61 -0
  222. package/src/host/guard/index.ts +281 -0
  223. package/src/host/guard/journal.ts +440 -0
  224. package/src/host/guard/migrate.ts +41 -0
  225. package/src/host/guard/parse.ts +1150 -0
  226. package/src/host/guard/paths.ts +239 -0
  227. package/src/host/guard/permission-policy.ts +15 -0
  228. package/src/host/guard/redact.ts +64 -0
  229. package/src/host/guard/rules.ts +891 -0
  230. package/src/host/guard/status-tool.ts +229 -0
  231. package/src/host/guard/tiers.ts +2 -0
  232. package/src/host/guard/validators.ts +29 -0
  233. package/src/host/health-poller.ts +446 -0
  234. package/src/host/index.ts +7 -0
  235. package/src/host/intents.ts +67 -0
  236. package/src/host/notifier.ts +71 -0
  237. package/src/host/paths.ts +70 -0
  238. package/src/host/plugin.ts +1097 -0
  239. package/src/host/preset.ts +170 -0
  240. package/src/host/report.ts +71 -0
  241. package/src/host/restart-exec.ts +81 -0
  242. package/src/host/restart-guards.ts +150 -0
  243. package/src/host/restart-tool.ts +483 -0
  244. package/src/host/restart-web.ts +72 -0
  245. package/src/host/resume-log.ts +39 -0
  246. package/src/host/resume-tools.ts +385 -0
  247. package/src/host/resume.ts +204 -0
  248. package/src/host/scan.ts +61 -0
  249. package/src/host/self-kill-guard.ts +216 -0
  250. package/src/host/session-health.ts +236 -0
  251. package/src/host/session-log-file.ts +77 -0
  252. package/src/host/skill-provider.ts +69 -0
  253. package/src/host/snapshot.ts +337 -0
  254. package/src/host/source.ts +19 -0
  255. package/src/host/store/index.ts +348 -0
  256. package/src/host/store/legacy.ts +96 -0
  257. package/src/host/supervisor.ts +720 -0
  258. package/src/host/sync/backup-config.ts +159 -0
  259. package/src/host/sync/backup-service.ts +453 -0
  260. package/src/host/sync/bidirectional.ts +66 -0
  261. package/src/host/sync/cli.ts +539 -0
  262. package/src/host/sync/config.ts +119 -0
  263. package/src/host/sync/fingerprint.ts +83 -0
  264. package/src/host/sync/hashing.ts +58 -0
  265. package/src/host/sync/index.ts +737 -0
  266. package/src/host/sync/machine-id.ts +81 -0
  267. package/src/host/sync/merge.ts +102 -0
  268. package/src/host/sync/peer-host.ts +65 -0
  269. package/src/host/sync/process-runner.ts +177 -0
  270. package/src/host/sync/remote-agent.ts +213 -0
  271. package/src/host/sync/remote-cache.ts +68 -0
  272. package/src/host/sync/remote-manifest.ts +70 -0
  273. package/src/host/sync/s3-object-store.ts +144 -0
  274. package/src/host/sync/session-merge.ts +220 -0
  275. package/src/host/sync/session-plan.ts +237 -0
  276. package/src/host/sync/sigv4.ts +81 -0
  277. package/src/host/sync/snapshot.ts +162 -0
  278. package/src/host/sync/ssh-mux.ts +56 -0
  279. package/src/host/sync/sync-plan.ts +366 -0
  280. package/src/host/sync/sync-service.ts +855 -0
  281. package/src/host/sync/sync-types.ts +102 -0
  282. package/src/host/sync/transport.ts +261 -0
  283. package/src/host/sync/tunnel-restore.ts +160 -0
  284. package/src/host/sync/validation.ts +91 -0
  285. package/src/host/tool-view.ts +98 -0
@@ -0,0 +1,440 @@
1
+ import { appendFile, chmod, mkdir, readFile, readdir, rename, stat, unlink } from 'node:fs/promises'
2
+ import { homedir } from 'node:os'
3
+ import { dirname, join } from 'node:path'
4
+ import { TIERS, type Tier } from './tiers.js'
5
+ import { redact } from './redact.js'
6
+
7
+ export type AskOutcome = 'granted' | 'rejected' | 'cancelled' | 'unavailable' | 'error'
8
+
9
+ export interface JournalEntry {
10
+ ts: string
11
+ session?: string
12
+ tool: string
13
+ rule: string
14
+ tier: Tier
15
+ target: string
16
+ repo?: string
17
+ branch?: string
18
+ cwd?: string
19
+ outcome?: AskOutcome | 'passed' | 'denied'
20
+ askMs?: number
21
+ redacted: true
22
+ note?: string
23
+ }
24
+
25
+ /** Retention knobs. Count and age are BOTH windows; the larger one wins. */
26
+ export interface RotateOptions {
27
+ /** Keep at least the newest N archive files (default 14). */
28
+ retainFiles?: number
29
+ /** Keep at least archives newer than N days (default 30). */
30
+ retainDays?: number
31
+ }
32
+
33
+ /**
34
+ * The journal block of `domains.guard`, read ONCE when the guard boots. These
35
+ * are boot-time knobs: unlike the per-call rule config the handler re-reads on
36
+ * every decision, changing them requires a host restart. Every field defaults
37
+ * to the built-in behaviour (enabled, counters on, 14 files / 30 days).
38
+ */
39
+ export interface JournalOptions {
40
+ /** `false` → `append()` writes nothing and `startFlush()` never starts. */
41
+ enabled?: boolean
42
+ /** `false` → `count()` is a no-op, so allow decisions never reach disk. */
43
+ allowCounters?: boolean
44
+ /** Default `retainFiles` for `rotate()`. */
45
+ retainFiles?: number
46
+ /** Default `retainDays` for `rotate()`. */
47
+ retainDays?: number
48
+ }
49
+
50
+ /** The rule id of the periodic aggregate line (see `flushCounters`). */
51
+ export const COUNTERS_RULE = 'counters'
52
+
53
+ const DEFAULT_RETAIN_FILES = 14
54
+ const DEFAULT_RETAIN_DAYS = 30
55
+ const DEFAULT_READ_LIMIT = 200
56
+ const DAY_MS = 86_400_000
57
+
58
+ /** `journal-2026-09-14.jsonl`, plus `-<n>` for a second roll on the same day. */
59
+ const ARCHIVE_RE = /^journal-(\d{4}-\d{2}-\d{2})(?:-(\d+))?\.jsonl$/
60
+
61
+ interface ArchiveRef {
62
+ name: string
63
+ /** The date carried by the file name (`YYYY-MM-DD`). */
64
+ date: string
65
+ /** 0 for the plain dated name; the collision counter otherwise. */
66
+ seq: number
67
+ }
68
+
69
+ function parseArchive(name: string): ArchiveRef | undefined {
70
+ const m = ARCHIVE_RE.exec(name)
71
+ if (!m) return undefined
72
+ return { name, date: m[1], seq: m[2] === undefined ? 0 : Number(m[2]) }
73
+ }
74
+
75
+ /** Oldest → newest, so the retention window can count from the end. */
76
+ function byAge(a: ArchiveRef, b: ArchiveRef): number {
77
+ if (a.date !== b.date) return a.date < b.date ? -1 : 1
78
+ return a.seq - b.seq
79
+ }
80
+
81
+ function resolveHome(dshHome?: string): string {
82
+ return dshHome ?? process.env.DSH_HOME ?? join(homedir(), '.dsh')
83
+ }
84
+ export function journalDir(dshHome?: string): string {
85
+ return join(resolveHome(dshHome), 'dsh-maestro-guard')
86
+ }
87
+ export function journalPath(dshHome?: string): string {
88
+ return join(journalDir(dshHome), 'journal.jsonl')
89
+ }
90
+
91
+ /**
92
+ * The boot-rotate decision: roll the live journal when its last write landed on
93
+ * an earlier UTC day than the current clock. The live file carries no date in
94
+ * its name (`journal.jsonl`), so the day is read from its mtime — one `stat`,
95
+ * no file read. `undefined` (no live file) is never a rotation: a boot with
96
+ * nothing recorded must not create an empty archive, and a missing file must
97
+ * never fail boot. UTC, because that is the day `freeArchivePath` names archives
98
+ * by.
99
+ */
100
+ export function shouldRotateAtBoot(liveMtimeMs: number | undefined, now: number): boolean {
101
+ if (liveMtimeMs === undefined || !Number.isFinite(liveMtimeMs)) return false
102
+ return dayOf(liveMtimeMs) !== dayOf(now)
103
+ }
104
+
105
+ /** The `YYYY-MM-DD` UTC day a timestamp falls in — the archive naming unit. */
106
+ function dayOf(ms: number): string {
107
+ return new Date(ms).toISOString().slice(0, 10)
108
+ }
109
+
110
+ /**
111
+ * Rotations are serialized through one in-flight promise chain (the idiom the
112
+ * deleted `pending.ts` used for its store writes). `freeArchivePath` is a
113
+ * stat-then-rename, so two overlapping calls would both pick the same free
114
+ * candidate and POSIX `rename` would replace the destination — destroying the
115
+ * first call's archive. Nothing calls `rotate()` concurrently today, but the
116
+ * status tools add a second caller, and a name collision must never cost a day
117
+ * of history.
118
+ */
119
+ let _rotationQueue: Promise<unknown> = Promise.resolve()
120
+ function enqueueRotation<T>(fn: () => Promise<T>): Promise<T> {
121
+ const p = _rotationQueue.then(fn, fn) as Promise<T>
122
+ _rotationQueue = p.catch(() => {})
123
+ return p
124
+ }
125
+
126
+ export class Journal {
127
+ /**
128
+ * Decisions per `${rule}|${tier}` since the last flush. `allow` is the tier
129
+ * that lives only here: it is counted in memory and reaches disk as one
130
+ * aggregate line, so an ordinary command costs no journal I/O.
131
+ */
132
+ private counters = new Map<string, number>()
133
+
134
+ /** Boot-time gates derived from {@link JournalOptions}. */
135
+ private readonly writesEnabled: boolean
136
+ private readonly allowCounters: boolean
137
+
138
+ constructor(private dshHome?: string, private now: () => number = Date.now, private opts: JournalOptions = {}) {
139
+ this.writesEnabled = opts.enabled !== false
140
+ this.allowCounters = opts.allowCounters !== false
141
+ }
142
+
143
+ /** The journal file this instance reads and appends (`journalPath` for its home). */
144
+ get path(): string {
145
+ return journalPath(this.dshHome)
146
+ }
147
+
148
+ /**
149
+ * The boot-time write gate. Exposed because the status tool must report what
150
+ * this instance actually does — not a second reading of the config block,
151
+ * which could disagree with the journal a long-running host already built.
152
+ */
153
+ get enabled(): boolean {
154
+ return this.writesEnabled
155
+ }
156
+
157
+ async append(entry: Omit<JournalEntry, 'ts' | 'redacted'>): Promise<void> {
158
+ if (!this.writesEnabled) return
159
+ try {
160
+ // Serialization is inside the try too: an unserializable field (BigInt, a
161
+ // circular reference) or a throwing clock must not break the never-throw
162
+ // guarantee any more than a filesystem failure may.
163
+ const line = JSON.stringify({ ...redactEntry(entry), ts: new Date(this.now()).toISOString(), redacted: true })
164
+ const p = journalPath(this.dshHome)
165
+ await mkdir(dirname(p), { recursive: true, mode: 0o700 })
166
+ await appendFile(p, line + '\n', { encoding: 'utf8', mode: 0o600 })
167
+ await chmod(p, 0o600)
168
+ } catch (e) {
169
+ // A journal failure must never change a decision.
170
+ console.error('[dsh-maestro-guard] journal write failed:', (e as Error)?.message)
171
+ }
172
+ }
173
+
174
+ /**
175
+ * Count one decision. Synchronous and I/O-free on purpose: this runs inside
176
+ * the decision path, so it must never cost more than two Map operations. The
177
+ * `rule` is part of the key (a later reader can break the aggregate down by
178
+ * rule) even though the flushed note reports tier totals.
179
+ */
180
+ count(rule: string, tier: Tier): void {
181
+ if (!this.allowCounters) return
182
+ const key = `${rule}|${tier}`
183
+ this.counters.set(key, (this.counters.get(key) ?? 0) + 1)
184
+ }
185
+
186
+ /**
187
+ * Persist the pending counters as ONE ordinary journal entry and clear them.
188
+ * The counters are drained before the write is awaited, so a decision counted
189
+ * during the write lands in the next flush rather than being lost or doubled.
190
+ * An empty map writes nothing — flushes are periodic, quiet ones are free.
191
+ */
192
+ async flushCounters(): Promise<void> {
193
+ if (this.counters.size === 0) return
194
+ const drained = this.counters
195
+ this.counters = new Map()
196
+ await this.append({
197
+ tool: 'guard',
198
+ rule: COUNTERS_RULE,
199
+ tier: 'allow',
200
+ target: COUNTERS_RULE,
201
+ note: renderCounters(drained),
202
+ })
203
+ }
204
+
205
+ /**
206
+ * The recent journal, NEWEST FIRST. The live file is the newest source, so it
207
+ * is read first, then the archives newest → oldest; `limit` keeps the most
208
+ * recent entries only and stops the walk as soon as it is satisfied. The walk
209
+ * must cross archives: reading the newest one alone would answer a
210
+ * `read(1000)` with a single day of history. A missing directory, a missing
211
+ * file or a torn line is skipped rather than thrown — a reader must not be
212
+ * able to break the guard.
213
+ */
214
+ async read(limit: number = DEFAULT_READ_LIMIT): Promise<JournalEntry[]> {
215
+ if (!Number.isFinite(limit) || limit <= 0) return []
216
+ const dir = journalDir(this.dshHome)
217
+ // Newest source first. The live file is newest; the archives follow, newest
218
+ // to oldest, so stopping at `limit` has still seen the newest entries.
219
+ const sources: string[] = [journalPath(this.dshHome)]
220
+ try {
221
+ const archives = (await readdir(dir)).map(parseArchive).filter((a): a is ArchiveRef => a !== undefined).sort(byAge)
222
+ for (let i = archives.length - 1; i >= 0; i--) sources.push(join(dir, archives[i].name))
223
+ } catch {
224
+ // No journal directory yet: the live read below still applies.
225
+ }
226
+ const entries: JournalEntry[] = []
227
+ for (const p of sources) {
228
+ if (entries.length >= limit) break
229
+ let text: string
230
+ try {
231
+ text = await readFile(p, 'utf8')
232
+ } catch {
233
+ continue
234
+ }
235
+ const lines = text.split('\n')
236
+ // Newest line of this source first: a torn trailing line is skipped
237
+ // before the complete lines of the same file are kept.
238
+ for (let i = lines.length - 1; i >= 0; i--) {
239
+ const line = lines[i]
240
+ if (!line.trim()) continue
241
+ try {
242
+ entries.push(JSON.parse(line) as JournalEntry)
243
+ } catch {
244
+ // A half-written line is not an error for a reader.
245
+ }
246
+ if (entries.length >= limit) break
247
+ }
248
+ }
249
+ return entries
250
+ }
251
+
252
+ /**
253
+ * Roll `journal.jsonl` into a dated archive, then enforce retention and
254
+ * return the REMOVED archive paths (the new archive is not a removal).
255
+ * Retention keeps an archive that is inside the file window OR inside the day
256
+ * window — i.e. the newer of the two — so a quiet month never prunes a busy
257
+ * fortnight. Never throws.
258
+ *
259
+ * Overlapping calls are serialized (see {@link enqueueRotation}) and the
260
+ * archive a call just created is never a retention candidate: with both
261
+ * windows empty the call would otherwise unlink the entire rolled history it
262
+ * had just renamed into place.
263
+ */
264
+ async rotate(opts: RotateOptions = {}): Promise<string[]> {
265
+ return enqueueRotation(() => this.rotateOnce(opts))
266
+ }
267
+
268
+ private async rotateOnce(opts: RotateOptions): Promise<string[]> {
269
+ const removed: string[] = []
270
+ try {
271
+ const dir = journalDir(this.dshHome)
272
+ await mkdir(dir, { recursive: true, mode: 0o700 })
273
+ const live = journalPath(this.dshHome)
274
+ let liveSize: number | undefined
275
+ try {
276
+ liveSize = (await stat(live)).size
277
+ } catch {
278
+ // Nothing to roll.
279
+ }
280
+ // An empty live file carries no decision; rolling it would only grow the
281
+ // archive set that the retention window then has to pay for.
282
+ let rolled: string | undefined
283
+ if (liveSize !== undefined && liveSize > 0) {
284
+ const target = await this.freeArchivePath(dir)
285
+ await rename(live, target)
286
+ rolled = target
287
+ // The rename already happened, so a failed chmod must not escape to the
288
+ // outer catch: that would abandon retention and report no removals for
289
+ // a rotation that in fact succeeded. Log it and carry on.
290
+ try {
291
+ await chmod(target, 0o600)
292
+ } catch (e) {
293
+ console.error('[dsh-maestro-guard] journal archive chmod failed:', (e as Error)?.message)
294
+ }
295
+ }
296
+ const retainFiles = opts.retainFiles ?? this.opts.retainFiles ?? DEFAULT_RETAIN_FILES
297
+ const retainDays = opts.retainDays ?? this.opts.retainDays ?? DEFAULT_RETAIN_DAYS
298
+ const dayCutoff = this.now() - retainDays * DAY_MS
299
+ const archives = (await readdir(dir)).map(parseArchive).filter((a): a is ArchiveRef => a !== undefined).sort(byAge)
300
+ for (let i = 0; i < archives.length; i++) {
301
+ const archive = archives[i]
302
+ const inFileWindow = i >= archives.length - retainFiles
303
+ const inDayWindow = Date.parse(`${archive.date}T00:00:00.000Z`) >= dayCutoff
304
+ if (inFileWindow || inDayWindow) continue
305
+ const p = join(dir, archive.name)
306
+ // The archive THIS call created holds the whole rolled history.
307
+ if (p === rolled) continue
308
+ try {
309
+ await unlink(p)
310
+ removed.push(p)
311
+ } catch {
312
+ // Already gone (or unreadable): retention is best-effort.
313
+ }
314
+ }
315
+ } catch (e) {
316
+ console.error('[dsh-maestro-guard] journal rotate failed:', (e as Error)?.message)
317
+ }
318
+ return removed
319
+ }
320
+
321
+ /**
322
+ * Flush the counters every `intervalMs` and return the disposer that stops
323
+ * it. The flush is periodic by design: the decision path only ever touches
324
+ * the in-memory map. The timer is unref'd so a pending flush never keeps the
325
+ * host process alive. A disabled journal starts no timer at all.
326
+ */
327
+ startFlush(intervalMs: number): () => void {
328
+ if (!this.writesEnabled) return () => {}
329
+ const timer = setInterval(() => {
330
+ void this.flushCounters()
331
+ }, intervalMs)
332
+ ;(timer as { unref?: () => void }).unref?.()
333
+ let stopped = false
334
+ return () => {
335
+ if (stopped) return
336
+ stopped = true
337
+ clearInterval(timer)
338
+ }
339
+ }
340
+
341
+ /**
342
+ * The BOOT roll: rotate when the live file's last write predates today, so
343
+ * the archive set — and the retention windows that prune it — advances even
344
+ * on a host that restarts daily. One `stat` is the only I/O; a missing live
345
+ * file, or one already written today, is a silent no-op. A disabled journal
346
+ * rolls nothing, the same rule `append` and `startFlush` follow.
347
+ *
348
+ * The roll is named by the rotation clock (today), like every other rotation;
349
+ * the file's contents are whatever accumulated since the last roll, so the
350
+ * archive day is the day the archive was made, never a claim about its
351
+ * contents.
352
+ */
353
+ async rotateIfStale(): Promise<string[]> {
354
+ if (!this.writesEnabled) return []
355
+ let mtimeMs: number | undefined
356
+ try {
357
+ mtimeMs = (await stat(journalPath(this.dshHome))).mtimeMs
358
+ } catch {
359
+ // No live file: nothing to roll, and boot must not fail on it.
360
+ return []
361
+ }
362
+ if (!shouldRotateAtBoot(mtimeMs, this.now())) return []
363
+ return this.rotate()
364
+ }
365
+
366
+ /**
367
+ * Rotate once per `intervalMs` (default: one day) and return the disposer that
368
+ * stops it. This is what makes `retainFiles`/`retainDays` take effect on a
369
+ * long-running host, not just at boot. The timer is unref'd so a pending roll
370
+ * never keeps the host process alive, and a disabled journal starts no timer
371
+ * at all — the same reversible-disposer discipline as {@link startFlush}.
372
+ */
373
+ startDailyRotation(intervalMs: number = DAY_MS): () => void {
374
+ if (!this.writesEnabled) return () => {}
375
+ const timer = setInterval(() => {
376
+ void this.rotate()
377
+ }, intervalMs)
378
+ ;(timer as { unref?: () => void }).unref?.()
379
+ let stopped = false
380
+ return () => {
381
+ if (stopped) return
382
+ stopped = true
383
+ clearInterval(timer)
384
+ }
385
+ }
386
+
387
+ /** The first unused `journal-<today>[-<n>].jsonl` under `dir`. */
388
+ private async freeArchivePath(dir: string): Promise<string> {
389
+ const date = dayOf(this.now())
390
+ for (let seq = 0; seq < 1000; seq++) {
391
+ const name = seq === 0 ? `journal-${date}.jsonl` : `journal-${date}-${seq}.jsonl`
392
+ const candidate = join(dir, name)
393
+ try {
394
+ await stat(candidate)
395
+ } catch {
396
+ return candidate
397
+ }
398
+ }
399
+ // 1000 collisions in one day is unreachable, but the fallback must still be
400
+ // a name this module can READ and PRUNE: interpolating the raw clock put a
401
+ // fractional millisecond into the name (`journal-<date>-<n>.<n>.jsonl`),
402
+ // which ARCHIVE_RE does not match, so such an archive would be invisible to
403
+ // `read()` and to retention forever. Truncate to a positive integer so the
404
+ // name always lands in the `-<n>` slot.
405
+ const seq = Math.max(1, Math.floor(this.now()))
406
+ return join(dir, `journal-${date}-${seq}.jsonl`)
407
+ }
408
+ }
409
+
410
+ /**
411
+ * `allow=2,ask=1` — tier totals in tier order, present tiers only. The rule is
412
+ * deliberately absent: the note is the tier roll-up, and a rule named after a
413
+ * secret would otherwise ride an aggregate line.
414
+ */
415
+ function renderCounters(counters: Map<string, number>): string {
416
+ const perTier = new Map<Tier, number>()
417
+ for (const [key, n] of counters) {
418
+ const tier = key.slice(key.lastIndexOf('|') + 1) as Tier
419
+ perTier.set(tier, (perTier.get(tier) ?? 0) + n)
420
+ }
421
+ return TIERS.filter((tier) => (perTier.get(tier) ?? 0) > 0)
422
+ .map((tier) => `${tier}=${perTier.get(tier)}`)
423
+ .join(',')
424
+ }
425
+
426
+ /**
427
+ * The single redaction choke point for the stored record. The `redacted: true`
428
+ * stamp is not a decoration: it is true only because every string this entry
429
+ * carries passes through the widened redactor here. Call sites stay free to pass
430
+ * raw verdict fields — a future caller that forgets cannot leak, and a
431
+ * non-string value (the throwaway object the never-throw test passes as `note`)
432
+ * is left untouched so serialization still fails exactly as before.
433
+ */
434
+ function redactEntry(entry: Omit<JournalEntry, 'ts' | 'redacted'>): Omit<JournalEntry, 'ts' | 'redacted'> {
435
+ const out: Record<string, unknown> = {}
436
+ for (const [key, value] of Object.entries(entry)) {
437
+ out[key] = typeof value === 'string' ? redact(value) : value
438
+ }
439
+ return out as Omit<JournalEntry, 'ts' | 'redacted'>
440
+ }
@@ -0,0 +1,41 @@
1
+ import { chmod, mkdir, rename, stat } from 'node:fs/promises'
2
+ import { join } from 'node:path'
3
+ import { Journal, journalDir } from './journal.js'
4
+
5
+ /**
6
+ * Retire the legacy ticket store (Task A4). The guard no longer reads tickets —
7
+ * the human answers through DSH's native approval service — so the old
8
+ * `pending.json` is moved out of its active path into the journal directory,
9
+ * where it is kept for reference but never consulted again.
10
+ *
11
+ * This runs once per boot inside `ctx.effect`; it is idempotent (a missing
12
+ * source is a no-op) and never throws, because a failed retirement must not
13
+ * stop the guard from booting.
14
+ */
15
+ export async function retireLegacyStore(journal: Journal, dshHome?: string): Promise<{ moved: boolean; to?: string }> {
16
+ const dir = journalDir(dshHome)
17
+ const from = join(dir, 'pending.json')
18
+ const to = join(dir, 'legacy-pending.json')
19
+ try {
20
+ await stat(from)
21
+ } catch {
22
+ return { moved: false }
23
+ }
24
+ try {
25
+ await mkdir(dir, { recursive: true, mode: 0o700 })
26
+ await rename(from, to)
27
+ await chmod(to, 0o600)
28
+ await journal.append({
29
+ tool: 'guard',
30
+ rule: 'guard.migration',
31
+ tier: 'journal',
32
+ target: to,
33
+ outcome: 'passed',
34
+ note: 'legacy ticket store retired; retained for reference, no longer read by the guard',
35
+ })
36
+ return { moved: true, to }
37
+ } catch (e) {
38
+ console.error('[dsh-maestro-guard] legacy store retirement failed:', (e as Error)?.message)
39
+ return { moved: false }
40
+ }
41
+ }