@aiwayds/dsh-model-sync 0.10.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1185 @@
1
+ // One-shot migrate-go support: a minimal YAML-subset reader + line-surgical
2
+ // editor for profile patch files (`<profileDir>/cordis.patch.yml`), plus the
3
+ // file-backed SettingsService adapter that lets the EXISTING migration engine
4
+ // (buildMigrationPlanFromDeps / applyMigration) drive a non-current profile.
5
+ //
6
+ // Why hand-rolled: this plugin keeps zero runtime dependencies (the whole
7
+ // @aiwayds plugin family convention), so there is no `yaml` import here. The
8
+ // parser accepts exactly the subset dsh profile patches use — block maps,
9
+ // block sequences, plain/quoted scalars, full-line comments, single-line flow
10
+ // collections, `!!js` expression lines — and REFUSES anything outside it
11
+ // (tabs, CRLF, unterminated constructs) with an actionable reason so a caller
12
+ // can fail closed and point at the manual migrate plan/apply path.
13
+ //
14
+ // Parse-time refusals (the "cannot silently write a file the host cannot
15
+ // load" rule, review Blocker A): every mapping key must be a BARE plain key —
16
+ // quoted keys, whitespace inside a key, and YAML indicator characters
17
+ // (#*&{[) in a key are refused; duplicate keys in the SAME mapping are
18
+ // refused (the host yaml rejects them, last-wins folding is not a valid
19
+ // edit basis); keys that the host yaml resolves to null/boolean/number
20
+ // (`~`, `true`, `1`, …) are refused because same-level spellings collapse
21
+ // into one key (`true` = `True`, `null` = `~`, `1` = `+1`) and the host
22
+ // rejects the document as duplicate-keyed (review M3); YAML anchors
23
+ // (`&name`), aliases (`*name`) and merge keys (`<<`) are refused anywhere in
24
+ // a value position. A colon-space (or trailing colon) in a plain VALUE
25
+ // position is refused: the parser used to accept `key: a: b` while the host
26
+ // yaml rejects the whole document (review M2). Tags (`!!`/`!`) keep the
27
+ // opaque-leaf behavior at block position: verbatim outside the edited
28
+ // providers tree, a refusal for any op whose target tree contains one — but
29
+ // INSIDE a flow collection a tag is refused outright, because flow values
30
+ // are decoded into the subset tree and a tagged leaf would silently become
31
+ // text (review M1). Flow scalars decode through the SAME unquoteYaml path as
32
+ // block-position quoted scalars, and flow entries that the host would parse
33
+ // differently (single-pair items like `[a: b]`, empty entries, comments
34
+ // inside the brackets) are refused, never guessed. All of these fail at
35
+ // PARSE time, so every consumer fails closed before a single byte is written.
36
+ //
37
+ // Round 3: flow brackets pair BY TYPE — `{a: b]` / `[a, b}` are refused (the
38
+ // host yaml rejects mismatched flow brackets; the old mixed depth counter
39
+ // accepted them and wrote an unloadable file). Properly nested single-line
40
+ // flow collections (`[{a: 1}]`, `{a: [b, c]}`) decode exactly like the host.
41
+ // Double-quoted scalars decode the host's common escape set
42
+ // (`\n \t \r \" \\ \0 \b \f \xXX \uXXXX \UXXXXXXXX`); any other escape
43
+ // REFUSES (conservative — the host either decodes it to a different
44
+ // character or rejects the document). Numeric-form KEYS outside the plain
45
+ // integer/decimal domain (`1e3`, `0x1F`, `1.`, `.5`, `.inf`, …) are refused,
46
+ // and numeric-form strings are QUOTED on write-back, so a rewritten value is
47
+ // never re-read by the host as a number.
48
+ //
49
+ // Editing strategy: never re-serialize the document. Each settings op becomes
50
+ // one original-line-range replacement computed from a fresh parse, so every
51
+ // untouched line (comments, formatting, other providers) survives
52
+ // byte-for-byte. Each op's candidate text is re-parsed and compared against a
53
+ // plain-tree simulation of that op before the next op runs; any mismatch
54
+ // refuses the write with zero side effects (the caller only ever sees the
55
+ // candidate text, never a partial file).
56
+ //
57
+ // `!!js` expressions, block scalars and quoted multi-line scalars are kept as
58
+ // opaque leaves: their raw lines are preserved verbatim but carry no value.
59
+ // An opaque leaf anywhere inside the `llm-pi-ai` providers tree makes every
60
+ // op refuse (validation would be unsound there). No timer, no network, no
61
+ // real ~/.dsh lives here — all I/O goes through the injected filesystem
62
+ // subset.
63
+ import { createHash } from 'node:crypto';
64
+ const LLM_PI_AI_ENTRY_ID = 'llm-pi-ai';
65
+ /** The KEY regex every block-map row must match (keys are simple identifiers in practice). */
66
+ const KEY_ENTRY = /^(\S[^:]*?):(?:[ \t]+(.*))?$/;
67
+ /**
68
+ * Refuse any mapping key this subset parser and the host yaml could disagree
69
+ * on. A key is accepted only as a BARE plain scalar: no quotes, no whitespace,
70
+ * no YAML indicator characters, and no merge key. The host (yaml@2) parses
71
+ * each of these shapes differently than this parser — or rejects the document
72
+ * outright (duplicate keys) — so an edit that survived here used to write a
73
+ * file the host could not load while the batch reported SUCCESS. Failing the
74
+ * PARSE makes every consumer fail closed: no descriptor, no ops, no write.
75
+ */
76
+ function keyRefusal(key, lineNo) {
77
+ if (key === '<<')
78
+ return `line ${lineNo}: merge key "<<" is not supported`;
79
+ if (key.startsWith('"') || key.startsWith("'")) {
80
+ return `line ${lineNo}: quoted key ${JSON.stringify(key)} is not supported (bare plain keys only)`;
81
+ }
82
+ if (/\s/.test(key))
83
+ return `line ${lineNo}: key ${JSON.stringify(key)} contains whitespace (bare plain keys only)`;
84
+ if (/[#*&{[]/.test(key)) {
85
+ return `line ${lineNo}: key ${JSON.stringify(key)} contains a YAML indicator character (#*&{[); refusing to guess`;
86
+ }
87
+ // Review M3: the host yaml resolves keys to scalars before folding them into
88
+ // a mapping — `true`/`True`/`TRUE`, `null`/`Null`/`~` and `1`/`+1`/`007` are
89
+ // each THE SAME key, so two same-level spellings make the host reject the
90
+ // whole document ("Map keys must be unique") while this parser sees distinct
91
+ // strings. A single non-string key would still disagree with the string view
92
+ // here. Refused outright instead of guessed.
93
+ const decoded = decodePlainScalar(key);
94
+ if (decoded === null || typeof decoded === 'boolean' || typeof decoded === 'number') {
95
+ return `line ${lineNo}: key ${JSON.stringify(key)} resolves to a non-string (${String(decoded)}) in the host yaml; null/~/true/1 spellings collide into one key`;
96
+ }
97
+ // Round 3: also refuse the host's wider numeric domain (1e3/0x1F/1./.5/
98
+ // .inf/.NaN/0o17/…) — decodePlainScalar sees a string there while the host
99
+ // yaml folds the KEY into a number, so same-level spellings collide and the
100
+ // parser's string view diverges from the host's.
101
+ if (hostNumberForm(key)) {
102
+ return `line ${lineNo}: key ${JSON.stringify(key)} is numeric-form (the host yaml resolves it to a number, folding same-level spellings into one key); refusing`;
103
+ }
104
+ return undefined;
105
+ }
106
+ /** True when a plain scalar/flow part is a YAML anchor (`&name`) or alias (`*name`). */
107
+ function isAnchorOrAlias(text) {
108
+ return text.startsWith('&') || text.startsWith('*');
109
+ }
110
+ class TabIndentError extends Error {
111
+ name = 'TabIndentError';
112
+ }
113
+ function indentOf(line) {
114
+ let count = 0;
115
+ for (const ch of line) {
116
+ if (ch === ' ')
117
+ count += 1;
118
+ else if (ch === '\t')
119
+ throw new TabIndentError();
120
+ else
121
+ break;
122
+ }
123
+ return count;
124
+ }
125
+ function isSkippable(line) {
126
+ const trimmed = line.trim();
127
+ return trimmed === '' || trimmed.startsWith('#');
128
+ }
129
+ function leadingSpaces(text) {
130
+ let count = 0;
131
+ while (count < text.length && text[count] === ' ')
132
+ count += 1;
133
+ return count;
134
+ }
135
+ function decodePlainScalar(raw) {
136
+ const s = raw.trim();
137
+ if (s === '' || s === '~' || s === 'null' || s === 'Null' || s === 'NULL')
138
+ return null;
139
+ if (s === 'true' || s === 'True' || s === 'TRUE')
140
+ return true;
141
+ if (s === 'false' || s === 'False' || s === 'FALSE')
142
+ return false;
143
+ if (/^[-+]?\d+$/.test(s))
144
+ return Number(s);
145
+ if (/^[-+]?\d+\.\d+$/.test(s))
146
+ return Number(s);
147
+ return s;
148
+ }
149
+ /**
150
+ * The scalar forms the host yaml@2 resolves to a NUMBER beyond the plain
151
+ * integer/decimal pair already handled by `decodePlainScalar` (differential-
152
+ * probed against the host closure's yaml@2.9.1): scientific notation
153
+ * (incl. `1.e3` / `.5e2`), trailing/leading-dot decimals, LOWERCASE-prefix
154
+ * hex/octal integers (the host keeps `0X1F`/`0O17` strings), and `.inf`/
155
+ * `.nan` spellings. Used to refuse numeric-form KEYS (the host folds them
156
+ * like `1`/`007`) and to QUOTE numeric-form strings on write-back (a plain
157
+ * `1e3` would be re-read by the host as the number 1000).
158
+ */
159
+ function hostNumberForm(text) {
160
+ return /^[-+]?\d+$/.test(text)
161
+ || /^[-+]?\d+\.\d+$/.test(text)
162
+ || /^[-+]?\d+\.$/.test(text)
163
+ || /^[-+]?\.\d+$/.test(text)
164
+ || /^[-+]?\d+(\.\d+)?[eE][-+]?\d+$/.test(text)
165
+ || /^[-+]?\d+\.[eE][-+]?\d+$/.test(text)
166
+ || /^[-+]?\.\d+[eE][-+]?\d+$/.test(text)
167
+ || /^0x[0-9a-fA-F]+$/.test(text)
168
+ || /^0o[0-7]+$/.test(text)
169
+ || /^\.(inf|Inf|INF)$/.test(text)
170
+ || /^[-+]?\.(inf|Inf|INF)$/.test(text)
171
+ || /^\.(nan|NaN|NAN)$/.test(text);
172
+ }
173
+ /** Strip one trailing ` #comment` from a plain scalar (values keep their own `#`). */
174
+ function stripTrailingComment(raw) {
175
+ const index = raw.indexOf(' #');
176
+ return index >= 0 ? raw.slice(0, index) : raw;
177
+ }
178
+ /** Index of the closing quote scanning from `from` ('' doubling / "\" escaping handled). */
179
+ function findClosingQuote(text, from, quote) {
180
+ for (let i = from; i < text.length; i++) {
181
+ const ch = text[i];
182
+ if (quote === '"' && ch === '\\') {
183
+ i += 1;
184
+ continue;
185
+ }
186
+ if (ch === quote) {
187
+ if (quote === "'" && text[i + 1] === "'") {
188
+ i += 1;
189
+ continue;
190
+ }
191
+ return i;
192
+ }
193
+ }
194
+ return -1;
195
+ }
196
+ /**
197
+ * Index of the closing bracket for a single-line flow collection, -1 when
198
+ * absent. Round-3 blocker: brackets pair BY TYPE (a stack of open chars), so
199
+ * `{a: b]` / `[a, b}` / `[{a: 1]]` no longer "resolve" — the host yaml
200
+ * rejects mismatched flow brackets outright and the old mixed depth counter
201
+ * accepted exactly those unloadable documents (migrate-go reported SUCCESS
202
+ * while the host refused to load the written file). A type mismatch THROWS
203
+ * with the line number so the parse fails with the precise reason; the
204
+ * caller only ever splices with a correctly matched close index.
205
+ */
206
+ function matchingFlowClose(text, from, lineNo) {
207
+ const stack = [text[from]];
208
+ let quote;
209
+ for (let i = from + 1; i < text.length; i++) {
210
+ const ch = text[i];
211
+ if (quote !== undefined) {
212
+ if (quote === '"' && ch === '\\') {
213
+ i += 1;
214
+ continue;
215
+ }
216
+ if (ch === quote)
217
+ quote = undefined;
218
+ continue;
219
+ }
220
+ if (ch === '"' || ch === "'") {
221
+ quote = ch;
222
+ continue;
223
+ }
224
+ if (ch === '[' || ch === '{') {
225
+ stack.push(ch);
226
+ continue;
227
+ }
228
+ if (ch === ']' || ch === '}') {
229
+ const opened = stack.pop();
230
+ const wanted = ch === ']' ? '[' : '{';
231
+ if (opened !== wanted) {
232
+ throw new Error(`line ${lineNo}: flow collection opened with "${opened}" but closed with "${ch}" — the host yaml rejects mismatched flow brackets; refusing`);
233
+ }
234
+ if (stack.length === 0)
235
+ return i;
236
+ }
237
+ }
238
+ return -1;
239
+ }
240
+ /**
241
+ * Decode ONE single-line quoted scalar the way the host yaml@2 would
242
+ * (round 3): single quotes only collapse `''`; double quotes decode
243
+ * left-to-right over the host's common escape set
244
+ * (`\n \t \r \" \\ \0 \b \f \xXX \uXXXX \UXXXXXXXX`). ANY other escape
245
+ * REFUSES: the host either decodes it to a different character (`\a`, `\v`,
246
+ * `\/`, `\N`, …) or rejects the document (`\q`, truncated hex, `\U` beyond
247
+ * U+10FFFF) — writing the escape through as literal text would silently flip
248
+ * the host's reading of the rewritten value. Multi-line quoted scalars never
249
+ * reach here (they are opaque leaves upstream), so no line-fold/continuation
250
+ * handling applies: refusing to decode what cannot be seen IS the
251
+ * host-consistent continuation behavior of this subset.
252
+ */
253
+ function unquoteYaml(text, lineNo) {
254
+ const quote = text[0];
255
+ const inner = text.slice(1, -1);
256
+ if (quote !== '"')
257
+ return inner.replaceAll("''", "'");
258
+ let out = '';
259
+ for (let i = 0; i < inner.length; i++) {
260
+ const ch = inner[i];
261
+ if (ch !== '\\') {
262
+ out += ch;
263
+ continue;
264
+ }
265
+ const code = inner[i + 1];
266
+ switch (code) {
267
+ case '0':
268
+ out += '\0';
269
+ i += 1;
270
+ break;
271
+ case 'b':
272
+ out += '\b';
273
+ i += 1;
274
+ break;
275
+ case 'f':
276
+ out += '\f';
277
+ i += 1;
278
+ break;
279
+ case 'n':
280
+ out += '\n';
281
+ i += 1;
282
+ break;
283
+ case 'r':
284
+ out += '\r';
285
+ i += 1;
286
+ break;
287
+ case 't':
288
+ out += '\t';
289
+ i += 1;
290
+ break;
291
+ case '"':
292
+ out += '"';
293
+ i += 1;
294
+ break;
295
+ case '\\':
296
+ out += '\\';
297
+ i += 1;
298
+ break;
299
+ case 'x':
300
+ case 'u':
301
+ case 'U': {
302
+ const width = code === 'x' ? 2 : code === 'u' ? 4 : 8;
303
+ const digits = inner.slice(i + 2, i + 2 + width);
304
+ if (digits.length !== width || !/^[0-9a-fA-F]+$/.test(digits)) {
305
+ throw new Error(`line ${lineNo}: invalid "\\${code}" escape in a double-quoted scalar (exactly ${width} hex digits required); refusing`);
306
+ }
307
+ const value = Number.parseInt(digits, 16);
308
+ if (value > 0x10ffff) {
309
+ throw new Error(`line ${lineNo}: "\\U" escape beyond U+10FFFF is rejected by the host yaml; refusing`);
310
+ }
311
+ out += String.fromCodePoint(value);
312
+ i += 1 + width;
313
+ break;
314
+ }
315
+ default:
316
+ throw new Error(`line ${lineNo}: unsupported escape sequence "\\${code ?? ''}" in a double-quoted scalar — the host yaml decodes it differently (or rejects the document); refusing instead of writing a value the host would read differently`);
317
+ }
318
+ }
319
+ return out;
320
+ }
321
+ /**
322
+ * True when a plain (non-quoted) text carries a mapping indicator the host
323
+ * yaml would act on: a colon followed by space/tab, or a colon at the end.
324
+ * Both parse as a nested / single-pair mapping — never as part of a plain
325
+ * scalar (review M1 flow single-pair items, review M2 value position).
326
+ */
327
+ function hasMappingIndicator(text) {
328
+ for (let i = 0; i < text.length; i++) {
329
+ if (text[i] !== ':')
330
+ continue;
331
+ const next = text[i + 1];
332
+ if (next === undefined || next === ' ' || next === '\t')
333
+ return true;
334
+ }
335
+ return false;
336
+ }
337
+ /**
338
+ * Split a single-line flow-collection body into its top-level parts,
339
+ * quote-, escape- and bracket-depth-aware (the old splitter mis-tracked
340
+ * `\"` escapes and silently dropped empty entries). Commas and the
341
+ * empty-entry check only act at depth 0, so nested `[`/`{` spans survive as
342
+ * one part and recursion decodes them (round 3: nested single-line flow
343
+ * collections decode like the host instead of being refused). Refuses what
344
+ * the host cannot load or would read differently (review M1/M2):
345
+ * - an empty entry between depth-0 commas (`[a, , b]` — the host rejects the
346
+ * file)
347
+ * - a `#` outside a quoted span at any depth (a comment inside the brackets
348
+ * swallows the closing bracket for the host — again an unloadable
349
+ * document; a `#` GLUED into a plain part like `a#b` is not a comment and
350
+ * stays legal)
351
+ */
352
+ function scanFlowParts(inner, lineNo) {
353
+ const parts = [];
354
+ let current = '';
355
+ let quote;
356
+ let prev = '';
357
+ let depth = 0;
358
+ for (let i = 0; i < inner.length; i++) {
359
+ const ch = inner[i];
360
+ if (quote !== undefined) {
361
+ current += ch;
362
+ if (quote === '"' && ch === '\\') {
363
+ i += 1;
364
+ const escaped = inner[i] ?? '';
365
+ current += escaped;
366
+ prev = escaped;
367
+ continue;
368
+ }
369
+ if (ch === quote)
370
+ quote = undefined;
371
+ prev = ch;
372
+ continue;
373
+ }
374
+ if (ch === '"' || ch === "'") {
375
+ quote = ch;
376
+ current += ch;
377
+ prev = ch;
378
+ continue;
379
+ }
380
+ if (ch === '[' || ch === '{') {
381
+ depth += 1;
382
+ prev = ch;
383
+ current += ch;
384
+ continue;
385
+ }
386
+ if (ch === ']' || ch === '}') {
387
+ depth -= 1;
388
+ prev = ch;
389
+ current += ch;
390
+ continue;
391
+ }
392
+ if (ch === '#' && (prev === '' || /\s/.test(prev) || ',{}[]:'.includes(prev))) {
393
+ throw new Error(`line ${lineNo}: a comment inside a flow collection swallows the closing bracket for the host yaml; refusing`);
394
+ }
395
+ if (ch === ',' && depth === 0) {
396
+ if (current.trim() === '')
397
+ throw new Error(`line ${lineNo}: empty flow entry (the host yaml rejects "[a, , b]")`);
398
+ parts.push(current);
399
+ current = '';
400
+ prev = ',';
401
+ continue;
402
+ }
403
+ prev = ch;
404
+ current += ch;
405
+ }
406
+ if (current.trim() !== '')
407
+ parts.push(current);
408
+ return parts;
409
+ }
410
+ /**
411
+ * Decode ONE flow scalar exactly the way the host yaml would (review M1):
412
+ * quoted scalars go through the SAME `unquoteYaml` path as the block
413
+ * position (single/double quotes, `''` and the round-3 double-quote escape
414
+ * domain), and a bracket-led item is a nested flow collection decoded by
415
+ * recursion (round 3) — the host parses `[{a: 1}]` as `[{a: 1}]`, not as
416
+ * text, so refusing it would diverge from the tree the host sees. Tags,
417
+ * single-pair entries and anchors/aliases are REFUSED — decoding them as
418
+ * text is what used to turn `input: ["text"]` into `["\"text\""]` on
419
+ * write-back. `depth` is the nesting level of the ENCLOSING flow collection;
420
+ * a bracket-led item recurses into `parseFlow` at `depth + 1`.
421
+ */
422
+ function decodeFlowScalar(item, lineNo, where, colonMeaning, depth) {
423
+ if (item.startsWith('!')) {
424
+ throw new Error(`line ${lineNo}: YAML tags inside a ${where} are not supported (a tagged leaf cannot be carried in the subset tree; refusing instead of guessing)`);
425
+ }
426
+ if (isAnchorOrAlias(item)) {
427
+ throw new Error(`line ${lineNo}: YAML anchors/aliases are not supported (in a ${where})`);
428
+ }
429
+ if (item.startsWith('"') || item.startsWith("'")) {
430
+ const quote = item[0];
431
+ const close = findClosingQuote(item, 1, quote);
432
+ if (close < 0)
433
+ throw new Error(`line ${lineNo}: unterminated quoted scalar in a ${where}`);
434
+ if (item.slice(close + 1).trim() !== '') {
435
+ throw new Error(`line ${lineNo}: unexpected content after a quoted scalar in a ${where}`);
436
+ }
437
+ return unquoteYaml(item, lineNo);
438
+ }
439
+ if (item.startsWith('[') || item.startsWith('{')) {
440
+ const close = matchingFlowClose(item, 0, lineNo);
441
+ if (item.slice(close + 1).trim() !== '') {
442
+ throw new Error(`line ${lineNo}: unexpected content after a flow collection in a ${where}`);
443
+ }
444
+ return parseFlow(item, lineNo, depth + 1);
445
+ }
446
+ if (hasMappingIndicator(item)) {
447
+ throw new Error(`line ${lineNo}: ${colonMeaning}; refusing instead of guessing`);
448
+ }
449
+ return decodePlainScalar(item);
450
+ }
451
+ /**
452
+ * Conservative nesting bound for flow collections. The host yaml is itself a
453
+ * recursive-descent parser with a finite stack: measured against the host
454
+ * runtime, flow nesting past roughly 850–1000 levels makes the HOST reject the
455
+ * whole file with a stack overflow. Everything below that boundary loads, but
456
+ * there is no cheap a-priori envelope for "the host's stack on this machine",
457
+ * so the subset draws a deliberately conservative line (100) far inside the
458
+ * host's measured load envelope: flow deeper than the bound is refused at
459
+ * parse so this editor can never validate and write a document the host may
460
+ * not be able to load (fail closed, zero writes).
461
+ */
462
+ const MAX_FLOW_DEPTH = 100;
463
+ /**
464
+ * Single-line flow parser (`[]`, `{}`, `[a, b]`, `{k: v}` and properly
465
+ * nested combinations since round 3). The outer bracket TYPE pair is
466
+ * validated first (round-3 blocker: the old `slice(1, -1)` never checked,
467
+ * so `{a: b]` decoded as the map `{a: b}` while the host yaml rejected the
468
+ * whole document). `depth` is this collection's nesting level (the parser's
469
+ * top-level flow value is depth 1); past MAX_FLOW_DEPTH the parse refuses —
470
+ * see the constant's comment for the host-envelope rationale.
471
+ */
472
+ function parseFlow(text, lineNo, depth = 1) {
473
+ if (depth > MAX_FLOW_DEPTH) {
474
+ throw new Error(`line ${lineNo}: flow collection nested ${depth} deep exceeds the conservative depth bound (${MAX_FLOW_DEPTH}) — the subset must stay strictly inside the envelope the host yaml is guaranteed to load (deep past this bound the host's own parser overflows and rejects the file); refusing`);
475
+ }
476
+ const trimmed = text.trim();
477
+ if (trimmed === '[]')
478
+ return [];
479
+ if (trimmed === '{}')
480
+ return {};
481
+ const open = trimmed[0];
482
+ const close = trimmed[trimmed.length - 1];
483
+ if (!((open === '[' && close === ']') || (open === '{' && close === '}'))) {
484
+ throw new Error(`line ${lineNo}: flow collection opened with "${open}" but closed with "${close}" — the host yaml rejects mismatched flow brackets; refusing`);
485
+ }
486
+ const inner = trimmed.slice(1, -1);
487
+ if (open === '[') {
488
+ if (inner.trim() === '')
489
+ return [];
490
+ return scanFlowParts(inner, lineNo).map((part) => decodeFlowScalar(part.trim(), lineNo, 'flow sequence item', 'a single-pair flow entry like "[a: b]" (the host yaml parses it as a mapping, not a string)', depth));
491
+ }
492
+ const out = {};
493
+ for (const part of scanFlowParts(inner, lineNo)) {
494
+ const match = KEY_ENTRY.exec(part.trim());
495
+ if (match === null)
496
+ throw new Error(`line ${lineNo}: unsupported flow mapping entry`);
497
+ const key = match[1].trim();
498
+ const keyLine = keyRefusal(key, lineNo);
499
+ if (keyLine !== undefined)
500
+ throw new Error(keyLine);
501
+ if (key in out)
502
+ throw new Error(`line ${lineNo}: duplicate key ${JSON.stringify(key)} in the same mapping`);
503
+ const value = (match[2] ?? '').trim();
504
+ out[key] = decodeFlowScalar(value, lineNo, 'flow mapping value', 'a nested mapping inside a flow collection ("{a: b: c}" — the host yaml rejects the whole document)', depth);
505
+ }
506
+ return out;
507
+ }
508
+ // ---------------------------------------------------------------------------
509
+ // Parser
510
+ // ---------------------------------------------------------------------------
511
+ class PatchParser {
512
+ lines;
513
+ constructor(lines) {
514
+ this.lines = lines;
515
+ }
516
+ nextStructural(from) {
517
+ for (let i = from; i < this.lines.length; i++) {
518
+ if (!isSkippable(this.lines[i]))
519
+ return i;
520
+ }
521
+ return undefined;
522
+ }
523
+ /** Last line of a value blob: deeper-indented continuation lines (blank lines kept only when the blob continues past them). */
524
+ consumeDeeper(startLine, entryIndent) {
525
+ let end = startLine;
526
+ let i = startLine + 1;
527
+ while (i < this.lines.length) {
528
+ const line = this.lines[i];
529
+ if (line.trim() === '') {
530
+ let j = i + 1;
531
+ while (j < this.lines.length && this.lines[j].trim() === '')
532
+ j += 1;
533
+ if (j < this.lines.length && indentOf(this.lines[j]) > entryIndent) {
534
+ end = i;
535
+ i += 1;
536
+ continue;
537
+ }
538
+ break;
539
+ }
540
+ if (indentOf(line) > entryIndent) {
541
+ end = i;
542
+ i += 1;
543
+ continue;
544
+ }
545
+ break;
546
+ }
547
+ return end;
548
+ }
549
+ /** Lines of a quoted scalar that continues past its opening line; fails loudly on dedent. */
550
+ consumeQuoted(startLine, entryIndent, quote, fromCol) {
551
+ let from = fromCol;
552
+ for (let i = startLine; i < this.lines.length; i++) {
553
+ const line = this.lines[i];
554
+ const close = findClosingQuote(line, i === startLine ? from : 0, quote);
555
+ if (close >= 0)
556
+ return i;
557
+ const next = i + 1;
558
+ if (next < this.lines.length) {
559
+ const nextLine = this.lines[next];
560
+ if (nextLine.trim() !== '' && indentOf(nextLine) <= entryIndent) {
561
+ throw new Error(`line ${next + 1}: unterminated quoted scalar`);
562
+ }
563
+ }
564
+ }
565
+ throw new Error(`line ${startLine + 1}: unterminated quoted scalar`);
566
+ }
567
+ /** Parse an inline value; multi-line shapes become opaque leaves over their raw lines. */
568
+ parseInlineValue(rawValue, lineIdx, entryIndent) {
569
+ const trimmed = rawValue.trim();
570
+ const line = this.lines[lineIdx];
571
+ if (trimmed.startsWith('"') || trimmed.startsWith("'")) {
572
+ const quote = trimmed[0];
573
+ const openCol = line.indexOf(quote);
574
+ const closeCol = findClosingQuote(line, openCol + 1, quote);
575
+ if (closeCol >= 0) {
576
+ const after = line.slice(closeCol + 1).trim();
577
+ if (after !== '' && !after.startsWith('#'))
578
+ throw new Error(`line ${lineIdx + 1}: unexpected content after a quoted scalar`);
579
+ return {
580
+ node: { kind: 'scalar', value: unquoteYaml(line.slice(openCol, closeCol + 1), lineIdx + 1), startLine: lineIdx, endLine: lineIdx },
581
+ endLine: lineIdx,
582
+ };
583
+ }
584
+ const end = this.consumeQuoted(lineIdx, entryIndent, quote, openCol + 1);
585
+ return { node: { kind: 'opaque', startLine: lineIdx, endLine: end }, endLine: end };
586
+ }
587
+ // Anchors/aliases are refused anywhere in a value position: this parser
588
+ // would decode `models: *m` as the literal string "*m" while the host yaml
589
+ // resolves the alias — an edit validated against the wrong tree used to
590
+ // pass self-validation and write a semantically different document.
591
+ // (Quoted values starting with & or * were already handled above.)
592
+ if (isAnchorOrAlias(trimmed)) {
593
+ throw new Error(`line ${lineIdx + 1}: YAML anchors/aliases are not supported (value starts with '${trimmed[0]}')`);
594
+ }
595
+ if (trimmed.startsWith('!')) {
596
+ const end = this.consumeDeeper(lineIdx, entryIndent);
597
+ return { node: { kind: 'opaque', startLine: lineIdx, endLine: end }, endLine: end };
598
+ }
599
+ if (/^[|>][+-]?[0-9]*(#.*)?$/.test(trimmed)) {
600
+ const end = this.consumeDeeper(lineIdx, entryIndent);
601
+ return { node: { kind: 'opaque', startLine: lineIdx, endLine: end }, endLine: end };
602
+ }
603
+ if (trimmed.startsWith('[') || trimmed.startsWith('{')) {
604
+ const openCol = line.indexOf(trimmed[0]);
605
+ const closeCol = matchingFlowClose(line, openCol, lineIdx + 1);
606
+ if (closeCol < 0)
607
+ throw new Error(`line ${lineIdx + 1}: multi-line flow collections are not supported`);
608
+ const after = line.slice(closeCol + 1).trim();
609
+ if (after !== '' && !after.startsWith('#'))
610
+ throw new Error(`line ${lineIdx + 1}: unexpected content after a flow collection`);
611
+ return {
612
+ node: { kind: 'scalar', value: parseFlow(line.slice(openCol, closeCol + 1), lineIdx + 1), startLine: lineIdx, endLine: lineIdx },
613
+ endLine: lineIdx,
614
+ };
615
+ }
616
+ // Review M2: a colon-space (or trailing colon) in a plain VALUE position
617
+ // parses here but the host yaml rejects the WHOLE document ("Nested
618
+ // mappings are not allowed"). Strip the trailing comment first — only the
619
+ // value's own colons count (`a # x: y` is a comment for the host too).
620
+ const plain = stripTrailingComment(trimmed);
621
+ if (hasMappingIndicator(plain)) {
622
+ throw new Error(`line ${lineIdx + 1}: a "b: c" nested mapping in a value position is rejected by the host yaml; refusing`);
623
+ }
624
+ const end = this.consumeDeeper(lineIdx, entryIndent);
625
+ if (end !== lineIdx) {
626
+ // Multi-line PLAIN blob: the raw lines stay opaque, but a mapping
627
+ // indicator on any continuation line still makes the file unloadable
628
+ // for the host — refuse instead of accepting a broken document.
629
+ for (let i = lineIdx + 1; i <= end; i++) {
630
+ const raw = stripTrailingComment(this.lines[i].trim());
631
+ if (raw === '' || raw.startsWith('#'))
632
+ continue;
633
+ if (hasMappingIndicator(raw)) {
634
+ throw new Error(`line ${i + 1}: a "b: c" nested mapping inside a plain multi-line scalar is rejected by the host yaml; refusing`);
635
+ }
636
+ }
637
+ return { node: { kind: 'opaque', startLine: lineIdx, endLine: end }, endLine: end };
638
+ }
639
+ return {
640
+ node: { kind: 'scalar', value: decodePlainScalar(plain), startLine: lineIdx, endLine: lineIdx },
641
+ endLine: lineIdx,
642
+ };
643
+ }
644
+ /** Parse the block starting at `start` (its first structural line, at column `indent`). */
645
+ parseBlock(start, indent) {
646
+ const text = this.lines[start].slice(indent);
647
+ if (text.startsWith('- ') || text === '-')
648
+ return this.parseSeq(start, indent);
649
+ const match = KEY_ENTRY.exec(text);
650
+ if (match !== null)
651
+ return this.parseMap(start, indent, { key: match[1], valueText: match[2] });
652
+ throw new Error(`line ${start + 1}: unsupported YAML construct`);
653
+ }
654
+ parseSeq(start, indent) {
655
+ const items = [];
656
+ let i = start;
657
+ for (;;) {
658
+ const at = this.nextStructural(i);
659
+ if (at === undefined)
660
+ break;
661
+ const atIndent = indentOf(this.lines[at]);
662
+ if (atIndent < indent)
663
+ break;
664
+ if (atIndent > indent)
665
+ throw new Error(`line ${at + 1}: unexpected indentation inside a sequence`);
666
+ const rest = this.lines[at].slice(indent);
667
+ if (!(rest.startsWith('- ') || rest === '-')) {
668
+ throw new Error(`line ${at + 1}: expected a "- " sequence item`);
669
+ }
670
+ const content = rest === '-' ? '' : rest.slice(1 + leadingSpaces(rest.slice(1)));
671
+ const contentCol = indent + 1 + leadingSpaces(rest.slice(1));
672
+ if (content.trim() === '' || content.trimStart().startsWith('#')) {
673
+ const nested = this.nextStructural(at + 1);
674
+ if (nested !== undefined && indentOf(this.lines[nested]) > indent) {
675
+ const child = this.parseBlock(nested, indentOf(this.lines[nested]));
676
+ items.push({ node: child.node, startLine: at, endLine: child.node.endLine });
677
+ i = child.node.endLine + 1;
678
+ }
679
+ else {
680
+ items.push({ node: { kind: 'scalar', value: null, startLine: at, endLine: at }, startLine: at, endLine: at });
681
+ i = at + 1;
682
+ }
683
+ continue;
684
+ }
685
+ const keyMatch = KEY_ENTRY.exec(content);
686
+ if (keyMatch !== null && !content.trimStart().startsWith('"') && !content.trimStart().startsWith("'")) {
687
+ // Inline map: the first key lives on the dash line at contentCol.
688
+ const map = this.parseMap(at, contentCol, { key: keyMatch[1], valueText: keyMatch[2] });
689
+ items.push({ node: map.node, startLine: at, endLine: map.node.endLine });
690
+ i = map.node.endLine + 1;
691
+ continue;
692
+ }
693
+ const value = this.parseInlineValue(content, at, indent);
694
+ items.push({ node: value.node, startLine: at, endLine: value.endLine });
695
+ i = value.endLine + 1;
696
+ }
697
+ if (items.length === 0)
698
+ throw new Error(`line ${start + 1}: empty sequence`);
699
+ return {
700
+ node: { kind: 'seq', indent, items, startLine: start, endLine: items[items.length - 1].endLine },
701
+ next: items[items.length - 1].endLine + 1,
702
+ };
703
+ }
704
+ /**
705
+ * Parse a block map whose entry rows sit at column `mapIndent`. When
706
+ * `first` is given, the first entry was pre-matched on the `start` line
707
+ * (which may be a sequence dash line).
708
+ */
709
+ parseMap(start, mapIndent, first) {
710
+ const entries = [];
711
+ // Same-level duplicate keys: this parser used to fold them last-wins in
712
+ // its plain view while the host yaml rejects the document outright — an
713
+ // edit validated against the folded view wrote a file the host could not
714
+ // load. Detect at parse time, per mapping level.
715
+ const seenKeys = new Set();
716
+ let i = start;
717
+ let pending = { key: first.key, valueText: first.valueText, line: start };
718
+ for (;;) {
719
+ let keyLine;
720
+ let key;
721
+ let rawValue;
722
+ if (pending !== undefined) {
723
+ keyLine = pending.line;
724
+ key = pending.key;
725
+ rawValue = pending.valueText;
726
+ pending = undefined;
727
+ }
728
+ else {
729
+ const at = this.nextStructural(i);
730
+ if (at === undefined)
731
+ break;
732
+ const atIndent = indentOf(this.lines[at]);
733
+ if (atIndent < mapIndent)
734
+ break;
735
+ if (atIndent > mapIndent)
736
+ throw new Error(`line ${at + 1}: unexpected indentation inside a mapping`);
737
+ const match = KEY_ENTRY.exec(this.lines[at].slice(atIndent));
738
+ if (match === null)
739
+ throw new Error(`line ${at + 1}: expected a "key: value" mapping entry`);
740
+ keyLine = at;
741
+ key = match[1];
742
+ rawValue = match[2];
743
+ i = at;
744
+ }
745
+ const keyProblem = keyRefusal(key, keyLine + 1);
746
+ if (keyProblem !== undefined)
747
+ throw new Error(keyProblem);
748
+ if (seenKeys.has(key)) {
749
+ throw new Error(`line ${keyLine + 1}: duplicate key ${JSON.stringify(key)} in the same mapping (the host yaml rejects duplicate keys)`);
750
+ }
751
+ seenKeys.add(key);
752
+ if (rawValue === undefined || rawValue.trim() === '' || rawValue.trimStart().startsWith('#')) {
753
+ const nested = this.nextStructural(keyLine + 1);
754
+ if (nested !== undefined && indentOf(this.lines[nested]) > mapIndent) {
755
+ const child = this.parseBlock(nested, indentOf(this.lines[nested]));
756
+ entries.push({ key, value: child.node, startLine: keyLine, endLine: child.node.endLine });
757
+ i = child.node.endLine + 1;
758
+ }
759
+ else {
760
+ entries.push({ key, value: { kind: 'scalar', value: null, startLine: keyLine, endLine: keyLine }, startLine: keyLine, endLine: keyLine });
761
+ i = keyLine + 1;
762
+ }
763
+ }
764
+ else {
765
+ const value = this.parseInlineValue(rawValue, keyLine, mapIndent);
766
+ entries.push({ key, value: value.node, startLine: keyLine, endLine: value.endLine });
767
+ i = value.endLine + 1;
768
+ }
769
+ }
770
+ if (entries.length === 0)
771
+ throw new Error(`line ${start + 1}: empty mapping`);
772
+ const endLine = entries[entries.length - 1].endLine;
773
+ return { node: { kind: 'map', indent: mapIndent, entries, startLine: start, endLine }, next: endLine + 1 };
774
+ }
775
+ }
776
+ /**
777
+ * Parse a profile patch document. Returns the root sequence node; every node
778
+ * carries its exact original line range so edits splice by line numbers.
779
+ * Anything outside the supported subset is a refusal, never a guess.
780
+ */
781
+ export function parsePatchDocument(text) {
782
+ if (text.includes('\r'))
783
+ return { ok: false, reason: 'CRLF line endings are not supported' };
784
+ const lines = text.split('\n');
785
+ try {
786
+ let first = 0;
787
+ while (first < lines.length && isSkippable(lines[first]))
788
+ first += 1;
789
+ if (first >= lines.length)
790
+ return { ok: false, reason: 'document is empty' };
791
+ const parser = new PatchParser(lines);
792
+ // Minimal-patch files are an empty top-level flow sequence (`[]`).
793
+ const firstText = lines[first].trim();
794
+ if (firstText === '[]') {
795
+ return { ok: true, root: { kind: 'seq', indent: indentOf(lines[first]), items: [], startLine: first, endLine: first } };
796
+ }
797
+ const root = parser.parseBlock(first, indentOf(lines[first])).node;
798
+ for (let i = root.endLine + 1; i < lines.length; i++) {
799
+ if (!isSkippable(lines[i])) {
800
+ return { ok: false, reason: `line ${i + 1}: content after the root sequence is not supported` };
801
+ }
802
+ }
803
+ if (root.kind !== 'seq')
804
+ return { ok: false, reason: 'profile patch must be a YAML sequence of entries' };
805
+ return { ok: true, root };
806
+ }
807
+ catch (err) {
808
+ if (err instanceof TabIndentError)
809
+ return { ok: false, reason: 'tab indentation is not supported' };
810
+ return { ok: false, reason: err instanceof Error ? err.message : String(err) };
811
+ }
812
+ }
813
+ // ---------------------------------------------------------------------------
814
+ // Plain view + llm-pi-ai location
815
+ // ---------------------------------------------------------------------------
816
+ /** Marker for leaves whose value could not be decoded (tags, block scalars, blobs). */
817
+ export class OpaqueValue {
818
+ opaque = true;
819
+ }
820
+ /** Deep plain-JS view of a parsed node (opaque leaves → OpaqueValue). */
821
+ export function plainView(node) {
822
+ switch (node.kind) {
823
+ case 'map': {
824
+ const out = {};
825
+ for (const entry of node.entries)
826
+ out[entry.key] = plainView(entry.value);
827
+ return out;
828
+ }
829
+ case 'seq':
830
+ return node.items.map((item) => plainView(item.node));
831
+ case 'scalar':
832
+ return node.value;
833
+ case 'opaque':
834
+ return new OpaqueValue();
835
+ }
836
+ }
837
+ function containsOpaque(value) {
838
+ if (value instanceof OpaqueValue)
839
+ return true;
840
+ if (Array.isArray(value))
841
+ return value.some(containsOpaque);
842
+ if (typeof value === 'object' && value !== null)
843
+ return Object.values(value).some(containsOpaque);
844
+ return false;
845
+ }
846
+ function findLlmPiAiEntry(root) {
847
+ if (root.kind !== 'seq')
848
+ return { refusal: 'profile patch must be a YAML sequence of entries' };
849
+ // The host edits the LAST non-insert row carrying the entry id.
850
+ for (let i = root.items.length - 1; i >= 0; i--) {
851
+ const node = root.items[i].node;
852
+ if (node.kind !== 'map')
853
+ continue;
854
+ if (node.entries.some((entry) => entry.key === 'insert'))
855
+ continue;
856
+ const idEntry = [...node.entries].reverse().find((entry) => entry.key === 'id');
857
+ if (idEntry !== undefined && idEntry.value.kind === 'scalar' && idEntry.value.value === LLM_PI_AI_ENTRY_ID)
858
+ return node;
859
+ }
860
+ return { refusal: `no "${LLM_PI_AI_ENTRY_ID}" entry found in the profile patch` };
861
+ }
862
+ /**
863
+ * Locate the `llm-pi-ai` providers mapping plus its plain before-value, or a
864
+ * refusal reason. Shared by the op applier and the descriptor builder.
865
+ */
866
+ function locateProviders(root) {
867
+ const entry = findLlmPiAiEntry(root);
868
+ if ('refusal' in entry)
869
+ return { refusal: entry.refusal };
870
+ const configEntry = [...entry.entries].reverse().find((item) => item.key === 'config');
871
+ if (configEntry === undefined || configEntry.value.kind !== 'map') {
872
+ return { refusal: 'the llm-pi-ai entry has no config mapping' };
873
+ }
874
+ const providersEntry = [...configEntry.value.entries].reverse().find((item) => item.key === 'providers');
875
+ if (providersEntry === undefined || providersEntry.value.kind !== 'map') {
876
+ return { refusal: 'the llm-pi-ai config has no providers mapping' };
877
+ }
878
+ const plain = plainView(providersEntry.value);
879
+ if (containsOpaque(plain))
880
+ return { refusal: 'the llm-pi-ai providers tree contains opaque values (tags / block scalars); refusing to edit' };
881
+ if (typeof plain !== 'object' || plain === null || Array.isArray(plain)) {
882
+ return { refusal: 'the llm-pi-ai providers section is not a mapping' };
883
+ }
884
+ return { providersNode: providersEntry.value, providersLine: providersEntry.startLine, before: plain };
885
+ }
886
+ /** The plain `providers` tree of the `llm-pi-ai` entry, or a refusal reason. */
887
+ export function patchLlmPiAiProviders(root) {
888
+ const located = locateProviders(root);
889
+ if ('refusal' in located)
890
+ return { ok: false, reason: located.refusal };
891
+ return { ok: true, providers: located.before };
892
+ }
893
+ // ---------------------------------------------------------------------------
894
+ // YAML emission (only for the blocks this module writes)
895
+ // ---------------------------------------------------------------------------
896
+ const PLAIN_SAFE = /^[A-Za-z0-9_][A-Za-z0-9_\-./: ]*$/;
897
+ /**
898
+ * Render one scalar in plain-or-quoted form (double quotes, JSON escaping).
899
+ * Round 3: any numeric-form STRING (`1e3`, `0x1F`, `1.`, `.5`, `.inf`, … as
900
+ * well as the plain integer/decimal pair) is QUOTED — the host yaml resolves
901
+ * those plain forms to numbers, so an unquoted write-back would silently
902
+ * flip the value's type in the host's reading (the plain decimal exclusion
903
+ * used to cover `42` only and let `1e3` through as a number).
904
+ */
905
+ export function renderYamlScalar(value) {
906
+ if (value === null || value === undefined)
907
+ return 'null';
908
+ if (typeof value === 'boolean')
909
+ return value ? 'true' : 'false';
910
+ if (typeof value === 'number')
911
+ return String(value);
912
+ const text = String(value);
913
+ if (text !== '' && text === text.trim() && PLAIN_SAFE.test(text)
914
+ && !/^(true|false|null|~|True|False|Null|TRUE|FALSE|NULL)$/i.test(text)
915
+ && !hostNumberForm(text)
916
+ && !text.includes(': ') && !text.endsWith(':') && !text.includes(' #')) {
917
+ return text;
918
+ }
919
+ return JSON.stringify(text);
920
+ }
921
+ function isScalarValue(value) {
922
+ return value === null || value === undefined || typeof value !== 'object';
923
+ }
924
+ function renderBlock(value, indent) {
925
+ const pad = ' '.repeat(indent);
926
+ if (Array.isArray(value)) {
927
+ if (value.length === 0)
928
+ return [`${pad}[]`];
929
+ const lines = [];
930
+ for (const item of value) {
931
+ if (item !== null && typeof item === 'object') {
932
+ const entries = Object.entries(item);
933
+ if (entries.length === 0) {
934
+ lines.push(`${pad}- {}`);
935
+ continue;
936
+ }
937
+ const [firstKey, firstValue] = entries[0];
938
+ if (isScalarValue(firstValue))
939
+ lines.push(`${pad}- ${firstKey}: ${renderYamlScalar(firstValue)}`);
940
+ else {
941
+ lines.push(`${pad}- ${firstKey}:`);
942
+ lines.push(...renderBlock(firstValue, indent + 4));
943
+ }
944
+ for (const [key, itemValue] of entries.slice(1)) {
945
+ if (isScalarValue(itemValue))
946
+ lines.push(`${' '.repeat(indent + 2)}${key}: ${renderYamlScalar(itemValue)}`);
947
+ else {
948
+ lines.push(`${' '.repeat(indent + 2)}${key}:`);
949
+ lines.push(...renderBlock(itemValue, indent + 4));
950
+ }
951
+ }
952
+ }
953
+ else {
954
+ lines.push(`${pad}- ${renderYamlScalar(item)}`);
955
+ }
956
+ }
957
+ return lines;
958
+ }
959
+ if (value !== null && typeof value === 'object') {
960
+ const entries = Object.entries(value);
961
+ if (entries.length === 0)
962
+ return [`${pad}{}`];
963
+ const lines = [];
964
+ for (const [key, itemValue] of entries) {
965
+ if (isScalarValue(itemValue))
966
+ lines.push(`${pad}${key}: ${renderYamlScalar(itemValue)}`);
967
+ else {
968
+ lines.push(`${pad}${key}:`);
969
+ lines.push(...renderBlock(itemValue, indent + 2));
970
+ }
971
+ }
972
+ return lines;
973
+ }
974
+ return [`${pad}${renderYamlScalar(value)}`];
975
+ }
976
+ /** Render one map row (`key: scalar` or `key:` + nested block) at the given indent. */
977
+ function renderEntryLines(key, value, indent) {
978
+ if (isScalarValue(value))
979
+ return [`${' '.repeat(indent)}${key}: ${renderYamlScalar(value)}`];
980
+ if (Array.isArray(value) && value.length === 0)
981
+ return [`${' '.repeat(indent)}${key}: []`];
982
+ if (value !== null && typeof value === 'object' && Object.keys(value).length === 0)
983
+ return [`${' '.repeat(indent)}${key}: {}`];
984
+ return [`${' '.repeat(indent)}${key}:`, ...renderBlock(value, indent + 2)];
985
+ }
986
+ function plainTreeOf(value) {
987
+ return structuredClone(value);
988
+ }
989
+ /** Plain-tree simulation of one op (the expected post-op providers value). */
990
+ function simulateOneOp(before, op) {
991
+ const root = plainTreeOf(before);
992
+ if (op.path[0] !== 'providers' || op.path.length < 2 || op.path.length > 3) {
993
+ return { ok: false, reason: `unsupported mutation path '${op.path.join('.')}'` };
994
+ }
995
+ const route = op.path[1];
996
+ if (op.path.length === 2) {
997
+ if (op.op === 'unset') {
998
+ delete root[route];
999
+ return { ok: true, result: root };
1000
+ }
1001
+ return { ok: false, reason: 'whole-provider set ops are not supported' };
1002
+ }
1003
+ const field = op.path[2];
1004
+ if (op.op === 'unset') {
1005
+ const bucket = root[route];
1006
+ if (bucket !== null && typeof bucket === 'object' && !Array.isArray(bucket))
1007
+ delete bucket[field];
1008
+ return { ok: true, result: root };
1009
+ }
1010
+ if (root[route] === undefined || root[route] === null)
1011
+ root[route] = {};
1012
+ const bucket = root[route];
1013
+ if (bucket === null || typeof bucket !== 'object' || Array.isArray(bucket)) {
1014
+ return { ok: false, reason: `provider ${route} is not a mapping; refusing to edit` };
1015
+ }
1016
+ ;
1017
+ bucket[field] = structuredClone(op.value);
1018
+ return { ok: true, result: root };
1019
+ }
1020
+ function deepEqual(a, b) {
1021
+ if (a === b)
1022
+ return true;
1023
+ if (Array.isArray(a) && Array.isArray(b)) {
1024
+ return a.length === b.length && a.every((item, i) => deepEqual(item, b[i]));
1025
+ }
1026
+ if (a instanceof OpaqueValue || b instanceof OpaqueValue)
1027
+ return false;
1028
+ if (a !== null && typeof a === 'object' && b !== null && typeof b === 'object') {
1029
+ const ka = Object.keys(a);
1030
+ const kb = Object.keys(b);
1031
+ if (ka.length !== kb.length)
1032
+ return false;
1033
+ return ka.every((key) => deepEqual(a[key], b[key]));
1034
+ }
1035
+ return false;
1036
+ }
1037
+ function spliceLines(text, start, end, replacement) {
1038
+ const lines = text.split('\n');
1039
+ lines.splice(start, end - start + 1, ...replacement);
1040
+ return lines.join('\n');
1041
+ }
1042
+ /**
1043
+ * Apply settings-style mutation ops to the patch text WITHOUT writing. Ops
1044
+ * run one at a time against the evolving text; after each op the candidate is
1045
+ * re-parsed and its providers tree must equal the plain-tree simulation of
1046
+ * that op. Only `providers.<route>[.<field>]` set/unset paths are supported
1047
+ * (that is all the migration engine writes); everything else refuses. The
1048
+ * returned text is a full candidate document — the caller persists it.
1049
+ */
1050
+ export function applyPatchOps(text, ops) {
1051
+ let current = text;
1052
+ for (const op of ops) {
1053
+ const parsed = parsePatchDocument(current);
1054
+ if (!parsed.ok)
1055
+ return { ok: false, reason: `patch parse failed: ${parsed.reason}` };
1056
+ const located = locateProviders(parsed.root);
1057
+ if ('refusal' in located)
1058
+ return { ok: false, reason: located.refusal };
1059
+ const simulated = simulateOneOp(located.before, op);
1060
+ if (!simulated.ok)
1061
+ return { ok: false, reason: simulated.reason };
1062
+ const { providersNode, providersLine } = located;
1063
+ const routeIndent = providersNode.indent + 2;
1064
+ let splice;
1065
+ if (op.path.length === 2 && op.op === 'unset') {
1066
+ const route = op.path[1];
1067
+ const entry = [...providersNode.entries].reverse().find((item) => item.key === route);
1068
+ if (entry !== undefined && entry.value.kind === 'map') {
1069
+ // The splice covers the ENTRY range (key line through the value's last
1070
+ // line) — the value node alone would leave an orphan `route:` key.
1071
+ splice = { start: entry.startLine, end: entry.endLine, lines: [] };
1072
+ }
1073
+ else if (entry !== undefined) {
1074
+ return { ok: false, reason: `provider ${route} exists but is not a mapping` };
1075
+ }
1076
+ }
1077
+ else {
1078
+ const route = op.path[1];
1079
+ const field = op.path[2];
1080
+ const routeEntry = [...providersNode.entries].reverse().find((item) => item.key === route);
1081
+ const routeNodeRaw = routeEntry?.value;
1082
+ if (routeNodeRaw !== undefined && routeNodeRaw.kind !== 'map') {
1083
+ return { ok: false, reason: `provider ${route} exists but is not a mapping` };
1084
+ }
1085
+ const routeNode = routeNodeRaw;
1086
+ if (routeNode === undefined) {
1087
+ // Create the provider section with this single field, after the last
1088
+ // existing provider (or right under `providers:` when empty). The
1089
+ // route KEY sits at the providers map's own indent; renderEntryLines
1090
+ // nests the field block one level below it.
1091
+ const boundary = providersNode.entries.length === 0
1092
+ ? providersLine + 1
1093
+ : providersNode.entries[providersNode.entries.length - 1].endLine + 1;
1094
+ splice = { start: boundary, end: boundary - 1, lines: renderEntryLines(route, { [field]: op.value }, providersNode.indent) };
1095
+ }
1096
+ else {
1097
+ const fieldEntry = [...routeNode.entries].reverse().find((item) => item.key === field);
1098
+ if (fieldEntry !== undefined) {
1099
+ splice = { start: fieldEntry.startLine, end: fieldEntry.endLine, lines: renderEntryLines(field, op.value, routeNode.indent) };
1100
+ }
1101
+ else {
1102
+ // Missing field: insert before `models` (keeps the visual order used
1103
+ // by already-migrated routes), otherwise append after the last entry.
1104
+ const modelsEntry = [...routeNode.entries].reverse().find((item) => item.key === 'models');
1105
+ const boundary = modelsEntry !== undefined ? modelsEntry.startLine : routeNode.endLine + 1;
1106
+ splice = { start: boundary, end: boundary - 1, lines: renderEntryLines(field, op.value, routeIndent) };
1107
+ }
1108
+ }
1109
+ }
1110
+ if (splice === undefined) {
1111
+ // Pure no-op (unset of an absent route/field): the tree already matches.
1112
+ if (!deepEqual(simulated.result, located.before))
1113
+ return { ok: false, reason: 'no-op op changed the simulated tree; refusing' };
1114
+ continue;
1115
+ }
1116
+ const candidate = spliceLines(current, splice.start, splice.end, splice.lines);
1117
+ const reparsed = parsePatchDocument(candidate);
1118
+ if (!reparsed.ok)
1119
+ return { ok: false, reason: `edited patch failed to re-parse: ${reparsed.reason}` };
1120
+ const after = patchLlmPiAiProviders(reparsed.root);
1121
+ if (!after.ok)
1122
+ return { ok: false, reason: `edited patch unusable: ${after.reason}` };
1123
+ if (!deepEqual(after.providers, simulated.result)) {
1124
+ return { ok: false, reason: 'edited patch does not match the simulated result; refusing to write' };
1125
+ }
1126
+ current = candidate;
1127
+ }
1128
+ return { ok: true, next: current };
1129
+ }
1130
+ /**
1131
+ * Revision for the file adapter: a stable 32-bit digest of the current file
1132
+ * content. The host's numeric revisions have no meaning across processes, so
1133
+ * content hashing is the conflict detector (applyMigration's mutateWithRetry
1134
+ * re-describes and retries once on SETTINGS_CONFLICT).
1135
+ */
1136
+ function revisionOf(text) {
1137
+ const digest = createHash('sha256').update(text).digest();
1138
+ const value = digest.readUInt32BE(0);
1139
+ return value === 0 ? 1 : value;
1140
+ }
1141
+ const SETTINGS_CONFLICT = 'SETTINGS_CONFLICT';
1142
+ /**
1143
+ * A SettingsService over one profile patch file. `describe()` re-reads the
1144
+ * file every call (external edits are always visible; an unreadable or
1145
+ * unparseable file yields NO descriptor, which fails closed upstream).
1146
+ * `mutate()` computes the candidate text in memory, validates it op by op,
1147
+ * then writes atomically through the injected io.
1148
+ */
1149
+ export function createFilePatchSettingsService(io) {
1150
+ return {
1151
+ describe() {
1152
+ let text;
1153
+ try {
1154
+ text = io.readText();
1155
+ }
1156
+ catch {
1157
+ return []; // unreadable ⇒ no descriptor ⇒ fail closed upstream
1158
+ }
1159
+ if (text === undefined || text === '')
1160
+ return [];
1161
+ const parsed = parsePatchDocument(text);
1162
+ if (!parsed.ok)
1163
+ return [];
1164
+ const providers = patchLlmPiAiProviders(parsed.root);
1165
+ if (!providers.ok)
1166
+ return [];
1167
+ return [{ ns: LLM_PI_AI_ENTRY_ID, revision: revisionOf(text), user: { providers: providers.providers } }];
1168
+ },
1169
+ async mutate(ns, ops, expectedRevision) {
1170
+ if (ns !== LLM_PI_AI_ENTRY_ID)
1171
+ throw new Error(`file patch adapter only mutates ${LLM_PI_AI_ENTRY_ID}`);
1172
+ const text = io.readText() ?? '';
1173
+ if (expectedRevision !== undefined && expectedRevision !== revisionOf(text)) {
1174
+ throw Object.assign(new Error('patch file changed since describe'), { code: SETTINGS_CONFLICT });
1175
+ }
1176
+ const applied = applyPatchOps(text, ops);
1177
+ if (!applied.ok)
1178
+ throw new Error(applied.reason);
1179
+ if (applied.next === text)
1180
+ return;
1181
+ await io.writeAtomic(applied.next);
1182
+ },
1183
+ };
1184
+ }
1185
+ //# sourceMappingURL=opencode-go-patch-file.js.map