@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.
- package/LICENSE +21 -0
- package/README.md +209 -0
- package/cordis.patch.yml +43 -0
- package/lib/bin.d.ts +2 -0
- package/lib/bin.js +3 -0
- package/lib/boot-guard.d.ts +33 -0
- package/lib/boot-guard.js +68 -0
- package/lib/boot-lock.d.ts +56 -0
- package/lib/boot-lock.js +155 -0
- package/lib/cli.d.ts +31 -0
- package/lib/cli.js +336 -0
- package/lib/client.js +2901 -0
- package/lib/config/index.d.ts +34 -0
- package/lib/config/index.js +62 -0
- package/lib/config/service.d.ts +18 -0
- package/lib/config/service.js +28 -0
- package/lib/config.d.ts +1 -0
- package/lib/config.js +19 -0
- package/lib/daemon-freshness.d.ts +48 -0
- package/lib/daemon-freshness.js +122 -0
- package/lib/debug-agent.d.ts +17 -0
- package/lib/debug-agent.js +144 -0
- package/lib/dsh-session.d.ts +26 -0
- package/lib/dsh-session.js +45 -0
- package/lib/guard/config.d.ts +82 -0
- package/lib/guard/config.js +211 -0
- package/lib/guard/decide.d.ts +30 -0
- package/lib/guard/decide.js +38 -0
- package/lib/guard/full-scan-tool.d.ts +6 -0
- package/lib/guard/full-scan-tool.js +65 -0
- package/lib/guard/index.d.ts +85 -0
- package/lib/guard/index.js +254 -0
- package/lib/guard/journal.d.ts +146 -0
- package/lib/guard/journal.js +398 -0
- package/lib/guard/migrate.d.ts +15 -0
- package/lib/guard/migrate.js +42 -0
- package/lib/guard/parse.d.ts +193 -0
- package/lib/guard/parse.js +1103 -0
- package/lib/guard/paths.d.ts +104 -0
- package/lib/guard/paths.js +254 -0
- package/lib/guard/permission-policy.d.ts +10 -0
- package/lib/guard/permission-policy.js +21 -0
- package/lib/guard/redact.d.ts +25 -0
- package/lib/guard/redact.js +52 -0
- package/lib/guard/rules.d.ts +65 -0
- package/lib/guard/rules.js +832 -0
- package/lib/guard/status-tool.d.ts +54 -0
- package/lib/guard/status-tool.js +195 -0
- package/lib/guard/tiers.d.ts +2 -0
- package/lib/guard/tiers.js +1 -0
- package/lib/guard/validators.d.ts +4 -0
- package/lib/guard/validators.js +45 -0
- package/lib/health-poller.d.ts +90 -0
- package/lib/health-poller.js +430 -0
- package/lib/index.d.ts +7 -0
- package/lib/index.js +7 -0
- package/lib/intents.d.ts +32 -0
- package/lib/intents.js +49 -0
- package/lib/notifier.d.ts +12 -0
- package/lib/notifier.js +62 -0
- package/lib/paths.d.ts +13 -0
- package/lib/paths.js +70 -0
- package/lib/plugin.d.ts +250 -0
- package/lib/plugin.js +1126 -0
- package/lib/preset.d.ts +73 -0
- package/lib/preset.js +158 -0
- package/lib/report.d.ts +11 -0
- package/lib/report.js +58 -0
- package/lib/restart-exec.d.ts +35 -0
- package/lib/restart-exec.js +60 -0
- package/lib/restart-guards.d.ts +39 -0
- package/lib/restart-guards.js +150 -0
- package/lib/restart-tool.d.ts +124 -0
- package/lib/restart-tool.js +539 -0
- package/lib/restart-web.d.ts +26 -0
- package/lib/restart-web.js +58 -0
- package/lib/resume-log.d.ts +24 -0
- package/lib/resume-log.js +18 -0
- package/lib/resume-tools.d.ts +131 -0
- package/lib/resume-tools.js +337 -0
- package/lib/resume.d.ts +33 -0
- package/lib/resume.js +221 -0
- package/lib/scan.d.ts +20 -0
- package/lib/scan.js +71 -0
- package/lib/self-kill-guard.d.ts +81 -0
- package/lib/self-kill-guard.js +208 -0
- package/lib/session-health.d.ts +89 -0
- package/lib/session-health.js +274 -0
- package/lib/session-log-file.d.ts +22 -0
- package/lib/session-log-file.js +74 -0
- package/lib/skill-provider.d.ts +6 -0
- package/lib/skill-provider.js +73 -0
- package/lib/snapshot.d.ts +59 -0
- package/lib/snapshot.js +358 -0
- package/lib/source.d.ts +19 -0
- package/lib/source.js +19 -0
- package/lib/store/index.d.ts +42 -0
- package/lib/store/index.js +340 -0
- package/lib/store/legacy.d.ts +17 -0
- package/lib/store/legacy.js +85 -0
- package/lib/supervisor.d.ts +119 -0
- package/lib/supervisor.js +741 -0
- package/lib/sync/backup-config.d.ts +55 -0
- package/lib/sync/backup-config.js +119 -0
- package/lib/sync/backup-service.d.ts +110 -0
- package/lib/sync/backup-service.js +440 -0
- package/lib/sync/bidirectional.d.ts +39 -0
- package/lib/sync/bidirectional.js +25 -0
- package/lib/sync/cli.d.ts +38 -0
- package/lib/sync/cli.js +536 -0
- package/lib/sync/config.d.ts +77 -0
- package/lib/sync/config.js +90 -0
- package/lib/sync/fingerprint.d.ts +29 -0
- package/lib/sync/fingerprint.js +65 -0
- package/lib/sync/hashing.d.ts +9 -0
- package/lib/sync/hashing.js +47 -0
- package/lib/sync/index.d.ts +6 -0
- package/lib/sync/index.js +634 -0
- package/lib/sync/machine-id.d.ts +29 -0
- package/lib/sync/machine-id.js +66 -0
- package/lib/sync/merge.d.ts +33 -0
- package/lib/sync/merge.js +88 -0
- package/lib/sync/peer-host.d.ts +22 -0
- package/lib/sync/peer-host.js +62 -0
- package/lib/sync/process-runner.d.ts +31 -0
- package/lib/sync/process-runner.js +161 -0
- package/lib/sync/remote-agent.d.ts +42 -0
- package/lib/sync/remote-agent.js +217 -0
- package/lib/sync/remote-cache.d.ts +18 -0
- package/lib/sync/remote-cache.js +60 -0
- package/lib/sync/remote-manifest.d.ts +8 -0
- package/lib/sync/remote-manifest.js +64 -0
- package/lib/sync/s3-object-store.d.ts +38 -0
- package/lib/sync/s3-object-store.js +126 -0
- package/lib/sync/session-merge.d.ts +18 -0
- package/lib/sync/session-merge.js +191 -0
- package/lib/sync/session-plan.d.ts +29 -0
- package/lib/sync/session-plan.js +213 -0
- package/lib/sync/sigv4.d.ts +20 -0
- package/lib/sync/sigv4.js +57 -0
- package/lib/sync/snapshot.d.ts +21 -0
- package/lib/sync/snapshot.js +176 -0
- package/lib/sync/ssh-mux.d.ts +12 -0
- package/lib/sync/ssh-mux.js +48 -0
- package/lib/sync/sync-plan.d.ts +24 -0
- package/lib/sync/sync-plan.js +366 -0
- package/lib/sync/sync-service.d.ts +177 -0
- package/lib/sync/sync-service.js +819 -0
- package/lib/sync/sync-types.d.ts +87 -0
- package/lib/sync/sync-types.js +1 -0
- package/lib/sync/transport.d.ts +75 -0
- package/lib/sync/transport.js +200 -0
- package/lib/sync/tunnel-restore.d.ts +77 -0
- package/lib/sync/tunnel-restore.js +142 -0
- package/lib/sync/validation.d.ts +10 -0
- package/lib/sync/validation.js +83 -0
- package/lib/tool-view.d.ts +62 -0
- package/lib/tool-view.js +70 -0
- package/lib/types/client/auto-reload.d.ts +8 -0
- package/lib/types/client/auto-reload.d.ts.map +1 -0
- package/lib/types/client/config/MaestroSettings.d.ts +25 -0
- package/lib/types/client/config/MaestroSettings.d.ts.map +1 -0
- package/lib/types/client/config/components/BrandMark.d.ts +50 -0
- package/lib/types/client/config/components/BrandMark.d.ts.map +1 -0
- package/lib/types/client/config/guard-view.d.ts +83 -0
- package/lib/types/client/config/guard-view.d.ts.map +1 -0
- package/lib/types/client/config/index.d.ts +20 -0
- package/lib/types/client/config/index.d.ts.map +1 -0
- package/lib/types/client/config/maestro-mark.d.ts +29 -0
- package/lib/types/client/config/maestro-mark.d.ts.map +1 -0
- package/lib/types/client/config/settings-nav-icon.d.ts +21 -0
- package/lib/types/client/config/settings-nav-icon.d.ts.map +1 -0
- package/lib/types/client/index.d.ts +16 -0
- package/lib/types/client/index.d.ts.map +1 -0
- package/lib/types/client/sync/R2SyncPanel.d.ts +6 -0
- package/lib/types/client/sync/R2SyncPanel.d.ts.map +1 -0
- package/lib/types/client/sync/SyncPanel.d.ts +12 -0
- package/lib/types/client/sync/SyncPanel.d.ts.map +1 -0
- package/lib/types/client/sync/confirm-dialog.d.ts +43 -0
- package/lib/types/client/sync/confirm-dialog.d.ts.map +1 -0
- package/lib/types/client/sync/index.d.ts +10 -0
- package/lib/types/client/sync/index.d.ts.map +1 -0
- package/lib/types/client/sync/ui.d.ts +79 -0
- package/lib/types/client/sync/ui.d.ts.map +1 -0
- package/lib/types/client/sync/use-backup.d.ts +50 -0
- package/lib/types/client/sync/use-backup.d.ts.map +1 -0
- package/lib/types/client/sync/use-sync.d.ts +88 -0
- package/lib/types/client/sync/use-sync.d.ts.map +1 -0
- package/package.json +89 -0
- package/skills/dsh-safe-restart/SKILL.md +206 -0
- package/skills/dsh-safe-restart/scripts/restart-dsh-web.sh +468 -0
- package/src/client/auto-reload.ts +104 -0
- package/src/client/config/MaestroSettings.tsx +892 -0
- package/src/client/config/components/BrandMark.tsx +94 -0
- package/src/client/config/guard-view.ts +187 -0
- package/src/client/config/index.tsx +109 -0
- package/src/client/config/maestro-mark.ts +37 -0
- package/src/client/config/settings-nav-icon.ts +68 -0
- package/src/client/index.tsx +33 -0
- package/src/client/sync/R2SyncPanel.tsx +260 -0
- package/src/client/sync/SyncPanel.tsx +422 -0
- package/src/client/sync/confirm-dialog.tsx +202 -0
- package/src/client/sync/index.tsx +336 -0
- package/src/client/sync/ui.tsx +313 -0
- package/src/client/sync/use-backup.ts +207 -0
- package/src/client/sync/use-sync.ts +502 -0
- package/src/host/bin.ts +3 -0
- package/src/host/boot-guard.ts +76 -0
- package/src/host/boot-lock.ts +155 -0
- package/src/host/cli.ts +288 -0
- package/src/host/config/index.ts +78 -0
- package/src/host/config/service.ts +40 -0
- package/src/host/config.ts +18 -0
- package/src/host/daemon-freshness.ts +143 -0
- package/src/host/debug-agent.ts +145 -0
- package/src/host/dsh-session.ts +56 -0
- package/src/host/dsh-skill.d.ts +44 -0
- package/src/host/guard/augment.d.ts +33 -0
- package/src/host/guard/config.ts +244 -0
- package/src/host/guard/decide.ts +40 -0
- package/src/host/guard/full-scan-tool.ts +61 -0
- package/src/host/guard/index.ts +281 -0
- package/src/host/guard/journal.ts +440 -0
- package/src/host/guard/migrate.ts +41 -0
- package/src/host/guard/parse.ts +1150 -0
- package/src/host/guard/paths.ts +239 -0
- package/src/host/guard/permission-policy.ts +15 -0
- package/src/host/guard/redact.ts +64 -0
- package/src/host/guard/rules.ts +891 -0
- package/src/host/guard/status-tool.ts +229 -0
- package/src/host/guard/tiers.ts +2 -0
- package/src/host/guard/validators.ts +29 -0
- package/src/host/health-poller.ts +446 -0
- package/src/host/index.ts +7 -0
- package/src/host/intents.ts +67 -0
- package/src/host/notifier.ts +71 -0
- package/src/host/paths.ts +70 -0
- package/src/host/plugin.ts +1097 -0
- package/src/host/preset.ts +170 -0
- package/src/host/report.ts +71 -0
- package/src/host/restart-exec.ts +81 -0
- package/src/host/restart-guards.ts +150 -0
- package/src/host/restart-tool.ts +483 -0
- package/src/host/restart-web.ts +72 -0
- package/src/host/resume-log.ts +39 -0
- package/src/host/resume-tools.ts +385 -0
- package/src/host/resume.ts +204 -0
- package/src/host/scan.ts +61 -0
- package/src/host/self-kill-guard.ts +216 -0
- package/src/host/session-health.ts +236 -0
- package/src/host/session-log-file.ts +77 -0
- package/src/host/skill-provider.ts +69 -0
- package/src/host/snapshot.ts +337 -0
- package/src/host/source.ts +19 -0
- package/src/host/store/index.ts +348 -0
- package/src/host/store/legacy.ts +96 -0
- package/src/host/supervisor.ts +720 -0
- package/src/host/sync/backup-config.ts +159 -0
- package/src/host/sync/backup-service.ts +453 -0
- package/src/host/sync/bidirectional.ts +66 -0
- package/src/host/sync/cli.ts +539 -0
- package/src/host/sync/config.ts +119 -0
- package/src/host/sync/fingerprint.ts +83 -0
- package/src/host/sync/hashing.ts +58 -0
- package/src/host/sync/index.ts +737 -0
- package/src/host/sync/machine-id.ts +81 -0
- package/src/host/sync/merge.ts +102 -0
- package/src/host/sync/peer-host.ts +65 -0
- package/src/host/sync/process-runner.ts +177 -0
- package/src/host/sync/remote-agent.ts +213 -0
- package/src/host/sync/remote-cache.ts +68 -0
- package/src/host/sync/remote-manifest.ts +70 -0
- package/src/host/sync/s3-object-store.ts +144 -0
- package/src/host/sync/session-merge.ts +220 -0
- package/src/host/sync/session-plan.ts +237 -0
- package/src/host/sync/sigv4.ts +81 -0
- package/src/host/sync/snapshot.ts +162 -0
- package/src/host/sync/ssh-mux.ts +56 -0
- package/src/host/sync/sync-plan.ts +366 -0
- package/src/host/sync/sync-service.ts +855 -0
- package/src/host/sync/sync-types.ts +102 -0
- package/src/host/sync/transport.ts +261 -0
- package/src/host/sync/tunnel-restore.ts +160 -0
- package/src/host/sync/validation.ts +91 -0
- package/src/host/tool-view.ts +98 -0
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { execSync } from 'node:child_process';
|
|
2
|
+
import { PermissionPolicy } from './permission-policy.js';
|
|
3
|
+
import { Journal } from './journal.js';
|
|
4
|
+
import { redact } from './redact.js';
|
|
5
|
+
import { classify } from './rules.js';
|
|
6
|
+
import { decide, renderReason } from './decide.js';
|
|
7
|
+
import { DEFAULT_CONFIG, loadGuardConfig, loadGuardConfigWithMigration } from './config.js';
|
|
8
|
+
import { retireLegacyStore } from './migrate.js';
|
|
9
|
+
import { apply as applyFullScan } from './full-scan-tool.js';
|
|
10
|
+
import { applyStatusTools } from './status-tool.js';
|
|
11
|
+
import './validators.js';
|
|
12
|
+
/** The rule id of the `tools/pre-execute` contract denial (spec §8). */
|
|
13
|
+
export const CONTRACT_MISMATCH_RULE = 'contract-mismatch';
|
|
14
|
+
/**
|
|
15
|
+
* The DSH `tools/pre-execute` contract the guard reads: a tool NAME and an
|
|
16
|
+
* arguments field. The guard accepts both spellings of each (`name`/`tool`,
|
|
17
|
+
* `args`/`arguments`), but a payload carrying neither is a DSH upgrade that
|
|
18
|
+
* renames a field — and a renamed `args` silently disables EVERY command rule,
|
|
19
|
+
* because `extractCommandText(undefined)` yields no command to classify.
|
|
20
|
+
* Spec §8: an unknown payload is a denial, never a pass.
|
|
21
|
+
*
|
|
22
|
+
* A `null` argument list counts as ABSENT, not as an empty one: `??` already
|
|
23
|
+
* falls through on null, so treating it as present would let a null `args`
|
|
24
|
+
* reach `extractCommandText` and allow a command the rules never saw.
|
|
25
|
+
*/
|
|
26
|
+
export function contractMismatch(exec) {
|
|
27
|
+
if (exec === null || typeof exec !== 'object')
|
|
28
|
+
return 'pre-execute payload is not an object';
|
|
29
|
+
const e = exec;
|
|
30
|
+
const name = typeof e.name === 'string' && e.name !== ''
|
|
31
|
+
? e.name
|
|
32
|
+
: typeof e.tool === 'string' && e.tool !== '' ? e.tool : undefined;
|
|
33
|
+
if (name === undefined)
|
|
34
|
+
return 'pre-execute payload carries no tool name (`name`/`tool`)';
|
|
35
|
+
if ((e.args === undefined || e.args === null) && (e.arguments === undefined || e.arguments === null)) {
|
|
36
|
+
return 'pre-execute payload carries no arguments (`args`/`arguments`)';
|
|
37
|
+
}
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Outcome vocabulary for the deny message. `unavailable` is the fail-closed
|
|
42
|
+
* case that matters most: no answerer is attached to this session, so the
|
|
43
|
+
* operation cannot be approved and must not silently proceed.
|
|
44
|
+
*
|
|
45
|
+
* `rejected` names BOTH causes on purpose. DSH's approval service resolves a
|
|
46
|
+
* session whose policy is `never` to `rejected` deterministically, before any
|
|
47
|
+
* answerer is dispatched (`packages/interaction/user-approval`), so the guard
|
|
48
|
+
* cannot tell a policy rejection from a human one — and a bare "the user
|
|
49
|
+
* rejected this" would be a lie in a session with no human in the loop. The
|
|
50
|
+
* message therefore carries the fix either way (spec §5.6/§8).
|
|
51
|
+
*/
|
|
52
|
+
const EXPLAIN = {
|
|
53
|
+
granted: 'granted once',
|
|
54
|
+
rejected: 'not approved — the user rejected it, or this session does not prompt (a `never` approval policy rejects every ask); start a session under a preset that prompts (danger-full-access now asks in this deployment) or switch the preset in the picker',
|
|
55
|
+
cancelled: 'the approval prompt was cancelled',
|
|
56
|
+
unavailable: 'no approval channel is available for this session (start a session under a preset that prompts — danger-full-access now asks in this deployment)',
|
|
57
|
+
error: 'the approval request failed (see the guard journal)',
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* The guard pipeline: classify the call into a rule id, resolve the rule's tier,
|
|
61
|
+
* journal the decision, then act — `next()` for allow/journal, a deny decision
|
|
62
|
+
* for deny, and for ask a NATIVE approval request to DSH's `approval` service.
|
|
63
|
+
*
|
|
64
|
+
* Every branch journals before it returns, and the journal is optional in the
|
|
65
|
+
* failure direction only: a journal write that fails is logged and changes no
|
|
66
|
+
* decision (see `Journal.append`).
|
|
67
|
+
*/
|
|
68
|
+
export function createGuardHandler(deps) {
|
|
69
|
+
const now = deps.now ?? Date.now;
|
|
70
|
+
return async (exec, next) => {
|
|
71
|
+
// The runtime contract first: a payload the guard cannot read must be denied
|
|
72
|
+
// and journaled, never allowed — a renamed field would otherwise silence
|
|
73
|
+
// every command rule (spec §8).
|
|
74
|
+
const mismatch = contractMismatch(exec);
|
|
75
|
+
if (mismatch !== undefined) {
|
|
76
|
+
const label = typeof exec?.name === 'string'
|
|
77
|
+
? exec.name
|
|
78
|
+
: 'unknown';
|
|
79
|
+
await deps.journal.append({
|
|
80
|
+
tool: label, rule: CONTRACT_MISMATCH_RULE, tier: 'deny',
|
|
81
|
+
target: 'tools/pre-execute', outcome: 'denied', note: mismatch,
|
|
82
|
+
});
|
|
83
|
+
return { kind: 'deny', reason: `${CONTRACT_MISMATCH_RULE} :: ${mismatch}` };
|
|
84
|
+
}
|
|
85
|
+
const tool = exec.name ?? exec.tool ?? '';
|
|
86
|
+
const args = exec.args ?? exec.arguments;
|
|
87
|
+
const cwd = exec.agent?.session?.header?.cwd;
|
|
88
|
+
const session = exec.agent?.session?.id;
|
|
89
|
+
const cfg = await deps.readConfig().catch(() => DEFAULT_CONFIG);
|
|
90
|
+
const settings = {
|
|
91
|
+
protectedBranches: cfg.protectedBranches,
|
|
92
|
+
protectedPaths: cfg.protectedPaths,
|
|
93
|
+
guardPaths: cfg.guardPaths,
|
|
94
|
+
// Part of the per-call read (unlike the boot-time journal block), so a
|
|
95
|
+
// `workingDirContainment` change takes effect on the next tool call.
|
|
96
|
+
workingDirContainment: cfg.workingDirContainment,
|
|
97
|
+
};
|
|
98
|
+
const verdict = classify({ tool, args, cwd, settings, branchOf: deps.branchOf });
|
|
99
|
+
const { tier } = decide(verdict, cfg.rules);
|
|
100
|
+
if (!deps.policy.isAllowed(tool, args)) {
|
|
101
|
+
await deps.journal.append({ session, tool, rule: 'policy.deny', tier: 'deny', target: verdict.target, cwd, outcome: 'denied' });
|
|
102
|
+
return { kind: 'deny', reason: `tool ${tool} denied by policy` };
|
|
103
|
+
}
|
|
104
|
+
if (tier === 'allow') {
|
|
105
|
+
// In-memory only: the count is what the periodic flush below persists, so
|
|
106
|
+
// an ordinary command stays off the journal's I/O path (see `startFlush`).
|
|
107
|
+
deps.journal.count(verdict.ruleId, tier);
|
|
108
|
+
return next();
|
|
109
|
+
}
|
|
110
|
+
if (tier === 'journal') {
|
|
111
|
+
await deps.journal.append({ session, tool, rule: verdict.ruleId, tier, target: verdict.target, repo: verdict.repo, branch: verdict.branch, cwd, outcome: 'passed' });
|
|
112
|
+
return next();
|
|
113
|
+
}
|
|
114
|
+
const reason = renderReason(verdict, redact);
|
|
115
|
+
if (tier === 'deny') {
|
|
116
|
+
await deps.journal.append({ session, tool, rule: verdict.ruleId, tier, target: verdict.target, cwd, outcome: 'denied' });
|
|
117
|
+
return { kind: 'deny', reason };
|
|
118
|
+
}
|
|
119
|
+
const t0 = now();
|
|
120
|
+
const raw = await deps.requestApproval({
|
|
121
|
+
agent: exec.agent, toolName: tool, callId: exec.callId, reason, signal: exec.signal,
|
|
122
|
+
});
|
|
123
|
+
const { outcome, note } = typeof raw === 'string' ? { outcome: raw, note: undefined } : raw;
|
|
124
|
+
await deps.journal.append({
|
|
125
|
+
session, tool, rule: verdict.ruleId, tier, target: verdict.target, repo: verdict.repo,
|
|
126
|
+
branch: verdict.branch, cwd, outcome, askMs: now() - t0,
|
|
127
|
+
// The deny text tells the human to see the journal, so the thrown reason
|
|
128
|
+
// has to be IN it; `Journal.append` redacts every string field.
|
|
129
|
+
...(note === undefined ? {} : { note }),
|
|
130
|
+
});
|
|
131
|
+
// A granted ask returns `next()` rather than a bare allow so the remaining
|
|
132
|
+
// pre-execute listeners still run (a bare allow would short-circuit them).
|
|
133
|
+
return outcome === 'granted' ? next() : { kind: 'deny', reason: `${reason} — ${EXPLAIN[outcome]}` };
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Branch of the repo a command targets. The caller resolves the repo directory
|
|
138
|
+
* itself (`git -C` / `cd` handling lives in `rules.ts`); an EMPTY directory is
|
|
139
|
+
* the "no resolvable repo" sentinel and must never be turned into
|
|
140
|
+
* `git -C ""`, which would silently resolve to the session cwd and re-create
|
|
141
|
+
* the false positives the repo resolution exists to remove.
|
|
142
|
+
*/
|
|
143
|
+
export function branchOf(dir) {
|
|
144
|
+
if (!dir)
|
|
145
|
+
return undefined;
|
|
146
|
+
try {
|
|
147
|
+
return execSync('git branch --show-current', { cwd: dir, timeout: 800, encoding: 'utf-8' }).trim() || undefined;
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
return undefined;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Journal an ALREADY-COMPUTED migration result. Split out of
|
|
155
|
+
* {@link journalLegacyConfigMigration} so `apply()` can reuse the single
|
|
156
|
+
* boot-time config read for both the journal knobs and this note. Never throws.
|
|
157
|
+
*/
|
|
158
|
+
export async function journalConfigMigration(journal, migratedKeys) {
|
|
159
|
+
try {
|
|
160
|
+
if (migratedKeys.length === 0)
|
|
161
|
+
return [];
|
|
162
|
+
const target = migratedKeys.join(',');
|
|
163
|
+
await journal.append({
|
|
164
|
+
tool: 'guard',
|
|
165
|
+
rule: 'config-legacy',
|
|
166
|
+
tier: 'journal',
|
|
167
|
+
target,
|
|
168
|
+
outcome: 'passed',
|
|
169
|
+
note: `legacy domains.guard keys migrated onto schema v2: ${target}`,
|
|
170
|
+
});
|
|
171
|
+
return migratedKeys;
|
|
172
|
+
}
|
|
173
|
+
catch (e) {
|
|
174
|
+
console.error('[dsh-maestro-guard] legacy config migration failed:', e?.message);
|
|
175
|
+
return [];
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Journal the schema-v1 → v2 config migration ONCE per boot. The handler's
|
|
180
|
+
* per-call config read (`loadGuardConfig`) is deliberately mute, so without
|
|
181
|
+
* this a persisted `domains.guard` written for schema v1 would change what the
|
|
182
|
+
* guard gates without leaving any trace of why.
|
|
183
|
+
*
|
|
184
|
+
* Exported so the boot effect body is unit-testable. Never throws: a failed
|
|
185
|
+
* read or a failed journal write must not stop the guard from booting, and
|
|
186
|
+
* `migratedKeys.length === 0` writes nothing at all.
|
|
187
|
+
*/
|
|
188
|
+
export async function journalLegacyConfigMigration(journal, dshHome) {
|
|
189
|
+
try {
|
|
190
|
+
const { migratedKeys } = await loadGuardConfigWithMigration(dshHome);
|
|
191
|
+
return await journalConfigMigration(journal, migratedKeys);
|
|
192
|
+
}
|
|
193
|
+
catch (e) {
|
|
194
|
+
console.error('[dsh-maestro-guard] legacy config migration failed:', e?.message);
|
|
195
|
+
return [];
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
export default {
|
|
199
|
+
inject: ['tools'],
|
|
200
|
+
async apply(ctx) {
|
|
201
|
+
// `domains.guard.journal` is a BOOT-TIME block: it decides whether the
|
|
202
|
+
// journal writes at all and which retention defaults `rotate()` uses, so it
|
|
203
|
+
// is read once here — unlike the per-call rule config, a settings change
|
|
204
|
+
// needs a host restart. The same read feeds the one-shot migration note.
|
|
205
|
+
const boot = await loadGuardConfigWithMigration().catch(() => ({ config: DEFAULT_CONFIG, migratedKeys: [] }));
|
|
206
|
+
const journal = new Journal(undefined, Date.now, boot.config.journal);
|
|
207
|
+
const policy = new PermissionPolicy({ deny: ['danger-tool'] });
|
|
208
|
+
const requestApproval = async (req) => {
|
|
209
|
+
const approval = ctx.get('approval');
|
|
210
|
+
if (!approval || req.agent === undefined)
|
|
211
|
+
return { outcome: 'unavailable' };
|
|
212
|
+
try {
|
|
213
|
+
const outcome = await approval.request({
|
|
214
|
+
agent: req.agent, toolName: req.toolName, callId: req.callId, reason: req.reason, signal: req.signal,
|
|
215
|
+
});
|
|
216
|
+
return { outcome: outcome === 'allowed-once' ? 'granted' : outcome };
|
|
217
|
+
}
|
|
218
|
+
catch (e) {
|
|
219
|
+
// The thrown reason is what the human needs (an idle ask rejects with
|
|
220
|
+
// "outside an open turn"), so it travels with the outcome instead of
|
|
221
|
+
// being dropped on the floor with only a stderr note.
|
|
222
|
+
const message = e?.message ?? String(e);
|
|
223
|
+
console.error('[dsh-maestro-guard] approval request failed:', message);
|
|
224
|
+
return { outcome: 'error', note: message };
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
const handler = createGuardHandler({ journal, policy, readConfig: loadGuardConfig, branchOf, requestApproval });
|
|
228
|
+
ctx.effect(() => ctx.on('tools/pre-execute', handler));
|
|
229
|
+
// Allow counters are in-memory; one aggregate line per interval keeps them
|
|
230
|
+
// off the decision path. The effect disposes the timer on unload, and a
|
|
231
|
+
// journal disabled by config starts no timer at all (`startFlush` is a no-op).
|
|
232
|
+
ctx.effect(() => { const stop = journal.startFlush(60_000); return () => stop(); }, 'guard-journal-counter-flush');
|
|
233
|
+
// Retention used to depend on a caller that never existed, so the live file
|
|
234
|
+
// grew without bound and `retainFiles`/`retainDays` never applied. The boot
|
|
235
|
+
// roll advances the archive day when the host was down across midnight; the
|
|
236
|
+
// daily roll keeps a long-running host on the same schedule. Both are
|
|
237
|
+
// reversible, and a disabled journal schedules nothing.
|
|
238
|
+
ctx.effect(() => {
|
|
239
|
+
void journal.rotateIfStale();
|
|
240
|
+
const stop = journal.startDailyRotation();
|
|
241
|
+
return () => stop();
|
|
242
|
+
}, 'guard-journal-rotation');
|
|
243
|
+
ctx.effect(() => { void retireLegacyStore(journal); return () => { }; }, 'guard-retire-legacy-store');
|
|
244
|
+
// Journal the v1 -> v2 config migration once per boot, from the boot read
|
|
245
|
+
// above; the per-call read stays the cheap `loadGuardConfig`.
|
|
246
|
+
ctx.effect(() => { void journalConfigMigration(journal, boot.migratedKeys); return () => { }; }, 'guard-journal-legacy-config');
|
|
247
|
+
// register on-demand full-scan tool (Task 4) alongside guard handler
|
|
248
|
+
applyFullScan(ctx, {});
|
|
249
|
+
// Read-only introspection of the journal the handler above writes: the
|
|
250
|
+
// recent decisions plus the aggregate counters. Registered after the flush
|
|
251
|
+
// wiring, each registration its own reversible effect (see the module).
|
|
252
|
+
applyStatusTools(ctx, { journal, config: loadGuardConfig });
|
|
253
|
+
},
|
|
254
|
+
};
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { type Tier } from './tiers.js';
|
|
2
|
+
export type AskOutcome = 'granted' | 'rejected' | 'cancelled' | 'unavailable' | 'error';
|
|
3
|
+
export interface JournalEntry {
|
|
4
|
+
ts: string;
|
|
5
|
+
session?: string;
|
|
6
|
+
tool: string;
|
|
7
|
+
rule: string;
|
|
8
|
+
tier: Tier;
|
|
9
|
+
target: string;
|
|
10
|
+
repo?: string;
|
|
11
|
+
branch?: string;
|
|
12
|
+
cwd?: string;
|
|
13
|
+
outcome?: AskOutcome | 'passed' | 'denied';
|
|
14
|
+
askMs?: number;
|
|
15
|
+
redacted: true;
|
|
16
|
+
note?: string;
|
|
17
|
+
}
|
|
18
|
+
/** Retention knobs. Count and age are BOTH windows; the larger one wins. */
|
|
19
|
+
export interface RotateOptions {
|
|
20
|
+
/** Keep at least the newest N archive files (default 14). */
|
|
21
|
+
retainFiles?: number;
|
|
22
|
+
/** Keep at least archives newer than N days (default 30). */
|
|
23
|
+
retainDays?: number;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The journal block of `domains.guard`, read ONCE when the guard boots. These
|
|
27
|
+
* are boot-time knobs: unlike the per-call rule config the handler re-reads on
|
|
28
|
+
* every decision, changing them requires a host restart. Every field defaults
|
|
29
|
+
* to the built-in behaviour (enabled, counters on, 14 files / 30 days).
|
|
30
|
+
*/
|
|
31
|
+
export interface JournalOptions {
|
|
32
|
+
/** `false` → `append()` writes nothing and `startFlush()` never starts. */
|
|
33
|
+
enabled?: boolean;
|
|
34
|
+
/** `false` → `count()` is a no-op, so allow decisions never reach disk. */
|
|
35
|
+
allowCounters?: boolean;
|
|
36
|
+
/** Default `retainFiles` for `rotate()`. */
|
|
37
|
+
retainFiles?: number;
|
|
38
|
+
/** Default `retainDays` for `rotate()`. */
|
|
39
|
+
retainDays?: number;
|
|
40
|
+
}
|
|
41
|
+
/** The rule id of the periodic aggregate line (see `flushCounters`). */
|
|
42
|
+
export declare const COUNTERS_RULE = "counters";
|
|
43
|
+
export declare function journalDir(dshHome?: string): string;
|
|
44
|
+
export declare function journalPath(dshHome?: string): string;
|
|
45
|
+
/**
|
|
46
|
+
* The boot-rotate decision: roll the live journal when its last write landed on
|
|
47
|
+
* an earlier UTC day than the current clock. The live file carries no date in
|
|
48
|
+
* its name (`journal.jsonl`), so the day is read from its mtime — one `stat`,
|
|
49
|
+
* no file read. `undefined` (no live file) is never a rotation: a boot with
|
|
50
|
+
* nothing recorded must not create an empty archive, and a missing file must
|
|
51
|
+
* never fail boot. UTC, because that is the day `freeArchivePath` names archives
|
|
52
|
+
* by.
|
|
53
|
+
*/
|
|
54
|
+
export declare function shouldRotateAtBoot(liveMtimeMs: number | undefined, now: number): boolean;
|
|
55
|
+
export declare class Journal {
|
|
56
|
+
private dshHome?;
|
|
57
|
+
private now;
|
|
58
|
+
private opts;
|
|
59
|
+
/**
|
|
60
|
+
* Decisions per `${rule}|${tier}` since the last flush. `allow` is the tier
|
|
61
|
+
* that lives only here: it is counted in memory and reaches disk as one
|
|
62
|
+
* aggregate line, so an ordinary command costs no journal I/O.
|
|
63
|
+
*/
|
|
64
|
+
private counters;
|
|
65
|
+
/** Boot-time gates derived from {@link JournalOptions}. */
|
|
66
|
+
private readonly writesEnabled;
|
|
67
|
+
private readonly allowCounters;
|
|
68
|
+
constructor(dshHome?: string | undefined, now?: () => number, opts?: JournalOptions);
|
|
69
|
+
/** The journal file this instance reads and appends (`journalPath` for its home). */
|
|
70
|
+
get path(): string;
|
|
71
|
+
/**
|
|
72
|
+
* The boot-time write gate. Exposed because the status tool must report what
|
|
73
|
+
* this instance actually does — not a second reading of the config block,
|
|
74
|
+
* which could disagree with the journal a long-running host already built.
|
|
75
|
+
*/
|
|
76
|
+
get enabled(): boolean;
|
|
77
|
+
append(entry: Omit<JournalEntry, 'ts' | 'redacted'>): Promise<void>;
|
|
78
|
+
/**
|
|
79
|
+
* Count one decision. Synchronous and I/O-free on purpose: this runs inside
|
|
80
|
+
* the decision path, so it must never cost more than two Map operations. The
|
|
81
|
+
* `rule` is part of the key (a later reader can break the aggregate down by
|
|
82
|
+
* rule) even though the flushed note reports tier totals.
|
|
83
|
+
*/
|
|
84
|
+
count(rule: string, tier: Tier): void;
|
|
85
|
+
/**
|
|
86
|
+
* Persist the pending counters as ONE ordinary journal entry and clear them.
|
|
87
|
+
* The counters are drained before the write is awaited, so a decision counted
|
|
88
|
+
* during the write lands in the next flush rather than being lost or doubled.
|
|
89
|
+
* An empty map writes nothing — flushes are periodic, quiet ones are free.
|
|
90
|
+
*/
|
|
91
|
+
flushCounters(): Promise<void>;
|
|
92
|
+
/**
|
|
93
|
+
* The recent journal, NEWEST FIRST. The live file is the newest source, so it
|
|
94
|
+
* is read first, then the archives newest → oldest; `limit` keeps the most
|
|
95
|
+
* recent entries only and stops the walk as soon as it is satisfied. The walk
|
|
96
|
+
* must cross archives: reading the newest one alone would answer a
|
|
97
|
+
* `read(1000)` with a single day of history. A missing directory, a missing
|
|
98
|
+
* file or a torn line is skipped rather than thrown — a reader must not be
|
|
99
|
+
* able to break the guard.
|
|
100
|
+
*/
|
|
101
|
+
read(limit?: number): Promise<JournalEntry[]>;
|
|
102
|
+
/**
|
|
103
|
+
* Roll `journal.jsonl` into a dated archive, then enforce retention and
|
|
104
|
+
* return the REMOVED archive paths (the new archive is not a removal).
|
|
105
|
+
* Retention keeps an archive that is inside the file window OR inside the day
|
|
106
|
+
* window — i.e. the newer of the two — so a quiet month never prunes a busy
|
|
107
|
+
* fortnight. Never throws.
|
|
108
|
+
*
|
|
109
|
+
* Overlapping calls are serialized (see {@link enqueueRotation}) and the
|
|
110
|
+
* archive a call just created is never a retention candidate: with both
|
|
111
|
+
* windows empty the call would otherwise unlink the entire rolled history it
|
|
112
|
+
* had just renamed into place.
|
|
113
|
+
*/
|
|
114
|
+
rotate(opts?: RotateOptions): Promise<string[]>;
|
|
115
|
+
private rotateOnce;
|
|
116
|
+
/**
|
|
117
|
+
* Flush the counters every `intervalMs` and return the disposer that stops
|
|
118
|
+
* it. The flush is periodic by design: the decision path only ever touches
|
|
119
|
+
* the in-memory map. The timer is unref'd so a pending flush never keeps the
|
|
120
|
+
* host process alive. A disabled journal starts no timer at all.
|
|
121
|
+
*/
|
|
122
|
+
startFlush(intervalMs: number): () => void;
|
|
123
|
+
/**
|
|
124
|
+
* The BOOT roll: rotate when the live file's last write predates today, so
|
|
125
|
+
* the archive set — and the retention windows that prune it — advances even
|
|
126
|
+
* on a host that restarts daily. One `stat` is the only I/O; a missing live
|
|
127
|
+
* file, or one already written today, is a silent no-op. A disabled journal
|
|
128
|
+
* rolls nothing, the same rule `append` and `startFlush` follow.
|
|
129
|
+
*
|
|
130
|
+
* The roll is named by the rotation clock (today), like every other rotation;
|
|
131
|
+
* the file's contents are whatever accumulated since the last roll, so the
|
|
132
|
+
* archive day is the day the archive was made, never a claim about its
|
|
133
|
+
* contents.
|
|
134
|
+
*/
|
|
135
|
+
rotateIfStale(): Promise<string[]>;
|
|
136
|
+
/**
|
|
137
|
+
* Rotate once per `intervalMs` (default: one day) and return the disposer that
|
|
138
|
+
* stops it. This is what makes `retainFiles`/`retainDays` take effect on a
|
|
139
|
+
* long-running host, not just at boot. The timer is unref'd so a pending roll
|
|
140
|
+
* never keeps the host process alive, and a disabled journal starts no timer
|
|
141
|
+
* at all — the same reversible-disposer discipline as {@link startFlush}.
|
|
142
|
+
*/
|
|
143
|
+
startDailyRotation(intervalMs?: number): () => void;
|
|
144
|
+
/** The first unused `journal-<today>[-<n>].jsonl` under `dir`. */
|
|
145
|
+
private freeArchivePath;
|
|
146
|
+
}
|