magpie-multi-usage 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,722 @@
1
+ import {
2
+ computeMonthContentHash,
3
+ isValidCalendarDay,
4
+ isValidCalendarMonth,
5
+ SCHEMA_VERSION,
6
+ } from "./aggregator.mjs";
7
+ import { normalizeBranch, normalizePrefix, normalizeRepo } from "./config.mjs";
8
+ import { DEVICE_ID_PATTERN } from "./magpie-client.mjs";
9
+
10
+ const DEFAULT_API_BASE_URL = "https://api.github.com";
11
+ const DAY_NUMERIC_FIELDS = [
12
+ "calls",
13
+ "errors",
14
+ "excludedForwarded",
15
+ "input",
16
+ "output",
17
+ "cacheRead",
18
+ "cacheWrite",
19
+ "cost",
20
+ ];
21
+
22
+ export class GitHubStoreError extends Error {
23
+ constructor(code, message, { status = null, cause } = {}) {
24
+ super(message, cause ? { cause } : undefined);
25
+ this.name = "GitHubStoreError";
26
+ this.code = code;
27
+ this.status = status;
28
+ }
29
+ }
30
+
31
+ function encodeRepoPath(relativePath) {
32
+ return relativePath
33
+ .split("/")
34
+ .filter(Boolean)
35
+ .map((segment) => encodeURIComponent(segment))
36
+ .join("/");
37
+ }
38
+
39
+ function decodeBase64Json(base64Content, label) {
40
+ if (typeof base64Content !== "string") {
41
+ throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", `${label} is missing base64 content.`);
42
+ }
43
+ const normalized = base64Content.replace(/\s+/g, "");
44
+ let text;
45
+ try {
46
+ text = Buffer.from(normalized, "base64").toString("utf8");
47
+ } catch (error) {
48
+ throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", `${label} contains invalid base64.`, { cause: error });
49
+ }
50
+ try {
51
+ return JSON.parse(text);
52
+ } catch (error) {
53
+ throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", `${label} contains invalid JSON.`, { cause: error });
54
+ }
55
+ }
56
+
57
+ function isNonNegativeFinite(value) {
58
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
59
+ }
60
+
61
+ function validateBreakdownMap(map, label) {
62
+ if (map === undefined) {
63
+ return;
64
+ }
65
+ if (map === null || typeof map !== "object" || Array.isArray(map)) {
66
+ throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", `${label} must be an object.`);
67
+ }
68
+ for (const key of Object.keys(map)) {
69
+ const bucket = map[key];
70
+ if (bucket === null || typeof bucket !== "object" || Array.isArray(bucket)) {
71
+ throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", `${label}.${key} must be an object.`);
72
+ }
73
+ for (const field of ["calls", "errors", "input", "output", "cacheRead", "cacheWrite", "cost"]) {
74
+ if (bucket[field] !== undefined && !isNonNegativeFinite(bucket[field])) {
75
+ throw new GitHubStoreError(
76
+ "GITHUB_INVALID_PAYLOAD",
77
+ `${label}.${key}.${field} must be a non-negative finite number.`,
78
+ );
79
+ }
80
+ }
81
+ }
82
+ }
83
+
84
+ export function validateRemoteManifest(manifest, expectedDeviceId) {
85
+ if (manifest === null || typeof manifest !== "object" || Array.isArray(manifest)) {
86
+ throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", "Remote manifest must be a JSON object.");
87
+ }
88
+ if (manifest.schemaVersion !== SCHEMA_VERSION) {
89
+ throw new GitHubStoreError(
90
+ "GITHUB_UNSUPPORTED_SCHEMA",
91
+ `Unsupported remote manifest schemaVersion: ${String(manifest.schemaVersion)}.`,
92
+ );
93
+ }
94
+ if (manifest.deviceId !== expectedDeviceId) {
95
+ throw new GitHubStoreError(
96
+ "GITHUB_DEVICE_MISMATCH",
97
+ `Remote manifest deviceId (${String(manifest.deviceId)}) does not match directory (${expectedDeviceId}).`,
98
+ );
99
+ }
100
+ if (manifest.displayName !== undefined && typeof manifest.displayName !== "string") {
101
+ throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", "Remote manifest displayName must be a string.");
102
+ }
103
+ if (manifest.months === null || typeof manifest.months !== "object" || Array.isArray(manifest.months)) {
104
+ throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", "Remote manifest months must be an object.");
105
+ }
106
+ for (const monthKey of Object.keys(manifest.months)) {
107
+ const entry = manifest.months[monthKey];
108
+ if (!isValidCalendarMonth(monthKey)) {
109
+ throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", `Invalid month key in manifest: ${monthKey}.`);
110
+ }
111
+ if (
112
+ entry === null ||
113
+ typeof entry !== "object" ||
114
+ typeof entry.sha256 !== "string" ||
115
+ !/^[0-9a-f]{64}$/.test(entry.sha256)
116
+ ) {
117
+ throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", `Invalid month metadata for ${monthKey}.`);
118
+ }
119
+ }
120
+ return manifest;
121
+ }
122
+
123
+ export function validateRemoteMonthSnapshot(snapshot, expectedDeviceId, expectedMonth, expectedSha256 = "") {
124
+ if (snapshot === null || typeof snapshot !== "object" || Array.isArray(snapshot)) {
125
+ throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", "Remote month snapshot must be a JSON object.");
126
+ }
127
+ if (snapshot.schemaVersion !== SCHEMA_VERSION) {
128
+ throw new GitHubStoreError(
129
+ "GITHUB_UNSUPPORTED_SCHEMA",
130
+ `Unsupported remote snapshot schemaVersion: ${String(snapshot.schemaVersion)}.`,
131
+ );
132
+ }
133
+ if (snapshot.deviceId !== expectedDeviceId) {
134
+ throw new GitHubStoreError(
135
+ "GITHUB_DEVICE_MISMATCH",
136
+ `Remote snapshot deviceId (${String(snapshot.deviceId)}) does not match ${expectedDeviceId}.`,
137
+ );
138
+ }
139
+ if (snapshot.month !== expectedMonth || !isValidCalendarMonth(snapshot.month)) {
140
+ throw new GitHubStoreError(
141
+ "GITHUB_MONTH_MISMATCH",
142
+ `Remote snapshot month (${String(snapshot.month)}) does not match ${expectedMonth}.`,
143
+ );
144
+ }
145
+ if (snapshot.days === null || typeof snapshot.days !== "object" || Array.isArray(snapshot.days)) {
146
+ throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", "Remote snapshot days must be an object.");
147
+ }
148
+ for (const dayKey of Object.keys(snapshot.days)) {
149
+ const bucket = snapshot.days[dayKey];
150
+ if (!isValidCalendarDay(dayKey) || dayKey.slice(0, 7) !== expectedMonth) {
151
+ throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", `Invalid day key in snapshot: ${dayKey}.`);
152
+ }
153
+ if (bucket === null || typeof bucket !== "object" || Array.isArray(bucket)) {
154
+ throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", `Invalid day bucket for ${dayKey}.`);
155
+ }
156
+ for (const field of DAY_NUMERIC_FIELDS) {
157
+ if (bucket[field] !== undefined && !isNonNegativeFinite(bucket[field])) {
158
+ throw new GitHubStoreError(
159
+ "GITHUB_INVALID_PAYLOAD",
160
+ `Invalid numeric value at days.${dayKey}.${field}.`,
161
+ );
162
+ }
163
+ }
164
+ validateBreakdownMap(bucket.byModel, `days.${dayKey}.byModel`);
165
+ validateBreakdownMap(bucket.byAgent, `days.${dayKey}.byAgent`);
166
+ validateBreakdownMap(bucket.byProvider, `days.${dayKey}.byProvider`);
167
+ }
168
+
169
+ if (expectedSha256) {
170
+ const actualHash = computeMonthContentHash(snapshot);
171
+ if (actualHash !== expectedSha256) {
172
+ throw new GitHubStoreError(
173
+ "GITHUB_HASH_MISMATCH",
174
+ `Content hash mismatch for ${expectedDeviceId}/${expectedMonth}.json.`,
175
+ );
176
+ }
177
+ }
178
+
179
+ return snapshot;
180
+ }
181
+
182
+ function sanitizeGitHubErrorMessage(status, bodyText) {
183
+ let detail = "";
184
+ if (bodyText) {
185
+ try {
186
+ const parsed = JSON.parse(bodyText);
187
+ if (typeof parsed?.message === "string") {
188
+ detail = parsed.message.trim();
189
+ }
190
+ } catch {
191
+ // Ignore non-JSON body.
192
+ }
193
+ }
194
+ if (status === 401) {
195
+ return "GitHub authentication failed (401). Check your Fine-grained PAT.";
196
+ }
197
+ if (status === 403) {
198
+ return detail
199
+ ? `GitHub access denied or rate limited (403): ${detail}`
200
+ : "GitHub access denied or rate limited (403).";
201
+ }
202
+ if (status === 404) {
203
+ return "GitHub repository or resource not found (404).";
204
+ }
205
+ if (status === 429) {
206
+ return "GitHub API rate limit exceeded (429).";
207
+ }
208
+ return detail ? `GitHub API error (${status}): ${detail}` : `GitHub API error (${status}).`;
209
+ }
210
+
211
+ /**
212
+ * Create a pluggable GitHub relay store for a single dedicated private repo.
213
+ *
214
+ * Uses Git Data API single-commit atomic publishing with compare-and-swap
215
+ * (force: false) branch ref updates so multi-month publishes never leave
216
+ * manifest/month hash mismatches, and re-verifies repo.private === true +
217
+ * immutable repo ID immediately before every write/ref-update.
218
+ */
219
+ export function createGitHubRelayStore({
220
+ repo,
221
+ branch = "",
222
+ prefix = "devices",
223
+ token,
224
+ apiBaseUrl = DEFAULT_API_BASE_URL,
225
+ fetchImpl = globalThis.fetch,
226
+ timeoutMs = 15000,
227
+ pluginVersion = "0.1.1",
228
+ } = {}) {
229
+ const normalizedRepo = normalizeRepo(repo);
230
+ if (!normalizedRepo) {
231
+ throw new GitHubStoreError("GITHUB_REPO_NOT_CONFIGURED", "GitHub repository is not configured.");
232
+ }
233
+ if (typeof token !== "string" || !token.trim()) {
234
+ throw new GitHubStoreError("GITHUB_TOKEN_MISSING", "GitHub token is not configured.");
235
+ }
236
+ if (typeof fetchImpl !== "function") {
237
+ throw new GitHubStoreError("MISSING_FETCH", "A fetch implementation is required.");
238
+ }
239
+
240
+ const [owner, repoName] = normalizedRepo.split("/");
241
+ const configuredBranch = normalizeBranch(branch);
242
+ const normalizedPrefix = normalizePrefix(prefix);
243
+ const cleanToken = token.trim();
244
+ const baseUrl = apiBaseUrl.replace(/\/+$/, "");
245
+
246
+ let verifiedRepoId = null;
247
+
248
+ async function request(method, apiPath, { body, etag } = {}) {
249
+ const url = `${baseUrl}${apiPath}`;
250
+ const headers = {
251
+ Accept: "application/vnd.github+json",
252
+ Authorization: `Bearer ${cleanToken}`,
253
+ "X-GitHub-Api-Version": "2022-11-28",
254
+ "User-Agent": `magpie-multi-usage/${pluginVersion}`,
255
+ };
256
+ if (etag) {
257
+ headers["If-None-Match"] = etag;
258
+ }
259
+ if (body !== undefined) {
260
+ headers["Content-Type"] = "application/json";
261
+ }
262
+
263
+ const controller = new AbortController();
264
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
265
+
266
+ try {
267
+ const response = await fetchImpl(url, {
268
+ method,
269
+ headers,
270
+ body: body !== undefined ? JSON.stringify(body) : undefined,
271
+ signal: controller.signal,
272
+ });
273
+ const responseText = response.status === 304 ? "" : await response.text();
274
+ return {
275
+ status: response.status,
276
+ ok: response.ok,
277
+ headers: response.headers,
278
+ text: responseText,
279
+ };
280
+ } catch (error) {
281
+ throw new GitHubStoreError(
282
+ error?.name === "AbortError" ? "GITHUB_TIMEOUT" : "GITHUB_NETWORK_ERROR",
283
+ error?.name === "AbortError"
284
+ ? "GitHub API request timed out."
285
+ : `GitHub API network error: ${error?.message || "request failed"}`,
286
+ );
287
+ } finally {
288
+ clearTimeout(timer);
289
+ }
290
+ }
291
+
292
+ /**
293
+ * Always verify repo.private === true and immutable repo ID directly against
294
+ * GitHub metadata before reads and immediately before every write/ref update.
295
+ */
296
+ async function verifyPrivateRepo({ requirePush = false } = {}) {
297
+ const res = await request("GET", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repoName)}`);
298
+ if (!res.ok) {
299
+ throw new GitHubStoreError(
300
+ res.status === 401 ? "GITHUB_AUTH_ERROR" : res.status === 404 ? "GITHUB_REPO_NOT_FOUND" : "GITHUB_HTTP_ERROR",
301
+ sanitizeGitHubErrorMessage(res.status, res.text),
302
+ { status: res.status },
303
+ );
304
+ }
305
+
306
+ let meta;
307
+ try {
308
+ meta = JSON.parse(res.text);
309
+ } catch (error) {
310
+ throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", "Repository metadata response was not valid JSON.", {
311
+ cause: error,
312
+ });
313
+ }
314
+
315
+ if (meta?.private !== true) {
316
+ throw new GitHubStoreError(
317
+ "PUBLIC_REPO_REFUSED",
318
+ `Refusing to use public repository "${normalizedRepo}". Use a dedicated private GitHub repository.`,
319
+ { status: 403 },
320
+ );
321
+ }
322
+
323
+ const repoId = meta?.id !== undefined && meta?.id !== null ? String(meta.id) : normalizedRepo;
324
+ if (verifiedRepoId !== null && verifiedRepoId !== repoId) {
325
+ throw new GitHubStoreError(
326
+ "GITHUB_REPO_IDENTITY_CHANGED",
327
+ `Repository identity changed mid-session for "${normalizedRepo}".`,
328
+ { status: 409 },
329
+ );
330
+ }
331
+ verifiedRepoId = repoId;
332
+
333
+ const resolvedBranch = configuredBranch || (typeof meta.default_branch === "string" && meta.default_branch.trim()) || "main";
334
+ const canPush = typeof meta?.permissions?.push === "boolean" ? meta.permissions.push : null;
335
+
336
+ if (requirePush && canPush === false) {
337
+ throw new GitHubStoreError(
338
+ "GITHUB_READ_ONLY_TOKEN",
339
+ "GitHub token does not have write permission for this repository.",
340
+ { status: 403 },
341
+ );
342
+ }
343
+
344
+ return {
345
+ repo: normalizedRepo,
346
+ repoId,
347
+ private: true,
348
+ branch: resolvedBranch,
349
+ prefix: normalizedPrefix,
350
+ canPush,
351
+ };
352
+ }
353
+
354
+ function assertOwnDevicePath(deviceId, relativePath) {
355
+ if (!DEVICE_ID_PATTERN.test(deviceId)) {
356
+ throw new GitHubStoreError("INVALID_DEVICE_ID", `Invalid deviceId: ${String(deviceId)}`);
357
+ }
358
+ const allowedPrefix = `${normalizedPrefix}/${deviceId}/`;
359
+ if (!relativePath.startsWith(allowedPrefix) || relativePath.includes("..")) {
360
+ throw new GitHubStoreError("PATH_OUT_OF_SCOPE", `Refusing write outside ${allowedPrefix}.`);
361
+ }
362
+ }
363
+
364
+ async function requestJsonOrThrow(method, apiPath, { body, label }) {
365
+ const res = await request(method, apiPath, { body });
366
+ if (!res.ok) {
367
+ throw new GitHubStoreError(
368
+ res.status === 409 || res.status === 422 ? "GITHUB_CONFLICT" : res.status === 403 ? "GITHUB_FORBIDDEN" : "GITHUB_HTTP_ERROR",
369
+ sanitizeGitHubErrorMessage(res.status, res.text),
370
+ { status: res.status },
371
+ );
372
+ }
373
+ try {
374
+ return JSON.parse(res.text);
375
+ } catch (error) {
376
+ throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", `Invalid JSON response for ${label}.`, {
377
+ cause: error,
378
+ });
379
+ }
380
+ }
381
+
382
+ async function fetchBlobJson(sha, label) {
383
+ const blob = await requestJsonOrThrow(
384
+ "GET",
385
+ `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repoName)}/git/blobs/${encodeURIComponent(sha)}`,
386
+ { label },
387
+ );
388
+ return decodeBase64Json(blob?.content, label);
389
+ }
390
+
391
+ async function decodeContentsEnvelope(envelope, label) {
392
+ if (typeof envelope?.content === "string" && envelope.content.trim() !== "") {
393
+ return decodeBase64Json(envelope.content, label);
394
+ }
395
+ // GitHub Contents API omits inline content for files > 1 MB; fall back to Git Blobs API.
396
+ if (typeof envelope?.sha === "string" && envelope.sha.trim() !== "") {
397
+ return fetchBlobJson(envelope.sha, label);
398
+ }
399
+ throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", `${label} is missing content and blob SHA.`);
400
+ }
401
+
402
+ return {
403
+ type: "github",
404
+ repo: normalizedRepo,
405
+ prefix: normalizedPrefix,
406
+
407
+ verifyPrivateRepo,
408
+
409
+ async testConnection() {
410
+ const verified = await verifyPrivateRepo({ requirePush: false });
411
+ const branchRes = await request(
412
+ "GET",
413
+ `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repoName)}/branches/${encodeURIComponent(verified.branch)}`,
414
+ );
415
+ if (branchRes.status === 404) {
416
+ return {
417
+ ok: false,
418
+ code: "BRANCH_NOT_FOUND",
419
+ error: `Branch "${verified.branch}" does not exist yet in ${verified.repo}. Initialize the repository with a commit first.`,
420
+ repo: verified.repo,
421
+ repoId: verified.repoId,
422
+ private: true,
423
+ branch: verified.branch,
424
+ branchExists: false,
425
+ canPush: verified.canPush,
426
+ };
427
+ }
428
+ if (!branchRes.ok) {
429
+ throw new GitHubStoreError(
430
+ "GITHUB_HTTP_ERROR",
431
+ sanitizeGitHubErrorMessage(branchRes.status, branchRes.text),
432
+ { status: branchRes.status },
433
+ );
434
+ }
435
+
436
+ return {
437
+ ok: true,
438
+ repo: verified.repo,
439
+ repoId: verified.repoId,
440
+ private: true,
441
+ branch: verified.branch,
442
+ branchExists: true,
443
+ canPush: verified.canPush,
444
+ };
445
+ },
446
+
447
+ /**
448
+ * Atomic single-commit publish scoped strictly to <prefix>/<deviceId>/:
449
+ * creates blobs for every changed month and manifest, builds a tree on the
450
+ * current branch head, re-verifies repo.private === true, and advances the
451
+ * branch ref with force: false (CAS), retrying once on fast-forward conflict.
452
+ */
453
+ async publishDevice({ deviceId, manifest, changedMonths = [], removedMonths = [] }) {
454
+ const repoApiBase = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repoName)}`;
455
+ const sortedMonths = [...changedMonths].sort((a, b) => a.month.localeCompare(b.month));
456
+ const sortedRemoved = [...removedMonths].sort();
457
+
458
+ // Validate all target paths before making any Git object calls.
459
+ const filesToWrite = [];
460
+ for (const item of sortedMonths) {
461
+ if (!isValidCalendarMonth(item.month)) {
462
+ throw new GitHubStoreError("INVALID_MONTH", `Invalid month key: ${item.month}`);
463
+ }
464
+ const monthPath = `${normalizedPrefix}/${deviceId}/${item.month}.json`;
465
+ assertOwnDevicePath(deviceId, monthPath);
466
+ filesToWrite.push({
467
+ month: item.month,
468
+ path: monthPath,
469
+ text: `${JSON.stringify(item.snapshot, null, 2)}\n`,
470
+ });
471
+ }
472
+
473
+ const pathsToDelete = [];
474
+ for (const month of sortedRemoved) {
475
+ if (!isValidCalendarMonth(month)) {
476
+ throw new GitHubStoreError("INVALID_MONTH", `Invalid removed month key: ${month}`);
477
+ }
478
+ const monthPath = `${normalizedPrefix}/${deviceId}/${month}.json`;
479
+ assertOwnDevicePath(deviceId, monthPath);
480
+ pathsToDelete.push(monthPath);
481
+ }
482
+
483
+ const manifestPath = `${normalizedPrefix}/${deviceId}/manifest.json`;
484
+ assertOwnDevicePath(deviceId, manifestPath);
485
+ filesToWrite.push({
486
+ month: null,
487
+ path: manifestPath,
488
+ text: `${JSON.stringify(manifest, null, 2)}\n`,
489
+ });
490
+
491
+ for (let attempt = 0; attempt < 2; attempt += 1) {
492
+ const verified = await verifyPrivateRepo({ requirePush: true });
493
+ const refPath = `${repoApiBase}/git/ref/heads/${encodeRepoPath(verified.branch)}`;
494
+ const refObj = await requestJsonOrThrow("GET", refPath, { label: `ref heads/${verified.branch}` });
495
+ const headSha = refObj?.object?.sha;
496
+ if (typeof headSha !== "string" || !headSha) {
497
+ throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", "Branch reference response is missing head SHA.");
498
+ }
499
+
500
+ const headCommit = await requestJsonOrThrow("GET", `${repoApiBase}/git/commits/${encodeURIComponent(headSha)}`, {
501
+ label: `commit ${headSha}`,
502
+ });
503
+ const baseTreeSha = headCommit?.tree?.sha;
504
+ if (typeof baseTreeSha !== "string" || !baseTreeSha) {
505
+ throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", "Head commit response is missing tree SHA.");
506
+ }
507
+
508
+ const treeEntries = [];
509
+ for (const file of filesToWrite) {
510
+ const blob = await requestJsonOrThrow("POST", `${repoApiBase}/git/blobs`, {
511
+ body: {
512
+ content: Buffer.from(file.text, "utf8").toString("base64"),
513
+ encoding: "base64",
514
+ },
515
+ label: `blob ${file.path}`,
516
+ });
517
+ if (typeof blob?.sha !== "string" || !blob.sha) {
518
+ throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", `Blob creation returned no SHA for ${file.path}.`);
519
+ }
520
+ treeEntries.push({
521
+ path: file.path,
522
+ mode: "100644",
523
+ type: "blob",
524
+ sha: blob.sha,
525
+ });
526
+ }
527
+
528
+ for (const delPath of pathsToDelete) {
529
+ treeEntries.push({
530
+ path: delPath,
531
+ mode: "100644",
532
+ type: "blob",
533
+ sha: null,
534
+ });
535
+ }
536
+
537
+ const tree = await requestJsonOrThrow("POST", `${repoApiBase}/git/trees`, {
538
+ body: {
539
+ base_tree: baseTreeSha,
540
+ tree: treeEntries,
541
+ },
542
+ label: "create git tree",
543
+ });
544
+
545
+ const commit = await requestJsonOrThrow("POST", `${repoApiBase}/git/commits`, {
546
+ body: {
547
+ message: `chore(usage): publish ${deviceId} r${manifest.revision}`,
548
+ tree: tree.sha,
549
+ parents: [headSha],
550
+ },
551
+ label: "create git commit",
552
+ });
553
+
554
+ // Re-verify private visibility and repo identity right before advancing the ref.
555
+ await verifyPrivateRepo({ requirePush: true });
556
+
557
+ const patchRes = await request("PATCH", `${repoApiBase}/git/refs/heads/${encodeRepoPath(verified.branch)}`, {
558
+ body: {
559
+ sha: commit.sha,
560
+ force: false,
561
+ },
562
+ });
563
+
564
+ if (patchRes.ok) {
565
+ return {
566
+ repoId: verified.repoId,
567
+ branch: verified.branch,
568
+ commitSha: commit.sha,
569
+ publishedMonths: sortedMonths.map((m) => m.month),
570
+ removedMonths: sortedRemoved,
571
+ };
572
+ }
573
+
574
+ if ((patchRes.status === 409 || patchRes.status === 422) && attempt === 0) {
575
+ continue;
576
+ }
577
+
578
+ throw new GitHubStoreError(
579
+ patchRes.status === 409 || patchRes.status === 422 ? "GITHUB_CONFLICT" : "GITHUB_HTTP_ERROR",
580
+ sanitizeGitHubErrorMessage(patchRes.status, patchRes.text),
581
+ { status: patchRes.status },
582
+ );
583
+ }
584
+
585
+ throw new GitHubStoreError("GITHUB_CONFLICT", "Failed to advance branch ref due to concurrent writes.", {
586
+ status: 422,
587
+ });
588
+ },
589
+
590
+ async listDeviceIds({ verified } = {}) {
591
+ const target = verified || await verifyPrivateRepo({ requirePush: false });
592
+ const res = await request(
593
+ "GET",
594
+ `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repoName)}/contents/${encodeRepoPath(normalizedPrefix)}?ref=${encodeURIComponent(target.branch)}`,
595
+ );
596
+ if (res.status === 404) {
597
+ return { deviceIds: [], target };
598
+ }
599
+ if (!res.ok) {
600
+ throw new GitHubStoreError(
601
+ res.status === 401 ? "GITHUB_AUTH_ERROR" : "GITHUB_HTTP_ERROR",
602
+ sanitizeGitHubErrorMessage(res.status, res.text),
603
+ { status: res.status },
604
+ );
605
+ }
606
+
607
+ let entries;
608
+ try {
609
+ entries = JSON.parse(res.text);
610
+ } catch (error) {
611
+ throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", "Directory listing response was not valid JSON.", {
612
+ cause: error,
613
+ });
614
+ }
615
+ if (!Array.isArray(entries)) {
616
+ throw new GitHubStoreError(
617
+ "GITHUB_INVALID_PREFIX_TARGET",
618
+ `Configured prefix "${normalizedPrefix}" resolved to a file rather than a directory.`,
619
+ );
620
+ }
621
+
622
+ const deviceIds = entries
623
+ .filter((entry) => entry && entry.type === "dir" && typeof entry.name === "string" && DEVICE_ID_PATTERN.test(entry.name))
624
+ .map((entry) => entry.name)
625
+ .sort();
626
+
627
+ return { deviceIds, target };
628
+ },
629
+
630
+ async fetchDeviceManifest(deviceId, { etag = null, verified } = {}) {
631
+ if (!DEVICE_ID_PATTERN.test(deviceId)) {
632
+ throw new GitHubStoreError("INVALID_DEVICE_ID", `Invalid deviceId: ${String(deviceId)}`);
633
+ }
634
+ const target = verified || await verifyPrivateRepo({ requirePush: false });
635
+ const manifestPath = `${normalizedPrefix}/${deviceId}/manifest.json`;
636
+ const res = await request(
637
+ "GET",
638
+ `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repoName)}/contents/${encodeRepoPath(manifestPath)}?ref=${encodeURIComponent(target.branch)}`,
639
+ { etag },
640
+ );
641
+
642
+ if (res.status === 304) {
643
+ return { status: "not_modified", etag };
644
+ }
645
+ if (res.status === 404) {
646
+ return { status: "missing" };
647
+ }
648
+ if (!res.ok) {
649
+ throw new GitHubStoreError(
650
+ res.status === 401 ? "GITHUB_AUTH_ERROR" : "GITHUB_HTTP_ERROR",
651
+ sanitizeGitHubErrorMessage(res.status, res.text),
652
+ { status: res.status },
653
+ );
654
+ }
655
+
656
+ let envelope;
657
+ try {
658
+ envelope = JSON.parse(res.text);
659
+ } catch (error) {
660
+ throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", `Invalid manifest envelope for ${deviceId}.`, {
661
+ cause: error,
662
+ });
663
+ }
664
+
665
+ const rawManifest = await decodeContentsEnvelope(envelope, `${deviceId}/manifest.json`);
666
+ const manifest = validateRemoteManifest(rawManifest, deviceId);
667
+
668
+ return {
669
+ status: "ok",
670
+ manifest,
671
+ etag: res.headers?.get?.("etag") || null,
672
+ sha: typeof envelope?.sha === "string" ? envelope.sha : null,
673
+ };
674
+ },
675
+
676
+ async fetchDeviceMonth(deviceId, month, { etag = null, expectedSha256 = "", verified } = {}) {
677
+ if (!DEVICE_ID_PATTERN.test(deviceId)) {
678
+ throw new GitHubStoreError("INVALID_DEVICE_ID", `Invalid deviceId: ${String(deviceId)}`);
679
+ }
680
+ if (!isValidCalendarMonth(month)) {
681
+ throw new GitHubStoreError("INVALID_MONTH", `Invalid month key: ${String(month)}`);
682
+ }
683
+ const target = verified || await verifyPrivateRepo({ requirePush: false });
684
+ const monthPath = `${normalizedPrefix}/${deviceId}/${month}.json`;
685
+ const res = await request(
686
+ "GET",
687
+ `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repoName)}/contents/${encodeRepoPath(monthPath)}?ref=${encodeURIComponent(target.branch)}`,
688
+ { etag },
689
+ );
690
+
691
+ if (res.status === 304) {
692
+ return { status: "not_modified", etag };
693
+ }
694
+ if (!res.ok) {
695
+ throw new GitHubStoreError(
696
+ res.status === 401 ? "GITHUB_AUTH_ERROR" : "GITHUB_HTTP_ERROR",
697
+ sanitizeGitHubErrorMessage(res.status, res.text),
698
+ { status: res.status },
699
+ );
700
+ }
701
+
702
+ let envelope;
703
+ try {
704
+ envelope = JSON.parse(res.text);
705
+ } catch (error) {
706
+ throw new GitHubStoreError("GITHUB_INVALID_PAYLOAD", `Invalid month envelope for ${deviceId}/${month}.json.`, {
707
+ cause: error,
708
+ });
709
+ }
710
+
711
+ const rawSnapshot = await decodeContentsEnvelope(envelope, `${deviceId}/${month}.json`);
712
+ const snapshot = validateRemoteMonthSnapshot(rawSnapshot, deviceId, month, expectedSha256);
713
+
714
+ return {
715
+ status: "ok",
716
+ snapshot,
717
+ etag: res.headers?.get?.("etag") || null,
718
+ sha: typeof envelope?.sha === "string" ? envelope.sha : null,
719
+ };
720
+ },
721
+ };
722
+ }