sprag-cli 3.90.4 → 3.92.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.
@@ -1,5 +1,6 @@
1
1
  /**
2
- * Statusline formatter — compact single-line output for Claude Code statusline API.
2
+ * Statusline formatter — compact output for Claude Code statusline API: one chip
3
+ * line, wrapped onto a few lines when COLUMNS is known and the chips would not fit.
3
4
  * Called every ~300ms, so kept minimal and fast. ANSI color codes included by default.
4
5
  *
5
6
  * Example output (color):
@@ -30,6 +31,7 @@ import { modelFamily } from '../savings-ledger.js';
30
31
  import { shareLegend } from '../model-share.js';
31
32
  import { STAR_URL } from '../star-note.js';
32
33
  import { speciesLabel } from '../office-species.js';
34
+ import { cellWidth } from '../cell-width.js';
33
35
 
34
36
  // The 8-color ANSI defaults (RED=31, GREEN=32, YELLOW=33…) read as garish
35
37
  // next to each other — terminal palettes set them with unbalanced perceptual
@@ -547,15 +549,133 @@ function buildCapWarnSeg(capWarn, c, isIcon, g, color, mode) {
547
549
  return `${c(BOLD)}${c(RED)}${capWarn.label} cap ${pct}%${clockTail}${c(RESET)}`;
548
550
  }
549
551
 
552
+ // Room Claude Code keeps for its own padding around the statusline. A guess
553
+ // from observed truncation, so it may be tuned.
554
+ const STATUSLINE_MARGIN = 4;
555
+ const CHIP_SEP = ' · ';
556
+ const SEP_WIDTH = 3;
557
+ // Continuation rows of a wrapped headline start indented, so they read as the
558
+ // rest of the line above rather than as a new headline.
559
+ const HEADLINE_INDENT = ' ';
560
+
561
+ const availWidth = (columns) => Math.max(20, columns - STATUSLINE_MARGIN);
562
+
563
+ /**
564
+ * Wrap one headline line to `avail` cells. A headline is sections joined by a
565
+ * gray `|`, and a section is items joined by a gray `·` (see buildDelegatedSeg
566
+ * and buildDoc2mdSeg), so it breaks at those joints and never inside an item.
567
+ * The routing line lists every model pair on purpose, which makes it the
568
+ * widest line of the statusline: unwrapped, the terminal cut it at the total
569
+ * and hid the whole breakdown.
570
+ */
571
+ function wrapHeadline(line, avail, c) {
572
+ if (cellWidth(line) <= avail) return [line];
573
+ const bar = ` ${c(GRAY)}|${c(RESET)} `;
574
+ const dot = ` ${c(GRAY)}·${c(RESET)} `;
575
+ const pieces = [];
576
+ line.split(bar).forEach((section, i) => {
577
+ section.split(dot).forEach((text, j) => pieces.push({ text, sep: j ? dot : i ? bar : '' }));
578
+ });
579
+ const rows = [];
580
+ let row = '';
581
+ let used = 0;
582
+ for (const { text, sep } of pieces) {
583
+ const w = cellWidth(text);
584
+ const sepW = cellWidth(sep);
585
+ if (row && used + sepW + w > avail) {
586
+ rows.push(row);
587
+ row = HEADLINE_INDENT + text;
588
+ used = HEADLINE_INDENT.length + w;
589
+ } else {
590
+ used += (row ? sepW : 0) + w;
591
+ row += (row ? sep : '') + text;
592
+ }
593
+ }
594
+ if (row) rows.push(row);
595
+ return rows;
596
+ }
597
+
598
+ /**
599
+ * Join chips into statusline lines no wider than the terminal. Without a known
600
+ * width Claude Code truncates the single line with an ellipsis, which hides the
601
+ * chips at the tail; wrapping at chip boundaries keeps every one readable.
602
+ *
603
+ * Chips arrive in priority order, so when the wrap needs more than `maxLines`
604
+ * lines the lowest-priority tail is dropped and counted in a `+N` chip.
605
+ * `protectedSegs` (the chips that stop the work) are never dropped, even if the
606
+ * result then overflows `maxLines`.
607
+ *
608
+ * @param {string[]} segs
609
+ * @param {object} [o]
610
+ * @param {number} [o.columns] - terminal width; falsy returns the legacy one-line join
611
+ * @param {number} [o.maxLines=3]
612
+ * @param {string} [o.eol=''] - erase-to-end-of-line suffix, appended to every line
613
+ * @param {Set<string>} [o.protectedSegs]
614
+ * @param {boolean} [o.color=true] - gray the `+N` chip
615
+ * @returns {string} lines joined by `eol + '\n'`; no trailing newline
616
+ */
617
+ export function layoutChips(segs, o = {}) {
618
+ return fitChips(segs, o).text;
619
+ }
620
+
621
+ // layoutChips plus how many chips it had to drop, so formatReport can tell a
622
+ // clean fit from one that cost chips.
623
+ function fitChips(segs, { columns, maxLines = 3, eol = '', protectedSegs = new Set(), color = true } = {}) {
624
+ if (!columns || !Number.isFinite(columns)) return { text: segs.join(CHIP_SEP) + eol, dropped: 0 };
625
+ const avail = availWidth(columns);
626
+ const widths = new Map();
627
+ const widthOf = (chip) => {
628
+ let w = widths.get(chip);
629
+ if (w === undefined) { w = cellWidth(chip); widths.set(chip, w); }
630
+ return w;
631
+ };
632
+ const wrap = (chips) => {
633
+ const lines = [];
634
+ let line = [];
635
+ let used = 0;
636
+ for (const chip of chips) {
637
+ const w = widthOf(chip);
638
+ if (line.length && used + SEP_WIDTH + w > avail) {
639
+ lines.push(line);
640
+ line = [];
641
+ used = 0;
642
+ }
643
+ used += (line.length ? SEP_WIDTH : 0) + w;
644
+ line.push(chip);
645
+ }
646
+ if (line.length) lines.push(line);
647
+ return lines;
648
+ };
649
+
650
+ let kept = segs;
651
+ let dropped = 0;
652
+ let lines = wrap(kept);
653
+ while (lines.length > maxLines) {
654
+ // Drop from the tail, skipping protected chips and any `+N` already added.
655
+ let at = kept.length - 1;
656
+ if (dropped) at -= 1;
657
+ while (at >= 0 && protectedSegs.has(kept[at])) at -= 1;
658
+ if (at < 0) break;
659
+ const base = dropped ? kept.slice(0, -1) : kept;
660
+ dropped += 1;
661
+ const rest = base.filter((_, i) => i !== at);
662
+ const more = `${color ? GRAY : ''}+${dropped}${color ? RESET : ''}`;
663
+ kept = [...rest, more];
664
+ lines = wrap(kept);
665
+ }
666
+ return { text: lines.map((l) => l.join(CHIP_SEP) + eol).join('\n'), dropped };
667
+ }
668
+
550
669
  /**
551
670
  * Fallback line for when no session data exists in the analysis window.
552
671
  * The stdin payload (rate limits, model) is still live in that case, and a
553
672
  * 90%+ cap warning is exactly the kind of signal that must not disappear
554
673
  * just because the user has been idle past the window — so cap-warn,
555
674
  * harness, model, and effort chips still render around the "no session data"
556
- * note.
675
+ * note. With `columns` the chips wrap onto at most `maxLines` lines (see
676
+ * layoutChips).
557
677
  */
