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