dsh-permission-rules 0.2.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 (49) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/LICENSE +201 -0
  3. package/README.es.md +182 -0
  4. package/README.hi.md +182 -0
  5. package/README.md +182 -0
  6. package/README.pt.md +182 -0
  7. package/README.zh.md +182 -0
  8. package/cordis.patch.yml +16 -0
  9. package/docs/rules-format.en.md +105 -0
  10. package/docs/rules-format.md +103 -0
  11. package/docs/rules-format.schema.json +117 -0
  12. package/lib/index.js +1606 -0
  13. package/lib/types/config.d.ts +83 -0
  14. package/lib/types/config.d.ts.map +1 -0
  15. package/lib/types/config.js +72 -0
  16. package/lib/types/config.js.map +1 -0
  17. package/lib/types/events.d.ts +68 -0
  18. package/lib/types/events.d.ts.map +1 -0
  19. package/lib/types/events.js +21 -0
  20. package/lib/types/events.js.map +1 -0
  21. package/lib/types/glob.d.ts +55 -0
  22. package/lib/types/glob.d.ts.map +1 -0
  23. package/lib/types/glob.js +307 -0
  24. package/lib/types/glob.js.map +1 -0
  25. package/lib/types/index.d.ts +25 -0
  26. package/lib/types/index.d.ts.map +1 -0
  27. package/lib/types/index.js +25 -0
  28. package/lib/types/index.js.map +1 -0
  29. package/lib/types/prose.d.ts +66 -0
  30. package/lib/types/prose.d.ts.map +1 -0
  31. package/lib/types/prose.js +143 -0
  32. package/lib/types/prose.js.map +1 -0
  33. package/lib/types/rules.d.ts +226 -0
  34. package/lib/types/rules.d.ts.map +1 -0
  35. package/lib/types/rules.js +581 -0
  36. package/lib/types/rules.js.map +1 -0
  37. package/lib/types/runtime.d.ts +175 -0
  38. package/lib/types/runtime.d.ts.map +1 -0
  39. package/lib/types/runtime.js +497 -0
  40. package/lib/types/runtime.js.map +1 -0
  41. package/package.json +103 -0
  42. package/scripts/repair-session-logs.mjs +327 -0
  43. package/src/config.ts +141 -0
  44. package/src/events.ts +75 -0
  45. package/src/glob.ts +303 -0
  46. package/src/index.ts +27 -0
  47. package/src/prose.ts +206 -0
  48. package/src/rules.ts +695 -0
  49. package/src/runtime.ts +504 -0