558
- export function formatNoSession({ caps = null, model = null, effort = null, windowLabel = '', version = '', update = null, team = null } = {}, { color = true, mode = 'icon', segments = null } = {}) {
678
+ export function formatNoSession({ caps = null, model = null, effort = null, windowLabel = '', version = '', update = null, team = null } = {}, { color = true, mode = 'icon', segments = null, columns = 0, maxLines = 3 } = {}) {
559
679
  const c = (v) => (color ? v : '');
560
680
  // narrow shares the icon layout and swaps only the glyphs, so both modes take
561
681
  // the same branches from here on.
@@ -580,7 +700,9 @@ export function formatNoSession({ caps = null, model = null, effort = null, wind
580
700
  const teamSeg = buildTeamSeg(team, c, mode);
581
701
  if (teamSeg) segs.push(teamSeg);
582
702
  if (versionSeg && !(update && update.available)) segs.push(versionSeg);
583
- return segs.join(' · ') + (color ? '\x1b[K' : '');
703
+ return layoutChips(segs, {
704
+ columns, maxLines, eol: color ? '\x1b[K' : '', protectedSegs: new Set(capSeg ? [capSeg] : []), color,
705
+ });
584
706
  }
585
707
 
586
708
  /**
@@ -927,7 +1049,7 @@ function sinceFormatters(c, isIcon, verbose) {
927
1049
  *
928
1050
  * @returns {{ chips: (string|null)[], headline: { usd: number, line: string } | null }}
929
1051
  */
930
- function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g, color) {
1052
+ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g) {
931
1053
  // Delegation savings — a DIFFERENT number from the "Cache saved" chip, which
932
1054
  // covers the prompt cache only. This one is what running work on a cheaper
933
1055
  // tier saved, the lifetime total of the delegation ledger (counted from the
@@ -990,18 +1112,9 @@ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g, color) {
990
1112
  : null;
991
1113
  // The unresolved count stands in only while there are no savings to show, so
992
1114
  // a dated zero keeps both: the reset and the dropped runs are separate facts.
993
- // What the spend was made of, for the same period as the routing counter:
994
- // "◩ Model used ● Opus 90% ● Sonnet 10%". A segment of its own, after the
995
- // savings and their breakdown, so a share is never read as another saving.
996
- // Only with a savings figure beside it, and absent when switched off
997
- // (`mode no-share`) or empty.
998
- const ms = data.modelShare;
999
- const usedLabel = isIcon ? `${g.used} Model used` : 'Model used';
1000
- const usedSeg = ms && Number(ms.totalUsd) > 0 && Array.isArray(ms.families) && ms.families.length
1001
- ? `${c(GREEN)}${usedLabel}${c(RESET)} ${shareLegend(ms.families, { color })}`
1002
- : '';
1003
- const withShare = (chip) => (chip && usedSeg ? `${chip} ${c(GRAY)}|${c(RESET)} ${usedSeg}` : chip);
1004
- const delegateSeg = withShare(savingsChip) || (delegationSaved === 0 ? unresolvedSeg : null);
1115
+ // The Model used share is no longer attached here: it has its own chip
1116
+ // (buildShareSeg), so it survives when there is no savings figure to carry it.
1117
+ const delegateSeg = savingsChip || (delegationSaved === 0 ? unresolvedSeg : null);
1005
1118
  const delegateExtra = savingsChip && delegationSaved === 0 ? unresolvedSeg : null;
1006
1119
 
1007
1120
  // Routing-savings headline line (multi-line layout). The lifetime sum from
@@ -1013,8 +1126,8 @@ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g, color) {
1013
1126
  // a row of rolling windows it read as a breakdown of whichever one it
1014
1127
  // touched. A single lifetime total makes the whole line one timeframe with
1015
1128
  // nothing to mismatch.
1016
- // icon: "🔀 Routing saved $9.8 | opus→haiku ×2 $6.4 · fable→sonnet ×1 $3.4 | 📊 Model used ● Opus 90%"
1017
- // text: "Routing saved $9.8 | opus→haiku ×2 $6.4 · fable→sonnet ×1 $3.4 | Model used ● Opus 90%"
1129
+ // icon: "🔀 Routing saved $9.8 | opus→haiku ×2 $6.4 · fable→sonnet ×1 $3.4"
1130
+ // text: "Routing saved $9.8 | opus→haiku ×2 $6.4 · fable→sonnet ×1 $3.4"
1018
1131
  let totalsLine = null;
1019
1132
  const totalsNum = Number(totals && totals.total);
1020
1133
  // A zero total gets its line only when a reset mark explains it; see the
@@ -1044,8 +1157,7 @@ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g, color) {
1044
1157
  `${c(tone)}${c(BOLD)}${head}${c(RESET)} ` +
1045
1158
  `${c(tone)}${formatMoney(totalsNum)}${c(RESET)}` +
1046
1159
  sinceWord(routingSince) + scanTag +
1047
- (pairText ? ` ${c(GRAY)}|${c(RESET)} ${pairText}` : '') +
1048
- (usedSeg ? ` ${c(GRAY)}|${c(RESET)} ${usedSeg}` : '');
1160
+ (pairText ? ` ${c(GRAY)}|${c(RESET)} ${pairText}` : '');
1049
1161
  }
1050
1162
 
1051
1163
  return {
@@ -1058,6 +1170,22 @@ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g, color) {
1058
1170
  };
1059
1171
  }
1060
1172
 
1173
+ /**
1174
+ * What the spend was made of, as its own chip: "◩ Model used ● Opus 90% ●
1175
+ * Sonnet 10% (since 10/9)". It used to ride behind the routing savings and
1176
+ * vanished whenever there was no savings figure. The period is dated every time
1177
+ * because it differs from the other chips: the routing reset mark, the start of
1178
+ * the month when never reset, or the 90-day cap (see loadModelShare). Absent
1179
+ * when switched off (`mode no-share`) or empty.
1180
+ */
1181
+ function buildShareSeg(ms, c, isIcon, g, color) {
1182
+ if (!(ms && Number(ms.totalUsd) > 0 && Array.isArray(ms.families) && ms.families.length)) return null;
1183
+ const usedLabel = isIcon ? `${g.used} Model used` : 'Model used';
1184
+ const date = formatSince(ms.since);
1185
+ const sinceText = date ? ` ${c(GRAY)}(since ${date})${c(RESET)}` : '';
1186
+ return `${c(GREEN)}${usedLabel}${c(RESET)} ${shareLegend(ms.families, { color })}${sinceText}`;
1187
+ }
1188
+
1061
1189
  /** The one-time star ask (see star-note.js); null unless the CLI passed a chip. */
1062
1190
  function buildStarSeg(star, c, isIcon) {
1063
1191
  if (!star || typeof star !== 'object' || !Number.isFinite(star.usd)) return null;
@@ -1175,6 +1303,9 @@ export const DEFAULT_SEGMENT_ORDER = [
1175
1303
  // Lifetime, from the savings ledgers. Delegation stays ahead of the cache
1176
1304
  // figure: routing is what the tool is for, the cache number is a brag stat.
1177
1305
  'delegated', 'doc2md',
1306
+ // Same period as the routing counter, so it sits after the lifetime routing
1307
+ // figures but carries its own since date.
1308
+ 'share',
1178
1309
  // One-time star ask; renders only while readStarChip returns an object.
1179
1310
  'star',
1180
1311
  // Analysis window. These two are the only chips measured over it, so the label
@@ -1220,6 +1351,7 @@ function segmentsNamed(name, s, usageByKey) {
1220
1351
  // the session's own subagent runs.
1221
1352
  case 'delegated': return [...s.delegated, s.subagents];
1222
1353
  case 'doc2md': return s.doc2md;
1354
+ case 'share': return [s.share];
1223
1355
  case 'star': return [s.star];
1224
1356
  case 'hit': return [s.hit];
1225
1357
  case 'ttl': return [s.ttl];
@@ -1307,7 +1439,7 @@ function arrangeSegments(order, s) {
1307
1439
  /**
1308
1440
  * The headline lines that sit above the chips, as one string of `line\n` pairs.
1309
1441
  */
1310
- function buildHeadlines(delegated, doc2md, want, eol) {
1442
+ function buildHeadlines(delegated, doc2md, want, eol, columns = 0, c = (v) => v) {
1311
1443
  // Each savings source that earned real money gets a headline line, ordered
1312
1444
  // biggest saver first — the top line is the one the eye lands on, so it
1313
1445
  // goes to whichever habit is actually paying for the tool. The diagnostics
@@ -1316,7 +1448,10 @@ function buildHeadlines(delegated, doc2md, want, eol) {
1316
1448
  if (delegated.headline && want('delegated')) headlines.push(delegated.headline);
1317
1449
  if (doc2md.headline && want('doc2md')) headlines.push(doc2md.headline);
1318
1450
  headlines.sort((a, b) => b.usd - a.usd);
1319
- return headlines.map((h) => h.line + eol + '\n').join('');
1451
+ const rows = columns
1452
+ ? headlines.flatMap((h) => wrapHeadline(h.line, availWidth(columns), c))
1453
+ : headlines.map((h) => h.line);
1454
+ return rows.map((row) => row + eol + '\n').join('');
1320
1455
  }
1321
1456
 
1322
1457
  /**
@@ -1326,10 +1461,12 @@ function buildHeadlines(delegated, doc2md, want, eol) {
1326
1461
  * @param {boolean} [opts.verbose=false] - longer layout with labels
1327
1462
  * @param {boolean} [opts.timer=true] - show TTL countdown segment
1328
1463
  * @param {'text'|'icon'} [opts.mode='text'] - label style. 'icon' uses 🧠 ⏳ 💰 instead of word labels.
1329
- * @param {string[]|null} [opts.segments] - segments to render, in the order given. Names: cap-warn, spike, version, harness (a full score with no warning draws only when named here), korean (draws only when named here), team (member id and office animal; joined machines only), model, effort, hit, ttl, month, saved, delegated, doc2md, star, ctx, period, `subagents` (this session's subagent runs; also rides with `delegated`), `rules` (only when named here), `usage` (every rate-limit window), plus per-window keys (`five_hour`, `seven_day`, …). `5h`/`7d` are kept as aliases for back-compat. cap-warn and spike keep the lead regardless of where they appear. Null/undefined = all, in the default order.
1330
- * @param {boolean} [opts.singleLine=false] - force the legacy one-line layout. By default, when the delegation ledger has lifetime savings, the routing totals lead on their own first line and everything else moves to line 2 (Claude Code renders multi-line statuslines; `--single-line` is the escape hatch for terminals that only show the first line).
1464
+ * @param {string[]|null} [opts.segments] - segments to render, in the order given. Names: cap-warn, spike, version, harness (a full score with no warning draws only when named here), korean (draws only when named here), team (member id and office animal; joined machines only), model, effort, hit, ttl, month, saved, delegated, doc2md, share (Model used by family, dated), star, ctx, period, `subagents` (this session's subagent runs; also rides with `delegated`), `rules` (only when named here), `usage` (every rate-limit window), plus per-window keys (`five_hour`, `seven_day`, …). `5h`/`7d` are kept as aliases for back-compat. cap-warn and spike keep the lead regardless of where they appear. Null/undefined = all, in the default order.
1465
+ * @param {boolean} [opts.singleLine=false] - force the legacy one-line layout. By default, when the delegation ledger has lifetime savings, the routing totals lead on their own first line and everything else moves to line 2 (Claude Code renders multi-line statuslines; `--single-line` is the escape hatch for terminals that only show the first line). It also ignores `columns`.
1466
+ * @param {number} [opts.columns=0] - terminal width in cells (Claude Code exports it as COLUMNS). When set, the chips wrap at chip boundaries instead of being truncated by the terminal; 0 keeps one unbounded line. A verbose layout that would need chips dropped is re-rendered once in the compact layout first.
1467
+ * @param {number} [opts.maxLines=3] - most chip lines when `columns` is set; lower-priority tail chips collapse into a `+N` chip beyond that. Counts the chip lines only: the headline lines above them wrap at their own `|` and `·` joints and are not included. Cap, usage, ctx, spike chips are never dropped.
1331
1468
  */
1332
- export function formatReport(data, { color = true, verbose = false, timer = true, mode = 'text', segments = null, singleLine = false } = {}) {
1469
+ export function formatReport(data, { color = true, verbose = false, timer = true, mode = 'text', segments = null, singleLine = false, columns = 0, maxLines = 3 } = {}) {
1333
1470
  const { summary, ttl, cost, options, lastActivity, contextWindow, ctxLive, spikeChip, caps, model, effort } = data;
1334
1471
 
1335
1472
  const c = (v) => (color ? v : '');
@@ -1362,7 +1499,7 @@ export function formatReport(data, { color = true, verbose = false, timer = true
1362
1499
  const capWarn = pickCapWarn(caps);
1363
1500
 
1364
1501
  // Routing and doc2md each return a chip and, for real money, a headline line.
1365
- const delegated = buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g, color);
1502
+ const delegated = buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g);
1366
1503
  const doc2md = buildDoc2mdSeg(data.doc2mdTotals, singleLine, c, isIcon, verbose, g);
1367
1504
 
1368
1505
  // An available upgrade moves the version chip forward (see resolveSegmentOrder).
@@ -1383,6 +1520,7 @@ export function formatReport(data, { color = true, verbose = false, timer = true
1383
1520
  delegated: delegated.chips,
1384
1521
  // The inline chip steps aside when a headline line owns the story.
1385
1522
  doc2md: doc2md.headline ? [] : [doc2md.chip],
1523
+ share: buildShareSeg(data.modelShare, c, isIcon, g, color),
1386
1524
  star: buildStarSeg(data.star, c, isIcon),
1387
1525
  // This session's subagent runs by model family. It is a session figure, so
1388
1526
  // it sits with the routing chips rather than with the lifetime totals.
@@ -1416,6 +1554,17 @@ export function formatReport(data, { color = true, verbose = false, timer = true
1416
1554
  // "erase from cursor to EOL" CSI. Only emitted when color (i.e. ANSI) is
1417
1555
  // allowed — --no-color/NO_COLOR consumers expect escape-free output.
1418
1556
  const eol = color ? '\x1b[K' : '';
1419
- const rest = segs.join(' · ') + eol;
1420
- return buildHeadlines(delegated, doc2md, want, eol) + rest;
1557
+ if (singleLine || !columns) return buildHeadlines(delegated, doc2md, want, eol) + segs.join(' · ') + eol;
1558
+ const headlines = buildHeadlines(delegated, doc2md, want, eol, columns, c);
1559
+
1560
+ // The chips that stop the work: layoutChips drops from the tail when the
1561
+ // terminal is narrow, and these must survive that.
1562
+ const protectedSegs = new Set([built.capWarn, built.spike, built.ctx, ...built.usage.map((u) => u.seg)].filter(Boolean));
1563
+ const fitted = fitChips(segs, { columns, maxLines, eol, protectedSegs, color });
1564
+ // Verbose labels are the first thing to give up: if they only fit by dropping
1565
+ // chips, the compact layout (same chips, shorter text) may keep all of them.
1566
+ if (verbose && fitted.dropped) {
1567
+ return formatReport(data, { color, verbose: false, timer, mode, segments, singleLine, columns, maxLines });
1568
+ }
1569
+ return headlines + fitted.text;
1421
1570
  }
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * korean-lint — machine-checkable half of the fluent-korean guidance.
3
+ * korean-lint: machine-checkable half of the Korean style rules.
4
4
  *
5
5
  * Why this exists next to korean-style.js:
6
6
  *
@@ -82,36 +82,36 @@ const METAPHOR_LEXICON = [
82
82
  {
83
83
  re: /(?<!빈 |좌석 |앞 |뒤 |옆 )(?:^|(?<=\s))자리(?:에서|에서는|에|로|가|는|다|입니다|였습니다)?(?=\s|$|[.,·)])/,
84
84
  except: /(?:^|\s)(?:\d+|한|두|세|네|다섯|여섯|일곱|여덟|아홉|열|몇) 자리(?=\s|$)|(?:첫째|둘째|셋째|넷째|다섯째|[일십백천만]의) 자리|자리 ?(?:수|숫자)(?![가-힣]{2})/,
85
- fix: "'지점'·'상황'·'부분'처럼 뜻을 그대로 담은 명사로 바꿉니다",
85
+ fix: "'지점', '상황', '부분'처럼 뜻을 그대로 담은 명사로 바꿉니다",
86
86
  },
87
87
  // The lookbehind pins the match to the start of a Hangul run. Without it the
88
88
  // engine retried `[가-힣]+` from every character of a long run that has no
89
89
  // `의 흐름` in it, which is quadratic: a 200k-character run took 20 seconds.
90
- { re: /(?<![가-힣])[가-힣]+의\s*흐름/, fix: "'방향'·'순서'·'경과'로 바꿉니다" },
91
- { re: /닿(?:는다|습니다|아|는 지점)/, fix: "'겨냥하다'·'해당하다'처럼 동작을 그대로 서술합니다" },
92
- { re: /박(?:아 두|혀 있|아 넣)/, fix: "'명시하다'·'기록하다'로 바꿉니다" },
93
- { re: /걷어내/, fix: "'없애다'·'제거하다'로 바꿉니다" },
94
- { re: /손대(?:는|지|어)/, fix: "'수정하다'·'변경하다'로 바꿉니다" },
90
+ { re: /(?<![가-힣])[가-힣]+의\s*흐름/, fix: "'방향', '순서', '경과'로 바꿉니다" },
91
+ { re: /닿(?:는다|습니다|아|는 지점)/, fix: "'겨냥하다', '해당하다'처럼 동작을 그대로 서술합니다" },
92
+ { re: /박(?:아 두|혀 있|아 넣)/, fix: "'명시하다', '기록하다'로 바꿉니다" },
93
+ { re: /걷어내/, fix: "'없애다', '제거하다'로 바꿉니다" },
94
+ { re: /손대(?:는|지|어)/, fix: "'수정하다', '변경하다'로 바꿉니다" },
95
95
  { re: /발목을 잡/, fix: '무엇이 어떻게 막는지 그대로 서술합니다' },
96
- { re: /민낯|속살/, fix: "'실제 상태'·'내부 구조'로 바꿉니다" },
97
- { re: /열쇠(?:다|입니다|가 된다)/, fix: "'핵심 조건'·'결정 요인'으로 바꿉니다" },
96
+ { re: /민낯|속살/, fix: "'실제 상태', '내부 구조'로 바꿉니다" },
97
+ { re: /열쇠(?:다|입니다|가 된다)/, fix: "'핵심 조건', '결정 요인'으로 바꿉니다" },
98
98
  { re: /물꼬|신호탄|분수령|기폭제/, fix: '무엇이 시작되고 무엇이 바뀌는지 그대로 적습니다' },
99
99
  { re: /판(?:을|도가|이)\s*(?:흔들|바뀌|뒤집)/, fix: '무엇이 어떻게 달라지는지 그대로 적습니다' },
100
- { re: /몸집|심장부|두뇌 역할/, fix: "'규모'·'중심 구성 요소'로 바꿉니다" },
100
+ { re: /몸집|심장부|두뇌 역할/, fix: "'규모', '중심 구성 요소'로 바꿉니다" },
101
101
  { re: /벽에 부딪|길을 열|문을 열/, fix: '무엇이 막히고 무엇이 가능해지는지 그대로 적습니다' },
102
102
  { re: /갈림길|갈리는 지점/, fix: "'결정이 나뉘는 조건'으로 바꿉니다" },
103
- { re: /깨어나|잠들어 있/, fix: "'동작을 시작하다'·'실행되지 않고 있다'로 바꿉니다" },
103
+ { re: /깨어나|잠들어 있/, fix: "'동작을 시작하다', '실행되지 않고 있다'로 바꿉니다" },
104
104
  // Added 2026-09-13. "fails loudly / fails silently" reads as idiom in English
105
105
  // but lands as figurative vocabulary in Korean: a failure has no volume.
106
106
  // 0 hits across 400 Korean files in yaml-sns-agent, so the confirm-request is
107
107
  // not noise.
108
108
  {
109
109
  re: /(?:시끄럽게|시끄러운|조용히|조용한)\s*[가-힣]*(?:실패|틀리|드러나|어긋)|(?:실패|오류|버그)[가은는이]?\s*(?:시끄럽|시끄러운|조용하|조용한)/,
110
- fix: "무엇으로 실패를 확인하는지 적습니다. '종료 코드로 바로 드러나는가'·'검증 없이 지나가는가'",
110
+ fix: "무엇으로 실패를 확인하는지 적습니다. '종료 코드로 바로 드러나는가', '검증 없이 지나가는가'",
111
111
  },
112
112
  {
113
113
  re: /안전망/,
114
- fix: "'검증 수단'·'확인 장치'처럼 무엇이 실패를 잡아내는지 그대로 적습니다",
114
+ fix: "'검증 수단', '확인 장치'처럼 무엇이 실패를 잡아내는지 그대로 적습니다",
115
115
  },
116
116
  ];
117
117
 
@@ -121,25 +121,56 @@ const TRANSLATIONESE = [
121
121
  { re: /[을를] 위한/, fix: '서술어로 풀어 씁니다' },
122
122
  // Every conjugation, not the stem alone: `되어졌다`, `되어진`, `되어질`.
123
123
  { re: /되어[지진질져졌집]/, fix: '이중 피동을 없애고 능동이나 단일 피동으로 씁니다' },
124
- { re: /하는 것을 통해/, fix: "'~해서'·'~함으로써'로 줄입니다" },
124
+ { re: /하는 것을 통해/, fix: "'~해서', '~함으로써'로 줄입니다" },
125
125
  { re: /라고 할 수 있다/, fix: '단정하거나 근거를 붙여 서술합니다' },
126
126
  // Conservative additions (2026-09-13), sourced from 국립국어원 공공언어
127
- // 지침·한글문화연대 교정 사례·쿠버네티스 한글화 가이드. Bar for inclusion:
127
+ // 지침, 한글문화연대 교정 사례, 쿠버네티스 한글화 가이드. Bar for inclusion:
128
128
  // the form is nearly always an improvement to change, so a confirm-request
129
- // on it is rarely noise. See presets/korean-style/supplement.md.
129
+ // on it is rarely noise. See presets/korean-style/rules.md, section 6.
130
130
  // `졌` is the past tense (`보여졌다`, `쓰여졌습니다`), which the first list missed.
131
- { re: /(?:보여|쓰여|불려|잊혀)[지집진질져졌]/, fix: "이중 피동입니다. '보인다'·'쓰인'·'불린'·'잊힌'처럼 단일 피동으로 씁니다" },
132
- { re: /에 다름 아니/, fix: "일본어 번역투입니다. '~일 뿐이다'·'바로 ~이다'로 바꿉니다" },
131
+ { re: /(?:보여|쓰여|불려|잊혀)[지집진질져졌]/, fix: "이중 피동입니다. '보인다', '쓰인', '불린', '잊힌'처럼 단일 피동으로 씁니다" },
132
+ { re: /에 다름 아니/, fix: "일본어 번역투입니다. '~일 뿐이다', '바로 ~이다'로 바꿉니다" },
133
133
  { re: /지 않으면 안 [되된됩돼]/, fix: "이중 부정 번역투입니다. '~해야 합니다'로 바꿉니다" },
134
134
  // `X에 있어서` also means "because it is at X", which is plain Korean. Two
135
135
  // signs separate that reading without touching the calque: a noun that names
136
136
  // a location or a container before it, or the clause ending right after it
137
137
  // (the calque is never clause-final). Corpus check: 4 hits before, 3 after,
138
138
  // the dropped one a quotation ending in `베드락에 있어서`.
139
- { re: /(?<!여기|거기|저기|어디|(?:^|\s)(?:안|밖|위|아래|옆|앞|뒤|속)|서버|폴더|디렉터리|디렉토리|경로|파일|목록|메모리|디스크|저장소|캐시|변수|로컬|원격)에 있어서(?!요|["'”’)\]]|[.!?]|$)/, fix: "'~에서'·'~에는'으로 바꿉니다" },
140
- { re: /(?:의미|특징|장점|단점|성격|가능성|중요성|효과)[을를] 가지고 있/, fix: "'~이다'·'~가 있다'로 바꿉니다 (have 직역)" },
139
+ { re: /(?<!여기|거기|저기|어디|(?:^|\s)(?:안|밖|위|아래|옆|앞|뒤|속)|서버|폴더|디렉터리|디렉토리|경로|파일|목록|메모리|디스크|저장소|캐시|변수|로컬|원격)에 있어서(?!요|["'”’)\]]|[.!?]|$)/, fix: "'~에서', '~에는'으로 바꿉니다" },
140
+ { re: /(?:의미|특징|장점|단점|성격|가능성|중요성|효과)[을를] 가지고 있/, fix: "'~이다', '~가 있다'로 바꿉니다 (have 직역)" },
141
141
  ];
142
142
 
143
+ // AI-tell punctuation (2026-11-01). KatFishNet (ACL 2025) found LLM Korean puts
144
+ // a comma after a connective ending about five times as often as people do
145
+ // (essays 19.83% vs 4.10%), and our own transcripts showed the same gap at 3.9x.
146
+ // People do write the comma now and then, so a single one passes and only a
147
+ // second one in the same paragraph is raised. Corpus check on 297 Korean files
148
+ // in yaml-sns-agent: 40 of 40 sampled hits were real connective commas.
149
+ // The word before each comma is read by walking back from the comma, and its
150
+ // ending is tested afterwards. Any `[가-힣]+` scanned left to right ahead of
151
+ // the comma retries from every position of a long comma-free Hangul run, which
152
+ // is quadratic.
153
+ function wordsBeforeCommas(line) {
154
+ const out = [];
155
+ for (let i = line.indexOf(','); i !== -1; i = line.indexOf(',', i + 1)) {
156
+ let j = i;
157
+ while (j > 0 && /[가-힣]/.test(line[j - 1])) j--;
158
+ if (j < i) out.push(line.slice(j, i));
159
+ }
160
+ return out;
161
+ }
162
+ const CONNECTIVE_ENDING = /(?:고|며|면|서|는데|은데|던데|지만|니까|므로|도록|려고|면서|거나|든지|다가)$/;
163
+ // Nouns and particles that merely end in a connective's spelling.
164
+ const CONNECTIVE_LOOKALIKE = /(?:문서|순서|서류|보고서|설명서|계약서|신청서|증명서|명세서|의견서|제안서|교과서|에서|최고|광고|경고|창고|원고|참고|재고|사고|측면|화면|반면|장면|표면|국면|전면|이면|단면|내면|외면|평면|방면|지면|가면|양면|그런데|그러면|그러니까|그러므로|그리고|아니면|예를 들면)$/;
165
+ // Korean orthography never asks for a comma after a conjunctive adverb; the
166
+ // habit comes from English. `A는 물론, B` is left out because people write it.
167
+ const CONJUNCTIVE_COMMA = /(?:^|[\s"'“(])(?:그리고|그러나|하지만|그런데|그래서|따라서|또한|게다가|그러므로|즉|반면에?|결국|다만|특히),/;
168
+ // A middle dot between Hangul words compresses a particle away (`직급·처우`,
169
+ // `커밋·푸시했다`). Assistant text used it 7.3x as often as user text in the
170
+ // 2026-11-01 transcript count. Settled pairs and table cells are exempt.
171
+ const MIDDLE_DOT = /[가-힣]·[가-힣]/g;
172
+ const SETTLED_DOT = /^(?:한|남|북|미|중|일|노|사|여|야|초|고|동|서|좌|우|상|하|입|출|전|후)·(?:중|북|남|미|일|사|야|고|서|우|하|출|후|대)/;
173
+
143
174
  // Guidance 3.7: a period belongs after a 종결어미, not after a nominal ending.
144
175
  const NOMINAL_ENDING = /(?:음|함|됨|임|점|론|양|성|화)\.$/;
145
176
 
@@ -268,7 +299,9 @@ function lintKoreanText(text, { maxFindings = 20, code = false } = {}) {
268
299
  // there; in a document a leading `|` is a table row rather than a sentence.
269
300
  const sep = line.match(code ? /[—ㅡ]/ : /[—ㅡ|]/);
270
301
  if (sep && !(sep[0] === '|' && /^\s*\|/.test(line))) {
271
- push('구분자', sep[0], '접속사나 쉼표, 가운뎃점(·)으로 바꿉니다');
302
+ // The middle dot is not offered as a substitute: it is itself an AI tell
303
+ // in Korean prose, and recommending it here taught sessions to scatter it.
304
+ push('구분자', sep[0], '문장을 둘로 나누거나 접속사로 잇습니다. 가운뎃점(·)으로 바꾸지 않습니다');
272
305
  }
273
306
 
274
307
  for (const { re, fix } of TRANSLATIONESE) {
@@ -281,6 +314,25 @@ function lintKoreanText(text, { maxFindings = 20, code = false } = {}) {
281
314
  if (m) push('비유 어휘', m[0], fix);
282
315
  }
283
316
 
317
+ const connectives = wordsBeforeCommas(line).filter((w) => CONNECTIVE_ENDING.test(w) && !CONNECTIVE_LOOKALIKE.test(w));
318
+ if (connectives.length >= 2) {
319
+ push('연결어미 쉼표', connectives.slice(0, 3).map((w) => `${w},`).join(' '), '연결어미 뒤 쉼표를 지웁니다. 절이 셋 이상 이어지면 문장을 나눕니다');
320
+ }
321
+
322
+ const conj = line.match(CONJUNCTIVE_COMMA);
323
+ if (conj) push('접속부사 쉼표', conj[0].trim(), '접속부사 뒤 쉼표를 지웁니다');
324
+
325
+ if (!/^\s*\|/.test(line)) {
326
+ const dot = [...line.matchAll(MIDDLE_DOT)].find((m) => !SETTLED_DOT.test(line.slice(m.index)));
327
+ if (dot) {
328
+ push('가운뎃점', line.slice(Math.max(0, dot.index - 6), dot.index + 7).trim(), "명사는 '와/과'나 쉼표로, 동사는 '~하고'로 풀어 씁니다");
329
+ }
330
+ }
331
+
332
+ if ((line.match(/아니라/g) || []).length >= 2) {
333
+ push("'아니라' 반복", line.trim().slice(0, 30), "'A가 아니라 B' 대조는 한 번만 쓰고 나머지는 B만 말합니다");
334
+ }
335
+
284
336
  for (const chunk of line.split(/[.,·\n]/)) {
285
337
  const count = (chunk.match(/[가-힣]의(?=\s|[가-힣])/g) || []).length;
286
338
  if (count >= 3) {
@@ -12,15 +12,16 @@
12
12
  * change and no plugin to install, and they survive `/clear` because the hook
13
13
  * fires again.
14
14
  *
15
- * Cost: the text is ~1.3k tokens, injected once per session (not per turn) and
15
+ * Cost: the text is ~2.5k tokens, injected once per session (not per turn) and
16
16
  * covered by the prompt cache from the second request on. A token-saving tool
17
17
  * has no business spending that silently, so the feature is opt-in via
18
18
  * `sprag korean on`.
19
19
  *
20
- * The guidance itself is vendored from fluent-korean
21
- * (https://github.com/snflkd/fluent-korean), Copyright (c) 2026 snflkd, MIT
22
- * License — see presets/korean-style/LICENSE-fluent-korean. Only the
23
- * output-style frontmatter was stripped; the wording is unmodified.
20
+ * The rules are sprag's own (presets/korean-style/rules.md, 2026-11-01). Each
21
+ * clause rests on a measurement or a cited source, listed in that file's
22
+ * header and in docs/KOREAN-STYLE.md. The guidance shipped through v3.90 did
23
+ * not touch the habits that read as machine-written (a comma after a
24
+ * connective ending, middle-dot lists), so it was replaced.
24
25
  */
25
26
 
26
27
  import { readFileSync, existsSync } from 'node:fs';
@@ -33,16 +34,9 @@ const require = createRequire(import.meta.url);
33
34
 
34
35
  const packageRoot = join(dirname(fileURLToPath(import.meta.url)), '..');
35
36
 
36
- export const KOREAN_STYLE_PATH = join(packageRoot, 'presets', 'korean-style', 'fluent-korean.md');
37
- // Our own conservative additions (국립국어원 공공언어 지침, 쿠버네티스 한글화
38
- // 가이드 등에서 수집). Appended after the vendored text so the vendored file
39
- // stays byte-identical to upstream.
40
- export const KOREAN_STYLE_SUPPLEMENT_PATH = join(packageRoot, 'presets', 'korean-style', 'supplement.md');
41
- export const KOREAN_STYLE_LICENSE_PATH = join(packageRoot, 'presets', 'korean-style', 'LICENSE-fluent-korean');
42
- // The separator here is a colon, not an em dash. The guidance this line cites
43
- // bans em dashes in Korean prose, and shipping one inside its own attribution
44
- // is the kind of contradiction that teaches the model the rule is negotiable.
45
- export const KOREAN_STYLE_SOURCE = 'fluent-korean by snflkd (MIT): https://github.com/snflkd/fluent-korean';
37
+ export const KOREAN_STYLE_PATH = join(packageRoot, 'presets', 'korean-style', 'rules.md');
38
+ // Where the evidence behind each clause and the cited studies are listed.
39
+ export const KOREAN_STYLE_SOURCE = 'https://sprag.io/docs/korean-style/';
46
40
 
47
41
  /** Whether session-start injection is enabled. Off unless the user asked. */
48
42
  export function koreanStyleEnabled(cfg = loadConfig()) {
@@ -111,9 +105,9 @@ export function setKoreanStyleEnabled(enabled) {
111
105
  }
112
106
 
113
107
  /**
114
- * The guidance text, with the vendoring comment stripped (it is provenance for
115
- * readers of the repo, not instruction for the model — and every token of it
116
- * would be charged on each session).
108
+ * The rules text, with the provenance comment stripped (it is for readers of
109
+ * the repo, not instruction for the model, and every token of it would be
110
+ * charged on each session).
117
111
  *
118
112
  * Returns null when the file is missing, which the hook reads as "inject
119
113
  * nothing" rather than failing a session start.
@@ -121,20 +115,8 @@ export function setKoreanStyleEnabled(enabled) {
121
115
  export function koreanStyleText() {
122
116
  try {
123
117
  if (!existsSync(KOREAN_STYLE_PATH)) return null;
124
- const raw = readFileSync(KOREAN_STYLE_PATH, 'utf8');
125
- const body = raw.replace(/^<!--[\s\S]*?-->\s*/, '').trim();
126
- if (!body) return null;
127
- // The supplement is optional: a missing or empty file degrades to the
128
- // vendored guidance alone rather than failing the injection.
129
- try {
130
- if (existsSync(KOREAN_STYLE_SUPPLEMENT_PATH)) {
131
- const sup = readFileSync(KOREAN_STYLE_SUPPLEMENT_PATH, 'utf8')
132
- .replace(/^<!--[\s\S]*?-->\s*/, '')
133
- .trim();
134
- if (sup) return `${body}\n\n${sup}`;
135
- }
136
- } catch { /* supplement unreadable: fall back to the vendored text */ }
137
- return body;
118
+ const body = readFileSync(KOREAN_STYLE_PATH, 'utf8').replace(/^<!--[\s\S]*?-->\s*/, '').trim();
119
+ return body || null;
138
120
  } catch {
139
121
  return null;
140
122
  }
@@ -157,20 +139,13 @@ export function koreanScopeLines(cfg = loadConfig()) {
157
139
  const scope = cfg?.koreanStyle?.lintScope === 'prose' ? 'prose' : 'all';
158
140
  if (scope === 'prose') {
159
141
  return [
160
- '적용 대상: 대화 답변, 그리고 새로 작성하거나 수정하는 마크다운·문서·보고서의 한국어 산문을 모두 포함합니다.',
142
+ '적용 대상: 대화 답변, 그리고 새로 작성하거나 수정하는 마크다운 문서와 보고서의 한국어 산문을 모두 포함합니다.',
161
143
  '적용 예외: 원문을 그대로 옮기는 인용, 코드, 코드 주석, 그리고 프로젝트의 기존 표기 관례를 따라야 하는 커밋 메시지와 로그 문자열입니다.',
162
144
  ];
163
145
  }
164
146
  return [
165
147
  '적용 대상: 대화 답변, 그리고 세션이 쓰거나 고치는 모든 파일의 한국어를 포함합니다. 문서와 보고서는 물론이고 코드 주석, 화면에 나가는 문자열, 자막과 템플릿, 스크립트가 읽어 산출물을 만드는 데이터 파일까지 모두 해당합니다.',
166
148
  '적용 예외: 원문을 그대로 옮기는 인용과, 프로젝트의 기존 표기 관례를 따라야 하는 커밋 메시지와 로그 문자열입니다.',
167
- // The vendored text says the opposite of the line above, and it says so
168
- // twice. Left unaddressed the model has no way to decide which sentence
169
- // governs a code comment, and in September 2026 that ambiguity shipped em
170
- // dashes into comments and log strings while the guidance was active. The
171
- // vendored wording stays untouched, so the conflict is resolved by naming
172
- // which side wins rather than by editing the source.
173
- '아래에 이어지는 fluent-korean 본문은 "인용, 코드, 코드 주석에는 이 지침들을 적용하지 않습니다"라고 적고 있으며 동작 범위 2번 조항에서 한 번 더 강조합니다. 그러나 이 세션에서는 바로 위의 적용 대상과 적용 예외가 그 문장보다 우선합니다. 즉 코드 주석에도 지침을 적용하십시오.',
174
149
  '쓰기 시점에 기계 검사가 함께 돌아갑니다. 위반을 알리면 그 파일을 고친 뒤에 다음 작업으로 넘어가십시오.',
175
150
  ];
176
151
  }
@@ -180,11 +155,11 @@ export function koreanStyleInjection({ cfg = loadConfig() } = {}) {
180
155
  const text = koreanStyleText();
181
156
  if (!text) return null;
182
157
  return [
183
- '[sprag korean-style] 이 세션에서 한국어를 출력할 때는 아래 지침을 따르십시오.',
158
+ '✇ [sprag korean-style] 이 세션에서 한국어를 출력할 때는 아래 지침을 따르십시오.',
184
159
  '이 지침은 사용자가 sprag에 설정한 것입니다.',
185
160
  ...koreanScopeLines(cfg),
186
- '표기 규칙(예외 없이 적용): 도구 호출 인자에 한국어를 비롯한 비ASCII 문자열을 담을 때에는 반드시 리터럴 UTF-8로 작성하고, \\uXXXX 유니코드 이스케이프로는 절대 작성하지 마십시오. 이스케이프로 작성하면 글자가 깨진 채 파일에 기록되는 사례가 자주 발생합니다.',
187
- `(출처: ${KOREAN_STYLE_SOURCE})`,
161
+ '표기 규칙(예외 없이 적용): 도구 호출 인자에 한국어를 비롯한 비ASCII 문자열을 담을 때에는 반드시 리터럴 UTF-8로 작성하고 \\uXXXX 유니코드 이스케이프로는 절대 작성하지 마십시오. 이스케이프로 작성하면 글자가 깨진 채 파일에 기록되는 사례가 자주 발생합니다.',
162
+ `(근거와 참고 문헌: ${KOREAN_STYLE_SOURCE})`,
188
163
  '',
189
164
  text,
190
165
  ].join('\n');
@@ -285,7 +285,7 @@ export function renderModelRatchet(rules, lang = userLanguage(), { root } = {})
285
285
  '',
286
286
  '위임을 실행할 때는 사용자에게 다음 한 줄을 먼저 표시할 것',
287
287
  '(어떤 도구가 토큰을 아끼고 있는지 가시화):',
288
- '`🔀 [sprag] 모델 피팅: "<유형>" → <agent> (<모델> · effort <effort>) 위임`',
288
+ '`✇ [sprag] 모델 피팅: "<유형>" → <agent> (<모델> · effort <effort>) 위임`',
289
289
  '',
290
290
  '<모델>과 <effort>에는 룰의 에이전트 표기 괄호 안에 적힌 값(예: Sonnet 5.5 · effort high)을',
291
291
  '그대로 옮기고, 값이 적혀 있지 않으면 그 부분을 뺍니다. Claude Code 호출 행에는 에이전트',
@@ -352,7 +352,7 @@ export function renderModelRatchet(rules, lang = userLanguage(), { root } = {})
352
352
  '',
353
353
  'When delegating under a rule below, show the user this line first so it is',
354
354
  'visible which tool is saving tokens:',
355
- '`🔀 [sprag] model fitting: "<category>" → delegated to <agent> (<model> · effort <effort>)`',
355
+ '`✇ [sprag] model fitting: "<category>" → delegated to <agent> (<model> · effort <effort>)`',
356
356
  '',
357
357
  'Fill <model> and <effort> from the parentheses after the agent in the rule',
358
358
  '(e.g. Sonnet 5.5, effort high), and leave out whichever the rule does not',