@aiwayds/dsh-model-sync 0.11.1 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/lib/index.d.ts +8 -0
  2. package/lib/index.js +90 -24
  3. package/lib/index.js.map +1 -1
  4. package/lib/opencode-go-diagnose.d.ts +43 -21
  5. package/lib/opencode-go-diagnose.js +87 -56
  6. package/lib/opencode-go-diagnose.js.map +1 -1
  7. package/lib/opencode-go-grouping.d.ts +4 -26
  8. package/lib/opencode-go-grouping.js +12 -68
  9. package/lib/opencode-go-grouping.js.map +1 -1
  10. package/lib/opencode-go-host-catalog.d.ts +42 -0
  11. package/lib/opencode-go-host-catalog.js +98 -0
  12. package/lib/opencode-go-host-catalog.js.map +1 -0
  13. package/lib/opencode-go-journal.d.ts +6 -2
  14. package/lib/opencode-go-journal.js +1 -1
  15. package/lib/opencode-go-journal.js.map +1 -1
  16. package/lib/opencode-go-migrate.d.ts +40 -5
  17. package/lib/opencode-go-migrate.js +313 -84
  18. package/lib/opencode-go-migrate.js.map +1 -1
  19. package/lib/opencode-go-migration.d.ts +43 -0
  20. package/lib/opencode-go-migration.js +91 -2
  21. package/lib/opencode-go-migration.js.map +1 -1
  22. package/lib/opencode-go-one-shot.d.ts +6 -0
  23. package/lib/opencode-go-one-shot.js +41 -4
  24. package/lib/opencode-go-one-shot.js.map +1 -1
  25. package/lib/opencode-go-planner.d.ts +39 -24
  26. package/lib/opencode-go-planner.js +275 -207
  27. package/lib/opencode-go-planner.js.map +1 -1
  28. package/lib/opencode-go-sync.d.ts +16 -3
  29. package/lib/opencode-go-sync.js +24 -0
  30. package/lib/opencode-go-sync.js.map +1 -1
  31. package/lib/opencode-go-writer.d.ts +17 -1
  32. package/lib/opencode-go-writer.js +111 -16
  33. package/lib/opencode-go-writer.js.map +1 -1
  34. package/package.json +2 -2
  35. package/src/index.ts +100 -25
  36. package/src/opencode-go-diagnose.ts +124 -70
  37. package/src/opencode-go-grouping.ts +14 -85
  38. package/src/opencode-go-host-catalog.ts +125 -0
  39. package/src/opencode-go-journal.ts +5 -3
  40. package/src/opencode-go-migrate.ts +352 -95
  41. package/src/opencode-go-migration.ts +116 -2
  42. package/src/opencode-go-one-shot.ts +49 -4
  43. package/src/opencode-go-planner.ts +293 -216
  44. package/src/opencode-go-sync.ts +40 -2
  45. package/src/opencode-go-writer.ts +127 -15