package/src/runtime.ts ADDED
@@ -0,0 +1,504 @@
1
+ /**
2
+ * Runtime of `dsh-permission-rules`: per-workspace rule loading (project
3
+ * file chain by session cwd → fallback path → empty set), the
4
+ * `tools/pre-execute` listener that turns a first-match hit into a
5
+ * deny/ask decision (and NEVER short-circuits on allow or passthrough),
6
+ * the `permissionRules/decision` audit event, the `/rules` session command
7
+ * (`list | reload | decisions [n] | test <tool> <json>`), and
8
+ * Chokidar-driven reloads. Every registration is an effect.
9
+ * @module dsh-permission-rules/runtime
10
+ */
11
+
12
+ import { existsSync, readFileSync } from 'node:fs'
13
+ import { dirname, isAbsolute, join, resolve } from 'node:path'
14
+ import chokidar from 'chokidar'
15
+ import type { Context } from '@deepseek-ai/cordis'
16
+ import type { CommandInvocation, CommandResult } from '@deepseek-ai/dsh-commands'
17
+ import type { PreToolDecision, ToolExecution } from '@deepseek-ai/dsh-tools'
18
+ import { resolveConfig } from './config.ts'
19
+ import type { Config, ResolvedConfig } from './config.ts'
20
+ import { compileRules, compileRulesChain, describeRule, findUnreachableRules, matchRules, parseRulesDocument, RuleError } from './rules.ts'
21
+ import type { CompileOptions, CompiledRuleset, MatchContext, RuleHit } from './rules.ts'
22
+ import { DESCRIBE_TOKENS, UI_PROSE } from './prose.ts'
23
+ import type { UiProse } from './prose.ts'
24
+ import type { AuditAppend, AuditDecision, DecisionOutcome } from './events.ts'
25
+
26
+ export const name = 'permission-rules'
27
+
28
+ /** Services required before the plugin mounts. */
29
+ export const inject = ['commands', 'tools']
30
+
31
+ /** The rule state bound to one workspace cwd. */
32
+ interface LoadedRules {
33
+ /** The workspace root these rules were resolved for. */
34
+ readonly cwd: string
35
+ /** Absolute paths of the rule files in effect, nearest first; `[]` = empty rule set. */
36
+ readonly sources: readonly string[]
37
+ readonly compiled: CompiledRuleset
38
+ /** Last load error, when one is being reported (see {@link PermissionRulesRuntime.rulesFor}). */
39
+ readonly lastError?: string
40
+ /** `true` when the last initial load threw under `badFilePolicy: 'fail'`. */
41
+ readonly failed?: true
42
+ }
43
+
44
+ /**
45
+ * State and behavior. One instance per plugin mount; disposals are owned by
46
+ * the watcher/timer effects registered in {@link apply}.
47
+ */
48
+ export class PermissionRulesRuntime {
49
+ /** Loaded (or failed) rules per workspace cwd, least-recently-used first for eviction. */
50
+ private readonly byCwd = new Map<string, LoadedRules>()
51
+
52
+ /** Live watchers per rule-file path, with the cwds each serves. */
53
+ private readonly watchers = new Map<string, { readonly cwds: Set<string>; readonly close: () => void }>()
54
+
55
+ /** Debounce timers per rule-file path. */
56
+ private readonly timers = new Map<string, ReturnType<typeof setTimeout>>()
57
+
58
+ constructor(
59
+ private readonly ctx: Context,
60
+ readonly config: ResolvedConfig,
61
+ ) {}
62
+
63
+ /** The shared compile options derived from config. */
64
+ private compileOptions(): CompileOptions {
65
+ return {
66
+ patternMode: this.config.patternMode,
67
+ maxRules: this.config.maxRules,
68
+ maxGlobStars: this.config.maxGlobStars,
69
+ caseInsensitivePaths: this.config.caseInsensitivePaths,
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Resolve which files serve a workspace, nearest first: the project file
75
+ * under the session cwd (or an absolute `rulesFile`), with `searchUp`
76
+ * also merging every parent directory's file on the way to the root,
77
+ * else the configured fallback, else `[]` (empty rule set). Nearer files
78
+ * evaluate first, so a child can override a parent rule.
79
+ * @param cwd - the session's absolute workspace root.
80
+ * @returns the absolute rule-file paths in effect, nearest first.
81
+ */
82
+ resolveSources(cwd: string): string[] {
83
+ if (this.config.searchUp) {
84
+ const sources: string[] = []
85
+ let dir = cwd
86
+ for (;;) {
87
+ const candidate = join(dir, this.config.rulesFile)
88
+ if (existsSync(candidate)) sources.push(candidate)
89
+ const parent = dirname(dir)
90
+ if (parent === dir) break
91
+ dir = parent
92
+ }
93
+ return sources.length === 0 ? this.resolveFallback() : sources
94
+ }
95
+ const projectPath = isAbsolute(this.config.rulesFile) ? this.config.rulesFile : join(cwd, this.config.rulesFile)
96
+ if (existsSync(projectPath)) return [projectPath]
97
+ return this.resolveFallback()
98
+ }
99
+
100
+ /** The configured fallback file when it exists, else `[]`. */
101
+ private resolveFallback(): string[] {
102
+ const fallback = this.config.fallbackPath
103
+ if (fallback !== undefined) {
104
+ const fallbackPath = isAbsolute(fallback) ? fallback : resolve(fallback)
105
+ if (existsSync(fallbackPath)) return [fallbackPath]
106
+ }
107
+ return []
108
+ }
109
+
110
+ /**
111
+ * Read, parse, and compile the rule-file chain serving `cwd`. Under
112
+ * `badFilePolicy: 'ignore-with-warning'` a bad file degrades to an empty
113
+ * rule set with a warning and keeps its source paths (so a later fix is
114
+ * watched and adopted); under `'fail'` it throws.
115
+ * @param cwd - the workspace root.
116
+ * @returns the loaded state.
117
+ */
118
+ load(cwd: string): LoadedRules {
119
+ const sources = this.resolveSources(cwd)
120
+ if (sources.length === 0) return { cwd, sources: [], compiled: { rules: [], caseInsensitivePaths: this.config.caseInsensitivePaths } }
121
+ try {
122
+ const entries = sources.map(path => ({ path, text: readFileSync(path, 'utf8') }))
123
+ const { ruleset } = compileRulesChain(entries, this.compileOptions())
124
+ return { cwd, sources, compiled: ruleset }
125
+ } catch (error: unknown) {
126
+ const message = error instanceof Error ? error.message : String(error)
127
+ if (this.config.badFilePolicy === 'ignore-with-warning') {
128
+ this.ctx.logger.warn(`permission-rules: ignoring ${sources.join(', ')}: ${message} (empty rule set)`)
129
+ return { cwd, sources, compiled: { rules: [], caseInsensitivePaths: this.config.caseInsensitivePaths }, lastError: message }
130
+ }
131
+ throw error instanceof RuleError ? error : new RuleError(`cannot load ${sources.join(', ')}: ${message}`)
132
+ }
133
+ }
134
+
135
+ /**
136
+ * The rules in effect for one cwd, loading on first use. Under
137
+ * `badFilePolicy: 'fail'` a bad initial load throws on EVERY use (the
138
+ * pending tool call errors loudly) while the watcher keeps observing the
139
+ * files so a fix reloads into active rules. Cache hits refresh the
140
+ * least-recently-used position, so eviction drops the workspace that
141
+ * went longest without a decision.
142
+ * @param cwd - the workspace root.
143
+ * @returns the loaded rules.
144
+ */
145
+ rulesFor(cwd: string): LoadedRules {
146
+ const existing = this.byCwd.get(cwd)
147
+ if (existing !== undefined) {
148
+ if (existing.failed === true) {
149
+ throw new RuleError(existing.lastError ?? `rule load failed for ${cwd}`)
150
+ }
151
+ this.byCwd.delete(cwd)
152
+ this.byCwd.set(cwd, existing)
153
+ return existing
154
+ }
155
+ this.evictIfFull(cwd)
156
+ try {
157
+ const loaded = this.load(cwd)
158
+ this.byCwd.set(cwd, loaded)
159
+ this.reconcileWatch(cwd, loaded.sources)
160
+ return loaded
161
+ } catch (error: unknown) {
162
+ const message = error instanceof Error ? error.message : String(error)
163
+ const sources = this.resolveSources(cwd)
164
+ this.byCwd.set(cwd, { cwd, sources, compiled: { rules: [], caseInsensitivePaths: this.config.caseInsensitivePaths }, lastError: message, failed: true })
165
+ this.reconcileWatch(cwd, sources)
166
+ throw error
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Re-read the rule-file chain for one cwd (watch-driven or
172
+ * `/rules reload`). A bad file NEVER crashes the process: the previous
173
+ * rules stay active, the error is logged and reported on the next
174
+ * `/rules` output.
175
+ * @param cwd - the workspace root.
176
+ */
177
+ reload(cwd: string): void {
178
+ const previous = this.byCwd.get(cwd)
179
+ try {
180
+ const loaded = this.load(cwd)
181
+ this.byCwd.set(cwd, loaded)
182
+ this.reconcileWatch(cwd, loaded.sources)
183
+ this.ctx.logger.info(`permission-rules: reloaded ${loaded.compiled.rules.length} rule(s) from ${loaded.sources.join(', ') || '(empty rule set)'} for ${cwd}`)
184
+ } catch (error: unknown) {
185
+ const message = error instanceof Error ? error.message : String(error)
186
+ this.ctx.logger.warn(`permission-rules: reload failed for ${cwd}: ${message} (keeping previous rules)`)
187
+ if (previous !== undefined) this.byCwd.set(cwd, { ...previous, lastError: message })
188
+ else this.byCwd.set(cwd, { cwd, sources: this.resolveSources(cwd), compiled: { rules: [], caseInsensitivePaths: this.config.caseInsensitivePaths }, lastError: message, failed: true })
189
+ }
190
+ }
191
+
192
+ /** The match context `when` conditions evaluate against. */
193
+ private matchContext(): MatchContext {
194
+ return { platform: process.platform, env: process.env }
195
+ }
196
+
197
+ /**
198
+ * The `tools/pre-execute` listener. A deny/ask hit returns the decision
199
+ * (first match wins, short-circuiting downstream listeners); an allow hit
200
+ * and a passthrough MUST delegate via `next()` so later listeners keep
201
+ * their say. Audit is appended once the final outcome is known, so the
202
+ * recorded `outcome` matches what the waterfall settled on.
203
+ * @param exec - the pending call (name, parsed arguments, caller agent).
204
+ * @param next - the downstream chain.
205
+ * @returns the pre-execute decision.
206
+ */
207
+ async preExecute(exec: ToolExecution, next: () => Promise<PreToolDecision>): Promise<PreToolDecision> {
208
+ const cwd = exec.agent?.session.header.cwd ?? process.cwd()
209
+ const loaded = this.rulesFor(cwd)
210
+ const hit = matchRules(loaded.compiled, exec.name, exec.arguments, cwd, this.matchContext())
211
+ if (hit === undefined || hit.rule.action === 'allow') {
212
+ const decision = await next()
213
+ this.audit(exec, loaded, hit, decision.kind)
214
+ return decision
215
+ }
216
+ const outcome: DecisionOutcome = hit.rule.action
217
+ this.audit(exec, loaded, hit, outcome)
218
+ if (outcome === 'deny') return { kind: 'deny', reason: hit.rule.reason }
219
+ return { kind: 'ask', reason: hit.rule.reason }
220
+ }
221
+
222
+ /**
223
+ * Append the log-only `permissionRules/decision` audit event for every
224
+ * decision (passthrough included unless `audit: 'hits'`), requesting the
225
+ * envelope's `ignorable: true` marker so any harness build can load the
226
+ * log (readers that do not know the type skip the audit record instead of
227
+ * refusing the session). `source` names the matched rule's file, or the
228
+ * nearest effective file on a passthrough. Agentless calls have no
229
+ * session to audit; append failures are contained so an audit hiccup can
230
+ * never change a permission decision.
231
+ * @param exec - the pending call.
232
+ * @param loaded - the rules in effect.
233
+ * @param hit - the first matching rule, or undefined for passthrough.
234
+ * @param outcome - the final pre-execute decision.
235
+ */
236
+ audit(exec: ToolExecution, loaded: LoadedRules, hit: RuleHit | undefined, outcome: DecisionOutcome): void {
237
+ if (this.config.audit === 'hits' && hit === undefined) return
238
+ const agent = exec.agent
239
+ if (agent === undefined) return
240
+ try {
241
+ ;(agent.session.append as unknown as AuditAppend)('permissionRules/decision', {
242
+ toolName: exec.name,
243
+ callId: exec.callId,
244
+ source: hit === undefined ? (loaded.sources[0] ?? '') : (loaded.sources[hit.rule.sourceIndex] ?? ''),
245
+ action: hit === undefined ? 'passthrough' : hit.rule.action,
246
+ outcome,
247
+ ...hit !== undefined ? { ruleIndex: hit.ruleIndex, reason: hit.rule.reason } : {},
248
+ }, { ignorable: true })
249
+ } catch (error: unknown) {
250
+ this.ctx.logger.warn(`permission-rules: audit append failed: ${String(error)}`)
251
+ }
252
+ }
253
+
254
+ /**
255
+ * Execute the `/rules` command: bare `/rules` lists the active rules and
256
+ * their sources; `/rules reload` re-reads the chain; `/rules decisions
257
+ * [n]` shows the session's audit trail; `/rules test <tool> <json>`
258
+ * dry-evaluates the rules against a hypothetical call. Command output
259
+ * stays in the UI — nothing here is injected into the model context.
260
+ * @param invocation - the received command invocation.
261
+ * @returns the command result shown to the user.
262
+ */
263
+ command(invocation: CommandInvocation): CommandResult {
264
+ const prose = UI_PROSE[this.config.language]
265
+ const raw = invocation.rawInput.trim()
266
+ const [verbRaw, ...rest] = raw.split(/\s+/)
267
+ const verb = (verbRaw ?? '').toLowerCase()
268
+ const cwd = invocation.agent.session.header.cwd ?? process.cwd()
269
+ if (verb === 'reload') {
270
+ if (rest.length > 0) return { kind: 'error', text: prose.unknownArg(invocation.rawInput.trim()) }
271
+ this.reload(cwd)
272
+ const reloaded = this.byCwd.get(cwd)
273
+ if (reloaded?.lastError !== undefined) return { kind: 'error', text: prose.reloadFailed(reloaded.lastError) }
274
+ const rules = reloaded?.compiled.rules ?? []
275
+ const source = reloaded === undefined || reloaded.sources.length === 0 ? prose.emptySource : reloaded.sources.join(', ')
276
+ return { kind: 'success', text: prose.reloaded(rules.length, source) }
277
+ }
278
+ if (verb === 'decisions') {
279
+ if (rest.length > 1) return { kind: 'error', text: prose.unknownArg(invocation.rawInput.trim()) }
280
+ let count = 10
281
+ if (rest.length === 1) {
282
+ const parsed = Number(rest[0])
283
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) return { kind: 'error', text: prose.invalidDecisionsCount(rest[0] as string) }
284
+ count = parsed
285
+ }
286
+ return this.decisionsCommand(invocation, count, prose)
287
+ }
288
+ if (verb === 'test') {
289
+ const verbText = verbRaw ?? ''
290
+ const restLine = raw.length > verbText.length ? raw.slice(verbText.length).trim() : ''
291
+ const match = /^(\S+)\s*(.*)$/s.exec(restLine)
292
+ const tool = match?.[1]
293
+ const jsonText = match?.[2] ?? ''
294
+ if (tool === undefined || tool.length === 0) return { kind: 'error', text: prose.testUsage }
295
+ let args: unknown
296
+ try {
297
+ args = jsonText.length > 0 ? JSON.parse(jsonText) : {}
298
+ } catch {
299
+ return { kind: 'error', text: prose.testBadJson(jsonText) }
300
+ }
301
+ let loaded: LoadedRules
302
+ try {
303
+ loaded = this.rulesFor(cwd)
304
+ } catch (error: unknown) {
305
+ return { kind: 'error', text: error instanceof Error ? error.message : String(error) }
306
+ }
307
+ const hit = matchRules(loaded.compiled, tool, args, cwd, this.matchContext())
308
+ return {
309
+ kind: 'success',
310
+ text: hit === undefined ? prose.testNoMatch(tool) : prose.testHit(tool, hit.ruleIndex, hit.rule.action, hit.rule.reason),
311
+ }
312
+ }
313
+ if (verb !== '') return { kind: 'error', text: prose.unknownArg(invocation.rawInput.trim()) }
314
+ let loaded: LoadedRules
315
+ try {
316
+ loaded = this.rulesFor(cwd)
317
+ } catch (error: unknown) {
318
+ return { kind: 'error', text: error instanceof Error ? error.message : String(error) }
319
+ }
320
+ const lines: string[] = []
321
+ if (loaded.sources.length === 0) {
322
+ lines.push(prose.noRules(cwd, this.config.fallbackPath !== undefined ? prose.fallbackMissing : ''))
323
+ } else {
324
+ lines.push(prose.rulesHeader(loaded.compiled.rules.length, loaded.sources, cwd))
325
+ lines.push(...loaded.compiled.rules.map(rule => describeRule(rule, DESCRIBE_TOKENS[this.config.language])))
326
+ const unreachable = findUnreachableRules(loaded.compiled)
327
+ if (unreachable.length > 0) lines.push(prose.unreachableWarning(unreachable.map(index => index + 1)))
328
+ }
329
+ if (loaded.lastError !== undefined) {
330
+ lines.push(prose.lastReloadWarning(loaded.lastError))
331
+ }
332
+ lines.push(prose.usage)
333
+ return { kind: 'success', text: lines.join('\n') }
334
+ }
335
+
336
+ /** Render the session's `permissionRules/decision` audit trail, newest last. */
337
+ private decisionsCommand(invocation: CommandInvocation, count: number, prose: UiProse): CommandResult {
338
+ const decisions = invocation.agent.session.events.filter(event => event.type === 'permissionRules/decision')
339
+ if (decisions.length === 0) return { kind: 'success', text: prose.noDecisions }
340
+ const shown = decisions.slice(-count)
341
+ const lines = [prose.decisionsHeader(shown.length, decisions.length)]
342
+ for (const event of shown) {
343
+ const data = event.data as AuditDecision
344
+ lines.push(prose.decisionLine(event.seq, data.action, data.toolName, data.ruleIndex, data.reason))
345
+ }
346
+ return { kind: 'success', text: lines.join('\n') }
347
+ }
348
+
349
+ /**
350
+ * Validate deployment-level file references at mount — the earliest
351
+ * resolvable point. An absolute `rulesFile` or a configured
352
+ * `fallbackPath` must exist and parse; a missing referent fails the mount
353
+ * loudly instead of silently degrading later.
354
+ * @throws when a mandated file is missing or invalid.
355
+ */
356
+ validateDeploymentFiles(): void {
357
+ if (isAbsolute(this.config.rulesFile)) {
358
+ this.loadForValidation(this.config.rulesFile)
359
+ }
360
+ if (this.config.fallbackPath !== undefined) {
361
+ const fallbackPath = isAbsolute(this.config.fallbackPath) ? this.config.fallbackPath : resolve(this.config.fallbackPath)
362
+ if (!existsSync(fallbackPath)) {
363
+ throw new RuleError(`permission-rules: fallbackPath ${JSON.stringify(this.config.fallbackPath)} does not exist`)
364
+ }
365
+ this.loadForValidation(fallbackPath)
366
+ }
367
+ }
368
+
369
+ /** Parse and compile one mandated file, rethrowing as a mount failure. */
370
+ private loadForValidation(filePath: string): void {
371
+ try {
372
+ const doc = parseRulesDocument(readFileSync(filePath, 'utf8'))
373
+ compileRules(doc, this.compileOptions())
374
+ } catch (error: unknown) {
375
+ const message = error instanceof Error ? error.message : String(error)
376
+ throw error instanceof RuleError ? error : new RuleError(`permission-rules: cannot load ${filePath}: ${message}`)
377
+ }
378
+ }
379
+
380
+ /** Attach (once per file path) the Chokidar watcher feeding {@link reload}. */
381
+ private attachWatch(cwd: string, source: string): void {
382
+ if (!this.config.watch || source === '') return
383
+ const existing = this.watchers.get(source)
384
+ if (existing !== undefined) {
385
+ existing.cwds.add(cwd)
386
+ return
387
+ }
388
+ const cwds = new Set([cwd])
389
+ const watcher = chokidar.watch(source, { persistent: true, ignoreInitial: true })
390
+ const onEvent = (): void => this.scheduleReload(source)
391
+ watcher.on('add', onEvent)
392
+ watcher.on('change', onEvent)
393
+ watcher.on('unlink', onEvent)
394
+ watcher.on('error', (error: unknown) => {
395
+ this.ctx.logger.warn(`permission-rules: watcher error on ${source}: ${String(error)}`)
396
+ })
397
+ this.watchers.set(source, {
398
+ cwds,
399
+ close: () => {
400
+ void watcher.close().catch((error: unknown) => {
401
+ this.ctx.logger.warn(`permission-rules: failed to close watcher on ${source}: ${String(error)}`)
402
+ })
403
+ },
404
+ })
405
+ this.ctx.effect(() => () => {
406
+ this.watchers.get(source)?.close()
407
+ this.watchers.delete(source)
408
+ const timer = this.timers.get(source)
409
+ if (timer !== undefined) {
410
+ clearTimeout(timer)
411
+ this.timers.delete(source)
412
+ }
413
+ })
414
+ }
415
+
416
+ /**
417
+ * Rebind `cwd` to its current rule-source chain. When a concrete source
418
+ * left the chain (deleted file, fallback switch), detach the workspace
419
+ * from watchers serving other sources and close the ones left empty, so
420
+ * long-running hosts cannot accumulate stale watchers. An empty chain (no
421
+ * rule file in effect) keeps the previous watchers alive: they own the
422
+ * "file recreated → adopted" signal, and the workspace-cache bound keeps
423
+ * the set of such watchers finite.
424
+ */
425
+ private reconcileWatch(cwd: string, sources: readonly string[]): void {
426
+ if (sources.length === 0) return
427
+ for (const [watchedSource, entry] of this.watchers) {
428
+ if (!sources.includes(watchedSource)) entry.cwds.delete(cwd)
429
+ }
430
+ this.pruneWatchers()
431
+ for (const source of sources) this.attachWatch(cwd, source)
432
+ }
433
+
434
+ /** Close and drop watchers whose workspace sets are empty, clearing their debounce timers. */
435
+ private pruneWatchers(): void {
436
+ for (const [source, entry] of this.watchers) {
437
+ if (entry.cwds.size > 0) continue
438
+ entry.close()
439
+ this.watchers.delete(source)
440
+ const timer = this.timers.get(source)
441
+ if (timer !== undefined) {
442
+ clearTimeout(timer)
443
+ this.timers.delete(source)
444
+ }
445
+ }
446
+ }
447
+
448
+ /**
449
+ * Bound the per-workspace cache: when a NEW workspace would exceed
450
+ * `maxCachedWorkspaces`, evict the least-recently-used entry (the Map
451
+ * head, refreshed by every {@link rulesFor} hit) and release its watcher
452
+ * slots. Long-lived hosts that visit many workspaces therefore keep a
453
+ * bounded memory footprint.
454
+ */
455
+ private evictIfFull(cwd: string): void {
456
+ if (this.byCwd.size < this.config.maxCachedWorkspaces || this.byCwd.has(cwd)) return
457
+ const oldest = this.byCwd.keys().next().value
458
+ if (oldest === undefined) return
459
+ this.byCwd.delete(oldest)
460
+ for (const entry of this.watchers.values()) entry.cwds.delete(oldest)
461
+ this.pruneWatchers()
462
+ }
463
+
464
+ /** Number of live watchers, for observability and tests. */
465
+ activeWatcherCount(): number {
466
+ return this.watchers.size
467
+ }
468
+
469
+ /** Number of pending debounce timers, for observability and tests. */
470
+ pendingReloadCount(): number {
471
+ return this.timers.size
472
+ }
473
+
474
+ /** Debounce watch events into one reload per stability window. */
475
+ private scheduleReload(source: string): void {
476
+ const existing = this.timers.get(source)
477
+ if (existing !== undefined) clearTimeout(existing)
478
+ const timer = setTimeout(() => {
479
+ this.timers.delete(source)
480
+ for (const cwd of this.watchers.get(source)?.cwds ?? []) this.reload(cwd)
481
+ }, this.config.watchStabilityThresholdMs)
482
+ this.timers.set(source, timer)
483
+ }
484
+ }
485
+
486
+ /**
487
+ * Mount the plugin: resolve config, validate deployment-level rule files,
488
+ * register the pre-execute listener and the `/rules` command.
489
+ * @param ctx - the host context.
490
+ * @param config - raw plugin config.
491
+ */
492
+ export function apply(ctx: Context, config: Config): void {
493
+ const resolved = resolveConfig(config)
494
+ const runtime = new PermissionRulesRuntime(ctx, resolved)
495
+ runtime.validateDeploymentFiles()
496
+ ctx.provide('permissionRulesRuntime', runtime)
497
+ ctx.on('tools/pre-execute', (exec, next) => runtime.preExecute(exec, next))
498
+ ctx.commands.register({
499
+ name: 'rules',
500
+ description: 'list, reload, audit, or dry-test the active permission rules for this workspace',
501
+ input: { hint: '[reload | decisions [n] | test <tool> <json-args>]' },
502
+ handler: invocation => runtime.command(invocation),
503
+ })
504
+ }