sprag-cli 3.106.1 → 3.107.1

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/src/harness.js CHANGED
@@ -26,6 +26,7 @@ import { routeWarningForStatusline } from './route-scan.js';
26
26
  import { ruleHealthWarningForStatusline, modelRatchetPathFor, renderModelRatchet } from './model-rules.js';
27
27
  import { compactWindowWarningForStatusline } from './compact-window.js';
28
28
  import { userLanguage } from './config.js';
29
+ import { writePrivateFile } from './private-file.js';
29
30
  import { routingEnabled, routingOffRatchetText } from './routing-switch.js';
30
31
  import { codexUserDir } from './agent.js';
31
32
  import { ratchetPresetEntries } from './presets-source.js';
@@ -241,7 +242,7 @@ export function harnessInit({ root = findProjectRoot(), force = false, scope = '
241
242
  if (force) {
242
243
  const stamp = new Date().toISOString().replace(/[:.]/g, '').slice(0, 15);
243
244
  const bak = `${cmPath}.bak-${stamp}`;
244
- writeFileSync(bak, existing);
245
+ writePrivateFile(bak, existing);
245
246
  result.backedUp.push(bak);
246
247
  }
247
248
  writeFileSync(cmPath, next);
@@ -254,7 +255,7 @@ export function harnessInit({ root = findProjectRoot(), force = false, scope = '
254
255
  // via the BEGIN/END markers.
255
256
  const stamp = new Date().toISOString().replace(/[:.]/g, '').slice(0, 15); // YYYYMMDDTHHMMSS
256
257
  const bak = `${cmPath}.bak-${stamp}`;
257
- writeFileSync(bak, existing);
258
+ writePrivateFile(bak, existing);
258
259
  const sep = existing.endsWith('\n') ? '\n' : '\n\n';
259
260
  writeFileSync(cmPath, existing + sep + block);
260
261
  result.backedUp.push(bak);
@@ -330,7 +331,7 @@ export function harnessUninit({ root = findProjectRoot(), purgeRatchet = false,
330
331
  } else if (beginIdx !== -1) {
331
332
  const stamp = new Date().toISOString().replace(/[:.]/g, '').slice(0, 15);
332
333
  const bak = `${cmPath}.bak-${stamp}`;
333
- writeFileSync(bak, existing);
334
+ writePrivateFile(bak, existing);
334
335
  const re = new RegExp(
335
336
  `\\n*${escapeRe(HARNESS_BLOCK_BEGIN)}[\\s\\S]*?${escapeRe(HARNESS_BLOCK_END)}\\n?`,
336
337
  'm',
@@ -349,7 +350,7 @@ export function harnessUninit({ root = findProjectRoot(), purgeRatchet = false,
349
350
  if (purgeRatchet && existsSync(rmPath)) {
350
351
  const stamp = new Date().toISOString().replace(/[:.]/g, '').slice(0, 15);
351
352
  const bak = `${rmPath}.bak-${stamp}`;
352
- writeFileSync(bak, readFileSync(rmPath, 'utf8'));
353
+ writePrivateFile(bak, readFileSync(rmPath, 'utf8'));
353
354
  result.backedUp.push(bak);
354
355
  // Replace with empty initial template rather than delete (preserves dir).
355
356
  writeFileSync(rmPath, harnessRatchetMdInitial());
@@ -554,7 +555,7 @@ export function harnessPrune({ root = findProjectRoot(), scope = 'project', agen
554
555
  });
555
556
  if (dryRun || doomed.length === 0) return { ok: true, path: rmPath, pruned: doomed, dryRun: true };
556
557
  const content = readFileSync(rmPath, 'utf8');
557
- writeFileSync(rmPath + '.bak', content);
558
+ writePrivateFile(rmPath + '.bak', content);
558
559
  const drop = new Set(doomed.map((r) => r.lineNo));
559
560
  const kept = content.split('\n').filter((_, i) => !drop.has(i));
560
561
  writeFileSync(rmPath, kept.join('\n'));
@@ -585,7 +586,7 @@ export function harnessRmRule(n, { root = findProjectRoot(), scope = 'project',
585
586
  return { ok: false, error: `No rule #${n} (have ${rules.length})`, rules };
586
587
  }
587
588
  const content = readFileSync(rmPath, 'utf8');
588
- writeFileSync(rmPath + '.bak', content);
589
+ writePrivateFile(rmPath + '.bak', content);
589
590
  const lines = content.split('\n');
590
591
  lines.splice(target.lineNo, 1);
591
592
  writeFileSync(rmPath, lines.join('\n'));
package/src/installer.js CHANGED
@@ -15,6 +15,7 @@
15
15
 
16
16
  import { writeFileSync, mkdirSync, existsSync, unlinkSync, readFileSync, rmSync, copyFileSync, renameSync, realpathSync, statSync } from 'node:fs';
17
17
  import { loadConfig, saveConfig } from './config.js';
18
+ import { restrictFile } from './private-file.js';
18
19
  import { CLI_NAME, LEGACY_CLI_NAME } from './cli-name.js';
19
20
  import { join, dirname, resolve } from 'node:path';
20
21
  import { homedir } from 'node:os';
@@ -163,6 +164,7 @@ export function writeSettings(file, settings) {
163
164
  target = realpathSync(file);
164
165
  mode = statSync(target).mode & 0o777;
165
166
  copyFileSync(target, `${target}.sprag-bak`);
167
+ restrictFile(`${target}.sprag-bak`);
166
168
  }
167
169
  const tmpPath = target === file ? tmp : `${target}.sprag-tmp-${process.pid}`;
168
170
  try {
@@ -0,0 +1,145 @@
1
+ /**
2
+ * judgement-prompt — does a subagent prompt ask for work whose conclusion is a
3
+ * judgement?
4
+ *
5
+ * The delegation grade (routing-switch.js) needs this at the moment the main
6
+ * model hands work to a haiku or sonnet subagent. Work whose answer is read off
7
+ * a command's output or a named file relays fine on a cheaper tier. Work whose
8
+ * answer is a judgement does not: a review that ends in priorities, an audit, a
9
+ * root-cause diagnosis, a web search for candidates, a lookup where "there is
10
+ * none" may be the answer, a check where the output decides what to open next.
11
+ * A cheaper model hands back a confident, wrong answer there and nothing
12
+ * announces it, so the guard sends that work to Opus (see delegation-guard.js).
13
+ *
14
+ * This is a regex and keyword pass, no model call: the hook runs on every
15
+ * Task/Agent call and has to stay in the milliseconds. Precision comes first.
16
+ * A false positive reroutes a delegation that was fine, a false
17
+ * negative only leaves today's behaviour in place.
18
+ *
19
+ * Left out on purpose: a prompt that names the pages to read and only copies
20
+ * facts off them ("Read https://... and quote ..."), which the rule set keeps
21
+ * as a delegable web read. A prompt that is nothing but a file path to an
22
+ * instruction sheet says nothing the pass can read, so it stays unflagged too.
23
+ *
24
+ * Measured 2026-11-08 against the lanes of the narrow-v3 assignment (54
25
+ * prompts, lane 'main' counted as judgement). Six 'main' prompts that are only
26
+ * a file path or a one-word reply say nothing a pass can read and were left
27
+ * out, which leaves 32 positives and 16 negatives:
28
+ *
29
+ * flagged not flagged
30
+ * main 25 7 recall 0.78 (25/32)
31
+ * other 1 15 precision 0.96 (25/26)
32
+ *
33
+ * The patterns were tuned on these same 54 prompts, so the figures are
34
+ * in-sample; with 16 negatives they are an order of magnitude, not a rate.
35
+ * The misses are mostly page reads whose questions end in "does the page say
36
+ * X": the assignment labels some 'main' and near-identical ones 'web', and no
37
+ * pattern separates the two. The one false positive is such a page read.
38
+ *
39
+ * Re-measured 2026-11-09 after a live session missed a review: paths now
40
+ * shrink to one token before matching (see judgementEvidence), which moved
41
+ * recall from 0.72 to 0.78, and the bare words "audit" and "읽기 전용 조사"
42
+ * left the audit pattern ("it feeds a security audit" and "read-only
43
+ * investigation" describe the purpose, not the job). Over the 240 prompts of
44
+ * the delegation-ledger snapshot the pass flags 52, about 22%. Both samples
45
+ * come from one user.
46
+ */
47
+
48
+ const MARKER = '<!-- sprag:delegation -->';
49
+
50
+ // Each kind is a list of regexes over the lowercased prompt, checked in this
51
+ // order so the kinds a stricter grade acts on come first. A prompt is a
52
+ // judgement when any pattern of any kind matches, unless a gate below applies.
53
+ const PATTERNS = {
54
+ diagnosis: [
55
+ /원인(?:을|이|은)? ?(?:진단|분석|찾|파악|조사|가 (?:뭐|무엇))|원인 진단|근본 ?원인|root[- ]?cause|\bdiagnos(?:e|es|is)\b|왜 (?:실패|느|안 ?되|안 ?돼|죽|멈|깨|오류|에러)|why (?:does|is|did|are|do|it|the)\b[^\n]{0,60}(?:fail|slow|crash|break|broken|not work|wrong|hang|stuck|0 impressions)|무엇이 문제|what(?:'s| is) (?:wrong|causing)|troubleshoot/,
56
+ ],
57
+ audit: [
58
+ /감사(?:해|하|를|\s|$)|\baudit (?:the|this|my|our|for|of|it)\b|security review|보안 (?:점검|검토|허점|감사)|허점|취약(?:점|성)[^\n]{0,12}(?:찾|점검|분석|있는지)|vulnerabilit[^\n]{0,20}(?:find|audit|review|look for)|문제(?:점|를|가)? ?(?:찾|발견)|find (?:the )?(?:problems|issues|bugs|gaps|weak)|훑어/,
59
+ ],
60
+ review: [
61
+ /개선점|개선 ?방안|권고|우선순위|improvements?\b|\brecommendations\b|\brecommend (?:which|the (?:best|top)|one|a (?:top|best))\b|prioriti[sz]|순위를 (?:매기|내)|상위 \d+\s*(?:개|건)[^\n]{0,30}(?:추천|고르|선정)|추천(?:해|까지|을)/,
62
+ /(?:검토|리뷰|review)(?:해|하여|해서|하십시오|하세요|를 해| the| this| my)?[^\n]{0,40}(?:개선|문제|결함|issues?|problems?|weakness|improve)/,
63
+ ],
64
+ search: [
65
+ // Looking for sources, candidates or cases on the web. The strong words say
66
+ // so on their own; a site name needs a research verb beside it, because
67
+ // "post it on Hacker News" is not a search.
68
+ /\bwebsearch\b|web search|웹 ?검색|검색으로|검색해|search the web|search for (?:candidates|packs|sources|alternatives|places|options|tools|articles|papers)|(?:web|market)[- ]research|research task|웹 조사|web only|웹으로 조사/,
69
+ /(?:reddit|레딧|hacker news|\bhn\b|itch\.io|github)[\s\S]{0,400}(?:조사|research|수집|모으|모은다|찾아|find\b|후보|candidates|evidence|what practitioners)|(?:조사|research|수집|모으|모은다|찾아|후보|candidates|evidence)[\s\S]{0,400}(?:reddit|레딧|hacker news)/,
70
+ ],
71
+ absence: [
72
+ /없다는 (?:결론|사실)|없다고 (?:단정|판단|보고)|없음을 (?:확인|단정)|(?:is|are) there any\b|does (?:it|the page|the doc|the docs|any page|this) (?:say|mention|describe)|any mention\b|if the page does not answer|read-only search\b/,
73
+ ],
74
+ conditional: [
75
+ /출력에 따라|결과에 따라|보고 (?:나서 )?(?:더 |어느 )|필요하면 (?:소스|코드|파일|로그)|depending on (?:what|the output|the result)|decide (?:which|what) to (?:open|read|look)|follow (?:the )?leads|(?:무엇|뭔)(?:인지)?(?:는|은)? 아직 모(?:른다|릅니다)|구현 (?:상태|여부)[^\n]{0,10}(?:조사|확인)|(?:막히면|실패하면|안 되면|if (?:it is blocked|that fails|blocked))[^\n]{0,80}(?:다음|대체|우회|fall ?back|시도|instead|try)/,
76
+ ],
77
+ };
78
+
79
+ /**
80
+ * A prompt that hands over a finished design to build. The wording ("the
81
+ * design is fixed", "implement the following") is how the main model briefs
82
+ * the implementation worker, and its text mentions audits, reviews and
83
+ * searches only as things the code does. Reading those as the task is the
84
+ * most common false positive in the ledger snapshot.
85
+ */
86
+ const IMPLEMENTATION_BRIEF = /구현 작업|설계(?:가|는|를)? (?:이미 )?확정|권장 모델|수정할 파일|수정 대상|(?:만들|작성할|생성할) 파일|완료 기준|leave (?:the )?changes uncommitted|do not git commit|커밋하지 마십시오|files to (?:create|add|change)|you are (?:extending|implementing)|^\s*(?:implement|extend)\b|implement the follow|(?:design|spec) is (?:fixed|final|settled)/;
87
+
88
+ /**
89
+ * A prompt that closes the web off and points at a file or pasted text to work
90
+ * from. Its mentions of Reddit or Hacker News name the content, not a search.
91
+ */
92
+ const SOURCE_IS_GIVEN = /파일 내용만으로|파일만으로|웹을 새로 조회하지|(?:do not|don't) (?:search|browse|fetch)[^\n]{0,20}(?:the )?web|only from the (?:file|text)/;
93
+
94
+ /** True when `re` matched at `m.index` inside a negation, "do not diagnose" or "원인 분석을 하지 말고". */
95
+ function negated(text, m) {
96
+ const before = text.slice(Math.max(0, m.index - 14), m.index);
97
+ const after = text.slice(m.index + m[0].length, m.index + m[0].length + 14);
98
+ return /(?:do not|don't|never|without|no)\s+$/.test(before) || /하지 (?:말|마|않)|금지|안 ?합니다/.test(after);
99
+ }
100
+
101
+ /**
102
+ * A prompt that names pages and asks for what they say. The gate looks for a
103
+ * URL, a read or fetch verb, and no search verb, so a prompt that goes looking
104
+ * for sources is not mistaken for a page read.
105
+ */
106
+ function isPageRead(text) {
107
+ if (!/https?:\/\//.test(text)) return false;
108
+ if (!/\b(?:read|fetch|open)\b|읽고|읽어|확인할 페이지/.test(text)) return false;
109
+ const bare = text.replace(/https?:\/\/\S+/g, ' ');
110
+ return !PATTERNS.search.some((re) => re.test(bare));
111
+ }
112
+
113
+ /**
114
+ * @param {string} prompt - the subagent prompt as the caller wrote it
115
+ * @returns {{ judgement: boolean, kind: 'review'|'audit'|'diagnosis'|'search'|'absence'|'conditional'|null }}
116
+ */
117
+ export function isJudgementDelegation(prompt) {
118
+ const { judgement, kind } = judgementEvidence(prompt);
119
+ return { judgement, kind };
120
+ }
121
+
122
+ /** Same answer plus the text that triggered it, for tests and for measuring false positives. */
123
+ export function judgementEvidence(prompt) {
124
+ if (typeof prompt !== 'string' || prompt === '') return { judgement: false, kind: null, match: null };
125
+ // The guard's own appendix is not part of what the caller asked for.
126
+ const cut = prompt.indexOf(MARKER);
127
+ // Paths shrink to one token first. The patterns keep their words within a
128
+ // short distance, and a real delegation names its directory in full: "review
129
+ // the file app.js in /private/tmp/…/project for security problems" put 70
130
+ // characters between the verb and its object and passed as not judgement in a
131
+ // live session, while the same prompt with a short path was caught.
132
+ const text = (cut === -1 ? prompt : prompt.slice(0, cut)).toLowerCase()
133
+ .replace(/(?:~|\.{0,2})?\/[^\s`'"()<>,;]+/g, '<path>');
134
+ if (IMPLEMENTATION_BRIEF.test(text) || SOURCE_IS_GIVEN.test(text) || isPageRead(text)) return { judgement: false, kind: null, match: null };
135
+ for (const [kind, res] of Object.entries(PATTERNS)) {
136
+ for (const re of res) {
137
+ const m = re.exec(text);
138
+ if (m && !negated(text, m)) return { judgement: true, kind, match: m[0].slice(0, 40) };
139
+ }
140
+ }
141
+ return { judgement: false, kind: null, match: null };
142
+ }
143
+
144
+ /** Kinds the 'cost' grade still raises: a wrong answer here costs the most and shows the least. */
145
+ export const SAVING_GRADE_KINDS = new Set(['diagnosis', 'audit']);
@@ -36,9 +36,10 @@ import { userDataDir } from './paths.js';
36
36
  import { userLanguage } from './config.js';
37
37
  import { agentPhrase, agentPhraseEn, resolveAgentName, agentForRule, TIER_MODEL } from './agents.js';
38
38
  import { writeStateFile } from './state-file.js';
39
+ import { safeExcerpt } from './redact.js';
39
40
  import { signedUsd } from './money.js';
40
41
  import { implementationDelegationRule } from './implementation-delegation.js';
41
- import { routingEnabled, routingOffRatchetText } from './routing-switch.js';
42
+ import { routingEnabled, routingOffRatchetText, delegationGrade, normalizeDelegationGrade, gradeKeepsRule, relaxUntil, relaxClock } from './routing-switch.js';
42
43
 
43
44
  // Post-promotion delegated-category error rate above this flags the rule
44
45
  // for review (rule-health). Calibrated against local T0 avg error incidence.
@@ -154,7 +155,9 @@ export function composeRuleText(baseText, rule, lang = userLanguage()) {
154
155
  */
155
156
  const EXAMPLE_MAX = 30;
156
157
  function shortExample(text) {
157
- const one = String(text || '').replace(/\s+/g, ' ').trim();
158
+ // Masked first, because a registry written by an older version may still hold
159
+ // a raw prompt excerpt, and this is the point where it reaches ratchet-model.md.
160
+ const one = safeExcerpt(text, Infinity).trim();
158
161
  return one.length <= EXAMPLE_MAX ? one : `${one.slice(0, EXAMPLE_MAX - 1)}…`;
159
162
  }
160
163
 
@@ -235,7 +238,18 @@ export function ruleForProject(rules, tier, category, projectDir) {
235
238
  return promotedHere || firstGlobal;
236
239
  }
237
240
 
241
+ /** The registry keeps the user's own words as rule examples; secrets and personal data never go to disk. */
242
+ function maskExamples(data) {
243
+ for (const r of data?.rules || []) {
244
+ for (const key of ['example', 'exampleEn']) {
245
+ if (typeof r?.[key] === 'string' && r[key]) r[key] = safeExcerpt(r[key], 80);
246
+ }
247
+ }
248
+ return data;
249
+ }
250
+
238
251
  export function saveModelRules(data) {
252
+ maskExamples(data);
239
253
  writeStateFile(modelRulesPath(), JSON.stringify(data, null, 2) + '\n');
240
254
  }
241
255
 
@@ -274,11 +288,22 @@ export function removeModelRule(index1) {
274
288
  * to, or null for the global file, which may only name agents the user
275
289
  * directory holds (see agentExists). Left out, it is the current directory.
276
290
  */
277
- export function renderModelRatchet(rules, lang = userLanguage(), { root } = {}) {
291
+ export function renderModelRatchet(rules, lang = userLanguage(), { root, grade = delegationGrade(), relaxUntilMs = relaxUntil() } = {}) {
278
292
  const ko = lang === 'ko';
293
+ // The same T2 filter the prompt hook applies (routeMatch), so the file and
294
+ // the hook do not tell the model different things. At grade 'quality' a T2
295
+ // rule survives only for paste, read and translate.
296
+ rules = rules.filter((r) => gradeKeepsRule(grade, r));
297
+ // Only a relaxed window gets a line. The default behaviour is not described.
298
+ const relaxed = normalizeDelegationGrade(grade) === 'cost';
299
+ const clock = relaxed && typeof relaxUntilMs === 'number' ? relaxClock(relaxUntilMs) : null;
300
+ const relaxLine = !relaxed ? [] : lang === 'ko'
301
+ ? [`이번 한도 창${clock ? `(${clock}까지)` : ''}은 위임 범위를 넓혀 둔 상태입니다. 판단형 일도 원인 진단, 감사, 보안이 아니면 위임할 수 있습니다.`, '']
302
+ : [`This limit window${clock ? ` (until ${clock})` : ''} is widened for delegation. Judgement work may be delegated too unless it is root-cause diagnosis, an audit, or security.`, ''];
279
303
  const lines = ko ? [
280
304
  '# Model-Fitting Ratchet (sprag 자동 관리)',
281
305
  '',
306
+ ...relaxLine,
282
307
  '로그 기반 티어 위임 룰. 이 파일은 route-scan이 매 스캔마다 통째로 재생성하므로',
283
308
  '직접 수정하지 마세요 — 목록/제거: `sprag route-scan rules [rm <N>]`.',
284
309
  '',
@@ -314,6 +339,12 @@ export function renderModelRatchet(rules, lang = userLanguage(), { root } = {})
314
339
  '- 사용자만 아는 맥락(이미 반려된 후보, 앞서 정한 조건)은 위임 지시문에 적습니다.',
315
340
  ' 서브에이전트는 그 맥락을 볼 수 없어서 effort를 올려도 찾지 못합니다(실측: effort를',
316
341
  ' 바꿔 9회 돌렸고 9회 모두 반려된 후보를 다시 추천했습니다).',
342
+ '- 개선점이나 권고를 내는 검토, 감사, 원인 진단, 검색이 필요한 조사, 무엇이 "없다"고',
343
+ ' 단정해야 하는 조회, 출력을 보고 더 볼 곳을 정해야 하는 점검은 결론이 판단입니다.',
344
+ ' 이런 일은 위임하지 않고 메인이 맡습니다. 세션이 Sonnet이면 Opus(effort high)로',
345
+ ' 올립니다. effort xhigh는 권하지 않습니다(판단형 10건 실측에서 틀린 주장이 3개에서',
346
+ ' 11개로 늘었습니다). 메인 세션의 effort가 low나 medium이면 판단 부분을 Opus effort high',
347
+ ' 서브에이전트에 맡기고 사용자에게 /effort high를 한 줄로 알립니다.',
317
348
  '',
318
349
  '## 티어 판별 기준 (모든 룰에 공통 적용)',
319
350
  '',
@@ -357,6 +388,7 @@ export function renderModelRatchet(rules, lang = userLanguage(), { root } = {})
357
388
  ] : [
358
389
  '# Model-Fitting Ratchet (managed by sprag)',
359
390
  '',
391
+ ...relaxLine,
360
392
  'Log-derived tier delegation rules. route-scan regenerates this file in full',
361
393
  'on every scan — do not edit it by hand. List / remove with:',
362
394
  '`sprag route-scan rules [rm <N>]`.',
@@ -395,6 +427,15 @@ export function renderModelRatchet(rules, lang = userLanguage(), { root } = {})
395
427
  ' settled earlier) into the delegation prompt. The subagent cannot see it, and',
396
428
  ' no effort level makes up for that (measured: 9 runs across efforts, all 9',
397
429
  ' recommended the rejected candidate again).',
430
+ '- A review that ends in improvements or recommendations, an audit, a root-cause',
431
+ ' diagnosis, research that needs searching, a lookup that has to conclude that',
432
+ ' something does "not exist", and a check where the output decides where to',
433
+ ' look next all end in a judgement. Do not delegate them; the main model does',
434
+ ' them. If the session is on Sonnet, move up to Opus at effort high. Do not',
435
+ ' recommend effort xhigh (measured on 10 judgement jobs: wrong claims rose from',
436
+ ' 3 to 11). If the main session runs at effort low or medium, hand the part that',
437
+ ' needs judgement to an Opus subagent at effort high and tell the user about',
438
+ ' /effort high in one line.',
398
439
  '',
399
440
  '## Tier criteria (apply to every rule below)',
400
441
  '',
@@ -0,0 +1,239 @@
1
+ /**
2
+ * permission-secrets — secrets that "don't ask again" left in approval lists.
3
+ *
4
+ * Claude Code stores an approved command verbatim in permissions.allow of
5
+ * .claude/settings.local.json. A command that carried a password or token
6
+ * therefore keeps it on disk, and a project whose settings file is committed
7
+ * publishes it (Apiiro found 1,122 public GitHub files this way, 2026-11-05).
8
+ *
9
+ * This module reads the four settings files (home and project, shared and
10
+ * local), reports which approval entries hold something findSecrets flags, and
11
+ * removes allow/ask entries on request. It never prints a value: previews go
12
+ * through maskPreview. An entry is deleted, not rewritten, because a repaired
13
+ * command could permit a different command than the one the user approved.
14
+ * deny entries stay: they block, and a blocked secret-bearing command is harmless.
15
+ */
16
+
17
+ import {
18
+ readFileSync, writeFileSync, existsSync, mkdirSync, statSync, renameSync, realpathSync, rmSync, chmodSync,
19
+ } from 'node:fs';
20
+ import { join, dirname, basename } from 'node:path';
21
+ import { homedir } from 'node:os';
22
+ import { execFileSync } from 'node:child_process';
23
+ import { findSecrets, maskPreview } from './redact.js';
24
+ import { userDataDir } from './paths.js';
25
+ import { writeStateFile } from './state-file.js';
26
+ import { writePrivateFile } from './private-file.js';
27
+ import { debug } from './debug.js';
28
+
29
+ export const PERMISSION_LISTS = ['allow', 'ask', 'deny'];
30
+ const GIT_TIMEOUT_MS = 2000;
31
+ const STATE_FILE = 'secret-scan-state.json';
32
+
33
+ /** The settings files worth reading, home first. A file reached twice (cwd is the home directory) appears once. */
34
+ export function settingsTargets({ home = homedir(), root = null } = {}) {
35
+ const out = [];
36
+ const seen = new Set();
37
+ const add = (dir, name, scope) => {
38
+ const path = join(dir, '.claude', name);
39
+ let key = path;
40
+ try { key = realpathSync(path); } catch { /* not there: keep the plain path */ }
41
+ if (seen.has(key)) return;
42
+ seen.add(key);
43
+ out.push({ path, scope, name });
44
+ };
45
+ add(home, 'settings.json', 'home');
46
+ add(home, 'settings.local.json', 'home');
47
+ if (root) {
48
+ add(root, 'settings.json', 'project');
49
+ add(root, 'settings.local.json', 'project');
50
+ }
51
+ return out;
52
+ }
53
+
54
+ function readJson(path) {
55
+ try {
56
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
57
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
58
+ } catch {
59
+ return null;
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Entries of one settings file that hold something that looks like a secret.
65
+ * @returns {{ path: string, mtimeMs: number, entries: { list: string, index: number, kinds: string[], preview: string }[] } | null}
66
+ * null when the file is missing or unreadable; `entries` is empty for a clean file
67
+ */
68
+ export function scanSettingsFile(path) {
69
+ if (!existsSync(path)) return null;
70
+ const json = readJson(path);
71
+ if (!json) return null;
72
+ const perms = json.permissions;
73
+ const entries = [];
74
+ if (perms && typeof perms === 'object') {
75
+ for (const list of PERMISSION_LISTS) {
76
+ if (!Array.isArray(perms[list])) continue;
77
+ perms[list].forEach((item, i) => {
78
+ if (typeof item !== 'string') return;
79
+ const hits = findSecrets(item);
80
+ if (!hits.length) return;
81
+ entries.push({
82
+ list,
83
+ index: i + 1,
84
+ kinds: [...new Set(hits.map((h) => h.kind))],
85
+ preview: maskPreview(item, 100),
86
+ });
87
+ });
88
+ }
89
+ }
90
+ let mtimeMs = 0;
91
+ try { mtimeMs = statSync(path).mtimeMs; } catch { /* the entries are still valid */ }
92
+ return { path, mtimeMs, entries };
93
+ }
94
+
95
+ /** Run git without a shell. Returns the exit status, or null when git cannot answer (missing, timed out). */
96
+ function gitStatus(args, cwd) {
97
+ try {
98
+ execFileSync('git', args, { cwd, stdio: 'ignore', timeout: GIT_TIMEOUT_MS });
99
+ return 0;
100
+ } catch (e) {
101
+ return typeof e.status === 'number' ? e.status : null;
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Whether git tracks `file` (a secret in a tracked file is one commit away from
107
+ * public, or already is) and whether it is ignored.
108
+ * @returns {{ tracked: boolean, ignored: boolean | null } | null} null when git is unavailable or the folder is no repository
109
+ */
110
+ export function gitState(file, { withIgnore = true } = {}) {
111
+ const cwd = dirname(file);
112
+ const tracked = gitStatus(['ls-files', '--error-unmatch', '--', basename(file)], cwd);
113
+ if (tracked === null || tracked > 1) return null; // 128: not a repository
114
+ let ignored = null;
115
+ if (withIgnore) {
116
+ const status = gitStatus(['check-ignore', '-q', '--', basename(file)], cwd);
117
+ ignored = status === 0 ? true : status === 1 ? false : null;
118
+ }
119
+ return { tracked: tracked === 0, ignored };
120
+ }
121
+
122
+ /**
123
+ * Scan every settings file for the given project.
124
+ * Project files with hits also get their git state; `withIgnore: false` skips the
125
+ * second git call (the session hook only needs to know whether a file is tracked).
126
+ */
127
+ export function scanPermissionSecrets({ home = homedir(), root = null, withIgnore = true } = {}) {
128
+ const results = [];
129
+ for (const target of settingsTargets({ home, root })) {
130
+ const scan = scanSettingsFile(target.path);
131
+ if (!scan) continue;
132
+ const git = target.scope === 'project' && scan.entries.length ? gitState(target.path, { withIgnore }) : null;
133
+ results.push({ ...target, ...scan, git });
134
+ }
135
+ return results;
136
+ }
137
+
138
+ /** Where `sprag secrets fix` keeps the original before it changes a file. */
139
+ export function backupPathFor(file, { dir = userDataDir(), now = new Date() } = {}) {
140
+ const folder = join(dir, 'backups', now.toISOString().replace(/[:.]/g, '-'));
141
+ mkdirSync(folder, { recursive: true });
142
+ let target = join(folder, basename(file));
143
+ // home and project both have a settings.local.json
144
+ for (let n = 2; existsSync(target); n += 1) target = join(folder, `${basename(file)}.${n}`);
145
+ return target;
146
+ }
147
+
148
+ /**
149
+ * Remove the flagged allow/ask entries from one settings file.
150
+ * The original is saved first (owner-only) and the rest of the JSON is kept as it was.
151
+ * @returns {{ removed: number, backup: string|null, error?: string }}
152
+ */
153
+ export function fixSettingsFile(path, { dir = userDataDir(), now = new Date() } = {}) {
154
+ const raw = readFileSync(path, 'utf8');
155
+ const json = JSON.parse(raw);
156
+ const perms = json?.permissions;
157
+ let removed = 0;
158
+ if (perms && typeof perms === 'object') {
159
+ for (const list of ['allow', 'ask']) {
160
+ if (!Array.isArray(perms[list])) continue;
161
+ const kept = perms[list].filter((item) => !(typeof item === 'string' && findSecrets(item).length > 0));
162
+ removed += perms[list].length - kept.length;
163
+ perms[list] = kept;
164
+ }
165
+ }
166
+ if (!removed) return { removed: 0, backup: null };
167
+
168
+ const backup = backupPathFor(path, { dir, now });
169
+ writePrivateFile(backup, raw);
170
+
171
+ // Same shape as installer.writeSettings (temp file + rename, mode kept, symlink followed),
172
+ // minus its .sprag-bak sidecar: that copy would put the secret right back beside the file.
173
+ let target = path;
174
+ let mode;
175
+ try { target = realpathSync(path); mode = statSync(target).mode & 0o777; } catch { /* write to the plain path */ }
176
+ const tmp = `${target}.sprag-tmp-${process.pid}`;
177
+ try {
178
+ writeFileSync(tmp, JSON.stringify(json, null, 2) + '\n', mode === undefined ? undefined : { mode });
179
+ if (mode !== undefined) { try { chmodSync(tmp, mode); } catch { /* mode is best effort */ } }
180
+ renameSync(tmp, target);
181
+ } catch (e) {
182
+ try { rmSync(tmp, { force: true }); } catch { /* nothing to clean */ }
183
+ return { removed: 0, backup, error: e.message };
184
+ }
185
+ return { removed, backup };
186
+ }
187
+
188
+ // ---------------------------------------------------------------------------
189
+ // Session start notice
190
+ // ---------------------------------------------------------------------------
191
+
192
+ const statePath = (dir) => join(dir, STATE_FILE);
193
+
194
+ function loadNoticeState(dir) {
195
+ try {
196
+ const parsed = JSON.parse(readFileSync(statePath(dir), 'utf8'));
197
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
198
+ } catch {
199
+ return {};
200
+ }
201
+ }
202
+
203
+ const shortPath = (p, home) => (p.startsWith(home) ? `~${p.slice(home.length)}` : p);
204
+
205
+ export function noticeLine({ file, n, tracked, lang }) {
206
+ if (lang === 'ko') {
207
+ return `✇ [sprag] ${file} 의 승인 목록 ${n}개 항목에 비밀 값으로 보이는 문자열이 있습니다${tracked ? '. 이 파일은 git이 추적하고 있어 커밋되면 공개될 수 있습니다' : ''}. 사용자에게 알리고 sprag secrets 로 확인한 뒤 sprag secrets fix 로 지우라고 안내하십시오.`;
208
+ }
209
+ return `✇ [sprag] ${n} entries in the permission list of ${file} look like they hold secrets${tracked ? ', and git tracks this file, so a commit would publish them' : ''}. Tell the user, and suggest sprag secrets to review them and sprag secrets fix to remove them.`;
210
+ }
211
+
212
+ /**
213
+ * The line(s) the session start hook shows when a settings file holds secrets, or null.
214
+ * A file is announced once per modification time: the same file at the same mtime
215
+ * stays quiet on later sessions, and editing it (adding an entry, or fixing it) re-arms the check.
216
+ * Cheap on purpose: four JSON reads, plus one `git ls-files` per project file that has hits.
217
+ */
218
+ export function secretsNotice({
219
+ home = homedir(), root = null, lang = 'en', dir = userDataDir(), enabled = true,
220
+ } = {}) {
221
+ if (!enabled) return null;
222
+ const state = loadNoticeState(dir);
223
+ const lines = [];
224
+ let changed = false;
225
+ for (const f of scanPermissionSecrets({ home, root, withIgnore: false })) {
226
+ if (!f.entries.length) {
227
+ if (state[f.path] !== undefined) { delete state[f.path]; changed = true; }
228
+ continue;
229
+ }
230
+ if (state[f.path] === f.mtimeMs) continue;
231
+ lines.push(noticeLine({ file: shortPath(f.path, home), n: f.entries.length, tracked: f.git?.tracked === true, lang }));
232
+ state[f.path] = f.mtimeMs;
233
+ changed = true;
234
+ }
235
+ if (changed) {
236
+ try { writeStateFile(statePath(dir), JSON.stringify(state) + '\n'); } catch (e) { debug('permission-secrets:state', e); }
237
+ }
238
+ return lines.length ? lines.join('\n') : null;
239
+ }
@@ -22,6 +22,7 @@ import { homedir } from 'node:os';
22
22
  import { dirname, join } from 'node:path';
23
23
  import { codexUserDir } from './agent.js';
24
24
  import { userLanguage } from './config.js';
25
+ import { writePrivateFile } from './private-file.js';
25
26
  import { routingEnabled, DELEGATION_PRESET_IDS } from './routing-switch.js';
26
27
  import {
27
28
  HARNESS_BLOCK_BEGIN,
@@ -102,7 +103,7 @@ export function migrateLegacyPresetRules({ agent = 'claude' } = {}) {
102
103
  return false;
103
104
  });
104
105
  if (!moved.length) return { file, moved: 0 };
105
- writeFileSync(`${file}.bak-preset-migration`, original);
106
+ writePrivateFile(`${file}.bak-preset-migration`, original);
106
107
  writeIfChanged(file, kept.join('\n'));
107
108
  const state = loadSeedState({ agent });
108
109
  const today = new Date().toISOString().slice(0, 10);
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Files that copy a user's settings or notes (the .bak and .sprag-bak
3
+ * backups) can hold what the original holds: a token in settings.json's env
4
+ * block, a pasted password in CLAUDE.md. A copy made with the default mode is
5
+ * readable by every account on the machine, so these helpers cut it to the
6
+ * owner. The content is never changed, because a backup exists to be restored.
7
+ */
8
+
9
+ import { chmodSync, writeFileSync } from 'node:fs';
10
+
11
+ /** chmod 0600; a failure (Windows, a filesystem without modes) is ignored. */
12
+ export function restrictFile(path) {
13
+ try { chmodSync(path, 0o600); } catch { /* best effort */ }
14
+ }
15
+
16
+ /** Write `data` to `path` readable by the owner only, replacing an older, wider-mode copy too. */
17
+ export function writePrivateFile(path, data) {
18
+ writeFileSync(path, data, { mode: 0o600 });
19
+ restrictFile(path);
20
+ }