@llman-sdd/core 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/package.json +6 -3
  2. package/src/archive/freeze.ts +0 -13
  3. package/src/archive/frozenCard.ts +1 -10
  4. package/src/archive/ignoreChain.ts +2 -6
  5. package/src/archive/sevenzip.ts +0 -1
  6. package/src/change/closeOutHarness.ts +17 -0
  7. package/src/change/collect.ts +0 -5
  8. package/src/change/frontmatter.ts +15 -7
  9. package/src/change/id.ts +0 -2
  10. package/src/change/lifecycle.ts +1 -38
  11. package/src/config/changeId.ts +0 -2
  12. package/src/config/load.ts +0 -4
  13. package/src/config/schema.ts +24 -0
  14. package/src/git/spawnGit.ts +0 -3
  15. package/src/hints/jitHints.ts +82 -0
  16. package/src/index.ts +455 -3
  17. package/src/init/defaultConfig.ts +2 -0
  18. package/src/init/init.ts +61 -20
  19. package/src/init/uncommentConfig.ts +909 -0
  20. package/src/locale.ts +0 -2
  21. package/src/project/migrateNotes.ts +0 -9
  22. package/src/project/migrations.ts +70 -0
  23. package/src/report/graph/analysis.ts +0 -4
  24. package/src/report/graph/nodes.ts +0 -6
  25. package/src/report/show.ts +7 -23
  26. package/src/report/specHelpers.ts +10 -14
  27. package/src/review/review.ts +0 -12
  28. package/src/spec/assignSpecIds.ts +0 -3
  29. package/src/spec/authoring.ts +14 -26
  30. package/src/spec/ir.ts +14 -5
  31. package/src/spec/keywords.ts +0 -2
  32. package/src/spec/machineKey.ts +49 -0
  33. package/src/spec/migrateNative.ts +4 -18
  34. package/src/spec/parser.ts +10 -19
  35. package/src/spec/reqRef.ts +135 -0
  36. package/src/studio/changeScope.ts +50 -0
  37. package/src/studio/changeScopeDiff.ts +195 -0
  38. package/src/studio/contracts.ts +493 -0
  39. package/src/studio/decisionTree.ts +206 -0
  40. package/src/studio/deeplink.ts +116 -0
  41. package/src/studio/demos.ts +167 -0
  42. package/src/studio/diff.ts +494 -0
  43. package/src/studio/drift.ts +738 -0
  44. package/src/studio/extract.ts +360 -0
  45. package/src/studio/featureSync.ts +592 -0
  46. package/src/studio/forest.ts +570 -0
  47. package/src/studio/index.ts +32 -0
  48. package/src/studio/model.ts +254 -0
  49. package/src/studio/revisions.ts +476 -0
  50. package/src/studio/search.ts +337 -0
  51. package/src/studio/store.ts +811 -0
  52. package/src/studio/sync.ts +912 -0
  53. package/src/studio/textfold.ts +72 -0
  54. package/src/studio/time.ts +107 -0
  55. package/src/studio/validate.ts +363 -0
  56. package/src/templates/embedded.ts +4 -6
  57. package/src/templates/engine.ts +1 -1
  58. package/src/templates/skills.ts +71 -49
  59. package/src/theorems/guard.ts +52 -0
  60. package/src/theorems/index.ts +56 -0
  61. package/src/theorems/migrate.ts +133 -0
  62. package/src/theorems/schema.ts +67 -0
  63. package/src/theorems/scope.ts +68 -0
  64. package/src/theorems/serialize.ts +60 -0
  65. package/src/theorems/transactionMachine.ts +247 -0
  66. package/src/theorems/validate.ts +141 -0
  67. package/src/util/nextNumber.ts +0 -2
  68. package/src/validation/changeCheck.ts +0 -24
  69. package/src/validation/flowAndNesting.ts +434 -0
  70. package/src/validation/harness.ts +108 -65
  71. package/src/validation/validate.ts +26 -12
  72. package/src/validation/xstateTransitions.ts +483 -184
  73. package/templates/zh-Hans/llmanspec-agents-stub.md +17 -2
  74. package/templates/zh-Hans/skills/llman-sdd-autopilot/SKILL.md +34 -0
  75. package/templates/zh-Hans/skills/llman-sdd-change/SKILL.md +44 -0
  76. package/templates/zh-Hans/skills/llman-sdd-change/playbooks/archive.md +15 -0
  77. package/templates/zh-Hans/skills/llman-sdd-change/playbooks/draft.md +9 -0
  78. package/templates/zh-Hans/skills/llman-sdd-review/SKILL.md +71 -0
  79. package/templates/zh-Hans/skills/llman-sdd-specs/SKILL.md +70 -0
  80. package/templates/zh-Hans/skills/llman-sdd-specs/playbooks/compact.md +12 -0
  81. package/templates/zh-Hans/skills/llman-sdd-specs/playbooks/doctor.md +26 -0
  82. package/templates/zh-Hans/skills/llman-sdd-specs/references/graph-dsl.md +33 -0
  83. package/templates/zh-Hans/skills/llman-sdd-studio/SKILL.md +33 -0
  84. package/templates/zh-Hans/skills/llman-sdd-studio/playbooks/collab.md +20 -0
  85. package/templates/zh-Hans/skills/llman-sdd-studio/playbooks/drift.md +52 -0
  86. package/templates/zh-Hans/skills/llman-sdd-studio/playbooks/onboard.md +33 -0
  87. package/templates/zh-Hans/units/skills/cli-footer.md +2 -2
  88. package/templates/zh-Hans/agents-root-stub.md +0 -9
  89. package/templates/zh-Hans/skills/llman-sdd-apply-cycle.md +0 -69
  90. package/templates/zh-Hans/skills/llman-sdd-apply.md +0 -116
  91. package/templates/zh-Hans/skills/llman-sdd-arch-review.md +0 -58
  92. package/templates/zh-Hans/skills/llman-sdd-archive.md +0 -78
  93. package/templates/zh-Hans/skills/llman-sdd-continue.md +0 -34
  94. package/templates/zh-Hans/skills/llman-sdd-draft.md +0 -53
  95. package/templates/zh-Hans/skills/llman-sdd-explore.md +0 -63
  96. package/templates/zh-Hans/skills/llman-sdd-ff.md +0 -34
  97. package/templates/zh-Hans/skills/llman-sdd-graph.md +0 -56
  98. package/templates/zh-Hans/skills/llman-sdd-propose.md +0 -106
  99. package/templates/zh-Hans/skills/llman-sdd-quick.md +0 -40
  100. package/templates/zh-Hans/skills/llman-sdd-research.md +0 -35
  101. package/templates/zh-Hans/skills/llman-sdd-specs-compact.md +0 -42
  102. package/templates/zh-Hans/skills/llman-sdd-validate.md +0 -28
  103. package/templates/zh-Hans/skills/llman-sdd-verify.md +0 -77
  104. package/templates/zh-Hans/skills/llman-sdd-wayfinder.md +0 -83
  105. package/templates/zh-Hans/units/skills/ethics-governance.md +0 -6
  106. package/templates/zh-Hans/units/skills/git-native-flow.md +0 -56
  107. package/templates/zh-Hans/units/skills/human-readable-summary.md +0 -9
  108. package/templates/zh-Hans/units/skills/stage-guard.md +0 -17
  109. package/templates/zh-Hans/units/skills/structured-protocol.md +0 -19
  110. package/templates/zh-Hans/units/skills/validation-hints.md +0 -20
  111. package/templates/zh-Hans/units/skills/version-drift.md +0 -3
  112. package/templates/zh-Hans/units/spec/feature-contract.md +0 -8
