@aiwayds/dsh-opentui 0.27.2 → 0.28.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,1428 @@
1
+ /**
2
+ * Patch ownership / convergence — pure functions (design 06, R0–R29, T3).
3
+ *
4
+ * No fs, no clock, no env reads. The caller supplies `template`, `current`,
5
+ * `sidecar` and `templateRevision`; every result is a plain value so the
6
+ * provisioner (T4) decides the exit code and the atomic write.
7
+ *
8
+ * Identity is decided by id (template row ids ∪ insert nested ids); the write
9
+ * range is decided by the YAML parser's byte range. Everything outside a
10
+ * managed span (blank lines, comments, foreign rows) is spliced through
11
+ * byte-for-byte (R2).
12
+ */
13
+ import { createHash } from 'node:crypto'
14
+ import { isDeepStrictEqual } from 'node:util'
15
+ import { parseDocument, isMap, isSeq, isScalar, isAlias, Scalar, Document } from 'yaml'
16
+
17
+ export const CONVERGE_POLICY_VERSION = 1
18
+ export const ROLE = Object.freeze({
19
+ 'llm-pi-ai': 'merge:providers',
20
+ subagent: 'carry',
21
+ permission: 'carry',
22
+ 'session-log-deepseek': 'carry',
23
+ 'dsh-approval-policy': 'carry',
24
+ 'agent-default-model': 'carry',
25
+ })
26
+ export const CARRY_GROUPS = Object.freeze({
27
+ 'agent-default-model': ['provider', 'model', 'reasoningEffort'],
28
+ })
29
+ export const RETIRED_MANAGED_IDS = new Set()
30
+ export const RETIRED_INSERT_IDS = new Set()
31
+
32
+ const ABSENT = Symbol('ABSENT')
33
+ const NEVER_EQUAL = Symbol('NEVER_EQUAL')
34
+ const JS_TAG = 'tag:yaml.org,2002:js'
35
+ const jsCustomTags = [{ tag: JS_TAG, resolve: (value) => value }]
36
+ const HEAD_RE = /^[ \t]*-([ \t]+#.*)?[ \t]*$/
37
+ const PROVIDER_ID_RE = /^[a-z][a-z0-9-]*$/
38
+ const API_ENUM = new Set(['openai-completions', 'openai-responses', 'anthropic-messages', 'google-generative-ai'])
39
+ const NO_REQUIRED_PATHS = new Set()
40
+
41
+ // P1-1: one-shot migration may only write these exact leaves. Six are
42
+ // two-segment row leaves; the single nested entry is an insert's config leaf.
43
+ // Anything else (unknown row, unknown leaf, extra depth) is dropped.
44
+ const EXT_ALLOWED_LEAVES = new Set([
45
+ 'subagent.maxActiveSubagents',
46
+ 'subagent.maxDepth',
47
+ 'session-log-deepseek.enabled',
48
+ 'agent-default-model.provider',
49
+ 'agent-default-model.model',
50
+ 'agent-default-model.reasoningEffort',
51
+ 'dsh-approval-policy.config.windowSeconds',
52
+ ])
53
+ // Segment names that would escape onto Object.prototype / Function.prototype.
54
+ const UNSAFE_PATH_SEGMENTS = new Set(['__proto__', 'constructor', 'prototype'])
55
+
56
+ // ---------------------------------------------------------------------------
57
+ // value helpers (projection, equality, deep get/set)
58
+ // ---------------------------------------------------------------------------
59
+
60
+ // Plain-object markers (not symbols): sidecars are JSON files, so the markers
61
+ // must survive JSON.stringify. The design itself uses { $js: "..." } (06:435).
62
+ function jsValue(payload) {
63
+ return { $js: payload }
64
+ }
65
+ function isJsValue(v) {
66
+ return v !== null && typeof v === 'object' && !Array.isArray(v) &&
67
+ Object.keys(v).length === 1 && typeof v.$js === 'string'
68
+ }
69
+ function taggedValue(tag, value) {
70
+ return { $tag: tag, value }
71
+ }
72
+ function isTaggedValue(v) {
73
+ return v !== null && typeof v === 'object' && !Array.isArray(v) &&
74
+ Object.keys(v).length === 2 && typeof v.$tag === 'string' && 'value' in v
75
+ }
76
+ function isPlainObject(v) {
77
+ return v !== null && typeof v === 'object' && !Array.isArray(v) && !isJsValue(v) && !isTaggedValue(v)
78
+ }
79
+
80
+ /** YAML projection P(node) per 06 §4.2. Duplicate keys / unknown shapes => NEVER_EQUAL. */
81
+ function projectNode(node) {
82
+ if (node === null || node === undefined) return ABSENT
83
+ if (isAlias(node)) return projectNode(node.resolve())
84
+ if (isMap(node)) {
85
+ const out = {}
86
+ for (const pair of node.items) {
87
+ const key = pair.key === null || pair.key === undefined ? ABSENT : String(pair.key.value)
88
+ if (key === ABSENT || Object.prototype.hasOwnProperty.call(out, key)) return NEVER_EQUAL
89
+ out[key] = projectNode(pair.value)
90
+ }
91
+ return out
92
+ }
93
+ if (isSeq(node)) return node.items.map((item) => projectNode(item))
94
+ if (isScalar(node)) {
95
+ if (node.tag === JS_TAG) return jsValue(node.value)
96
+ if (node.tag && node.tag !== 'tag:yaml.org,2002:str' && node.tag !== 'tag:yaml.org,2002:int' &&
97
+ node.tag !== 'tag:yaml.org,2002:float' && node.tag !== 'tag:yaml.org,2002:bool' &&
98
+ node.tag !== 'tag:yaml.org,2002:null') {
99
+ return taggedValue(node.tag, node.value)
100
+ }
101
+ return node.value === undefined ? null : node.value
102
+ }
103
+ return NEVER_EQUAL
104
+ }
105
+
106
+ function eq(a, b) {
107
+ if (a === NEVER_EQUAL || b === NEVER_EQUAL) return false
108
+ return isDeepStrictEqual(a, b)
109
+ }
110
+
111
+ function getIn(obj, path) {
112
+ let cur = obj
113
+ for (const key of path) {
114
+ if (!isPlainObject(cur) || !Object.prototype.hasOwnProperty.call(cur, key)) return ABSENT
115
+ cur = cur[key]
116
+ }
117
+ return cur
118
+ }
119
+
120
+ function setIn(obj, path, value) {
121
+ // Defense in depth: even a future caller that bypasses prepareExternalCarry
122
+ // cannot walk onto Object.prototype / Function.prototype via a path segment.
123
+ for (const key of path) if (UNSAFE_PATH_SEGMENTS.has(key)) return false
124
+ let cur = obj
125
+ for (let i = 0; i < path.length - 1; i++) {
126
+ const key = path[i]
127
+ if (!isPlainObject(cur[key])) cur[key] = {}
128
+ cur = cur[key]
129
+ }
130
+ const last = path[path.length - 1]
131
+ if (value === ABSENT) delete cur[last]
132
+ else cur[last] = value
133
+ return true
134
+ }
135
+
136
+ function cloneValue(v) {
137
+ if (Array.isArray(v)) return v.map(cloneValue)
138
+ if (isJsValue(v)) return jsValue(v.$js)
139
+ if (isTaggedValue(v)) return taggedValue(v.$tag, v.value)
140
+ if (isPlainObject(v)) {
141
+ const out = {}
142
+ for (const k of Object.keys(v)) out[k] = cloneValue(v[k])
143
+ return out
144
+ }
145
+ return v
146
+ }
147
+
148
+ function scalarText(v) {
149
+ if (v === ABSENT) return 'ABSENT'
150
+ if (isJsValue(v)) return `!!js(${String(v.$js).slice(0, 80)})`
151
+ if (Array.isArray(v)) return '[array]'
152
+ if (isPlainObject(v)) return '{object}'
153
+ return String(v).slice(0, 80)
154
+ }
155
+
156
+ function hashString(s) {
157
+ return createHash('sha256').update(s).digest('hex')
158
+ }
159
+
160
+ function shapeOf(node) {
161
+ const keys = {}
162
+ for (const pair of node.items) {
163
+ const key = String(pair.key.value)
164
+ keys[key] = projectNode(pair.value)
165
+ }
166
+ return {
167
+ present: true,
168
+ id: keys.id,
169
+ name: keys.name === undefined ? ABSENT : keys.name,
170
+ config: keys.config === undefined ? ABSENT : keys.config,
171
+ disabled: keys.disabled === undefined ? ABSENT : keys.disabled,
172
+ extra: (() => {
173
+ const out = {}
174
+ for (const k of Object.keys(keys)) {
175
+ if (k !== 'id' && k !== 'name' && k !== 'config' && k !== 'disabled') out[k] = keys[k]
176
+ }
177
+ return out
178
+ })(),
179
+ }
180
+ }
181
+
182
+ function disabledEq(a, b) {
183
+ const norm = (v) => (v === ABSENT || v === null || v === undefined || v === false ? false : v)
184
+ return eq(norm(a), norm(b))
185
+ }
186
+
187
+ function rowEq(a, b) {
188
+ return eq(a.config, b.config) && eq(a.name, b.name) && disabledEq(a.disabled, b.disabled) && eq(a.extra, b.extra)
189
+ }
190
+
191
+ // ---------------------------------------------------------------------------
192
+ // structural analysis / splitPatch
193
+ // ---------------------------------------------------------------------------
194
+
195
+ function makeDiagnostic(code, message, extra = {}) {
196
+ return Object.assign(new Error(message), { code, ...extra })
197
+ }
198
+
199
+ /** Internal parse + split + R28 assertions. Returns { blocks, error }. */
200
+ function analyze(text, label = 'current') {
201
+ if (typeof text !== 'string' || text.length === 0) {
202
+ return { blocks: [], error: makeDiagnostic('parse', `${label}: empty or non-string input`, { line: 1, col: 1 }) }
203
+ }
204
+ let doc
205
+ try {
206
+ doc = parseDocument(text, { customTags: jsCustomTags })
207
+ } catch (err) {
208
+ return { blocks: [], error: makeDiagnostic('parse', `${label}: ${err.message}`, { line: 1, col: 1 }) }
209
+ }
210
+ if (doc.errors && doc.errors.length > 0) {
211
+ const e = doc.errors[0]
212
+ const pos = e.linePos && e.linePos[0]
213
+ return {
214
+ blocks: [],
215
+ error: makeDiagnostic('parse', `${label}: ${e.message}`, {
216
+ line: pos ? pos.line : 1,
217
+ col: pos ? pos.col : 1,
218
+ }),
219
+ }
220
+ }
221
+ if (!isSeq(doc.contents)) {
222
+ const pos = doc.contents && doc.contents.range ? doc.contents.range[0] : 0
223
+ let line = 1
224
+ let col = 1
225
+ if (pos > 0) {
226
+ const before = text.slice(0, pos)
227
+ line = before.split('\n').length
228
+ col = pos - before.lastIndexOf('\n')
229
+ }
230
+ return { blocks: [], error: makeDiagnostic('shape', `${label}: top level is not a YAML sequence`, { line, col }) }
231
+ }
232
+
233
+ const blocks = []
234
+ for (const node of doc.contents.items) {
235
+ const nodeStart = node.range ? node.range[0] : 0
236
+ const nodeEnd = node.range ? node.range[2] : text.length
237
+ const lineStart = text.lastIndexOf('\n', nodeStart - 1) + 1
238
+ const head = text.slice(lineStart, nodeStart)
239
+ if (!HEAD_RE.test(head)) {
240
+ let line = 1
241
+ for (let i = 0; i < nodeStart; i++) if (text[i] === '\n') line++
242
+ const col = nodeStart - lineStart + 1
243
+ return {
244
+ blocks: [],
245
+ error: makeDiagnostic('shape', `${label}: '- # comment' must share the logical line with its node (R28)`, {
246
+ line,
247
+ col,
248
+ head,
249
+ }),
250
+ }
251
+ }
252
+ const indent = head.match(/^[ \t]*/)[0]
253
+ let kind = 'foreign'
254
+ let id
255
+ let insertTarget
256
+ let insertIds = []
257
+ let key
258
+ if (isMap(node)) {
259
+ if (node.has('insert') && isSeq(node.get('insert', true))) {
260
+ kind = 'insert'
261
+ insertTarget = node.has('id') ? String(node.get('id')) : undefined
262
+ const seq = node.get('insert', true)
263
+ insertIds = seq.items
264
+ .map((entry) => (isMap(entry) && entry.has('id') ? String(entry.get('id')) : undefined))
265
+ .filter((x) => typeof x === 'string')
266
+ key = `insert@${insertTarget ?? ''}:${[...insertIds].sort().join(',')}`
267
+ } else if (node.has('id') && typeof node.get('id') === 'string') {
268
+ kind = 'row'
269
+ id = String(node.get('id'))
270
+ key = `id:${id}`
271
+ }
272
+ }
273
+ blocks.push({
274
+ kind,
275
+ id,
276
+ insertTarget,
277
+ insertIds,
278
+ key,
279
+ range: [lineStart, nodeEnd],
280
+ nodeRange: [nodeStart, nodeEnd],
281
+ head,
282
+ indent,
283
+ raw: text.slice(lineStart, nodeEnd),
284
+ node,
285
+ text,
286
+ })
287
+ }
288
+
289
+ // R28 ①: spans monotonic, non-overlapping (node ranges drive replacement).
290
+ for (let i = 1; i < blocks.length; i++) {
291
+ if (blocks[i].range[0] < blocks[i - 1].range[0] || blocks[i].range[0] < blocks[i - 1].range[1]) {
292
+ const b = blocks[i]
293
+ let line = 1
294
+ for (let p = 0; p < b.range[0]; p++) if (text[p] === '\n') line++
295
+ return {
296
+ blocks: [],
297
+ error: makeDiagnostic('span', `${label}: overlapping top-level spans at line ${line}`, { line, col: 1 }),
298
+ }
299
+ }
300
+ }
301
+ return { blocks, error: undefined }
302
+ }
303
+
304
+ /** Public: top-level blocks with byte ranges, id, insert info and raw text. Throws on structural error. */
305
+ export function splitPatch(text) {
306
+ const { blocks, error } = analyze(text, 'patch')
307
+ if (error) throw error
308
+ return blocks
309
+ }
310
+
311
+ /** Managed identity set: top-level row ids ∪ insert nested ids (R0). */
312
+ export function managedIds(templateText) {
313
+ const ids = new Set()
314
+ for (const block of splitPatch(templateText)) {
315
+ if (block.kind === 'row') ids.add(block.id)
316
+ else if (block.kind === 'insert') for (const id of block.insertIds) ids.add(id)
317
+ }
318
+ return ids
319
+ }
320
+
321
+ // ---------------------------------------------------------------------------
322
+ // sidecar projection (N9: ancestor never contains name/disabled)
323
+ // ---------------------------------------------------------------------------
324
+
325
+ function roleOf(id) {
326
+ return ROLE[id] || 'authority'
327
+ }
328
+
329
+ function canonical(value) {
330
+ return JSON.stringify(value, (_k, v) => {
331
+ if (isJsValue(v)) return { $js: v.$js }
332
+ if (isTaggedValue(v)) return { $tag: v.$tag, value: v.value }
333
+ if (v === ABSENT) return null
334
+ return v
335
+ })
336
+ }
337
+
338
+ function ancestorFor(shape, role) {
339
+ if (role === 'carry') return { config: shape.config === ABSENT ? {} : cloneValue(shape.config) }
340
+ if (role === 'merge:providers') {
341
+ const cfg = isPlainObject(shape.config) ? shape.config : {}
342
+ const providers = cfg.providers === undefined ? {} : cloneValue(cfg.providers)
343
+ const rest = {}
344
+ for (const k of Object.keys(cfg)) if (k !== 'providers') rest[k] = cfg[k]
345
+ return { providers, restSha256: `sha256:${hashString(canonical(rest))}` }
346
+ }
347
+ const authority = { config: shape.config, extra: shape.extra }
348
+ return { ancestorSha256: `sha256:${hashString(canonical(authority))}` }
349
+ }
350
+
351
+ /** Sidecar shape for a template (used for first convergence and N1 self-heal). */
352
+ export function templateProjection(templateText, templateRevision) {
353
+ const blocks = splitPatch(templateText)
354
+ const rows = {}
355
+ for (const block of blocks) {
356
+ if (block.kind !== 'row') continue
357
+ const shape = shapeOf(block.node)
358
+ const role = roleOf(block.id)
359
+ rows[block.id] = {
360
+ role,
361
+ disabled: shape.disabled === ABSENT || shape.disabled === false ? false : shape.disabled,
362
+ ancestor: ancestorFor(shape, role),
363
+ }
364
+ }
365
+ // Insert nested entries with a ROLE entry get a row too (e.g. dsh-approval-policy).
366
+ for (const block of blocks) {
367
+ if (block.kind !== 'insert') continue
368
+ const seq = block.node.get('insert', true)
369
+ for (const entry of seq.items) {
370
+ if (!isMap(entry) || !entry.has('id')) continue
371
+ const id = String(entry.get('id'))
372
+ if (roleOf(id) === 'authority') continue
373
+ const shape = shapeOf(entry)
374
+ const role = roleOf(id)
375
+ rows[id] = {
376
+ role,
377
+ disabled: shape.disabled === ABSENT || shape.disabled === false ? false : shape.disabled,
378
+ ancestor: ancestorFor(shape, role),
379
+ }
380
+ }
381
+ }
382
+ const revision = templateRevision || hashString(templateText).slice(0, 16)
383
+ return { version: 1, templateRevision: revision, rows }
384
+ }
385
+
386
+ // ---------------------------------------------------------------------------
387
+ // effective row value (R3/R17) and three-way merge primitives
388
+ // ---------------------------------------------------------------------------
389
+
390
+ function templateNameFor(templateBlocks, id) {
391
+ const row = templateBlocks.find((b) => b.kind === 'row' && b.id === id)
392
+ if (!row) return ABSENT
393
+ return row.node.has('name') ? projectNode(row.node.get('name', true)) : ABSENT
394
+ }
395
+
396
+ /** E(id) per 06 §3.4.1: per-key last-wins over applicable rows, name-mismatch rows skipped. */
397
+ function effectiveRow(blocks, id, nameOfTemplate, warnSink) {
398
+ const E = { present: false, keys: {}, applicable: [], skipped: [] }
399
+ for (const block of blocks) {
400
+ if (block.kind !== 'row' || block.id !== id) continue
401
+ let applicable
402
+ if (!block.node.has('name')) applicable = true
403
+ else if (nameOfTemplate === ABSENT) applicable = false
404
+ else applicable = eq(projectNode(block.node.get('name', true)), nameOfTemplate)
405
+ if (!applicable) {
406
+ E.skipped.push(block)
407
+ let line = 1
408
+ for (let p = 0; p < block.range[0]; p++) if (block.text[p] === '\n') line++
409
+ warnSink(`row-name-mismatch: ${id}: line ${line} skipped (name does not match template)`)
410
+ continue
411
+ }
412
+ E.present = true
413
+ E.applicable.push(block)
414
+ for (const pair of block.node.items) {
415
+ const key = String(pair.key.value)
416
+ E.keys[key] = projectNode(pair.value)
417
+ }
418
+ }
419
+ const shape = {
420
+ present: E.present,
421
+ id,
422
+ name: E.keys.name === undefined ? ABSENT : E.keys.name,
423
+ config: E.keys.config === undefined ? ABSENT : E.keys.config,
424
+ disabled: E.keys.disabled === undefined ? ABSENT : E.keys.disabled,
425
+ extra: (() => {
426
+ const out = {}
427
+ for (const k of Object.keys(E.keys)) {
428
+ if (k !== 'id' && k !== 'name' && k !== 'config' && k !== 'disabled') out[k] = E.keys[k]
429
+ }
430
+ return out
431
+ })(),
432
+ }
433
+ return { ...E, shape }
434
+ }
435
+
436
+ function carryFromCurrentValue(current, next, ctx) {
437
+ if (current === ABSENT) return next
438
+ if (!isPlainObject(current) || !isPlainObject(next)) return cloneValue(current)
439
+ const out = cloneValue(next)
440
+ for (const key of Object.keys(current)) {
441
+ const value = current[key]
442
+ if (isJsValue(value)) {
443
+ ctx.warns.push(`carry-js-rejected: ${ctx.id}.${ctx.path.concat(key).join('.')}: template value kept`)
444
+ continue
445
+ }
446
+ out[key] = cloneValue(value)
447
+ }
448
+ return out
449
+ }
450
+
451
+ /** R5.1: a js-tagged leaf in the CURRENT value may never be carried. */
452
+ function rejectJsLeaves(current, expected, next, id, warns) {
453
+ if (!isPlainObject(current) || !isPlainObject(expected)) return expected
454
+ const nextObj = isPlainObject(next) ? next : {}
455
+ const out = cloneValue(expected)
456
+ for (const [key, value] of Object.entries(current)) {
457
+ if (isJsValue(value)) {
458
+ warns.push(`carry-js-rejected: ${id}.${key}: template value kept`)
459
+ if (Object.prototype.hasOwnProperty.call(nextObj, key)) out[key] = cloneValue(nextObj[key])
460
+ else delete out[key]
461
+ } else if (isPlainObject(value) && isPlainObject(out[key])) {
462
+ out[key] = rejectJsLeaves(value, out[key], nextObj[key], `${id}.${key}`, warns)
463
+ }
464
+ }
465
+ return out
466
+ }
467
+
468
+ /** merge3 per 06 §4.4.1. Arrays are atomic; recursion only into plain objects. */
469
+ function merge3Value(anc, cur, nxt, ctx) {
470
+ if (cur === ABSENT) {
471
+ if (anc !== ABSENT && NO_REQUIRED_PATHS.has(ctx.path.join('.'))) {
472
+ ctx.warns.push(`required-path-restored: ${ctx.id}.${ctx.path.join('.')}`)
473
+ return cloneValue(nxt)
474
+ }
475
+ return ABSENT // user deletion survives
476
+ }
477
+ if (anc === ABSENT) return carryFromCurrentValue(cur, nxt, ctx)
478
+ const objectInvolved = isPlainObject(anc) || isPlainObject(cur) || isPlainObject(nxt)
479
+ if (objectInvolved) {
480
+ const a = isPlainObject(anc) ? anc : {}
481
+ const c = isPlainObject(cur) ? cur : {}
482
+ const n = isPlainObject(nxt) ? nxt : {}
483
+ const keys = new Set([...Object.keys(a), ...Object.keys(c), ...Object.keys(n)])
484
+ const out = {}
485
+ for (const key of keys) {
486
+ const res = merge3Value(
487
+ Object.prototype.hasOwnProperty.call(a, key) ? a[key] : ABSENT,
488
+ Object.prototype.hasOwnProperty.call(c, key) ? c[key] : ABSENT,
489
+ Object.prototype.hasOwnProperty.call(n, key) ? n[key] : ABSENT,
490
+ { ...ctx, path: ctx.path.concat(key) },
491
+ )
492
+ if (res !== ABSENT) out[key] = res
493
+ }
494
+ return out
495
+ }
496
+ if (eq(cur, anc)) return cloneValue(nxt)
497
+ if (eq(nxt, anc)) return cloneValue(cur)
498
+ if (eq(cur, nxt)) return cloneValue(cur)
499
+ // both changed → current wins with path-level WARN (§4.4.2)
500
+ ctx.warns.push(
501
+ `carry-conflict: ${ctx.id}.${ctx.path.join('.')}: ancestor=${scalarText(anc)} current=${scalarText(cur)} next=${scalarText(nxt)}`,
502
+ )
503
+ return cloneValue(cur)
504
+ }
505
+
506
+ export function merge3(ancestor, current, next, opts = {}) {
507
+ return merge3Value(ancestor, current, next, {
508
+ id: opts.id || 'row',
509
+ path: opts.path || [],
510
+ warns: opts.warns || [],
511
+ })
512
+ }
513
+
514
+ function mergeProvider(anc, cur, nxt, id, warns) {
515
+ let m = merge3Value(anc, cur, nxt, { id, path: ['providers', id], warns })
516
+ if (m === ABSENT) m = cloneValue(nxt)
517
+ if (!isPlainObject(m)) m = cloneValue(nxt)
518
+ for (const key of Object.keys(isPlainObject(nxt) ? nxt : {})) {
519
+ if (!Object.prototype.hasOwnProperty.call(m, key)) {
520
+ m[key] = cloneValue(nxt[key])
521
+ warns.push(`provider-shape-restored: ${id}.${key}: template shape restored`)
522
+ }
523
+ }
524
+ if (nxt.api !== undefined && m.api !== undefined && !API_ENUM.has(String(m.api))) {
525
+ warns.push(`provider-api-invalid: ${id}: provider restored to template`)
526
+ return cloneValue(nxt)
527
+ }
528
+ if (Array.isArray(nxt.models) && nxt.models.length > 0 &&
529
+ (!Array.isArray(m.models) || m.models.length === 0) && !nxt.modelOverrides) {
530
+ warns.push(`provider-models-invalid: ${id}: provider restored to template`)
531
+ return cloneValue(nxt)
532
+ }
533
+ return m
534
+ }
535
+
536
+ /** providersMerge per 06 §5.3.1. */
537
+ export function providersMerge(anc, cur, nxt, rowId = 'llm-pi-ai', warns = []) {
538
+ const P_anc = anc === ABSENT ? ABSENT : anc
539
+ const P_cur = isPlainObject(cur) ? cur : {}
540
+ const P_next = isPlainObject(nxt) ? nxt : {}
541
+ const out = {}
542
+ const ids = new Set([...Object.keys(P_next), ...Object.keys(P_cur)])
543
+ for (const id of ids) {
544
+ if (!Object.prototype.hasOwnProperty.call(P_next, id)) {
545
+ out[id] = cloneValue(P_cur[id])
546
+ if (!PROVIDER_ID_RE.test(id)) warns.push(`provider-id-unstorable: ${id}: name cannot be stored as a credential record`)
547
+ continue
548
+ }
549
+ const n = P_next[id]
550
+ if (!Object.prototype.hasOwnProperty.call(P_cur, id)) {
551
+ out[id] = cloneValue(n)
552
+ warns.push(`provider-restored: ${id}: missing template provider restored`)
553
+ continue
554
+ }
555
+ const c = P_cur[id]
556
+ if (P_anc === ABSENT) {
557
+ out[id] = cloneValue(n)
558
+ warns.push(`provider-template-authority: ${id}: base unknown, template provider wins`)
559
+ continue
560
+ }
561
+ const a = Object.prototype.hasOwnProperty.call(P_anc, id) ? P_anc[id] : ABSENT
562
+ if (eq(c, a)) out[id] = cloneValue(n)
563
+ else out[id] = mergeProvider(a, c, n, id, warns)
564
+ }
565
+ return out
566
+ }
567
+
568
+ function carryDisabled(cur, anc, next, templateDisabled, id, warns) {
569
+ if (isJsValue(templateDisabled)) {
570
+ if (typeof cur === 'boolean') warns.push(`disabled-js-overwritten: ${id}: template !!js expression restored`)
571
+ return cloneValue(next)
572
+ }
573
+ const c = cur === ABSENT || cur === null ? false : cur
574
+ const a = anc === ABSENT || anc === null ? false : anc
575
+ const n = next === ABSENT || next === null ? false : next
576
+ if (eq(c, a)) return n
577
+ if (!eq(c, n) && !eq(a, n)) warns.push(`disabled-conflict: ${id}: both sides changed, current wins`)
578
+ return c
579
+ }
580
+
581
+ // ---------------------------------------------------------------------------
582
+ // external carry validation (R21/R22/R11 — 06 §4.5/§5.4/§7.3)
583
+ // ---------------------------------------------------------------------------
584
+
585
+ function reportExtDrop(path, reason, warnings, dropped) {
586
+ const entry = { path: String(path), reason: String(reason || 'invalid-value') }
587
+ dropped.push(entry)
588
+ warnings.push(`external-dropped: ${entry.path}: ${entry.reason}`)
589
+ }
590
+
591
+ /** Roles / paths one-shot migration may never write (R11, 06 §7.3). */
592
+ function extForbiddenReason(id, parts) {
593
+ if (id === 'permission') {
594
+ return parts[1] === 'presets' ? 'sandbox-loosening-forbidden' : 'template-authority'
595
+ }
596
+ if (id === 'llm-pi-ai') return 'model-table-template-owned'
597
+ return undefined
598
+ }
599
+
600
+ /** A carry leaf must be a finite scalar of the field's expected type.
601
+ * P1-1: unknown rows/leaves are invalid by default; only the whitelisted
602
+ * leaves can ever pass. */
603
+ function extLeafValid(id, parts, value) {
604
+ if (isJsValue(value) || isTaggedValue(value)) return false
605
+ if (value === undefined || value === null || typeof value === 'object') return false
606
+ if (typeof value === 'number' && !Number.isFinite(value)) return false
607
+ const leaf = parts.join('.')
608
+ if (!EXT_ALLOWED_LEAVES.has(`${id}.${leaf}`)) return false
609
+ if (id === 'session-log-deepseek' && leaf === 'enabled') return typeof value === 'boolean'
610
+ if (id === 'subagent' && (leaf === 'maxActiveSubagents' || leaf === 'maxDepth')) {
611
+ return typeof value === 'number' && Number.isInteger(value) && value >= 1
612
+ }
613
+ if (id === 'agent-default-model' && (leaf === 'provider' || leaf === 'model' || leaf === 'reasoningEffort')) {
614
+ return typeof value === 'string'
615
+ }
616
+ // Nested insert config leaf: finite number within the policy's hard bounds.
617
+ // Strings, NaN/Infinity, !!js markers and objects are all rejected here.
618
+ if (id === 'dsh-approval-policy' && leaf === 'config.windowSeconds') {
619
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 86400
620
+ }
621
+ return false
622
+ }
623
+
624
+ /** Insert entries in the template that have carry rights (nested ext targets). */
625
+ function templateCarryInsertIds(templateIndex) {
626
+ const ids = new Set()
627
+ for (const block of templateIndex.inserts) {
628
+ const seq = block.node.get('insert', true)
629
+ if (!seq || !isSeq(seq)) continue
630
+ for (const entry of seq.items) {
631
+ if (!isMap(entry) || !entry.has('id')) continue
632
+ const id = String(entry.get('id'))
633
+ if (roleOf(id) === 'carry') ids.add(id)
634
+ }
635
+ }
636
+ return ids
637
+ }
638
+
639
+ /** Config-relative leaf path of an ext key, or undefined for an unknown shape.
640
+ * Two-segment row leaves map directly; the one nested insert leaf drops its
641
+ * literal `config` segment so the value lands in the insert's config map. */
642
+ function extConfigLeafPath(parts) {
643
+ if (parts.length === 2) return parts.slice(1)
644
+ if (parts.length === 3 && parts[1] === 'config') return parts.slice(2)
645
+ return undefined
646
+ }
647
+
648
+ function templateProviders(templateIndex) {
649
+ const block = templateIndex.rows.get('llm-pi-ai')
650
+ if (!block) return undefined
651
+ const cfg = shapeOf(block.node).config
652
+ return isPlainObject(cfg) ? cfg.providers : undefined
653
+ }
654
+
655
+ /** R22: provider/model required, reasoningEffort optional but checked if present. */
656
+ function admGroupValid(values, providers) {
657
+ if (typeof values.provider !== 'string' || typeof values.model !== 'string') {
658
+ return { ok: false, reason: 'invalid-value' }
659
+ }
660
+ if (values.reasoningEffort !== undefined && typeof values.reasoningEffort !== 'string') {
661
+ return { ok: false, reason: 'invalid-value' }
662
+ }
663
+ if (!isPlainObject(providers) || !Object.prototype.hasOwnProperty.call(providers, values.provider)) {
664
+ return { ok: false, reason: 'model-id-not-in-template' }
665
+ }
666
+ const p = providers[values.provider]
667
+ const models = Array.isArray(p.models) ? p.models : []
668
+ const model = models.find((m) => isPlainObject(m) && m.id === values.model)
669
+ let found = !!model
670
+ if (!found && isPlainObject(p.modelOverrides)) {
671
+ found = Object.prototype.hasOwnProperty.call(p.modelOverrides, values.model)
672
+ }
673
+ if (!found) return { ok: false, reason: 'model-id-not-in-template' }
674
+ if (values.reasoningEffort !== undefined && model && isPlainObject(model.reasoningEfforts) &&
675
+ !Object.prototype.hasOwnProperty.call(model.reasoningEfforts, values.reasoningEffort)) {
676
+ return { ok: false, reason: 'invalid-value' }
677
+ }
678
+ return { ok: true }
679
+ }
680
+
681
+ /**
682
+ * Validate the one-shot migration input once per converge call. Returns a
683
+ * sanitized ext whose `values` hold only applicable leaf paths; every
684
+ * rejection is appended to `dropped` and `warnings` as `<rowId>.<dot.path>`.
685
+ */
686
+ function prepareExternalCarry(externalCarry, templateIndex, warnings, dropped) {
687
+ if (!externalCarry || typeof externalCarry !== 'object') return undefined
688
+ if (Array.isArray(externalCarry.dropped)) {
689
+ for (const d of externalCarry.dropped) reportExtDrop(d && d.path, d && d.reason, warnings, dropped)
690
+ }
691
+ if (!isPlainObject(externalCarry.values)) return undefined
692
+ const providers = templateProviders(templateIndex)
693
+ const carryInserts = templateCarryInsertIds(templateIndex)
694
+ const valid = {}
695
+ const adm = {}
696
+ const admPaths = {}
697
+ for (const [path, value] of Object.entries(externalCarry.values)) {
698
+ const parts = String(path).split('.')
699
+ const id = parts[0]
700
+ // P1-1: unsafe segment names are rejected with invalid-value, ahead of any
701
+ // role-specific reason, so a polluting path never gets a different verdict.
702
+ if (parts.some((seg) => UNSAFE_PATH_SEGMENTS.has(seg))) {
703
+ reportExtDrop(path, 'invalid-value', warnings, dropped); continue
704
+ }
705
+ const forbidden = extForbiddenReason(id, parts)
706
+ if (forbidden) { reportExtDrop(path, forbidden, warnings, dropped); continue }
707
+ // P1-1: exact whitelist only. Row leaves are two segments; the nested
708
+ // insert leaf is three segments with a literal `config`, and must target a
709
+ // carry insert that actually exists in the template. Any other depth or
710
+ // unknown row/leaf is dropped instead of being legal by default.
711
+ const nested = parts.length === 3 && parts[1] === 'config'
712
+ const known = nested
713
+ ? carryInserts.has(id)
714
+ : (parts.length === 2 && templateIndex.rows.has(id) && roleOf(id) === 'carry')
715
+ if (!EXT_ALLOWED_LEAVES.has(path) || !known || !extConfigLeafPath(parts)) {
716
+ reportExtDrop(path, 'invalid-value', warnings, dropped); continue
717
+ }
718
+ if (!extLeafValid(id, parts.slice(1), value)) {
719
+ reportExtDrop(path, 'invalid-value', warnings, dropped); continue
720
+ }
721
+ if (id === 'agent-default-model') {
722
+ adm[parts[1]] = value
723
+ admPaths[parts[1]] = path
724
+ continue
725
+ }
726
+ valid[path] = value
727
+ }
728
+ if (Object.keys(adm).length > 0) {
729
+ const verdict = admGroupValid(adm, providers)
730
+ if (verdict.ok) {
731
+ for (const [key, path] of Object.entries(admPaths)) valid[path] = adm[key]
732
+ } else {
733
+ for (const path of Object.values(admPaths)) reportExtDrop(path, verdict.reason, warnings, dropped)
734
+ }
735
+ }
736
+ return { source: externalCarry.source, values: valid }
737
+ }
738
+
739
+ /** Apply the sanitized ext to one carry shape (row or insert entry); ancestor
740
+ * is never touched — callers keep the template projection as the sidecar. */
741
+ function applyExt(shape, ext, id) {
742
+ if (!ext || !isPlainObject(ext.values)) return shape
743
+ const out = cloneValue(shape)
744
+ for (const [path, value] of Object.entries(ext.values)) {
745
+ const parts = path.split('.')
746
+ if (parts[0] !== id) continue
747
+ const leaf = extConfigLeafPath(parts)
748
+ if (!leaf) continue
749
+ if (out.config === ABSENT) out.config = {}
750
+ if (!isPlainObject(out.config)) continue
751
+ setIn(out.config, leaf, cloneValue(value))
752
+ }
753
+ return out
754
+ }
755
+
756
+ /** R22: verify agent-default-model triple against the (merged) provider table. */
757
+ function checkCarryGroup(id, config, nextConfig) {
758
+ if (!CARRY_GROUPS[id]) return true
759
+ const group = CARRY_GROUPS[id]
760
+ if (!isPlainObject(config)) return false
761
+ for (const key of group) {
762
+ if (key !== 'reasoningEffort' && (config[key] === undefined || config[key] === ABSENT)) return false
763
+ }
764
+ // Cross-row validation against providers is performed by the caller (needs llm-pi-ai).
765
+ return true
766
+ }
767
+
768
+ // ---------------------------------------------------------------------------
769
+ // rendering (clone template AST; no whole-file round trip)
770
+ // ---------------------------------------------------------------------------
771
+
772
+ function valueToNode(value, doc) {
773
+ if (isJsValue(value)) {
774
+ const scalar = new Scalar(value.$js)
775
+ scalar.tag = JS_TAG
776
+ return scalar
777
+ }
778
+ if (isTaggedValue(value)) {
779
+ const scalar = new Scalar(value.value)
780
+ scalar.tag = value.$tag
781
+ return scalar
782
+ }
783
+ if (Array.isArray(value)) {
784
+ const seq = doc.createNode([])
785
+ for (const item of value) seq.add(valueToNode(item, doc))
786
+ return seq
787
+ }
788
+ if (isPlainObject(value)) {
789
+ const map = doc.createNode({})
790
+ for (const key of Object.keys(value)) map.set(key, valueToNode(value[key], doc))
791
+ return map
792
+ }
793
+ return new Scalar(value === ABSENT ? null : value)
794
+ }
795
+
796
+ function normalizeEol(text, eol) {
797
+ if (eol === '\n') return text.replace(/\r\n/g, '\n')
798
+ return text.replace(/\r\n/g, '\n').replace(/\n/g, eol)
799
+ }
800
+
801
+ function dominantEol(text) {
802
+ const crlf = (text.match(/\r\n/g) || []).length
803
+ const lf = (text.match(/(?<!\r)\n/g) || []).length
804
+ return crlf > lf ? '\r\n' : '\n'
805
+ }
806
+
807
+ function eolOfBlock(block) {
808
+ return block.raw.includes('\r\n') ? '\r\n' : '\n'
809
+ }
810
+
811
+ function renderRow(templateBlock, expected, eol) {
812
+ const tplShape = shapeOf(templateBlock.node)
813
+ if (rowEq(expected, tplShape)) return normalizeEol(templateBlock.raw, eol)
814
+ const doc = new Document()
815
+ const node = templateBlock.node.clone()
816
+ // config (template leaves with !!js markers survive via valueToNode)
817
+ if (isPlainObject(expected.config) || Array.isArray(expected.config) || isJsValue(expected.config)) {
818
+ node.set('config', valueToNode(expected.config, doc))
819
+ } else if (node.has('config')) node.delete('config')
820
+ // name: template name is authoritative (R24); template clone already has it.
821
+ // disabled (R20): true/!!js -> write; false/absent -> omit.
822
+ const d = expected.disabled
823
+ if (d === true || isJsValue(d) || isTaggedValue(d)) node.set('disabled', valueToNode(d, doc))
824
+ else if (node.has('disabled')) node.delete('disabled')
825
+ // extra: template clone already carries template extras (authority).
826
+ doc.contents = doc.createNode([node])
827
+ const rendered = String(doc, { lineWidth: 0 })
828
+ return normalizeEol(rendered, eol)
829
+ }
830
+
831
+ function renderInsertBlock(templateBlock, currentBlock, entries, eol) {
832
+ const doc = new Document()
833
+ const entryNodes = entries.map((entry) => valueToNode(entry, doc))
834
+ const seq = doc.createNode([])
835
+ for (const node of entryNodes) seq.add(node)
836
+ const map = doc.createNode({ insert: null })
837
+ map.set('insert', seq)
838
+ doc.contents = doc.createNode([map])
839
+ void templateBlock
840
+ void currentBlock
841
+ return normalizeEol(String(doc, { lineWidth: 0 }), eol)
842
+ }
843
+
844
+ function entryShape(entry) {
845
+ if (!isMap(entry) || !entry.has('id')) return undefined
846
+ return shapeOf(entry)
847
+ }
848
+
849
+ // ---------------------------------------------------------------------------
850
+ // preamble repair (R13)
851
+ // ---------------------------------------------------------------------------
852
+
853
+ function preambleEdit(current, template, revision, blocks) {
854
+ const firstStart = blocks.length > 0 ? blocks[0].range[0] : current.length
855
+ const head = current.slice(0, firstStart)
856
+ const tplBlocks = splitPatch(template)
857
+ const tplHead = template.slice(0, tplBlocks.length > 0 ? tplBlocks[0].range[0] : template.length)
858
+ const expectedHead = tplHead.replace(/(# profileRevision: )[^\n]*/, `$1${revision}`)
859
+ const eol = head.includes('\r\n') ? '\r\n' : '\n'
860
+ const norm = (s) => s.replace(/\r\n/g, '\n')
861
+ if (norm(head) === expectedHead) return undefined
862
+
863
+ let newHead = norm(head)
864
+ const headerLine = '# dsh-opentui inproc profile patch'
865
+ if (!newHead.startsWith(headerLine)) {
866
+ const header = expectedHead.slice(0, expectedHead.indexOf('\n') + 1)
867
+ newHead = header + newHead
868
+ }
869
+ if (/# profileRevision: /.test(newHead)) {
870
+ newHead = newHead.replace(/(# profileRevision: )[^\n]*/, `$1${revision}`)
871
+ } else {
872
+ const revLine = expectedHead.split('\n').find((line) => line.startsWith('# profileRevision: '))
873
+ const firstNl = newHead.indexOf('\n')
874
+ newHead = newHead.slice(0, firstNl + 1) + `${revLine}\n` + newHead.slice(firstNl + 1)
875
+ }
876
+ // R13: one blank line between the first comment block and the first item.
877
+ if (newHead.length > 0 && !/\n[ \t]*\n$/.test(newHead)) newHead += '\n'
878
+ if (newHead === norm(head)) return undefined
879
+ return { start: 0, end: firstStart, text: normalizeEol(newHead, eol), reason: 'preamble' }
880
+ }
881
+
882
+ // ---------------------------------------------------------------------------
883
+ // backup reason priority + path reporting (R10/R29)
884
+ // ---------------------------------------------------------------------------
885
+
886
+ const BACKUP_PRIORITY = ['duplicates', 'foreign-comments', 'drift', 'new-managed-row', 'base-unknown']
887
+
888
+ function pickBackup(reasons) {
889
+ for (const reason of BACKUP_PRIORITY) if (reasons.has(reason)) return reason
890
+ return undefined
891
+ }
892
+
893
+ function collectForeignComments(block, templateBlock, notes) {
894
+ if (!block || !templateBlock) return false
895
+ const commentRe = /#[^\n]*/g
896
+ const currentComments = block.raw.match(commentRe) || []
897
+ const tplComments = templateBlock.raw.match(commentRe) || []
898
+ const foreign = currentComments.filter((c) => !tplComments.includes(c))
899
+ if (foreign.length === 0) return false
900
+ notes.push(`foreign-comments: ${block.id || 'insert'}: ${foreign.join(' | ').slice(0, 200)}`)
901
+ return true
902
+ }
903
+
904
+ function pathLines(id, path, cur, next, paths, notes, label) {
905
+ if (eq(cur, next)) return
906
+ const line = `${id}.${path}: ${scalarText(cur)} → ${scalarText(next)}`
907
+ paths.push(line)
908
+ notes.push(`${label}: ${line}`)
909
+ }
910
+
911
+ // ---------------------------------------------------------------------------
912
+ // converge
913
+ // ---------------------------------------------------------------------------
914
+
915
+ function indexTemplate(template) {
916
+ const analysis = analyze(template, 'template')
917
+ if (analysis.error) throw analysis.error // template parse failure is a build bug
918
+ const blocks = analysis.blocks
919
+ const rows = new Map()
920
+ const inserts = []
921
+ for (const block of blocks) {
922
+ if (block.kind === 'row') rows.set(block.id, block)
923
+ else if (block.kind === 'insert') inserts.push(block)
924
+ }
925
+ return { blocks, rows, inserts }
926
+ }
927
+
928
+ function applyEdits(base, list) {
929
+ let result = base
930
+ const sorted = [...list].sort((a, b) => b.start - a.start || b.end - a.end)
931
+ for (const edit of sorted) result = result.slice(0, edit.start) + edit.text + result.slice(edit.end)
932
+ return result
933
+ }
934
+
935
+ function absentConverge({ template, templateIndex, revision, externalCarry, notes, warnings, dropped }) {
936
+ const edits = []
937
+ for (const [id, tplBlock] of templateIndex.rows) {
938
+ const shape = shapeOf(tplBlock.node)
939
+ const nextEff = applyExt(shape, externalCarry, id)
940
+ if (rowEq(nextEff, shape)) continue
941
+ const expected = {
942
+ id,
943
+ name: shape.name,
944
+ config: nextEff.config,
945
+ disabled: nextEff.disabled,
946
+ extra: shape.extra,
947
+ }
948
+ edits.push({ start: tplBlock.range[0], end: tplBlock.range[1], text: renderRow(tplBlock, expected, '\n') })
949
+ }
950
+ // Nested insert leaves (e.g. dsh-approval-policy.config.windowSeconds) live
951
+ // in an insert block, not in a top-level row. With no current file, render
952
+ // the template insert block with ext applied; the sidecar below still uses
953
+ // the untouched template as the ancestor.
954
+ const eol = dominantEol(template)
955
+ for (const tplInsert of templateIndex.inserts) {
956
+ const seq = tplInsert.node.get('insert', true)
957
+ if (!seq || !isSeq(seq)) continue
958
+ let changed = false
959
+ const entries = seq.items.filter(isMap).map((entry) => {
960
+ const shape = shapeOf(entry)
961
+ const id = String(entry.get('id'))
962
+ const eff = applyExt(shape, externalCarry, id)
963
+ if (!eq(eff.config, shape.config) || !eq(eff.extra, shape.extra)) changed = true
964
+ return {
965
+ id,
966
+ name: shape.name === ABSENT ? undefined : shape.name,
967
+ config: eff.config === ABSENT ? undefined : cloneValue(eff.config),
968
+ // Match row rendering: template disabled/extra fields stay authoritative.
969
+ // Omit absent fields so entries without extras keep their existing bytes.
970
+ ...(shape.disabled === ABSENT ? {} : { disabled: cloneValue(shape.disabled) }),
971
+ ...cloneValue(shape.extra),
972
+ }
973
+ })
974
+ if (!changed) continue
975
+ edits.push({ start: tplInsert.range[0], end: tplInsert.range[1], text: renderInsertBlock(tplInsert, undefined, entries, eol) })
976
+ }
977
+ const content = edits.length > 0 ? applyEdits(template, edits) : template
978
+ return {
979
+ write: true,
980
+ content,
981
+ reason: 'absent',
982
+ backupReason: undefined,
983
+ backupPaths: [],
984
+ paths: [],
985
+ carried: [],
986
+ drift: [],
987
+ notes,
988
+ warnings,
989
+ dropped,
990
+ sidecar: templateProjection(template, revision),
991
+ }
992
+ }
993
+
994
+ /**
995
+ * Main entry (06 §4.6.1). Returns a plain result; never writes, never throws
996
+ * for bad `current` (returns `{ write:false, error }` instead).
997
+ */
998
+ export function converge({ template, current, sidecar, templateRevision, externalCarry }) {
999
+ const notes = []
1000
+ const warnings = []
1001
+ const paths = []
1002
+ const backupReasons = new Set()
1003
+ const revision = templateRevision || hashString(template).slice(0, 16)
1004
+
1005
+ const templateIndex = indexTemplate(template)
1006
+ const managed = managedIds(template)
1007
+ const dropped = []
1008
+ const ext = prepareExternalCarry(externalCarry, templateIndex, warnings, dropped)
1009
+
1010
+ if (current === undefined || current === null || current === '') {
1011
+ return absentConverge({ template, templateIndex, revision, sidecar, externalCarry: ext, notes, warnings, dropped })
1012
+ }
1013
+
1014
+ const analysis = analyze(current, 'current')
1015
+ if (analysis.error) {
1016
+ return {
1017
+ write: false,
1018
+ error: {
1019
+ code: analysis.error.code,
1020
+ message: analysis.error.message,
1021
+ line: analysis.error.line,
1022
+ col: analysis.error.col,
1023
+ },
1024
+ notes,
1025
+ warnings,
1026
+ dropped,
1027
+ backupPaths: [],
1028
+ paths,
1029
+ }
1030
+ }
1031
+ const blocks = analysis.blocks
1032
+ const fileEol = dominantEol(current)
1033
+
1034
+ // A sidecar is a valid merge ancestor iff version === 1 and rows is a map
1035
+ // (06 §4.3.1). A stale `templateRevision` does NOT invalidate the rows: that
1036
+ // is exactly how a template default change is detected (§4.3.2). Stale
1037
+ // revision matters only for N1's no-write sidecar self-heal path.
1038
+ const stateUsable = !!sidecar && sidecar.version === 1 && isPlainObject(sidecar.rows)
1039
+ const stateRows = stateUsable ? sidecar.rows : undefined
1040
+ const sidecarStale = stateUsable && sidecar.templateRevision !== revision
1041
+
1042
+ const edits = []
1043
+ const missingRows = []
1044
+ const duplicates = []
1045
+ const retired = []
1046
+ const missingInserts = []
1047
+ const rewriteInserts = []
1048
+ const expectedShapes = new Map()
1049
+
1050
+ // ---- managed rows -------------------------------------------------------
1051
+ for (const [id, templateBlock] of templateIndex.rows) {
1052
+ const tplShape = shapeOf(templateBlock.node)
1053
+ const nameOfTemplate = tplShape.name
1054
+ const E = effectiveRow(blocks, id, nameOfTemplate, warnings)
1055
+ if (!E.present) missingRows.push(id)
1056
+ if (E.applicable.length > 1) {
1057
+ duplicates.push(id)
1058
+ backupReasons.add('duplicates')
1059
+ pathLines(id, 'rows', `${E.applicable.length} applicable rows`, '1', paths, notes, 'duplicates')
1060
+ }
1061
+ const role = roleOf(id)
1062
+ const curShape = E.shape
1063
+ const nextShape = tplShape
1064
+ const nextEff = applyExt(nextShape, ext, id)
1065
+ const ancRow = stateRows ? stateRows[id] : undefined
1066
+ let expectedConfig
1067
+
1068
+ if (!E.present || curShape.config === ABSENT) {
1069
+ // R23-②/③: line absent or config absent (host reset) -> template + ext, no backup.
1070
+ expectedConfig = cloneValue(nextEff.config)
1071
+ if (E.present && Object.keys(curShape.extra).length > 0) {
1072
+ warnings.push(`row-extra-key: ${id}: ${Object.keys(curShape.extra).join(',')}`)
1073
+ }
1074
+ } else if (!stateUsable) {
1075
+ // base-unknown (R4.3.3): carry current, default not updated.
1076
+ if (role === 'merge:providers') {
1077
+ const pCur = isPlainObject(curShape.config) ? curShape.config.providers : ABSENT
1078
+ const pNext = isPlainObject(nextEff.config) ? nextEff.config.providers : ABSENT
1079
+ expectedConfig = isPlainObject(curShape.config)
1080
+ ? { ...cloneValue(nextEff.config), providers: providersMerge(ABSENT, pCur, pNext, id, warnings) }
1081
+ : cloneValue(nextEff.config)
1082
+ backupReasons.add('base-unknown')
1083
+ } else if (role === 'carry') {
1084
+ expectedConfig = carryFromCurrentValue(curShape.config, nextEff.config, { id, path: [], warns: warnings })
1085
+ backupReasons.add('base-unknown')
1086
+ } else {
1087
+ expectedConfig = cloneValue(nextEff.config)
1088
+ if (!eq(curShape.config, nextEff.config)) backupReasons.add('base-unknown')
1089
+ }
1090
+ pathLines(id, 'config', curShape.config, expectedConfig, paths, notes, 'base-unknown')
1091
+ } else if (ancRow === undefined) {
1092
+ // new managed row (state exists but row absent)
1093
+ if (role === 'merge:providers') {
1094
+ const pCur = isPlainObject(curShape.config) ? curShape.config.providers : ABSENT
1095
+ const pNext = isPlainObject(nextEff.config) ? nextEff.config.providers : ABSENT
1096
+ expectedConfig = isPlainObject(curShape.config)
1097
+ ? { ...cloneValue(nextEff.config), providers: providersMerge(ABSENT, pCur, pNext, id, warnings) }
1098
+ : cloneValue(nextEff.config)
1099
+ } else {
1100
+ expectedConfig = cloneValue(nextEff.config)
1101
+ }
1102
+ backupReasons.add('new-managed-row')
1103
+ pathLines(id, 'config', curShape.config, expectedConfig, paths, notes, 'new-managed-row')
1104
+ } else {
1105
+ const anc = ancRow.ancestor || {}
1106
+ if (role === 'carry') {
1107
+ const ancConfig = anc.config === undefined ? ABSENT : anc.config
1108
+ if (eq(curShape.config, ancConfig)) {
1109
+ expectedConfig = cloneValue(nextEff.config)
1110
+ } else {
1111
+ expectedConfig = merge3Value(ancConfig, curShape.config, nextEff.config, {
1112
+ id,
1113
+ path: [],
1114
+ warns: warnings,
1115
+ })
1116
+ if (expectedConfig === ABSENT) expectedConfig = cloneValue(nextEff.config)
1117
+ expectedConfig = rejectJsLeaves(curShape.config, expectedConfig, nextEff.config, id, warnings)
1118
+ // R22 group atomicity (cross-row validation done below)
1119
+ }
1120
+ } else if (role === 'merge:providers') {
1121
+ const pAnc = anc.providers === undefined ? ABSENT : anc.providers
1122
+ const pCur = isPlainObject(curShape.config) ? curShape.config.providers : ABSENT
1123
+ const pNext = isPlainObject(nextEff.config) ? nextEff.config.providers : ABSENT
1124
+ expectedConfig = isPlainObject(curShape.config)
1125
+ ? { ...cloneValue(nextEff.config), providers: providersMerge(pAnc, pCur, pNext, id, warnings) }
1126
+ : cloneValue(nextEff.config)
1127
+ // restConfig is template authority; a user change there is drift.
1128
+ const restCur = {}
1129
+ const restNext = {}
1130
+ if (isPlainObject(curShape.config)) for (const k of Object.keys(curShape.config)) if (k !== 'providers') restCur[k] = curShape.config[k]
1131
+ if (isPlainObject(nextEff.config)) for (const k of Object.keys(nextEff.config)) if (k !== 'providers') restNext[k] = nextEff.config[k]
1132
+ if (!eq(restCur, restNext)) {
1133
+ backupReasons.add('drift')
1134
+ pathLines(id, 'restConfig', restCur, restNext, paths, notes, 'drift')
1135
+ }
1136
+ } else {
1137
+ expectedConfig = cloneValue(nextEff.config)
1138
+ const curAuthority = canonical({ config: curShape.config, extra: curShape.extra })
1139
+ const expectedSha = `sha256:${hashString(curAuthority)}`
1140
+ if (anc.ancestorSha256 !== expectedSha) {
1141
+ backupReasons.add('drift')
1142
+ pathLines(id, 'config', curShape.config, expectedConfig, paths, notes, 'drift')
1143
+ }
1144
+ }
1145
+ pathLines(id, 'config', curShape.config, expectedConfig, paths, notes, 'compare')
1146
+ void ancRow
1147
+ }
1148
+
1149
+ // R22: group rejected -> whole group back to template.
1150
+ if (CARRY_GROUPS[id] && !checkCarryGroup(id, expectedConfig, nextEff.config)) {
1151
+ warnings.push(`carry-group-rejected: ${id}: group failed validation, template restored`)
1152
+ expectedConfig = cloneValue(nextEff.config)
1153
+ }
1154
+
1155
+ // R20: disabled carry, orthogonal to role.
1156
+ const templateDisabled = tplShape.disabled
1157
+ const ancDisabled = ancRow ? ancRow.disabled : ABSENT
1158
+ const expectedDisabled = carryDisabled(
1159
+ curShape.disabled,
1160
+ ancDisabled === undefined ? ABSENT : ancDisabled,
1161
+ nextEff.disabled,
1162
+ templateDisabled,
1163
+ id,
1164
+ warnings,
1165
+ )
1166
+
1167
+ const expected = {
1168
+ id,
1169
+ name: tplShape.name, // R24: template name always wins
1170
+ config: expectedConfig,
1171
+ disabled: expectedDisabled,
1172
+ extra: tplShape.extra,
1173
+ }
1174
+ expectedShapes.set(id, expected)
1175
+
1176
+ if (!rowEq(expected, curShape) || !E.present || E.applicable.length > 1) {
1177
+ const eol = E.applicable.length > 0 ? eolOfBlock(E.applicable[0]) : fileEol
1178
+ if (collectForeignComments(E.applicable[0], templateBlock, notes)) backupReasons.add('foreign-comments')
1179
+ const rendered = renderRow(templateBlock, expected, eol)
1180
+ if (E.applicable.length > 0) {
1181
+ edits.push({ start: E.applicable[0].range[0], end: E.applicable[0].range[1], text: rendered })
1182
+ for (let i = 1; i < E.applicable.length; i++) {
1183
+ edits.push({ start: E.applicable[i].range[0], end: E.applicable[i].range[1], text: '' })
1184
+ }
1185
+ }
1186
+ }
1187
+ }
1188
+
1189
+ // R22 cross-row validation: agent-default-model provider/model must exist in merged llm-pi-ai providers.
1190
+ const admExpected = expectedShapes.get('agent-default-model')
1191
+ if (admExpected && isPlainObject(admExpected.config)) {
1192
+ const provider = admExpected.config.provider
1193
+ const llm = expectedShapes.get('llm-pi-ai')
1194
+ if (provider !== undefined && llm && isPlainObject(llm.config) && isPlainObject(llm.config.providers)) {
1195
+ const p = llm.config.providers[provider]
1196
+ let ok = !!p
1197
+ const model = admExpected.config.model
1198
+ if (ok && model !== undefined && Array.isArray(p.models)) {
1199
+ ok = p.models.some((m) => isPlainObject(m) && m.id === model)
1200
+ if (!ok && isPlainObject(p.modelOverrides)) ok = Object.prototype.hasOwnProperty.call(p.modelOverrides, model)
1201
+ }
1202
+ if (!ok) {
1203
+ warnings.push('carry-group-rejected: agent-default-model: provider/model not in merged provider table, template restored')
1204
+ const tplBlock = templateIndex.rows.get('agent-default-model')
1205
+ if (tplBlock) {
1206
+ admExpected.config = cloneValue(shapeOf(tplBlock.node).config)
1207
+ const eol = fileEol
1208
+ const rendered = renderRow(tplBlock, admExpected, eol)
1209
+ const E = effectiveRow(blocks, 'agent-default-model', shapeOf(tplBlock.node).name, () => {})
1210
+ if (E.applicable.length > 0) {
1211
+ // replace an earlier edit for the same anchor
1212
+ const idx = edits.findIndex((ed) => ed.start === E.applicable[0].range[0])
1213
+ if (idx >= 0) edits.splice(idx, 1, { start: E.applicable[0].range[0], end: E.applicable[0].range[1], text: rendered })
1214
+ }
1215
+ }
1216
+ }
1217
+ }
1218
+ }
1219
+
1220
+ // ---- retired ids --------------------------------------------------------
1221
+ for (const block of blocks) {
1222
+ if (block.kind === 'row' && RETIRED_MANAGED_IDS.has(block.id)) {
1223
+ retired.push(block.id)
1224
+ edits.push({ start: block.range[0], end: block.range[1], text: '' })
1225
+ notes.push(`retired: ${block.id}: removed`)
1226
+ }
1227
+ }
1228
+
1229
+ // ---- managed insert blocks (R18) ---------------------------------------
1230
+ for (const tplInsert of templateIndex.inserts) {
1231
+ const tplIds = new Set(tplInsert.insertIds)
1232
+ const candidates = blocks.filter(
1233
+ (b) => b.kind === 'insert' && b.insertIds.some((id) => tplIds.has(id) || RETIRED_INSERT_IDS.has(id)),
1234
+ )
1235
+ if (candidates.length === 0) {
1236
+ missingInserts.push(tplInsert.key)
1237
+ continue
1238
+ }
1239
+ if (candidates.length > 1) {
1240
+ duplicates.push(tplInsert.key)
1241
+ backupReasons.add('duplicates')
1242
+ pathLines(tplInsert.key, 'blocks', `${candidates.length} insert blocks`, '1', paths, notes, 'duplicates')
1243
+ }
1244
+ const cur = candidates[0]
1245
+ const tplSeq = tplInsert.node.get('insert', true)
1246
+ const curSeq = cur.node.get('insert', true)
1247
+ const tplEntries = tplSeq.items.filter(isMap)
1248
+ const curEntries = curSeq.items.filter(isMap)
1249
+ const tplEntryById = new Map(tplEntries.map((e) => [String(e.get('id')), e]))
1250
+ const curEntryById = new Map(curEntries.map((e) => [String(e.get('id')), e]))
1251
+
1252
+ let needsRewrite = false
1253
+ const outEntries = []
1254
+ // Conflicts: nested id that is a top-level managed row id must be dropped.
1255
+ for (const [id, entry] of curEntryById) {
1256
+ if (managed.has(id) && !tplEntryById.has(id)) {
1257
+ warnings.push(`insert-managed-id-removed: ${id}: nested managed row removed from insert block`)
1258
+ needsRewrite = true
1259
+ }
1260
+ }
1261
+ for (const [id, tplEntry] of tplEntryById) {
1262
+ const tplShape = entryShape(tplEntry)
1263
+ // Ext is applied to the template-side value (the "next" of this nested
1264
+ // carry row); the sidecar ancestor stays the raw template projection.
1265
+ const effShape = applyExt(tplShape, ext, id)
1266
+ const curEntry = curEntryById.get(id)
1267
+ let entryValue = {
1268
+ id,
1269
+ name: tplShape.name === ABSENT ? undefined : tplShape.name,
1270
+ config: effShape.config === ABSENT ? undefined : cloneValue(effShape.config),
1271
+ }
1272
+ // Insert nested entries with a ROLE get carry treatment (e.g. dsh-approval-policy).
1273
+ if (roleOf(id) !== 'authority' && curEntry && stateUsable) {
1274
+ const role = roleOf(id)
1275
+ const anc = stateRows && stateRows[id] ? stateRows[id].ancestor : undefined
1276
+ const curCfg = curEntry.has('config') ? projectNode(curEntry.get('config', true)) : ABSENT
1277
+ if (!anc || !isPlainObject(entryValue.config)) {
1278
+ needsRewrite = needsRewrite || !eq(curCfg, entryValue.config)
1279
+ } else if (role === 'carry') {
1280
+ const merged = eq(curCfg, anc.config) ? cloneValue(entryValue.config)
1281
+ : merge3Value(anc.config, curCfg, entryValue.config, { id, path: [], warns: warnings })
1282
+ entryValue.config = merged === ABSENT ? cloneValue(entryValue.config) : merged
1283
+ needsRewrite = needsRewrite || !eq(curCfg, entryValue.config)
1284
+ } else {
1285
+ needsRewrite = needsRewrite || !eq(curCfg, entryValue.config)
1286
+ }
1287
+ } else {
1288
+ needsRewrite = needsRewrite || !curEntry || !eq(projectNode(tplEntry), projectNode(curEntry))
1289
+ // Without a usable sidecar the raw template is still the base, but an
1290
+ // ext value must land in the nested config even when current equals
1291
+ // that raw template.
1292
+ if (roleOf(id) !== 'authority' && curEntry &&
1293
+ !eq(entryValue.config, projectNode(tplEntry.get('config', true)))) {
1294
+ needsRewrite = true
1295
+ }
1296
+ }
1297
+ outEntries.push(entryValue)
1298
+ }
1299
+ // User-added entries preserved and appended after template entries (R18/P0-4).
1300
+ let userEntryMoved = false
1301
+ for (const [id, entry] of curEntryById) {
1302
+ if (tplEntryById.has(id)) continue
1303
+ if (managed.has(id)) continue
1304
+ const shape = entryShape(entry)
1305
+ outEntries.push({ id, name: shape.name === ABSENT ? undefined : shape.name, config: shape.config === ABSENT ? undefined : cloneValue(shape.config) })
1306
+ userEntryMoved = true
1307
+ }
1308
+ if (userEntryMoved && needsRewrite) {
1309
+ warnings.push(`insert-user-entry-moved: ${tplInsert.key}: user entries re-appended after template entries`)
1310
+ }
1311
+ const nestedConflict = [...curEntryById.keys()].some((id) => managed.has(id) && !tplEntryById.has(id))
1312
+ if (nestedConflict) needsRewrite = true
1313
+ // Duplicate insert blocks: drop the rest.
1314
+ for (let i = 1; i < candidates.length; i++) {
1315
+ edits.push({ start: candidates[i].range[0], end: candidates[i].range[1], text: '' })
1316
+ }
1317
+ if (needsRewrite) {
1318
+ rewriteInserts.push(tplInsert.key)
1319
+ if (collectForeignComments(cur, tplInsert, notes)) backupReasons.add('foreign-comments')
1320
+ const rendered = renderInsertBlock(tplInsert, cur, outEntries, eolOfBlock(cur))
1321
+ edits.push({ start: cur.range[0], end: cur.range[1], text: rendered })
1322
+ }
1323
+ }
1324
+
1325
+ // ---- missing rows / inserts appended to EOF (R23/R27) -------------------
1326
+ const appended = []
1327
+ for (const id of missingRows) {
1328
+ const tplBlock = templateIndex.rows.get(id)
1329
+ const expected = expectedShapes.get(id)
1330
+ if (!tplBlock || !expected) continue
1331
+ const eol = fileEol
1332
+ appended.push(renderRow(tplBlock, expected, eol))
1333
+ }
1334
+ for (const key of missingInserts) {
1335
+ const tplInsert = templateIndex.inserts.find((b) => b.key === key)
1336
+ if (!tplInsert) continue
1337
+ const entries = tplInsert.node.get('insert', true).items.filter(isMap).map((e) => {
1338
+ const shape = entryShape(e)
1339
+ const eff = applyExt(shape, ext, String(shape.id))
1340
+ return {
1341
+ id: shape.id,
1342
+ name: shape.name === ABSENT ? undefined : shape.name,
1343
+ config: eff.config === ABSENT ? undefined : cloneValue(eff.config),
1344
+ }
1345
+ })
1346
+ appended.push(renderInsertBlock(tplInsert, undefined, entries, fileEol))
1347
+ }
1348
+
1349
+ // ---- preamble (R13) -----------------------------------------------------
1350
+ const preamble = preambleEdit(current, template, revision, blocks)
1351
+ if (preamble) edits.push(preamble)
1352
+
1353
+ const semanticDiff = [...expectedShapes.entries()].some(([id, expected]) => {
1354
+ const E = effectiveRow(blocks, id, shapeOf(templateIndex.rows.get(id).node).name, () => {})
1355
+ return !rowEq(expected, E.shape)
1356
+ })
1357
+ const write =
1358
+ missingRows.length > 0 ||
1359
+ missingInserts.length > 0 ||
1360
+ duplicates.length > 0 ||
1361
+ retired.length > 0 ||
1362
+ rewriteInserts.length > 0 ||
1363
+ semanticDiff ||
1364
+ !!preamble
1365
+
1366
+ // ---- assemble content ---------------------------------------------------
1367
+ let content = current
1368
+ if (write) {
1369
+ content = applyEdits(current, edits)
1370
+ if (appended.length > 0) {
1371
+ const sep = content.endsWith('\n') ? '' : fileEol
1372
+ content += sep + appended.join('')
1373
+ }
1374
+ }
1375
+
1376
+ // ---- result -------------------------------------------------------------
1377
+ const backupReason = pickBackup(backupReasons)
1378
+ const notesOut = [...notes]
1379
+ if (backupReason) notesOut.unshift(`backup: ${backupReason}`)
1380
+
1381
+ const result = {
1382
+ write,
1383
+ content,
1384
+ reason: write ? (missingRows.length || missingInserts.length ? 'missing'
1385
+ : duplicates.length ? 'duplicates'
1386
+ : retired.length ? 'retired'
1387
+ : rewriteInserts.length ? 'managed-diff'
1388
+ : preamble ? 'preamble' : 'managed-diff') : 'semantically-equal',
1389
+ backupReason,
1390
+ backupPaths: paths,
1391
+ paths,
1392
+ carried: [],
1393
+ drift: notes.filter((n) => n.startsWith('drift:')),
1394
+ droppedComments: notes.filter((n) => n.startsWith('foreign-comments:')),
1395
+ notes: notesOut,
1396
+ warnings,
1397
+ dropped,
1398
+ missingRows,
1399
+ missingInserts,
1400
+ duplicates,
1401
+ retired,
1402
+ rewriteInserts,
1403
+ }
1404
+
1405
+ if (write) {
1406
+ result.sidecar = templateProjection(template, revision)
1407
+ } else if (!stateUsable || sidecarStale) {
1408
+ // N1: self-heal the sidecar even when the patch needs no write.
1409
+ result.writeSidecarOnly = true
1410
+ result.sidecar = templateProjection(template, revision)
1411
+ warnings.push('sidecar-self-heal: patch is already converged but sidecar is missing/corrupt/stale; writing sidecar only')
1412
+ } else {
1413
+ result.sidecar = undefined
1414
+ }
1415
+ return result
1416
+ }
1417
+
1418
+ export default {
1419
+ splitPatch,
1420
+ managedIds,
1421
+ templateProjection,
1422
+ converge,
1423
+ merge3,
1424
+ providersMerge,
1425
+ ROLE,
1426
+ CARRY_GROUPS,
1427
+ CONVERGE_POLICY_VERSION,
1428
+ }