claude-code-session-manager 0.138.0 → 0.140.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/.claude-plugin/marketplace.json +1 -1
- package/README.md +352 -79
- package/dist/assets/AppSettings-CMFEM68R.js +2 -0
- package/dist/assets/History--JwsFnbn.js +2 -0
- package/dist/assets/HomeClaudeConfig-ijEXs--3.js +3 -0
- package/dist/assets/{Panel-CeDiyuNn.js → Panel-CALyU0pe.js} +1 -1
- package/dist/assets/ProjectClaudeConfig-sdlA-fUb.js +26 -0
- package/dist/assets/Scheduler-YT3j8SUa.js +16 -0
- package/dist/assets/{SkillReferenceGraph-CFMK8NJh.js → SkillReferenceGraph-CxAuwhNN.js} +1 -1
- package/dist/assets/Skills-DtRzghn5.js +67 -0
- package/dist/assets/{TiptapBody-D1kTj-tn.js → TiptapBody-DApeu7x8.js} +60 -54
- package/dist/assets/ViewTabs-B7qLXRAH.js +1 -0
- package/dist/assets/{VoiceButton-CZeyPM31.js → VoiceButton-DtStfv1H.js} +1 -1
- package/dist/assets/{historyTotals-B00l64Jw.js → historyTotals-ydfnwepc.js} +1 -1
- package/dist/assets/index-CtxruO1L.js +3121 -0
- package/dist/assets/{index-62tyjEQB.css → index-DKXdXfka.css} +1 -1
- package/dist/index.html +2 -2
- package/dist-web/app.css +1 -1
- package/dist-web/app.js +467 -451
- package/package.json +17 -6
- package/plugins/AGENTS.md +60 -0
- package/plugins/CLAUDE.md +1 -60
- package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
- package/plugins/session-manager-dev/skills/builder/SKILL.md +12 -4
- package/plugins/session-manager-dev/skills/builder/scripts/publish-preflight.cjs +255 -0
- package/plugins/session-manager-dev/skills/develop/SKILL.md +36 -22
- package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +5 -4
- package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +4 -2
- package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +16 -12
- package/plugins/session-manager-dev/skills/maintaining-md-network/migrate-to-agents-md.md +15 -0
- package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +50 -2
- package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +10 -10
- package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +117 -112
- package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdDuplicates.cjs +182 -0
- package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdLinks.cjs +340 -0
- package/scripts/README.md +2 -0
- package/scripts/hooks/guard-tool-risk.cjs +91 -0
- package/scripts/hooks/lib/guard-tool-risk-policy.cjs +217 -0
- package/scripts/ops-sweep.cjs +53 -23
- package/scripts/scheduler-mcp-server.cjs +360 -35
- package/src/main/build-info.json +4 -4
- package/src/main/chatRunner.cjs +2 -2
- package/src/main/config.cjs +112 -8
- package/src/main/docEdit.cjs +6 -1
- package/src/main/exchanges.cjs +70 -5
- package/src/main/files.cjs +7 -27
- package/src/main/health.cjs +48 -15
- package/src/main/historyAggregator.cjs +172 -63
- package/src/main/historyDashboard.cjs +87 -17
- package/src/main/index.cjs +78 -4
- package/src/main/ipcSchemas.cjs +233 -20
- package/src/main/lib/AGENTS.md +54 -0
- package/src/main/lib/CLAUDE.md +1 -54
- package/src/main/lib/agent-cli/adapters/codex.cjs +5 -2
- package/src/main/lib/agent-cli/agentCliIpc.cjs +18 -2
- package/src/main/lib/agent-cli/agentCliSessionStore.cjs +1 -0
- package/src/main/lib/agent-cli/agentCliTurn.cjs +20 -2
- package/src/main/lib/agent-cli/geminiContextDefaults.cjs +94 -0
- package/src/main/lib/claude/effectiveModelInfo.cjs +92 -22
- package/src/main/lib/claude/jobSandboxPolicy.cjs +202 -0
- package/src/main/lib/claude/modelPricing.cjs +148 -0
- package/src/main/lib/claude/personaToolScope.cjs +12 -6
- package/src/main/lib/claude/rateLimitDetect.cjs +13 -2
- package/src/main/lib/claude/runClaudeP.cjs +6 -1
- package/src/main/lib/claude/toolRiskIpc.cjs +177 -0
- package/src/main/lib/claude/toolRiskMarks.cjs +373 -0
- package/src/main/lib/demo-video-kit/seedKit.cjs +27 -6
- package/src/main/lib/ephemeralCwd.cjs +37 -2
- package/src/main/lib/epic/delegationReadiness.cjs +42 -9
- package/src/main/lib/epic/epicAdminRoutes.cjs +121 -0
- package/src/main/lib/epic/epicJobReceipt.cjs +87 -0
- package/src/main/lib/epic/epicOutsideRead.cjs +423 -0
- package/src/main/lib/epic/epicOutsideState.cjs +233 -0
- package/src/main/lib/epic/epicSettle.cjs +1 -1
- package/src/main/lib/epic/epicStateWatcher.cjs +157 -0
- package/src/main/lib/epic/epicSweepValidator.cjs +7 -2
- package/src/main/lib/epic/epicValidationHook.cjs +24 -4
- package/src/main/lib/epic/externalRef.cjs +37 -0
- package/src/main/lib/epic/externalRefIndex.cjs +136 -0
- package/src/main/lib/epic/guardSpawnSettings.cjs +57 -1
- package/src/main/lib/epic/restorableSessions.cjs +151 -17
- package/src/main/lib/epic/transcriptUsage.cjs +197 -0
- package/src/main/lib/externalContract.cjs +137 -0
- package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +176 -5
- package/src/main/lib/feedback-remote/crossProjectReply.cjs +186 -9
- package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -6
- package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +50 -8
- package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +218 -4
- package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +19 -3
- package/src/main/lib/feedback-remote/feedbackImages.cjs +171 -0
- package/src/main/lib/feedback-remote/localAdminHttp.cjs +11 -10
- package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +167 -21
- package/src/main/lib/feedback-remote/needsYouAdminRoutes.cjs +133 -0
- package/src/main/lib/feedback-remote/needsYouIpc.cjs +50 -0
- package/src/main/lib/feedback-remote/needsYouStore.cjs +285 -0
- package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +98 -1
- package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +5 -0
- package/src/main/lib/git/branchSweep.cjs +209 -4
- package/src/main/lib/git/gitWorktree.cjs +41 -5
- package/src/main/lib/guardShims.cjs +1 -1
- package/src/main/lib/historyRollup.cjs +58 -5
- package/src/main/lib/insideHome.cjs +27 -1
- package/src/main/lib/mcpToolCatalog.cjs +232 -25
- package/src/main/lib/mdDocCensus.cjs +59 -78
- package/src/main/lib/mdDocRefs.cjs +71 -93
- package/src/main/lib/mdNetworkScan.cjs +245 -250
- package/src/main/lib/mdReviewRecord.cjs +22 -9
- package/src/main/lib/memoryMdNetwork.cjs +5 -12
- package/src/main/lib/opsOwnership.cjs +18 -2
- package/src/main/lib/opsRetentionSettings.cjs +28 -4
- package/src/main/lib/persona-macro/agentAdminRoutes.cjs +121 -0
- package/src/main/lib/persona-macro/macroJobDispatch.cjs +90 -20
- package/src/main/lib/persona-macro/macroJobIpc.cjs +144 -46
- package/src/main/lib/persona-macro/macroJobStatus.cjs +87 -9
- package/src/main/lib/persona-macro/macroLibrary.cjs +95 -5
- package/src/main/lib/persona-macro/personaImportHealth.cjs +78 -17
- package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +96 -0
- package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
- package/src/main/lib/prd/depSlugResolve.cjs +104 -4
- package/src/main/lib/prd/prdAdminRoutes.cjs +35 -2
- package/src/main/lib/prd/prdCreate.cjs +351 -23
- package/src/main/lib/prd/prdDisposition.cjs +11 -2
- package/src/main/lib/prd/prdFrontmatter.cjs +96 -3
- package/src/main/lib/process/loginItem.cjs +171 -0
- package/src/main/lib/process/loginItemPlan.cjs +193 -0
- package/src/main/lib/project-pages/playerBridge.cjs +4 -0
- package/src/main/lib/project-pages/videoReview.cjs +268 -0
- package/src/main/lib/project-pages/videoReviewIpc.cjs +229 -0
- package/src/main/lib/promptSessionSchema.cjs +4 -0
- package/src/main/lib/remoteTranscriptTail.cjs +32 -1
- package/src/main/lib/scheduler/cpuSample.cjs +131 -4
- package/src/main/lib/scheduler/fixPlanSlug.cjs +4 -3
- package/src/main/lib/scheduler/loadGate.cjs +24 -6
- package/src/main/lib/scheduler/planRecordHarvest.cjs +108 -0
- package/src/main/lib/scheduler/planRecordRetention.cjs +144 -0
- package/src/main/lib/scheduler/queueStore.cjs +7 -0
- package/src/main/lib/scheduler/rcaReport.cjs +21 -1
- package/src/main/lib/scheduler/reaperHelpers.cjs +35 -5
- package/src/main/lib/scheduler/runLogRetention.cjs +104 -3
- package/src/main/lib/scheduler/scheduleJobSchema.cjs +3 -0
- package/src/main/lib/scheduler/schedulerBatch.cjs +25 -48
- package/src/main/lib/scheduler/schedulerPaths.cjs +12 -0
- package/src/main/lib/scheduler/sessionSlots.cjs +176 -21
- package/src/main/lib/scheduler/validationQuality.cjs +282 -0
- package/src/main/lib/scheduler/validatorVerdictSchema.cjs +254 -0
- package/src/main/lib/tasks/taskAdminRoutes.cjs +641 -0
- package/src/main/lib/tasks/taskIpc.cjs +80 -0
- package/src/main/lib/tasks/taskLedger.cjs +502 -0
- package/src/main/lib/tasks/taskRun.cjs +313 -0
- package/src/main/lib/tasks/taskSwitch.cjs +120 -0
- package/src/main/lib/telemetry/auditEvents.cjs +176 -0
- package/src/main/lib/telemetry/eventsAdminRoutes.cjs +45 -0
- package/src/main/loginItemIpc.cjs +35 -0
- package/src/main/loopEfficiencyHandlers.cjs +11 -2
- package/src/main/projectPages.cjs +6 -15
- package/src/main/promptSessionEvents.cjs +9 -1
- package/src/main/queueOps.cjs +260 -3
- package/src/main/runVerify.cjs +53 -25
- package/src/main/scheduler/AGENTS.md +26 -0
- package/src/main/scheduler/CLAUDE.md +1 -26
- package/src/main/scheduler/budget.cjs +239 -9
- package/src/main/scheduler/cancelDependents.cjs +154 -0
- package/src/main/scheduler/prdParser.cjs +4 -1
- package/src/main/scheduler/starvation.cjs +20 -18
- package/src/main/scheduler.cjs +774 -64
- package/src/main/supervisor.cjs +5 -1
- package/src/main/templates/PRD_AUTHORING.md +7 -1
- package/src/main/transcripts.cjs +62 -7
- package/src/main/validationQualityHandlers.cjs +199 -0
- package/src/main/webRemote.cjs +132 -20
- package/src/preload/api.d.ts +434 -28
- package/src/preload/apiSurface.cjs +7 -0
- package/src/preload/apiSurface.json +485 -81
- package/src/preload/index.cjs +38 -5
- package/src/seed/agents/validator.md +19 -8
- package/dist/assets/AgentLibrary-C1d_D7uQ.js +0 -2
- package/dist/assets/AppSettings-CgDhqrsU.js +0 -2
- package/dist/assets/Button-Bk23rEnZ.js +0 -1
- package/dist/assets/DocumentEditorPane-BqY5Nq6W.js +0 -1
- package/dist/assets/Extensions-CXem-uwI.js +0 -2
- package/dist/assets/History-BwO3coo4.js +0 -2
- package/dist/assets/Library-BDV69fSe.js +0 -32
- package/dist/assets/ListDetail-CD-Fm6mh.js +0 -1
- package/dist/assets/ProjectClaudeConfig-NjdKdwe8.js +0 -25
- package/dist/assets/ProvenanceBadge-Bu8NmI_R.js +0 -1
- package/dist/assets/Scheduler-CkhTvG7C.js +0 -16
- package/dist/assets/Settings-COT34hBF.js +0 -2
- package/dist/assets/Skills-BgexoUkQ.js +0 -29
- package/dist/assets/SourceChip-BXjcdeb1.js +0 -1
- package/dist/assets/SystemPrompt-CeeH3EeW.js +0 -1
- package/dist/assets/Toggle-CENi19iK.js +0 -1
- package/dist/assets/ViewTabs-DDBb0x96.js +0 -1
- package/dist/assets/claude-settings-schema-COigsajx.js +0 -3
- package/dist/assets/index-CgCxpunJ.js +0 -3116
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* mdLinks.cjs — the single definition of the markdown link convention named in
|
|
6
|
+
* the maintaining-md-network SKILL.md section "What counts as a link": inline
|
|
7
|
+
* `[text](target)` links (images too) and `<target.md>` autolinks, `@path.md`
|
|
8
|
+
* imports and backticked repo paths — all outside code fences and HTML
|
|
9
|
+
* comments (links and imports also outside inline code).
|
|
10
|
+
*
|
|
11
|
+
* The app requires this file from src/main, and the skill's own scripts require
|
|
12
|
+
* it too, so it MUST stay dependency-free: node built-ins only.
|
|
13
|
+
*
|
|
14
|
+
* - linksOf(file) — a doc's followed links, in document order (memoized per file object).
|
|
15
|
+
* - rawLinksOf(text) — every link destination as written, before followLink's filters
|
|
16
|
+
* (for checkers that judge `/rooted` or `#fragment` targets themselves).
|
|
17
|
+
* - followLink(from, raw, line) — one raw link target -> followed link, or null when ignored.
|
|
18
|
+
* - visibleText(line, state) — the part of one line that can hold links.
|
|
19
|
+
* - visibleLine(line, state) — one line outside fences, HTML comments removed, inline code kept.
|
|
20
|
+
* - importsOf(text, fromPath) — the `@path.md` imports a doc makes, resolved against its folder.
|
|
21
|
+
* - backtickPaths(text) — the path-shaped inline-code tokens a doc names.
|
|
22
|
+
* - toRepoPath(p) — repo-relative POSIX form.
|
|
23
|
+
*
|
|
24
|
+
* For links, ignored: any `scheme:` target, `/absolute` and `//host` targets, and
|
|
25
|
+
* `#anchor`-only links; `#fragment` and `?query` are stripped and the rest
|
|
26
|
+
* resolves against the linking doc's folder.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
const path = require('node:path');
|
|
30
|
+
|
|
31
|
+
/** Longest link destination or title scanned, so a pathological line stays linear. */
|
|
32
|
+
const MAX_LINK_CHARS = 1024;
|
|
33
|
+
/** Most backticked path tokens returned per doc. */
|
|
34
|
+
const MAX_TOKENS = 200;
|
|
35
|
+
|
|
36
|
+
const MD_RE = /\.md$/i;
|
|
37
|
+
const SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;
|
|
38
|
+
const FENCE_RE = /^\s*(`{3,}|~{3,})(.*)$/;
|
|
39
|
+
const INLINE_CODE_RE = /(`+).{0,1024}?\1/g;
|
|
40
|
+
const INLINE_CODE_TOKEN_RE = /(`+)(.{0,1024}?)\1/g;
|
|
41
|
+
const AUTOLINK_RE = /<([^<>\s]{1,1024})>/g;
|
|
42
|
+
const IMPORT_RE = /(^|\s)@(\S+)/g;
|
|
43
|
+
const TRAILING_PUNCT_RE = /[),.;:!?'"\]]+$/;
|
|
44
|
+
const BAD_START_RE = /^(?:[/~$<]|http)/i;
|
|
45
|
+
const BAD_CHAR_RE = /[*{}<>:]/;
|
|
46
|
+
const EXT_RE = /\.[A-Za-z0-9]{1,8}$/;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* @typedef {{ path: string, text: string }} MdFile a doc: repo-relative POSIX path + text
|
|
50
|
+
* @typedef {{ line: number, target: string, to: string, escapes: boolean }} MdLink
|
|
51
|
+
* `target` as written (fragment/query stripped); `to` resolved repo-relative
|
|
52
|
+
* @typedef {{ fence: string, inComment: boolean }} LineState an open code fence / HTML comment
|
|
53
|
+
*/
|
|
54
|
+
|
|
55
|
+
/** Repo-relative POSIX form: no `./` or trailing `/`; `.` is the root folder. @param {string} p */
|
|
56
|
+
function toRepoPath(p) {
|
|
57
|
+
return path.posix.normalize(p).replace(/\/+$/, '') || '.';
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** @param {string} s @param {number} i @returns {number} the first index at or after `i` that is not a space/tab */
|
|
61
|
+
function skipBlanks(s, i) {
|
|
62
|
+
while (s[i] === ' ' || s[i] === '\t') i += 1;
|
|
63
|
+
return i;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** @param {string} s @param {string} ch @param {number} from @returns {number} `ch`'s index within MAX_LINK_CHARS, or -1 */
|
|
67
|
+
function indexWithin(s, ch, from) {
|
|
68
|
+
const i = s.slice(from, from + MAX_LINK_CHARS).indexOf(ch);
|
|
69
|
+
return i === -1 ? -1 : from + i;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Parses an inline link's destination (+ optional title) starting just after `](`.
|
|
74
|
+
* @param {string} s
|
|
75
|
+
* @param {number} start
|
|
76
|
+
* @returns {{ target: string, end: number } | null} the raw target and the index after `)`
|
|
77
|
+
*/
|
|
78
|
+
function parseDestination(s, start) {
|
|
79
|
+
let j = skipBlanks(s, start);
|
|
80
|
+
let target;
|
|
81
|
+
if (s[j] === '<') {
|
|
82
|
+
const close = indexWithin(s, '>', j + 1);
|
|
83
|
+
if (close === -1) return null;
|
|
84
|
+
target = s.slice(j + 1, close);
|
|
85
|
+
j = close + 1;
|
|
86
|
+
} else {
|
|
87
|
+
const from = j;
|
|
88
|
+
const limit = Math.min(s.length, from + MAX_LINK_CHARS);
|
|
89
|
+
let depth = 0;
|
|
90
|
+
for (; j < limit; j += 1) {
|
|
91
|
+
const c = s[j];
|
|
92
|
+
if (c === ' ' || c === '\t') break;
|
|
93
|
+
if (c === '(') depth += 1;
|
|
94
|
+
else if (c === ')') {
|
|
95
|
+
if (depth === 0) break;
|
|
96
|
+
depth -= 1;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
if (j === limit && j < s.length) return null;
|
|
100
|
+
target = s.slice(from, j);
|
|
101
|
+
}
|
|
102
|
+
j = skipBlanks(s, j);
|
|
103
|
+
const quote = s[j];
|
|
104
|
+
if (quote === '"' || quote === "'" || quote === '(') {
|
|
105
|
+
const close = indexWithin(s, quote === '(' ? ')' : quote, j + 1);
|
|
106
|
+
if (close === -1) return null;
|
|
107
|
+
j = skipBlanks(s, close + 1);
|
|
108
|
+
}
|
|
109
|
+
return s[j] === ')' ? { target, end: j + 1 } : null;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Raw targets of one line's inline links, then of its `<x.md>` autolinks. @param {string} s @returns {string[]} */
|
|
113
|
+
function lineTargets(s) {
|
|
114
|
+
/** @type {string[]} */
|
|
115
|
+
const targets = [];
|
|
116
|
+
let outside = ''; // the line minus its inline links, so `[x](<a.md>)` is not also an autolink
|
|
117
|
+
let last = 0;
|
|
118
|
+
for (let i = s.indexOf(']('); i !== -1; ) {
|
|
119
|
+
const dest = parseDestination(s, i + 2);
|
|
120
|
+
if (dest) {
|
|
121
|
+
targets.push(dest.target);
|
|
122
|
+
outside += `${s.slice(last, i)} `;
|
|
123
|
+
last = dest.end;
|
|
124
|
+
i = s.indexOf('](', dest.end);
|
|
125
|
+
} else {
|
|
126
|
+
i = s.indexOf('](', i + 2);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
outside += s.slice(last);
|
|
130
|
+
for (const m of outside.matchAll(AUTOLINK_RE)) {
|
|
131
|
+
if (MD_RE.test(m[1].replace(/[?#].*$/, ''))) targets.push(m[1]);
|
|
132
|
+
}
|
|
133
|
+
return targets;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Drops HTML comments (which may span lines) from one line. The one copy shared
|
|
138
|
+
* by visibleText (links) and visibleLine (backticked paths).
|
|
139
|
+
* @param {string} line @param {LineState} state
|
|
140
|
+
*/
|
|
141
|
+
function stripComments(line, state) {
|
|
142
|
+
let out = '';
|
|
143
|
+
let i = 0;
|
|
144
|
+
while (i < line.length) {
|
|
145
|
+
if (state.inComment) {
|
|
146
|
+
const close = line.indexOf('-->', i);
|
|
147
|
+
if (close === -1) return out;
|
|
148
|
+
state.inComment = false;
|
|
149
|
+
i = close + 3;
|
|
150
|
+
} else {
|
|
151
|
+
const open = line.indexOf('<!--', i);
|
|
152
|
+
if (open === -1) return out + line.slice(i);
|
|
153
|
+
out += `${line.slice(i, open)} `;
|
|
154
|
+
state.inComment = true;
|
|
155
|
+
i = open + 4;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return out;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Advances fence state for one line. @param {string} line @param {LineState} state
|
|
163
|
+
* @returns {boolean} true when the line is a fence line or inside a fence (nothing visible)
|
|
164
|
+
*/
|
|
165
|
+
function fenced(line, state) {
|
|
166
|
+
const fence = state.inComment ? null : FENCE_RE.exec(line);
|
|
167
|
+
if (state.fence) {
|
|
168
|
+
if (fence && fence[1][0] === state.fence[0] && fence[1].length >= state.fence.length && fence[2].trim() === '') {
|
|
169
|
+
state.fence = '';
|
|
170
|
+
}
|
|
171
|
+
return true;
|
|
172
|
+
}
|
|
173
|
+
if (fence && !(fence[1][0] === '`' && fence[2].includes('`'))) {
|
|
174
|
+
state.fence = fence[1];
|
|
175
|
+
return true;
|
|
176
|
+
}
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** The part of one line that can hold links. @param {string} line @param {LineState} state @returns {string} */
|
|
181
|
+
function visibleText(line, state) {
|
|
182
|
+
if (fenced(line, state)) return '';
|
|
183
|
+
return stripComments(line.replace(INLINE_CODE_RE, ' '), state);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** One line outside fences, comments removed (inline code kept). @param {string} line @param {LineState} state */
|
|
187
|
+
function visibleLine(line, state) {
|
|
188
|
+
if (fenced(line, state)) return '';
|
|
189
|
+
return stripComments(line, state);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* The followed link for one raw target written in doc `from`, or null when ignored.
|
|
194
|
+
* @param {string} from @param {string} raw @param {number} line 1-based
|
|
195
|
+
* @returns {MdLink | null}
|
|
196
|
+
*/
|
|
197
|
+
function followLink(from, raw, line) {
|
|
198
|
+
const written = raw.trim();
|
|
199
|
+
if (written === '' || written[0] === '#' || written[0] === '/' || SCHEME_RE.test(written)) return null;
|
|
200
|
+
const target = written.replace(/[?#].*$/, '');
|
|
201
|
+
if (target === '') return null;
|
|
202
|
+
let decoded = target;
|
|
203
|
+
try {
|
|
204
|
+
decoded = decodeURIComponent(target);
|
|
205
|
+
} catch {
|
|
206
|
+
// a stray `%` is part of the file name
|
|
207
|
+
}
|
|
208
|
+
const to = toRepoPath(path.posix.join(path.posix.dirname(from), decoded));
|
|
209
|
+
return { line, target, to, escapes: to === '..' || to.startsWith('../') };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Memo for linksOf: callers may walk the docs more than once, so each doc is
|
|
214
|
+
* parsed once. File objects are treated as immutable.
|
|
215
|
+
* @type {WeakMap<MdFile, MdLink[]>}
|
|
216
|
+
*/
|
|
217
|
+
const linkMemo = new WeakMap();
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Every inline / image / `<x.md>` autolink destination outside code and HTML
|
|
221
|
+
* comments, as written (fragment, query, scheme and leading `/` kept), in document order.
|
|
222
|
+
* @param {string} text @returns {{ line: number, raw: string }[]} line is 1-based
|
|
223
|
+
*/
|
|
224
|
+
function rawLinksOf(text) {
|
|
225
|
+
/** @type {{ line: number, raw: string }[]} */
|
|
226
|
+
const out = [];
|
|
227
|
+
if (typeof text !== 'string') return out;
|
|
228
|
+
/** @type {LineState} */
|
|
229
|
+
const state = { fence: '', inComment: false };
|
|
230
|
+
const lines = text.split(/\r?\n/);
|
|
231
|
+
for (let n = 0; n < lines.length; n += 1) {
|
|
232
|
+
const visible = visibleText(lines[n], state);
|
|
233
|
+
if (visible === '') continue;
|
|
234
|
+
for (const raw of lineTargets(visible)) out.push({ line: n + 1, raw });
|
|
235
|
+
}
|
|
236
|
+
return out;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** A doc's followed links, in document order. @param {MdFile} file @returns {MdLink[]} */
|
|
240
|
+
function linksOf(file) {
|
|
241
|
+
const memo = linkMemo.get(file);
|
|
242
|
+
if (memo) return memo;
|
|
243
|
+
const from = toRepoPath(file.path);
|
|
244
|
+
/** @type {MdLink[]} */
|
|
245
|
+
const links = [];
|
|
246
|
+
for (const { line, raw } of rawLinksOf(file.text)) {
|
|
247
|
+
const link = followLink(from, raw, line);
|
|
248
|
+
if (link) links.push(link);
|
|
249
|
+
}
|
|
250
|
+
linkMemo.set(file, links);
|
|
251
|
+
return links;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* The `@path.md` imports in `text`, outside fenced and inline code, resolved
|
|
256
|
+
* against `fromPath`'s folder. Skips `@~/...`, absolute and escaping targets.
|
|
257
|
+
* (HTML comments are not stripped here — as in mdDocCensus.cjs importsOf.)
|
|
258
|
+
* @param {string} text @param {string} fromPath @returns {string[]}
|
|
259
|
+
*/
|
|
260
|
+
function importsOf(text, fromPath) {
|
|
261
|
+
if (typeof text !== 'string' || typeof fromPath !== 'string') return [];
|
|
262
|
+
const dir = path.posix.dirname(fromPath);
|
|
263
|
+
/** @type {string[]} */
|
|
264
|
+
const out = [];
|
|
265
|
+
const seen = new Set();
|
|
266
|
+
let fence = '';
|
|
267
|
+
for (const line of text.split(/\r?\n/)) {
|
|
268
|
+
const f = FENCE_RE.exec(line);
|
|
269
|
+
if (fence) {
|
|
270
|
+
if (f && f[1][0] === fence[0] && f[1].length >= fence.length && f[2].trim() === '') fence = '';
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
if (f && !(f[1][0] === '`' && f[2].includes('`'))) {
|
|
274
|
+
fence = f[1];
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
const visible = line.replace(INLINE_CODE_RE, ' ');
|
|
278
|
+
for (const m of visible.matchAll(IMPORT_RE)) {
|
|
279
|
+
const target = m[2].replace(TRAILING_PUNCT_RE, '');
|
|
280
|
+
if (!MD_RE.test(target) || target.startsWith('~') || target.startsWith('/')) continue;
|
|
281
|
+
const resolved = path.posix.normalize(path.posix.join(dir, target));
|
|
282
|
+
if (resolved === '..' || resolved.startsWith('../') || resolved.startsWith('/')) continue;
|
|
283
|
+
if (seen.has(resolved)) continue;
|
|
284
|
+
seen.add(resolved);
|
|
285
|
+
out.push(resolved);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return out;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** The repo-path form of one inline-code token, or null. @param {string} raw @returns {string | null} */
|
|
292
|
+
function pathToken(raw) {
|
|
293
|
+
const t = raw.trim();
|
|
294
|
+
if (t === '' || !t.includes('/') || /\s/.test(t) || BAD_START_RE.test(t)) return null;
|
|
295
|
+
const bare = t.replace(/:\d+$/, '').replace(/#.*$/, '');
|
|
296
|
+
if (bare === '' || BAD_CHAR_RE.test(bare)) return null;
|
|
297
|
+
if (!bare.endsWith('/') && !EXT_RE.test(bare)) return null;
|
|
298
|
+
return bare;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Distinct path-shaped inline-code tokens outside fenced code and HTML comments,
|
|
303
|
+
* in document order, at most MAX_TOKENS. O(text length).
|
|
304
|
+
* @param {string} text
|
|
305
|
+
* @returns {string[]}
|
|
306
|
+
*/
|
|
307
|
+
function backtickPaths(text) {
|
|
308
|
+
if (typeof text !== 'string' || text === '') return [];
|
|
309
|
+
/** @type {LineState} */
|
|
310
|
+
const state = { fence: '', inComment: false };
|
|
311
|
+
const seen = new Set();
|
|
312
|
+
/** @type {string[]} */
|
|
313
|
+
const out = [];
|
|
314
|
+
for (const line of text.split(/\r?\n/)) {
|
|
315
|
+
const visible = visibleLine(line, state);
|
|
316
|
+
if (visible === '' || !visible.includes('`')) continue;
|
|
317
|
+
for (const m of visible.matchAll(INLINE_CODE_TOKEN_RE)) {
|
|
318
|
+
const tok = pathToken(m[2]);
|
|
319
|
+
if (tok === null || seen.has(tok)) continue;
|
|
320
|
+
seen.add(tok);
|
|
321
|
+
out.push(tok);
|
|
322
|
+
if (out.length >= MAX_TOKENS) return out;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
return out;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* True when the doc's first non-blank line is the `@AGENTS.md` (or `@./AGENTS.md`) import —
|
|
330
|
+
* a CLAUDE.md stub that hands its folder's notes to the AGENTS.md beside it.
|
|
331
|
+
* @param {string} text
|
|
332
|
+
* @returns {boolean}
|
|
333
|
+
*/
|
|
334
|
+
function isAgentsStub(text) {
|
|
335
|
+
if (typeof text !== 'string') return false;
|
|
336
|
+
const first = text.split(/\r?\n/).find((l) => l.trim() !== '');
|
|
337
|
+
return first !== undefined && /^@(\.\/)?AGENTS\.md$/.test(first.trim());
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
module.exports = { linksOf, rawLinksOf, followLink, visibleText, visibleLine, importsOf, backtickPaths, toRepoPath, isAgentsStub };
|
package/scripts/README.md
CHANGED
|
@@ -17,6 +17,7 @@ scripts/lib was moved into src/main/lib (2026-09); nothing under src/ may requir
|
|
|
17
17
|
| check-conditional-hooks.cjs | `npm run lint:hooks` (in `lint`) | no |
|
|
18
18
|
| check-epic-transcripts.cjs | manual read-only diagnostic (`--json`); also surfaced as a non-fatal warning in `npm run health` | no |
|
|
19
19
|
| check-doc-hierarchy.cjs | `npm run lint:docs` (in `lint`) | no |
|
|
20
|
+
| check-readme.cjs | `npm run readme:build` (`--write`) fills the README's generated regions; `npm run lint:readme` checks the README (run by `lint` and `prepublishOnly`) | no |
|
|
20
21
|
| check-explicit-any.cjs | `npm run lint:any` (in `lint`) — bans explicit `any`/`@ts-ignore` in renderer+preload; per-line `// lint-allow-any: <reason>` | no |
|
|
21
22
|
| check-main-ts-check.cjs | `npm run lint:main-ts-check` (in `lint`) — `tsconfig.main.json` `include` ⇔ `// @ts-check` first line, both directions; explicit list only, `checkJs` false | no |
|
|
22
23
|
| check-renderer-storage.cjs | `npm run lint:renderer-storage` (in `lint`) — ratchet-bans `localStorage.`/`sessionStorage.` in `src/renderer` outside an explicit ALLOWLIST (Epic stateless-ui-review) | no |
|
|
@@ -26,6 +27,7 @@ scripts/lib was moved into src/main/lib (2026-09); nothing under src/ may requir
|
|
|
26
27
|
| install-scheduler-mcp-user-scope.sh | manual (`seedSchedulerMcp.cjs` does the same on first boot, or on the next boot after its marker file is deleted) | no |
|
|
27
28
|
| install-scheduler-watchdog.sh | manual; installs the systemd user timer (cron fallback) | no |
|
|
28
29
|
| move-modules.cjs | manual; `node scripts/move-modules.cjs <mapping.json> [root] [--dry-run]` — idempotent codemod that git-mvs `src/main/lib` modules (+ their tests) into subfolders and rewrites every relative require and `lib/<m>.cjs` path string | no |
|
|
30
|
+
| job-sandbox-probe.cjs | `npm run probe:job-sandbox` (manual, dev-only; never in a gate) — one pinned-haiku `claude -p` per sandbox profile against a fake home with canaries; each profile gets a private `/tmp/smj-*` tmpDir + `sandboxChildEnv`, and writes to `$HOME` and a sibling `/tmp` dir count as escapes; exit 1 on any escape, 2 = SKIP (deps missing); `--dry-run` prints the settings (with each tmpDir) and spawns nothing; `--fetch-socat` (Linux, socat missing) unpacks the distro's socat .deb into temp dirs via `apt-get download` + `dpkg-deb -x` and puts it on PATH for that run only — never installs, no sudo. The live probe cannot run inside an os-sandbox job (nested user namespaces are refused) | no |
|
|
29
31
|
| mint-epic.cjs | manual; joins an existing Epic and prints its prds dir | yes |
|
|
30
32
|
| ops-sweep.cjs | manual; `node scripts/ops-sweep.cjs <cwd>` | yes |
|
|
31
33
|
| postinstall.cjs | npm `postinstall` | yes |
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* guard-tool-risk.cjs — PreToolUse hook that refuses a Bash or MCP call whose
|
|
4
|
+
* resolved risk mark is `irreversible`, `money` or `public` inside a headless
|
|
5
|
+
* scheduler job, unless the job's PRD clears it.
|
|
6
|
+
*
|
|
7
|
+
* Marks live in two Claude config layers, read and matched only through
|
|
8
|
+
* src/main/lib/claude/toolRiskMarks.cjs:
|
|
9
|
+
* System = ~/.claude/tool-risk.json
|
|
10
|
+
* Project = <SM_PROJECT_ROOT>/.claude/tool-risk.json (the main checkout —
|
|
11
|
+
* never payload.cwd, which in a job is a worktree it can rewrite)
|
|
12
|
+
* A matching Project rule beats every System rule.
|
|
13
|
+
*
|
|
14
|
+
* Why a hook and not a prompt: a sentence in a job's prompt saying "don't
|
|
15
|
+
* publish" is advice the model can talk itself past; PRD 460/479/1204 (see
|
|
16
|
+
* guard-self-schedule.cjs) showed prose rules fail in headless runs. A
|
|
17
|
+
* PreToolUse hook sits outside the model and refuses the call before it runs
|
|
18
|
+
* — verified on CLI 2.1.325 to block both Bash and MCP calls even under
|
|
19
|
+
* --dangerously-skip-permissions, with permissionDecisionReason reaching the
|
|
20
|
+
* model verbatim.
|
|
21
|
+
*
|
|
22
|
+
* ── Scope ────────────────────────────────────────────────────────────────
|
|
23
|
+
* - Headless (env SM_SCHEDULER_JOB_SLUG, or SM_TOOL_RISK_HEADLESS=1): a
|
|
24
|
+
* blocking mark is denied unless an entry of the JSON array in
|
|
25
|
+
* SM_SCHEDULER_JOB_RISK_TOOLS (the PRD's riskTools) matches the call.
|
|
26
|
+
* A marks file that exists but is invalid denies every Bash/MCP call (fail
|
|
27
|
+
* closed). Write/Edit/NotebookEdit of any tool-risk.json is denied — marks
|
|
28
|
+
* are human-owned and edited in Settings.
|
|
29
|
+
* - Interactive: inert, unless the Project layer sets `interactive: true`;
|
|
30
|
+
* then a blocking mark is denied in a Chat turn (SM_CHAT_SESSION_ID set —
|
|
31
|
+
* a -p turn has no approval surface, and the CLI turns 'ask' into a generic
|
|
32
|
+
* auto-deny) and answered with 'ask' in a Terminal session.
|
|
33
|
+
* - Any other internal error fails open with a stderr line, like
|
|
34
|
+
* guard-self-schedule.cjs.
|
|
35
|
+
*
|
|
36
|
+
* ── Install ──────────────────────────────────────────────────────────────
|
|
37
|
+
* Listed in guardShims.cjs's GUARD_NAMES, so it gets a stable shim at
|
|
38
|
+
* ~/.claude/session-manager/hooks/guard-tool-risk.cjs. It is NOT a New Epic
|
|
39
|
+
* readiness item: the scheduler injects it into job spawns. To run it by hand:
|
|
40
|
+
*
|
|
41
|
+
* {
|
|
42
|
+
* "hooks": {
|
|
43
|
+
* "PreToolUse": [
|
|
44
|
+
* {
|
|
45
|
+
* "matcher": "Bash|mcp__.*|Write|Edit|MultiEdit|NotebookEdit",
|
|
46
|
+
* "hooks": [
|
|
47
|
+
* { "type": "command", "command": "node ~/.claude/session-manager/hooks/guard-tool-risk.cjs" }
|
|
48
|
+
* ]
|
|
49
|
+
* }
|
|
50
|
+
* ]
|
|
51
|
+
* }
|
|
52
|
+
* }
|
|
53
|
+
*
|
|
54
|
+
* ── Contract ─────────────────────────────────────────────────────────────
|
|
55
|
+
* Reads a PreToolUse payload on stdin ({ tool_name, tool_input, cwd, ... })
|
|
56
|
+
* and writes one hook-response JSON object on stdout; always exits 0.
|
|
57
|
+
* Decision logic: scripts/hooks/lib/guard-tool-risk-policy.cjs.
|
|
58
|
+
*/
|
|
59
|
+
'use strict';
|
|
60
|
+
|
|
61
|
+
const { decide, parsePayload } = require('./lib/guard-tool-risk-policy.cjs');
|
|
62
|
+
|
|
63
|
+
function readStdin() {
|
|
64
|
+
return new Promise((resolve) => {
|
|
65
|
+
let data = '';
|
|
66
|
+
process.stdin.setEncoding('utf8');
|
|
67
|
+
process.stdin.on('data', (chunk) => { data += chunk; });
|
|
68
|
+
process.stdin.on('end', () => resolve(data));
|
|
69
|
+
// Fail open if stdin never closes/errors for some reason.
|
|
70
|
+
process.stdin.on('error', () => resolve(data));
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function emit(result) {
|
|
75
|
+
process.stdout.write(JSON.stringify(result));
|
|
76
|
+
process.exit(0);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function main() {
|
|
80
|
+
const raw = await readStdin();
|
|
81
|
+
return emit(decide(parsePayload(raw), process.env));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Runs as a require-time side effect, NOT gated on `require.main === module`
|
|
85
|
+
// — see src/main/lib/guardShims.cjs's header: the installed shim invokes this
|
|
86
|
+
// script via a plain `require()`, so gating on `require.main` would silently
|
|
87
|
+
// stop the shim from ever running the guard.
|
|
88
|
+
main().catch((e) => {
|
|
89
|
+
console.error(`[guard-tool-risk] unhandled error, failing open: ${e?.message}`);
|
|
90
|
+
emit({ continue: true });
|
|
91
|
+
});
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* guard-tool-risk-policy.cjs — decision logic for
|
|
3
|
+
* scripts/hooks/guard-tool-risk.cjs, split out so it can be `require()`d
|
|
4
|
+
* in-process (by tests) with no CLI-level side effects.
|
|
5
|
+
*
|
|
6
|
+
* `decide(payload, env, deps)` reads the System marks layer from
|
|
7
|
+
* `deps.homeDir || os.homedir()` and the Project layer ONLY from
|
|
8
|
+
* `env.SM_PROJECT_ROOT` (the main checkout) — never `payload.cwd`, which in a
|
|
9
|
+
* job is a disposable worktree the job itself can rewrite. All mark parsing,
|
|
10
|
+
* matching and precedence lives in src/main/lib/claude/toolRiskMarks.cjs;
|
|
11
|
+
* this module only applies the enforcement policy on top of it.
|
|
12
|
+
*/
|
|
13
|
+
'use strict';
|
|
14
|
+
|
|
15
|
+
const os = require('node:os');
|
|
16
|
+
const path = require('node:path');
|
|
17
|
+
const {
|
|
18
|
+
BLOCKING_MARKS,
|
|
19
|
+
systemMarksPath,
|
|
20
|
+
projectMarksPath,
|
|
21
|
+
parseRule,
|
|
22
|
+
ruleMatches,
|
|
23
|
+
readMarksLayer,
|
|
24
|
+
resolveMark,
|
|
25
|
+
} = require('../../../src/main/lib/claude/toolRiskMarks.cjs');
|
|
26
|
+
|
|
27
|
+
const TAG = '[guard-tool-risk]';
|
|
28
|
+
const WRITE_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit']);
|
|
29
|
+
const MAX_SHOWN = 200;
|
|
30
|
+
const LAYER_LABEL = { system: 'System', project: 'Project' };
|
|
31
|
+
|
|
32
|
+
function buildAllow() {
|
|
33
|
+
return { continue: true };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function buildDeny(reason) {
|
|
37
|
+
return {
|
|
38
|
+
continue: true,
|
|
39
|
+
decision: 'block',
|
|
40
|
+
reason,
|
|
41
|
+
hookSpecificOutput: {
|
|
42
|
+
hookEventName: 'PreToolUse',
|
|
43
|
+
permissionDecision: 'deny',
|
|
44
|
+
permissionDecisionReason: reason,
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function buildAsk(reason) {
|
|
50
|
+
return {
|
|
51
|
+
continue: true,
|
|
52
|
+
hookSpecificOutput: {
|
|
53
|
+
hookEventName: 'PreToolUse',
|
|
54
|
+
permissionDecision: 'ask',
|
|
55
|
+
permissionDecisionReason: reason,
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function isRiskTool(toolName) {
|
|
61
|
+
return toolName === 'Bash' || (typeof toolName === 'string' && toolName.startsWith('mcp__'));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function shown(call) {
|
|
65
|
+
if (call.tool === 'Bash') {
|
|
66
|
+
const cmd = call.input && typeof call.input.command === 'string' ? call.input.command : '';
|
|
67
|
+
const one = cmd.replace(/\s+/g, ' ').trim();
|
|
68
|
+
return one.length > MAX_SHOWN ? `${one.slice(0, MAX_SHOWN)}…` : one;
|
|
69
|
+
}
|
|
70
|
+
return call.tool;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function parseClearance(env) {
|
|
74
|
+
const raw = env.SM_SCHEDULER_JOB_RISK_TOOLS;
|
|
75
|
+
if (!raw) return [];
|
|
76
|
+
try {
|
|
77
|
+
const arr = JSON.parse(raw);
|
|
78
|
+
return Array.isArray(arr) ? arr.filter((e) => typeof e === 'string') : [];
|
|
79
|
+
} catch (e) {
|
|
80
|
+
console.error(`${TAG} SM_SCHEDULER_JOB_RISK_TOOLS is not a JSON array, ignoring it: ${e?.message}`);
|
|
81
|
+
return [];
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Does clearance rule `e` cover every command marks rule `r` can match? Used
|
|
87
|
+
* for Bash so that, in a compound command, a clearance for one simple command
|
|
88
|
+
* never clears a different blocking simple command in the same line.
|
|
89
|
+
*/
|
|
90
|
+
function bashCovers(e, r) {
|
|
91
|
+
if (!e || !r || e.kind !== 'bash' || r.kind !== 'bash') return false;
|
|
92
|
+
if (e.prefix.length > r.prefix.length) return false;
|
|
93
|
+
for (let i = 0; i < e.prefix.length; i++) if (e.prefix[i] !== r.prefix[i]) return false;
|
|
94
|
+
if (!e.exact) return true;
|
|
95
|
+
return r.exact && e.prefix.length === r.prefix.length;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function isCleared(entries, call, hit) {
|
|
99
|
+
return entries.some((entry) => {
|
|
100
|
+
if (!ruleMatches(entry, call)) return false;
|
|
101
|
+
if (call.tool !== 'Bash') return true;
|
|
102
|
+
return bashCovers(parseRule(entry), parseRule(hit.rule));
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Resolve the first blocking, uncleared mark for `call`, or null. A cleared
|
|
108
|
+
* rule is re-marked 'read' in a working copy and resolution repeats, so every
|
|
109
|
+
* blocking simple command in a compound Bash line must be cleared on its own.
|
|
110
|
+
*/
|
|
111
|
+
function findBlocking(call, layers, clearance) {
|
|
112
|
+
const work = {
|
|
113
|
+
system: { ...layers.system, marks: { ...(layers.system.marks || {}) } },
|
|
114
|
+
project: { ...layers.project, marks: { ...(layers.project.marks || {}) } },
|
|
115
|
+
};
|
|
116
|
+
for (let i = 0; i < 64; i++) {
|
|
117
|
+
const hit = resolveMark(call, work);
|
|
118
|
+
if (!hit || !BLOCKING_MARKS.has(hit.mark)) return null;
|
|
119
|
+
if (!isCleared(clearance, call, hit)) return hit;
|
|
120
|
+
work[hit.layer].marks[hit.rule] = 'read';
|
|
121
|
+
}
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function blockReason(call, hit, headless) {
|
|
126
|
+
const layer = LAYER_LABEL[hit.layer] || hit.layer;
|
|
127
|
+
return [
|
|
128
|
+
`Blocked: \`${shown(call)}\` is marked '${hit.mark}' by rule \`${hit.rule}\` in the ${layer} tool-risk file ${hit.file || '(unknown file)'}.`,
|
|
129
|
+
headless
|
|
130
|
+
? `A headless job may run a '${hit.mark}' tool only when its PRD clears it: name it in riskTools (e.g. "${hit.rule}") in the PRD and re-queue.`
|
|
131
|
+
: `This project enforces tool-risk marks in interactive sessions (interactive: true); to run it from a job, name it in riskTools in the PRD.`,
|
|
132
|
+
'Do not work around this refusal (no other tool, wrapper, script or alias for the same effect); stop and report that this step needs clearance.',
|
|
133
|
+
].join(' ');
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function unreadableReason(layerObj, which) {
|
|
137
|
+
return [
|
|
138
|
+
`Blocked: the ${which} tool-risk file ${layerObj.file} cannot be used (${layerObj.error}), so every Bash and MCP call is refused (fail closed).`,
|
|
139
|
+
'A human must fix the file in Settings.',
|
|
140
|
+
'Do not work around this refusal; stop and report it.',
|
|
141
|
+
].join(' ');
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function protectedTarget(payload, homeDir, projectRoot) {
|
|
145
|
+
const input = payload.tool_input || {};
|
|
146
|
+
const target = typeof input.file_path === 'string' ? input.file_path
|
|
147
|
+
: typeof input.notebook_path === 'string' ? input.notebook_path : null;
|
|
148
|
+
if (!target) return null;
|
|
149
|
+
const base = typeof payload.cwd === 'string' && payload.cwd ? payload.cwd : process.cwd();
|
|
150
|
+
const resolved = path.resolve(base, target);
|
|
151
|
+
const guarded = [systemMarksPath(homeDir)];
|
|
152
|
+
if (projectRoot) guarded.push(projectMarksPath(projectRoot));
|
|
153
|
+
if (typeof payload.cwd === 'string' && payload.cwd) guarded.push(projectMarksPath(payload.cwd));
|
|
154
|
+
return guarded.some((g) => path.resolve(g) === resolved) ? resolved : null;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* PreToolUse payload in, hook-response object out. No stdin/stdout and no
|
|
159
|
+
* process.exit. `env` defaults to process.env; `deps.homeDir` to os.homedir().
|
|
160
|
+
*/
|
|
161
|
+
function decide(payload, env = process.env, deps = {}) {
|
|
162
|
+
try {
|
|
163
|
+
const homeDir = deps.homeDir || os.homedir();
|
|
164
|
+
const projectRoot = env.SM_PROJECT_ROOT || null;
|
|
165
|
+
const headless = Boolean(env.SM_SCHEDULER_JOB_SLUG) || env.SM_TOOL_RISK_HEADLESS === '1';
|
|
166
|
+
const toolName = payload.tool_name;
|
|
167
|
+
|
|
168
|
+
const system = readMarksLayer(systemMarksPath(homeDir));
|
|
169
|
+
const project = projectRoot
|
|
170
|
+
? readMarksLayer(projectMarksPath(projectRoot))
|
|
171
|
+
: { ok: true, exists: false, marks: {}, interactive: false, file: null };
|
|
172
|
+
|
|
173
|
+
let refuse;
|
|
174
|
+
if (headless) {
|
|
175
|
+
refuse = buildDeny;
|
|
176
|
+
} else if (project.ok && project.interactive) {
|
|
177
|
+
// A -p Chat turn has no approval surface: the CLI auto-denies 'ask' with generic text.
|
|
178
|
+
refuse = env.SM_CHAT_SESSION_ID ? buildDeny : buildAsk;
|
|
179
|
+
} else {
|
|
180
|
+
return buildAllow(); // interactive session without opt-in — inert
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
if (WRITE_TOOLS.has(toolName)) {
|
|
184
|
+
const target = protectedTarget(payload, homeDir, projectRoot);
|
|
185
|
+
if (target) {
|
|
186
|
+
return buildDeny(`Blocked: ${toolName} of ${target} — marks are human-owned: edit them in Settings. Do not work around this refusal.`);
|
|
187
|
+
}
|
|
188
|
+
return buildAllow();
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
if (!isRiskTool(toolName)) return buildAllow();
|
|
192
|
+
|
|
193
|
+
if (system.exists && !system.ok) return refuse(unreadableReason(system, 'System'));
|
|
194
|
+
if (project.exists && !project.ok) return refuse(unreadableReason(project, 'Project'));
|
|
195
|
+
|
|
196
|
+
const call = { tool: toolName, input: payload.tool_input };
|
|
197
|
+
const clearance = headless ? parseClearance(env) : [];
|
|
198
|
+
const hit = findBlocking(call, { system, project }, clearance);
|
|
199
|
+
if (!hit) return buildAllow();
|
|
200
|
+
return refuse(blockReason(call, hit, headless));
|
|
201
|
+
} catch (e) {
|
|
202
|
+
console.error(`${TAG} internal error, failing open: ${e?.message}`);
|
|
203
|
+
return buildAllow();
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Mirrors the CLI's stdin-JSON handling so it can be exercised without a spawn. */
|
|
208
|
+
function parsePayload(raw) {
|
|
209
|
+
try {
|
|
210
|
+
return raw ? JSON.parse(raw) : {};
|
|
211
|
+
} catch (e) {
|
|
212
|
+
console.error(`${TAG} malformed stdin JSON, failing open: ${e?.message}`);
|
|
213
|
+
return {};
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
module.exports = { decide, parsePayload };
|