@@ -0,0 +1,909 @@
1
+ import { parse } from 'smol-toml';
2
+
3
+ export const UNCOMMENT_CONFIG_CANDIDATES = [
4
+ '.uncomment.toml',
5
+ '.uncommentrc.toml',
6
+ 'uncomment.toml',
7
+ ] as const;
8
+
9
+ export const LLMAN_UNCOMMENT_PRESERVE_PATTERNS = ['@llmanspec:', 'LLMANSPEC:'] as const;
10
+
11
+ export const LLMAN_UNCOMMENT_EXCLUDES = [
12
+ 'llmanspec/**',
13
+ '.llman-sdd/**',
14
+ '.agents/skills/llman-sdd-*/**',
15
+ ] as const;
16
+
17
+ export interface UncommentPatchResult {
18
+ changed: boolean;
19
+ content: string;
20
+ addedPreserve: string[];
21
+ addedExclude: string[];
22
+ warning?: string;
23
+ }
24
+
25
+ type TomlTable = Record<string, unknown>;
26
+ type MultilineState = null | '"""' | "'''";
27
+
28
+ interface TableHeader {
29
+ line: number;
30
+ keys: string[];
31
+ arrayTable: boolean;
32
+ }
33
+
34
+ interface TableScan {
35
+ boundaries: number[];
36
+ headers: TableHeader[];
37
+ }
38
+
39
+ interface ArrayBounds {
40
+ openLine: number;
41
+ openCol: number;
42
+ closeLine: number;
43
+ closeCol: number;
44
+ }
45
+
46
+ interface OffsetSpan {
47
+ start: number;
48
+ end: number;
49
+ }
50
+
51
+ function isTable(value: unknown): value is TomlTable {
52
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
53
+ }
54
+
55
+ function asStringArray(value: unknown): string[] | null {
56
+ if (!Array.isArray(value)) return null;
57
+ const items: string[] = [];
58
+ for (const item of value) {
59
+ if (typeof item !== 'string') return null;
60
+ items.push(item);
61
+ }
62
+ return items;
63
+ }
64
+
65
+ function errorMessage(error: unknown): string {
66
+ return error instanceof Error ? (error.message.split('\n')[0] ?? '') : String(error);
67
+ }
68
+
69
+ function escapeTomlString(value: string): string {
70
+ return `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`;
71
+ }
72
+
73
+ function escapeRegExp(value: string): string {
74
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
75
+ }
76
+
77
+ function leadingWhitespace(line: string): string {
78
+ return /^[ \t]*/u.exec(line)?.[0] ?? '';
79
+ }
80
+
81
+ function dominantEol(content: string): '\r\n' | '\n' {
82
+ let crlf = 0;
83
+ let lf = 0;
84
+ for (let index = 0; index < content.length; index += 1) {
85
+ if (content[index] !== '\n') continue;
86
+ if (index > 0 && content[index - 1] === '\r') crlf += 1;
87
+ else lf += 1;
88
+ }
89
+ return crlf > lf ? '\r\n' : '\n';
90
+ }
91
+
92
+ /** Highest-priority existing config among `.uncomment.toml` > `.uncommentrc.toml` > `uncomment.toml`. */
93
+ export function findUncommentConfig(exists: (path: string) => boolean): string | null {
94
+ for (const candidate of UNCOMMENT_CONFIG_CANDIDATES) {
95
+ if (exists(candidate)) return candidate;
96
+ }
97
+ return null;
98
+ }
99
+
100
+ /**
101
+ * Match a TOML 1.0 multi-line closing delimiter (`"""` or `'''`), consuming up
102
+ * to two extra trailing quotes that belong to the string content (e.g. `"""foo""""`).
103
+ */
104
+ function consumeMultilineClose(text: string, index: number, quote: '"' | "'"): number {
105
+ const delim = quote.repeat(3);
106
+ if (!text.startsWith(delim, index)) return 0;
107
+ let extra = 0;
108
+ while (extra < 2 && text[index + 3 + extra] === quote) extra += 1;
109
+ return 3 + extra;
110
+ }
111
+
112
+ /**
113
+ * Advance the TOML string state across one line. Only multi-line strings
114
+ * (`"""..."""` and `'''...'''`) survive a line break; basic and literal strings
115
+ * always close on their own line.
116
+ */
117
+ function advanceLineState(line: string, start: MultilineState): MultilineState {
118
+ let state = start;
119
+ let index = 0;
120
+ while (index < line.length) {
121
+ if (state === '"""') {
122
+ if (line[index] === '\\') {
123
+ index += 2;
124
+ continue;
125
+ }
126
+ const closeLen = consumeMultilineClose(line, index, '"');
127
+ if (closeLen > 0) {
128
+ state = null;
129
+ index += closeLen;
130
+ continue;
131
+ }
132
+ index += 1;
133
+ continue;
134
+ }
135
+ if (state === "'''") {
136
+ const closeLen = consumeMultilineClose(line, index, "'");
137
+ if (closeLen > 0) {
138
+ state = null;
139
+ index += closeLen;
140
+ continue;
141
+ }
142
+ index += 1;
143
+ continue;
144
+ }
145
+ const char = line[index];
146
+ if (char === '#') break;
147
+ if (char === '"') {
148
+ if (line.startsWith('"""', index)) {
149
+ state = '"""';
150
+ index += 3;
151
+ continue;
152
+ }
153
+ index += 1;
154
+ while (index < line.length) {
155
+ if (line[index] === '\\') {
156
+ index += 2;
157
+ continue;
158
+ }
159
+ if (line[index] === '"') {
160
+ index += 1;
161
+ break;
162
+ }
163
+ index += 1;
164
+ }
165
+ continue;
166
+ }
167
+ if (char === "'") {
168
+ if (line.startsWith("'''", index)) {
169
+ state = "'''";
170
+ index += 3;
171
+ continue;
172
+ }
173
+ index += 1;
174
+ while (index < line.length) {
175
+ if (line[index] === "'") {
176
+ index += 1;
177
+ break;
178
+ }
179
+ index += 1;
180
+ }
181
+ continue;
182
+ }
183
+ index += 1;
184
+ }
185
+ return state;
186
+ }
187
+
188
+ /** Multi-line string state at the start of each line. */
189
+ function scanLineStates(lines: readonly string[]): MultilineState[] {
190
+ const states: MultilineState[] = [];
191
+ let state: MultilineState = null;
192
+ for (const line of lines) {
193
+ states.push(state);
194
+ state = advanceLineState(line, state);
195
+ }
196
+ return states;
197
+ }
198
+
199
+ /** Parse `[a.b]`, `[[a]]`, `["global"]`, `[patterns."foo[bar]"]` into its key path. */
200
+ function parseTableHeader(line: string): { keys: string[]; arrayTable: boolean } | null {
201
+ let index = 0;
202
+ while (index < line.length && (line[index] === ' ' || line[index] === '\t')) index += 1;
203
+ if (line[index] !== '[') return null;
204
+ const arrayTable = line[index + 1] === '[';
205
+ index += arrayTable ? 2 : 1;
206
+ const keys: string[] = [];
207
+ for (;;) {
208
+ while (index < line.length && (line[index] === ' ' || line[index] === '\t')) index += 1;
209
+ if (index >= line.length) return null;
210
+ const char = line[index];
211
+ if (char === '"') {
212
+ index += 1;
213
+ let key = '';
214
+ while (index < line.length) {
215
+ const inner = line[index];
216
+ if (inner === '\\') {
217
+ const escape = line[index + 1];
218
+ if (escape === undefined) return null;
219
+ key += escape === 'n' ? '\n' : escape === 't' ? '\t' : escape;
220
+ index += 2;
221
+ continue;
222
+ }
223
+ if (inner === '"') {
224
+ index += 1;
225
+ break;
226
+ }
227
+ key += inner;
228
+ index += 1;
229
+ }
230
+ keys.push(key);
231
+ } else if (char === "'") {
232
+ index += 1;
233
+ let key = '';
234
+ while (index < line.length) {
235
+ if (line[index] === "'") {
236
+ index += 1;
237
+ break;
238
+ }
239
+ key += line[index];
240
+ index += 1;
241
+ }
242
+ keys.push(key);
243
+ } else {
244
+ const start = index;
245
+ while (index < line.length && /[A-Za-z0-9_-]/u.test(line[index] ?? '')) index += 1;
246
+ if (index === start) return null;
247
+ keys.push(line.slice(start, index));
248
+ }
249
+ while (index < line.length && (line[index] === ' ' || line[index] === '\t')) index += 1;
250
+ if (index >= line.length) return null;
251
+ if (line[index] === '.') {
252
+ index += 1;
253
+ continue;
254
+ }
255
+ if (line[index] !== ']') return null;
256
+ index += 1;
257
+ if (arrayTable) {
258
+ if (line[index] !== ']') return null;
259
+ index += 1;
260
+ }
261
+ break;
262
+ }
263
+ while (index < line.length && (line[index] === ' ' || line[index] === '\t')) index += 1;
264
+ if (index >= line.length) return { keys, arrayTable };
265
+ return line[index] === '#' ? { keys, arrayTable } : null;
266
+ }
267
+
268
+ /**
269
+ * Track bracket nesting across one line outside strings and comments so
270
+ * multi-line nested arrays (e.g. `matrix = [\n [1, 2],\n]`) are never mistaken
271
+ * for top-level table headers.
272
+ */
273
+ function advanceBracketDepth(line: string, startState: MultilineState, startDepth: number): number {
274
+ let state = startState;
275
+ let depth = startDepth;
276
+ let index = 0;
277
+ while (index < line.length) {
278
+ if (state === '"""') {
279
+ if (line[index] === '\\') {
280
+ index += 2;
281
+ continue;
282
+ }
283
+ const closeLen = consumeMultilineClose(line, index, '"');
284
+ if (closeLen > 0) {
285
+ state = null;
286
+ index += closeLen;
287
+ continue;
288
+ }
289
+ index += 1;
290
+ continue;
291
+ }
292
+ if (state === "'''") {
293
+ const closeLen = consumeMultilineClose(line, index, "'");
294
+ if (closeLen > 0) {
295
+ state = null;
296
+ index += closeLen;
297
+ continue;
298
+ }
299
+ index += 1;
300
+ continue;
301
+ }
302
+ const char = line[index];
303
+ if (char === '#') break;
304
+ if (char === '"') {
305
+ if (line.startsWith('"""', index)) {
306
+ state = '"""';
307
+ index += 3;
308
+ continue;
309
+ }
310
+ index += 1;
311
+ while (index < line.length) {
312
+ if (line[index] === '\\') {
313
+ index += 2;
314
+ continue;
315
+ }
316
+ if (line[index] === '"') {
317
+ index += 1;
318
+ break;
319
+ }
320
+ index += 1;
321
+ }
322
+ continue;
323
+ }
324
+ if (char === "'") {
325
+ if (line.startsWith("'''", index)) {
326
+ state = "'''";
327
+ index += 3;
328
+ continue;
329
+ }
330
+ index += 1;
331
+ while (index < line.length) {
332
+ if (line[index] === "'") {
333
+ index += 1;
334
+ break;
335
+ }
336
+ index += 1;
337
+ }
338
+ continue;
339
+ }
340
+ if (char === '[' || char === '{') depth += 1;
341
+ else if (char === ']' || char === '}') depth = Math.max(0, depth - 1);
342
+ index += 1;
343
+ }
344
+ return depth;
345
+ }
346
+
347
+ /**
348
+ * Top-level table boundaries and parsed headers. Lines inside multi-line
349
+ * strings or nested arrays/inline-tables are skipped so `[1, 2]` on its own
350
+ * line cannot truncate the enclosing table.
351
+ */
352
+ function scanTableStructure(
353
+ lines: readonly string[],
354
+ states: readonly MultilineState[],
355
+ ): TableScan {
356
+ const boundaries: number[] = [];
357
+ const headers: TableHeader[] = [];
358
+ let depth = 0;
359
+ for (let line = 0; line < lines.length; line += 1) {
360
+ const startState = states[line] ?? null;
361
+ const text = lines[line] ?? '';
362
+ if (startState === null && depth === 0) {
363
+ const first = text.trimStart()[0];
364
+ if (first === '[') {
365
+ boundaries.push(line);
366
+ const parsed = parseTableHeader(text);
367
+ if (parsed !== null) headers.push({ line, ...parsed });
368
+ continue;
369
+ }
370
+ }
371
+ depth = advanceBracketDepth(text, startState, depth);
372
+ }
373
+ return { boundaries, headers };
374
+ }
375
+
376
+ function locateGlobalHeader(scan: TableScan): number {
377
+ for (const header of scan.headers) {
378
+ if (!header.arrayTable && header.keys.length === 1 && header.keys[0] === 'global') {
379
+ return header.line;
380
+ }
381
+ }
382
+ return -1;
383
+ }
384
+
385
+ function locateBlockEnd(scan: TableScan, headerIndex: number, lineCount: number): number {
386
+ for (const boundary of scan.boundaries) {
387
+ if (boundary > headerIndex) return boundary;
388
+ }
389
+ return lineCount;
390
+ }
391
+
392
+ function locateKeyLine(
393
+ lines: readonly string[],
394
+ states: readonly MultilineState[],
395
+ headerIndex: number,
396
+ blockEnd: number,
397
+ key: string,
398
+ ): number {
399
+ if (headerIndex === -1) return -1;
400
+ const escaped = escapeRegExp(key);
401
+ const pattern = new RegExp(`^[ \\t]*(?:"${escaped}"|'${escaped}'|${escaped})[ \\t]*=`, 'u');
402
+ for (let index = headerIndex + 1; index < blockEnd; index += 1) {
403
+ if (states[index] !== null) continue;
404
+ if (pattern.test(lines[index] ?? '')) return index;
405
+ }
406
+ return -1;
407
+ }
408
+
409
+ /** Index of the assignment `=` on a key line, ignoring string contents and comments. */
410
+ function assignmentEquals(line: string): number {
411
+ let state: 'code' | 'basic' | 'literal' = 'code';
412
+ for (let index = 0; index < line.length; index += 1) {
413
+ const char = line[index];
414
+ if (state === 'basic') {
415
+ if (char === '\\') {
416
+ index += 1;
417
+ continue;
418
+ }
419
+ if (char === '"') state = 'code';
420
+ continue;
421
+ }
422
+ if (state === 'literal') {
423
+ if (char === "'") state = 'code';
424
+ continue;
425
+ }
426
+ if (char === '#') return -1;
427
+ if (char === '"') {
428
+ state = 'basic';
429
+ continue;
430
+ }
431
+ if (char === "'") {
432
+ state = 'literal';
433
+ continue;
434
+ }
435
+ if (char === '=') return index;
436
+ }
437
+ return -1;
438
+ }
439
+
440
+ /** Bounds of the array value assigned on `keyLine`, tracking multi-line strings. */
441
+ function locateArray(
442
+ lines: readonly string[],
443
+ states: readonly MultilineState[],
444
+ keyLine: number,
445
+ blockEnd: number,
446
+ ): ArrayBounds | null {
447
+ const keyLineText = lines[keyLine] ?? '';
448
+ const equals = assignmentEquals(keyLineText);
449
+ if (equals === -1) return null;
450
+ let openCol = -1;
451
+ let depth = 0;
452
+ let state: MultilineState = null;
453
+ let line = keyLine;
454
+ let column = equals + 1;
455
+ while (line < blockEnd) {
456
+ const text = lines[line] ?? '';
457
+ while (column < text.length) {
458
+ const char = text[column];
459
+ if (state === '"""') {
460
+ if (char === '\\') {
461
+ column += 2;
462
+ continue;
463
+ }
464
+ const closeLen = consumeMultilineClose(text, column, '"');
465
+ if (closeLen > 0) {
466
+ state = null;
467
+ column += closeLen;
468
+ continue;
469
+ }
470
+ column += 1;
471
+ continue;
472
+ }
473
+ if (state === "'''") {
474
+ const closeLen = consumeMultilineClose(text, column, "'");
475
+ if (closeLen > 0) {
476
+ state = null;
477
+ column += closeLen;
478
+ continue;
479
+ }
480
+ column += 1;
481
+ continue;
482
+ }
483
+ if (char === '#') break;
484
+ if (char === '"') {
485
+ if (text.startsWith('"""', column)) {
486
+ state = '"""';
487
+ column += 3;
488
+ continue;
489
+ }
490
+ column += 1;
491
+ while (column < text.length) {
492
+ if (text[column] === '\\') {
493
+ column += 2;
494
+ continue;
495
+ }
496
+ if (text[column] === '"') {
497
+ column += 1;
498
+ break;
499
+ }
500
+ column += 1;
501
+ }
502
+ continue;
503
+ }
504
+ if (char === "'") {
505
+ if (text.startsWith("'''", column)) {
506
+ state = "'''";
507
+ column += 3;
508
+ continue;
509
+ }
510
+ column += 1;
511
+ while (column < text.length) {
512
+ if (text[column] === "'") {
513
+ column += 1;
514
+ break;
515
+ }
516
+ column += 1;
517
+ }
518
+ continue;
519
+ }
520
+ if (char === '[') {
521
+ if (openCol === -1) {
522
+ openCol = column;
523
+ depth = 0;
524
+ }
525
+ depth += 1;
526
+ column += 1;
527
+ continue;
528
+ }
529
+ if (char === ']') {
530
+ if (openCol === -1) {
531
+ column += 1;
532
+ continue;
533
+ }
534
+ depth -= 1;
535
+ if (depth === 0) return { openLine: keyLine, openCol, closeLine: line, closeCol: column };
536
+ column += 1;
537
+ continue;
538
+ }
539
+ column += 1;
540
+ }
541
+ line += 1;
542
+ if (line >= blockEnd) break;
543
+ state = states[line] ?? null;
544
+ column = 0;
545
+ }
546
+ return null;
547
+ }
548
+
549
+ /** Array text between the brackets plus the start offset of every source line. */
550
+ function arrayContent(
551
+ lines: readonly string[],
552
+ bounds: ArrayBounds,
553
+ ): { text: string; starts: number[] } {
554
+ const parts: string[] = [];
555
+ const starts: number[] = [];
556
+ let offset = 0;
557
+ for (let line = bounds.openLine; line <= bounds.closeLine; line += 1) {
558
+ const text = lines[line] ?? '';
559
+ const from = line === bounds.openLine ? bounds.openCol + 1 : 0;
560
+ const to = line === bounds.closeLine ? bounds.closeCol : text.length;
561
+ const piece = text.slice(from, to);
562
+ starts.push(offset);
563
+ parts.push(piece);
564
+ offset += piece.length + 1;
565
+ }
566
+ return { text: parts.join('\n'), starts };
567
+ }
568
+
569
+ /**
570
+ * Top-level element spans of an array body. Commas at depth zero separate
571
+ * elements; strings, multi-line strings, comments and nested arrays are opaque.
572
+ * A trailing comment closes the element before the comment text.
573
+ */
574
+ function splitArrayElements(text: string): OffsetSpan[] {
575
+ const spans: OffsetSpan[] = [];
576
+ let state: 'code' | 'comment' | 'basic' | 'literal' | 'multiBasic' | 'multiLiteral' = 'code';
577
+ let depth = 0;
578
+ let elementStart = -1;
579
+ let index = 0;
580
+ const closeElement = (end: number): void => {
581
+ if (elementStart === -1) return;
582
+ let stop = end;
583
+ while (stop > elementStart && /\s/u.test(text[stop - 1] ?? '')) stop -= 1;
584
+ spans.push({ start: elementStart, end: stop });
585
+ elementStart = -1;
586
+ };
587
+ while (index < text.length) {
588
+ const char = text[index] ?? '';
589
+ if (state === 'comment') {
590
+ if (char === '\n') state = 'code';
591
+ index += 1;
592
+ continue;
593
+ }
594
+ if (state === 'multiBasic') {
595
+ if (char === '\\') {
596
+ index += 2;
597
+ continue;
598
+ }
599
+ const closeLen = consumeMultilineClose(text, index, '"');
600
+ if (closeLen > 0) {
601
+ state = 'code';
602
+ index += closeLen;
603
+ continue;
604
+ }
605
+ index += 1;
606
+ continue;
607
+ }
608
+ if (state === 'multiLiteral') {
609
+ const closeLen = consumeMultilineClose(text, index, "'");
610
+ if (closeLen > 0) {
611
+ state = 'code';
612
+ index += closeLen;
613
+ continue;
614
+ }
615
+ index += 1;
616
+ continue;
617
+ }
618
+ if (state === 'basic') {
619
+ if (char === '\\') {
620
+ index += 2;
621
+ continue;
622
+ }
623
+ if (char === '"') state = 'code';
624
+ index += 1;
625
+ continue;
626
+ }
627
+ if (state === 'literal') {
628
+ if (char === "'") state = 'code';
629
+ index += 1;
630
+ continue;
631
+ }
632
+ if (/\s/u.test(char)) {
633
+ index += 1;
634
+ continue;
635
+ }
636
+ if (char === '#') {
637
+ closeElement(index);
638
+ state = 'comment';
639
+ index += 1;
640
+ continue;
641
+ }
642
+ if (char === ',' && depth === 0) {
643
+ closeElement(index);
644
+ index += 1;
645
+ continue;
646
+ }
647
+ if (char === ']' || char === '}') {
648
+ depth -= 1;
649
+ index += 1;
650
+ continue;
651
+ }
652
+ if (elementStart === -1) elementStart = index;
653
+ if (char === '"') {
654
+ if (text.startsWith('"""', index)) {
655
+ state = 'multiBasic';
656
+ index += 3;
657
+ continue;
658
+ }
659
+ state = 'basic';
660
+ index += 1;
661
+ continue;
662
+ }
663
+ if (char === "'") {
664
+ if (text.startsWith("'''", index)) {
665
+ state = 'multiLiteral';
666
+ index += 3;
667
+ continue;
668
+ }
669
+ state = 'literal';
670
+ index += 1;
671
+ continue;
672
+ }
673
+ if (char === '[' || char === '{') {
674
+ depth += 1;
675
+ index += 1;
676
+ continue;
677
+ }
678
+ index += 1;
679
+ }
680
+ closeElement(text.length);
681
+ return spans;
682
+ }
683
+
684
+ /** Offset of the separating comma after an element (skipping blanks/comments), or -1. */
685
+ function findSeparatorAfter(text: string, from: number): number {
686
+ let index = from;
687
+ while (index < text.length) {
688
+ const char = text[index];
689
+ if (char === ' ' || char === '\t' || char === '\r' || char === '\n') {
690
+ index += 1;
691
+ continue;
692
+ }
693
+ if (char === '#') {
694
+ while (index < text.length && text[index] !== '\n') index += 1;
695
+ continue;
696
+ }
697
+ return char === ',' ? index : -1;
698
+ }
699
+ return -1;
700
+ }
701
+
702
+ function arrayBlock(key: string, items: readonly string[]): string[] {
703
+ return [`${key} = [`, ...items.map((item) => ` ${escapeTomlString(item)},`), ']'];
704
+ }
705
+
706
+ function eofLineIndex(lines: readonly string[]): number {
707
+ return lines.length > 0 && lines[lines.length - 1] === '' ? lines.length - 1 : lines.length;
708
+ }
709
+
710
+ function appendGlobalTable(
711
+ lines: readonly string[],
712
+ key: string,
713
+ items: readonly string[],
714
+ ): string[] {
715
+ const eof = eofLineIndex(lines);
716
+ const previous = lines[eof - 1] ?? '';
717
+ const separator = eof > 0 && previous.trim() !== '' ? [''] : [];
718
+ const block = ['[global]', ...arrayBlock(key, items)];
719
+ return [...lines.slice(0, eof), ...separator, ...block, ...lines.slice(eof)];
720
+ }
721
+
722
+ function insertKeyBlock(
723
+ lines: readonly string[],
724
+ headerIndex: number,
725
+ blockEnd: number,
726
+ key: string,
727
+ items: readonly string[],
728
+ ): string[] {
729
+ let insertAt = Math.min(blockEnd, eofLineIndex(lines));
730
+ while (insertAt > headerIndex + 1 && (lines[insertAt - 1] ?? '').trim() === '') insertAt -= 1;
731
+ return [...lines.slice(0, insertAt), ...arrayBlock(key, items), ...lines.slice(insertAt)];
732
+ }
733
+
734
+ /**
735
+ * Insert missing entries into an existing array without reformatting it: the
736
+ * last real element gains a comma when needed (before its trailing comment) and
737
+ * every new element is emitted with a trailing comma.
738
+ */
739
+ function insertArrayItems(
740
+ lines: readonly string[],
741
+ bounds: ArrayBounds,
742
+ items: readonly string[],
743
+ ): string[] {
744
+ const rendered = items.map((item) => escapeTomlString(item));
745
+ const closeLineText = lines[bounds.closeLine] ?? '';
746
+ if (bounds.closeLine === bounds.openLine) {
747
+ const inner = closeLineText.slice(bounds.openCol + 1, bounds.closeCol);
748
+ const trimmed = inner.replace(/[ \t]+$/u, '');
749
+ const inserted =
750
+ trimmed.trim() === ''
751
+ ? rendered.join(', ')
752
+ : trimmed.endsWith(',')
753
+ ? ` ${rendered.join(', ')}`
754
+ : `, ${rendered.join(', ')}`;
755
+ const nextLine = `${closeLineText.slice(0, bounds.openCol + 1)}${inner}${inserted}${closeLineText.slice(bounds.closeCol)}`;
756
+ return [...lines.slice(0, bounds.closeLine), nextLine, ...lines.slice(bounds.closeLine + 1)];
757
+ }
758
+ const { text, starts } = arrayContent(lines, bounds);
759
+ const spans = splitArrayElements(text);
760
+ const positionOf = (offset: number): { line: number; col: number } => {
761
+ let lineIndex = 0;
762
+ while (lineIndex + 1 < starts.length && (starts[lineIndex + 1] ?? 0) <= offset) lineIndex += 1;
763
+ const line = bounds.openLine + lineIndex;
764
+ const base = line === bounds.openLine ? bounds.openCol + 1 : 0;
765
+ return { line, col: offset - (starts[lineIndex] ?? 0) + base };
766
+ };
767
+ const nextLines = [...lines];
768
+ let insertLine: number;
769
+ let indent: string;
770
+ const last = spans[spans.length - 1];
771
+ if (last === undefined) {
772
+ insertLine = bounds.closeLine;
773
+ indent = `${leadingWhitespace(lines[bounds.openLine] ?? '')} `;
774
+ } else {
775
+ const sepOffset = findSeparatorAfter(text, last.end);
776
+ const position = positionOf(last.end);
777
+ const sepPos = sepOffset === -1 ? null : positionOf(sepOffset);
778
+ if (position.line === bounds.closeLine || sepPos?.line === bounds.closeLine) {
779
+ const target = nextLines[bounds.closeLine] ?? '';
780
+ const beforeClose = target.slice(0, bounds.closeCol);
781
+ const inserted = sepOffset === -1 ? `, ${rendered.join(', ')}` : ` ${rendered.join(', ')}`;
782
+ nextLines[bounds.closeLine] = `${beforeClose}${inserted}${target.slice(bounds.closeCol)}`;
783
+ return nextLines;
784
+ }
785
+ if (sepPos === null) {
786
+ const target = nextLines[position.line] ?? '';
787
+ nextLines[position.line] = `${target.slice(0, position.col)},${target.slice(position.col)}`;
788
+ insertLine = position.line + 1;
789
+ } else {
790
+ insertLine = sepPos.line + 1;
791
+ }
792
+ indent =
793
+ position.line === bounds.openLine
794
+ ? `${leadingWhitespace(lines[bounds.openLine] ?? '')} `
795
+ : leadingWhitespace(nextLines[position.line] ?? '');
796
+ }
797
+ const added = rendered.map((item) => `${indent}${item},`);
798
+ return [...nextLines.slice(0, insertLine), ...added, ...nextLines.slice(insertLine)];
799
+ }
800
+
801
+ function ensureGlobalTableEntry(
802
+ lines: readonly string[],
803
+ key: string,
804
+ items: readonly string[],
805
+ ): string[] {
806
+ const states = scanLineStates(lines);
807
+ const scan = scanTableStructure(lines, states);
808
+ const headerIndex = locateGlobalHeader(scan);
809
+ if (headerIndex === -1) return appendGlobalTable(lines, key, items);
810
+ const blockEnd = locateBlockEnd(scan, headerIndex, lines.length);
811
+ const keyLine = locateKeyLine(lines, states, headerIndex, blockEnd, key);
812
+ if (keyLine === -1) return insertKeyBlock(lines, headerIndex, blockEnd, key, items);
813
+ const bounds = locateArray(lines, states, keyLine, blockEnd);
814
+ if (bounds === null) return insertKeyBlock(lines, headerIndex, blockEnd, key, items);
815
+ return insertArrayItems(lines, bounds, items);
816
+ }
817
+
818
+ function verifyPatched(content: string): void {
819
+ const parsed = parse(content) as TomlTable;
820
+ const globalTable = parsed['global'];
821
+ if (!isTable(globalTable)) throw new Error('uncomment config patch lost the [global] table');
822
+ const preserve = asStringArray(globalTable['preserve_patterns']) ?? [];
823
+ const exclude = asStringArray(globalTable['exclude']) ?? [];
824
+ for (const item of LLMAN_UNCOMMENT_PRESERVE_PATTERNS) {
825
+ if (!preserve.includes(item))
826
+ throw new Error(`uncomment config patch lost preserve entry ${item}`);
827
+ }
828
+ for (const item of LLMAN_UNCOMMENT_EXCLUDES) {
829
+ if (!exclude.includes(item))
830
+ throw new Error(`uncomment config patch lost exclude entry ${item}`);
831
+ }
832
+ }
833
+
834
+ /**
835
+ * Idempotent, format-preserving patch of an existing uncomment config: ensure the
836
+ * llman-sdd preserve patterns and exclude globs without rewriting the user's
837
+ * schema directive, comments, other tables or array layout. Returns the raw
838
+ * content untouched (with a warning) whenever the file cannot be patched safely.
839
+ */
840
+ export function patchUncommentConfig(rawContent: string): UncommentPatchResult {
841
+ const unchanged = (warning?: string): UncommentPatchResult => ({
842
+ changed: false,
843
+ content: rawContent,
844
+ addedPreserve: [],
845
+ addedExclude: [],
846
+ ...(warning === undefined ? {} : { warning }),
847
+ });
848
+ let parsed: TomlTable;
849
+ try {
850
+ parsed = parse(rawContent) as TomlTable;
851
+ } catch (error) {
852
+ return unchanged(`existing config is not valid TOML (${errorMessage(error)})`);
853
+ }
854
+ const globalValue = parsed['global'];
855
+ if (globalValue !== undefined && !isTable(globalValue)) {
856
+ return unchanged("existing 'global' is not a table");
857
+ }
858
+ const globalTable = isTable(globalValue) ? globalValue : {};
859
+ const preserveValue = globalTable['preserve_patterns'];
860
+ const preserveList = preserveValue === undefined ? [] : asStringArray(preserveValue);
861
+ if (preserveList === null) {
862
+ return unchanged("existing 'global.preserve_patterns' is not an array of strings");
863
+ }
864
+ const excludeValue = globalTable['exclude'];
865
+ const excludeList = excludeValue === undefined ? [] : asStringArray(excludeValue);
866
+ if (excludeList === null) {
867
+ return unchanged("existing 'global.exclude' is not an array of strings");
868
+ }
869
+ const missingPreserve = LLMAN_UNCOMMENT_PRESERVE_PATTERNS.filter(
870
+ (item) => !preserveList.includes(item),
871
+ );
872
+ const missingExclude = LLMAN_UNCOMMENT_EXCLUDES.filter((item) => !excludeList.includes(item));
873
+ if (missingPreserve.length === 0 && missingExclude.length === 0) return unchanged();
874
+ const eol = dominantEol(rawContent);
875
+ const lines = rawContent.split(/\r?\n/u);
876
+ const states = scanLineStates(lines);
877
+ const scan = scanTableStructure(lines, states);
878
+ const headerIndex = locateGlobalHeader(scan);
879
+ if (globalValue !== undefined && headerIndex === -1) {
880
+ return unchanged("'global' is defined without a [global] table header");
881
+ }
882
+ const blockEnd =
883
+ headerIndex === -1 ? lines.length : locateBlockEnd(scan, headerIndex, lines.length);
884
+ for (const [key, present] of [
885
+ ['preserve_patterns', preserveValue !== undefined],
886
+ ['exclude', excludeValue !== undefined],
887
+ ] as const) {
888
+ if (present && locateKeyLine(lines, states, headerIndex, blockEnd, key) === -1) {
889
+ return unchanged(`cannot locate the existing '${key}' key in the [global] table`);
890
+ }
891
+ }
892
+ let nextLines = [...lines];
893
+ if (missingPreserve.length > 0)
894
+ nextLines = ensureGlobalTableEntry(nextLines, 'preserve_patterns', missingPreserve);
895
+ if (missingExclude.length > 0)
896
+ nextLines = ensureGlobalTableEntry(nextLines, 'exclude', missingExclude);
897
+ const nextContent = nextLines.join(eol);
898
+ try {
899
+ verifyPatched(nextContent);
900
+ } catch (error) {
901
+ return unchanged(`patched config failed verification (${errorMessage(error)})`);
902
+ }
903
+ return {
904
+ changed: true,
905
+ content: nextContent,
906
+ addedPreserve: missingPreserve,
907
+ addedExclude: missingExclude,
908
+ };
909
+ }