@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,276 @@
1
+ import { type GoModelRecord } from './opencode-go-source.ts';
2
+ import { type GoRouteSlot } from './opencode-go-grouping.ts';
3
+ import type { GoOwnershipStore } from './opencode-go-writer.ts';
4
+ import type { GoJournalStore } from './opencode-go-journal.ts';
5
+ import { type MigrateDeps, type MigrationPlan, type ReferenceRewrite, type RewriteRefMode } from './opencode-go-migrate.ts';
6
+ import type { MigrationStateStore } from './opencode-go-migration.ts';
7
+ import { type PatchFileIo, type PatchFs } from './opencode-go-patch-file.ts';
8
+ import type { Logger, SettingsService } from './writer.ts';
9
+ export interface AskOptionShape {
10
+ label: string;
11
+ description?: string;
12
+ }
13
+ export interface AskItemShape {
14
+ id: string;
15
+ question: string;
16
+ detail?: string;
17
+ header?: string;
18
+ options?: AskOptionShape[];
19
+ }
20
+ export interface AskAnswerItemShape {
21
+ id: string;
22
+ selected?: string[];
23
+ custom?: string;
24
+ }
25
+ export interface AskServiceShape {
26
+ ask(request: {
27
+ questions: AskItemShape[];
28
+ agent?: unknown;
29
+ signal?: AbortSignal;
30
+ }): Promise<{
31
+ answers?: AskAnswerItemShape[];
32
+ }>;
33
+ }
34
+ export interface OneShotFs extends PatchFs {
35
+ readdir(path: string): Promise<string[]>;
36
+ /**
37
+ * Exclusive-claim + atomic write in one step: creates `path` with O_EXCL
38
+ * semantics (returns `false` when the name is already taken — the caller
39
+ * retries the next sequence suffix), then replaces its content through a
40
+ * sibling temp file + rename so a crash never leaves a torn backup. This is
41
+ * how backups are born: the FILESYSTEM decides "name taken", never a
42
+ * readdir snapshot two racers can read identically.
43
+ */
44
+ writeFileExclusive(path: string, data: string, mode?: number): Promise<boolean>;
45
+ }
46
+ export interface MigrateGoFlags {
47
+ allProfiles: boolean;
48
+ adopt: boolean;
49
+ pruneUserExtra: boolean;
50
+ rewriteRefs: RewriteRefMode;
51
+ }
52
+ export declare const MIGRATE_GO_USAGE: string;
53
+ /**
54
+ * Strict flag parsing: unknown flags (including --yes/--auto — there is no
55
+ * bypass semantics on this command) and stray positional words are errors
56
+ * carrying the usage text.
57
+ */
58
+ export declare function parseMigrateGoFlags(args: readonly string[]): {
59
+ ok: true;
60
+ flags: MigrateGoFlags;
61
+ } | {
62
+ ok: false;
63
+ error: string;
64
+ };
65
+ export interface OneShotDeps {
66
+ /** dsh home (resolveDshHome()); anchors the storages dir + profiles dir. */
67
+ home: string;
68
+ /** Absolute path of the shared models-store.json (MODELS_STORE_PATH). */
69
+ modelsStorePath: string;
70
+ /** Profiles directory; default `<home>/profiles`. */
71
+ profilesDir?: string;
72
+ /** Filesystem subset for discovery / backups / restore / log. */
73
+ fs: OneShotFs;
74
+ /**
75
+ * Sync-read + atomic-write io for one profile patch file — the sync read is
76
+ * what lets the file-backed settings adapter satisfy the SYNC describe()
77
+ * contract the migration engine builds plans through.
78
+ */
79
+ patchIoFor(patchPath: string): PatchFileIo;
80
+ /** Current profile identity (resolveProfileKey + dir derivation at wiring). */
81
+ currentProfile?: {
82
+ key?: string;
83
+ dir?: string;
84
+ };
85
+ /** Host settings seam serving the CURRENT profile's settings document. */
86
+ currentSettings?: SettingsService;
87
+ /**
88
+ * Host settings seam for the enabled flip (prefers settings.update patch
89
+ * merge, falls back to mutate; undefined → manual guidance in the report).
90
+ */
91
+ hostSettings?: (SettingsService & {
92
+ update?(ns: string, patch: object): Promise<void>;
93
+ }) | undefined;
94
+ /** Resolved go config projection (readGoRuntimeConfig at the wiring site). */
95
+ goConfig: {
96
+ routes: Partial<Record<GoRouteSlot, string>>;
97
+ ref: string;
98
+ pinnedModels: readonly string[];
99
+ adoptDisabled: boolean;
100
+ };
101
+ /** Credential value resolution (resolveRouteCredentialValue at the wiring). */
102
+ resolveCredential(): Promise<{
103
+ value: string | undefined;
104
+ ref: string;
105
+ }>;
106
+ /** Official listing (credential-gated; test seams win before any fetch). */
107
+ resolveEntries(apiKey: string): Promise<readonly GoModelRecord[]>;
108
+ /** Public catalog ids for id classification; undefined = fail-closed. */
109
+ resolvePublicCatalogIds(apiKey: string, entries: readonly GoModelRecord[]): Promise<readonly string[] | undefined>;
110
+ /** ask-user seam, resolved lazily at invocation time. */
111
+ resolveAsk(): AskServiceShape | undefined;
112
+ /**
113
+ * Per-profile store pair. The injected test seams win at the wiring and are
114
+ * returned verbatim; the production fallback scopes both file-backed stores
115
+ * with the given profile key in the shared models-store.json.
116
+ */
117
+ storesFor(profileKey: string): {
118
+ ownership: GoOwnershipStore;
119
+ migration: MigrationStateStore;
120
+ };
121
+ /** Write-ahead journal store for post-apply cleanup; optional. */
122
+ journalStore?: GoJournalStore;
123
+ /** M-5 single-flight check (go scheduler lock). */
124
+ isSyncInFlight(): boolean;
125
+ /** Reference rewriter seam — CURRENT profile only. */
126
+ applyReferenceRewrite?: ((rewrite: ReferenceRewrite) => Promise<void>) | undefined;
127
+ /**
128
+ * TEST FAULT INJECTION ONLY (mirrors MigrateDeps.faultInjectOp). When set,
129
+ * ownership-ledger writes whose key starts with this prefix throw, which is
130
+ * how the mid-apply failure + byte-restore path is exercised. Production
131
+ * callers never set it.
132
+ */
133
+ faultOwnershipWriteOnKeyPrefix?: string | undefined;
134
+ logger: Logger;
135
+ /** Clock (never reads Date.now() directly). */
136
+ now(): number;
137
+ }
138
+ /** Local-time `YYYYMMDD-HHMMSS` stamp — the backup/log naming convention. */
139
+ export declare function formatStamp(date: Date): string;
140
+ /** sha256 hex digest of a text — the staleness / concurrent-modification detector. */
141
+ export declare function sha256Of(text: string): string;
142
+ /**
143
+ * Create `<base>` / `<base>.<seq>` exclusively: `writeFileExclusive` returns
144
+ * false when the name is taken (O_EXCL), and only then does the loop advance
145
+ * the sequence suffix. No readdir snapshot is consulted, so two processes
146
+ * racing inside the same second can never both "win" the same backup name —
147
+ * the loser retries onto `.<seq+1>` and both files survive.
148
+ */
149
+ export declare function writeExclusiveBackup(fs: OneShotFs, base: string, text: string, mode?: number): Promise<string>;
150
+ /**
151
+ * Retention: keep the `keep` newest backups matching `pattern` in `dirPath`
152
+ * (sorted by filename timestamp, then sequence) and unlink the rest. Returns
153
+ * the removed names. Best-effort per file: unlink errors are reported, not
154
+ * thrown — retention must never fail a migration that already backed up.
155
+ */
156
+ export declare function pruneBackups(fs: OneShotFs, dirPath: string, pattern: RegExp, keep?: number): Promise<string[]>;
157
+ interface LegacyStub {
158
+ route: string;
159
+ ids: string[];
160
+ }
161
+ /**
162
+ * The legacy stub definition from the approved behavior: an `opencode-go*`
163
+ * section that carries a models array but NO api/baseURL — the handwritten
164
+ * pre-migration entry. Any other provider section is ignored here.
165
+ */
166
+ export declare function legacyStubsOf(providers: unknown, goRouteIds: readonly string[]): LegacyStub[];
167
+ interface Target {
168
+ /** Profile key (store scoping + report label). */
169
+ key: string;
170
+ /** Profile directory (backup anchors). */
171
+ dir: string;
172
+ patchPath: string;
173
+ /** True when this target is served by the host settings seam. */
174
+ isCurrent: boolean;
175
+ stubs: LegacyStub[];
176
+ }
177
+ interface ChangeTracker {
178
+ patchChanged: boolean;
179
+ storeChanged: boolean;
180
+ /**
181
+ * sha256 of the patch file's content recorded IMMEDIATELY after this
182
+ * target's last settings write (the post-write baseline). Restore only
183
+ * replaces the file while its current content still hashes to this value;
184
+ * `undefined` (file unreadable after the write) makes restore refuse —
185
+ * fail closed instead of clobbering an unbaselined file.
186
+ */
187
+ patchPostWriteSha?: string | undefined;
188
+ }
189
+ interface BackupRecord {
190
+ source: string;
191
+ backup: string;
192
+ /** sha256 of the source content captured at backup time — the pre-apply
193
+ * staleness check re-verifies the source against this before any write. */
194
+ sourceSha: string;
195
+ }
196
+ interface RestoreOutcome {
197
+ line: string;
198
+ /** True only when the file was actually replaced/removed. */
199
+ restored: boolean;
200
+ }
201
+ /**
202
+ * Restore one changed patch file from its backup, but ONLY while the on-disk
203
+ * content still hashes to the post-write baseline this run recorded right
204
+ * after its last write. Anything else means another process touched the file
205
+ * after us: never overwrite it — report "concurrent modification detected,
206
+ * not restored" with the backup path so a human can decide. The write itself
207
+ * goes through the SAME atomic io (tmp + rename, mode preserved) the apply
208
+ * used — never a raw writeFile.
209
+ */
210
+ export declare function restorePatchIfUnchanged(deps: OneShotDeps, record: BackupRecord, postWriteSha: string | undefined): Promise<RestoreOutcome>;
211
+ /**
212
+ * Remove a models-store this run CREATED, but only while its content still
213
+ * matches this run's post-write baseline; a store another process has touched
214
+ * since is left in place and reported for manual handling.
215
+ */
216
+ export declare function removeStoreIfUnchanged(deps: OneShotDeps, postWriteSha: string | undefined): Promise<RestoreOutcome>;
217
+ /**
218
+ * Restore the models-store from its backup through the remote-catalog store
219
+ * accessor — the SAME promise queue + cross-process lock every other
220
+ * models-store writer uses — instead of overwriting the file behind its back.
221
+ * Review M5: the restore is a whole-document BYTE replacement
222
+ * (`restoreRawDocument`: exact backup bytes staged via tmp + rename under the
223
+ * lock), not a per-key rebuild — the backup's key order survives verbatim and
224
+ * the restore is transactional. The same post-write-baseline check as the
225
+ * patch restore applies first, and a backup that is not valid JSON refuses
226
+ * loudly before anything is touched. Round 3: the baseline is ALSO
227
+ * re-verified INSIDE the store's queue + cross-process lock (the accessor's
228
+ * `expectedCurrentSha`), so a writer that landed between the pre-lock check
229
+ * and the restore is refused at the write site and reported as concurrent
230
+ * modification instead of clobbering the foreign bytes.
231
+ */
232
+ export declare function restoreModelsStoreIfUnchanged(deps: OneShotDeps, backupPath: string, postWriteSha: string | undefined): Promise<RestoreOutcome>;
233
+ /**
234
+ * Re-hash every target's patch file and drop the ones whose content changed
235
+ * after their backup was taken (the backup → apply window, review Major 2
236
+ * item 3): a plan computed from stale bytes is never applied, and a dropped
237
+ * target writes nothing.
238
+ */
239
+ export declare function dropStaleTargets(deps: OneShotDeps, prepared: readonly PreparedTarget[]): Promise<{
240
+ ready: PreparedTarget[];
241
+ stale: {
242
+ key: string;
243
+ patchPath: string;
244
+ }[];
245
+ }>;
246
+ export type StoreFreshness = {
247
+ ok: true;
248
+ } | {
249
+ ok: false;
250
+ reason: string;
251
+ };
252
+ /**
253
+ * Verify the shared models-store has not drifted inside the backup → apply
254
+ * window: with a backup, its content must still hash to the backup-time
255
+ * value; without one (the file did not exist at backup time), it must still
256
+ * not exist — a store another process created meanwhile must never end up
257
+ * deleted by this run's rollback path.
258
+ */
259
+ export declare function verifyStoreFreshness(deps: OneShotDeps, modelsStoreBackup: string | undefined, storeSourceSha: string | undefined, storeExistedBefore: boolean): Promise<StoreFreshness>;
260
+ interface PreparedTarget {
261
+ target: Target;
262
+ plan: MigrationPlan;
263
+ migrateDeps: MigrateDeps;
264
+ tracker: ChangeTracker;
265
+ stubs: LegacyStub[];
266
+ patchBackup: BackupRecord;
267
+ }
268
+ export interface OneShotOutcome {
269
+ kind: 'success' | 'error';
270
+ text: string;
271
+ }
272
+ export declare function runMigrateGoOneShot(deps: OneShotDeps, flags: MigrateGoFlags, invocation: {
273
+ agent?: unknown;
274
+ signal?: AbortSignal;
275
+ }): Promise<OneShotOutcome>;
276
+ export {};