@monoes/monodesign 1.2.18 → 1.2.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +3 -3
  2. package/cli/engine/design-system-checks.mjs +381 -0
  3. package/cli/engine/design-system-parse.mjs +433 -0
  4. package/cli/engine/design-system.mjs +20 -736
  5. package/cli/engine/detect-antipatterns-browser.js +12 -1
  6. package/cli/engine/engines/regex/detect-text-matchers.mjs +371 -0
  7. package/cli/engine/engines/regex/detect-text-run.mjs +186 -0
  8. package/cli/engine/engines/regex/detect-text.mjs +11 -523
  9. package/cli/engine/engines/static-html/css-cascade-color.mjs +219 -0
  10. package/cli/engine/engines/static-html/css-cascade-static-data.mjs +138 -0
  11. package/cli/engine/engines/static-html/css-cascade-static-dom.mjs +132 -0
  12. package/cli/engine/engines/static-html/css-cascade-static-parse.mjs +393 -0
  13. package/cli/engine/engines/static-html/css-cascade.mjs +24 -837
  14. package/cli/engine/registry/antipatterns-provider.mjs +60 -0
  15. package/cli/engine/registry/antipatterns-quality.mjs +218 -0
  16. package/cli/engine/registry/antipatterns-slop.mjs +226 -0
  17. package/cli/engine/registry/antipatterns.mjs +7 -494
  18. package/cli/engine/rules/checks-background.mjs +155 -0
  19. package/cli/engine/rules/checks-css-values.mjs +137 -0
  20. package/cli/engine/rules/checks-dom-effects.mjs +243 -0
  21. package/cli/engine/rules/checks-dom.mjs +148 -0
  22. package/cli/engine/rules/checks-element.mjs +286 -0
  23. package/cli/engine/rules/checks-html.mjs +204 -0
  24. package/cli/engine/rules/checks-overflow.mjs +263 -0
  25. package/cli/engine/rules/checks-page.mjs +465 -0
  26. package/cli/engine/rules/checks-pure.mjs +453 -0
  27. package/cli/engine/rules/checks-quality.mjs +447 -0
  28. package/cli/engine/rules/checks-stylesheet.mjs +324 -0
  29. package/cli/engine/rules/checks.mjs +98 -2939
  30. package/cli/lib/monodesign-config-consent.mjs +93 -0
  31. package/cli/lib/monodesign-config-core.mjs +37 -0
  32. package/cli/lib/monodesign-config-detection.mjs +133 -0
  33. package/cli/lib/monodesign-config-filter.mjs +198 -0
  34. package/cli/lib/monodesign-config-ignore-value.mjs +212 -0
  35. package/cli/lib/monodesign-config.mjs +21 -623
  36. package/package.json +2 -2
  37. package/skill/scripts/context-fields.mjs +65 -0
  38. package/skill/scripts/context-resolve.mjs +425 -0
  39. package/skill/scripts/context-update.mjs +151 -0
  40. package/skill/scripts/context-utils.mjs +68 -0
  41. package/skill/scripts/context-workspace.mjs +245 -0
  42. package/skill/scripts/context.mjs +17 -891
  43. package/skill/scripts/hook-admin-config.mjs +152 -0
  44. package/skill/scripts/hook-admin-ignore.mjs +131 -0
  45. package/skill/scripts/hook-admin-manifest.mjs +292 -0
  46. package/skill/scripts/hook-admin.mjs +8 -541
  47. package/skill/scripts/hook-before-edit-shell.mjs +184 -0
  48. package/skill/scripts/hook-before-edit.mjs +9 -165
  49. package/skill/scripts/hook-lib-cache.mjs +145 -0
  50. package/skill/scripts/hook-lib-config.mjs +292 -0
  51. package/skill/scripts/hook-lib-detector.mjs +72 -0
  52. package/skill/scripts/hook-lib-events.mjs +182 -0
  53. package/skill/scripts/hook-lib-findings.mjs +201 -0
  54. package/skill/scripts/hook-lib-ignore.mjs +205 -0
  55. package/skill/scripts/hook-lib-render.mjs +273 -0
  56. package/skill/scripts/hook-lib-run.mjs +281 -0
  57. package/skill/scripts/hook-lib-scan-targets.mjs +128 -0
  58. package/skill/scripts/hook-lib.mjs +71 -1747
  59. package/skill/scripts/lib/design-parser-colors.mjs +182 -0
  60. package/skill/scripts/lib/design-parser-extract.mjs +333 -0
  61. package/skill/scripts/lib/design-parser-sections.mjs +214 -0
  62. package/skill/scripts/lib/design-parser-yaml.mjs +135 -0
  63. package/skill/scripts/lib/design-parser.mjs +10 -783
  64. package/skill/scripts/live/manual-apply-chunk.mjs +151 -0
  65. package/skill/scripts/live/manual-apply-compact.mjs +122 -0
  66. package/skill/scripts/live/manual-apply-evidence.mjs +115 -0
  67. package/skill/scripts/live/manual-apply-log.mjs +179 -0
  68. package/skill/scripts/live/manual-apply-transaction.mjs +122 -0
  69. package/skill/scripts/live/manual-apply.mjs +65 -640
  70. package/skill/scripts/live/svelte-component-accept.mjs +248 -0
  71. package/skill/scripts/live/svelte-component-css.mjs +230 -0
  72. package/skill/scripts/live/svelte-component-markup.mjs +104 -0
  73. package/skill/scripts/live/svelte-component-scaffold.mjs +118 -0
  74. package/skill/scripts/live/svelte-component-session.mjs +158 -0
  75. package/skill/scripts/live/svelte-component.mjs +32 -792
  76. package/skill/scripts/live-accept-mutate.mjs +152 -0
  77. package/skill/scripts/live-accept-parse.mjs +370 -0
  78. package/skill/scripts/live-accept-scrub.mjs +59 -0
  79. package/skill/scripts/live-accept-search.mjs +58 -0
  80. package/skill/scripts/live-accept.mjs +15 -631
  81. package/skill/scripts/live-commit-manual-edits-paths.mjs +27 -0
  82. package/skill/scripts/live-commit-manual-edits-repair.mjs +166 -0
  83. package/skill/scripts/live-commit-manual-edits-rollback.mjs +231 -0
  84. package/skill/scripts/live-commit-manual-edits-utils.mjs +167 -0
  85. package/skill/scripts/live-commit-manual-edits-verify.mjs +356 -0
  86. package/skill/scripts/live-commit-manual-edits.mjs +24 -881
  87. package/skill/scripts/live-copy-edit-agent.mjs +16 -551
  88. package/skill/scripts/live-copy-edit-compact.mjs +137 -0
  89. package/skill/scripts/live-copy-edit-post-apply.mjs +175 -0
  90. package/skill/scripts/live-copy-edit-runners.mjs +297 -0
  91. package/skill/scripts/live-inject-csp.mjs +132 -0
  92. package/skill/scripts/live-inject-files.mjs +229 -0
  93. package/skill/scripts/live-inject-tag.mjs +114 -0
  94. package/skill/scripts/live-inject.mjs +13 -440
  95. package/skill/scripts/live-server-poll.mjs +232 -0
  96. package/skill/scripts/live-server-routes.mjs +449 -0
  97. package/skill/scripts/live-server-state.mjs +361 -0
  98. package/skill/scripts/live-server.mjs +10 -946
  99. package/skill/scripts/live-wrap-css.mjs +132 -0
  100. package/skill/scripts/live-wrap-manual-edit.mjs +153 -0
  101. package/skill/scripts/live-wrap-search.mjs +247 -0
  102. package/skill/scripts/live-wrap.mjs +21 -484
  103. package/skill/scripts/palette-seeds.mjs +401 -0
  104. package/skill/scripts/palette.mjs +1 -395
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Shell-command parsing for the Cursor preToolUse write gate
3
+ * (hook-before-edit.mjs): where a shell command writes, and what it writes.
4
+ */
5
+
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+
9
+ import { SENSITIVE_PATH, isGeneratedPath } from './hook-lib.mjs';
10
+
11
+ function shellCommand(input) {
12
+ if (typeof input.command === 'string') return input.command;
13
+ if (input.args && typeof input.args.command === 'string') return input.args.command;
14
+ return '';
15
+ }
16
+
17
+ function shellRedirectPath(command) {
18
+ if (!command || typeof command !== 'string') return '';
19
+ const match = command.match(/(?:^|[\s;&|])(?:>>?|1>>?)\s*(?:"([^"]+)"|'([^']+)'|([^<>\s]+))/);
20
+ return (match?.[1] || match?.[2] || match?.[3] || '').trim();
21
+ }
22
+
23
+ function shellWriteDestination(command) {
24
+ return shellRedirectPath(command) || shellTeeDestination(command) || shellCopyPaths(command)?.dest || shellPythonWriteDestination(command) || '';
25
+ }
26
+
27
+ function shellPythonWriteDestination(command) {
28
+ if (!/\bpython(?:3)?\b/.test(command || '')) return '';
29
+ const directPath = firstMatch(command, /(?:^|[^\w.])(?:pathlib\.)?Path\(\s*(["'])(.*?)\1\s*\)\s*\.write_text\s*\(/);
30
+ if (directPath) return directPath;
31
+
32
+ const pathsByVar = new Map();
33
+ const assignmentRe = /\b([A-Za-z_]\w*)\s*=\s*(?:pathlib\.)?Path\(\s*(["'])(.*?)\2\s*\)/g;
34
+ let assignment;
35
+ while ((assignment = assignmentRe.exec(command))) {
36
+ pathsByVar.set(assignment[1], assignment[3]);
37
+ }
38
+
39
+ const writeVarRe = /\b([A-Za-z_]\w*)\.write_text\s*\(/g;
40
+ let writeVar;
41
+ while ((writeVar = writeVarRe.exec(command))) {
42
+ const candidate = pathsByVar.get(writeVar[1]);
43
+ if (candidate) return candidate;
44
+ }
45
+
46
+ return firstMatch(command, /\bopen\(\s*(["'])(.*?)\1\s*,\s*(["'])[wax](?:\+)?b?\3/);
47
+ }
48
+
49
+ function firstMatch(value, re) {
50
+ const match = String(value || '').match(re);
51
+ return (match?.[2] || '').trim();
52
+ }
53
+
54
+ function shellTeeDestination(command) {
55
+ const words = shellWords(command);
56
+ const teeIndex = words.findIndex((word) => path.basename(word) === 'tee');
57
+ if (teeIndex === -1) return '';
58
+ for (const word of words.slice(teeIndex + 1)) {
59
+ if (['&&', '||', ';', '|'].includes(word)) break;
60
+ if (word === '--') continue;
61
+ if (word.startsWith('-')) continue;
62
+ return word;
63
+ }
64
+ return '';
65
+ }
66
+
67
+ function shellCopiedFileContent(command, cwd) {
68
+ const source = shellCopyPaths(command)?.source;
69
+ if (!source) return '';
70
+ const sourcePath = path.isAbsolute(source) ? source : path.resolve(cwd, source);
71
+ if (!isInsideProject(sourcePath, cwd)) return '';
72
+ if (SENSITIVE_PATH.test(sourcePath) || isGeneratedPath(sourcePath, cwd)) return '';
73
+ try {
74
+ const stat = fs.statSync(sourcePath);
75
+ if (!stat.isFile() || stat.size > 1024 * 1024) return '';
76
+ return fs.readFileSync(sourcePath, 'utf-8');
77
+ } catch {
78
+ return '';
79
+ }
80
+ }
81
+
82
+ function shellCopyPaths(command) {
83
+ const words = shellWords(command);
84
+ if (words.length < 3 || path.basename(words[0]) !== 'cp') return null;
85
+ const args = [];
86
+ for (const word of words.slice(1)) {
87
+ if (['&&', '||', ';', '|'].includes(word)) break;
88
+ if (word === '--') continue;
89
+ if (word.startsWith('-')) continue;
90
+ args.push(word);
91
+ }
92
+ if (args.length < 2) return null;
93
+ return { source: args[args.length - 2], dest: args[args.length - 1] };
94
+ }
95
+
96
+ function shellWords(command) {
97
+ if (!command || typeof command !== 'string') return [];
98
+ const words = [];
99
+ const re = /"((?:\\"|[^"])*)"|'((?:\\'|[^'])*)'|([^\s]+)/g;
100
+ let match;
101
+ while ((match = re.exec(command))) {
102
+ words.push((match[1] ?? match[2] ?? match[3] ?? '').replace(/\\(["'])/g, '$1'));
103
+ }
104
+ return words;
105
+ }
106
+
107
+ function shellHereDocContent(command) {
108
+ if (!command || typeof command !== 'string') return '';
109
+ const markerMatch = command.match(/<<-?\s*['"]?([A-Za-z0-9_.-]+)['"]?[^\r\n]*\r?\n/);
110
+ if (!markerMatch) return '';
111
+ const marker = markerMatch[1];
112
+ const start = (markerMatch.index || 0) + markerMatch[0].length;
113
+ const rest = command.slice(start);
114
+ const endRe = new RegExp(`\\r?\\n${escapeRegExp(marker)}(?:\\r?\\n|$)`);
115
+ const end = rest.search(endRe);
116
+ return end >= 0 ? rest.slice(0, end) : '';
117
+ }
118
+
119
+ function shellPythonWriteContent(command) {
120
+ if (!/\bpython(?:3)?\b/.test(command || '')) return '';
121
+ const script = shellHereDocContent(command) || command;
122
+ return pythonStringArg(script, /\.write_text\s*\(\s*/g) || pythonStringArg(script, /\.write\s*\(\s*/g);
123
+ }
124
+
125
+ function pythonStringArg(script, prefixRe) {
126
+ let prefix;
127
+ while ((prefix = prefixRe.exec(script))) {
128
+ const start = prefixRe.lastIndex;
129
+ const triple = script.slice(start, start + 3);
130
+ if (triple === "'''" || triple === '"""') {
131
+ const end = script.indexOf(triple, start + 3);
132
+ if (end !== -1) return script.slice(start + 3, end);
133
+ continue;
134
+ }
135
+ const quote = script[start];
136
+ if (quote !== '"' && quote !== "'") continue;
137
+ let out = '';
138
+ for (let i = start + 1; i < script.length; i++) {
139
+ const ch = script[i];
140
+ if (ch === '\\') {
141
+ out += script[i + 1] || '';
142
+ i += 1;
143
+ } else if (ch === quote) {
144
+ return out;
145
+ } else {
146
+ out += ch;
147
+ }
148
+ }
149
+ }
150
+ return '';
151
+ }
152
+
153
+ function escapeRegExp(value) {
154
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
155
+ }
156
+
157
+ function relativePath(filePath, cwd) {
158
+ try {
159
+ const rel = path.relative(cwd, filePath).split(path.sep).join('/');
160
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return filePath;
161
+ return rel.split(path.sep).join('/');
162
+ } catch {
163
+ return filePath;
164
+ }
165
+ }
166
+
167
+ function isInsideProject(filePath, cwd) {
168
+ try {
169
+ const rel = path.relative(cwd, filePath).split(path.sep).join('/');
170
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
171
+ } catch {
172
+ return false;
173
+ }
174
+ }
175
+
176
+ export {
177
+ shellCommand,
178
+ shellWriteDestination,
179
+ shellCopiedFileContent,
180
+ shellHereDocContent,
181
+ shellPythonWriteContent,
182
+ relativePath,
183
+ isInsideProject,
184
+ };
@@ -36,6 +36,15 @@ import {
36
36
  truthy,
37
37
  writeAuditLog,
38
38
  } from './hook-lib.mjs';
39
+ import {
40
+ shellCommand,
41
+ shellWriteDestination,
42
+ shellCopiedFileContent,
43
+ shellHereDocContent,
44
+ shellPythonWriteContent,
45
+ relativePath,
46
+ isInsideProject,
47
+ } from './hook-before-edit-shell.mjs';
39
48
 
40
49
  async function readStdin() {
41
50
  if (process.stdin.isTTY) return '';
@@ -172,171 +181,6 @@ function readExistingProjectFile(filePath, cwd) {
172
181
  }
173
182
  }
174
183
 
175
- function shellCommand(input) {
176
- if (typeof input.command === 'string') return input.command;
177
- if (input.args && typeof input.args.command === 'string') return input.args.command;
178
- return '';
179
- }
180
-
181
- function shellRedirectPath(command) {
182
- if (!command || typeof command !== 'string') return '';
183
- const match = command.match(/(?:^|[\s;&|])(?:>>?|1>>?)\s*(?:"([^"]+)"|'([^']+)'|([^<>\s]+))/);
184
- return (match?.[1] || match?.[2] || match?.[3] || '').trim();
185
- }
186
-
187
- function shellWriteDestination(command) {
188
- return shellRedirectPath(command) || shellTeeDestination(command) || shellCopyPaths(command)?.dest || shellPythonWriteDestination(command) || '';
189
- }
190
-
191
- function shellPythonWriteDestination(command) {
192
- if (!/\bpython(?:3)?\b/.test(command || '')) return '';
193
- const directPath = firstMatch(command, /(?:^|[^\w.])(?:pathlib\.)?Path\(\s*(["'])(.*?)\1\s*\)\s*\.write_text\s*\(/);
194
- if (directPath) return directPath;
195
-
196
- const pathsByVar = new Map();
197
- const assignmentRe = /\b([A-Za-z_]\w*)\s*=\s*(?:pathlib\.)?Path\(\s*(["'])(.*?)\2\s*\)/g;
198
- let assignment;
199
- while ((assignment = assignmentRe.exec(command))) {
200
- pathsByVar.set(assignment[1], assignment[3]);
201
- }
202
-
203
- const writeVarRe = /\b([A-Za-z_]\w*)\.write_text\s*\(/g;
204
- let writeVar;
205
- while ((writeVar = writeVarRe.exec(command))) {
206
- const candidate = pathsByVar.get(writeVar[1]);
207
- if (candidate) return candidate;
208
- }
209
-
210
- return firstMatch(command, /\bopen\(\s*(["'])(.*?)\1\s*,\s*(["'])[wax](?:\+)?b?\3/);
211
- }
212
-
213
- function firstMatch(value, re) {
214
- const match = String(value || '').match(re);
215
- return (match?.[2] || '').trim();
216
- }
217
-
218
- function shellTeeDestination(command) {
219
- const words = shellWords(command);
220
- const teeIndex = words.findIndex((word) => path.basename(word) === 'tee');
221
- if (teeIndex === -1) return '';
222
- for (const word of words.slice(teeIndex + 1)) {
223
- if (['&&', '||', ';', '|'].includes(word)) break;
224
- if (word === '--') continue;
225
- if (word.startsWith('-')) continue;
226
- return word;
227
- }
228
- return '';
229
- }
230
-
231
- function shellCopiedFileContent(command, cwd) {
232
- const source = shellCopyPaths(command)?.source;
233
- if (!source) return '';
234
- const sourcePath = path.isAbsolute(source) ? source : path.resolve(cwd, source);
235
- if (!isInsideProject(sourcePath, cwd)) return '';
236
- if (SENSITIVE_PATH.test(sourcePath) || isGeneratedPath(sourcePath, cwd)) return '';
237
- try {
238
- const stat = fs.statSync(sourcePath);
239
- if (!stat.isFile() || stat.size > 1024 * 1024) return '';
240
- return fs.readFileSync(sourcePath, 'utf-8');
241
- } catch {
242
- return '';
243
- }
244
- }
245
-
246
- function shellCopyPaths(command) {
247
- const words = shellWords(command);
248
- if (words.length < 3 || path.basename(words[0]) !== 'cp') return null;
249
- const args = [];
250
- for (const word of words.slice(1)) {
251
- if (['&&', '||', ';', '|'].includes(word)) break;
252
- if (word === '--') continue;
253
- if (word.startsWith('-')) continue;
254
- args.push(word);
255
- }
256
- if (args.length < 2) return null;
257
- return { source: args[args.length - 2], dest: args[args.length - 1] };
258
- }
259
-
260
- function shellWords(command) {
261
- if (!command || typeof command !== 'string') return [];
262
- const words = [];
263
- const re = /"((?:\\"|[^"])*)"|'((?:\\'|[^'])*)'|([^\s]+)/g;
264
- let match;
265
- while ((match = re.exec(command))) {
266
- words.push((match[1] ?? match[2] ?? match[3] ?? '').replace(/\\(["'])/g, '$1'));
267
- }
268
- return words;
269
- }
270
-
271
- function shellHereDocContent(command) {
272
- if (!command || typeof command !== 'string') return '';
273
- const markerMatch = command.match(/<<-?\s*['"]?([A-Za-z0-9_.-]+)['"]?[^\r\n]*\r?\n/);
274
- if (!markerMatch) return '';
275
- const marker = markerMatch[1];
276
- const start = (markerMatch.index || 0) + markerMatch[0].length;
277
- const rest = command.slice(start);
278
- const endRe = new RegExp(`\\r?\\n${escapeRegExp(marker)}(?:\\r?\\n|$)`);
279
- const end = rest.search(endRe);
280
- return end >= 0 ? rest.slice(0, end) : '';
281
- }
282
-
283
- function shellPythonWriteContent(command) {
284
- if (!/\bpython(?:3)?\b/.test(command || '')) return '';
285
- const script = shellHereDocContent(command) || command;
286
- return pythonStringArg(script, /\.write_text\s*\(\s*/g) || pythonStringArg(script, /\.write\s*\(\s*/g);
287
- }
288
-
289
- function pythonStringArg(script, prefixRe) {
290
- let prefix;
291
- while ((prefix = prefixRe.exec(script))) {
292
- const start = prefixRe.lastIndex;
293
- const triple = script.slice(start, start + 3);
294
- if (triple === "'''" || triple === '"""') {
295
- const end = script.indexOf(triple, start + 3);
296
- if (end !== -1) return script.slice(start + 3, end);
297
- continue;
298
- }
299
- const quote = script[start];
300
- if (quote !== '"' && quote !== "'") continue;
301
- let out = '';
302
- for (let i = start + 1; i < script.length; i++) {
303
- const ch = script[i];
304
- if (ch === '\\') {
305
- out += script[i + 1] || '';
306
- i += 1;
307
- } else if (ch === quote) {
308
- return out;
309
- } else {
310
- out += ch;
311
- }
312
- }
313
- }
314
- return '';
315
- }
316
-
317
- function escapeRegExp(value) {
318
- return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
319
- }
320
-
321
- function relativePath(filePath, cwd) {
322
- try {
323
- const rel = path.relative(cwd, filePath).split(path.sep).join('/');
324
- if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return filePath;
325
- return rel.split(path.sep).join('/');
326
- } catch {
327
- return filePath;
328
- }
329
- }
330
-
331
- function isInsideProject(filePath, cwd) {
332
- try {
333
- const rel = path.relative(cwd, filePath).split(path.sep).join('/');
334
- return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
335
- } catch {
336
- return false;
337
- }
338
- }
339
-
340
184
  // The static HTML engine reads its input from disk, but preToolUse only has
341
185
  // the proposed content. Stage it in a temp file so html-engine targets get the
342
186
  // same DOM-structural rules pre-write that runHook applies post-edit.
@@ -0,0 +1,145 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { MONODESIGN_COMMAND } from './lib/provider.mjs';
4
+ import { ENVELOPE_PREFIX, HOOK_LOCAL_IGNORE_PATTERNS, EDIT_COUNT_THRESHOLD, safeReadJson, getCachePath } from './hook-lib-config.mjs';
5
+
6
+ const HOOK_IGNORE_MARKER_OPEN = '# monodesign-hook-ignore-start';
7
+ const HOOK_IGNORE_MARKER_CLOSE = '# monodesign-hook-ignore-end';
8
+ const CACHE_MAX_SESSIONS = 8;
9
+
10
+ export function readCache(cwd) {
11
+ const raw = safeReadJson(getCachePath(cwd));
12
+ if (!raw || typeof raw !== 'object' || raw.version !== 1) {
13
+ return { version: 1, sessions: {} };
14
+ }
15
+ return {
16
+ version: 1,
17
+ sessions: raw.sessions && typeof raw.sessions === 'object' ? raw.sessions : {},
18
+ };
19
+ }
20
+
21
+ export function persistCache(cwd, cache) {
22
+ const sessions = cache.sessions || {};
23
+ const ids = Object.keys(sessions);
24
+ if (ids.length > CACHE_MAX_SESSIONS) {
25
+ // Garbage-collect oldest sessions by updatedAt.
26
+ const ordered = ids
27
+ .map((id) => [id, sessions[id]?.updatedAt || 0])
28
+ .sort((a, b) => b[1] - a[1])
29
+ .slice(0, CACHE_MAX_SESSIONS);
30
+ const next = {};
31
+ for (const [id] of ordered) next[id] = sessions[id];
32
+ cache = { ...cache, sessions: next };
33
+ }
34
+ const target = getCachePath(cwd);
35
+ try {
36
+ ensureHookGitExcludes(cwd);
37
+ fs.mkdirSync(path.dirname(target), { recursive: true });
38
+ fs.writeFileSync(target, JSON.stringify(cache));
39
+ return true;
40
+ } catch {
41
+ return false;
42
+ }
43
+ }
44
+
45
+ export function ensureHookGitExcludes(cwd = process.cwd()) {
46
+ try {
47
+ const target = resolveHookGitExcludeTarget(cwd);
48
+ if (!target) {
49
+ return { mode: 'none', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
50
+ }
51
+
52
+ const patterns = target.patternPrefix
53
+ ? HOOK_LOCAL_IGNORE_PATTERNS.map((pattern) => `${target.patternPrefix}/${pattern}`)
54
+ : [...HOOK_LOCAL_IGNORE_PATTERNS];
55
+ const markerSuffix = target.patternPrefix || '.';
56
+ const markerOpen = `${HOOK_IGNORE_MARKER_OPEN} ${markerSuffix}`;
57
+ const markerClose = `${HOOK_IGNORE_MARKER_CLOSE} ${markerSuffix}`;
58
+ const existing = fs.existsSync(target.path) ? fs.readFileSync(target.path, 'utf-8') : '';
59
+ const block = [markerOpen, ...patterns, markerClose].join('\n');
60
+ const markerRe = new RegExp(`${escapeRegExp(markerOpen)}[\\s\\S]*?${escapeRegExp(markerClose)}`);
61
+
62
+ let updated;
63
+ if (markerRe.test(existing)) {
64
+ updated = existing.replace(markerRe, block);
65
+ } else {
66
+ const prefix = existing.length === 0 ? '' : existing.endsWith('\n') ? existing : `${existing}\n`;
67
+ updated = `${prefix}${prefix.endsWith('\n\n') || prefix === '' ? '' : '\n'}${block}\n`;
68
+ }
69
+
70
+ if (updated !== existing) {
71
+ fs.mkdirSync(path.dirname(target.path), { recursive: true });
72
+ fs.writeFileSync(target.path, updated, 'utf-8');
73
+ }
74
+
75
+ return {
76
+ mode: 'git-info-exclude',
77
+ file: path.relative(path.resolve(cwd), target.path).split(path.sep).join('/'),
78
+ changed: updated !== existing,
79
+ patterns,
80
+ };
81
+ } catch {
82
+ return { mode: 'error', changed: false, patterns: [...HOOK_LOCAL_IGNORE_PATTERNS] };
83
+ }
84
+ }
85
+
86
+ function resolveHookGitExcludeTarget(cwd) {
87
+ const start = path.resolve(cwd);
88
+ let dir = start;
89
+ while (true) {
90
+ const dotGit = path.join(dir, '.git');
91
+ if (fs.existsSync(dotGit)) {
92
+ const gitDir = resolveGitDir(dotGit, dir);
93
+ if (!gitDir) return null;
94
+ const relPrefix = path.relative(dir, start).split(path.sep).join('/');
95
+ return {
96
+ path: path.join(gitDir, 'info', 'exclude'),
97
+ patternPrefix: relPrefix && relPrefix !== '.' ? relPrefix : '',
98
+ };
99
+ }
100
+ const parent = path.dirname(dir);
101
+ if (parent === dir) return null;
102
+ dir = parent;
103
+ }
104
+ }
105
+
106
+ function resolveGitDir(dotGit, worktreeDir) {
107
+ const stat = fs.statSync(dotGit);
108
+ if (stat.isDirectory()) return dotGit;
109
+ if (!stat.isFile()) return null;
110
+
111
+ const body = fs.readFileSync(dotGit, 'utf-8').trim();
112
+ const match = body.match(/^gitdir:\s*(.+)$/i);
113
+ if (!match) return null;
114
+ return path.isAbsolute(match[1]) ? match[1] : path.resolve(worktreeDir, match[1]);
115
+ }
116
+
117
+ function escapeRegExp(value) {
118
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
119
+ }
120
+
121
+ export function ensureSession(cache, sessionId) {
122
+ if (!cache.sessions[sessionId]) {
123
+ cache.sessions[sessionId] = { updatedAt: Date.now(), files: {} };
124
+ }
125
+ return cache.sessions[sessionId];
126
+ }
127
+
128
+ export function ensureFile(cache, sessionId, filePath) {
129
+ const session = ensureSession(cache, sessionId);
130
+ if (!session.files[filePath]) {
131
+ session.files[filePath] = { editCount: 0, findings: [] };
132
+ }
133
+ return session.files[filePath];
134
+ }
135
+
136
+ export function bumpEditCount(cache, sessionId, filePath) {
137
+ const fileEntry = ensureFile(cache, sessionId, filePath);
138
+ fileEntry.editCount = (fileEntry.editCount || 0) + 1;
139
+ ensureSession(cache, sessionId).updatedAt = Date.now();
140
+ return fileEntry.editCount;
141
+ }
142
+
143
+ export function suppressionNotice(filePath) {
144
+ return `${ENVELOPE_PREFIX} Suppressing further design hints on ${filePath}. More than ${EDIT_COUNT_THRESHOLD} edits in this session reached. Run ${MONODESIGN_COMMAND} audit to revisit.`;
145
+ }