@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,40 @@
|
|
|
1
|
+
import type { Tier } from './tiers.js'
|
|
2
|
+
import { DEFAULT_TIERS, type Verdict } from './rules.js'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Resolve a classified verdict to the tier actually enforced, after per-rule
|
|
6
|
+
* config overrides.
|
|
7
|
+
*
|
|
8
|
+
* `deny` is a structural floor: a rule that is never approvable cannot be
|
|
9
|
+
* downgraded by configuration, or the guard's tamper protection would be one
|
|
10
|
+
* settings edit away from disappearing.
|
|
11
|
+
*
|
|
12
|
+
* An entry that merely ECHOES the rule's built-in tier is not an override. The
|
|
13
|
+
* handler passes `cfg.rules`, which is the fully-populated table
|
|
14
|
+
* `DEFAULT_CONFIG` carries — every rule id appears there whether the user wrote
|
|
15
|
+
* one or not. Honouring those entries as overrides made every classify-level
|
|
16
|
+
* tier refinement unreachable: `pkg.publish` classifies a `--dry-run` as
|
|
17
|
+
* `journal`, but the table's `pkg.publish: ask` default then won, so production
|
|
18
|
+
* asked for a dry run while the corpus (asserting through `decide(v, {})`, a
|
|
19
|
+
* shape no production code used) reported `journal`. An entry that DIFFERS from
|
|
20
|
+
* `DEFAULT_TIERS` is an explicit user choice, and it raises or lowers the tier.
|
|
21
|
+
*/
|
|
22
|
+
export function decide(v: Verdict, overrides: Partial<Record<string, Tier>>): { tier: Tier; ruleId: string } {
|
|
23
|
+
if (v.tier === 'deny') return { tier: 'deny', ruleId: v.ruleId }
|
|
24
|
+
const override = overrides[v.ruleId]
|
|
25
|
+
if (override === undefined || override === DEFAULT_TIERS[v.ruleId]) {
|
|
26
|
+
return { tier: v.tier, ruleId: v.ruleId }
|
|
27
|
+
}
|
|
28
|
+
return { tier: override, ruleId: v.ruleId }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Human-readable reason for a blocked/asked call: the rule id plus where it
|
|
33
|
+
* happened, then the (redacted, truncated) target. The rule id is the stable
|
|
34
|
+
* contract other surfaces key on; the prose after `::` is presentation only.
|
|
35
|
+
*/
|
|
36
|
+
export function renderReason(v: Verdict, redactFn: (s: string) => string): string {
|
|
37
|
+
const where = [v.repo, v.branch].filter(Boolean).join(':')
|
|
38
|
+
const head = `${v.ruleId}${where ? ` (${where})` : ''}`
|
|
39
|
+
return `${head} :: ${redactFn(v.target).slice(0, 300)}`
|
|
40
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process'
|
|
2
|
+
import { existsSync } from 'node:fs'
|
|
3
|
+
import { resolve, join } from 'node:path'
|
|
4
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
5
|
+
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
6
|
+
export const name = 'maestro-full-scan-tool'
|
|
7
|
+
export const inject = ['tools'] as const
|
|
8
|
+
function workspaceRootFor(c:string|undefined, e:unknown): string {
|
|
9
|
+
if (c) return c
|
|
10
|
+
const cwd=(e as any)?.agent?.session?.header?.cwd
|
|
11
|
+
return typeof cwd==='string'&&cwd?cwd:process.cwd()
|
|
12
|
+
}
|
|
13
|
+
function resolveScript(root:string): string {
|
|
14
|
+
// ONLY the requested root and its ancestors. The old version also walked up
|
|
15
|
+
// from process.cwd() as a last resort, so a call aimed at a directory without
|
|
16
|
+
// the script silently scanned the guard's OWN checkout and returned that
|
|
17
|
+
// repo's blacklist hits as if they were the caller's. Scanning a tree nobody
|
|
18
|
+
// asked about is worse than reporting nothing: the report looks authoritative.
|
|
19
|
+
let cur = resolve(root)
|
|
20
|
+
for (let i=0;i<8;i++) {
|
|
21
|
+
const cand = join(cur, 'scripts/enforce-rules.mjs')
|
|
22
|
+
if (existsSync(cand)) return cand
|
|
23
|
+
const parent = resolve(cur, '..')
|
|
24
|
+
if (parent===cur) break
|
|
25
|
+
cur = parent
|
|
26
|
+
}
|
|
27
|
+
return join(resolve(root), 'scripts/enforce-rules.mjs')
|
|
28
|
+
}
|
|
29
|
+
export function apply(ctx: Context, config:{rootPath?:string}={}) {
|
|
30
|
+
ctx.effect(()=> ctx.tools.register(defineTool({
|
|
31
|
+
name:'maestro_full_scan',
|
|
32
|
+
description:'Run full enforce-rules scan (blacklist + protection + publish gate) and return report. No approval needed; read-only.',
|
|
33
|
+
parameters:{ rootPath:{type:'string', description:'workspace root override'} },
|
|
34
|
+
output:{ schema:{type:'object', additionalProperties:true, properties:{ok:{type:'boolean', required:true}, report:{type:'string', required:true}, code:{type:'number', required:true}}}, render:(_a:any,v:any)=>[{type:'text', text: v.report.slice(0,4000)}] },
|
|
35
|
+
async execute(args:any, exec:unknown) {
|
|
36
|
+
const root = workspaceRootFor((args as any)?.rootPath ?? config.rootPath, exec)
|
|
37
|
+
const script = resolveScript(root)
|
|
38
|
+
if (!existsSync(script)) {
|
|
39
|
+
return {ok: true, report: `enforce-rules: no script found at ${script} (standalone repo, skipping)`, code: 0}
|
|
40
|
+
}
|
|
41
|
+
const run = (extra:string[])=>{
|
|
42
|
+
// cwd = the scanned root: the script resolves its own targets relative to
|
|
43
|
+
// it, so inheriting the host's cwd made the report describe the wrong tree.
|
|
44
|
+
const r=spawnSync('node', [script, ...extra], {encoding:'utf-8', timeout: 30000, cwd: resolve(root)})
|
|
45
|
+
return {code: r.status??0, out: (r.stdout??'')+(r.stderr??'')}
|
|
46
|
+
}
|
|
47
|
+
let combined=''
|
|
48
|
+
let ok=true
|
|
49
|
+
const a=run([])
|
|
50
|
+
combined+=`$ node scripts/enforce-rules.mjs\n${a.out}\n`
|
|
51
|
+
if (a.code!==0) ok=false
|
|
52
|
+
const b=run(['--check-protection'])
|
|
53
|
+
combined+=`$ node scripts/enforce-rules.mjs --check-protection\n${b.out}\n`
|
|
54
|
+
if (b.code!==0) combined+=`[warn] --check-protection non-zero (may need gh auth)\n`
|
|
55
|
+
const c=run(['--check-publish'])
|
|
56
|
+
combined+=`$ node scripts/enforce-rules.mjs --check-publish\n${c.out}\n`
|
|
57
|
+
// do not fail on --check-publish when no tag
|
|
58
|
+
return {ok, report: combined.slice(0,12000), code: ok?0:1}
|
|
59
|
+
}
|
|
60
|
+
})))
|
|
61
|
+
}
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import { execSync } from 'node:child_process'
|
|
2
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
3
|
+
import { PermissionPolicy } from './permission-policy.js'
|
|
4
|
+
import { Journal, type AskOutcome } from './journal.js'
|
|
5
|
+
import { redact } from './redact.js'
|
|
6
|
+
import { classify } from './rules.js'
|
|
7
|
+
import { decide, renderReason } from './decide.js'
|
|
8
|
+
import { DEFAULT_CONFIG, loadGuardConfig, loadGuardConfigWithMigration, type GuardConfigV2 } from './config.js'
|
|
9
|
+
import { retireLegacyStore } from './migrate.js'
|
|
10
|
+
import { apply as applyFullScan } from './full-scan-tool.js'
|
|
11
|
+
import { applyStatusTools } from './status-tool.js'
|
|
12
|
+
import './validators.js'
|
|
13
|
+
import type { GuardToolExecution, GuardPreToolDecision } from './augment.js'
|
|
14
|
+
|
|
15
|
+
export interface GuardDeps {
|
|
16
|
+
journal: Journal
|
|
17
|
+
policy: PermissionPolicy
|
|
18
|
+
readConfig: () => Promise<GuardConfigV2>
|
|
19
|
+
branchOf?: (dir: string) => string | undefined
|
|
20
|
+
requestApproval: (req: { agent?: unknown; toolName: string; callId?: string; reason: string; signal?: AbortSignal }) => Promise<AskOutcome | ApprovalResult>
|
|
21
|
+
now?: () => number
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* What the approval transport observed, plus why when it failed. A transport
|
|
26
|
+
* that only knows the outcome may return the bare {@link AskOutcome} string; one
|
|
27
|
+
* that caught an error returns this shape so the message reaches the journal.
|
|
28
|
+
*/
|
|
29
|
+
export interface ApprovalResult {
|
|
30
|
+
outcome: AskOutcome
|
|
31
|
+
/** The thrown message, journaled (and redacted) with the `error` outcome. */
|
|
32
|
+
note?: string
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The rule id of the `tools/pre-execute` contract denial (spec §8). */
|
|
36
|
+
export const CONTRACT_MISMATCH_RULE = 'contract-mismatch'
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The DSH `tools/pre-execute` contract the guard reads: a tool NAME and an
|
|
40
|
+
* arguments field. The guard accepts both spellings of each (`name`/`tool`,
|
|
41
|
+
* `args`/`arguments`), but a payload carrying neither is a DSH upgrade that
|
|
42
|
+
* renames a field — and a renamed `args` silently disables EVERY command rule,
|
|
43
|
+
* because `extractCommandText(undefined)` yields no command to classify.
|
|
44
|
+
* Spec §8: an unknown payload is a denial, never a pass.
|
|
45
|
+
*
|
|
46
|
+
* A `null` argument list counts as ABSENT, not as an empty one: `??` already
|
|
47
|
+
* falls through on null, so treating it as present would let a null `args`
|
|
48
|
+
* reach `extractCommandText` and allow a command the rules never saw.
|
|
49
|
+
*/
|
|
50
|
+
export function contractMismatch(exec: unknown): string | undefined {
|
|
51
|
+
if (exec === null || typeof exec !== 'object') return 'pre-execute payload is not an object'
|
|
52
|
+
const e = exec as GuardToolExecution
|
|
53
|
+
const name = typeof e.name === 'string' && e.name !== ''
|
|
54
|
+
? e.name
|
|
55
|
+
: typeof e.tool === 'string' && e.tool !== '' ? e.tool : undefined
|
|
56
|
+
if (name === undefined) return 'pre-execute payload carries no tool name (`name`/`tool`)'
|
|
57
|
+
if ((e.args === undefined || e.args === null) && (e.arguments === undefined || e.arguments === null)) {
|
|
58
|
+
return 'pre-execute payload carries no arguments (`args`/`arguments`)'
|
|
59
|
+
}
|
|
60
|
+
return undefined
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Outcome vocabulary for the deny message. `unavailable` is the fail-closed
|
|
65
|
+
* case that matters most: no answerer is attached to this session, so the
|
|
66
|
+
* operation cannot be approved and must not silently proceed.
|
|
67
|
+
*
|
|
68
|
+
* `rejected` names BOTH causes on purpose. DSH's approval service resolves a
|
|
69
|
+
* session whose policy is `never` to `rejected` deterministically, before any
|
|
70
|
+
* answerer is dispatched (`packages/interaction/user-approval`), so the guard
|
|
71
|
+
* cannot tell a policy rejection from a human one — and a bare "the user
|
|
72
|
+
* rejected this" would be a lie in a session with no human in the loop. The
|
|
73
|
+
* message therefore carries the fix either way (spec §5.6/§8).
|
|
74
|
+
*/
|
|
75
|
+
const EXPLAIN: Record<AskOutcome, string> = {
|
|
76
|
+
granted: 'granted once',
|
|
77
|
+
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',
|
|
78
|
+
cancelled: 'the approval prompt was cancelled',
|
|
79
|
+
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)',
|
|
80
|
+
error: 'the approval request failed (see the guard journal)',
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The guard pipeline: classify the call into a rule id, resolve the rule's tier,
|
|
85
|
+
* journal the decision, then act — `next()` for allow/journal, a deny decision
|
|
86
|
+
* for deny, and for ask a NATIVE approval request to DSH's `approval` service.
|
|
87
|
+
*
|
|
88
|
+
* Every branch journals before it returns, and the journal is optional in the
|
|
89
|
+
* failure direction only: a journal write that fails is logged and changes no
|
|
90
|
+
* decision (see `Journal.append`).
|
|
91
|
+
*/
|
|
92
|
+
export function createGuardHandler(deps: GuardDeps) {
|
|
93
|
+
const now = deps.now ?? Date.now
|
|
94
|
+
return async (exec: GuardToolExecution, next: () => Promise<GuardPreToolDecision>): Promise<GuardPreToolDecision> => {
|
|
95
|
+
// The runtime contract first: a payload the guard cannot read must be denied
|
|
96
|
+
// and journaled, never allowed — a renamed field would otherwise silence
|
|
97
|
+
// every command rule (spec §8).
|
|
98
|
+
const mismatch = contractMismatch(exec)
|
|
99
|
+
if (mismatch !== undefined) {
|
|
100
|
+
const label = typeof (exec as GuardToolExecution | undefined)?.name === 'string'
|
|
101
|
+
? (exec as GuardToolExecution).name
|
|
102
|
+
: 'unknown'
|
|
103
|
+
await deps.journal.append({
|
|
104
|
+
tool: label, rule: CONTRACT_MISMATCH_RULE, tier: 'deny',
|
|
105
|
+
target: 'tools/pre-execute', outcome: 'denied', note: mismatch,
|
|
106
|
+
})
|
|
107
|
+
return { kind: 'deny', reason: `${CONTRACT_MISMATCH_RULE} :: ${mismatch}` }
|
|
108
|
+
}
|
|
109
|
+
const tool = exec.name ?? exec.tool ?? ''
|
|
110
|
+
const args = exec.args ?? exec.arguments
|
|
111
|
+
const cwd = exec.agent?.session?.header?.cwd
|
|
112
|
+
const session = exec.agent?.session?.id
|
|
113
|
+
const cfg = await deps.readConfig().catch(() => DEFAULT_CONFIG)
|
|
114
|
+
const settings = {
|
|
115
|
+
protectedBranches: cfg.protectedBranches,
|
|
116
|
+
protectedPaths: cfg.protectedPaths,
|
|
117
|
+
guardPaths: cfg.guardPaths,
|
|
118
|
+
// Part of the per-call read (unlike the boot-time journal block), so a
|
|
119
|
+
// `workingDirContainment` change takes effect on the next tool call.
|
|
120
|
+
workingDirContainment: cfg.workingDirContainment,
|
|
121
|
+
}
|
|
122
|
+
const verdict = classify({ tool, args, cwd, settings, branchOf: deps.branchOf })
|
|
123
|
+
const { tier } = decide(verdict, cfg.rules)
|
|
124
|
+
|
|
125
|
+
if (!deps.policy.isAllowed(tool, args)) {
|
|
126
|
+
await deps.journal.append({ session, tool, rule: 'policy.deny', tier: 'deny', target: verdict.target, cwd, outcome: 'denied' })
|
|
127
|
+
return { kind: 'deny', reason: `tool ${tool} denied by policy` }
|
|
128
|
+
}
|
|
129
|
+
if (tier === 'allow') {
|
|
130
|
+
// In-memory only: the count is what the periodic flush below persists, so
|
|
131
|
+
// an ordinary command stays off the journal's I/O path (see `startFlush`).
|
|
132
|
+
deps.journal.count(verdict.ruleId, tier)
|
|
133
|
+
return next()
|
|
134
|
+
}
|
|
135
|
+
if (tier === 'journal') {
|
|
136
|
+
await deps.journal.append({ session, tool, rule: verdict.ruleId, tier, target: verdict.target, repo: verdict.repo, branch: verdict.branch, cwd, outcome: 'passed' })
|
|
137
|
+
return next()
|
|
138
|
+
}
|
|
139
|
+
const reason = renderReason(verdict, redact)
|
|
140
|
+
if (tier === 'deny') {
|
|
141
|
+
await deps.journal.append({ session, tool, rule: verdict.ruleId, tier, target: verdict.target, cwd, outcome: 'denied' })
|
|
142
|
+
return { kind: 'deny', reason }
|
|
143
|
+
}
|
|
144
|
+
const t0 = now()
|
|
145
|
+
const raw = await deps.requestApproval({
|
|
146
|
+
agent: exec.agent, toolName: tool, callId: exec.callId, reason, signal: exec.signal,
|
|
147
|
+
})
|
|
148
|
+
const { outcome, note } = typeof raw === 'string' ? { outcome: raw, note: undefined } : raw
|
|
149
|
+
await deps.journal.append({
|
|
150
|
+
session, tool, rule: verdict.ruleId, tier, target: verdict.target, repo: verdict.repo,
|
|
151
|
+
branch: verdict.branch, cwd, outcome, askMs: now() - t0,
|
|
152
|
+
// The deny text tells the human to see the journal, so the thrown reason
|
|
153
|
+
// has to be IN it; `Journal.append` redacts every string field.
|
|
154
|
+
...(note === undefined ? {} : { note }),
|
|
155
|
+
})
|
|
156
|
+
// A granted ask returns `next()` rather than a bare allow so the remaining
|
|
157
|
+
// pre-execute listeners still run (a bare allow would short-circuit them).
|
|
158
|
+
return outcome === 'granted' ? next() : { kind: 'deny', reason: `${reason} — ${EXPLAIN[outcome]}` }
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Branch of the repo a command targets. The caller resolves the repo directory
|
|
164
|
+
* itself (`git -C` / `cd` handling lives in `rules.ts`); an EMPTY directory is
|
|
165
|
+
* the "no resolvable repo" sentinel and must never be turned into
|
|
166
|
+
* `git -C ""`, which would silently resolve to the session cwd and re-create
|
|
167
|
+
* the false positives the repo resolution exists to remove.
|
|
168
|
+
*/
|
|
169
|
+
export function branchOf(dir: string): string | undefined {
|
|
170
|
+
if (!dir) return undefined
|
|
171
|
+
try {
|
|
172
|
+
return execSync('git branch --show-current', { cwd: dir, timeout: 800, encoding: 'utf-8' }).trim() || undefined
|
|
173
|
+
} catch {
|
|
174
|
+
return undefined
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** The DSH approval service, structurally typed (the guard never imports it). */
|
|
179
|
+
interface NativeApproval {
|
|
180
|
+
request(req: { agent: unknown; toolName: string; callId?: string; reason: string; signal?: AbortSignal }): Promise<string>
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Journal an ALREADY-COMPUTED migration result. Split out of
|
|
185
|
+
* {@link journalLegacyConfigMigration} so `apply()` can reuse the single
|
|
186
|
+
* boot-time config read for both the journal knobs and this note. Never throws.
|
|
187
|
+
*/
|
|
188
|
+
export async function journalConfigMigration(journal: Journal, migratedKeys: string[]): Promise<string[]> {
|
|
189
|
+
try {
|
|
190
|
+
if (migratedKeys.length === 0) return []
|
|
191
|
+
const target = migratedKeys.join(',')
|
|
192
|
+
await journal.append({
|
|
193
|
+
tool: 'guard',
|
|
194
|
+
rule: 'config-legacy',
|
|
195
|
+
tier: 'journal',
|
|
196
|
+
target,
|
|
197
|
+
outcome: 'passed',
|
|
198
|
+
note: `legacy domains.guard keys migrated onto schema v2: ${target}`,
|
|
199
|
+
})
|
|
200
|
+
return migratedKeys
|
|
201
|
+
} catch (e) {
|
|
202
|
+
console.error('[dsh-maestro-guard] legacy config migration failed:', (e as Error)?.message)
|
|
203
|
+
return []
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Journal the schema-v1 → v2 config migration ONCE per boot. The handler's
|
|
209
|
+
* per-call config read (`loadGuardConfig`) is deliberately mute, so without
|
|
210
|
+
* this a persisted `domains.guard` written for schema v1 would change what the
|
|
211
|
+
* guard gates without leaving any trace of why.
|
|
212
|
+
*
|
|
213
|
+
* Exported so the boot effect body is unit-testable. Never throws: a failed
|
|
214
|
+
* read or a failed journal write must not stop the guard from booting, and
|
|
215
|
+
* `migratedKeys.length === 0` writes nothing at all.
|
|
216
|
+
*/
|
|
217
|
+
export async function journalLegacyConfigMigration(journal: Journal, dshHome?: string): Promise<string[]> {
|
|
218
|
+
try {
|
|
219
|
+
const { migratedKeys } = await loadGuardConfigWithMigration(dshHome)
|
|
220
|
+
return await journalConfigMigration(journal, migratedKeys)
|
|
221
|
+
} catch (e) {
|
|
222
|
+
console.error('[dsh-maestro-guard] legacy config migration failed:', (e as Error)?.message)
|
|
223
|
+
return []
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export default {
|
|
228
|
+
inject: ['tools'] as const,
|
|
229
|
+
async apply(ctx: Context) {
|
|
230
|
+
// `domains.guard.journal` is a BOOT-TIME block: it decides whether the
|
|
231
|
+
// journal writes at all and which retention defaults `rotate()` uses, so it
|
|
232
|
+
// is read once here — unlike the per-call rule config, a settings change
|
|
233
|
+
// needs a host restart. The same read feeds the one-shot migration note.
|
|
234
|
+
const boot = await loadGuardConfigWithMigration().catch(() => ({ config: DEFAULT_CONFIG, migratedKeys: [] as string[] }))
|
|
235
|
+
const journal = new Journal(undefined, Date.now, boot.config.journal)
|
|
236
|
+
const policy = new PermissionPolicy({ deny: ['danger-tool'] })
|
|
237
|
+
const requestApproval = async (req: { agent?: unknown; toolName: string; callId?: string; reason: string; signal?: AbortSignal }): Promise<ApprovalResult> => {
|
|
238
|
+
const approval = ctx.get('approval') as NativeApproval | undefined
|
|
239
|
+
if (!approval || req.agent === undefined) return { outcome: 'unavailable' }
|
|
240
|
+
try {
|
|
241
|
+
const outcome = await approval.request({
|
|
242
|
+
agent: req.agent, toolName: req.toolName, callId: req.callId, reason: req.reason, signal: req.signal,
|
|
243
|
+
})
|
|
244
|
+
return { outcome: outcome === 'allowed-once' ? 'granted' : (outcome as AskOutcome) }
|
|
245
|
+
} catch (e) {
|
|
246
|
+
// The thrown reason is what the human needs (an idle ask rejects with
|
|
247
|
+
// "outside an open turn"), so it travels with the outcome instead of
|
|
248
|
+
// being dropped on the floor with only a stderr note.
|
|
249
|
+
const message = (e as Error)?.message ?? String(e)
|
|
250
|
+
console.error('[dsh-maestro-guard] approval request failed:', message)
|
|
251
|
+
return { outcome: 'error', note: message }
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
const handler = createGuardHandler({ journal, policy, readConfig: loadGuardConfig, branchOf, requestApproval })
|
|
255
|
+
ctx.effect(() => ctx.on('tools/pre-execute', handler as any))
|
|
256
|
+
// Allow counters are in-memory; one aggregate line per interval keeps them
|
|
257
|
+
// off the decision path. The effect disposes the timer on unload, and a
|
|
258
|
+
// journal disabled by config starts no timer at all (`startFlush` is a no-op).
|
|
259
|
+
ctx.effect(() => { const stop = journal.startFlush(60_000); return () => stop() }, 'guard-journal-counter-flush')
|
|
260
|
+
// Retention used to depend on a caller that never existed, so the live file
|
|
261
|
+
// grew without bound and `retainFiles`/`retainDays` never applied. The boot
|
|
262
|
+
// roll advances the archive day when the host was down across midnight; the
|
|
263
|
+
// daily roll keeps a long-running host on the same schedule. Both are
|
|
264
|
+
// reversible, and a disabled journal schedules nothing.
|
|
265
|
+
ctx.effect(() => {
|
|
266
|
+
void journal.rotateIfStale()
|
|
267
|
+
const stop = journal.startDailyRotation()
|
|
268
|
+
return () => stop()
|
|
269
|
+
}, 'guard-journal-rotation')
|
|
270
|
+
ctx.effect(() => { void retireLegacyStore(journal); return () => {} }, 'guard-retire-legacy-store')
|
|
271
|
+
// Journal the v1 -> v2 config migration once per boot, from the boot read
|
|
272
|
+
// above; the per-call read stays the cheap `loadGuardConfig`.
|
|
273
|
+
ctx.effect(() => { void journalConfigMigration(journal, boot.migratedKeys); return () => {} }, 'guard-journal-legacy-config')
|
|
274
|
+
// register on-demand full-scan tool (Task 4) alongside guard handler
|
|
275
|
+
applyFullScan(ctx, {})
|
|
276
|
+
// Read-only introspection of the journal the handler above writes: the
|
|
277
|
+
// recent decisions plus the aggregate counters. Registered after the flush
|
|
278
|
+
// wiring, each registration its own reversible effect (see the module).
|
|
279
|
+
applyStatusTools(ctx, { journal, config: loadGuardConfig })
|
|
280
|
+
},
|
|
281
|
+
}
|