@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,398 @@
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 } from './tiers.js';
5
+ import { redact } from './redact.js';
6
+ /** The rule id of the periodic aggregate line (see `flushCounters`). */
7
+ export const COUNTERS_RULE = 'counters';
8
+ const DEFAULT_RETAIN_FILES = 14;
9
+ const DEFAULT_RETAIN_DAYS = 30;
10
+ const DEFAULT_READ_LIMIT = 200;
11
+ const DAY_MS = 86_400_000;
12
+ /** `journal-2026-09-14.jsonl`, plus `-<n>` for a second roll on the same day. */
13
+ const ARCHIVE_RE = /^journal-(\d{4}-\d{2}-\d{2})(?:-(\d+))?\.jsonl$/;
14
+ function parseArchive(name) {
15
+ const m = ARCHIVE_RE.exec(name);
16
+ if (!m)
17
+ return undefined;
18
+ return { name, date: m[1], seq: m[2] === undefined ? 0 : Number(m[2]) };
19
+ }
20
+ /** Oldest → newest, so the retention window can count from the end. */
21
+ function byAge(a, b) {
22
+ if (a.date !== b.date)
23
+ return a.date < b.date ? -1 : 1;
24
+ return a.seq - b.seq;
25
+ }
26
+ function resolveHome(dshHome) {
27
+ return dshHome ?? process.env.DSH_HOME ?? join(homedir(), '.dsh');
28
+ }
29
+ export function journalDir(dshHome) {
30
+ return join(resolveHome(dshHome), 'dsh-maestro-guard');
31
+ }
32
+ export function journalPath(dshHome) {
33
+ return join(journalDir(dshHome), 'journal.jsonl');
34
+ }
35
+ /**
36
+ * The boot-rotate decision: roll the live journal when its last write landed on
37
+ * an earlier UTC day than the current clock. The live file carries no date in
38
+ * its name (`journal.jsonl`), so the day is read from its mtime — one `stat`,
39
+ * no file read. `undefined` (no live file) is never a rotation: a boot with
40
+ * nothing recorded must not create an empty archive, and a missing file must
41
+ * never fail boot. UTC, because that is the day `freeArchivePath` names archives
42
+ * by.
43
+ */
44
+ export function shouldRotateAtBoot(liveMtimeMs, now) {
45
+ if (liveMtimeMs === undefined || !Number.isFinite(liveMtimeMs))
46
+ return false;
47
+ return dayOf(liveMtimeMs) !== dayOf(now);
48
+ }
49
+ /** The `YYYY-MM-DD` UTC day a timestamp falls in — the archive naming unit. */
50
+ function dayOf(ms) {
51
+ return new Date(ms).toISOString().slice(0, 10);
52
+ }
53
+ /**
54
+ * Rotations are serialized through one in-flight promise chain (the idiom the
55
+ * deleted `pending.ts` used for its store writes). `freeArchivePath` is a
56
+ * stat-then-rename, so two overlapping calls would both pick the same free
57
+ * candidate and POSIX `rename` would replace the destination — destroying the
58
+ * first call's archive. Nothing calls `rotate()` concurrently today, but the
59
+ * status tools add a second caller, and a name collision must never cost a day
60
+ * of history.
61
+ */
62
+ let _rotationQueue = Promise.resolve();
63
+ function enqueueRotation(fn) {
64
+ const p = _rotationQueue.then(fn, fn);
65
+ _rotationQueue = p.catch(() => { });
66
+ return p;
67
+ }
68
+ export class Journal {
69
+ dshHome;
70
+ now;
71
+ opts;
72
+ /**
73
+ * Decisions per `${rule}|${tier}` since the last flush. `allow` is the tier
74
+ * that lives only here: it is counted in memory and reaches disk as one
75
+ * aggregate line, so an ordinary command costs no journal I/O.
76
+ */
77
+ counters = new Map();
78
+ /** Boot-time gates derived from {@link JournalOptions}. */
79
+ writesEnabled;
80
+ allowCounters;
81
+ constructor(dshHome, now = Date.now, opts = {}) {
82
+ this.dshHome = dshHome;
83
+ this.now = now;
84
+ this.opts = opts;
85
+ this.writesEnabled = opts.enabled !== false;
86
+ this.allowCounters = opts.allowCounters !== false;
87
+ }
88
+ /** The journal file this instance reads and appends (`journalPath` for its home). */
89
+ get path() {
90
+ return journalPath(this.dshHome);
91
+ }
92
+ /**
93
+ * The boot-time write gate. Exposed because the status tool must report what
94
+ * this instance actually does — not a second reading of the config block,
95
+ * which could disagree with the journal a long-running host already built.
96
+ */
97
+ get enabled() {
98
+ return this.writesEnabled;
99
+ }
100
+ async append(entry) {
101
+ if (!this.writesEnabled)
102
+ return;
103
+ try {
104
+ // Serialization is inside the try too: an unserializable field (BigInt, a
105
+ // circular reference) or a throwing clock must not break the never-throw
106
+ // guarantee any more than a filesystem failure may.
107
+ const line = JSON.stringify({ ...redactEntry(entry), ts: new Date(this.now()).toISOString(), redacted: true });
108
+ const p = journalPath(this.dshHome);
109
+ await mkdir(dirname(p), { recursive: true, mode: 0o700 });
110
+ await appendFile(p, line + '\n', { encoding: 'utf8', mode: 0o600 });
111
+ await chmod(p, 0o600);
112
+ }
113
+ catch (e) {
114
+ // A journal failure must never change a decision.
115
+ console.error('[dsh-maestro-guard] journal write failed:', e?.message);
116
+ }
117
+ }
118
+ /**
119
+ * Count one decision. Synchronous and I/O-free on purpose: this runs inside
120
+ * the decision path, so it must never cost more than two Map operations. The
121
+ * `rule` is part of the key (a later reader can break the aggregate down by
122
+ * rule) even though the flushed note reports tier totals.
123
+ */
124
+ count(rule, tier) {
125
+ if (!this.allowCounters)
126
+ return;
127
+ const key = `${rule}|${tier}`;
128
+ this.counters.set(key, (this.counters.get(key) ?? 0) + 1);
129
+ }
130
+ /**
131
+ * Persist the pending counters as ONE ordinary journal entry and clear them.
132
+ * The counters are drained before the write is awaited, so a decision counted
133
+ * during the write lands in the next flush rather than being lost or doubled.
134
+ * An empty map writes nothing — flushes are periodic, quiet ones are free.
135
+ */
136
+ async flushCounters() {
137
+ if (this.counters.size === 0)
138
+ return;
139
+ const drained = this.counters;
140
+ this.counters = new Map();
141
+ await this.append({
142
+ tool: 'guard',
143
+ rule: COUNTERS_RULE,
144
+ tier: 'allow',
145
+ target: COUNTERS_RULE,
146
+ note: renderCounters(drained),
147
+ });
148
+ }
149
+ /**
150
+ * The recent journal, NEWEST FIRST. The live file is the newest source, so it
151
+ * is read first, then the archives newest → oldest; `limit` keeps the most
152
+ * recent entries only and stops the walk as soon as it is satisfied. The walk
153
+ * must cross archives: reading the newest one alone would answer a
154
+ * `read(1000)` with a single day of history. A missing directory, a missing
155
+ * file or a torn line is skipped rather than thrown — a reader must not be
156
+ * able to break the guard.
157
+ */
158
+ async read(limit = DEFAULT_READ_LIMIT) {
159
+ if (!Number.isFinite(limit) || limit <= 0)
160
+ return [];
161
+ const dir = journalDir(this.dshHome);
162
+ // Newest source first. The live file is newest; the archives follow, newest
163
+ // to oldest, so stopping at `limit` has still seen the newest entries.
164
+ const sources = [journalPath(this.dshHome)];
165
+ try {
166
+ const archives = (await readdir(dir)).map(parseArchive).filter((a) => a !== undefined).sort(byAge);
167
+ for (let i = archives.length - 1; i >= 0; i--)
168
+ sources.push(join(dir, archives[i].name));
169
+ }
170
+ catch {
171
+ // No journal directory yet: the live read below still applies.
172
+ }
173
+ const entries = [];
174
+ for (const p of sources) {
175
+ if (entries.length >= limit)
176
+ break;
177
+ let text;
178
+ try {
179
+ text = await readFile(p, 'utf8');
180
+ }
181
+ catch {
182
+ continue;
183
+ }
184
+ const lines = text.split('\n');
185
+ // Newest line of this source first: a torn trailing line is skipped
186
+ // before the complete lines of the same file are kept.
187
+ for (let i = lines.length - 1; i >= 0; i--) {
188
+ const line = lines[i];
189
+ if (!line.trim())
190
+ continue;
191
+ try {
192
+ entries.push(JSON.parse(line));
193
+ }
194
+ catch {
195
+ // A half-written line is not an error for a reader.
196
+ }
197
+ if (entries.length >= limit)
198
+ break;
199
+ }
200
+ }
201
+ return entries;
202
+ }
203
+ /**
204
+ * Roll `journal.jsonl` into a dated archive, then enforce retention and
205
+ * return the REMOVED archive paths (the new archive is not a removal).
206
+ * Retention keeps an archive that is inside the file window OR inside the day
207
+ * window — i.e. the newer of the two — so a quiet month never prunes a busy
208
+ * fortnight. Never throws.
209
+ *
210
+ * Overlapping calls are serialized (see {@link enqueueRotation}) and the
211
+ * archive a call just created is never a retention candidate: with both
212
+ * windows empty the call would otherwise unlink the entire rolled history it
213
+ * had just renamed into place.
214
+ */
215
+ async rotate(opts = {}) {
216
+ return enqueueRotation(() => this.rotateOnce(opts));
217
+ }
218
+ async rotateOnce(opts) {
219
+ const removed = [];
220
+ try {
221
+ const dir = journalDir(this.dshHome);
222
+ await mkdir(dir, { recursive: true, mode: 0o700 });
223
+ const live = journalPath(this.dshHome);
224
+ let liveSize;
225
+ try {
226
+ liveSize = (await stat(live)).size;
227
+ }
228
+ catch {
229
+ // Nothing to roll.
230
+ }
231
+ // An empty live file carries no decision; rolling it would only grow the
232
+ // archive set that the retention window then has to pay for.
233
+ let rolled;
234
+ if (liveSize !== undefined && liveSize > 0) {
235
+ const target = await this.freeArchivePath(dir);
236
+ await rename(live, target);
237
+ rolled = target;
238
+ // The rename already happened, so a failed chmod must not escape to the
239
+ // outer catch: that would abandon retention and report no removals for
240
+ // a rotation that in fact succeeded. Log it and carry on.
241
+ try {
242
+ await chmod(target, 0o600);
243
+ }
244
+ catch (e) {
245
+ console.error('[dsh-maestro-guard] journal archive chmod failed:', e?.message);
246
+ }
247
+ }
248
+ const retainFiles = opts.retainFiles ?? this.opts.retainFiles ?? DEFAULT_RETAIN_FILES;
249
+ const retainDays = opts.retainDays ?? this.opts.retainDays ?? DEFAULT_RETAIN_DAYS;
250
+ const dayCutoff = this.now() - retainDays * DAY_MS;
251
+ const archives = (await readdir(dir)).map(parseArchive).filter((a) => a !== undefined).sort(byAge);
252
+ for (let i = 0; i < archives.length; i++) {
253
+ const archive = archives[i];
254
+ const inFileWindow = i >= archives.length - retainFiles;
255
+ const inDayWindow = Date.parse(`${archive.date}T00:00:00.000Z`) >= dayCutoff;
256
+ if (inFileWindow || inDayWindow)
257
+ continue;
258
+ const p = join(dir, archive.name);
259
+ // The archive THIS call created holds the whole rolled history.
260
+ if (p === rolled)
261
+ continue;
262
+ try {
263
+ await unlink(p);
264
+ removed.push(p);
265
+ }
266
+ catch {
267
+ // Already gone (or unreadable): retention is best-effort.
268
+ }
269
+ }
270
+ }
271
+ catch (e) {
272
+ console.error('[dsh-maestro-guard] journal rotate failed:', e?.message);
273
+ }
274
+ return removed;
275
+ }
276
+ /**
277
+ * Flush the counters every `intervalMs` and return the disposer that stops
278
+ * it. The flush is periodic by design: the decision path only ever touches
279
+ * the in-memory map. The timer is unref'd so a pending flush never keeps the
280
+ * host process alive. A disabled journal starts no timer at all.
281
+ */
282
+ startFlush(intervalMs) {
283
+ if (!this.writesEnabled)
284
+ return () => { };
285
+ const timer = setInterval(() => {
286
+ void this.flushCounters();
287
+ }, intervalMs);
288
+ timer.unref?.();
289
+ let stopped = false;
290
+ return () => {
291
+ if (stopped)
292
+ return;
293
+ stopped = true;
294
+ clearInterval(timer);
295
+ };
296
+ }
297
+ /**
298
+ * The BOOT roll: rotate when the live file's last write predates today, so
299
+ * the archive set — and the retention windows that prune it — advances even
300
+ * on a host that restarts daily. One `stat` is the only I/O; a missing live
301
+ * file, or one already written today, is a silent no-op. A disabled journal
302
+ * rolls nothing, the same rule `append` and `startFlush` follow.
303
+ *
304
+ * The roll is named by the rotation clock (today), like every other rotation;
305
+ * the file's contents are whatever accumulated since the last roll, so the
306
+ * archive day is the day the archive was made, never a claim about its
307
+ * contents.
308
+ */
309
+ async rotateIfStale() {
310
+ if (!this.writesEnabled)
311
+ return [];
312
+ let mtimeMs;
313
+ try {
314
+ mtimeMs = (await stat(journalPath(this.dshHome))).mtimeMs;
315
+ }
316
+ catch {
317
+ // No live file: nothing to roll, and boot must not fail on it.
318
+ return [];
319
+ }
320
+ if (!shouldRotateAtBoot(mtimeMs, this.now()))
321
+ return [];
322
+ return this.rotate();
323
+ }
324
+ /**
325
+ * Rotate once per `intervalMs` (default: one day) and return the disposer that
326
+ * stops it. This is what makes `retainFiles`/`retainDays` take effect on a
327
+ * long-running host, not just at boot. The timer is unref'd so a pending roll
328
+ * never keeps the host process alive, and a disabled journal starts no timer
329
+ * at all — the same reversible-disposer discipline as {@link startFlush}.
330
+ */
331
+ startDailyRotation(intervalMs = DAY_MS) {
332
+ if (!this.writesEnabled)
333
+ return () => { };
334
+ const timer = setInterval(() => {
335
+ void this.rotate();
336
+ }, intervalMs);
337
+ timer.unref?.();
338
+ let stopped = false;
339
+ return () => {
340
+ if (stopped)
341
+ return;
342
+ stopped = true;
343
+ clearInterval(timer);
344
+ };
345
+ }
346
+ /** The first unused `journal-<today>[-<n>].jsonl` under `dir`. */
347
+ async freeArchivePath(dir) {
348
+ const date = dayOf(this.now());
349
+ for (let seq = 0; seq < 1000; seq++) {
350
+ const name = seq === 0 ? `journal-${date}.jsonl` : `journal-${date}-${seq}.jsonl`;
351
+ const candidate = join(dir, name);
352
+ try {
353
+ await stat(candidate);
354
+ }
355
+ catch {
356
+ return candidate;
357
+ }
358
+ }
359
+ // 1000 collisions in one day is unreachable, but the fallback must still be
360
+ // a name this module can READ and PRUNE: interpolating the raw clock put a
361
+ // fractional millisecond into the name (`journal-<date>-<n>.<n>.jsonl`),
362
+ // which ARCHIVE_RE does not match, so such an archive would be invisible to
363
+ // `read()` and to retention forever. Truncate to a positive integer so the
364
+ // name always lands in the `-<n>` slot.
365
+ const seq = Math.max(1, Math.floor(this.now()));
366
+ return join(dir, `journal-${date}-${seq}.jsonl`);
367
+ }
368
+ }
369
+ /**
370
+ * `allow=2,ask=1` — tier totals in tier order, present tiers only. The rule is
371
+ * deliberately absent: the note is the tier roll-up, and a rule named after a
372
+ * secret would otherwise ride an aggregate line.
373
+ */
374
+ function renderCounters(counters) {
375
+ const perTier = new Map();
376
+ for (const [key, n] of counters) {
377
+ const tier = key.slice(key.lastIndexOf('|') + 1);
378
+ perTier.set(tier, (perTier.get(tier) ?? 0) + n);
379
+ }
380
+ return TIERS.filter((tier) => (perTier.get(tier) ?? 0) > 0)
381
+ .map((tier) => `${tier}=${perTier.get(tier)}`)
382
+ .join(',');
383
+ }
384
+ /**
385
+ * The single redaction choke point for the stored record. The `redacted: true`
386
+ * stamp is not a decoration: it is true only because every string this entry
387
+ * carries passes through the widened redactor here. Call sites stay free to pass
388
+ * raw verdict fields — a future caller that forgets cannot leak, and a
389
+ * non-string value (the throwaway object the never-throw test passes as `note`)
390
+ * is left untouched so serialization still fails exactly as before.
391
+ */
392
+ function redactEntry(entry) {
393
+ const out = {};
394
+ for (const [key, value] of Object.entries(entry)) {
395
+ out[key] = typeof value === 'string' ? redact(value) : value;
396
+ }
397
+ return out;
398
+ }
@@ -0,0 +1,15 @@
1
+ import { Journal } from './journal.js';
2
+ /**
3
+ * Retire the legacy ticket store (Task A4). The guard no longer reads tickets —
4
+ * the human answers through DSH's native approval service — so the old
5
+ * `pending.json` is moved out of its active path into the journal directory,
6
+ * where it is kept for reference but never consulted again.
7
+ *
8
+ * This runs once per boot inside `ctx.effect`; it is idempotent (a missing
9
+ * source is a no-op) and never throws, because a failed retirement must not
10
+ * stop the guard from booting.
11
+ */
12
+ export declare function retireLegacyStore(journal: Journal, dshHome?: string): Promise<{
13
+ moved: boolean;
14
+ to?: string;
15
+ }>;
@@ -0,0 +1,42 @@
1
+ import { chmod, mkdir, rename, stat } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { journalDir } from './journal.js';
4
+ /**
5
+ * Retire the legacy ticket store (Task A4). The guard no longer reads tickets —
6
+ * the human answers through DSH's native approval service — so the old
7
+ * `pending.json` is moved out of its active path into the journal directory,
8
+ * where it is kept for reference but never consulted again.
9
+ *
10
+ * This runs once per boot inside `ctx.effect`; it is idempotent (a missing
11
+ * source is a no-op) and never throws, because a failed retirement must not
12
+ * stop the guard from booting.
13
+ */
14
+ export async function retireLegacyStore(journal, dshHome) {
15
+ const dir = journalDir(dshHome);
16
+ const from = join(dir, 'pending.json');
17
+ const to = join(dir, 'legacy-pending.json');
18
+ try {
19
+ await stat(from);
20
+ }
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
+ }
38
+ catch (e) {
39
+ console.error('[dsh-maestro-guard] legacy store retirement failed:', e?.message);
40
+ return { moved: false };
41
+ }
42
+ }
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Shell-aware tokenizer and segmenter for the guard's command surface.
3
+ *
4
+ * The guard judges a command by what it actually executes, and a regex over the
5
+ * raw string cannot do that. It splits on operators that sit inside quotes, and
6
+ * — the live bypass this module exists to close — it cannot see the subcommand
7
+ * of `git -C /repo push origin v1.2.3`, because a value-taking global option
8
+ * sits between `git` and `push`.
9
+ *
10
+ * The parse is deliberately shallow: just enough structure (segments, argv, the
11
+ * verb/subcommand, flags, refspecs, paths, ambiguity) for the rule layer, never
12
+ * a POSIX implementation. Two invariants hold:
13
+ *
14
+ * - nothing is silently dropped — every word, operator, redirection operator and
15
+ * redirection target appears exactly once across the segments' `argv`, so a
16
+ * rule can always re-derive the text it needs (an operator keeps its own
17
+ * token kind and is never read as a word). The one deliberate exception is a
18
+ * heredoc BODY: it is not command surface, so it leaves the token stream and
19
+ * is attached to its owning segment as `Segment.heredoc` instead;
20
+ * - anything unresolvable is marked `ambiguous` rather than guessed, and the
21
+ * rule layer treats ambiguity as "ask", never as "allow".
22
+ *
23
+ * Two consequences of that second invariant are worth naming, because both were
24
+ * live bypasses before they were closed:
25
+ *
26
+ * - an option the tables do not know is NOT assumed valueless when a word
27
+ * follows it. `git --bare push` (valueless) and `git --shallow-file x push`
28
+ * (value-taking) differ only in git's own option table, so the parser cannot
29
+ * resolve the subcommand and marks the segment `ambiguous` instead of reading
30
+ * `x` as the subcommand and losing the push;
31
+ * - a backtick substitutes a command exactly like `$(...)` does, so it sets the
32
+ * same expandable signal — otherwise `` echo `git -C /repo push origin v1.2.3`
33
+ * `` reads as a resolved `echo` and the push never reaches a rule.
34
+ *
35
+ * `unwrapSegments` is the layer above that parse. It removes the wrappers that
36
+ * only change WHO runs a command (`env VAR=…`, `sudo`, `nohup`, `time`), replaces
37
+ * a shell wrapper with the script it runs (`bash -c <script>`, `bash -s`, and a
38
+ * `bash <<EOF` body), and tags every segment it derives with `wrappedBy`. A body
39
+ * fed to a non-shell — `cat`, `tee`, an interpreter — stays data and is never
40
+ * turned into segments; it is attached as `Segment.heredoc` so a rule can inspect
41
+ * it without parsing it. A wrapper whose script cannot be read (a script file, a
42
+ * `-c` with no argument, a nest deeper than `MAX_WRAP_DEPTH`, an interpreter's
43
+ * inline program) marks its segments `ambiguous` instead of being treated as
44
+ * resolved — and so does an exec-like wrapper the guard deliberately does not
45
+ * unwrap (`timeout`, `nice`, `setsid`, `watch`, …), which runs a command of its
46
+ * own that would otherwise never reach a rule.
47
+ *
48
+ * Pure with respect to the environment it inspects: string in, data out. It
49
+ * writes no file, starts no child process, opens no socket and never expands
50
+ * `$VAR`/backticks — an unexpanded token is exactly what `ambiguous` records.
51
+ * Reading the ambient environment is allowed where the caller cannot supply it:
52
+ * `node:os` `homedir()` and `node:path` resolve a `~`-relative `cd` target in
53
+ * `getCommandWorkingDir`, which is the only reason either is imported.
54
+ */
55
+ /** How many shell-wrapper levels `parseCommand` will descend before giving up. */
56
+ export declare const MAX_WRAP_DEPTH = 3;
57
+ export interface Segment {
58
+ /** The original source text of this segment, quoting preserved. */
59
+ raw: string;
60
+ /** Every token of the segment: quotes stripped, operator and redirections kept. */
61
+ argv: string[];
62
+ verb?: string;
63
+ subcommand?: string;
64
+ flags: string[];
65
+ refspecs: string[];
66
+ paths: string[];
67
+ ambiguous: boolean;
68
+ wrappedBy?: string;
69
+ /**
70
+ * Every heredoc body this segment owns (`<<`/`<<-`), concatenated in feed
71
+ * order with a `\n` between them: terminators are excluded and each body keeps
72
+ * its own trailing newline. Present only when the segment owns at least one
73
+ * heredoc redirection, so more than one cannot be told apart here. A rule that
74
+ * judges content inspects it instead of forcing the body back through the
75
+ * parser.
76
+ */
77
+ heredoc?: string;
78
+ }
79
+ /** Verbs whose meaning is entirely "run whatever the arguments say". */
80
+ export declare const OPAQUE_VERBS: Set<string>;
81
+ /**
82
+ * Verbs that run a trailing COMMAND of their own — after their own options and,
83
+ * for most of them, a leading duration/priority/pid argument. The verb the guard
84
+ * reads is therefore not the verb that executes: `timeout 5 bash -c '…'` runs
85
+ * bash, never `timeout`, and the real command is invisible to a rule keyed on it.
86
+ *
87
+ * `unwrapSegments` does not unwrap these forms, because their argument grammar
88
+ * is per-verb (`timeout 5 CMD`, `nice -n 5 CMD`, `stdbuf -o0 CMD`, `flock FILE
89
+ * CMD`, …) and a wrong guess would hide the command rather than reveal it. Each
90
+ * one is marked `ambiguous` instead, which the rule layer answers with a prompt,
91
+ * never an allow. `xargs` is the same shape and is already in `OPAQUE_VERBS`.
92
+ *
93
+ * The class is closed over that SHAPE, not over a hand-picked sample: a verb that
94
+ * runs a trailing command belongs here even when it is a tracer (`strace`,
95
+ * `ltrace`), a sandbox/root switcher (`chroot`, `setarch`, `bwrap`, `fakeroot`),
96
+ * a remote runner (`ssh`), or a scheduler/multiplexer (`parallel`, `unbuffer`,
97
+ * `script`, `caffeinate`). Leaving one out does not fail safe: the segment reads
98
+ * as a resolved verb and the command it really runs never reaches a rule.
99
+ *
100
+ * Exported (with `OPAQUE_VERBS`) so the rule layer can tell which segments hold a
101
+ * COMMAND in their quoted spans rather than data — see `rawSurface` in `rules.ts`.
102
+ */
103
+ export declare const EXEC_WRAPPERS: Set<string>;
104
+ /**
105
+ * Verbs that only SCAN or PRINT their arguments, never execute them: the
106
+ * protected phrase in `grep -rn npm publish docs` is the pattern being searched
107
+ * for, not a command. They lead a segment whose later words name a rule verb
108
+ * without running it, so the later-token shape test must not apply to them.
109
+ *
110
+ * `find` is the one verb here that CAN run a command — but only through one of
111
+ * its action flags ({@link FIND_ACTION_FLAGS}), which {@link unresolvedCommand}
112
+ * treats separately. The set is exported so the rule layer applies the same
113
+ * reading to a protected path.
114
+ */
115
+ export declare const MENTION_VERBS: Set<string>;
116
+ /**
117
+ * The `find` actions that really RUN the command they name (every other find
118
+ * predicate only tests the entry). `-exec` alone was recognized, so a protected
119
+ * push or a protected-path mutation under `-execdir`/`-ok`/`-okdir` reached no
120
+ * rule — the escalation found nothing and the call was allowed.
121
+ */
122
+ export declare const FIND_ACTION_FLAGS: Set<string>;
123
+ /**
124
+ * A shell's "run this script text" switch (`-c`, `-lc`, `--command`). The token
125
+ * after it is a COMMAND LINE, not an argument: `bash -c "rm -f <path>"` hands the
126
+ * mutation to a shell, and `find -exec bash -c "…" +` hides it one level deeper.
127
+ */
128
+ export declare const SHELL_COMMAND_FLAG: RegExp;
129
+ /** The shells that read `{@link SHELL_COMMAND_FLAG}`; a wrapper may hand them the script. */
130
+ export declare const SHELL_VERBS: Set<string>;
131
+ /**
132
+ * Parse a shell command into its segments. `depth` is the shell-wrapper nesting
133
+ * level: once it reaches `MAX_WRAP_DEPTH` the segments are marked ambiguous
134
+ * instead of parsed, so an unreadable wrapper can never be treated as harmless.
135
+ *
136
+ * The operator that ends a segment stays in that segment's `argv` (its kind is
137
+ * `sep`, so no rule reads it as a word): splitting must not drop tokens, and the
138
+ * concatenated `argv` still holds every word, operator and redirection target of
139
+ * the command. A heredoc BODY is the one deliberate exception — it is not argv —
140
+ * so the round trip covers the command surface only: every body is removed from
141
+ * the token stream and attached to its owning segment as `Segment.heredoc`.
142
+ */
143
+ export declare function parseCommand(command: string, depth?: number): Segment[];
144
+ /**
145
+ * Remove every wrapper around a parsed command and return the segments that
146
+ * actually run.
147
+ *
148
+ * A segment that is not a wrapper is returned unchanged — same object, no
149
+ * re-derivation — so the common path costs nothing and cannot drift. A shell
150
+ * wrapper (`bash -c …`, `bash -s`, a `bash <<EOF` body) is REPLACED by the
151
+ * segments of its script, each tagged `wrappedBy`. A wrapper that cannot be read
152
+ * — unknown nesting past `MAX_WRAP_DEPTH`, a `-c` with no argument, a script file
153
+ * the guard cannot open, an interpreter's inline program — stays in the result
154
+ * marked `ambiguous`, which the rule layer answers with a prompt, never an allow.
155
+ * An exec-like wrapper (`timeout`, `nice`, `setsid`, `watch`, …) is not unwrapped
156
+ * at all and is `ambiguous` for the same reason: the command it runs is not the
157
+ * command the guard read.
158
+ */
159
+ export declare function unwrapSegments(segs: Segment[], depth?: number): Segment[];
160
+ /**
161
+ * Collapse quoted spans — text inside quotes is data (echo/printf/script
162
+ * bodies), not argv.
163
+ */
164
+ export declare function stripQuoted(cmd: string): string;
165
+ /**
166
+ * Collapse heredoc bodies — the lines fed to a command's stdin are data, not
167
+ * argv. A heredoc body routinely contains protected path literals (setup
168
+ * scripts, config generators) which must not be mistaken for an access.
169
+ * Run this AFTER `stripQuoted` so a quoted delimiter (`<<'EOF'`) is already
170
+ * reduced to its bare form.
171
+ */
172
+ export declare function stripHeredocs(cmd: string): string;
173
+ /**
174
+ * The executed command surface of a tool call. Shell-style tools carry their
175
+ * script in `args.command` (bash/exec/shell/govard_shell); bare string args are
176
+ * the command itself. Tools with no command field (read/write/memory/...) have
177
+ * no execution surface, so protected-op detection must not apply to their
178
+ * content — that was the source of the analysis-tool false positives.
179
+ */
180
+ export declare function extractCommandText(args: unknown): string | undefined;
181
+ /**
182
+ * The path a file-oriented tool call targets, from the args shapes the DSH and
183
+ * Maestro file tools use (`path` / `file` / `file_path` / `filePath`, or a bare
184
+ * string arg). Returns undefined when the call carries no path.
185
+ */
186
+ export declare function extractPathField(args: unknown): string | undefined;
187
+ /**
188
+ * Resolve the working directory a command actually executes in, when it names
189
+ * one explicitly (cd <dir> / git -C <dir>). Falls back to the passed cwd when
190
+ * the command has no explicit target — preserving the historical session-cwd
191
+ * semantics for commands that run in place.
192
+ */
193
+ export declare function getCommandWorkingDir(command: string | undefined, cwd: string | undefined): string | undefined;