@@ -133,6 +133,15 @@ export function unclaimedRecordState(
133
133
  /** Migration record seam. `write` / `legacyKeys` are optional so read-only test stores keep working. */
134
134
  export interface MigrationStateStore {
135
135
  read(): Promise<MigrationRecord | undefined>
136
+ /**
137
+ * H4: strict read for write paths — `undefined` ONLY when the slot does not
138
+ * exist; a store error is THROWN so the caller (onOwnWrite /
139
+ * loadMigrationStatus({strict:true})) can fail closed instead of mistaking
140
+ * an unreadable record for "no prior record" and overwriting a live
141
+ * MigrationRecord (backup/planHash/movedIds would be lost). The plain
142
+ * `read()` keeps its tolerant read-only semantics for status/plan paths.
143
+ */
144
+ readStrict?(): Promise<MigrationRecord | undefined>
136
145
  /** Queue-serialized atomic slot replacement (same models-store queue as the ledger). */
137
146
  write?(record: MigrationRecord): Promise<void>
138
147
  /** Advisory: unscoped legacy keys found in the shared store (reported, never claimed). */
@@ -294,6 +303,86 @@ export function appliedFingerprintFieldsOf(
294
303
  return { identity, appliedFingerprint: appliedFingerprintOf(identity, managedIds) }
295
304
  }
296
305
 
306
+ /** Inputs to `ownWriteRecordUpdate` — everything the go writer knows post-write. */
307
+ export interface OwnWriteRecordInput {
308
+ /** The migration record read BEFORE this update (strict read; may be undefined). */
309
+ record: MigrationRecord | undefined
310
+ /** Live llm-pi-ai descriptor (or raw providers map) read AFTER the settings write. */
311
+ source: SettingsDescriptor | Record<string, unknown> | undefined
312
+ /** Configured go route ids (the identity comparison universe). */
313
+ routes: readonly string[]
314
+ /** The route this write landed on. */
315
+ route: string
316
+ /** Ledger-managed ids just committed for this route (sorted by the writer). */
317
+ managedIds: readonly string[]
318
+ /** True when this write was a whole-section unset (the ledger key was deleted). */
319
+ unset?: boolean
320
+ }
321
+
322
+ /**
323
+ * The ONE post-own-write migration record update — extracted from index.ts so
324
+ * tests (H2: the 0.11.x four-route convergence) drive the exact code the
325
+ * plugin runs. Semantics:
326
+ * - `appliedIdentityRoutes` shrinks to the routes still PRESENT in settings
327
+ * (0.12.0 catalog-reuse unsets the legacy protocol routes; keeping them in
328
+ * the identity set would make every later read look like drift) — with the
329
+ * just-written route always included (M2: prevents the degenerate
330
+ * constant `sha256('{}')` identity when every section is gone).
331
+ * - `appliedManagedIds[route]` is SET for a normal write and DELETED for an
332
+ * unset (M2: the ledger key was deleted — a persisted `[]` entry no ledger
333
+ * backs makes the stored fingerprint disagree with every status read and
334
+ * costs a fingerprint-healed round).
335
+ * - `appliedIdentity` / `appliedFingerprint` are recomputed from the live
336
+ * sections + the updated managed-id map, so the persisted record always
337
+ * matches what `migrationStatusOf` recomputes (no phantom heal).
338
+ * Pure: returns the next record; the caller persists it.
339
+ */
340
+ export function ownWriteRecordUpdate(input: OwnWriteRecordInput): MigrationRecord {
341
+ const sections = readGoProviderSections(input.source, input.routes) ?? {}
342
+ const presentRoutes = Object.keys(sections)
343
+ const prior = input.record ?? {}
344
+ // The just-written route joins the identity set ONLY on a real write. An
345
+ // unset drops it together with its section: identity and fingerprint are
346
+ // always recomputed from the SAME list the status read will use, so the
347
+ // degenerate empty-set hash (`sha256('{}')`) can only ever arise on BOTH
348
+ // sides simultaneously — never as a one-sided drift.
349
+ const includeRoute = input.unset !== true
350
+ const identityRoutes = [...new Set([
351
+ ...(prior.appliedIdentityRoutes ?? presentRoutes).filter((candidate) =>
352
+ presentRoutes.includes(candidate) || (includeRoute && candidate === input.route)),
353
+ ...(includeRoute ? [input.route] : []),
354
+ ])]
355
+ const appliedManagedIds: Record<string, string[]> = { ...(prior.appliedManagedIds ?? {}) }
356
+ if (input.unset === true) delete appliedManagedIds[input.route]
357
+ else appliedManagedIds[input.route] = [...input.managedIds].sort((a, b) => a.localeCompare(b))
358
+ // P2-②: an EMPTY identity route set means "no verifiable applied identity".
359
+ // Persisting `appliedIdentityRoutes: []` (+ the constant `sha256('{}')`
360
+ // identity it hashes to) would make ANY later config — including an
361
+ // unmigrated legacy-inline one — constant-match and read as `applied`
362
+ // (migration-gate penetration). Drop the applied-state fields instead: the
363
+ // record keeps everything else and state detection falls back to the
364
+ // closed-gate legacy path. `migrationStateOf` carries the matching
365
+ // read-side guard, so an old record that already carries `[]` cannot
366
+ // penetrate either.
367
+ if (identityRoutes.length === 0) {
368
+ const rest = { ...prior, appliedManagedIds }
369
+ delete rest.appliedIdentity
370
+ delete rest.appliedIdentityRoutes
371
+ delete rest.appliedFingerprint
372
+ return rest
373
+ }
374
+ const { identity, appliedFingerprint } = appliedFingerprintFieldsOf(
375
+ sections, { appliedIdentityRoutes: identityRoutes }, appliedManagedIds,
376
+ )
377
+ return {
378
+ ...prior,
379
+ appliedIdentity: identity,
380
+ appliedIdentityRoutes: identityRoutes,
381
+ appliedManagedIds,
382
+ appliedFingerprint,
383
+ }
384
+ }
385
+
297
386
  /**
298
387
  * Ledger ids for exactly the routes that HAVE a ledger entry. This is the
299
388
  * managed-id half of the shared fingerprint convention above: no entry means
@@ -339,8 +428,15 @@ export function migrationStateOf(
339
428
  if (sections === undefined || Object.keys(sections).length === 0) return 'absent'
340
429
  const fingerprint = fingerprintSection(sections)
341
430
  if (record?.appliedIdentity !== undefined) {
342
- return fingerprintGoIdentity(sections, record.appliedIdentityRoutes) === record.appliedIdentity
343
- ? 'applied' : 'drifted'
431
+ // P2-②: an explicit EMPTY appliedIdentityRoutes hashes every config to the
432
+ // same constant (`sha256('{}')`), so it must never count as a valid
433
+ // applied identity — treat it as absent and fall through to the legacy
434
+ // fingerprint comparison (which can only match the truly applied bytes).
435
+ const identityRoutes = record.appliedIdentityRoutes
436
+ if (identityRoutes === undefined || identityRoutes.length > 0) {
437
+ return fingerprintGoIdentity(sections, identityRoutes) === record.appliedIdentity
438
+ ? 'applied' : 'drifted'
439
+ }
344
440
  }
345
441
  // Backward compatibility with the pre-§14.7.4 full-section fingerprint.
346
442
  if (record?.appliedFingerprint !== undefined && fingerprint === record.appliedFingerprint) return 'applied'
@@ -383,7 +479,16 @@ export function migrationStatusOf(
383
479
  appliedFingerprint: record?.appliedFingerprint,
384
480
  legacyFingerprint: record?.legacyFingerprint,
385
481
  applying: record?.applying === true,
482
+ // P2-② (agy final): a degenerate record (`appliedIdentityRoutes: []`,
483
+ // constant `sha256('{}')` identity) constant-matches ANY config, so the
484
+ // raw identity equality below is trivially true — gating `fingerprintHealed`
485
+ // on the same valid-identity condition `migrationStateOf` uses keeps the
486
+ // §14.7.4 self-heal write-back (index.ts persists `expectedFingerprint`
487
+ // when this flag fires) away from records no state detector reads as
488
+ // applied. `undefined` routes stay valid (pre-identity-list records fall
489
+ // back to the routes present in settings).
386
490
  fingerprintHealed: record?.appliedIdentity !== undefined
491
+ && (record.appliedIdentityRoutes === undefined || record.appliedIdentityRoutes.length > 0)
387
492
  && identity === record.appliedIdentity
388
493
  && record.appliedFingerprint !== expectedFingerprint,
389
494
  expectedFingerprint,
@@ -508,6 +613,15 @@ export function createFileMigrationStateStore(
508
613
  if (profileKey !== undefined && raw.profileKey !== profileKey) return undefined
509
614
  return raw as unknown as MigrationRecord
510
615
  },
616
+ // H4: write paths must see store errors, never "no prior record". Only a
617
+ // genuinely absent slot (or a foreign stamp, which is an ownership
618
+ // verdict — not an error) reads as undefined here.
619
+ async readStrict(): Promise<MigrationRecord | undefined> {
620
+ const raw = await accessor.readRaw(slot)
621
+ if (!isRecord(raw)) return undefined
622
+ if (profileKey !== undefined && raw.profileKey !== profileKey) return undefined
623
+ return raw as unknown as MigrationRecord
624
+ },
511
625
  async write(record: MigrationRecord): Promise<void> {
512
626
  // writeRaw is queue-serialized atomic temp+rename, i.e. the SAME queue
513
627
  // that persists the ownership ledger (§14.7.4: settings → ledger → fingerprint).
@@ -225,6 +225,12 @@ export interface OneShotDeps {
225
225
  resolveEntries(apiKey: string): Promise<readonly GoModelRecord[]>
226
226
  /** Public catalog ids for id classification; undefined = fail-closed. */
227
227
  resolvePublicCatalogIds(apiKey: string, entries: readonly GoModelRecord[]): Promise<readonly string[] | undefined>
228
+ /**
229
+ * 0.12.1: host runtime catalog ids for opencode-go. `null` FAILS THE RUN
230
+ * CLOSED (zero writes) — without it the desired listing cannot be proven
231
+ * servable and the host would reject the whole mutate anyway.
232
+ */
233
+ resolveHostCatalogIds(): Promise<readonly string[] | null>
228
234
  /** ask-user seam, resolved lazily at invocation time. */
229
235
  resolveAsk(): AskServiceShape | undefined
230
236
  /**
@@ -547,6 +553,8 @@ function wrapReferenceRewrite(
547
553
  interface SharedPlanInputs {
548
554
  entries: readonly GoModelRecord[]
549
555
  publicCatalogIds: readonly string[] | undefined
556
+ /** Host runtime catalog ids (0.12.1); the run aborts before planning on null. */
557
+ hostCatalogIds: readonly string[]
550
558
  keyFingerprint: string
551
559
  }
552
560
 
@@ -578,6 +586,7 @@ function buildTargetDeps(
578
586
  logger: deps.logger,
579
587
  entries: shared.entries,
580
588
  publicCatalogIds: shared.publicCatalogIds,
589
+ hostCatalogIds: shared.hostCatalogIds,
581
590
  routes: deps.goConfig.routes,
582
591
  ref: deps.goConfig.ref,
583
592
  keyFingerprint: shared.keyFingerprint,
@@ -650,14 +659,16 @@ const CONFIRM_PROCEED = '执行迁移'
650
659
  const CONFIRM_CANCEL = '取消'
651
660
 
652
661
  /**
653
- * Slot summary INCLUDING the route field values (api/baseURL, review M8) —
654
- * the user approves the exact endpoints, not just route names.
662
+ * Slot summary INCLUDING the route field values (review M8) — with the
663
+ * catalog-reuse shape the written fields are displayName/apiKeyEnv only (the
664
+ * endpoint lives in pi-ai's builtin catalog; api/baseURL are stripped), plus
665
+ * an explicit marker for legacy routes this run will whole-section unset.
655
666
  */
656
667
  function slotSummary(plan: MigrationPlan): string {
657
668
  const slots = (['chat', 'msg', 'resp', 'google'] as GoRouteSlot[])
658
669
  .map((slot) => ({ slot, route: plan.routes.find((candidate) => candidate.slot === slot) }))
659
670
  .filter((item): item is { slot: GoRouteSlot; route: MigrationPlan['routes'][number] } => item.route !== undefined)
660
- .map((item) => `${item.slot}→${item.route.route} (${item.route.fields.api}, ${item.route.fields.baseURL})`)
671
+ .map((item) => `${item.slot}→${item.route.route} (${item.route.fields.displayName}, ${item.route.fields.apiKeyEnv}${item.route.action === 'unset' ? ', 整段 unset' : ''})`)
661
672
  return slots.length > 0 ? slots.join('、') : '(no route changes)'
662
673
  }
663
674
 
@@ -727,6 +738,11 @@ function perIdActionLines(plan: MigrationPlan): string[] {
727
738
  return lines
728
739
  }
729
740
 
741
+ /** Host-catalog lag ids of a plan (official ids excluded from the desired write). */
742
+ function hostCatalogLagOf(plan: MigrationPlan): string[] {
743
+ return plan.hostCatalogLagIds ?? []
744
+ }
745
+
730
746
  function buildConfirmQuestion(stamp: string, prepared: PreparedTarget[], modelsStoreBackup: string | undefined, rewriteRefs: RewriteRefMode): AskItemShape {
731
747
  const lines: string[] = []
732
748
  lines.push('即将执行 opencode-go 一键迁移(写入前最后确认)。')
@@ -759,6 +775,17 @@ function buildConfirmQuestion(stamp: string, prepared: PreparedTarget[], modelsS
759
775
  for (const line of item.plan.managedAfterMigration.split('\n')) lines.push(` ${line}`)
760
776
  }
761
777
  lines.push('')
778
+ // 0.12.1: host-catalog lag ids — the section the user most needs to see,
779
+ // because these OFFICIAL ids are deliberately not written.
780
+ const lagIds = hostCatalogLagOf(prepared[0]!.plan)
781
+ lines.push('【宿主目录滞后(官方有、宿主内置目录没有 —— 本轮不写入)】')
782
+ if (lagIds.length > 0) {
783
+ lines.push(` ${lagIds.join(', ')}`)
784
+ lines.push(' 宿主侧滞后,非本插件问题;宿主升级后 sync 自动纳入。')
785
+ } else {
786
+ lines.push(' (无 —— 官方 listing 全部被宿主目录覆盖)')
787
+ }
788
+ lines.push('')
762
789
  lines.push(`【槽位】${slotSummary(prepared[0]!.plan)}(按 opencode.go.routes 配置;未配置的槽不创建,google 缺省不建)`)
763
790
  lines.push('')
764
791
  // Review M8 (the most important item): with --rewrite-refs in effect, the
@@ -1059,7 +1086,21 @@ export async function runMigrateGoOneShot(
1059
1086
  return { kind: 'error', text: `migrate-go: official listing unavailable (${err instanceof Error ? err.message : String(err)}); zero writes` }
1060
1087
  }
1061
1088
  const publicCatalogIds = await deps.resolvePublicCatalogIds(apiKey, entries)
1062
- const shared: SharedPlanInputs = { entries, publicCatalogIds, keyFingerprint: fingerprintKey(apiKey.trim()) }
1089
+ // 0.12.1 fail-closed: no host runtime catalog → the run aborts before any
1090
+ // plan/write. Never fail open onto the unverified full listing.
1091
+ const hostCatalogIds = await deps.resolveHostCatalogIds()
1092
+ if (hostCatalogIds === null) {
1093
+ return {
1094
+ kind: 'error',
1095
+ text: [
1096
+ 'migrate-go: host runtime catalog unavailable(host-catalog-unavailable)—— 已中止:零写入。',
1097
+ ' 宿主 llm 服务未能返回 opencode-go 的内置目录(discoverModels 失败/未注册)。',
1098
+ ' 继续迁移会写入宿主目录不认识的模型 id(宿主对整条 mutate fail-closed 拒绝,0.12.0 故障根因);',
1099
+ ' 待宿主目录可读后重跑 /model-sync migrate-go。',
1100
+ ].join('\n'),
1101
+ }
1102
+ }
1103
+ const shared: SharedPlanInputs = { entries, publicCatalogIds, hostCatalogIds, keyFingerprint: fingerprintKey(apiKey.trim()) }
1063
1104
 
1064
1105
  const prepared: PreparedTarget[] = []
1065
1106
  const notMigratable: string[] = []
@@ -1296,6 +1337,10 @@ export async function runMigrateGoOneShot(
1296
1337
  const add = item.plan.idActions.filter((action) => action.op === 'add' || action.op === 'move').length
1297
1338
  const del = item.plan.idActions.filter((action) => action.op === 'delete').length
1298
1339
  lines.push(` [${item.target.key}] slots: ${slotSummary(item.plan)}; +${add}/-${del}; ${desiredCount} managed models; state after: ${postPlan.state}`)
1340
+ const lagIds = hostCatalogLagOf(item.plan)
1341
+ if (lagIds.length > 0) {
1342
+ lines.push(` host-catalog lag (未写入,宿主升级后自动纳入): ${lagIds.join(', ')}`)
1343
+ }
1299
1344
  lines.push(` backup: ${item.patchBackup.backup}`)
1300
1345
  lines.push(` rollback: /model-sync migrate rollback --plan ${item.plan.planHash}`)
1301
1346
  }