From 1175510954dd641658f9af031894b03321ea9a98 Mon Sep 17 00:00:00 2001
From: Jay Wedgeworth <12656028+jaywedgeworth22@users.noreply.github.com>
Date: Tue, 3 Nov 2026 05:16:35 -0600
Subject: [PATCH 1/6] fix(telemetry): collect explicitly selected OpenCode
profiles
---
package.json | 2 +-
.../__tests__/opencode-profiles.node-test.mjs | 167 ++++++++++++++++++
scripts/opencode-usage-collector.mjs | 81 ++++++++-
3 files changed, 243 insertions(+), 7 deletions(-)
create mode 100644 scripts/__tests__/opencode-profiles.node-test.mjs
diff --git a/package.json b/package.json
index 3dace829..aad26003 100644
--- a/package.json
+++ b/package.json
@@ -61,7 +61,7 @@
"test:apple-projects": "bash scripts/verify-apple-projects.sh",
"test:antigravity-collector": "node scripts/test-antigravity-collector.mjs",
"test:session-token-collectors": "node scripts/test-session-token-collectors.mjs",
- "test:collector-runtime": "node scripts/test-local-collector-runtime.mjs",
+ "test:collector-runtime": "node scripts/test-local-collector-runtime.mjs && node --test scripts/__tests__/opencode-profiles.node-test.mjs",
"test:cf-token-map": "bash scripts/test-cf-token-map.sh",
"test:replica-status-probe": "bash scripts/test-replica-status-probe.sh",
"test:quota-wrapper": "bash scripts/test-subscription-quota-wrapper.sh",
diff --git a/scripts/__tests__/opencode-profiles.node-test.mjs b/scripts/__tests__/opencode-profiles.node-test.mjs
new file mode 100644
index 00000000..5c50a66a
--- /dev/null
+++ b/scripts/__tests__/opencode-profiles.node-test.mjs
@@ -0,0 +1,167 @@
+import assert from "node:assert/strict";
+import { copyFile, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { DatabaseSync } from "node:sqlite";
+import { test } from "node:test";
+import {
+ collectOpencodeDatabases,
+ collectOpencodeEvents,
+ opencodeDbPaths,
+ readFrozenProjectNames,
+ writeFrozenProjectNames,
+} from "../opencode-usage-collector.mjs";
+import { canAdvanceCollectorCheckpoint } from "../lib/run-session-token-collector.mjs";
+import { collectorSentryEvents } from "../lib/collector-sentry-bridge.mjs";
+
+const BASE = 1_792_000_000_000;
+const PRIVATE_CONTENT = "private prompt and response must never enter telemetry";
+
+async function harness(t) {
+ const root = await mkdtemp(join(tmpdir(), "opencode-profiles-"));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ return root;
+}
+
+function fixture(path, { session = "ses_primary", message = "msg_primary", child = false, dual = false, agent = "build" } = {}) {
+ const db = new DatabaseSync(path);
+ db.exec("CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT, type TEXT, seq INTEGER, time_created INTEGER, time_updated INTEGER, data TEXT)");
+ db.exec("CREATE TABLE session_v2 (id TEXT PRIMARY KEY, project_id TEXT, parent_id TEXT, directory TEXT, title TEXT, cost REAL, tokens_input INTEGER, tokens_output INTEGER, tokens_reasoning INTEGER, tokens_cache_read INTEGER, tokens_cache_write INTEGER, summary_additions INTEGER, summary_deletions INTEGER, summary_files INTEGER, time_created INTEGER, time_updated INTEGER, time_compacting INTEGER, time_archived INTEGER)");
+ if (dual) {
+ db.exec("CREATE TABLE session (id TEXT PRIMARY KEY, directory TEXT)");
+ db.prepare("INSERT INTO session VALUES (?, ?)").run(session, "/obsolete/profile");
+ }
+ db.prepare("INSERT INTO session_v2 (id,directory,tokens_input,tokens_output,tokens_cache_read,time_created,time_updated) VALUES (?,?,?,?,?,?,?)").run(session, child ? "/home/test/.botfleet/workspaces/child-project" : "/home/test/primary-project", 999999, 999999, 999999, BASE, BASE + 1000);
+ const data = {
+ time: { created: BASE, completed: BASE + 1000 },
+ model: { id: "fixture-model", providerID: "opencode" },
+ tokens: { input: child ? 9414 : 10, output: 2, reasoning: 0, cache: { read: child ? 512 : 3, write: 0 } },
+ cost: 0,
+ agent,
+ prompt: PRIVATE_CONTENT,
+ response: PRIVATE_CONTENT,
+ };
+ db.prepare("INSERT INTO session_message VALUES (?,?,?,?,?,?,?)").run(message, session, "assistant", 1, BASE, BASE + 1000, JSON.stringify(data));
+ db.close();
+}
+
+const tokenRows = (events) => events.filter((event) => event.metricType === "usage" && event.unit === "token");
+
+test("explicit additional profiles preserve the ordinary source and bound selection", () => {
+ assert.deepEqual(opencodeDbPaths({ OPENCODE_DB: "/primary.db" }), ["/primary.db"]);
+ assert.deepEqual(opencodeDbPaths({ OPENCODE_DB: "primary.db" }), [resolve("primary.db")]);
+ assert.deepEqual(opencodeDbPaths({ OPENCODE_DB: "/primary.db", OPENCODE_ADDITIONAL_DBS_JSON: '["/child.db"]' }), ["/primary.db", "/child.db"]);
+ for (const value of ["not-json", "null", '"/child.db"', '["relative.db"]', '[1]', JSON.stringify(["/bad\0.db"]), JSON.stringify(Array(9).fill("/child.db"))]) {
+ assert.throws(() => opencodeDbPaths({ OPENCODE_DB: "/primary.db", OPENCODE_ADDITIONAL_DBS_JSON: value }), /bounded array/);
+ }
+});
+
+test("a v2-only child source adds exact calls and cache reads without substituting session totals", async (t) => {
+ const root = await harness(t);
+ const primary = join(root, "primary.db");
+ const child = join(root, "child.db");
+ fixture(primary, { dual: true });
+ fixture(child, { session: "ses_child", message: "msg_child", child: true });
+ const before = await Promise.all([primary, child].map((path) => readFile(path)));
+ const standalone = await collectOpencodeEvents({ dbPath: primary, since: new Date(0) });
+ const scanStatus = { complete: true };
+ const events = await collectOpencodeDatabases({ dbPaths: [primary, child], since: new Date(0), scanStatus });
+ assert.equal(scanStatus.complete, true);
+ assert.deepEqual(events.slice(0, standalone.length), standalone);
+ const rows = tokenRows(events).filter((event) => event.metadata["session.id"] === "ses_child");
+ assert.deepEqual(rows.map((event) => [event.label, event.quantity]), [["token:input", 9414], ["token:output", 2], ["token:cacheRead", 512]]);
+ assert.ok(rows.every((event) => event.metadata["agent.launcher"] === "botfleet"));
+ assert.ok(!JSON.stringify(events).includes(PRIVATE_CONTENT));
+ assert.ok(!JSON.stringify(events).includes(child));
+ assert.equal(events.filter((event) => event.metricType === "cost").length, 0);
+ const spans = collectorSentryEvents(events, { producerId: "opencode", producerInstanceId: "fixture" });
+ assert.equal(spans.length, 2);
+ assert.ok(spans.every((event) => event.kind === "span"));
+ assert.deepEqual(await Promise.all([primary, child].map((path) => readFile(path))), before);
+});
+
+test("repeated paths, symlinks and copied profiles preserve one set of existing event identities", async (t) => {
+ const root = await harness(t);
+ const primary = join(root, "primary.db");
+ const alias = join(root, "alias.db");
+ const copy = join(root, "copy.db");
+ fixture(primary);
+ await symlink(primary, alias);
+ await copyFile(primary, copy);
+ const standalone = await collectOpencodeEvents({ dbPath: primary, since: new Date(0) });
+ const scanStatus = { complete: true };
+ const events = await collectOpencodeDatabases({ dbPaths: [primary, primary, alias, copy], since: new Date(0), scanStatus });
+ assert.equal(scanStatus.complete, true);
+ assert.deepEqual(events, standalone);
+ assert.equal(collectorSentryEvents(events, { producerId: "opencode", producerInstanceId: "fixture" }).length, 1);
+});
+
+test("profiles share durable frozen project names across replay and source order changes", async (t) => {
+ const root = await harness(t);
+ const primary = join(root, "primary.db");
+ const copy = join(root, "copy.db");
+ const state = join(root, "project-names.json");
+ fixture(primary);
+ await copyFile(primary, copy);
+ const frozen = new Map();
+ const first = await collectOpencodeDatabases({ dbPaths: [primary, copy], since: new Date(0), frozenProjectNames: frozen });
+ await writeFrozenProjectNames(state, frozen);
+ for (const path of [primary, copy]) {
+ const db = new DatabaseSync(path);
+ db.prepare("UPDATE session_v2 SET directory=?").run("/new/project-name");
+ db.close();
+ }
+ const second = await collectOpencodeDatabases({ dbPaths: [copy, primary], since: new Date(0), frozenProjectNames: await readFrozenProjectNames(state) });
+ assert.deepEqual(second, first);
+ assert.ok(second.every((event) => event.project === "primary-project"));
+});
+
+test("missing and unreadable explicit sources retain the checkpoint while other sources still flow", async (t) => {
+ const root = await harness(t);
+ const primary = join(root, "primary.db");
+ fixture(primary);
+ const corrupt = join(root, "corrupt.db");
+ await writeFile(corrupt, "not a SQLite database");
+ for (const source of [join(root, "absent.db"), root, corrupt]) {
+ const scanStatus = { complete: true };
+ const warnings = [];
+ const events = await collectOpencodeDatabases({ dbPaths: [primary, source], since: new Date(0), scanStatus, onWarning: (message) => warnings.push(message) });
+ assert.ok(tokenRows(events).length > 0);
+ assert.equal(scanStatus.complete, false);
+ assert.equal(canAdvanceCollectorCheckpoint({ dryRun: false, explicitSince: false }, { scanComplete: scanStatus.complete }), false);
+ assert.ok(warnings.some((message) => message.includes("checkpoint retained")));
+ assert.ok(warnings.every((message) => !message.includes(root)));
+ }
+ await assert.rejects(() => collectOpencodeDatabases({ dbPaths: Array(10).fill(primary) }), /one to nine/);
+});
+
+test("an older profile without v2 session facts keeps its existing token event identities", async (t) => {
+ const root = await harness(t);
+ const primary = join(root, "primary.db");
+ fixture(primary, { dual: true });
+ const db = new DatabaseSync(primary);
+ db.exec("DROP TABLE session_v2");
+ db.close();
+ const standalone = await collectOpencodeEvents({ dbPath: primary, since: new Date(0) });
+ const scanStatus = { complete: true };
+ const events = await collectOpencodeDatabases({ dbPaths: [primary], since: new Date(0), scanStatus });
+ assert.deepEqual(events, standalone);
+ assert.equal(scanStatus.complete, true);
+ assert.equal(tokenRows(events).length, 3);
+ assert.ok(events.every((event) => event.project === undefined));
+});
+
+test("conflicting replay identities preserve primary payload and prevent checkpoint advancement", async (t) => {
+ const root = await harness(t);
+ const primary = join(root, "primary.db");
+ const copy = join(root, "copy.db");
+ fixture(primary);
+ fixture(copy, { agent: "other-agent" });
+ const scanStatus = { complete: true };
+ const warnings = [];
+ const events = await collectOpencodeDatabases({ dbPaths: [primary, copy], since: new Date(0), scanStatus, onWarning: (message) => warnings.push(message) });
+ assert.equal(scanStatus.complete, false);
+ assert.equal(warnings.filter((message) => message.includes("disagree")).length, 1);
+ assert.ok(tokenRows(events).every((event) => event.metadata.agent === "build"));
+ assert.equal(new Set(tokenRows(events).map((event) => event.eventId)).size, tokenRows(events).length);
+});
diff --git a/scripts/opencode-usage-collector.mjs b/scripts/opencode-usage-collector.mjs
index b368a409..243b1f66 100644
--- a/scripts/opencode-usage-collector.mjs
+++ b/scripts/opencode-usage-collector.mjs
@@ -35,11 +35,12 @@ import { flushCollectorSentry } from "./lib/collector-sentry-bridge.mjs";
// OPENCODE_INGEST_TOKEN or USAGE_INGEST_TOKEN
// USAGE_MONITOR_INGEST_URL (default https://usage.jays.services/api/ingest/usage)
// OPENCODE_DB (default ~/.local/share/opencode/opencode.db)
+// OPENCODE_ADDITIONAL_DBS_JSON (optional JSON array of up to eight explicit absolute database paths)
-import { existsSync } from "node:fs";
+import { existsSync, statSync } from "node:fs";
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
import { homedir } from "node:os";
-import { dirname, join } from "node:path";
+import { dirname, isAbsolute, join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import {
@@ -90,6 +91,24 @@ export function defaultOpencodeDbPath(env = process.env) {
return join(expandHome(dataHome), "opencode", "opencode.db");
}
+/** Additional profiles supplement the ordinary source without discovering new stores. */
+export function opencodeDbPaths(env = process.env) {
+ const primary = resolve(defaultOpencodeDbPath(env));
+ if (!env.OPENCODE_ADDITIONAL_DBS_JSON) return [primary];
+ let additional;
+ try {
+ additional = JSON.parse(env.OPENCODE_ADDITIONAL_DBS_JSON);
+ } catch {
+ throw new Error("OPENCODE_ADDITIONAL_DBS_JSON must be a bounded array of absolute database paths");
+ }
+ if (!Array.isArray(additional) || additional.length > 8 || additional.some((path) =>
+ typeof path !== "string" || !path || path.length > 4096 || path.includes("\0") || !isAbsolute(expandHome(path))
+ )) {
+ throw new Error("OPENCODE_ADDITIONAL_DBS_JSON must be a bounded array of absolute database paths");
+ }
+ return [primary, ...additional.map(expandHome)];
+}
+
/**
* Where the frozen project names live. The file sits beside the collector's
* checkpoint but is a file of its own, because it has to outlive the
@@ -199,9 +218,9 @@ export async function collectOpencodeEvents({
frozenProjectNames,
);
// Sessions BotFleet launched (their directory is a BotFleet workspace).
- // Their token rows are tagged, so the monitor drops them only where a
- // stored BotFleet turn names the same session, or left out entirely when
- // USAGE_MONITOR_EXCLUDE_BOTFLEET_CHILDREN=1.
+ // Their token rows are tagged for exact receiver-verified billed-call
+ // coverage; session identity or approximate timing alone proves no overlap.
+ // The explicit USAGE_MONITOR_EXCLUDE_BOTFLEET_CHILDREN=1 switch excludes them.
const botFleetSessionIds = new Set(
(telemetry.sessions ?? [])
.filter((session) => typeof session?.directory === "string" && session.directory)
@@ -263,6 +282,53 @@ export async function collectOpencodeEvents({
}
}
+/** Read explicitly configured profiles with shared frozen names and unchanged event identities. */
+export async function collectOpencodeDatabases({
+ dbPaths = opencodeDbPaths(),
+ scanStatus,
+ frozenProjectNames = new Map(),
+ onWarning,
+ ...options
+} = {}) {
+ if (!Array.isArray(dbPaths) || dbPaths.length < 1 || dbPaths.length > 9 || dbPaths.some((path) =>
+ typeof path !== "string" || !path || path.length > 4096 || path.includes("\0") || !isAbsolute(path)
+ )) throw new Error("OpenCode database selection must contain one to nine absolute paths");
+ const databases = new Set();
+ const events = new Map();
+ let collisionReported = false;
+ for (const [index, dbPath] of dbPaths.entries()) {
+ let identity;
+ try {
+ const info = statSync(dbPath, { bigint: true });
+ if (!info.isFile()) throw new Error("Not a database file");
+ identity = `${info.dev}:${info.ino}`;
+ } catch {
+ if (scanStatus) scanStatus.complete = false;
+ onWarning?.(`OpenCode database ${index + 1} is unavailable; checkpoint retained`);
+ continue;
+ }
+ if (databases.has(identity)) continue;
+ databases.add(identity);
+ const sourceStatus = { complete: true };
+ const sourceEvents = await collectOpencodeEvents({ ...options, dbPath, scanStatus: sourceStatus, frozenProjectNames, onWarning });
+ if (!sourceStatus.complete) {
+ if (scanStatus) scanStatus.complete = false;
+ onWarning?.(`OpenCode database ${index + 1} could not be read completely; checkpoint retained`);
+ }
+ for (const event of sourceEvents) {
+ const previous = events.get(event.eventId);
+ if (!previous) events.set(event.eventId, event);
+ else if (JSON.stringify(previous) !== JSON.stringify(event)) {
+ // The ordinary source retains precedence for a replay identity already sent.
+ if (scanStatus) scanStatus.complete = false;
+ if (!collisionReported) onWarning?.("OpenCode profiles disagree on an event identity; checkpoint retained");
+ collisionReported = true;
+ }
+ }
+ }
+ return [...events.values()];
+}
+
/** Bucket the window's events by kind for the run log. */
export function countEventKinds(events) {
const counts = { token: 0, cost: 0, context: 0, session: 0, lifecycle: 0 };
@@ -302,8 +368,10 @@ export function sampleEventPerKind(events) {
async function main() {
const passStartedAt = new Date();
let args;
+ let dbPaths;
try {
args = await resolveCollectorArgs(process.argv, PRODUCER_ID, { now: passStartedAt });
+ dbPaths = opencodeDbPaths();
} catch (error) {
fail(error instanceof Error ? error.message : String(error));
}
@@ -321,7 +389,8 @@ async function main() {
// the rows the failed pass had already stored.
const projectNamesPath = opencodeProjectNamesPath(PRODUCER_ID);
const frozenProjectNames = await readFrozenProjectNames(projectNamesPath);
- const events = await collectOpencodeEvents({
+ const events = await collectOpencodeDatabases({
+ dbPaths,
since: args.since,
scanStatus,
sessionIdCutoffMs,
From a85c057063bb759634d7c516fd7dfa54afd72b84 Mon Sep 17 00:00:00 2001
From: Jay Wedgeworth <12656028+jaywedgeworth22@users.noreply.github.com>
Date: Tue, 3 Nov 2026 05:17:31 -0600
Subject: [PATCH 2/6] Reconcile telemetry handoff source and CI evidence
---
docs/rollouts/2026-10-30-telemetry-handoff.md | 20 ++++++++++++++++++-
1 file changed, 19 insertions(+), 1 deletion(-)
diff --git a/docs/rollouts/2026-10-30-telemetry-handoff.md b/docs/rollouts/2026-10-30-telemetry-handoff.md
index f229cb8f..9d4bae4b 100644
--- a/docs/rollouts/2026-10-30-telemetry-handoff.md
+++ b/docs/rollouts/2026-10-30-telemetry-handoff.md
@@ -12,12 +12,30 @@ The regression uses the adapter's own SQLite library for both connections. Usi
## Preserve Child Telemetry
+### Implementation snapshot recorded October 30 (superseded by the November 3 source audit)
+
The former BotFleet drop flag could discard rows from the same child session and time window without proving that BotFleet billed them. It is now inert, even when configured as `1`, and performs no database query. A future replacement needs authoritative per-call identities and quantities reconciled to the sender's billed aggregate; session and timing are insufficient. Native OTLP mapping retains the two allowlisted launcher correlation fields. No existing stored data is deleted or rewritten.
The collector parser/runtime suites already run explicitly in CI. Opencode non-token correlation enrichment is prepared in a separate collector delivery slice, preserving event identities and using the existing one-sided replay compatibility rule.
-## Remaining Verification
+### Deployment verification recorded October 30 (not refreshed by the source audit)
This document is implementation evidence, not a claim of deployment or Sentry receipt. Live ingest needs a restart and collector backlog check after deployment. Sentry coverage needs a durable, privacy-preserving path for transcript collectors; activating the existing OTLP hub alone does not connect those collectors. Exact BotFleet billed-call suppression, historical overcount cleanup and credential rotation remain separate work until their evidence and owner decisions are recorded.
SQLite reference: [Isolation And Concurrency](https://www.sqlite.org/isolation.html).
+
+## 2026-11-03 Source And CI Reconciliation
+
+This appendix records repository source and CI wiring, not production deployment, runtime configuration, or telemetry receipt. It supersedes the October 30 implementation snapshot above.
+
+MiniMax runtime usage is correlated to workspace data by exact `session_id` and `workspace_dir`; duplicate or ambiguous session rows receive no launcher attribution, and usage events retain their existing IDs and quantities. OpenCode token, cost, and context rows carry session correlation, and BotFleet workspace sessions receive launcher attribution without changing event identity. The native OTLP metadata allowlist preserves `agent.launcher` and `agent.launcher.session`.
+
+Aggregate native coverage remains fail-open and performs no database lookup. Separate BotFleet child suppression requires the opt-in `BOTFLEET_CHILD_COVERAGE_DROP=1`, a BotFleet-scoped receiver credential, and a persisted signed single-call receipt with matching session, call, model, host, and token-component quantities. Missing authorization or incomplete evidence preserves the child event; no time-window fallback is used.
+
+CI explicitly runs the parser, native telemetry, and collector runtime suites:
+
+- `npm run test:session-token-collectors`
+- `node --test scripts/collector-sentry-bridge.node-test.mjs scripts/telemetry-hub-auth.node-test.mjs scripts/telemetry-hub-bootstrap.node-test.mjs scripts/telemetry-native-followup.node-test.mjs`
+- `npm run test:collector-runtime`
+
+Related implementation and review: PRs #1844, #1847, #1848, and #1850. This source audit did not verify deployed flag state or production receipts.
From 041158b43a5b050036dfa5d3e7671c0ec43618d4 Mon Sep 17 00:00:00 2001
From: Jay Wedgeworth <12656028+jaywedgeworth22@users.noreply.github.com>
Date: Tue, 3 Nov 2026 05:25:50 -0600
Subject: [PATCH 3/6] fix(opencode): keep implicit missing primary healthy
---
.../__tests__/opencode-profiles.node-test.mjs | 44 +++++++++++++++++++
scripts/opencode-usage-collector.mjs | 10 +++--
2 files changed, 51 insertions(+), 3 deletions(-)
diff --git a/scripts/__tests__/opencode-profiles.node-test.mjs b/scripts/__tests__/opencode-profiles.node-test.mjs
index 5c50a66a..57ee66b1 100644
--- a/scripts/__tests__/opencode-profiles.node-test.mjs
+++ b/scripts/__tests__/opencode-profiles.node-test.mjs
@@ -135,6 +135,50 @@ test("missing and unreadable explicit sources retain the checkpoint while other
await assert.rejects(() => collectOpencodeDatabases({ dbPaths: Array(10).fill(primary) }), /one to nine/);
});
+test("a missing implicit default is empty while explicit and additional missing databases retain the checkpoint", async (t) => {
+ const root = await harness(t);
+ const missingPrimary = join(root, "default", "opencode.db");
+ const child = join(root, "child.db");
+ fixture(child, { session: "ses_child", message: "msg_child", child: true });
+ const childEvents = await collectOpencodeEvents({ dbPath: child, since: new Date(0) });
+
+ const implicitScan = { complete: true };
+ const implicitEvents = await collectOpencodeDatabases({
+ dbPaths: [missingPrimary, child],
+ allowMissingPrimary: true,
+ since: new Date(0),
+ scanStatus: implicitScan,
+ });
+ assert.deepEqual(implicitEvents, childEvents);
+ assert.equal(implicitScan.complete, true);
+ assert.equal(canAdvanceCollectorCheckpoint({ dryRun: false, explicitSince: false }, { scanComplete: implicitScan.complete }), true);
+
+ const explicitScan = { complete: true };
+ const explicitWarnings = [];
+ const explicitEvents = await collectOpencodeDatabases({
+ dbPaths: [missingPrimary, child],
+ allowMissingPrimary: false,
+ since: new Date(0),
+ scanStatus: explicitScan,
+ onWarning: (message) => explicitWarnings.push(message),
+ });
+ assert.deepEqual(explicitEvents, childEvents);
+ assert.equal(explicitScan.complete, false);
+ assert.equal(canAdvanceCollectorCheckpoint({ dryRun: false, explicitSince: false }, { scanComplete: explicitScan.complete }), false);
+ assert.ok(explicitWarnings.some((message) => message.includes("checkpoint retained")));
+
+ const additionalScan = { complete: true };
+ const additionalEvents = await collectOpencodeDatabases({
+ dbPaths: [child, missingPrimary],
+ allowMissingPrimary: true,
+ since: new Date(0),
+ scanStatus: additionalScan,
+ });
+ assert.deepEqual(additionalEvents, childEvents);
+ assert.equal(additionalScan.complete, false);
+ assert.equal(canAdvanceCollectorCheckpoint({ dryRun: false, explicitSince: false }, { scanComplete: additionalScan.complete }), false);
+});
+
test("an older profile without v2 session facts keeps its existing token event identities", async (t) => {
const root = await harness(t);
const primary = join(root, "primary.db");
diff --git a/scripts/opencode-usage-collector.mjs b/scripts/opencode-usage-collector.mjs
index 243b1f66..023823e6 100644
--- a/scripts/opencode-usage-collector.mjs
+++ b/scripts/opencode-usage-collector.mjs
@@ -285,6 +285,7 @@ export async function collectOpencodeEvents({
/** Read explicitly configured profiles with shared frozen names and unchanged event identities. */
export async function collectOpencodeDatabases({
dbPaths = opencodeDbPaths(),
+ allowMissingPrimary = false,
scanStatus,
frozenProjectNames = new Map(),
onWarning,
@@ -302,9 +303,11 @@ export async function collectOpencodeDatabases({
const info = statSync(dbPath, { bigint: true });
if (!info.isFile()) throw new Error("Not a database file");
identity = `${info.dev}:${info.ino}`;
- } catch {
- if (scanStatus) scanStatus.complete = false;
- onWarning?.(`OpenCode database ${index + 1} is unavailable; checkpoint retained`);
+ } catch (error) {
+ if (!(index === 0 && allowMissingPrimary && error?.code === "ENOENT")) {
+ if (scanStatus) scanStatus.complete = false;
+ onWarning?.(`OpenCode database ${index + 1} is unavailable; checkpoint retained`);
+ }
continue;
}
if (databases.has(identity)) continue;
@@ -391,6 +394,7 @@ async function main() {
const frozenProjectNames = await readFrozenProjectNames(projectNamesPath);
const events = await collectOpencodeDatabases({
dbPaths,
+ allowMissingPrimary: !process.env.OPENCODE_DB,
since: args.since,
scanStatus,
sessionIdCutoffMs,
From 3658ba4b520398527cdfcdeca9146fc2d8e37b11 Mon Sep 17 00:00:00 2001
From: Jay Wedgeworth <12656028+jaywedgeworth22@users.noreply.github.com>
Date: Tue, 3 Nov 2026 05:34:15 -0600
Subject: [PATCH 4/6] fix(opencode): tolerate blocked implicit default path
---
.../__tests__/opencode-profiles.node-test.mjs | 20 ++++++++++++++++---
scripts/opencode-usage-collector.mjs | 2 +-
2 files changed, 18 insertions(+), 4 deletions(-)
diff --git a/scripts/__tests__/opencode-profiles.node-test.mjs b/scripts/__tests__/opencode-profiles.node-test.mjs
index 57ee66b1..a4fd10fc 100644
--- a/scripts/__tests__/opencode-profiles.node-test.mjs
+++ b/scripts/__tests__/opencode-profiles.node-test.mjs
@@ -135,10 +135,13 @@ test("missing and unreadable explicit sources retain the checkpoint while other
await assert.rejects(() => collectOpencodeDatabases({ dbPaths: Array(10).fill(primary) }), /one to nine/);
});
-test("a missing implicit default is empty while explicit and additional missing databases retain the checkpoint", async (t) => {
+test("missing implicit default paths are empty while explicit and additional missing paths retain the checkpoint", async (t) => {
const root = await harness(t);
const missingPrimary = join(root, "default", "opencode.db");
+ const blockingParent = join(root, "blocking-file");
+ const blockedPrimary = join(blockingParent, "opencode.db");
const child = join(root, "child.db");
+ await writeFile(blockingParent, "a file blocking the database parent path");
fixture(child, { session: "ses_child", message: "msg_child", child: true });
const childEvents = await collectOpencodeEvents({ dbPath: child, since: new Date(0) });
@@ -153,10 +156,21 @@ test("a missing implicit default is empty while explicit and additional missing
assert.equal(implicitScan.complete, true);
assert.equal(canAdvanceCollectorCheckpoint({ dryRun: false, explicitSince: false }, { scanComplete: implicitScan.complete }), true);
+ const blockedImplicitScan = { complete: true };
+ const blockedImplicitEvents = await collectOpencodeDatabases({
+ dbPaths: [blockedPrimary, child],
+ allowMissingPrimary: true,
+ since: new Date(0),
+ scanStatus: blockedImplicitScan,
+ });
+ assert.deepEqual(blockedImplicitEvents, childEvents);
+ assert.equal(blockedImplicitScan.complete, true);
+ assert.equal(canAdvanceCollectorCheckpoint({ dryRun: false, explicitSince: false }, { scanComplete: blockedImplicitScan.complete }), true);
+
const explicitScan = { complete: true };
const explicitWarnings = [];
const explicitEvents = await collectOpencodeDatabases({
- dbPaths: [missingPrimary, child],
+ dbPaths: [blockedPrimary, child],
allowMissingPrimary: false,
since: new Date(0),
scanStatus: explicitScan,
@@ -169,7 +183,7 @@ test("a missing implicit default is empty while explicit and additional missing
const additionalScan = { complete: true };
const additionalEvents = await collectOpencodeDatabases({
- dbPaths: [child, missingPrimary],
+ dbPaths: [child, blockedPrimary],
allowMissingPrimary: true,
since: new Date(0),
scanStatus: additionalScan,
diff --git a/scripts/opencode-usage-collector.mjs b/scripts/opencode-usage-collector.mjs
index 023823e6..22c70ebe 100644
--- a/scripts/opencode-usage-collector.mjs
+++ b/scripts/opencode-usage-collector.mjs
@@ -304,7 +304,7 @@ export async function collectOpencodeDatabases({
if (!info.isFile()) throw new Error("Not a database file");
identity = `${info.dev}:${info.ino}`;
} catch (error) {
- if (!(index === 0 && allowMissingPrimary && error?.code === "ENOENT")) {
+ if (!(index === 0 && allowMissingPrimary && ["ENOENT", "ENOTDIR"].includes(error?.code))) {
if (scanStatus) scanStatus.complete = false;
onWarning?.(`OpenCode database ${index + 1} is unavailable; checkpoint retained`);
}
From 2ec155692fa91b960fcdca32b9f4c152772d659b Mon Sep 17 00:00:00 2001
From: Jay Wedgeworth <12656028+jaywedgeworth22@users.noreply.github.com>
Date: Thu, 12 Nov 2026 01:23:38 -0600
Subject: [PATCH 5/6] WIP: preserve uncommitted work from server
/mnt/fleet-extra/apps/lanes/Usage-Monitor/codex-um-1646-completion-audit
(fleet commit-push-delete pass 2026-11-12)
---
.kody-trigger.txt | 1 +
...766a4b11ab189cce28af3894fc96616bb34b7.json | 77 ++
.um1646-child-pair-plan.json | 130 +++
.um1646-claude-historic24h.mjs | 98 +++
.um1646-claude-historic24h.py | 18 +
...inventory-update.before-copy-fix.plan.json | 27 +
.um1646-inventory-update.plan.json | 27 +
...ncode-child-source-plan-v1.superseded.json | 6 +
.um1646-opencode-child-source-plan-v2.json | 55 ++
.um1646-opencode-child-source-plan.json | 53 ++
.um1646-opencode-config-plan.json | 9 +
.um1646-relay-publication-receipt.json | 1 +
.um1651-empty-sentry-ack-receipt.json | 1 +
.um1651-final-runtime-verification.json | 1 +
.um1651-gh-commit-body.json | 1 +
.um1651-gh-merge-receipt.json | 1 +
.um1651-gh-ref-body.json | 1 +
.um1651-gh-tree-body.json | 1 +
...39f5b576f498dabc43963c89c47b3713.plan.json | 153 ++++
...c43963c89c47b3713.stale-41ce4cd6.plan.json | 153 ++++
...750fd4dc87a97b1f3cc3afea0-repin.claim.json | 1 +
...0fd4dc87a97b1f3cc3afea0-repin.receipt.json | 1 +
...750fd4dc87a97b1f3cc3afea0-start.claim.json | 1 +
...0fd4dc87a97b1f3cc3afea0-start.receipt.json | 1 +
...6750fd4dc87a97b1f3cc3afea0-stop.claim.json | 1 +
...1f3cc3afea0-stop.independent-readback.json | 1 +
...50fd4dc87a97b1f3cc3afea0-stop.receipt.json | 1 +
...08a21a8a41c4e831187b8235f486d511.plan.json | 107 +++
.um1651-kody-trigger.txt | 1 +
.um1651-main-merge-publish-receipt.json | 1 +
.um1651-relay-publication-3b7884b09665.json | 1 +
.um1651-relay-publication-d650a1cb95bb.json | 1 +
.um1651-relay-publication-receipt.json | 1 +
HANDOFF-UM-1646-2026-11-03.md | 98 +++
audit-mac-replay-receipt.py | 23 +
audit-runtime-metadata.py | 33 +
build-reviewed-hub-image.py | 227 +++++
child_config_local_cas.py | 378 ++++++++
child_config_pair_controller.py | 220 +++++
child_config_pair_remote.py | 378 ++++++++
claude-retained-source-metadata.audit.py | 48 ++
configure-opencode-child-source.py | 133 +++
final-child-hub-readback.py | 14 +
inspect-tool-schemas.py | 36 +
opencode-child-source-plan.py | 282 ++++++
plan-reviewed-hub-upgrade.py | 143 ++++
prepare-um1646-inventory-update.py | 591 +++++++++++++
preserve-final-safe-receipts.py | 13 +
probe-sentry-empty-ack.py | 41 +
publish-reviewed-files.py | 33 +
publish-um1651-main-merge.py | 63 ++
publish-um1651-merge-gh-fallback.py | 48 ++
publish-um1651-reviewed.py | 41 +
read-current-operations.py | 9 +
read-final-suppression-flag.py | 9 +
read-mounted-hub-metadata.py | 9 +
recover-verified-stop.py | 22 +
sentry-historic-claude-receipts.audit.py | 137 +++
test_child_config_local_cas.py | 130 +++
test_um1646_inventory_update_fixture.py | 67 ++
test_upgrade_reviewed_hub.py | 327 +++++++
upgrade-reviewed-hub.py | 807 ++++++++++++++++++
verify-reviewed-hub-image.py | 168 ++++
verify-upgraded-hub-and-track.py | 40 +
64 files changed, 5501 insertions(+)
create mode 100644 .kody-trigger.txt
create mode 100644 .um1646-child-pair-apply-ae3a6cbb3461248daad470f024b766a4b11ab189cce28af3894fc96616bb34b7.json
create mode 100644 .um1646-child-pair-plan.json
create mode 100644 .um1646-claude-historic24h.mjs
create mode 100644 .um1646-claude-historic24h.py
create mode 100644 .um1646-inventory-update.before-copy-fix.plan.json
create mode 100644 .um1646-inventory-update.plan.json
create mode 100644 .um1646-opencode-child-source-plan-v1.superseded.json
create mode 100644 .um1646-opencode-child-source-plan-v2.json
create mode 100644 .um1646-opencode-child-source-plan.json
create mode 100644 .um1646-opencode-config-plan.json
create mode 100644 .um1646-relay-publication-receipt.json
create mode 100644 .um1651-empty-sentry-ack-receipt.json
create mode 100644 .um1651-final-runtime-verification.json
create mode 100644 .um1651-gh-commit-body.json
create mode 100644 .um1651-gh-merge-receipt.json
create mode 100644 .um1651-gh-ref-body.json
create mode 100644 .um1651-gh-tree-body.json
create mode 100644 .um1651-hub-upgrade-0a92fcfa39f5b576f498dabc43963c89c47b3713.plan.json
create mode 100644 .um1651-hub-upgrade-0a92fcfa39f5b576f498dabc43963c89c47b3713.stale-41ce4cd6.plan.json
create mode 100644 .um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-repin.claim.json
create mode 100644 .um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-repin.receipt.json
create mode 100644 .um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-start.claim.json
create mode 100644 .um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-start.receipt.json
create mode 100644 .um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-stop.claim.json
create mode 100644 .um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-stop.independent-readback.json
create mode 100644 .um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-stop.receipt.json
create mode 100644 .um1651-hub-upgrade-80f0c92708a21a8a41c4e831187b8235f486d511.plan.json
create mode 100644 .um1651-kody-trigger.txt
create mode 100644 .um1651-main-merge-publish-receipt.json
create mode 100644 .um1651-relay-publication-3b7884b09665.json
create mode 100644 .um1651-relay-publication-d650a1cb95bb.json
create mode 100644 .um1651-relay-publication-receipt.json
create mode 100644 HANDOFF-UM-1646-2026-11-03.md
create mode 100644 audit-mac-replay-receipt.py
create mode 100644 audit-runtime-metadata.py
create mode 100644 build-reviewed-hub-image.py
create mode 100644 child_config_local_cas.py
create mode 100644 child_config_pair_controller.py
create mode 100644 child_config_pair_remote.py
create mode 100644 claude-retained-source-metadata.audit.py
create mode 100644 configure-opencode-child-source.py
create mode 100644 final-child-hub-readback.py
create mode 100644 inspect-tool-schemas.py
create mode 100644 opencode-child-source-plan.py
create mode 100644 plan-reviewed-hub-upgrade.py
create mode 100644 prepare-um1646-inventory-update.py
create mode 100644 preserve-final-safe-receipts.py
create mode 100644 probe-sentry-empty-ack.py
create mode 100644 publish-reviewed-files.py
create mode 100644 publish-um1651-main-merge.py
create mode 100644 publish-um1651-merge-gh-fallback.py
create mode 100644 publish-um1651-reviewed.py
create mode 100644 read-current-operations.py
create mode 100644 read-final-suppression-flag.py
create mode 100644 read-mounted-hub-metadata.py
create mode 100644 recover-verified-stop.py
create mode 100644 sentry-historic-claude-receipts.audit.py
create mode 100644 test_child_config_local_cas.py
create mode 100644 test_um1646_inventory_update_fixture.py
create mode 100644 test_upgrade_reviewed_hub.py
create mode 100644 upgrade-reviewed-hub.py
create mode 100644 verify-reviewed-hub-image.py
create mode 100644 verify-upgraded-hub-and-track.py
diff --git a/.kody-trigger.txt b/.kody-trigger.txt
new file mode 100644
index 00000000..1ea16be4
--- /dev/null
+++ b/.kody-trigger.txt
@@ -0,0 +1 @@
+@kody start-review
diff --git a/.um1646-child-pair-apply-ae3a6cbb3461248daad470f024b766a4b11ab189cce28af3894fc96616bb34b7.json b/.um1646-child-pair-apply-ae3a6cbb3461248daad470f024b766a4b11ab189cce28af3894fc96616bb34b7.json
new file mode 100644
index 00000000..b3448dc7
--- /dev/null
+++ b/.um1646-child-pair-apply-ae3a6cbb3461248daad470f024b766a4b11ab189cce28af3894fc96616bb34b7.json
@@ -0,0 +1,77 @@
+{
+ "backup": {
+ "backup": "created_and_verified",
+ "sha256": "7e7f8408962c84ca3925536a6da5f3cffe2a49615b23bc0c25592964c17792de"
+ },
+ "localAfter": {
+ "desiredValueSha256": {
+ "BOTFLEET_WORKSPACES_DIRS": "f5099a13db2d688fadbb916ae270f1b0ed6a758b8b05dc99fa8f4601550bf77e",
+ "OPENCODE_ADDITIONAL_DBS_JSON": "c3f9990ffa4c45c50c16fad923e748412451e4dbb0af64e835635d22b2b715f2"
+ },
+ "fileIdentity": {
+ "bytes": 1023,
+ "device": 2049,
+ "inode": 262355,
+ "mtimeNs": 1793714056530732994
+ },
+ "keys": {
+ "BOTFLEET_WORKSPACES_DIRS": "equal",
+ "OPENCODE_ADDITIONAL_DBS_JSON": "equal"
+ },
+ "mode": "0600",
+ "ownerGid": 1001,
+ "ownerUid": 1001,
+ "sourceSha256": "fdf864f67f7788448e6169c12ec915b7d2f78ad9ee8617c05df1152f48366188"
+ },
+ "localBefore": {
+ "desiredValueSha256": {
+ "BOTFLEET_WORKSPACES_DIRS": "f5099a13db2d688fadbb916ae270f1b0ed6a758b8b05dc99fa8f4601550bf77e",
+ "OPENCODE_ADDITIONAL_DBS_JSON": "c3f9990ffa4c45c50c16fad923e748412451e4dbb0af64e835635d22b2b715f2"
+ },
+ "fileIdentity": {
+ "bytes": 832,
+ "device": 2049,
+ "inode": 274578,
+ "mtimeNs": 1793403562519636205
+ },
+ "keys": {
+ "BOTFLEET_WORKSPACES_DIRS": "absent",
+ "OPENCODE_ADDITIONAL_DBS_JSON": "absent"
+ },
+ "mode": "0600",
+ "ownerGid": 1001,
+ "ownerUid": 1001,
+ "sourceSha256": "7e7f8408962c84ca3925536a6da5f3cffe2a49615b23bc0c25592964c17792de"
+ },
+ "localResult": {
+ "sha256": "fdf864f67f7788448e6169c12ec915b7d2f78ad9ee8617c05df1152f48366188",
+ "status": "applied_and_verified"
+ },
+ "phase": "complete",
+ "releaseMessageId": 637193996,
+ "remote": {
+ "claimSha256": "57ee2e4825f71ef78afd0d6a6e94897980b033161950bc7584cd9d0a8e4ae172",
+ "keys": {
+ "BOTFLEET_SERVER_WORKSPACES_DIRS": {
+ "attempted": true,
+ "confirmedCreated": true,
+ "plannedState": "absent",
+ "postHttpStatus": 200,
+ "readbackVerified": true,
+ "status": "verified_equal"
+ },
+ "OPENCODE_SERVER_ADDITIONAL_DBS_JSON": {
+ "attempted": true,
+ "confirmedCreated": true,
+ "plannedState": "absent",
+ "postHttpStatus": 200,
+ "readbackVerified": true,
+ "status": "verified_equal"
+ }
+ },
+ "ok": true,
+ "sourceOfTruthComplete": true
+ },
+ "rootPlanSha256": "ae3a6cbb3461248daad470f024b766a4b11ab189cce28af3894fc96616bb34b7",
+ "unrelatedBytesPreserved": true
+}
diff --git a/.um1646-child-pair-plan.json b/.um1646-child-pair-plan.json
new file mode 100644
index 00000000..6d9c8e46
--- /dev/null
+++ b/.um1646-child-pair-plan.json
@@ -0,0 +1,130 @@
+{
+ "code": {
+ "controllerSha256": "0b2887e70ac5117b7d934b63a79ebc48daf0e9c6797b53bafaa0b0eceae96831",
+ "localModuleSha256": "bf985135a63c8f4129c1a2c0d8029a7dff074fc6d1df9d823259da8fb2fb1f2b",
+ "remoteSha256": "6ff4e606a01202ea6a1ec671d2b09464367e16c4f2bd18b12f7ec6f6851e62a5"
+ },
+ "installed": {
+ "hashes": {
+ "lib/collector-sentry-bridge.mjs": "c0e50eecccbf33447a0872e6f3d8acd1fe5e24170f203583abea41a131cdfb7d",
+ "lib/fleet-secrets.mjs": "965161f006d83325d136c1b9a0ce4295a56bf75b388a5729209cec734b7cd95c",
+ "lib/opencode-session-telemetry.mjs": "ee2b5c32ace959c88654a3d0b50cedcd408ab6a159ba2b6213682a9f7d1858e8",
+ "lib/run-session-token-collector.mjs": "adc6674e7b957fd0562212ecd9dd3bbbc24b53bdc4f40f70ddaab46293036d53",
+ "lib/session-token-collectors.mjs": "816829d8df98b2518164e58f0f697072d4e6bd369ec2e400a8173a2800ca6505",
+ "opencode-usage-collector.mjs": "78bfeaddc395d9e5a41b0c4fe0dec19a975231f5c586bfbafe7a35160ee3088c",
+ "telemetry-hub/allowlist.mjs": "d9020928a99d258e975b406ef152b787e9212329f753ed5179dbca75dd141be1",
+ "telemetry-hub/internal-event.mjs": "d061efdad89096a99e982aaeed8dff4a5ffd110fe3a1ba2a08bdcf9985fcca7d",
+ "telemetry-hub/journal.mjs": "da3893330b9f5f6861edab614687e4b0fa5dec4e2013c2e1e266415e42c61434",
+ "telemetry-hub/metadata-projection.mjs": "8b91b390859eebc729de0b4118340a7a3bff114e105121ff38ead83264c18c51",
+ "telemetry-hub/sentry-sender.mjs": "bf6fb45f7ef1e921aba9487d6479dbcf00f95329b6f0784ebeaaee5ce96a8a92"
+ },
+ "sourceCommit": "ca19ad6ab8e98b5ac506d75d15b72dd0b9cd9015"
+ },
+ "local": {
+ "desiredValueSha256": {
+ "BOTFLEET_WORKSPACES_DIRS": "f5099a13db2d688fadbb916ae270f1b0ed6a758b8b05dc99fa8f4601550bf77e",
+ "OPENCODE_ADDITIONAL_DBS_JSON": "c3f9990ffa4c45c50c16fad923e748412451e4dbb0af64e835635d22b2b715f2"
+ },
+ "fileIdentity": {
+ "bytes": 832,
+ "device": 2049,
+ "inode": 274578,
+ "mtimeNs": 1793403562519636205
+ },
+ "keys": {
+ "BOTFLEET_WORKSPACES_DIRS": "absent",
+ "OPENCODE_ADDITIONAL_DBS_JSON": "absent"
+ },
+ "mode": "0600",
+ "ownerGid": 1001,
+ "ownerUid": 1001,
+ "sourceSha256": "7e7f8408962c84ca3925536a6da5f3cffe2a49615b23bc0c25592964c17792de"
+ },
+ "releaseMessageId": 637193996,
+ "remote": {
+ "ok": true,
+ "remoteCodeSha256": "6ff4e606a01202ea6a1ec671d2b09464367e16c4f2bd18b12f7ec6f6851e62a5",
+ "remoteWrites": false,
+ "snapshot": {
+ "custody": {
+ "read": {
+ "bytes": 105,
+ "device": 16777233,
+ "gid": 20,
+ "inode": 757911686,
+ "mode": 384,
+ "mtimeNs": 1793711131926484407,
+ "parent": {
+ "device": 16777233,
+ "gid": 20,
+ "inode": 757911654,
+ "mode": 448,
+ "uid": 501
+ },
+ "sha256": "e8a0c8582f931dce2c179565f45880bc82b91dc9076eb6bacf459c3210530715",
+ "uid": 501
+ },
+ "write": {
+ "bytes": 105,
+ "device": 16777233,
+ "gid": 20,
+ "inode": 757911697,
+ "mode": 384,
+ "mtimeNs": 1793711132492581515,
+ "parent": {
+ "device": 16777233,
+ "gid": 20,
+ "inode": 757911654,
+ "mode": 448,
+ "uid": 501
+ },
+ "sha256": "27fc3af9abe4035163a9fa8d652d7108385c3538b5adfea29461db6e80a025fc",
+ "uid": 501
+ }
+ },
+ "keys": {
+ "BOTFLEET_SERVER_WORKSPACES_DIRS": {
+ "state": "absent",
+ "valueSha256": null
+ },
+ "OPENCODE_SERVER_ADDITIONAL_DBS_JSON": {
+ "state": "absent",
+ "valueSha256": null
+ }
+ },
+ "serviceMetadata": {
+ "read": {
+ "expiresAt": "2027-02-01T13:05:31.892Z",
+ "explicitIds": {
+ "_id": "2da57b07-1bed-4955-85ad-4db24ff60c43",
+ "id": "2da57b07-1bed-4955-85ad-4db24ff60c43"
+ },
+ "metadataSha256": "99cf668852d65a5dc0773b4b7a1e607c73eebed4b2130c384db6cbc2a988c547",
+ "nameVerified": true,
+ "projectVerified": true,
+ "role": "read",
+ "singletonEnvironment": "prod",
+ "singletonFolder": "/telemetry",
+ "singletonPermission": "read"
+ },
+ "write": {
+ "expiresAt": "2027-02-01T13:05:32.458Z",
+ "explicitIds": {
+ "_id": "81318b7a-7e2e-41f9-8788-cb0fefa12273",
+ "id": "81318b7a-7e2e-41f9-8788-cb0fefa12273"
+ },
+ "metadataSha256": "0c76ad22503593f306c9ebc5bf944dc1efb3a01f7fdf0982fb1b500d24519965",
+ "nameVerified": true,
+ "projectVerified": true,
+ "role": "write",
+ "singletonEnvironment": "prod",
+ "singletonFolder": "/telemetry",
+ "singletonPermission": "write"
+ }
+ }
+ }
+ },
+ "scope": "two-child-source-settings-only",
+ "version": 1,
+ "wireMessageId": 637192947
+}
diff --git a/.um1646-claude-historic24h.mjs b/.um1646-claude-historic24h.mjs
new file mode 100644
index 00000000..52938f0f
--- /dev/null
+++ b/.um1646-claude-historic24h.mjs
@@ -0,0 +1,98 @@
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { readFile, writeFile } from 'node:fs/promises';
+import { hostname } from 'node:os';
+import { join } from 'node:path';
+import { pathToFileURL } from 'node:url';
+import childProcess from 'node:child_process';
+import { syncBuiltinESMExports } from 'node:module';
+
+const root='/Users/jay/apps/usage-monitor-collectors';
+const planFile='/tmp/um1646-sentry-historic-20261103/claude-historic-24h-plan-v3.json';
+const receiptFile='/tmp/um1646-sentry-historic-20261103/claude-historic-24h-receipt-v3.json';
+const fixedLower='2026-10-29T23:32:30.055Z';
+const fixedUpper='2026-10-30T23:32:30.055Z';
+const commit='ca19ad6ab8e98b5ac506d75d15b72dd0b9cd9015';
+assert.match(commit,/^[a-f0-9]{40}$/);
+const mode=process.env.UM_CLAUDE_CATCHUP_MODE;
+assert.ok(['plan','apply'].includes(mode));
+assert.equal(process.argv[1],undefined);
+Object.defineProperty(process,'argv',{value:Object.freeze([...process.argv,'--dry-run']),writable:false,configurable:false});
+assert.ok(process.argv.includes('--dry-run'));
+assert.ok(!Object.keys(process.env).some(key=>/INGEST.*TOKEN|TOKEN.*INGEST/.test(key)&&process.env[key]));
+// Block the installed token resolver's absolute fleet-secrets fallback too.
+const originalExecFileSync=childProcess.execFileSync;
+childProcess.execFileSync=(file,args,options)=>{
+ if(!['ps','/bin/ps','/usr/bin/ps'].includes(file)||!Array.isArray(args)||args.length!==4||args[0]!=='-o'||args[1]!=='lstart='||args[2]!=='-p'||!/^\d+$/.test(String(args[3])))throw Error('Only read-only process birth lookup is allowed');
+ return originalExecFileSync(file,args,options);
+};
+syncBuiltinESMExports();
+assert.ok(!['1','true','yes','on'].includes((process.env.USAGE_MONITOR_EXCLUDE_BOTFLEET_CHILDREN||'').toLowerCase()));
+const versionMatch=(await readFile(join(root,'VERSION'),'utf8')).match(/^sha=([a-f0-9]{7,40})$/m);
+assert.ok(versionMatch&&commit.startsWith(versionMatch[1]));
+const hash=value=>createHash('sha256').update(value).digest('hex');
+const modules=['claude-usage-collector.mjs','lib/session-token-collectors.mjs','lib/collector-sentry-bridge.mjs','telemetry-hub/metadata-projection.mjs','telemetry-hub/allowlist.mjs','telemetry-hub/sentry-sender.mjs'];
+const sourceHashes=await Promise.all(modules.map(async file=>[file,hash(await readFile(join(root,'scripts',file)))]));
+const originalFetch=globalThis.fetch;
+globalThis.fetch=()=>{throw Error('Plan/import phase prohibits network delivery');};
+const {collectClaudeEvents}=await import(pathToFileURL(join(root,'scripts/claude-usage-collector.mjs')).href);
+const {collectorSentryConfig,collectorSentryEvents,enqueueCollectorSentry,drainCollectorSentry}=await import(pathToFileURL(join(root,'scripts/lib/collector-sentry-bridge.mjs')).href);
+const identity={producerId:'claude-code',producerInstanceId:process.env.USAGE_MACHINE_ID?.trim()||hostname()};
+assert.ok(!process.env.CLAUDE_PRODUCER_ID||process.env.CLAUDE_PRODUCER_ID===identity.producerId);
+const config=collectorSentryConfig(process.env,identity.producerId);
+assert.equal(config?.destination,'hub');
+const deliveryConfiguration={destination:config.destination,endpoint:config.endpoint,stateRoot:config.stateRoot};
+const deliveryConfigDigest=hash(JSON.stringify(deliveryConfiguration));
+let approved,planBytes;
+if(mode==='apply'){
+ planBytes=await readFile(planFile);
+ assert.equal(hash(planBytes),process.env.UM_CLAUDE_CATCHUP_APPROVED_PLAN_SHA256);
+ approved=JSON.parse(planBytes);
+ assert.equal(approved.commit,commit);
+ assert.equal(approved.sourceHashDigest,hash(JSON.stringify(sourceHashes)));
+ assert.equal(approved.identityDigest,hash(JSON.stringify(identity)));
+ assert.equal(approved.deliveryConfigDigest,deliveryConfigDigest);
+}
+const upper=mode==='plan'?new Date(fixedUpper):new Date(approved.upper);
+const lower=mode==='plan'?new Date(fixedLower):new Date(approved.lower);
+assert.equal(upper.getTime()-lower.getTime(),86400000);
+const scanStatus={complete:true};
+const sourceEvents=await collectClaudeEvents({since:lower,scanStatus});
+assert.equal(scanStatus.complete,true);
+assert.ok(sourceEvents.every(event=>Number.isFinite(Date.parse(event.occurredAt))));
+const events=sourceEvents.filter(event=>Date.parse(event.occurredAt)>=lower.getTime()&&Date.parse(event.occurredAt)<=upper.getTime());
+assert.ok(events.length<=60000);
+assert.ok(events.every(event=>event.metricType==='usage'&&event.unit==='token'));
+const projected=collectorSentryEvents(events,identity);
+const calls=projected.filter(event=>event.name==='chat');
+assert.ok(calls.length<=15000);
+const measured=calls.filter(event=>Number.isFinite(event.durationMs)&&event.durationMs>=0).length;
+const selectedDigest=hash(JSON.stringify([...projected].sort((a,b)=>a.eventId.localeCompare(b.eventId))));
+const summary={commit,windowHours:24,components:events.length,callMarkers:calls.length,observations:projected.length-calls.length,measuredDurations:measured,measuredCallSpans:calls.filter(event=>event.kind==='span').length,unmeasuredCallLogs:calls.filter(event=>event.kind==='log'&&!Number.isFinite(event.durationMs)).length,excludedAfterUpper:sourceEvents.length-events.length};
+const plan={...summary,lower:lower.toISOString(),upper:upper.toISOString(),selectedDigest,sourceHashDigest:hash(JSON.stringify(sourceHashes)),identityDigest:hash(JSON.stringify(identity)),deliveryConfiguration,deliveryConfigDigest,maxComponents:60000,maxCallMarkers:15000,maxDrainInvocations:16,globalDrainBudgetMs:55000,perInvocationRequestLimit:32,perInvocationBudgetMs:5000};
+if(mode==='plan'){
+ const bytes=Buffer.from(JSON.stringify(plan,null,2)+'\n');
+ await writeFile(planFile,bytes,{flag:'wx',mode:0o600});
+ console.log(JSON.stringify({mode,...summary,approvedPlanSha256:hash(bytes),durableOutboxTouched:false,networkRequests:0,umPosts:0,checkpointWrites:0}));
+}else{
+ assert.equal(selectedDigest,approved.selectedDigest);
+ assert.equal(events.length,approved.components);
+ assert.equal(calls.length,approved.callMarkers);
+ const allowed=new Set(['/v1/traces','/v1/logs'].map(signal=>config.endpoint+signal));
+ globalThis.fetch=(url,options)=>{
+ if(!allowed.has(String(url))||options?.method!=='POST')throw Error('Only the reviewed hub delivery target is allowed');
+ return originalFetch(url,options);
+ };
+ // The installed converter projects metadata before its durable SQLite write.
+ const outbox=await enqueueCollectorSentry(events,identity,config);
+ const deadline=performance.now()+55000;
+ const results=[];
+ for(let invocation=1;invocation<=16&&performance.now()+5000<=deadline;invocation++){
+ const result=await drainCollectorSentry(outbox,config,{requestLimit:32,budgetMs:5000});
+ results.push({invocation,...result});
+ if(!result.pending||(!result.delivered&&!result.quarantined))break;
+ }
+ const receipt={mode,...summary,planSha256:hash(planBytes),umPosts:0,checkpointWrites:0,sourceWrites:0,results};
+ await writeFile(receiptFile,JSON.stringify(receipt,null,2)+'\n',{flag:'wx',mode:0o600});
+ console.log(JSON.stringify(receipt));
+}
diff --git a/.um1646-claude-historic24h.py b/.um1646-claude-historic24h.py
new file mode 100644
index 00000000..f3980a64
--- /dev/null
+++ b/.um1646-claude-historic24h.py
@@ -0,0 +1,18 @@
+import json, os, pathlib, plistlib, subprocess, sys
+mode=sys.argv[1] if len(sys.argv)>1 else None
+if mode not in ('plan','apply'):raise SystemExit('Use plan or apply')
+path=pathlib.Path.home()/'Library/LaunchAgents/com.jays.claude-usage-collector.plist'
+with path.open('rb') as handle:job=plistlib.load(handle)
+env={**os.environ,**job.get('EnvironmentVariables',{})}
+for key in list(env):
+ if ('INGEST' in key and 'TOKEN' in key):del env[key]
+tokens=json.loads(env['COLLECTOR_TELEMETRY_HUB_TOKENS_JSON'])
+env['COLLECTOR_TELEMETRY_HUB_TOKENS_JSON']=json.dumps({'claude-code':tokens['claude-code']},separators=(',',':'))
+env['UM_CLAUDE_CATCHUP_MODE']=mode
+if mode=='apply' and len(env.get('UM_CLAUDE_CATCHUP_APPROVED_PLAN_SHA256',''))!=64:raise SystemExit('Exact approved plan digest required')
+code=pathlib.Path('/tmp/um1646-sentry-historic-20261103/claude-historic-24h.mjs').read_text()
+result=subprocess.run([job['ProgramArguments'][0],'--input-type=module'],input=code,text=True,capture_output=True,env=env,timeout=180)
+if result.returncode:raise SystemExit('Catch-up guard failed; no source or configuration values printed')
+rows=[json.loads(line) for line in result.stdout.splitlines() if line.startswith('{')]
+if len(rows)!=1:raise SystemExit('Unexpected catch-up output; no content printed')
+print(json.dumps(rows[0]))
diff --git a/.um1646-inventory-update.before-copy-fix.plan.json b/.um1646-inventory-update.before-copy-fix.plan.json
new file mode 100644
index 00000000..42add3ea
--- /dev/null
+++ b/.um1646-inventory-update.before-copy-fix.plan.json
@@ -0,0 +1,27 @@
+{
+ "applyRequiresExactPlanSha256": true,
+ "inventory": {
+ "afterSectionSha256": "cea3de5065d6ace0947e684ff932b27a9433bfbedda48e918da360567105e001",
+ "afterSha256": "9b8bb9d30f6316f1e8852391ade0e94f02f121c0e28686cdb88733a2786dfa5b",
+ "beforeSectionSha256": "d10a24b18dba6c5cbfcc0d75cf5c57d422356e695ef3060108862921dc6eb070",
+ "beforeSha256": "9d9446953d0767a7a87789b8d1a5926fd19050ebfdd07080d15ca863927bc590",
+ "diff": "--- MAC-LOCAL-PROCESSES.md:UM-1646 before\n+++ MAC-LOCAL-PROCESSES.md:UM-1646 after\n@@ -2,11 +2,11 @@\n \n | Process / Helper | Schedule And Purpose |\n |---|---|\n-| usage-monitor-telemetry-hub | Always-on server container; active; source 80f0c927; program node /app/scripts/telemetry-hub/start-with-infisical.mjs; restart unless-stopped; logs Docker stdout/stderr; generated span/log numeric aliases stored in Sentry; initial eleven receipts preserved plus two generated alias receipts verified across same-volume upgrade after Usage-Monitor PR #1845 review and merge. |\n-| Collector Sentry bridge | Active source 80f0c927; both hosts verified installed/imported; all four CLI sources configured for authenticated hub delivery; Mac jobs reloaded with guarded config readbacks; delivery will use the existing four CLI collector schedules; independent durable delivery inside existing invocations, with no additional daemon. |\n+| usage-monitor-telemetry-hub | Always-on server container; active; source 0a92fcfa; program node /app/scripts/telemetry-hub/start-with-infisical.mjs; restart unless-stopped; logs Docker stdout/stderr; generated span/log numeric aliases stored in Sentry; independently healthy after the same-service upgrade from Usage-Monitor PR #1874; original durable volume and configuration preserved; durable acknowledgements hold. |\n+| Collector Sentry bridge | Server collector installation: 55 files at ca19ad6; Mac: 54 files at ca19ad6 plus the Muse file at 7424ae0; both hosts verified installed/imported; all four CLI sources configured for authenticated hub delivery; Mac jobs reloaded with guarded config readbacks; delivery uses the existing four CLI collector schedules; independent durable delivery inside existing invocations; no additional daemon. Muse source 7424ae0 is installed but remains unloaded under the injector hold; no Muse job is loaded. |\n | scripts/prune-collector-sentry-outbox.mjs | On-demand only; bounded receipt pruning requires a verified checkpoint and preserves pending or quarantined records. |\n | scripts/retry-collector-sentry-outbox.mjs | On-demand only; retries explicitly selected quarantined records after correction. |\n-| botfleet-session-collector.mjs | Mac and server active; Sentry-only BotFleet turn aggregates; explicit 24-hour lookback; every 900 seconds; Mac label com.jays.botfleet-session-collector using /opt/homebrew/bin/node; server user cron uses existing run-server-collector.sh; logs ~/Library/Logs/botfleet-session-collector.log on Mac and ~/.local/state/usage-monitor/botfleet-native.log on server; registered before enable; first Mac pass delivered and stored 152 authentic turn spans with zero pending or quarantined; Linux ordinary native activity remains zero; one generated failed functional-test turn delivered and stored without fabricated usage. Its child OpenCode data-root location remains unverified after the child exited; the standalone source is unchanged. |\n+| botfleet-session-collector.mjs | Mac and server active; Sentry-only BotFleet turn aggregates; explicit 24-hour lookback; every 900 seconds; Mac label com.jays.botfleet-session-collector using /opt/homebrew/bin/node; server user cron uses existing run-server-collector.sh; logs ~/Library/Logs/botfleet-session-collector.log on Mac and ~/.local/state/usage-monitor/botfleet-native.log on server; registered before enable; first Mac pass delivered and stored 152 authentic turn spans with zero pending or quarantined; Linux ordinary native activity remains zero; one generated failed functional-test turn delivered and stored without fabricated usage. The standalone OpenCode source is unchanged. The permanent server child sources are verified: the OpenCode database is /mnt/fleet-extra/apps/botfleet-server/home/.local/share/opencode/opencode.db and the workspace root is /mnt/fleet-extra/apps/botfleet-server/data/workspaces; all eight retained child events are classified BotFleet. |\n | UM-1646 Sentry Receipt Audit | Task-scoped on-demand helper; approved Mac Python read route; stdout aggregate receipt counts only; no scheduler. |\n \n \n",
+ "path": "/Users/jay/apps/MAC-LOCAL-PROCESSES.md",
+ "sectionAfter": "## Usage Monitor Telemetry (UM-1646)\n\n| Process / Helper | Schedule And Purpose |\n|---|---|\n| usage-monitor-telemetry-hub | Always-on server container; active; source 0a92fcfa; program node /app/scripts/telemetry-hub/start-with-infisical.mjs; restart unless-stopped; logs Docker stdout/stderr; generated span/log numeric aliases stored in Sentry; independently healthy after the same-service upgrade from Usage-Monitor PR #1874; original durable volume and configuration preserved; durable acknowledgements hold. |\n| Collector Sentry bridge | Server collector installation: 55 files at ca19ad6; Mac: 54 files at ca19ad6 plus the Muse file at 7424ae0; both hosts verified installed/imported; all four CLI sources configured for authenticated hub delivery; Mac jobs reloaded with guarded config readbacks; delivery uses the existing four CLI collector schedules; independent durable delivery inside existing invocations; no additional daemon. Muse source 7424ae0 is installed but remains unloaded under the injector hold; no Muse job is loaded. |\n| scripts/prune-collector-sentry-outbox.mjs | On-demand only; bounded receipt pruning requires a verified checkpoint and preserves pending or quarantined records. |\n| scripts/retry-collector-sentry-outbox.mjs | On-demand only; retries explicitly selected quarantined records after correction. |\n| botfleet-session-collector.mjs | Mac and server active; Sentry-only BotFleet turn aggregates; explicit 24-hour lookback; every 900 seconds; Mac label com.jays.botfleet-session-collector using /opt/homebrew/bin/node; server user cron uses existing run-server-collector.sh; logs ~/Library/Logs/botfleet-session-collector.log on Mac and ~/.local/state/usage-monitor/botfleet-native.log on server; registered before enable; first Mac pass delivered and stored 152 authentic turn spans with zero pending or quarantined; Linux ordinary native activity remains zero; one generated failed functional-test turn delivered and stored without fabricated usage. The standalone OpenCode source is unchanged. The permanent server child sources are verified: the OpenCode database is /mnt/fleet-extra/apps/botfleet-server/home/.local/share/opencode/opencode.db and the workspace root is /mnt/fleet-extra/apps/botfleet-server/data/workspaces; all eight retained child events are classified BotFleet. |\n| UM-1646 Sentry Receipt Audit | Task-scoped on-demand helper; approved Mac Python read route; stdout aggregate receipt counts only; no scheduler. |\n\n\nPrivate runtime routing and credentials remain in the private operations inventory and Infisical.\n\n\n- `com.jay.afc602-infisical-metadata-*`: On-demand Infisical service-token migration for AFC-602; CLI token creation and metadata audit, one-shot tasks with no KeepAlive or schedule. Retired and unloaded after each task; no persistent job installed.\n\n",
+ "sectionBefore": "## Usage Monitor Telemetry (UM-1646)\n\n| Process / Helper | Schedule And Purpose |\n|---|---|\n| usage-monitor-telemetry-hub | Always-on server container; active; source 80f0c927; program node /app/scripts/telemetry-hub/start-with-infisical.mjs; restart unless-stopped; logs Docker stdout/stderr; generated span/log numeric aliases stored in Sentry; initial eleven receipts preserved plus two generated alias receipts verified across same-volume upgrade after Usage-Monitor PR #1845 review and merge. |\n| Collector Sentry bridge | Active source 80f0c927; both hosts verified installed/imported; all four CLI sources configured for authenticated hub delivery; Mac jobs reloaded with guarded config readbacks; delivery will use the existing four CLI collector schedules; independent durable delivery inside existing invocations, with no additional daemon. |\n| scripts/prune-collector-sentry-outbox.mjs | On-demand only; bounded receipt pruning requires a verified checkpoint and preserves pending or quarantined records. |\n| scripts/retry-collector-sentry-outbox.mjs | On-demand only; retries explicitly selected quarantined records after correction. |\n| botfleet-session-collector.mjs | Mac and server active; Sentry-only BotFleet turn aggregates; explicit 24-hour lookback; every 900 seconds; Mac label com.jays.botfleet-session-collector using /opt/homebrew/bin/node; server user cron uses existing run-server-collector.sh; logs ~/Library/Logs/botfleet-session-collector.log on Mac and ~/.local/state/usage-monitor/botfleet-native.log on server; registered before enable; first Mac pass delivered and stored 152 authentic turn spans with zero pending or quarantined; Linux ordinary native activity remains zero; one generated failed functional-test turn delivered and stored without fabricated usage. Its child OpenCode data-root location remains unverified after the child exited; the standalone source is unchanged. |\n| UM-1646 Sentry Receipt Audit | Task-scoped on-demand helper; approved Mac Python read route; stdout aggregate receipt counts only; no scheduler. |\n\n\nPrivate runtime routing and credentials remain in the private operations inventory and Infisical.\n\n\n- `com.jay.afc602-infisical-metadata-*`: On-demand Infisical service-token migration for AFC-602; CLI token creation and metadata audit, one-shot tasks with no KeepAlive or schedule. Retired and unloaded after each task; no persistent job installed.\n\n"
+ },
+ "note": {
+ "afterSectionSha256": "9abbea4c2175c5c80c9636dfe27a00d6b544e1596145ebf020b07233fd4c04b8",
+ "afterSha256": "d71e5adc3a324b738e21bfd0d795b6750b487a85c983180501b50a540fe25b2f",
+ "beforeSectionSha256": "d3952f74e3237e2d766ad8491b0331e894f48c83719a55c5539a39f3abf2f935",
+ "beforeSha256": "f600e812fe54cb90fc13b279f539ac570ad36bc68132ac0de920451d83541fe7",
+ "diff": "--- Background Jobs Master List:UM-1646 before\n+++ Background Jobs Master List:UM-1646 after\n@@ -1,3 +1,3 @@\n
\n-
\n+- usage-monitor-telemetry-hub: Always-on server container; active; source 0a92fcfa; program node /app/scripts/telemetry-hub/start-with-infisical.mjs; restart unless-stopped; logs Docker stdout/stderr; generated span/log numeric aliases stored in Sentry; independently healthy after the same-service upgrade from Usage-Monitor PR #1874; original durable volume and configuration preserved; durable acknowledgements hold.
- Collector Sentry bridge: Server collector installation: 55 files at ca19ad6; Mac: 54 files at ca19ad6 plus the Muse file at 7424ae0; both hosts verified installed/imported; all four CLI sources configured for authenticated hub delivery; Mac jobs reloaded with guarded config readbacks; delivery uses the existing four CLI collector schedules; independent durable delivery inside existing invocations; no additional daemon. Muse source 7424ae0 is installed but remains unloaded under the injector hold; no Muse job is loaded.
- scripts/prune-collector-sentry-outbox.mjs: On-demand only; bounded receipt pruning requires a verified checkpoint and preserves pending or quarantined records.
- scripts/retry-collector-sentry-outbox.mjs: On-demand only; retries explicitly selected quarantined records after correction.
- botfleet-session-collector.mjs: Mac and server active; Sentry-only BotFleet turn aggregates; explicit 24-hour lookback; every 900 seconds; Mac label com.jays.botfleet-session-collector using /opt/homebrew/bin/node; server user cron uses existing run-server-collector.sh; logs ~/Library/Logs/botfleet-session-collector.log on Mac and ~/.local/state/usage-monitor/botfleet-native.log on server; registered before enable; first Mac pass delivered and stored 152 authentic turn spans with zero pending or quarantined; Linux ordinary native activity remains zero; one generated failed functional-test turn delivered and stored without fabricated usage. The standalone OpenCode source is unchanged. The permanent server child sources are verified: the OpenCode database is /mnt/fleet-extra/apps/botfleet-server/home/.local/share/opencode/opencode.db and the workspace root is /mnt/fleet-extra/apps/botfleet-server/data/workspaces; all eight retained child events are classified BotFleet.
- UM-1646 Sentry Receipt Audit: Task-scoped on-demand helper; approved Mac Python read route; stdout aggregate receipt counts only; no scheduler.
\n
\n",
+ "sectionAfter": "\n- usage-monitor-telemetry-hub: Always-on server container; active; source 0a92fcfa; program node /app/scripts/telemetry-hub/start-with-infisical.mjs; restart unless-stopped; logs Docker stdout/stderr; generated span/log numeric aliases stored in Sentry; independently healthy after the same-service upgrade from Usage-Monitor PR #1874; original durable volume and configuration preserved; durable acknowledgements hold.
- Collector Sentry bridge: Server collector installation: 55 files at ca19ad6; Mac: 54 files at ca19ad6 plus the Muse file at 7424ae0; both hosts verified installed/imported; all four CLI sources configured for authenticated hub delivery; Mac jobs reloaded with guarded config readbacks; delivery uses the existing four CLI collector schedules; independent durable delivery inside existing invocations; no additional daemon. Muse source 7424ae0 is installed but remains unloaded under the injector hold; no Muse job is loaded.
- scripts/prune-collector-sentry-outbox.mjs: On-demand only; bounded receipt pruning requires a verified checkpoint and preserves pending or quarantined records.
- scripts/retry-collector-sentry-outbox.mjs: On-demand only; retries explicitly selected quarantined records after correction.
- botfleet-session-collector.mjs: Mac and server active; Sentry-only BotFleet turn aggregates; explicit 24-hour lookback; every 900 seconds; Mac label com.jays.botfleet-session-collector using /opt/homebrew/bin/node; server user cron uses existing run-server-collector.sh; logs ~/Library/Logs/botfleet-session-collector.log on Mac and ~/.local/state/usage-monitor/botfleet-native.log on server; registered before enable; first Mac pass delivered and stored 152 authentic turn spans with zero pending or quarantined; Linux ordinary native activity remains zero; one generated failed functional-test turn delivered and stored without fabricated usage. The standalone OpenCode source is unchanged. The permanent server child sources are verified: the OpenCode database is /mnt/fleet-extra/apps/botfleet-server/home/.local/share/opencode/opencode.db and the workspace root is /mnt/fleet-extra/apps/botfleet-server/data/workspaces; all eight retained child events are classified BotFleet.
- UM-1646 Sentry Receipt Audit: Task-scoped on-demand helper; approved Mac Python read route; stdout aggregate receipt counts only; no scheduler.
\n
\n",
+ "sectionBefore": "\n
\n
\n",
+ "title": "⭐️ Background Jobs Master List"
+ },
+ "schema": 1,
+ "session": "01a18e51-51e1-7093-9269-0901397a9ec1",
+ "task": "UM-1646 inventory completion",
+ "writes": false
+}
diff --git a/.um1646-inventory-update.plan.json b/.um1646-inventory-update.plan.json
new file mode 100644
index 00000000..bb9e43a6
--- /dev/null
+++ b/.um1646-inventory-update.plan.json
@@ -0,0 +1,27 @@
+{
+ "applyRequiresExactPlanSha256": true,
+ "inventory": {
+ "afterSectionSha256": "45626ba12f0c51aa86755c7a4db07f25ebe0e98b4ae9ca6eec25e4a0792088b4",
+ "afterSha256": "382836487089103eb429a9807cf5bca471fa70ddd2296d89be210e9ca0042fcc",
+ "beforeSectionSha256": "d10a24b18dba6c5cbfcc0d75cf5c57d422356e695ef3060108862921dc6eb070",
+ "beforeSha256": "9d9446953d0767a7a87789b8d1a5926fd19050ebfdd07080d15ca863927bc590",
+ "diff": "--- MAC-LOCAL-PROCESSES.md:UM-1646 before\n+++ MAC-LOCAL-PROCESSES.md:UM-1646 after\n@@ -2,11 +2,11 @@\n \n | Process / Helper | Schedule And Purpose |\n |---|---|\n-| usage-monitor-telemetry-hub | Always-on server container; active; source 80f0c927; program node /app/scripts/telemetry-hub/start-with-infisical.mjs; restart unless-stopped; logs Docker stdout/stderr; generated span/log numeric aliases stored in Sentry; initial eleven receipts preserved plus two generated alias receipts verified across same-volume upgrade after Usage-Monitor PR #1845 review and merge. |\n-| Collector Sentry bridge | Active source 80f0c927; both hosts verified installed/imported; all four CLI sources configured for authenticated hub delivery; Mac jobs reloaded with guarded config readbacks; delivery will use the existing four CLI collector schedules; independent durable delivery inside existing invocations, with no additional daemon. |\n+| usage-monitor-telemetry-hub | Always-on server container; active; source 0a92fcfa; program node /app/scripts/telemetry-hub/start-with-infisical.mjs; restart unless-stopped; logs Docker stdout/stderr; generated span/log numeric aliases stored in Sentry; independently healthy after the same-service upgrade from Usage-Monitor PR #1874; original durable volume and configuration preserved; ambiguous acknowledgements are held for reconciliation. |\n+| Collector Sentry bridge | Server collector installation: 55 files at ca19ad6; Mac: 54 files at ca19ad6 plus the Muse file at 7424ae0; both hosts verified installed/imported; all four CLI sources configured for authenticated hub delivery; Mac jobs reloaded with guarded config readbacks; delivery uses the existing four CLI collector schedules; independent durable delivery inside existing invocations; no additional daemon. Muse source 7424ae0 is installed but remains unloaded under the injector hold; no Muse job is loaded. |\n | scripts/prune-collector-sentry-outbox.mjs | On-demand only; bounded receipt pruning requires a verified checkpoint and preserves pending or quarantined records. |\n | scripts/retry-collector-sentry-outbox.mjs | On-demand only; retries explicitly selected quarantined records after correction. |\n-| botfleet-session-collector.mjs | Mac and server active; Sentry-only BotFleet turn aggregates; explicit 24-hour lookback; every 900 seconds; Mac label com.jays.botfleet-session-collector using /opt/homebrew/bin/node; server user cron uses existing run-server-collector.sh; logs ~/Library/Logs/botfleet-session-collector.log on Mac and ~/.local/state/usage-monitor/botfleet-native.log on server; registered before enable; first Mac pass delivered and stored 152 authentic turn spans with zero pending or quarantined; Linux ordinary native activity remains zero; one generated failed functional-test turn delivered and stored without fabricated usage. Its child OpenCode data-root location remains unverified after the child exited; the standalone source is unchanged. |\n+| botfleet-session-collector.mjs | Mac and server active; Sentry-only BotFleet turn aggregates; explicit 24-hour lookback; every 900 seconds; Mac label com.jays.botfleet-session-collector using /opt/homebrew/bin/node; server user cron uses existing run-server-collector.sh; logs ~/Library/Logs/botfleet-session-collector.log on Mac and ~/.local/state/usage-monitor/botfleet-native.log on server; registered before enable; first Mac pass delivered and stored 152 authentic turn spans with zero pending or quarantined; The earlier Linux native audit found no ordinary activity; one generated failed functional-test turn delivered and stored without fabricated usage. The standalone OpenCode source is unchanged. The permanent server child sources are verified: the OpenCode database is /mnt/fleet-extra/apps/botfleet-server/home/.local/share/opencode/opencode.db and the workspace root is /mnt/fleet-extra/apps/botfleet-server/data/workspaces; all eight retained child events are classified BotFleet. |\n | UM-1646 Sentry Receipt Audit | Task-scoped on-demand helper; approved Mac Python read route; stdout aggregate receipt counts only; no scheduler. |\n \n \n",
+ "path": "/Users/jay/apps/MAC-LOCAL-PROCESSES.md",
+ "sectionAfter": "## Usage Monitor Telemetry (UM-1646)\n\n| Process / Helper | Schedule And Purpose |\n|---|---|\n| usage-monitor-telemetry-hub | Always-on server container; active; source 0a92fcfa; program node /app/scripts/telemetry-hub/start-with-infisical.mjs; restart unless-stopped; logs Docker stdout/stderr; generated span/log numeric aliases stored in Sentry; independently healthy after the same-service upgrade from Usage-Monitor PR #1874; original durable volume and configuration preserved; ambiguous acknowledgements are held for reconciliation. |\n| Collector Sentry bridge | Server collector installation: 55 files at ca19ad6; Mac: 54 files at ca19ad6 plus the Muse file at 7424ae0; both hosts verified installed/imported; all four CLI sources configured for authenticated hub delivery; Mac jobs reloaded with guarded config readbacks; delivery uses the existing four CLI collector schedules; independent durable delivery inside existing invocations; no additional daemon. Muse source 7424ae0 is installed but remains unloaded under the injector hold; no Muse job is loaded. |\n| scripts/prune-collector-sentry-outbox.mjs | On-demand only; bounded receipt pruning requires a verified checkpoint and preserves pending or quarantined records. |\n| scripts/retry-collector-sentry-outbox.mjs | On-demand only; retries explicitly selected quarantined records after correction. |\n| botfleet-session-collector.mjs | Mac and server active; Sentry-only BotFleet turn aggregates; explicit 24-hour lookback; every 900 seconds; Mac label com.jays.botfleet-session-collector using /opt/homebrew/bin/node; server user cron uses existing run-server-collector.sh; logs ~/Library/Logs/botfleet-session-collector.log on Mac and ~/.local/state/usage-monitor/botfleet-native.log on server; registered before enable; first Mac pass delivered and stored 152 authentic turn spans with zero pending or quarantined; The earlier Linux native audit found no ordinary activity; one generated failed functional-test turn delivered and stored without fabricated usage. The standalone OpenCode source is unchanged. The permanent server child sources are verified: the OpenCode database is /mnt/fleet-extra/apps/botfleet-server/home/.local/share/opencode/opencode.db and the workspace root is /mnt/fleet-extra/apps/botfleet-server/data/workspaces; all eight retained child events are classified BotFleet. |\n| UM-1646 Sentry Receipt Audit | Task-scoped on-demand helper; approved Mac Python read route; stdout aggregate receipt counts only; no scheduler. |\n\n\nPrivate runtime routing and credentials remain in the private operations inventory and Infisical.\n\n\n- `com.jay.afc602-infisical-metadata-*`: On-demand Infisical service-token migration for AFC-602; CLI token creation and metadata audit, one-shot tasks with no KeepAlive or schedule. Retired and unloaded after each task; no persistent job installed.\n\n",
+ "sectionBefore": "## Usage Monitor Telemetry (UM-1646)\n\n| Process / Helper | Schedule And Purpose |\n|---|---|\n| usage-monitor-telemetry-hub | Always-on server container; active; source 80f0c927; program node /app/scripts/telemetry-hub/start-with-infisical.mjs; restart unless-stopped; logs Docker stdout/stderr; generated span/log numeric aliases stored in Sentry; initial eleven receipts preserved plus two generated alias receipts verified across same-volume upgrade after Usage-Monitor PR #1845 review and merge. |\n| Collector Sentry bridge | Active source 80f0c927; both hosts verified installed/imported; all four CLI sources configured for authenticated hub delivery; Mac jobs reloaded with guarded config readbacks; delivery will use the existing four CLI collector schedules; independent durable delivery inside existing invocations, with no additional daemon. |\n| scripts/prune-collector-sentry-outbox.mjs | On-demand only; bounded receipt pruning requires a verified checkpoint and preserves pending or quarantined records. |\n| scripts/retry-collector-sentry-outbox.mjs | On-demand only; retries explicitly selected quarantined records after correction. |\n| botfleet-session-collector.mjs | Mac and server active; Sentry-only BotFleet turn aggregates; explicit 24-hour lookback; every 900 seconds; Mac label com.jays.botfleet-session-collector using /opt/homebrew/bin/node; server user cron uses existing run-server-collector.sh; logs ~/Library/Logs/botfleet-session-collector.log on Mac and ~/.local/state/usage-monitor/botfleet-native.log on server; registered before enable; first Mac pass delivered and stored 152 authentic turn spans with zero pending or quarantined; Linux ordinary native activity remains zero; one generated failed functional-test turn delivered and stored without fabricated usage. Its child OpenCode data-root location remains unverified after the child exited; the standalone source is unchanged. |\n| UM-1646 Sentry Receipt Audit | Task-scoped on-demand helper; approved Mac Python read route; stdout aggregate receipt counts only; no scheduler. |\n\n\nPrivate runtime routing and credentials remain in the private operations inventory and Infisical.\n\n\n- `com.jay.afc602-infisical-metadata-*`: On-demand Infisical service-token migration for AFC-602; CLI token creation and metadata audit, one-shot tasks with no KeepAlive or schedule. Retired and unloaded after each task; no persistent job installed.\n\n"
+ },
+ "note": {
+ "afterSectionSha256": "f9d661c5bb6bcd36e6b0b0ba0cd1b6627e31d5118b46b1ec44f9e18e40b6b4e6",
+ "afterSha256": "a789142238a445a5c0ed9d221f411f695be6a29b837d42a89bdb3561a1e3d420",
+ "beforeSectionSha256": "d3952f74e3237e2d766ad8491b0331e894f48c83719a55c5539a39f3abf2f935",
+ "beforeSha256": "f600e812fe54cb90fc13b279f539ac570ad36bc68132ac0de920451d83541fe7",
+ "diff": "--- Background Jobs Master List:UM-1646 before\n+++ Background Jobs Master List:UM-1646 after\n@@ -1,3 +1,3 @@\n \n-
\n+- usage-monitor-telemetry-hub: Always-on server container; active; source 0a92fcfa; program node /app/scripts/telemetry-hub/start-with-infisical.mjs; restart unless-stopped; logs Docker stdout/stderr; generated span/log numeric aliases stored in Sentry; independently healthy after the same-service upgrade from Usage-Monitor PR #1874; original durable volume and configuration preserved; ambiguous acknowledgements are held for reconciliation.
- Collector Sentry bridge: Server collector installation: 55 files at ca19ad6; Mac: 54 files at ca19ad6 plus the Muse file at 7424ae0; both hosts verified installed/imported; all four CLI sources configured for authenticated hub delivery; Mac jobs reloaded with guarded config readbacks; delivery uses the existing four CLI collector schedules; independent durable delivery inside existing invocations; no additional daemon. Muse source 7424ae0 is installed but remains unloaded under the injector hold; no Muse job is loaded.
- scripts/prune-collector-sentry-outbox.mjs: On-demand only; bounded receipt pruning requires a verified checkpoint and preserves pending or quarantined records.
- scripts/retry-collector-sentry-outbox.mjs: On-demand only; retries explicitly selected quarantined records after correction.
- botfleet-session-collector.mjs: Mac and server active; Sentry-only BotFleet turn aggregates; explicit 24-hour lookback; every 900 seconds; Mac label com.jays.botfleet-session-collector using /opt/homebrew/bin/node; server user cron uses existing run-server-collector.sh; logs ~/Library/Logs/botfleet-session-collector.log on Mac and ~/.local/state/usage-monitor/botfleet-native.log on server; registered before enable; first Mac pass delivered and stored 152 authentic turn spans with zero pending or quarantined; The earlier Linux native audit found no ordinary activity; one generated failed functional-test turn delivered and stored without fabricated usage. The standalone OpenCode source is unchanged. The permanent server child sources are verified: the OpenCode database is /mnt/fleet-extra/apps/botfleet-server/home/.local/share/opencode/opencode.db and the workspace root is /mnt/fleet-extra/apps/botfleet-server/data/workspaces; all eight retained child events are classified BotFleet.
- UM-1646 Sentry Receipt Audit: Task-scoped on-demand helper; approved Mac Python read route; stdout aggregate receipt counts only; no scheduler.
\n
\n",
+ "sectionAfter": "\n- usage-monitor-telemetry-hub: Always-on server container; active; source 0a92fcfa; program node /app/scripts/telemetry-hub/start-with-infisical.mjs; restart unless-stopped; logs Docker stdout/stderr; generated span/log numeric aliases stored in Sentry; independently healthy after the same-service upgrade from Usage-Monitor PR #1874; original durable volume and configuration preserved; ambiguous acknowledgements are held for reconciliation.
- Collector Sentry bridge: Server collector installation: 55 files at ca19ad6; Mac: 54 files at ca19ad6 plus the Muse file at 7424ae0; both hosts verified installed/imported; all four CLI sources configured for authenticated hub delivery; Mac jobs reloaded with guarded config readbacks; delivery uses the existing four CLI collector schedules; independent durable delivery inside existing invocations; no additional daemon. Muse source 7424ae0 is installed but remains unloaded under the injector hold; no Muse job is loaded.
- scripts/prune-collector-sentry-outbox.mjs: On-demand only; bounded receipt pruning requires a verified checkpoint and preserves pending or quarantined records.
- scripts/retry-collector-sentry-outbox.mjs: On-demand only; retries explicitly selected quarantined records after correction.
- botfleet-session-collector.mjs: Mac and server active; Sentry-only BotFleet turn aggregates; explicit 24-hour lookback; every 900 seconds; Mac label com.jays.botfleet-session-collector using /opt/homebrew/bin/node; server user cron uses existing run-server-collector.sh; logs ~/Library/Logs/botfleet-session-collector.log on Mac and ~/.local/state/usage-monitor/botfleet-native.log on server; registered before enable; first Mac pass delivered and stored 152 authentic turn spans with zero pending or quarantined; The earlier Linux native audit found no ordinary activity; one generated failed functional-test turn delivered and stored without fabricated usage. The standalone OpenCode source is unchanged. The permanent server child sources are verified: the OpenCode database is /mnt/fleet-extra/apps/botfleet-server/home/.local/share/opencode/opencode.db and the workspace root is /mnt/fleet-extra/apps/botfleet-server/data/workspaces; all eight retained child events are classified BotFleet.
- UM-1646 Sentry Receipt Audit: Task-scoped on-demand helper; approved Mac Python read route; stdout aggregate receipt counts only; no scheduler.
\n
\n",
+ "sectionBefore": "\n
\n
\n",
+ "title": "⭐️ Background Jobs Master List"
+ },
+ "schema": 1,
+ "session": "01a18e51-51e1-7093-9269-0901397a9ec1",
+ "task": "UM-1646 inventory completion",
+ "writes": false
+}
diff --git a/.um1646-opencode-child-source-plan-v1.superseded.json b/.um1646-opencode-child-source-plan-v1.superseded.json
new file mode 100644
index 00000000..5b3d658b
--- /dev/null
+++ b/.um1646-opencode-child-source-plan-v1.superseded.json
@@ -0,0 +1,6 @@
+{
+ "priorPlan": ".um1646-opencode-child-source-plan.json",
+ "reason": "Earlier planner checked source-key names in the runtime snapshot; this version checks the runtime-key names.",
+ "status": "superseded",
+ "supersededBy": ".um1646-opencode-child-source-plan-v2.json"
+}
diff --git a/.um1646-opencode-child-source-plan-v2.json b/.um1646-opencode-child-source-plan-v2.json
new file mode 100644
index 00000000..48186154
--- /dev/null
+++ b/.um1646-opencode-child-source-plan-v2.json
@@ -0,0 +1,55 @@
+{
+ "applyAvailable": false,
+ "bindings": [
+ {
+ "currentState": "absent",
+ "currentValueSha256": null,
+ "desiredValueSha256": "c3f9990ffa4c45c50c16fad923e748412451e4dbb0af64e835635d22b2b715f2",
+ "runtimeKey": "OPENCODE_ADDITIONAL_DBS_JSON",
+ "sourceKey": "OPENCODE_SERVER_ADDITIONAL_DBS_JSON"
+ },
+ {
+ "currentState": "absent",
+ "currentValueSha256": null,
+ "desiredValueSha256": "f5099a13db2d688fadbb916ae270f1b0ed6a758b8b05dc99fa8f4601550bf77e",
+ "runtimeKey": "BOTFLEET_WORKSPACES_DIRS",
+ "sourceKey": "BOTFLEET_SERVER_WORKSPACES_DIRS"
+ }
+ ],
+ "collectorGuard": {
+ "botfleetRuntimeKey": "BOTFLEET_WORKSPACES_DIRS",
+ "opencodeRuntimeKey": "OPENCODE_ADDITIONAL_DBS_JSON",
+ "reviewedCommit": "ca19ad6ab8e98b5ac506d75d15b72dd0b9cd9015",
+ "runtimeInstallationRechecked": false
+ },
+ "configurationMutation": false,
+ "credentialAccess": false,
+ "currentStateEvidence": "local runtime snapshot only; Infisical remains unverified",
+ "destination": {
+ "compareAndSwap": {
+ "keys": [
+ "OPENCODE_SERVER_ADDITIONAL_DBS_JSON",
+ "BOTFLEET_SERVER_WORKSPACES_DIRS"
+ ],
+ "mustBeAbsentBeforeWrite": true,
+ "required": true
+ },
+ "currentState": "not-verified-from-Infisical",
+ "environment": "prod",
+ "secretPath": "/telemetry"
+ },
+ "mode": "plan-only",
+ "schema": "usage-monitor-collector-config-plan-v1",
+ "source": {
+ "kind": "approved-local-runtime-snapshot",
+ "modeOctal": "0600",
+ "nofollowOpen": true,
+ "ownerMatchesCurrentUser": true,
+ "regularFile": true,
+ "sourceSha256": "7e7f8408962c84ca3925536a6da5f3cffe2a49615b23bc0c25592964c17792de",
+ "stableDuringRead": true
+ },
+ "sourceOfTruthRoute": "HELD_NOT_IMPLEMENTED",
+ "supersedes": ".um1646-opencode-child-source-plan.json",
+ "supersedesReason": "Earlier planner checked source-key names in the runtime snapshot; this version checks the runtime-key names."
+}
diff --git a/.um1646-opencode-child-source-plan.json b/.um1646-opencode-child-source-plan.json
new file mode 100644
index 00000000..4fe356bd
--- /dev/null
+++ b/.um1646-opencode-child-source-plan.json
@@ -0,0 +1,53 @@
+{
+ "applyAvailable": false,
+ "bindings": [
+ {
+ "currentState": "absent",
+ "currentValueSha256": null,
+ "desiredValueSha256": "c3f9990ffa4c45c50c16fad923e748412451e4dbb0af64e835635d22b2b715f2",
+ "runtimeKey": "OPENCODE_ADDITIONAL_DBS_JSON",
+ "sourceKey": "OPENCODE_SERVER_ADDITIONAL_DBS_JSON"
+ },
+ {
+ "currentState": "absent",
+ "currentValueSha256": null,
+ "desiredValueSha256": "f5099a13db2d688fadbb916ae270f1b0ed6a758b8b05dc99fa8f4601550bf77e",
+ "runtimeKey": "BOTFLEET_WORKSPACES_DIRS",
+ "sourceKey": "BOTFLEET_SERVER_WORKSPACES_DIRS"
+ }
+ ],
+ "collectorGuard": {
+ "botfleetRuntimeKey": "BOTFLEET_WORKSPACES_DIRS",
+ "opencodeRuntimeKey": "OPENCODE_ADDITIONAL_DBS_JSON",
+ "reviewedCommit": "ca19ad6ab8e98b5ac506d75d15b72dd0b9cd9015",
+ "runtimeInstallationRechecked": false
+ },
+ "configurationMutation": false,
+ "credentialAccess": false,
+ "currentStateEvidence": "local runtime snapshot only; Infisical remains unverified",
+ "destination": {
+ "compareAndSwap": {
+ "keys": [
+ "OPENCODE_ADDITIONAL_DBS_JSON",
+ "BOTFLEET_WORKSPACES_DIRS"
+ ],
+ "mustBeAbsentBeforeWrite": true,
+ "required": true
+ },
+ "currentState": "not-verified-from-Infisical",
+ "environment": "prod",
+ "secretPath": "/telemetry"
+ },
+ "mode": "plan-only",
+ "schema": "usage-monitor-collector-config-plan-v1",
+ "source": {
+ "kind": "approved-local-runtime-snapshot",
+ "modeOctal": "0600",
+ "nofollowOpen": true,
+ "ownerMatchesCurrentUser": true,
+ "regularFile": true,
+ "sourceSha256": "7e7f8408962c84ca3925536a6da5f3cffe2a49615b23bc0c25592964c17792de",
+ "stableDuringRead": true
+ },
+ "sourceOfTruthRoute": "HELD_NOT_IMPLEMENTED"
+}
diff --git a/.um1646-opencode-config-plan.json b/.um1646-opencode-config-plan.json
new file mode 100644
index 00000000..36454737
--- /dev/null
+++ b/.um1646-opencode-config-plan.json
@@ -0,0 +1,9 @@
+{
+ "additionalDatabaseCount": 1,
+ "alreadyConfigured": false,
+ "primarySourcePreserved": true,
+ "setting": "OPENCODE_ADDITIONAL_DBS_JSON",
+ "sourceOfTruthKey": "OPENCODE_SERVER_ADDITIONAL_DBS_JSON",
+ "sourceSha256": "7e7f8408962c84ca3925536a6da5f3cffe2a49615b23bc0c25592964c17792de",
+ "valueSha256": "c3f9990ffa4c45c50c16fad923e748412451e4dbb0af64e835635d22b2b715f2"
+}
diff --git a/.um1646-relay-publication-receipt.json b/.um1646-relay-publication-receipt.json
new file mode 100644
index 00000000..9388bc58
--- /dev/null
+++ b/.um1646-relay-publication-receipt.json
@@ -0,0 +1 @@
+{"result": {"content": [{"type": "text", "text": "{\"branch\":\"codex/um-1646-completion-audit\",\"commit\":\"fab3a4fc2b15dedf3faf9b17b695883eeb2bf746\",\"files\":2}"}], "structuredContent": {"branch": "codex/um-1646-completion-audit", "commit": "fab3a4fc2b15dedf3faf9b17b695883eeb2bf746", "files": 2}}, "jsonrpc": "2.0", "id": 2}
\ No newline at end of file
diff --git a/.um1651-empty-sentry-ack-receipt.json b/.um1651-empty-sentry-ack-receipt.json
new file mode 100644
index 00000000..93b3e31a
--- /dev/null
+++ b/.um1651-empty-sentry-ack-receipt.json
@@ -0,0 +1 @@
+{"existingCustody": true, "envelopesContainNoEvents": true, "outputs": [{"signal": "logs", "submittedEvents": 0, "status": 200, "contentType": "application/json", "responseBytes": 2, "empty": false, "jsonObject": true, "emptyJsonObject": true, "partialSuccessPresent": false}, {"signal": "traces", "submittedEvents": 0, "status": 200, "contentType": "application/json", "responseBytes": 2, "empty": false, "jsonObject": true, "emptyJsonObject": true, "partialSuccessPresent": false}]}
\ No newline at end of file
diff --git a/.um1651-final-runtime-verification.json b/.um1651-final-runtime-verification.json
new file mode 100644
index 00000000..bc27d164
--- /dev/null
+++ b/.um1651-final-runtime-verification.json
@@ -0,0 +1 @@
+{"configSha256":"4de53644a6cfc8bc79af1c2f7da1b6b52c1db19fbd8bc806920e30ce6b671579","configUnchanged":true,"containerId":"420311a137b2","healthy":true,"imageId":"sha256:ebb8ef80a94380e00003db983f02768432a907338dc0d56d55fa863f6d8d3cca","intentPresent":false,"noPublishedPorts":true,"phase":"independent-final-runtime-verification","planSha256":"7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0","privateHostListener":true,"privateTrackingUpdated":true,"readonlyRootAndConfig":true,"sameDurableVolume":true,"sameService":true,"sentCounts":{"sentry":10000},"sentryPendingBytes":0,"sourceCommit":"0a92fcfa39f5b576f498dabc43963c89c47b3713","uid10001":true}
diff --git a/.um1651-gh-commit-body.json b/.um1651-gh-commit-body.json
new file mode 100644
index 00000000..a9721841
--- /dev/null
+++ b/.um1651-gh-commit-body.json
@@ -0,0 +1 @@
+{"message": "Merge Main And Preserve Both Collector Runtime Gates", "tree": "b0effe5d5afb89f68a7f382a1e92bdccf85b95e1", "parents": ["d5441d9b500d553f096d8beac9c9340e4aaf38b7", "5c218189851cbc44dfc7271e3879cda8b481d446"], "author": {"name": "Codex", "email": "344783151+swu-codex[bot]@users.noreply.github.com"}, "committer": {"name": "Codex", "email": "344783151+swu-codex[bot]@users.noreply.github.com"}}
\ No newline at end of file
diff --git a/.um1651-gh-merge-receipt.json b/.um1651-gh-merge-receipt.json
new file mode 100644
index 00000000..0225d196
--- /dev/null
+++ b/.um1651-gh-merge-receipt.json
@@ -0,0 +1 @@
+{"phase": "branchUpdated", "expectedOldHead": "d5441d9b500d553f096d8beac9c9340e4aaf38b7", "mainParent": "5c218189851cbc44dfc7271e3879cda8b481d446", "localHead": "276ba0e955b255a445282a44072b22af0e50c6d6", "expectedTree": "b0effe5d5afb89f68a7f382a1e92bdccf85b95e1", "tree": "b0effe5d5afb89f68a7f382a1e92bdccf85b95e1", "commit": "f9c75027e85dab5f9983cbe119128acaad2baf13"}
\ No newline at end of file
diff --git a/.um1651-gh-ref-body.json b/.um1651-gh-ref-body.json
new file mode 100644
index 00000000..e0d87e22
--- /dev/null
+++ b/.um1651-gh-ref-body.json
@@ -0,0 +1 @@
+{"sha": "f9c75027e85dab5f9983cbe119128acaad2baf13", "force": false}
\ No newline at end of file
diff --git a/.um1651-gh-tree-body.json b/.um1651-gh-tree-body.json
new file mode 100644
index 00000000..d54ae9fc
--- /dev/null
+++ b/.um1651-gh-tree-body.json
@@ -0,0 +1 @@
+{"base_tree": "8b791f9e36c677937c07a176c473dfa9321546bc", "tree": [{"path": "package.json", "mode": "100644", "type": "blob", "content": "{\n \"name\": \"api-usage-monitor\",\n \"description\": \"Tracks API usage and cost via poller snapshots, pushed telemetry, and OTLP metrics. Production: usage.jays.services\",\n \"homepage\": \"https://usage.jays.services\",\n \"version\": \"0.1.0\",\n \"license\": \"Apache-2.0\",\n \"private\": true,\n \"engines\": {\n \"node\": \">=24.14.0 <25\"\n },\n \"scripts\": {\n \"dev\": \"next dev\",\n \"build\": \"next build\",\n \"start\": \"next start\",\n \"lint\": \"eslint .\",\n \"typecheck\": \"tsc --noEmit\",\n \"postinstall\": \"prisma generate\",\n \"db:push\": \"prisma db push\",\n \"db:studio\": \"prisma studio\",\n \"repair:claude-cost\": \"node scripts/repair-claude-cumulative-cost.mjs\",\n \"pricing:update\": \"node scripts/update-model-pricing.mjs\",\n \"pricing:audit\": \"node scripts/audit-model-pricing.mjs\",\n \"repair:anthropic-funding\": \"node scripts/repair-anthropic-funding.mjs\",\n \"add:cursor-subscription\": \"node scripts/add-cursor-subscription.mjs\",\n \"antigravity:collect\": \"node scripts/antigravity-usage-collector.mjs\",\n \"antigravity-session:collect\": \"node scripts/antigravity-session-collector.mjs\",\n \"fleet:collect\": \"node scripts/fleet-usage-collector.mjs\",\n \"codex:collect\": \"node scripts/codex-usage-collector.mjs\",\n \"grok:collect\": \"node scripts/grok-usage-collector.mjs\",\n \"subscription-quota:collect\": \"node scripts/subscription-quota-collector.mjs\",\n \"copilot:collect\": \"node scripts/copilot-usage-collector.mjs\",\n \"deepseek:collect\": \"node scripts/deepseek-usage-collector.mjs\",\n \"minimax:collect\": \"node scripts/minimax-usage-collector.mjs\",\n \"opencode:collect\": \"node scripts/opencode-usage-collector.mjs\",\n \"fx:collect\": \"node scripts/fx-usage-collector.mjs\",\n \"kimi:collect\": \"node scripts/kimi-usage-collector.mjs\",\n \"zcode:collect\": \"node scripts/zcode-usage-collector.mjs\",\n \"import:receipt-screenshots\": \"node scripts/add-user-billing-receipts.mjs\",\n \"import:billing-receipts\": \"node scripts/import-private-billing-receipts.mjs\",\n \"receipt-inbox:verify-lifecycle\": \"node scripts/verify-receipt-inbox-lifecycle.mjs\",\n \"receipt-inbox:deploy-auditor\": \"npm run receipt-inbox:verify-lifecycle && wrangler deploy --config workers/receipt-lifecycle-auditor/wrangler.jsonc\",\n \"receipt-inbox:deploy\": \"npm run receipt-inbox:deploy-auditor && wrangler deploy --config workers/receipt-inbox/wrangler.jsonc\",\n \"receipt-inbox:rules\": \"wrangler email routing rules list jays.services\",\n \"import:subscription-adjustments\": \"node scripts/import-manual-subscription-events.mjs\",\n \"audit:subscription-currency\": \"node scripts/audit-subscription-currency.mjs\",\n \"migrate:provider-secrets\": \"node scripts/migrate-provider-config-secrets.mjs\",\n \"audit:provider-duplicates\": \"node scripts/audit-provider-duplicates.mjs\",\n \"audit:subscription-links\": \"node scripts/audit-subscription-links.mjs\",\n \"ensure:subscription-link-index\": \"node scripts/ensure-subscription-link-unique-index.mjs\",\n \"test\": \"vitest run && npm run test:infisical-fetch && npm run test:alert-timestamps\",\n \"test:coverage\": \"vitest run --coverage && npm run test:infisical-fetch && npm run test:alert-timestamps\",\n \"test:infisical-fetch\": \"node --test scripts/infisical-fetch.node-test.mjs scripts/infisical-fetch-expand.node-test.mjs scripts/infisical-run.node-test.mjs\",\n \"test:alert-timestamps\": \"node --test scripts/normalize-alert-timestamps.node-test.mjs\",\n \"test:receipt-inbox-worker\": \"vitest run --config workers/receipt-inbox/vitest.config.mjs\",\n \"test:migrate-safe\": \"node scripts/test-migrate-safe-repro.mjs\",\n \"test:sqlite-backup\": \"node scripts/test-sqlite-pre-migration-backup.mjs\",\n \"test:backup-concurrent-startup\": \"node --test scripts/test-backup-concurrent-startup.mjs scripts/__tests__/sqlite-pre-migration-backup-cleanup.test.mjs\",\n \"test:backup-staged-errors\": \"node scripts/test-backup-staged-errors.mjs\",\n \"test:r2-archive\": \"node scripts/test-r2-weekly-archive.mjs\",\n \"test:startup-config\": \"node scripts/test-startup-config.mjs\",\n \"test:node-runtime\": \"node scripts/check-node-runtime-parity.mjs\",\n \"test:oracle-deploy\": \"node scripts/test-oracle-deploy-config.mjs\",\n \"test:apple-projects\": \"bash scripts/verify-apple-projects.sh\",\n \"test:antigravity-collector\": \"node scripts/test-antigravity-collector.mjs\",\n \"test:session-token-collectors\": \"node scripts/test-session-token-collectors.mjs\",\n \"test:collector-runtime\": \"node scripts/test-local-collector-runtime.mjs && node --test scripts/__tests__/opencode-profiles.node-test.mjs scripts/sentry-partial-ack.node-test.mjs && vitest run --config scripts/vitest.collectors.config.mjs\",\n \"test:cf-token-map\": \"bash scripts/test-cf-token-map.sh\",\n \"test:replica-status-probe\": \"bash scripts/test-replica-status-probe.sh\",\n \"test:quota-wrapper\": \"bash scripts/test-subscription-quota-wrapper.sh\",\n \"test:e2e-visual-snapshot-files\": \"node scripts/test-e2e-visual-snapshot-files.mjs\",\n \"test:audit-ci\": \"node scripts/test-audit-ci.mjs\",\n \"test:sentry-ci-report\": \"python3 scripts/test-sentry-ci-report.py\",\n \"verify\": \"npm run test:node-runtime && npm run test:sentry-ci-report && npm run lint && npm run typecheck && npm test && npm run test:receipt-inbox-worker && npm run test:migrate-safe && npm run test:sqlite-backup && npm run test:backup-concurrent-startup && npm run test:r2-archive && npm run test:startup-config && npm run test:oracle-deploy && npm run test:apple-projects && npm run test:antigravity-collector && npm run test:session-token-collectors && npm run test:collector-runtime && npm run test:cf-token-map && npm run test:replica-status-probe && npm run test:quota-wrapper && npm run test:audit-ci && npm run build\"\n },\n \"dependencies\": {\n \"@datadog/browser-logs\": \"^7.15.0\",\n \"@datadog/browser-rum\": \"^7.9.0\",\n \"@jaywedgeworth22/congress-trading-shared\": \"github:Simple-With-Us/congress-trading-shared#v2.9.0\",\n \"@prisma/adapter-better-sqlite3\": \"^7.0.0\",\n \"@prisma/client\": \"^7.0.0\",\n \"better-sqlite3\": \"^13.0.0\",\n \"@sentry/nextjs\": \"^11.3.0\",\n \"dd-trace\": \"^6.19.0\",\n \"lucide-react\": \"^1.50.0\",\n \"next\": \"16.4.3\",\n \"next-themes\": \"^0.4.6\",\n \"postal-mime\": \"^4.0.8\",\n \"protobufjs\": \"^8.8.0\",\n \"react\": \"^19.3.0\",\n \"react-dom\": \"^19.3.0\",\n \"react-is\": \"^19.3.0\",\n \"recharts\": \"^3.10.1\",\n \"zod\": \"^4.6.6\"\n },\n \"devDependencies\": {\n \"@cloudflare/vitest-plugin\": \"^1.4.7\",\n \"@eslint/eslintrc\": \"^3.3.7\",\n \"@playwright/test\": \"^1.62.0\",\n \"@tailwindcss/postcss\": \"^4.3.3\",\n \"@testing-library/dom\": \"^10.4.2\",\n \"@testing-library/react\": \"^16.3.3\",\n \"@types/node\": \"^26.6.4\",\n \"@types/react\": \"^19.3.0\",\n \"@types/react-dom\": \"^19.3.0\",\n \"@vitest/coverage-v8\": \"^5.0.0\",\n \"audit-ci\": \"^7.1.0\",\n \"autoprefixer\": \"^10.6.1\",\n \"browserslist\": \"^4.29.3\",\n \"dotenv\": \"^18.0.5\",\n \"eslint\": \"^10.0.0\",\n \"eslint-config-next\": \"^16.3.8\",\n \"jsdom\": \"^30.1.1\",\n \"postcss\": \"^8.5.18\",\n \"prisma\": \"^7.0.0\",\n \"@typescript/native\": \"npm:typescript@^7.0.0\",\n \"tailwindcss\": \"^4.3.3\",\n \"typescript\": \"^6.0.3\",\n \"vitest\": \"^5.0.0\",\n \"wrangler\": \"4.155.0\"\n },\n \"overrides\": {\n \"minimatch\": \"^11.0.0\",\n \"postcss\": \"$postcss\",\n \"sharp\": \"0.35.5\",\n \"undici\": \"^8.12.2\",\n \"js-yaml\": \"^5.4.1\",\n \"deepmerge-ts\": \"^8.0.0\",\n \"brace-expansion\": \"^5.0.12\",\n \"braces\": \"^3.0.3\",\n \"source-map-js\": \"1.2.2\",\n \"@cloudflare/vitest-plugin\": {\n \"zod\": \"^4.6.6\"\n },\n \"c12\": {\n \"magicast\": \"^0.5.2\"\n }\n }\n}\n"}, {"path": "scripts/telemetry-hub/journal.mjs", "mode": "100644", "type": "blob", "content": "// The append-only journal and the per-destination read offsets.\n//\n// The journal is the hub's audit trail. It holds the CONTENT, so it is a\n// local file, and it is readable only by the user: the state directory is\n// created with mode 700 and every file in it with mode 600.\n//\n// One JSON object per line, fsynced on write. A crash can lose the tail of\n// the file, never reorder it and never interleave two lines.\n//\n// Each destination (the UM turn channel, the UM ledger channel and Sentry)\n// keeps its OWN read offset and its OWN set of already-sent event ids, in\n// separate small state files. A destination that is down therefore never\n// holds the other one back.\n//\n// The offset advances ONLY after a successful delivery. A crash between\n// \"delivered\" and \"offset advanced\" would resend, so every sender also\n// checks the sent set before it sends. Sentry does not dedupe OTLP logs,\n// which is why that check is not optional.\n//\n// The offset is an ABSOLUTE byte position in the logical journal stream.\n// The file on disk only holds the part of the stream that is not consumed\n// yet: once the file grows past MAX_JOURNAL_BYTES, the prefix that every\n// destination has already read is dropped and the base of the file moves\n// forward. The offsets themselves never change, so a compaction can\n// neither lose nor replay an event. The prefix that is dropped is a whole\n// number of lines, because every offset sits on a line boundary.\n//\n// Every persisted state file and every journal row is validated with Zod\n// before it is used. A malformed state file is rejected instead of being\n// half believed, and a malformed row is dropped instead of reaching a\n// sender with an invalid identity.\n//\n// Zod is a runtime dependency of this repository. The hub therefore has one\n// third-party import, and it is on the parsing boundary, where an explicit\n// runtime shape guard belongs.\n\nimport { constants as fsConstants } from \"node:fs\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { chmod, link, mkdir, open, readFile, rename, stat, unlink, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { StringDecoder } from \"node:string_decoder\";\nimport { z } from \"zod\";\n\nimport { NULL_LOGGER } from \"./internal-event.mjs\";\nimport { rebuildLogBody, scalarFromAnyValue, scrubOtlpAttributes } from \"./allowlist.mjs\";\n\nconst DIR_MODE = 0o700;\nconst FILE_MODE = 0o600;\n\n/** How many already-sent event ids one destination remembers. */\nexport const MAX_SENT_IDS = 10_000;\n\n/** The journal file is compacted once it grows past this size. */\nexport const MAX_JOURNAL_BYTES = 32 * 1024 * 1024;\n\n/** Read chunk size when scanning the journal. */\nconst READ_CHUNK_BYTES = 256 * 1024;\n\n/** The file that records where the journal file starts in the stream. */\nconst BASE_FILE = \"journal.base.json\";\nconst SENTRY_REQUEST_FILE = \"sentry-request.json\";\nexport const MAX_SENTRY_REQUEST_BYTES = 2 * 1024 * 1024;\nconst SentryResponseClass = z.enum([\"partial_success\", \"malformed_ack\", \"oversized_ack\", \"unreadable_ack\", \"unexpected_content_type\"]);\nconst SentryWireEventSchema = z.strictObject({\n eventId: z.string().min(1).max(256), ts: z.string().max(64), kind: z.enum([\"span\", \"log\"]),\n name: z.string().max(160), attributes: z.array(z.unknown()).max(64),\n durationMs: z.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER).optional(),\n body: z.strictObject({ stringValue: z.string() }).optional(),\n severityNumber: z.union([z.literal(9), z.literal(17)]).optional(),\n status: z.strictObject({ code: z.union([z.literal(1), z.literal(2)]) }).optional(),\n});\nconst SentryRequestSchema = z.strictObject({\n version: z.literal(1), destination: z.literal(\"sentry\"), signal: z.enum([\"logs\", \"traces\"]),\n batchDigest: z.string().regex(/^[a-f0-9]{64}$/), phase: z.enum([\"prepared\", \"held\"]),\n eventIds: z.array(z.string().min(1).max(256)).min(1).max(1000),\n events: z.array(SentryWireEventSchema).min(1).max(1000),\n responseClass: SentryResponseClass.optional(), rejectedCount: z.number().int().nonnegative().max(1000).optional(),\n httpStatus: z.number().int().min(200).max(299).optional(),\n});\n\nfunction sentryRequestEvents(events, signal) {\n if (!Array.isArray(events) || !events.length || events.length > (signal === \"logs\" ? 100 : 1000)) throw new Error(\"Invalid Sentry request size\");\n return events.map((event) => {\n const eventId = eventIdOf(event);\n if (!eventId || !Number.isFinite(Date.parse(event.ts))) throw new Error(\"Invalid Sentry request identity\");\n const attributes = scrubOtlpAttributes(event.attributes);\n const operation = attributes.find((a) => a.key === \"gen_ai.operation.name\");\n const name = operation ? scalarFromAnyValue(operation.value) : signal === \"logs\" ? \"log\" : \"chat\";\n const safe = { eventId, ts: event.ts, kind: signal === \"logs\" ? \"log\" : \"span\", name: typeof name === \"string\" ? name.slice(0, 160) : \"chat\", attributes };\n if (Number.isFinite(event.durationMs) && event.durationMs >= 0 && event.durationMs <= Number.MAX_SAFE_INTEGER) safe.durationMs = event.durationMs;\n if (signal === \"logs\") {\n safe.body = { stringValue: rebuildLogBody(attributes) };\n safe.severityNumber = event.severityNumber === 17 ? 17 : 9;\n } else safe.status = { code: event.status?.code === 2 ? 2 : 1 };\n return SentryWireEventSchema.parse(safe);\n });\n}\n\nfunction sentryBatchDigest(signal, events) {\n return createHash(\"sha256\").update(JSON.stringify({ signal, events })).digest(\"hex\");\n}\n\n/** The persisted read offset of one destination. */\nconst OffsetStateSchema = z.object({\n offset: z.number().int().nonnegative(),\n});\n\n/** The persisted set of delivered event ids of one destination. */\nconst SentStateSchema = z.object({\n eventIds: z.array(z.string().min(1).max(256)).max(MAX_SENT_IDS),\n});\n\n/**\n * One journal row.\n *\n * The identity fields are required: a row without an event id cannot be\n * deduplicated and a row without a timestamp cannot be ordered. The rest\n * of the row is the internal event, which is passed through as it is.\n */\nconst JournalEventSchema = z.looseObject({\n eventId: z.string().min(1).max(256),\n ts: z.string().min(1).max(64),\n kind: z.enum([\"span\", \"log\"]).optional(),\n platform: z.string().max(200).optional(),\n});\n\n/** The compaction bookkeeping of the journal file. */\nconst BaseStateSchema = z.object({\n base: z.number().int().nonnegative(),\n nextBase: z.number().int().nonnegative(),\n pendingSize: z.number().int().nonnegative(),\n});\n\nfunction isPlainObject(value) {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/**\n * A tiny promise mutex.\n *\n * Two places must not interleave: the appends and the compaction of the\n * journal file, and the writes of the per-destination state files. Each\n * one gets its own mutex.\n */\nfunction createMutex() {\n let tail = Promise.resolve();\n return function run(task) {\n const result = tail.then(task, task);\n tail = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n };\n}\n\n/**\n * The id of an event, when the event carries a valid one.\n *\n * The journal validates every row before a sender can see it, so this is\n * the second guard for a caller that maps ids out of an event.\n */\nexport function eventIdOf(event) {\n const checked = JournalEventSchema.safeParse(event);\n return checked.success ? checked.data.eventId : undefined;\n}\n\n/** A destination name becomes a file name, so it is restricted. */\nexport function normalizeDestination(name) {\n const value = String(name ?? \"\").trim().toLowerCase();\n if (!/^[a-z0-9][a-z0-9_-]{0,39}$/.test(value)) {\n throw new Error(`Invalid destination name: ${String(name).slice(0, 40)}`);\n }\n return value;\n}\n\nexport class Journal {\n /**\n * @param {object} options\n * @param {string} options.dir State directory. Created with mode 700.\n * @param {object} [options.logger]\n * @param {number} [options.maxJournalBytes] The size the journal file\n * passes before the consumed prefix is dropped.\n */\n constructor({ dir, logger = NULL_LOGGER, maxJournalBytes = MAX_JOURNAL_BYTES } = {}) {\n if (typeof dir !== \"string\" || !dir.trim()) throw new Error(\"Journal dir is required\");\n this.dir = dir;\n this.logger = logger;\n this.maxJournalBytes = Number.isSafeInteger(maxJournalBytes) && maxJournalBytes > 0\n ? maxJournalBytes\n : MAX_JOURNAL_BYTES;\n this.journalPath = join(dir, \"journal.jsonl\");\n this.stateDir = join(dir, \"state\");\n this.deadLetterPath = join(dir, \"dead-letter.jsonl\");\n this.handle = undefined;\n this.offsets = new Map();\n this.sentSets = new Map();\n // The absolute byte position of the first retained byte of the file.\n this.base = 0;\n this.fileMutex = createMutex();\n this.stateMutex = createMutex();\n this.writeCounter = 0;\n }\n\n /** Create the directory tree with tight modes and open the journal. */\n async open() {\n await mkdir(this.stateDir, { recursive: true, mode: DIR_MODE });\n await chmod(this.dir, DIR_MODE);\n await chmod(this.stateDir, DIR_MODE);\n await this.recoverBase();\n this.handle = await open(this.journalPath, \"a\", FILE_MODE);\n await this.handle.chmod(FILE_MODE);\n return this;\n }\n\n /**\n * Read the compaction bookkeeping and settle an interrupted compaction.\n *\n * The base file records the base of the file, the base the file WILL have\n * after a compaction, and the size the file had before that compaction.\n * A compaction interrupted after the swap left a file that is smaller\n * than the recorded size, so the new base is the right one. A compaction\n * interrupted before the swap left the file untouched, so the old base is\n * the right one.\n */\n async recoverBase() {\n const state = await this.readBaseFile();\n let base = 0;\n if (state) {\n if (state.pendingSize > 0) {\n const size = await this.fileSize();\n base = size < state.pendingSize ? state.nextBase : state.base;\n } else {\n base = state.base;\n }\n }\n this.base = base;\n await this.writeBaseFile({ base, nextBase: base, pendingSize: 0 });\n return base;\n }\n\n async readBaseFile() {\n try {\n const raw = await readFile(join(this.stateDir, BASE_FILE), \"utf8\");\n const parsed = BaseStateSchema.safeParse(JSON.parse(raw));\n if (!parsed.success) {\n this.logger.warn(\"the journal base state is not usable\", { file: BASE_FILE });\n return null;\n }\n return parsed.data;\n } catch {\n return null;\n }\n }\n\n async writeBaseFile(state) {\n await this.writeStateFile(BASE_FILE, state);\n }\n\n /** Load the persisted offsets and sent sets for the known destinations. */\n async loadDestinations(destinations) {\n for (const raw of destinations) {\n const destination = normalizeDestination(raw);\n if (this.offsets.has(destination)) continue;\n this.offsets.set(destination, await this.readOffsetFile(destination));\n this.sentSets.set(destination, await this.readSentFile(destination));\n }\n }\n\n async readOffsetFile(destination) {\n try {\n const raw = await readFile(join(this.stateDir, `${destination}.offset.json`), \"utf8\");\n const parsed = OffsetStateSchema.safeParse(JSON.parse(raw));\n if (!parsed.success) {\n this.logger.warn(\"the offset state is not usable\", { destination });\n return 0;\n }\n return parsed.data.offset;\n } catch {\n return 0;\n }\n }\n\n async readSentFile(destination) {\n try {\n const raw = await readFile(join(this.stateDir, `${destination}.sent.json`), \"utf8\");\n const parsed = SentStateSchema.safeParse(JSON.parse(raw));\n if (!parsed.success) {\n this.logger.warn(\"the sent state is not usable\", { destination });\n return new Set();\n }\n return new Set(parsed.data.eventIds);\n } catch {\n return new Set();\n }\n }\n\n /**\n * Append one internal event and fsync it.\n *\n * The line is serialized with JSON.stringify, so a newline inside a value\n * can never split the record across two lines.\n */\n async append(event) {\n return this.appendBatch([event]);\n }\n\n /**\n * Append a batch of internal events with ONE write and ONE fsync.\n *\n * A receiver request can carry a hundred events. Flushing once per event\n * turns one request into a hundred disk flushes and delays the response,\n * which invites the producer to retry and duplicate the spans.\n */\n async appendBatch(events) {\n const list = Array.isArray(events) ? events : [];\n if (list.length === 0) return 0;\n for (const event of list) {\n if (!isPlainObject(event)) throw new Error(\"Journal append needs an object\");\n }\n const body = `${list.map((event) => JSON.stringify(event)).join(\"\\n\")}\\n`;\n const bytes = Buffer.byteLength(body, \"utf8\");\n await this.fileMutex(async () => {\n if (!this.handle) throw new Error(\"Journal is not open\");\n await this.handle.write(body, null, \"utf8\");\n await this.handle.sync();\n });\n await this.maybeCompact();\n return bytes;\n }\n\n /** The current read offset of one destination. */\n getOffset(destination) {\n const key = normalizeDestination(destination);\n return this.offsets.get(key) ?? 0;\n }\n\n /** Persist the read offset of one destination. */\n async setOffset(destination, offset) {\n const key = normalizeDestination(destination);\n if (!Number.isSafeInteger(offset) || offset < 0) throw new Error(\"Offset must be a non-negative integer\");\n await this.stateMutex(async () => {\n await this.writeStateFile(`${key}.offset.json`, { offset });\n this.offsets.set(key, offset);\n });\n await this.maybeCompact();\n }\n\n /** True when this destination already delivered the event. */\n isSent(destination, eventId) {\n const key = normalizeDestination(destination);\n if (typeof eventId !== \"string\" || !eventId) return false;\n return (this.sentSets.get(key) ?? new Set()).has(eventId);\n }\n\n /** Record that this destination delivered the event. */\n async markSent(destination, eventId) {\n const key = normalizeDestination(destination);\n if (typeof eventId !== \"string\" || !eventId) return;\n await this.stateMutex(async () => {\n const set = new Set(this.sentSet(key));\n if (set.has(eventId)) return;\n set.add(eventId);\n this.trimSentSet(set);\n await this.writeStateFile(`${key}.sent.json`, { eventIds: [...set] });\n this.sentSets.set(key, set);\n });\n }\n\n /** Record a batch of delivered event ids. */\n async markSentBatch(destination, eventIds) {\n const key = normalizeDestination(destination);\n await this.stateMutex(async () => {\n const set = new Set(this.sentSet(key));\n let changed = false;\n for (const eventId of eventIds) {\n if (typeof eventId !== \"string\" || !eventId || set.has(eventId)) continue;\n set.add(eventId);\n changed = true;\n }\n this.trimSentSet(set);\n if (changed) {\n await this.writeStateFile(`${key}.sent.json`, { eventIds: [...set] });\n this.sentSets.set(key, set);\n }\n });\n }\n\n sentSet(key) {\n let set = this.sentSets.get(key);\n if (!set) {\n set = new Set();\n this.sentSets.set(key, set);\n }\n return set;\n }\n\n trimSentSet(set) {\n while (set.size > MAX_SENT_IDS) {\n const oldest = set.values().next().value;\n set.delete(oldest);\n }\n }\n\n /**\n * Write one state file.\n *\n * The temporary path is unique per write, so two concurrent writes can\n * never truncate the same temporary file, and the rename that publishes\n * the file is atomic.\n */\n async writeStateFile(fileName, payload, { exclusive = false } = {}) {\n const target = join(this.stateDir, fileName);\n const temporary = this.tempPath(target);\n const body = `${JSON.stringify(payload)}\\n`;\n try {\n const file = await open(temporary, \"wx\", FILE_MODE);\n try {\n await file.writeFile(body);\n await this.syncStateFile(file);\n } finally { await file.close(); }\n if (exclusive) await link(temporary, target);\n else await rename(temporary, target);\n await chmod(target, FILE_MODE);\n await this.syncStateDirectory();\n } finally { await unlink(temporary).catch((error) => { if (error.code !== \"ENOENT\") throw error; }); }\n }\n\n async syncStateFile(file) { await file.sync(); }\n\n async syncStateDirectory() {\n const directory = await open(this.stateDir, \"r\");\n try { await directory.sync(); } finally { await directory.close(); }\n }\n\n /** An unresolved pre-POST intent is a channel hold, including after a restart. */\n async readSentryRequest() {\n let file;\n try { file = await open(join(this.stateDir, SENTRY_REQUEST_FILE), fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW); }\n catch (error) { if (error.code === \"ENOENT\") return null; throw error; }\n let bytes;\n try {\n const info = await file.stat();\n if (!info.isFile() || info.size > MAX_SENTRY_REQUEST_BYTES) throw new Error(\"Invalid Sentry request state\");\n bytes = await file.readFile(\"utf8\");\n } finally { await file.close(); }\n const request = SentryRequestSchema.parse(JSON.parse(bytes));\n const events = sentryRequestEvents(request.events, request.signal);\n if (JSON.stringify(events) !== JSON.stringify(request.events) || sentryBatchDigest(request.signal, events) !== request.batchDigest || JSON.stringify(events.map((e) => e.eventId)) !== JSON.stringify(request.eventIds) || new Set(request.eventIds).size !== events.length || (request.rejectedCount ?? 0) > events.length) throw new Error(\"Invalid Sentry request state\");\n return request;\n }\n\n async prepareSentryRequest(signal, events) {\n if (![\"logs\", \"traces\"].includes(signal)) throw new Error(\"Invalid Sentry signal\");\n return this.stateMutex(async () => {\n if (await this.readSentryRequest()) throw new Error(\"Unresolved Sentry request retained\");\n const safe = sentryRequestEvents(events, signal);\n const request = SentryRequestSchema.parse({ version: 1, destination: \"sentry\", signal, phase: \"prepared\", batchDigest: sentryBatchDigest(signal, safe), events: safe, eventIds: safe.map((e) => e.eventId) });\n if (new Set(request.eventIds).size !== safe.length || Buffer.byteLength(JSON.stringify(request)) > MAX_SENTRY_REQUEST_BYTES) throw new Error(\"Invalid Sentry request bounds\");\n await this.writeStateFile(SENTRY_REQUEST_FILE, request, { exclusive: true });\n return request;\n });\n }\n\n async holdSentryRequest(batchDigest, { responseClass, rejectedCount, httpStatus }) {\n return this.stateMutex(async () => {\n const request = await this.readSentryRequest();\n if (!request || request.batchDigest !== batchDigest) throw new Error(\"Sentry request identity changed\");\n const held = SentryRequestSchema.parse({ ...request, phase: \"held\", responseClass, httpStatus, ...(rejectedCount === undefined ? {} : { rejectedCount }) });\n if ((rejectedCount ?? 0) > request.events.length || Buffer.byteLength(JSON.stringify(held)) > MAX_SENTRY_REQUEST_BYTES) throw new Error(\"Invalid Sentry hold bounds\");\n await this.writeStateFile(SENTRY_REQUEST_FILE, held);\n return held;\n });\n }\n\n async clearSentryRequest(batchDigest) {\n return this.stateMutex(async () => {\n const request = await this.readSentryRequest();\n if (!request || request.phase !== \"prepared\" || request.batchDigest !== batchDigest) throw new Error(\"Unresolved Sentry request preserved\");\n await unlink(join(this.stateDir, SENTRY_REQUEST_FILE));\n await this.syncStateDirectory();\n });\n }\n\n /** A temporary path that no other write can collide with. */\n tempPath(target) {\n this.writeCounter += 1;\n return `${target}.${process.pid}.${this.writeCounter}.${randomUUID()}.tmp`;\n }\n\n /**\n * Read up to `limit` events for one destination, starting at its offset.\n *\n * Events this destination already sent are skipped, and the returned\n * `endOffset` points past every line that was consumed, so a skipped\n * event never blocks the ones behind it. A repeated event id inside one\n * batch is skipped as well, so one turn is never delivered twice.\n *\n * A partial trailing line (a crash mid-write) is never parsed and never\n * counted, so the offset stays on a line boundary.\n *\n * A row that does not match the journal schema is dropped: it cannot be\n * deduplicated and it must not reach a sender.\n */\n async readBatch(destination, limit) {\n const key = normalizeDestination(destination);\n const start = this.getOffset(key);\n const sent = this.sentSets.get(key) ?? new Set();\n const events = [];\n if (!this.handle && !(await this.exists())) {\n return { events, endOffset: start };\n }\n // The base and the file are taken together, under the file mutex, so\n // a compaction cannot slip between them. A compaction that runs\n // after this point replaces the file, but the handle below still\n // points at the file this read belongs to, so the positions of this\n // read and the base of this read always belong together.\n const opened = await this.fileMutex(async () => {\n const base = this.base;\n const file = await open(this.journalPath, fsConstants.O_RDONLY);\n let size;\n try {\n size = (await file.stat()).size;\n } catch (error) {\n // The handle is only closed by the `finally` below once it has\n // been handed out, so a failure here has to close it itself.\n // Otherwise every read that fails after the open leaks a\n // descriptor until the process runs out of them.\n await file.close();\n throw error;\n }\n return { base, file, size };\n });\n const { base, file, size } = opened;\n try {\n const fileStart = Math.max(0, start - base);\n if (fileStart >= size) return { events, endOffset: start };\n const decoder = new StringDecoder(\"utf8\");\n const buffer = Buffer.alloc(READ_CHUNK_BYTES);\n const seen = new Set();\n let pending = \"\";\n let pendingStart = fileStart;\n let filePos = fileStart;\n let endOffset = start;\n let done = false;\n while (!done && events.length < limit) {\n const remaining = size - filePos;\n if (remaining <= 0) break;\n const want = Math.min(READ_CHUNK_BYTES, remaining);\n const { bytesRead } = await file.read(buffer, 0, want, filePos);\n if (bytesRead <= 0) break;\n filePos += bytesRead;\n pending += decoder.write(buffer.subarray(0, bytesRead));\n for (;;) {\n const newline = pending.indexOf(\"\\n\");\n if (newline === -1) break;\n const line = pending.slice(0, newline);\n const consumed = Buffer.byteLength(line, \"utf8\") + 1;\n pending = pending.slice(newline + 1);\n pendingStart += consumed;\n endOffset = base + pendingStart;\n const trimmed = line.trim();\n if (!trimmed) continue;\n let parsed = null;\n try {\n parsed = JSON.parse(trimmed);\n } catch {\n parsed = null;\n }\n const checked = JournalEventSchema.safeParse(parsed);\n if (!checked.success) continue;\n const event = checked.data;\n if (sent.has(event.eventId)) continue;\n if (seen.has(event.eventId)) continue;\n seen.add(event.eventId);\n events.push(event);\n if (events.length >= limit) break;\n }\n }\n return { events, endOffset };\n } finally {\n await file.close();\n }\n }\n\n async exists() {\n try {\n await stat(this.journalPath);\n return true;\n } catch {\n return false;\n }\n }\n\n /** The size of the journal file on disk. */\n async fileSize() {\n try {\n const info = await stat(this.journalPath);\n return info.size;\n } catch {\n return 0;\n }\n }\n\n /** The smallest offset of every known destination. */\n minimumOffset() {\n if (this.offsets.size === 0) return undefined;\n let min = Infinity;\n for (const offset of this.offsets.values()) {\n if (offset < min) min = offset;\n }\n return Number.isFinite(min) ? min : undefined;\n }\n\n /**\n * Drop the part of the journal every destination has already read.\n *\n * The offsets are absolute, so removing a prefix does not change them:\n * only the base of the file moves. The region that is removed is the\n * part below the smallest offset, so no destination can lose an event it\n * has not read yet. A destination that is down keeps the journal from\n * shrinking, which is the price of not dropping its events.\n */\n async maybeCompact() {\n const target = this.minimumOffset();\n if (target === undefined) return false;\n if (target <= this.base) return false;\n const size = await this.fileSize();\n if (size <= this.maxJournalBytes) return false;\n // The compaction rewrites the whole remaining file, so it is only\n // worth its copy when the consumed prefix is a real part of the file.\n // While the unconsumed backlog is still over the cap the rewrite\n // cannot bring the file under it, so skipping keeps the write\n // amplification at 2x instead of copying the whole file for every\n // byte a slow destination consumes.\n // The skip is NOT unbounded, though: once the consumed prefix is at\n // least half the file the copy pays for itself, so the file still\n // shrinks. That bounds the file at 2x the unconsumed backlog, which\n // is the smallest it can ever be while that backlog is retained.\n const prefix = Math.min(target - this.base, size);\n const remaining = size - prefix;\n if (remaining >= this.maxJournalBytes && prefix * 2 < size) return false;\n await this.compactTo(target);\n return true;\n }\n\n /** Rewrite the journal file without the consumed prefix. */\n async compactTo(target) {\n await this.fileMutex(async () => {\n const size = await this.fileSize();\n const cut = Math.min(target - this.base, size);\n if (cut <= 0) return;\n const temporary = `${this.journalPath}.compact`;\n if (cut >= size) {\n await writeFile(temporary, \"\", { mode: FILE_MODE });\n } else {\n await this.copyRange(this.journalPath, temporary, cut, size);\n }\n // The pending record is written BEFORE the swap, so a crash in\n // between leaves enough information to settle the outcome.\n await this.writeBaseFile({ base: this.base, nextBase: target, pendingSize: size });\n await rename(temporary, this.journalPath);\n await chmod(this.journalPath, FILE_MODE);\n await this.writeBaseFile({ base: target, nextBase: target, pendingSize: 0 });\n this.base = target;\n if (this.handle) {\n await this.handle.close();\n this.handle = undefined;\n }\n this.handle = await open(this.journalPath, \"a\", FILE_MODE);\n await this.handle.chmod(FILE_MODE);\n });\n }\n\n /** Copy a byte range of one file into another file. */\n async copyRange(source, target, from, to) {\n const input = await open(source, fsConstants.O_RDONLY);\n const output = await open(target, \"w\", FILE_MODE);\n try {\n const buffer = Buffer.alloc(READ_CHUNK_BYTES);\n let position = from;\n while (position < to) {\n const want = Math.min(READ_CHUNK_BYTES, to - position);\n const { bytesRead } = await input.read(buffer, 0, want, position);\n if (bytesRead <= 0) break;\n await output.write(buffer.subarray(0, bytesRead), 0, bytesRead, position - from);\n position += bytesRead;\n }\n await output.sync();\n } finally {\n await output.close();\n await input.close();\n }\n }\n\n /**\n * Quarantine one event into the dead-letter file.\n *\n * The record carries the event id, the metric type, the destination and a\n * reason. It carries NO content: no prompt, no response, no tool\n * argument. The journal itself stays the only place content lives.\n */\n async quarantine(destination, event, { reason, status } = {}) {\n const key = normalizeDestination(destination);\n const record = {\n quarantinedAt: new Date().toISOString(),\n destination: key,\n eventId: typeof event?.eventId === \"string\" ? event.eventId : \"\",\n metricType: typeof event?.operation === \"string\" ? event.operation : \"\",\n provider: typeof event?.provider === \"string\" ? event.provider : \"\",\n status: typeof event?.status === \"string\" ? event.status : \"\",\n reason: typeof reason === \"string\" ? reason.slice(0, 200) : \"\",\n httpStatus: Number.isInteger(status) ? status : undefined,\n };\n const line = `${JSON.stringify(record)}\\n`;\n const file = await open(this.deadLetterPath, \"a\", FILE_MODE);\n try {\n await file.write(line, null, \"utf8\");\n await file.sync();\n } finally {\n await file.close();\n }\n return record;\n }\n\n /** Close the journal handle. */\n async close() {\n if (this.handle) {\n await this.handle.close();\n this.handle = undefined;\n }\n }\n}\n"}, {"path": "scripts/telemetry-hub/sentry-sender.mjs", "mode": "100644", "type": "blob", "content": "// The Sentry sender.\n//\n// Sentry gets ONLY counts, durations, the model, the tool names and a\n// status. It never gets the prompt, the response, the tool arguments, the\n// tool results, a file path, a project name, a session id or a raw error\n// message.\n//\n// The scrubber in ./allowlist.mjs is the control. Sentry's own default\n// scrubbing does not protect `gen_ai.input.messages`,\n// `gen_ai.output.messages`, `gen_ai.tool.call.arguments` or\n// `gen_ai.tool.call.result`, and plain OTLP bypasses the SDK PII flags\n// entirely, so the content is removed on this Mac before the packet\n// leaves.\n//\n// Two envelopes go out: `/v1/traces` for the turn events and `/v1/logs` for\n// the log events. Sentry has no OTLP metrics path, so none is attempted.\n//\n// The endpoint is project-specific and region-specific, so it is read from\n// the environment and never hardcoded. The public key is not a secret, but\n// it is still read from the environment.\n\nimport { gzipSync } from \"node:zlib\";\nimport { z } from \"zod\";\n\nimport { scrubInternalEvent } from \"./allowlist.mjs\";\nimport { NULL_LOGGER } from \"./internal-event.mjs\";\nimport { eventIdOf } from \"./journal.mjs\";\n\n/**\n * Success ACKs are byte-bounded and retain only typed rejection counts.\n * Response messages, rejection bodies and headers are never persisted.\n */\nconst AckCount = z.union([z.number(), z.string().max(16).regex(/^(0|[1-9][0-9]*)$/).transform(Number)]).pipe(z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER));\nexport const MAX_SENTRY_ACK_BYTES = 64 * 1024;\n\nasync function readSuccessAck(response, logs, submitted) {\n let text = \"\";\n let reader;\n try {\n if (response.body === undefined) return { responseClass: \"unreadable_ack\" };\n if (response.body) {\n if (typeof response.body.getReader !== \"function\") return { responseClass: \"unreadable_ack\" };\n reader = response.body.getReader();\n const chunks = [];\n let bytes = 0;\n for (;;) {\n const next = await reader.read();\n if (next.done) break;\n bytes += next.value.byteLength;\n if (bytes > MAX_SENTRY_ACK_BYTES) {\n await reader.cancel().catch(() => {});\n return { responseClass: \"oversized_ack\" };\n }\n chunks.push(next.value);\n }\n text = new TextDecoder(\"utf-8\", { fatal: true }).decode(Buffer.concat(chunks));\n }\n } catch { return { responseClass: \"unreadable_ack\" }; }\n finally { reader?.releaseLock(); }\n const contentType = response.headers?.get(\"content-type\")?.split(\";\", 1)[0].trim().toLowerCase();\n const jsonType = !contentType || contentType === \"application/json\" || /^application\\/[a-z0-9.+-]+\\+json$/.test(contentType);\n const emptyProtobuf = !text.trim() && [\"application/x-protobuf\", \"application/protobuf\"].includes(contentType);\n if (!jsonType && !emptyProtobuf) return { responseClass: \"unexpected_content_type\" };\n if (!text.trim()) return { accepted: true };\n const camel = logs ? \"rejectedLogRecords\" : \"rejectedSpans\";\n const snake = logs ? \"rejected_log_records\" : \"rejected_spans\";\n const schema = z.strictObject({\n partialSuccess: z.strictObject({ [camel]: AckCount.optional(), errorMessage: z.string().optional() }).optional(),\n partial_success: z.strictObject({ [snake]: AckCount.optional(), error_message: z.string().optional() }).optional(),\n }).refine((ack) => !(ack.partialSuccess && ack.partial_success));\n let result;\n try { result = schema.safeParse(JSON.parse(text)); } catch { return { responseClass: \"malformed_ack\" }; }\n if (!result.success) return { responseClass: \"malformed_ack\" };\n const partial = result.data.partialSuccess ?? result.data.partial_success;\n const rejected = partial?.[camel] ?? partial?.[snake] ?? 0;\n if (rejected > submitted) return { responseClass: \"malformed_ack\" };\n return rejected > 0 ? { responseClass: \"partial_success\", rejectedCount: rejected } : { accepted: true };\n}\n\n/** The Sentry OTLP envelopes. Sentry does not support OTLP metrics. */\nexport const SENTRY_TRACES_PATH = \"/v1/traces\";\nexport const SENTRY_LOGS_PATH = \"/v1/logs\";\n\n/** Sentry accepts at most 100 log records per envelope. */\nexport const MAX_LOGS_PER_REQUEST = 100;\n\n/** Sentry accepts at most 1000 spans per request. */\nexport const MAX_SPANS_PER_REQUEST = 1000;\n\n/** Keep every request body well under 1 MB, far inside the 12 MiB cap. */\nexport const MAX_BODY_CHARS = 512 * 1024;\n\n/** How many journal events one pass reads before it splits them by kind. */\nexport const DEFAULT_READ_LIMIT = 200;\n\nconst REQUEST_TIMEOUT_MS = 20_000;\nconst MAX_ATTEMPTS = 3;\nconst BASE_BACKOFF_MS = 1_000;\n\n/** The service name Sentry sees. */\nconst SERVICE_NAME = \"telemetry-hub\";\nconst SERVICE_VERSION = \"1\";\n\nfunction isPlainObject(value) {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction sleep(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Classify an HTTP status. Same policy as the UM sender: a validation\n * failure is a poison event, an auth or routing failure is the channel's\n * own problem, and 429/5xx is transient.\n */\nexport function classifyStatus(status) {\n if (status >= 200 && status < 300) return \"ok\";\n if (status === 429 || status >= 500) return \"retry\";\n if (status === 400 || status === 409 || status === 422) return \"poison\";\n return \"channel\";\n}\n\nfunction isoToNanos(iso) {\n const time = Date.parse(iso);\n if (!Number.isFinite(time)) return undefined;\n return String(BigInt(Math.round(time)) * 1_000_000n);\n}\n\n/** A 32 hex trace id and a 16 hex span id, derived from the event id. */\nexport function traceAndSpanIds(eventId) {\n const hex = typeof eventId === \"string\" ? eventId.replace(/[^0-9a-f]/gi, \"\").toLowerCase() : \"\";\n const traceId = (hex + \"0\".repeat(32)).slice(0, 32);\n const spanId = (hex + \"0\".repeat(16)).slice(0, 16);\n return { traceId, spanId };\n}\n\n/**\n * Build the OTLP traces envelope for a list of SCRUBBED events.\n *\n * The input is already scrubbed, so this function never sees a prompt or a\n * response and never has to decide whether one is safe.\n */\nexport function buildTracesEnvelope(events) {\n const spans = [];\n for (const event of events) {\n if (!isPlainObject(event)) continue;\n const { traceId, spanId } = traceAndSpanIds(event.eventId);\n const start = isoToNanos(event.ts);\n const durationMs = typeof event.durationMs === \"number\" ? event.durationMs : 0;\n const end = start ? String(BigInt(start) + BigInt(Math.max(0, Math.round(durationMs)) * 1_000_000)) : undefined;\n const span = {\n traceId,\n spanId,\n name: typeof event.name === \"string\" && event.name ? event.name : \"chat\",\n kind: 3,\n attributes: Array.isArray(event.attributes) ? event.attributes : [],\n };\n if (start) span.startTimeUnixNano = start;\n if (end) span.endTimeUnixNano = end;\n if (isPlainObject(event.status)) span.status = { code: event.status.code };\n spans.push(span);\n }\n return {\n resourceSpans: [\n {\n resource: {\n attributes: [\n { key: \"service.name\", value: { stringValue: SERVICE_NAME } },\n { key: \"service.version\", value: { stringValue: SERVICE_VERSION } },\n ],\n },\n scopeSpans: [{ scope: { name: SERVICE_NAME }, spans }],\n },\n ],\n };\n}\n\n/**\n * Build the OTLP logs envelope for a list of SCRUBBED events.\n *\n * The body was rebuilt by the scrubber from allowlisted fields, so it never\n * contains producer free text.\n */\nexport function buildLogsEnvelope(events) {\n const logRecords = [];\n for (const event of events) {\n if (!isPlainObject(event)) continue;\n const { traceId, spanId } = traceAndSpanIds(event.eventId);\n const record = {\n timeUnixNano: isoToNanos(event.ts) ?? String(Date.now() * 1_000_000),\n severityNumber: typeof event.severityNumber === \"number\" ? event.severityNumber : 9,\n body: isPlainObject(event.body) ? event.body : { stringValue: \"\" },\n traceId,\n spanId,\n attributes: Array.isArray(event.attributes) ? event.attributes : [],\n };\n logRecords.push(record);\n }\n return {\n resourceLogs: [\n {\n resource: {\n attributes: [\n { key: \"service.name\", value: { stringValue: SERVICE_NAME } },\n { key: \"service.version\", value: { stringValue: SERVICE_VERSION } },\n ],\n },\n scopeLogs: [{ scope: { name: SERVICE_NAME }, logRecords }],\n },\n ],\n };\n}\n\n/**\n * Split a list into chunks that respect both a count cap and a body size\n * cap. The body cap is checked on the serialized envelope, so a batch of\n * very large attribute values is split before it reaches the 12 MiB cap.\n *\n * The size of ONE event is measured once and the running total is carried\n * along. Re-serializing the whole candidate for every event made the pass\n * quadratic and could build hundreds of megabytes of discarded JSON.\n */\nexport function chunkBySize(events, build, { maxCount, maxChars }) {\n const chunks = [];\n let current = [];\n let currentChars = 0;\n // The fixed part of the envelope is serialized once, and every event\n // gets an allowance for the ids and the timestamps the envelope adds.\n const overhead = JSON.stringify(build([])).length;\n const perEventAllowance = 256;\n const limit = Math.max(1, maxChars - overhead);\n for (const event of events) {\n const eventChars = JSON.stringify(event ?? null).length + perEventAllowance;\n const candidateChars = currentChars + eventChars;\n if (current.length > 0 && (current.length + 1 > maxCount || candidateChars > limit)) {\n chunks.push(current);\n current = [event];\n currentChars = eventChars;\n continue;\n }\n current.push(event);\n currentChars = candidateChars;\n }\n if (current.length > 0) chunks.push(current);\n return chunks;\n}\n\n/**\n * Create the Sentry sender.\n *\n * @param {object} options\n * @param {import(\"./journal.mjs\").Journal} options.journal\n */\nexport function createSentrySender({\n journal,\n endpoint = process.env.SENTRY_OTLP_ENDPOINT?.trim(),\n publicKey = process.env.SENTRY_PUBLIC_KEY?.trim(),\n readLimit = DEFAULT_READ_LIMIT,\n dryRun = false,\n logger = NULL_LOGGER,\n fetchImpl = globalThis.fetch,\n retryDelayMs = BASE_BACKOFF_MS,\n} = {}) {\n if (!journal) throw new Error(\"The Sentry sender needs a journal\");\n const destination = \"sentry\";\n const root = endpoint ? endpoint.replace(/\\/+$/, \"\") : \"\";\n let inFlight = false;\n let blocked = false;\n let holdWarningSent = false;\n\n function warnHeld({ responseClass, heldEvents = 0, rejectedCount } = {}) {\n if (holdWarningSent) return;\n holdWarningSent = true;\n logger.warn(\"sentry delivery is held\", { destination, responseClass: responseClass ?? \"unresolved_intent\", heldEvents, ...(rejectedCount === undefined ? {} : { rejectedCount }) });\n }\n\n async function post(path, envelope, submitted) {\n const json = JSON.stringify(envelope);\n const body = gzipSync(Buffer.from(json, \"utf8\"));\n let response;\n try {\n response = await fetchImpl(`${root}${path}`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"content-encoding\": \"gzip\",\n \"x-sentry-auth\": `sentry sentry_key=${publicKey}`,\n \"content-length\": String(body.length),\n },\n body,\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n } catch (error) {\n return { outcome: \"retry\", status: 0, errorName: error?.name ?? \"Error\" };\n }\n const outcome = classifyStatus(response.status);\n if (outcome === \"ok\") {\n const ack = await readSuccessAck(response, path === SENTRY_LOGS_PATH, submitted);\n return ack.accepted ? { outcome, status: response.status } : { outcome: \"held\", status: response.status, ...ack };\n }\n // Rejection bodies can echo producer content; only the HTTP class is needed.\n await response.body?.cancel?.().catch(() => {});\n return { outcome, status: response.status };\n }\n\n async function postWithRetry(path, envelope, submitted) {\n let last = { outcome: \"retry\", status: 0 };\n for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt += 1) {\n last = await post(path, envelope, submitted);\n if (last.outcome !== \"retry\") return last;\n if (attempt < MAX_ATTEMPTS && retryDelayMs > 0) {\n await sleep(retryDelayMs * 2 ** (attempt - 1));\n }\n }\n return last;\n }\n\n /**\n * Deliver one group of events, isolating a single poisoned event.\n *\n * A poison response is answered for the whole envelope, so the group is\n * halved until one event is left; that event is quarantined and the rest\n * is delivered.\n */\n async function deliverGroup(events, path, build) {\n const delivered = [];\n const quarantined = [];\n\n const attempt = async (subset) => {\n let intent;\n let result;\n try {\n intent = await journal.prepareSentryRequest(path === SENTRY_LOGS_PATH ? \"logs\" : \"traces\", subset);\n result = await postWithRetry(path, build(intent.events), subset.length);\n if (result.outcome === \"held\") {\n blocked = true;\n warnHeld({ responseClass: result.responseClass, heldEvents: subset.length, rejectedCount: result.rejectedCount });\n await journal.holdSentryRequest(intent.batchDigest, { responseClass: result.responseClass, rejectedCount: result.rejectedCount, httpStatus: result.status });\n return { ...result, heldEvents: subset.length };\n }\n if (result.outcome === \"ok\") await journal.markSentBatch(destination, intent.eventIds);\n await journal.clearSentryRequest(intent.batchDigest);\n } catch (error) {\n blocked = true;\n throw error;\n }\n if (result.outcome === \"ok\") {\n delivered.push(...subset);\n return { outcome: \"ok\" };\n }\n if (result.outcome === \"retry\" || result.outcome === \"channel\") {\n return { outcome: result.outcome, status: result.status };\n }\n if (subset.length === 1) {\n quarantined.push(subset[0]);\n await journal.quarantine(destination, subset[0], {\n reason: \"sentry rejected the event\",\n status: result.status,\n });\n logger.warn(\"quarantined an event\", {\n destination,\n eventId: subset[0]?.eventId,\n metricType: subset[0]?.operation,\n status: result.status,\n });\n return { outcome: \"ok\" };\n }\n const middle = Math.ceil(subset.length / 2);\n const left = await attempt(subset.slice(0, middle));\n if (left.outcome !== \"ok\") return left;\n const right = await attempt(subset.slice(middle));\n if (right.outcome !== \"ok\") return right;\n return { outcome: \"ok\" };\n };\n\n const result = await attempt(events);\n return { ...result, delivered, quarantined };\n }\n\n /** One pass over the Sentry destination. */\n async function runOnce() {\n // A pass can outlive the delivery tick. The guard keeps two passes\n // from delivering the same events twice and from writing the same\n // offset file at the same time. The hub guards the whole pass as\n // well; this one makes the sender safe on its own.\n if (inFlight) return { ok: true, delivered: 0, quarantined: 0, busy: true };\n inFlight = true;\n try {\n return await runOnceGuarded();\n } finally {\n inFlight = false;\n }\n }\n\n async function runOnceGuarded() {\n let request;\n try { request = await journal.readSentryRequest(); }\n catch { blocked = true; warnHeld({ responseClass: \"invalid_request_state\" }); }\n if (blocked || request) {\n warnHeld({ responseClass: request?.responseClass, heldEvents: request?.events.length, rejectedCount: request?.rejectedCount });\n return { ok: false, retry: false, held: true, delivered: 0, quarantined: 0, ...(request ? { heldEvents: request.events.length, responseClass: request.responseClass ?? \"unresolved_intent\", ...(request.rejectedCount === undefined ? {} : { rejectedCount: request.rejectedCount }) } : {}) };\n }\n const batch = await journal.readBatch(destination, readLimit);\n if (batch.events.length === 0) {\n return { ok: true, delivered: 0, quarantined: 0, empty: true };\n }\n\n // S1: the content fields are stripped before the scrubber runs, and the\n // scrubber drops them as well. Two independent barriers.\n const scrubbed = batch.events\n .map((event) => scrubInternalEvent(event))\n .filter((event) => !!event);\n\n const spans = scrubbed.filter((event) => event.kind !== \"log\");\n const logs = scrubbed.filter((event) => event.kind === \"log\");\n\n if (dryRun) {\n logger.info(\"sentry dry run\", {\n destination,\n events: batch.events.length,\n spans: spans.length,\n logs: logs.length,\n attributeKeys: [...new Set(scrubbed.flatMap((event) => event.attributes.map((a) => a.key)))].sort(),\n });\n return { ok: true, delivered: 0, quarantined: 0, dryRun: true };\n }\n\n if (!root || !publicKey) {\n logger.error(\"the sentry otlp endpoint or public key is not configured\", { destination });\n return { ok: false, retry: false, delivered: 0, quarantined: 0 };\n }\n\n const deliveredIds = [];\n let quarantined = 0;\n\n const spanChunks = chunkBySize(spans, buildTracesEnvelope, {\n maxCount: MAX_SPANS_PER_REQUEST,\n maxChars: MAX_BODY_CHARS,\n });\n for (const chunk of spanChunks) {\n const outcome = await deliverGroup(chunk, SENTRY_TRACES_PATH, buildTracesEnvelope);\n if (outcome.outcome !== \"ok\") {\n // Whatever was delivered before the failure stays delivered, so\n // the next pass does not send it again. That includes the events\n // of the failed chunk that the isolation split delivered before\n // the failure: they reached Sentry, so they must be marked.\n const partial = [...outcome.delivered, ...outcome.quarantined]\n .map((event) => eventIdOf(event))\n .filter((id) => typeof id === \"string\" && id);\n await journal.markSentBatch(destination, [...deliveredIds, ...partial]);\n logger.warn(\"sentry is not accepting the batch\", {\n destination,\n path: SENTRY_TRACES_PATH,\n status: outcome.status,\n outcome: outcome.outcome,\n });\n return { ok: false, retry: outcome.outcome === \"retry\", delivered: deliveredIds.length + outcome.delivered.length, quarantined: quarantined + outcome.quarantined.length, ...(outcome.outcome === \"held\" ? { held: true, heldEvents: outcome.heldEvents, responseClass: outcome.responseClass, ...(outcome.rejectedCount === undefined ? {} : { rejectedCount: outcome.rejectedCount }) } : {}) };\n }\n const ids = [...outcome.delivered, ...outcome.quarantined]\n .map((event) => event.eventId)\n .filter((id) => typeof id === \"string\" && id);\n quarantined += outcome.quarantined.length;\n await journal.markSentBatch(destination, ids);\n deliveredIds.push(...outcome.delivered.map((event) => event.eventId));\n }\n\n const logChunks = chunkBySize(logs, buildLogsEnvelope, {\n maxCount: MAX_LOGS_PER_REQUEST,\n maxChars: MAX_BODY_CHARS,\n });\n for (const chunk of logChunks) {\n const outcome = await deliverGroup(chunk, SENTRY_LOGS_PATH, buildLogsEnvelope);\n if (outcome.outcome !== \"ok\") {\n // The same rule as the span chunks: the events of the failed\n // chunk that were delivered before the failure stay delivered.\n const partial = [...outcome.delivered, ...outcome.quarantined]\n .map((event) => eventIdOf(event))\n .filter((id) => typeof id === \"string\" && id);\n await journal.markSentBatch(destination, [...deliveredIds, ...partial]);\n logger.warn(\"sentry is not accepting the batch\", {\n destination,\n path: SENTRY_LOGS_PATH,\n status: outcome.status,\n outcome: outcome.outcome,\n });\n return { ok: false, retry: outcome.outcome === \"retry\", delivered: deliveredIds.length + outcome.delivered.length, quarantined: quarantined + outcome.quarantined.length, ...(outcome.outcome === \"held\" ? { held: true, heldEvents: outcome.heldEvents, responseClass: outcome.responseClass, ...(outcome.rejectedCount === undefined ? {} : { rejectedCount: outcome.rejectedCount }) } : {}) };\n }\n const ids = [...outcome.delivered, ...outcome.quarantined]\n .map((event) => event.eventId)\n .filter((id) => typeof id === \"string\" && id);\n quarantined += outcome.quarantined.length;\n await journal.markSentBatch(destination, ids);\n deliveredIds.push(...outcome.delivered.map((event) => event.eventId));\n }\n\n await journal.setOffset(destination, batch.endOffset);\n return {\n ok: true,\n delivered: deliveredIds.length,\n quarantined,\n };\n }\n\n return {\n destinations: [destination],\n runOnce,\n };\n}\n"}, {"path": "scripts/sentry-partial-ack.node-test.mjs", "mode": "100644", "type": "blob", "content": "import assert from \"node:assert/strict\";\nimport { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport test from \"node:test\";\nimport { gunzipSync } from \"node:zlib\";\nimport { Journal } from \"./telemetry-hub/journal.mjs\";\nimport { createSentrySender, MAX_SENTRY_ACK_BYTES } from \"./telemetry-hub/sentry-sender.mjs\";\n\nconst PRIVATE = \"PRIVATE_RESPONSE_CONTENT_https://secret@example.test/private\";\nconst id = (n) => n.toString(16).padStart(64, \"0\");\nfunction event(n, kind = \"log\") {\n return { eventId: id(n), ts: \"2026-10-30T12:00:00Z\", kind, platform: \"claude-code\", operation: \"chat\", model: \"claude-test\", tokens: { input: n, output: 2 }, ...(kind === \"span\" ? { durationMs: 1 } : {}), promptText: PRIVATE, responseText: PRIVATE, sessionId: PRIVATE, project: PRIVATE };\n}\nclass FaultJournal extends Journal {\n async syncStateFile(file) {\n if (this.failFileSync) throw Object.assign(new Error(\"Injected fsync failure\"), { code: \"EIO\" });\n await super.syncStateFile(file);\n }\n async syncStateDirectory() {\n if (this.failDirectorySync) throw Object.assign(new Error(\"Injected directory fsync failure\"), { code: \"EIO\" });\n await super.syncStateDirectory();\n }\n}\nasync function fixture(t, events = [event(1), event(2), event(3)]) {\n const dir = await mkdtemp(join(tmpdir(), \"sentry-ack-\"));\n const opened = [];\n t.after(async () => { for (const journal of opened) await journal.close(); await rm(dir, { recursive: true, force: true }); });\n const reopen = async () => {\n const journal = new FaultJournal({ dir });\n await journal.open(); await journal.loadDestinations([\"sentry\"]); opened.push(journal);\n return journal;\n };\n const journal = await reopen();\n await journal.appendBatch(events);\n const sender = (j, fetchImpl, logger) => createSentrySender({ journal: j, endpoint: \"https://example.sentry.io/api/1/integration/otlp\", publicKey: \"test-only-public-key\", fetchImpl, logger, retryDelayMs: 0 });\n return { dir, journal, reopen, sender };\n}\nconst holdPath = (dir) => join(dir, \"state\", \"sentry-request.json\");\n\ntest(\"journal startup preserves an orphaned deterministic temporary file after PID and counter reuse\", async (t) => {\n const dir = await mkdtemp(join(tmpdir(), \"sentry-orphan-\"));\n t.after(() => rm(dir, { recursive: true, force: true }));\n const state = join(dir, \"state\");\n await mkdir(state, { mode: 0o700 });\n const stale = join(state, `journal.base.json.${process.pid}.1.tmp`);\n const original = Buffer.from(\"PRIVATE_LEGACY_ORPHAN_BYTES\");\n await writeFile(stale, original, { mode: 0o600 });\n for (let attempt = 0; attempt < 2; attempt++) {\n const journal = new Journal({ dir });\n try {\n await journal.open();\n assert.equal(journal.base, 0);\n assert.deepEqual(JSON.parse(await readFile(join(state, \"journal.base.json\"), \"utf8\")), { base: 0, nextBase: 0, pendingSize: 0 });\n assert.deepEqual(await readFile(stale), original);\n assert.equal((await stat(stale)).mode & 0o777, 0o600);\n } finally { await journal.close(); }\n }\n});\n\ntest(\"positive partial ACK holds the entire scrubbed batch without claiming all records rejected\", async (t) => {\n const f = await fixture(t);\n let requests = 0;\n const warnings = [];\n const logger = { info() {}, error() {}, warn(message, fields) { warnings.push({ message, fields }); } };\n const sender = f.sender(f.journal, async (_url, init) => {\n requests++;\n const prepared = await f.journal.readSentryRequest();\n assert.equal(prepared.phase, \"prepared\");\n assert.equal(prepared.events.length, 3);\n assert.ok(!gunzipSync(init.body).toString().includes(PRIVATE));\n return Response.json({ partialSuccess: { rejectedLogRecords: \"1\", errorMessage: PRIVATE } });\n }, logger);\n const result = await sender.runOnce();\n assert.equal(result.held, true);\n assert.equal(result.retry, false);\n assert.equal(result.delivered, 0);\n assert.equal(result.quarantined, 0);\n assert.equal(result.heldEvents, 3);\n assert.equal(result.rejectedCount, 1);\n assert.equal(f.journal.getOffset(\"sentry\"), 0);\n assert.ok([1, 2, 3].every((n) => !f.journal.isSent(\"sentry\", id(n))));\n const raw = await readFile(holdPath(f.dir), \"utf8\");\n const held = JSON.parse(raw);\n assert.equal(held.phase, \"held\");\n assert.equal(held.responseClass, \"partial_success\");\n assert.equal(held.rejectedCount, 1);\n assert.deepEqual(held.eventIds, [id(1), id(2), id(3)]);\n assert.equal(held.events[2].attributes.find((a) => a.key === \"gen_ai.usage.input_tokens\").value.intValue, \"3\");\n assert.ok(!raw.includes(PRIVATE));\n assert.ok(!raw.includes(\"errorMessage\"));\n assert.ok(!raw.includes(\"public-key\"));\n assert.equal((await stat(holdPath(f.dir))).mode & 0o777, 0o600);\n await sender.runOnce(); await sender.runOnce();\n assert.equal(requests, 1);\n assert.equal(warnings.filter((row) => row.message === \"sentry delivery is held\").length, 1);\n assert.ok(!JSON.stringify(warnings).includes(id(1)));\n await f.journal.close();\n const restarted = await f.reopen();\n const restartWarnings = [];\n const restartedSender = f.sender(restarted, async () => { assert.fail(\"A partial batch must not be retried after restart\"); }, { ...logger, warn: (message, fields) => restartWarnings.push({ message, fields }) });\n assert.equal((await restartedSender.runOnce()).held, true);\n await restartedSender.runOnce();\n assert.equal(restartWarnings.length, 1);\n assert.equal(restartWarnings[0].fields.rejectedCount, 1);\n await restarted.compactTo(restarted.base + await restarted.fileSize());\n assert.equal(await restarted.fileSize(), 0);\n assert.equal((await restarted.readSentryRequest()).events.length, 3);\n});\n\ntest(\"trace partial counts use their own schema and preserve stable held identities\", async (t) => {\n const f = await fixture(t, [event(1, \"span\"), event(2, \"span\")]);\n const result = await f.sender(f.journal, async (url) => {\n assert.ok(url.endsWith(\"/v1/traces\"));\n return Response.json({ partialSuccess: { rejectedSpans: 1 } });\n }).runOnce();\n assert.equal(result.held, true);\n assert.equal(result.rejectedCount, 1);\n const held = await f.journal.readSentryRequest();\n assert.equal(held.signal, \"traces\");\n assert.deepEqual(held.eventIds, [id(1), id(2)]);\n});\n\ntest(\"normal empty and JSON ACKs, zero warnings and valid int64 strings deliver normally\", async (t) => {\n for (const [name, response] of [\n [\"empty\", () => new Response(null, { status: 200 })],\n [\"empty-protobuf\", () => new Response(null, { headers: { \"content-type\": \"application/x-protobuf\" } })],\n [\"json\", () => Response.json({})],\n [\"zero-number-warning\", () => Response.json({ partialSuccess: { rejectedLogRecords: 0, errorMessage: PRIVATE } })],\n [\"zero-string-warning\", () => Response.json({ partialSuccess: { rejectedLogRecords: \"0\", errorMessage: PRIVATE } })],\n [\"zero-snake\", () => Response.json({ partial_success: { rejected_log_records: \"0\", error_message: PRIVATE } })],\n ]) await t.test(name, async (sub) => {\n const f = await fixture(sub);\n let requests = 0;\n const sender = f.sender(f.journal, async () => { requests++; return response(); });\n const result = await sender.runOnce();\n assert.equal(result.ok, true);\n assert.equal(result.delivered, 3);\n assert.equal(result.quarantined, 0);\n assert.equal(requests, 1);\n assert.equal(await f.journal.readSentryRequest(), null);\n assert.ok([1, 2, 3].every((n) => f.journal.isSent(\"sentry\", id(n))));\n assert.ok(f.journal.getOffset(\"sentry\") > 0);\n });\n});\n\ntest(\"invalid or oversized 2xx acknowledgements become typed holds without retries\", async (t) => {\n for (const [name, make, expected] of [\n [\"invalid-json\", () => new Response(PRIVATE, { headers: { \"content-type\": \"application/json\" } }), \"malformed_ack\"],\n [\"oversized\", () => new Response(\"x\".repeat(MAX_SENTRY_ACK_BYTES + 1), { headers: { \"content-type\": \"application/json\" } }), \"oversized_ack\"],\n [\"negative\", () => Response.json({ partialSuccess: { rejectedLogRecords: -1 } }), \"malformed_ack\"],\n [\"boolean\", () => Response.json({ partialSuccess: { rejectedLogRecords: true } }), \"malformed_ack\"],\n [\"fraction\", () => Response.json({ partialSuccess: { rejectedLogRecords: 0.5 } }), \"malformed_ack\"],\n [\"unsafe\", () => Response.json({ partialSuccess: { rejectedLogRecords: \"9007199254740992\" } }), \"malformed_ack\"],\n [\"above-submitted\", () => Response.json({ partialSuccess: { rejectedLogRecords: 4 } }), \"malformed_ack\"],\n [\"wrong-signal\", () => Response.json({ partialSuccess: { rejectedSpans: 0 } }), \"malformed_ack\"],\n [\"both-names\", () => Response.json({ partialSuccess: {}, partial_success: {} }), \"malformed_ack\"],\n [\"unknown-field\", () => Response.json({ error: PRIVATE }), \"malformed_ack\"],\n [\"null\", () => Response.json(null), \"malformed_ack\"],\n [\"empty-html\", () => new Response(null, { headers: { \"content-type\": \"text/html\" } }), \"unexpected_content_type\"],\n [\"html-json\", () => new Response(\"{}\", { headers: { \"content-type\": \"text/html\" } }), \"unexpected_content_type\"],\n [\"stream-failure\", () => new Response(new ReadableStream({ start(controller) { controller.error(new Error(PRIVATE)); } })), \"unreadable_ack\"],\n ]) await t.test(name, async (sub) => {\n const f = await fixture(sub);\n let requests = 0;\n const sender = f.sender(f.journal, async () => { requests++; return make(); });\n const result = await sender.runOnce();\n assert.equal(result.held, true);\n assert.equal(result.responseClass, expected);\n assert.equal(result.delivered, 0);\n assert.equal(result.quarantined, 0);\n assert.equal(f.journal.getOffset(\"sentry\"), 0);\n await sender.runOnce();\n assert.equal(requests, 1);\n const raw = await readFile(holdPath(f.dir), \"utf8\");\n assert.ok(!raw.includes(PRIVATE));\n assert.equal(JSON.parse(raw).responseClass, expected);\n });\n});\n\ntest(\"pre-POST fsync failure sends nothing and never advances offset or sent state\", async (t) => {\n const f = await fixture(t);\n f.journal.failFileSync = true;\n const sender = f.sender(f.journal, async () => { assert.fail(\"No request before durable intent\"); });\n await assert.rejects(sender.runOnce(), { code: \"EIO\" });\n assert.equal(f.journal.getOffset(\"sentry\"), 0);\n assert.equal(f.journal.isSent(\"sentry\", id(1)), false);\n assert.equal((await sender.runOnce()).held, true);\n await assert.rejects(f.journal.setOffset(\"sentry\", 123), { code: \"EIO\" });\n assert.equal(f.journal.getOffset(\"sentry\"), 0);\n await assert.rejects(f.journal.markSentBatch(\"sentry\", [id(1)]), { code: \"EIO\" });\n assert.equal(f.journal.isSent(\"sentry\", id(1)), false);\n});\n\ntest(\"pre-POST directory fsync failure leaves an intent and makes no request even after restart\", async (t) => {\n const f = await fixture(t);\n f.journal.failDirectorySync = true;\n const sender = f.sender(f.journal, async () => { assert.fail(\"Directory durability precedes POST\"); });\n await assert.rejects(sender.runOnce(), { code: \"EIO\" });\n assert.equal(f.journal.getOffset(\"sentry\"), 0);\n assert.equal((await f.journal.readSentryRequest()).phase, \"prepared\");\n assert.equal(f.journal.isSent(\"sentry\", id(1)), false);\n await f.journal.close();\n const restart = await f.reopen();\n assert.equal((await f.sender(restart, async () => { assert.fail(\"An unresolved published intent must not be retried\"); }).runOnce()).held, true);\n});\n\ntest(\"a partial response followed by hold fsync failure retains the pre-POST intent across restart\", async (t) => {\n const f = await fixture(t);\n let requests = 0;\n const sender = f.sender(f.journal, async () => {\n requests++; f.journal.failFileSync = true;\n return Response.json({ partialSuccess: { rejectedLogRecords: 1, errorMessage: PRIVATE } });\n });\n await assert.rejects(sender.runOnce(), { code: \"EIO\" });\n assert.equal(f.journal.getOffset(\"sentry\"), 0);\n assert.equal(f.journal.isSent(\"sentry\", id(1)), false);\n assert.equal((await f.journal.readSentryRequest()).phase, \"prepared\");\n await sender.runOnce();\n assert.equal(requests, 1);\n await f.journal.close();\n const restart = await f.reopen();\n assert.equal((await f.sender(restart, async () => { assert.fail(\"Unknown outcome must not be re-posted\"); }).runOnce()).held, true);\n assert.ok(!(await readFile(holdPath(f.dir), \"utf8\")).includes(PRIVATE));\n});\n\ntest(\"full ACK sent-state fsync failure retains unresolved intent rather than replaying accepted data\", async (t) => {\n const f = await fixture(t);\n const sender = f.sender(f.journal, async () => { f.journal.failFileSync = true; return Response.json({}); });\n await assert.rejects(sender.runOnce(), { code: \"EIO\" });\n assert.equal(f.journal.isSent(\"sentry\", id(1)), false);\n assert.equal(f.journal.getOffset(\"sentry\"), 0);\n await f.journal.close();\n const restart = await f.reopen();\n assert.equal((await f.sender(restart, async () => { assert.fail(\"No automatic ambiguous replay\"); }).runOnce()).held, true);\n});\n\ntest(\"a crash before intent removal preserves confirmed sent receipts and still fails closed on restart\", async (t) => {\n const f = await fixture(t);\n f.journal.clearSentryRequest = async () => { throw Object.assign(new Error(\"Injected interruption\"), { code: \"EIO\" }); };\n await assert.rejects(f.sender(f.journal, async () => Response.json({})).runOnce(), { code: \"EIO\" });\n assert.equal(f.journal.isSent(\"sentry\", id(1)), true);\n await f.journal.close();\n const restart = await f.reopen();\n assert.equal(restart.isSent(\"sentry\", id(1)), true);\n assert.equal((await f.sender(restart, async () => { assert.fail(\"A restart must not repeat an unresolved request\"); }).runOnce()).held, true);\n});\n\ntest(\"corrupt durable intent blocks delivery and warns only once without exposing state bytes\", async (t) => {\n const f = await fixture(t);\n await writeFile(holdPath(f.dir), PRIVATE, { mode: 0o600 });\n const warnings = [];\n const sender = f.sender(f.journal, async () => { assert.fail(\"Corrupt intent is not permission to send\"); }, { info() {}, error() {}, warn(message, fields) { warnings.push({ message, fields }); } });\n await sender.runOnce(); await sender.runOnce();\n assert.equal(warnings.length, 1);\n assert.equal(warnings[0].fields.responseClass, \"invalid_request_state\");\n assert.ok(!JSON.stringify(warnings).includes(PRIVATE));\n});\n\ntest(\"explicit transient failures retain the existing retry contract without persisting response text\", async (t) => {\n const f = await fixture(t);\n let requests = 0;\n const result = await f.sender(f.journal, async () => {\n requests++;\n assert.equal((await f.journal.readSentryRequest()).phase, \"prepared\");\n return requests === 1 ? new Response(PRIVATE, { status: 429 }) : Response.json({});\n }).runOnce();\n assert.equal(requests, 2);\n assert.equal(result.delivered, 3);\n assert.equal(result.ok, true);\n assert.equal(await f.journal.readSentryRequest(), null);\n for (const name of await readdir(join(f.dir, \"state\"))) assert.ok(!(await readFile(join(f.dir, \"state\", name), \"utf8\")).includes(PRIVATE));\n});\n\ntest(\"existing HTTP 400 isolation delivers valid siblings and never persists rejection text\", async (t) => {\n const f = await fixture(t, [event(1), { ...event(2), model: \"bad-model\" }, event(3)]);\n const sender = f.sender(f.journal, async (_url, init) => {\n const payload = JSON.parse(gunzipSync(init.body));\n const records = payload.resourceLogs[0].scopeLogs[0].logRecords;\n const poisoned = records.some((record) => record.attributes.some((attr) => attr.key === \"gen_ai.request.model\" && attr.value.stringValue === \"bad-model\"));\n return poisoned ? new Response(PRIVATE, { status: 400 }) : Response.json({});\n });\n const result = await sender.runOnce();\n assert.equal(result.ok, true);\n assert.equal(result.delivered, 2);\n assert.equal(result.quarantined, 1);\n assert.ok([1, 2, 3].every((n) => f.journal.isSent(\"sentry\", id(n))));\n assert.ok(f.journal.getOffset(\"sentry\") > 0);\n assert.equal(await f.journal.readSentryRequest(), null);\n const rejected = await readFile(join(f.dir, \"dead-letter.jsonl\"), \"utf8\");\n assert.ok(!rejected.includes(PRIVATE));\n assert.equal(rejected.trim().split('\\n').length, 1);\n assert.equal(JSON.parse(rejected).httpStatus, 400);\n assert.equal((await sender.runOnce()).delivered, 0);\n});\n\ntest(\"a later log partial hold preserves an earlier confirmed trace chunk and its durable sent receipt\", async (t) => {\n const f = await fixture(t, [event(1, \"span\"), event(2), event(3)]);\n const sender = f.sender(f.journal, async (url) => url.endsWith('/v1/traces') ? Response.json({}) : Response.json({ partialSuccess: { rejectedLogRecords: 1 } }));\n const result = await sender.runOnce();\n assert.equal(result.held, true);\n assert.equal(result.delivered, 1);\n assert.equal(result.heldEvents, 2);\n assert.equal(result.rejectedCount, 1);\n assert.equal(result.quarantined, 0);\n assert.equal(f.journal.getOffset(\"sentry\"), 0);\n assert.equal(f.journal.isSent(\"sentry\", id(1)), true);\n assert.equal(f.journal.isSent(\"sentry\", id(2)), false);\n assert.deepEqual((await f.journal.readSentryRequest()).eventIds, [id(2), id(3)]);\n await f.journal.close();\n const restart = await f.reopen();\n assert.equal(restart.isSent(\"sentry\", id(1)), true);\n assert.equal((await f.sender(restart, async () => { assert.fail(\"Neither the accepted trace nor ambiguous logs may be replayed\"); }).runOnce()).held, true);\n});\n\ntest(\"base-state fsync failure before compaction preserves the original journal and held request\", async (t) => {\n const f = await fixture(t);\n await f.sender(f.journal, async () => Response.json({ partialSuccess: { rejectedLogRecords: 1 } })).runOnce();\n const before = await readFile(join(f.dir, \"journal.jsonl\"));\n const held = await readFile(holdPath(f.dir));\n f.journal.failFileSync = true;\n await assert.rejects(f.journal.compactTo(f.journal.base + await f.journal.fileSize()), { code: \"EIO\" });\n assert.equal(f.journal.base, 0);\n assert.equal(f.journal.getOffset(\"sentry\"), 0);\n assert.deepEqual(await readFile(join(f.dir, \"journal.jsonl\")), before);\n assert.deepEqual(await readFile(holdPath(f.dir)), held);\n await f.journal.close();\n const restart = await f.reopen();\n assert.equal(restart.base, 0);\n assert.equal((await restart.readBatch(\"sentry\", 100)).events.length, 3);\n assert.equal((await f.sender(restart, async () => { assert.fail(\"Compaction failure must not re-post the held request\"); }).runOnce()).held, true);\n});\n"}, {"path": "docs/rollouts/2026-11-03-sentry-partial-acks.md", "mode": "100644", "type": "blob", "content": "# Durable Sentry Partial ACK Holds\n\nThe Sentry hub previously treated every HTTP 2xx response as full acceptance.\u00a0 The sender now reads at most 64 KiB of response bytes and validates the signal's OTLP rejection count, including safe integer strings.\u00a0 Empty compatible responses and JSON full success continue to work; a zero rejection warning also succeeds.\u00a0 A live empty-request probe returned HTTP 200 with `application/json` and `{}` for both logs and traces without emitting telemetry events.\u00a0 Explicit incompatible content types, malformed or oversized success replies, and positive partial rejection counts stop Sentry delivery without retrying the ambiguous batch.\u00a0 Free response messages, rejection bodies and headers are never persisted.\n\nBefore each POST, the journal durably publishes one private `state/sentry-request.json` intent containing the full scrubbed metadata batch, original event IDs and a stable digest.\u00a0 File fsync, atomic exclusive publication and directory fsync precede the request.\u00a0 A partial or ambiguous success updates that file with only a typed response class, HTTP status and any validated rejection count.\u00a0 The rejection count does not identify which records failed, so the whole batch remains held while confirmed delivery and rejected counts stay separate.\u00a0 Its independent metadata copy survives journal compaction; the older ID-only dead-letter record is insufficient for this purpose.\n\nThe Sentry channel holds while a prepared, held or invalid intent exists, including after restart.\u00a0 It emits one count-only warning per sender instance and retains the journal offset.\u00a0 A normal full success persists its sent receipts before clearing the intent.\u00a0 Explicit HTTP failure and bounded same-process transport retries retain their existing contract.\u00a0 A crash with an unresolved pre-POST intent conservatively requires reconciliation even if the request was never sent or a success receipt was already written.\u00a0 This trades automatic recovery for preservation and avoids guessing which records may be retried; no automatic hold deletion or batch replay is introduced.\u00a0 Preserve the intent file, payload and event identities before any manual reconciliation.\u00a0 The other delivery destinations remain independent.\n\nOlder sender images ignore the intent file.\u00a0 A rollback to an older image must keep Sentry delivery stopped whenever an intent exists.\u00a0 Preserve its payload and identities, then reconcile receiver receipts before resuming delivery.\n\nThis fixes a confirmed ACK-validation weakness.\u00a0 The historical Claude catch-up was independently verified in Sentry in full; partial response loss was not established as its cause.\u00a0 Focused Node tests exercise real journal files, restart and compaction, file and directory fsync failures, strict ACK schemas, safe warnings, valid siblings around an HTTP 400 rejection, and a confirmed trace chunk followed by ambiguous logs.\u00a0 The suite runs through the existing collector runtime CI gate.\n"}]}
\ No newline at end of file
diff --git a/.um1651-hub-upgrade-0a92fcfa39f5b576f498dabc43963c89c47b3713.plan.json b/.um1651-hub-upgrade-0a92fcfa39f5b576f498dabc43963c89c47b3713.plan.json
new file mode 100644
index 00000000..f1baef62
--- /dev/null
+++ b/.um1651-hub-upgrade-0a92fcfa39f5b576f498dabc43963c89c47b3713.plan.json
@@ -0,0 +1,153 @@
+{
+ "configMountSource": "/mnt/fleet-extra/apps/telemetry-hub/config.json",
+ "currentCompose": {
+ "services": {
+ "telemetry-hub": {
+ "cap_drop": [
+ "ALL"
+ ],
+ "container_name": "telemetry-hub-a4tp0kk9jmfibzvbmsxvmtqg",
+ "cpus": 0.5,
+ "env_file": [
+ ".env"
+ ],
+ "environment": {
+ "COOLIFY_APP_NAME": "usage-monitor-telemetry-hub",
+ "COOLIFY_CONTAINER_NAME": "telemetry-hub-a4tp0kk9jmfibzvbmsxvmtqg",
+ "COOLIFY_ENVIRONMENT_NAME": "production",
+ "COOLIFY_PROJECT_NAME": "Fleet Infra",
+ "COOLIFY_RESOURCE_UUID": "a4tp0kk9jmfibzvbmsxvmtqg",
+ "COOLIFY_SERVER_IP": "host.docker.internal",
+ "SERVICE_NAME_TELEMETRY_HUB": "telemetry-hub",
+ "TELEMETRY_HUB_BIND_HOST": "100.69.77.26",
+ "TELEMETRY_HUB_CONFIG_FILE": "/run/secrets/telemetry-hub.json"
+ },
+ "image": "usage-monitor-telemetry-hub:80f0c92708a21a8a41c4e831187b8235f486d511",
+ "init": true,
+ "labels": [
+ "telemetry.task=UM-1646",
+ "telemetry.commit=80f0c92708a21a8a41c4e831187b8235f486d511",
+ "coolify.managed=true",
+ "coolify.version=4.5.3",
+ "coolify.serviceUuid=a4tp0kk9jmfibzvbmsxvmtqg",
+ "coolify.type=service",
+ "coolify.name=telemetry-hub-a4tp0kk9jmfibzvbmsxvmtqg",
+ "coolify.resourceName=usage-monitor-telemetry-hub",
+ "coolify.projectName=fleet-infra",
+ "coolify.serviceName=telemetry-hub",
+ "coolify.environmentName=production",
+ "coolify.pullRequestId=0",
+ "coolify.service.subUuid=s4oqyz6lbb0yn6kg4sljaonk",
+ "coolify.service.subType=application",
+ "coolify.service.subName=telemetry-hub"
+ ],
+ "mem_limit": "512m",
+ "network_mode": "host",
+ "pull_policy": "never",
+ "read_only": true,
+ "restart": "unless-stopped",
+ "security_opt": [
+ "no-new-privileges:true"
+ ],
+ "tmpfs": [
+ "/tmp:rw,noexec,nosuid,size=16m"
+ ],
+ "volumes": [
+ "a4tp0kk9jmfibzvbmsxvmtqg_journal:/data",
+ {
+ "bind": {
+ "create_host_path": true
+ },
+ "read_only": true,
+ "source": "/mnt/fleet-extra/apps/telemetry-hub/config.json",
+ "target": "/run/secrets/telemetry-hub.json",
+ "type": "bind"
+ }
+ ]
+ }
+ },
+ "volumes": {
+ "a4tp0kk9jmfibzvbmsxvmtqg_journal": {
+ "name": "a4tp0kk9jmfibzvbmsxvmtqg_journal"
+ },
+ "journal": {
+ "name": "usage-monitor-telemetry-hub-journal"
+ }
+ }
+ },
+ "currentComposeSha256": "7c7cc57899ca52c31fe6842b0fd7660565d6a6865e29f1435dd378f04a38124b",
+ "durableVolume": "a4tp0kk9jmfibzvbmsxvmtqg_journal",
+ "metadata": {
+ "configMode": 384,
+ "configSha256": "4de53644a6cfc8bc79af1c2f7da1b6b52c1db19fbd8bc806920e30ce6b671579",
+ "configUid": 10001,
+ "journalBase": 33388798,
+ "journalBytes": 16207767,
+ "pendingBytes": 0,
+ "sentryOffset": 49596565
+ },
+ "mode": "plan-only",
+ "oldContainer": "3cefe8519dd3",
+ "oldImageId": "sha256:57ddfdd0b33583f215238738954ee703fc437c11029292f58ecf13d44b790cf7",
+ "preparedComposeSha256": "3531da30d755e97a5e027efaa64f0f5d426eb83e7f03665a811a011a5142482a",
+ "rawCompose": {
+ "services": {
+ "telemetry-hub": {
+ "cap_drop": [
+ "ALL"
+ ],
+ "cpus": 0.5,
+ "environment": {
+ "TELEMETRY_HUB_BIND_HOST": "100.69.77.26",
+ "TELEMETRY_HUB_CONFIG_FILE": "/run/secrets/telemetry-hub.json"
+ },
+ "image": "usage-monitor-telemetry-hub:80f0c92708a21a8a41c4e831187b8235f486d511",
+ "init": true,
+ "labels": {
+ "telemetry.commit": "80f0c92708a21a8a41c4e831187b8235f486d511",
+ "telemetry.task": "UM-1646"
+ },
+ "mem_limit": "512m",
+ "network_mode": "host",
+ "pull_policy": "never",
+ "read_only": true,
+ "restart": "unless-stopped",
+ "security_opt": [
+ "no-new-privileges:true"
+ ],
+ "tmpfs": [
+ "/tmp:rw,noexec,nosuid,size=16m"
+ ],
+ "volumes": [
+ "journal:/data",
+ {
+ "read_only": true,
+ "source": "/mnt/fleet-extra/apps/telemetry-hub/config.json",
+ "target": "/run/secrets/telemetry-hub.json",
+ "type": "bind"
+ }
+ ]
+ }
+ },
+ "volumes": {
+ "journal": {
+ "name": "usage-monitor-telemetry-hub-journal"
+ }
+ }
+ },
+ "rawComposeSha256": "a2a022132849a439c9463d4271b447f2525d5c927fa910d4bcd5fc11670e80b3",
+ "runtimeChanges": false,
+ "service": {
+ "environment_uuid": "tmrwg4denz09sb6qn9rlvjfu",
+ "image_id": "sha256:57ddfdd0b33583f215238738954ee703fc437c11029292f58ecf13d44b790cf7",
+ "project_uuid": "l11qegr5vie93o7dqlfjgd6n",
+ "server_uuid": "jxzqcs3h6g1wiipnnblhismp",
+ "source_commit": "80f0c92708a21a8a41c4e831187b8235f486d511",
+ "status": "exited",
+ "uuid": "a4tp0kk9jmfibzvbmsxvmtqg"
+ },
+ "serviceStatus": "running:healthy",
+ "targetCommit": "0a92fcfa39f5b576f498dabc43963c89c47b3713",
+ "targetImageId": "sha256:ebb8ef80a94380e00003db983f02768432a907338dc0d56d55fa863f6d8d3cca",
+ "upgradeContract": "Build before stop; recheck live compose/image/config and zero pending bytes before one stop; preserve current compose except image/telemetry.commit; same service/volume/config; inspect unknown outcomes before any retry"
+}
diff --git a/.um1651-hub-upgrade-0a92fcfa39f5b576f498dabc43963c89c47b3713.stale-41ce4cd6.plan.json b/.um1651-hub-upgrade-0a92fcfa39f5b576f498dabc43963c89c47b3713.stale-41ce4cd6.plan.json
new file mode 100644
index 00000000..0c7c73c5
--- /dev/null
+++ b/.um1651-hub-upgrade-0a92fcfa39f5b576f498dabc43963c89c47b3713.stale-41ce4cd6.plan.json
@@ -0,0 +1,153 @@
+{
+ "configMountSource": "/mnt/fleet-extra/apps/telemetry-hub/config.json",
+ "currentCompose": {
+ "services": {
+ "telemetry-hub": {
+ "cap_drop": [
+ "ALL"
+ ],
+ "container_name": "telemetry-hub-a4tp0kk9jmfibzvbmsxvmtqg",
+ "cpus": 0.5,
+ "env_file": [
+ ".env"
+ ],
+ "environment": {
+ "COOLIFY_APP_NAME": "usage-monitor-telemetry-hub",
+ "COOLIFY_CONTAINER_NAME": "telemetry-hub-a4tp0kk9jmfibzvbmsxvmtqg",
+ "COOLIFY_ENVIRONMENT_NAME": "production",
+ "COOLIFY_PROJECT_NAME": "Fleet Infra",
+ "COOLIFY_RESOURCE_UUID": "a4tp0kk9jmfibzvbmsxvmtqg",
+ "COOLIFY_SERVER_IP": "host.docker.internal",
+ "SERVICE_NAME_TELEMETRY_HUB": "telemetry-hub",
+ "TELEMETRY_HUB_BIND_HOST": "100.69.77.26",
+ "TELEMETRY_HUB_CONFIG_FILE": "/run/secrets/telemetry-hub.json"
+ },
+ "image": "usage-monitor-telemetry-hub:80f0c92708a21a8a41c4e831187b8235f486d511",
+ "init": true,
+ "labels": [
+ "telemetry.task=UM-1646",
+ "telemetry.commit=80f0c92708a21a8a41c4e831187b8235f486d511",
+ "coolify.managed=true",
+ "coolify.version=4.5.3",
+ "coolify.serviceUuid=a4tp0kk9jmfibzvbmsxvmtqg",
+ "coolify.type=service",
+ "coolify.name=telemetry-hub-a4tp0kk9jmfibzvbmsxvmtqg",
+ "coolify.resourceName=usage-monitor-telemetry-hub",
+ "coolify.projectName=fleet-infra",
+ "coolify.serviceName=telemetry-hub",
+ "coolify.environmentName=production",
+ "coolify.pullRequestId=0",
+ "coolify.service.subUuid=s4oqyz6lbb0yn6kg4sljaonk",
+ "coolify.service.subType=application",
+ "coolify.service.subName=telemetry-hub"
+ ],
+ "mem_limit": "512m",
+ "network_mode": "host",
+ "pull_policy": "never",
+ "read_only": true,
+ "restart": "unless-stopped",
+ "security_opt": [
+ "no-new-privileges:true"
+ ],
+ "tmpfs": [
+ "/tmp:rw,noexec,nosuid,size=16m"
+ ],
+ "volumes": [
+ "a4tp0kk9jmfibzvbmsxvmtqg_journal:/data",
+ {
+ "bind": {
+ "create_host_path": true
+ },
+ "read_only": true,
+ "source": "/mnt/fleet-extra/apps/telemetry-hub/config.json",
+ "target": "/run/secrets/telemetry-hub.json",
+ "type": "bind"
+ }
+ ]
+ }
+ },
+ "volumes": {
+ "a4tp0kk9jmfibzvbmsxvmtqg_journal": {
+ "name": "a4tp0kk9jmfibzvbmsxvmtqg_journal"
+ },
+ "journal": {
+ "name": "usage-monitor-telemetry-hub-journal"
+ }
+ }
+ },
+ "currentComposeSha256": "7c7cc57899ca52c31fe6842b0fd7660565d6a6865e29f1435dd378f04a38124b",
+ "durableVolume": "a4tp0kk9jmfibzvbmsxvmtqg_journal",
+ "metadata": {
+ "configMode": 384,
+ "configSha256": "4de53644a6cfc8bc79af1c2f7da1b6b52c1db19fbd8bc806920e30ce6b671579",
+ "configUid": 10001,
+ "journalBase": 33388798,
+ "journalBytes": 15777089,
+ "pendingBytes": 0,
+ "sentryOffset": 49165887
+ },
+ "mode": "plan-only",
+ "oldContainer": "3cefe8519dd3",
+ "oldImageId": "sha256:57ddfdd0b33583f215238738954ee703fc437c11029292f58ecf13d44b790cf7",
+ "preparedComposeSha256": "3531da30d755e97a5e027efaa64f0f5d426eb83e7f03665a811a011a5142482a",
+ "rawCompose": {
+ "services": {
+ "telemetry-hub": {
+ "cap_drop": [
+ "ALL"
+ ],
+ "cpus": 0.5,
+ "environment": {
+ "TELEMETRY_HUB_BIND_HOST": "100.69.77.26",
+ "TELEMETRY_HUB_CONFIG_FILE": "/run/secrets/telemetry-hub.json"
+ },
+ "image": "usage-monitor-telemetry-hub:80f0c92708a21a8a41c4e831187b8235f486d511",
+ "init": true,
+ "labels": {
+ "telemetry.commit": "80f0c92708a21a8a41c4e831187b8235f486d511",
+ "telemetry.task": "UM-1646"
+ },
+ "mem_limit": "512m",
+ "network_mode": "host",
+ "pull_policy": "never",
+ "read_only": true,
+ "restart": "unless-stopped",
+ "security_opt": [
+ "no-new-privileges:true"
+ ],
+ "tmpfs": [
+ "/tmp:rw,noexec,nosuid,size=16m"
+ ],
+ "volumes": [
+ "journal:/data",
+ {
+ "read_only": true,
+ "source": "/mnt/fleet-extra/apps/telemetry-hub/config.json",
+ "target": "/run/secrets/telemetry-hub.json",
+ "type": "bind"
+ }
+ ]
+ }
+ },
+ "volumes": {
+ "journal": {
+ "name": "usage-monitor-telemetry-hub-journal"
+ }
+ }
+ },
+ "rawComposeSha256": "a2a022132849a439c9463d4271b447f2525d5c927fa910d4bcd5fc11670e80b3",
+ "runtimeChanges": false,
+ "service": {
+ "environment_uuid": "tmrwg4denz09sb6qn9rlvjfu",
+ "image_id": "sha256:57ddfdd0b33583f215238738954ee703fc437c11029292f58ecf13d44b790cf7",
+ "project_uuid": "l11qegr5vie93o7dqlfjgd6n",
+ "server_uuid": "jxzqcs3h6g1wiipnnblhismp",
+ "source_commit": "80f0c92708a21a8a41c4e831187b8235f486d511",
+ "status": "exited",
+ "uuid": "a4tp0kk9jmfibzvbmsxvmtqg"
+ },
+ "serviceStatus": "running:healthy",
+ "targetCommit": "0a92fcfa39f5b576f498dabc43963c89c47b3713",
+ "targetImageId": "sha256:ebb8ef80a94380e00003db983f02768432a907338dc0d56d55fa863f6d8d3cca",
+ "upgradeContract": "Build before stop; recheck live compose/image/config and zero pending bytes before one stop; preserve current compose except image/telemetry.commit; same service/volume/config; inspect unknown outcomes before any retry"
+}
diff --git a/.um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-repin.claim.json b/.um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-repin.claim.json
new file mode 100644
index 00000000..78ae743c
--- /dev/null
+++ b/.um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-repin.claim.json
@@ -0,0 +1 @@
+{"phase":"repin","planSha256":"7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0","state":"claimed"}
diff --git a/.um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-repin.receipt.json b/.um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-repin.receipt.json
new file mode 100644
index 00000000..b3752158
--- /dev/null
+++ b/.um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-repin.receipt.json
@@ -0,0 +1 @@
+{"patchResponseKeys":["domains","uuid"],"phase":"repin","planSha256":"7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0","sourceComposeSha256":"a2a022132849a439c9463d4271b447f2525d5c927fa910d4bcd5fc11670e80b3","state":"verified","targetComposeSha256":"fea37a775358138172142ec918a1ac734c8a54fb8ae811fdd5a4aa4a6778b226","targetImageId":"sha256:ebb8ef80a94380e00003db983f02768432a907338dc0d56d55fa863f6d8d3cca"}
diff --git a/.um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-start.claim.json b/.um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-start.claim.json
new file mode 100644
index 00000000..c5b8ee17
--- /dev/null
+++ b/.um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-start.claim.json
@@ -0,0 +1 @@
+{"phase":"start","planSha256":"7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0","state":"claimed"}
diff --git a/.um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-start.receipt.json b/.um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-start.receipt.json
new file mode 100644
index 00000000..1698b4ff
--- /dev/null
+++ b/.um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-start.receipt.json
@@ -0,0 +1 @@
+{"configSha256":"4de53644a6cfc8bc79af1c2f7da1b6b52c1db19fbd8bc806920e30ce6b671579","configSourceSha256":"e9af6bf66c5c9f1b47bec8fe3ede0364166c9812a4d30ad926aa3eefb78678f5","containerHealth":"starting","containerId":"420311a137b2","phase":"start","planSha256":"7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0","startResponseKeys":["message"],"state":"started","targetComposeSha256":"fea37a775358138172142ec918a1ac734c8a54fb8ae811fdd5a4aa4a6778b226","targetImageId":"sha256:ebb8ef80a94380e00003db983f02768432a907338dc0d56d55fa863f6d8d3cca","volumeNameSha256":"fe26f0d3dfb73e4a5712a1ec3c0f9635ca0ec6374feb9af2eedfce4f06899170"}
diff --git a/.um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-stop.claim.json b/.um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-stop.claim.json
new file mode 100644
index 00000000..270d3edd
--- /dev/null
+++ b/.um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-stop.claim.json
@@ -0,0 +1 @@
+{"phase":"stop","planSha256":"7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0","state":"claimed"}
diff --git a/.um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-stop.independent-readback.json b/.um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-stop.independent-readback.json
new file mode 100644
index 00000000..3e61c527
--- /dev/null
+++ b/.um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-stop.independent-readback.json
@@ -0,0 +1 @@
+{"configMode":384,"configSha256":"4de53644a6cfc8bc79af1c2f7da1b6b52c1db19fbd8bc806920e30ce6b671579","configUid":10001,"durableVolumePreserved":true,"independentReadOnlyVerification":true,"oldContainerRemoved":true,"originalReceiptSha256":"cc04293b6477ccc8772d21c86c3e6206cd11b227b8f99966924f02edb99d2ee5","phase":"stop","planSha256":"7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0","privatePortFree":true,"serviceStopped":true,"state":"verified"}
diff --git a/.um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-stop.receipt.json b/.um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-stop.receipt.json
new file mode 100644
index 00000000..a75b3055
--- /dev/null
+++ b/.um1651-hub-upgrade-7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0-stop.receipt.json
@@ -0,0 +1 @@
+{"containerId":"3cefe8519dd3","phase":"stop","planSha256":"7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0","reason":"docker_command_failed","state":"verification_failed"}
diff --git a/.um1651-hub-upgrade-80f0c92708a21a8a41c4e831187b8235f486d511.plan.json b/.um1651-hub-upgrade-80f0c92708a21a8a41c4e831187b8235f486d511.plan.json
new file mode 100644
index 00000000..b6908313
--- /dev/null
+++ b/.um1651-hub-upgrade-80f0c92708a21a8a41c4e831187b8235f486d511.plan.json
@@ -0,0 +1,107 @@
+{
+ "configMountSource": "/mnt/fleet-extra/apps/telemetry-hub/config.json",
+ "currentCompose": {
+ "services": {
+ "telemetry-hub": {
+ "cap_drop": [
+ "ALL"
+ ],
+ "container_name": "telemetry-hub-a4tp0kk9jmfibzvbmsxvmtqg",
+ "cpus": 0.5,
+ "env_file": [
+ ".env"
+ ],
+ "environment": {
+ "COOLIFY_APP_NAME": "usage-monitor-telemetry-hub",
+ "COOLIFY_CONTAINER_NAME": "telemetry-hub-a4tp0kk9jmfibzvbmsxvmtqg",
+ "COOLIFY_ENVIRONMENT_NAME": "production",
+ "COOLIFY_PROJECT_NAME": "Fleet Infra",
+ "COOLIFY_RESOURCE_UUID": "a4tp0kk9jmfibzvbmsxvmtqg",
+ "COOLIFY_SERVER_IP": "host.docker.internal",
+ "SERVICE_NAME_TELEMETRY_HUB": "telemetry-hub",
+ "TELEMETRY_HUB_BIND_HOST": "100.69.77.26",
+ "TELEMETRY_HUB_CONFIG_FILE": "/run/secrets/telemetry-hub.json"
+ },
+ "image": "usage-monitor-telemetry-hub:80f0c92708a21a8a41c4e831187b8235f486d511",
+ "init": true,
+ "labels": [
+ "telemetry.task=UM-1646",
+ "telemetry.commit=80f0c92708a21a8a41c4e831187b8235f486d511",
+ "coolify.managed=true",
+ "coolify.version=4.5.3",
+ "coolify.serviceUuid=a4tp0kk9jmfibzvbmsxvmtqg",
+ "coolify.type=service",
+ "coolify.name=telemetry-hub-a4tp0kk9jmfibzvbmsxvmtqg",
+ "coolify.resourceName=usage-monitor-telemetry-hub",
+ "coolify.projectName=fleet-infra",
+ "coolify.serviceName=telemetry-hub",
+ "coolify.environmentName=production",
+ "coolify.pullRequestId=0",
+ "coolify.service.subUuid=s4oqyz6lbb0yn6kg4sljaonk",
+ "coolify.service.subType=application",
+ "coolify.service.subName=telemetry-hub"
+ ],
+ "mem_limit": "512m",
+ "network_mode": "host",
+ "pull_policy": "never",
+ "read_only": true,
+ "restart": "unless-stopped",
+ "security_opt": [
+ "no-new-privileges:true"
+ ],
+ "tmpfs": [
+ "/tmp:rw,noexec,nosuid,size=16m"
+ ],
+ "volumes": [
+ "a4tp0kk9jmfibzvbmsxvmtqg_journal:/data",
+ {
+ "bind": {
+ "create_host_path": true
+ },
+ "read_only": true,
+ "source": "/mnt/fleet-extra/apps/telemetry-hub/config.json",
+ "target": "/run/secrets/telemetry-hub.json",
+ "type": "bind"
+ }
+ ]
+ }
+ },
+ "volumes": {
+ "a4tp0kk9jmfibzvbmsxvmtqg_journal": {
+ "name": "a4tp0kk9jmfibzvbmsxvmtqg_journal"
+ },
+ "journal": {
+ "name": "usage-monitor-telemetry-hub-journal"
+ }
+ }
+ },
+ "currentComposeSha256": "7c7cc57899ca52c31fe6842b0fd7660565d6a6865e29f1435dd378f04a38124b",
+ "durableVolume": "a4tp0kk9jmfibzvbmsxvmtqg_journal",
+ "metadata": {
+ "configMode": 384,
+ "configSha256": "4de53644a6cfc8bc79af1c2f7da1b6b52c1db19fbd8bc806920e30ce6b671579",
+ "configUid": 10001,
+ "journalBase": 33388798,
+ "journalBytes": 12891238,
+ "pendingBytes": 0,
+ "sentryOffset": 46280036
+ },
+ "mode": "plan-only",
+ "oldContainer": "3cefe8519dd3",
+ "oldImageId": "sha256:57ddfdd0b33583f215238738954ee703fc437c11029292f58ecf13d44b790cf7",
+ "preparedComposeSha256": "3531da30d755e97a5e027efaa64f0f5d426eb83e7f03665a811a011a5142482a",
+ "runtimeChanges": false,
+ "service": {
+ "environment_uuid": "tmrwg4denz09sb6qn9rlvjfu",
+ "image_id": "sha256:57ddfdd0b33583f215238738954ee703fc437c11029292f58ecf13d44b790cf7",
+ "project_uuid": "l11qegr5vie93o7dqlfjgd6n",
+ "server_uuid": "jxzqcs3h6g1wiipnnblhismp",
+ "source_commit": "80f0c92708a21a8a41c4e831187b8235f486d511",
+ "status": "exited",
+ "uuid": "a4tp0kk9jmfibzvbmsxvmtqg"
+ },
+ "serviceStatus": "running:healthy",
+ "targetCommit": "80f0c92708a21a8a41c4e831187b8235f486d511",
+ "targetImageId": "sha256:57ddfdd0b33583f215238738954ee703fc437c11029292f58ecf13d44b790cf7",
+ "upgradeContract": "Build before stop; recheck live compose/image/config and zero pending bytes before one stop; preserve current compose except image/telemetry.commit; same service/volume/config; inspect unknown outcomes before any retry"
+}
diff --git a/.um1651-kody-trigger.txt b/.um1651-kody-trigger.txt
new file mode 100644
index 00000000..1ea16be4
--- /dev/null
+++ b/.um1651-kody-trigger.txt
@@ -0,0 +1 @@
+@kody start-review
diff --git a/.um1651-main-merge-publish-receipt.json b/.um1651-main-merge-publish-receipt.json
new file mode 100644
index 00000000..c5f1b998
--- /dev/null
+++ b/.um1651-main-merge-publish-receipt.json
@@ -0,0 +1 @@
+{"phase": "prepared", "localHead": "276ba0e955b255a445282a44072b22af0e50c6d6", "remoteHead": "d5441d9b500d553f096d8beac9c9340e4aaf38b7", "mainHead": "5c218189851cbc44dfc7271e3879cda8b481d446", "expectedTree": "b0effe5d5afb89f68a7f382a1e92bdccf85b95e1"}
diff --git a/.um1651-relay-publication-3b7884b09665.json b/.um1651-relay-publication-3b7884b09665.json
new file mode 100644
index 00000000..723af189
--- /dev/null
+++ b/.um1651-relay-publication-3b7884b09665.json
@@ -0,0 +1 @@
+{"result": {"content": [{"type": "text", "text": "{\"branch\":\"codex/um1646-sentry-partial-ack\",\"commit\":\"5a101cd4476aac39c3050f9974e69dd16270d64c\",\"files\":4}"}], "structuredContent": {"branch": "codex/um1646-sentry-partial-ack", "commit": "5a101cd4476aac39c3050f9974e69dd16270d64c", "files": 4}}, "jsonrpc": "2.0", "id": 2}
\ No newline at end of file
diff --git a/.um1651-relay-publication-d650a1cb95bb.json b/.um1651-relay-publication-d650a1cb95bb.json
new file mode 100644
index 00000000..cecaeb87
--- /dev/null
+++ b/.um1651-relay-publication-d650a1cb95bb.json
@@ -0,0 +1 @@
+{"result": {"content": [{"type": "text", "text": "{\"branch\":\"codex/um1646-sentry-partial-ack\",\"commit\":\"d5441d9b500d553f096d8beac9c9340e4aaf38b7\",\"files\":3}"}], "structuredContent": {"branch": "codex/um1646-sentry-partial-ack", "commit": "d5441d9b500d553f096d8beac9c9340e4aaf38b7", "files": 3}}, "jsonrpc": "2.0", "id": 2}
\ No newline at end of file
diff --git a/.um1651-relay-publication-receipt.json b/.um1651-relay-publication-receipt.json
new file mode 100644
index 00000000..6a1c82d8
--- /dev/null
+++ b/.um1651-relay-publication-receipt.json
@@ -0,0 +1 @@
+{"result": {"content": [{"type": "text", "text": "{\"branch\":\"codex/um1646-sentry-partial-ack\",\"commit\":\"d2cdc5deabed446a8dd163ed80dca6179506e03b\",\"files\":5}"}], "structuredContent": {"branch": "codex/um1646-sentry-partial-ack", "commit": "d2cdc5deabed446a8dd163ed80dca6179506e03b", "files": 5}}, "jsonrpc": "2.0", "id": 2}
\ No newline at end of file
diff --git a/HANDOFF-UM-1646-2026-11-03.md b/HANDOFF-UM-1646-2026-11-03.md
new file mode 100644
index 00000000..4e8eab5b
--- /dev/null
+++ b/HANDOFF-UM-1646-2026-11-03.md
@@ -0,0 +1,98 @@
+# UM-1646 Telemetry Completion Audit
+
+Private operational evidence. Do not commit or publish this file. Updated November 3 at 6:05 AM; work remains active.
+
+## Authority And Coordination
+
+Owner requested reconciliation and completion of the October handoff, current fleet protocols, app changes and economical subagents. Earlier explicit approvals cover scoped ingest-token rotation, reviewed historical cleanup, server hub activation and BotFleet update/restart. Preserve startup policy, active work, uncertain telemetry and existing access routes. No new model request or paid fallback is authorized by the screenshot.
+
+Full chat: `01a18e51-51e1-7093-9269-0901397a9ec1`. Linear UM-1646 remains claimed CODEX/In Progress. Work topic: `UM-1614 Telemetry for AI platforms`; resumption post637159462, correction637160564, evidence637161137. Check inbox without moving sibling cursors and relevant work every 2–3 minutes while peers share the repo, otherwise every 15 minutes, plus turn boundaries.
+
+CODEX whoami and Linear viewer verified. Policy topics enumerated after installed checkpoint636105695; only two have newer messages, both fully read. Owner1211974/human:636359797 permits purpose-built automated alert bots while agent identities send judged messages;637100341 says close unwanted/superseded PRs and draft work that must wait. Read the November 2 Mac/server runbook from the owner-provided FleetLink URL. Use assigned own Relay tools; their presence does not establish an allowed operation. Exact Kody trigger is `@kody start-review`; a local review is not a platform-trigger substitute.
+
+BF-2606 recovery is owned by a DIFFERENT CODEX chat, `01a18e51-fa5e-77a3-8d7b-b5baa414ab98`, which explicitly resumed its original handoff. Its lane is `codex-bf-2606-resume-20261103`. Ownership acknowledged in637159872; fresh metadata supplied in637160946. Do not interleave runtime/updater changes. BF-2621 and AFC-599 are other active sibling handoff audits; preserve their scopes.
+
+## Fresh Runtime And Receipt Evidence
+
+- Fetched Usage Monitor main and live health/strict readiness agree on `23fa597184b68d34dad9c23de1deb2248e5caa60`; both HTTP200/ok, strict ready. Coolify running healthy, auto-deploy on, exact child-drop flag absent/off, last deployments finished. Current-container bounded log read:365 lines, no unhandled ingest failures, explicit writer-busy, createMany or timeout markers. This samples the current container, not every historical restart.
+- The server hub is healthy at reviewed `80f0c92708a21a8a41c4e831187b8235f486d511`, UID10001, read-only root/configuration, preserved named volume, no published ports, restart count zero. Both hosts'54 installed `.mjs` files match that reviewed revision. Existing Infisical-source snapshot fallback remains; no new machine identity or bootstrap change.
+- All observed durable collector outboxes have zero pending/quarantine. Server Codex60,100 sent, MiniMax24,055, BotFleet94, OpenCode2; Mac Codex10,251, MiniMax6,176, BotFleet166. The earlier Codex backlog has drained.
+- Complete paginated Sentry24-hour query: MiniMax/server21,927 logs, Codex/server7,606 logs, Codex/Mac194 logs; one native BotFleet/server span. No current Claude/OpenCode/Mac MiniMax rows in this query. Mac native scan has zero in-window completions and6,754 retained older completions; server scan has one in-window turn. Empty windows are not proof of application-wide inactivity.
+- Seven-day Usage Monitor BotFleet audit:158 rows, one page, no more pages. One server row has childSessionId/childHarness/turnStartedAt;157 Mac rows lack these. None carries authoritative billed-call proof. Do not enable exact suppression from aggregate/Sentry evidence.
+- Fresh non-writing invalid-body credential probes: old Claude token401, replacement400 (auth accepted, invalid body). Server scoped Claude custody matches Mac settings' metrics credential; only key names/comparison results were emitted. No secret value was printed or changed.
+- Mac installed bundle reports1.0.2304; owner-authenticated running source harness reports1.0.31, dirty source/all-zero commit,22 active items, safeToRestart=false. Actual startup-disabled marker exists; stopped marker absent. Earlier helper used the wrong marker basename, so its false booleans are invalid. Linux owner-authenticated runtime remains clean `c1b956d`, ready and idle. Updater status/null fields do not establish that no external updater exists.
+
+## Completed Historical Work
+
+Protected apply and independent verification receipts confirm all201,252 indexed cleanup candidates deleted across2,013 shards with matching tombstones, zero keeper failures and zero missing receipts. That approved set is complete. Separate4,317 keeper-absent candidates and548 older rollup groups remain preserved; no exact membership proof authorizes deleting them. Any additional deletion needs recovered original membership, unchanged candidate fingerprints, a current exact keeper, a newly reviewed plan/digest and backup assessment. Never infer candidate identities from tombstones.
+
+Server replay receipt:178,142 received,35,115 persisted, zero rejected, six recovered503s. Frozen Oct22–30 before/after cache-read receipts show combined+61,944 rows/+14,742,815,925 tokens. The named retained Mac receipt was subsequently read independently and confirms187,117 received,45,583 persisted, zero rejected. It remains in the installed Mac collector root as `.um-1646-historical-replay-receipt.json`; no replay was repeated.
+
+Full pre-cleanup backup SHA256 `4f523f1192263ee4419ef9d0499737223922f62eb2e771c02d52f70bbd6e16e6`; approved index SHA256 `9794dc8a7b6d0501ec13f077a0028f42fb2a523c6f0d0b030019a7bd57627b0f`; master digest `73639d15cc22f9ce478a9bef9b38b18f188e0fe7a8ffbb7c3eb4209895bbc8c3`. Preserve all backup/source/proof/receipt files and old Mac collector backup.
+
+## Concrete Remaining Source Gap
+
+The successful historical BotFleet child call is in `/mnt/fleet-extra/apps/botfleet-server/home/.local/share/opencode/opencode.db`, matched by exact native session ID in session_v2. It is absent from both session tables in the scheduled standalone source `/home/jay/.local/share/opencode/opencode.db`. Existing collector already supports session_v2; the initial legacy-only diagnosis was corrected publicly.
+
+One completed call reports9,414 input,2 output,512 cache-read tokens. Native BotFleet aggregate matches input/output but does not report cache; missing cache is not zero and must remain additive. No new model call was sent. Profile proof: `/tmp/um1646-botfleet-profile-audit-20261103.json`.
+
+Worker has a reviewed three-file patch in `codex-um1646-current-coverage`: optional `OPENCODE_ADDITIONAL_DBS_JSON`, at most eight explicit additional absolute paths; preserve ordinary source, event IDs, shared frozen project attribution; physical aliases and identical events dedupe; disagreement/unavailable sources keep checkpoint. Seven real SQLite fixture tests and existing collector-runtime gate passed. Parent source review found no correctness issue. Commit/publication, complete review/CI, merge, source-of-truth configuration, installed-byte verification and bounded child replay remain pending at this timestamp. No production source configuration changed yet.
+
+## Other Gaps Checked
+
+Current CI explicitly executes parser, native telemetry and collector-runtime suites. MiniMax exact session/workspace join, OpenCode non-token correlation, native OTLP launcher allowlist and authenticated exact-call receiver gate all exist. Generic/native timing suppression is disabled; missing proof stays additive.
+
+Muse quota collector is loaded, last exit zero; it intentionally has no checkpoint, so that absence is expected. Current native Muse store activity exists, but the quota collector is not evidence of native Sentry coverage. New Usage Monitor PR1862 supplies CodeCaps Muse session-delta burn reads; those deltas remain estimated floors, not an exact per-turn ledger. Retention/owner-expense and usage-event read-auth changes landed in1863; naming changes1866/1868 preserve unrelated work.
+
+The old Mac Claude Sentry-only24-hour plan/artifacts are gone. Complete historical Sentry query covering October29–30 found no Claude hub spans/logs. Retained Mac Claude source root exists (5,380 files); mtimes alone do not prove event membership. A new fixed-window metadata-only plan is being prepared for parent review, without Usage Monitor credentials, source/checkpoint writes or network during planning. No Sentry catch-up has been applied in this resumed work.
+
+## Evidence Locations
+
+- `/tmp/um-1646-ops/cleanup-apply-approved-receipt.json`, `cleanup-verify-receipt.json`, `historical-server-replay-receipt.json`, `cache-read-before-receipt.json`, `cache-read-after-receipt.json`.
+- `/tmp/um1646-current-server-metadata.json`, `um1646-current-mac-metadata.json`, `um1646-current-receipts.json`, `um1646-current-native-receipts.json`.
+- Parent lane helpers `audit-runtime-metadata.py`, `sentry-historic-claude-receipts.audit.py`, `claude-retained-source-metadata.audit.py`; all read-only/count-only.
+- `/tmp/um1646-root-status.md` is verbose historical context with superseded paragraphs. The original October30 handoff lane/file was pruned; do not treat its former link as an extant artifact.
+
+## Delivery Since The Initial Audit
+
+PR1869 merged `ca19ad6ab8e98b5ac506d75d15b72dd0b9cd9015`; PR1870 merged `3fe32891b266e39d1d9d37747b3168b3a1f830ca`. All three real findings were fixed/evidenced/resolved: missing implicit primary, blocked default parent and invalid Date-domain timing. Final merged composition passed52/52 Node tests and the runtime-update gate with8/8 profile fixtures. PR1870 had full current-head Kody approval. PR1869 completed two earlier reviews; its third run reported no findings but its custom fleet-recall agent timed out without a result. Root inspected the actual check detail, recorded the owner's limited additional-request waiver in6603022951 and used the guarded Relay merge. Do not call that partial review a clean approval.
+
+All source publications/merges used Relay. A repeated exact review request returned a cached old comment; the alternate workflow-comment route refused. Only the exact new-head trigger6602862622 used the owner's explicit `gh` exception for THIS chat. This exception does not apply to future chats. PRs are attached to this chat.
+
+Root-reviewed final collector install plan: `/tmp/um1646-reviewed-collector-install-ca19ad6ab8e9.plan.json`, SHA256 `e6f94295aea59a049b7002713822100a28ba46ecb2f4f029b420374606bb1c45`. Both complete55-file inventories, baseline hashes and Node22/24/26 guarded imports passed. Exactly two selected files change: OpenCode entry and Sentry bridge.
+
+The ONE approved apply stopped inside the server step before Mac apply. Fresh failure audit proves all55 server code files now match the reviewed release, but VERSION remains the old80f0c927 bytes. Mac remains entirely at the old baseline with no new backup. Server's private code-only backup has56 entries/675,840 bytes, mode0600, SHA256 `251dc9a47acb27dce79093700ec61cf0876f89d52fb12d87c1a1ac2141b9b113`; all original code/VERSION bytes verified. Original inner phase/error was not retained. Do not guess its cause or retry the old baseline-only apply. Worker is preparing a separately reviewed server VERSION completion plan with syntax/import witnesses and improved safe phase diagnostics for the later Mac step. No config, launcher, hub or checkpoint was changed by this install.
+
+Historical Claude catch-up remains HELD. Independent review reproduced an inherited zero-duration fabrication across collector→hub. PR1870 fixes this by delivering unknown-duration calls as metadata logs, retaining genuine measured spans including zero; legacy durable payloads remain unchanged. The private catch-up helper is now a v3 draft with delivery endpoint/state-root digest binding, fixed Oct29–30 6:32:30 PM window, and call-marker counts based on `chat` rather than span kind. Its commit placeholder deliberately prevents execution until the reviewed install completes. Regenerate/read/review the new exact plan before any Sentry-only apply; do not apply the old point-span plan.
+
+AFC-600/UM-1648 asked active consumers to hold new shared-Automation writes while a scoped replacement route is established. Root acknowledged this in637165902. The new OpenCode source setting is staged only; no source-of-truth or local setting write occurred. Existing bootstrap paths are preserved. The private config helper now requires a verified reviewed install, original private custody backup, exact config digest, source-of-truth readback and local compare-before-replace; its installed SHA remains pending.
+
+Sibling CODEX chat tagged `01a18a45` owns UM-1649; its full ID has not been checked here. Its issue/branch explicitly owns new Z.ai/Kimi coverage, the overall current platform matrix, and the separately discovered direct-UM Codex backlog/Mac missing-token defects. Root's earlier zero-pending claim concerns SENTRY outboxes only. Do not confuse direct UM queues with Sentry delivery. Reservation reply637169284 and clarification637171520 preserve the split; avoid installed collector/hub changes until this installation receipt is complete.
+
+## Installation Completion And Current Pending Work
+
+Server finish succeeded under separately reviewed plan SHA256 `07a87c1f9d5ac52458d946b223e3a0eb73fd508d78d5383bbde91cdc2d11126d`; receipt `/tmp/um1646-finish-server-install-ca19ad6ab8e9.receipt.json`. All55 code bytes, full-sha VERSION, original backup and preserved owner/mode were independently verified;18 entry syntax checks on each Node22/24 and guarded imports passed. Only VERSION was written by that finish step. The original installer failure's exact stderr was lost; root-owned library-directory timestamp metadata is consistent with rsync's preservation constraint, not proof of the original error.
+
+A new Mac-only plan bound original source/host manifests plus a phase-instrumented worker. Plan SHA256 `7888756317928ef25e8c997d5ecc4e343698e9965f3906463822d76d42132557`; helper `/tmp/um1646-mac-only-collector-install.py`. Its ONE approved apply succeeded: `/tmp/um1646-mac-only-install-ca19ad6ab8e9.receipt.json`. All55 files matchca19ad6, truthful VERSION points to the immutable owned source, actual Node26.11.1/24.21.0 guarded imports pass. The56-entry private backup is verified, SHA256 `7a8317de95dcb4cee73f9b8faeeb66b04f1c33c7a49daed73766eebf973cd5c6`. No config, launchers, hub or checkpoints changed; no collector/Muse/security invocation ran during install.
+
+Current receiver is now live and strict-ready onca19ad6, both HTTP200. Its bounded current-container log has no unhandled ingest/createMany/timeout markers. Coolify's deployment is finished, auto-deploy on, exact child-drop flag absent/off.
+
+The v3 private historical Claude helper is staged on the Mac with final sourceca19ad6 and call markers selected by `name=chat`, not kind. A fresh PLAN-ONLY invocation is running/pending collection in tool session47833; no apply GO yet. Read its exact new digest, private deliveryConfiguration and counts, obtain independent final helper review, then authorize only its fixed-window Sentry-only apply. It removes all ingest-token env, blocks token-resolver fallback, freezes argv with --dry-run before entry import, denies network during plan, binds source/identity/endpoint/state-root/selection digests and bounds every drain. Unknown calls must be logs, measured spans0 for this dataset. The old plan/digest is superseded and must not be applied.
+
+BotFleet child worker is preparing a bounded read-only replay plan for the exact proven child DB/session and checking existing `BOTFLEET_WORKSPACES_DIRS` classification. Do not print IDs/titles/bodies. No direct child replay or permanent setting activation is authorized until root reviews its precise plan. Permanent setting remains held for AFC-600's verified scoped write route; config helper's expected install SHA must be set to reviewedca19ad6 before activation.
+
+Later UM-1649 correction637172861: its8,920 server/1,302 Mac pending counts are SENTRY queues after renewed load, not direct UM delivery queues. Server UM ACKs succeed; Mac separately parsed1,618 components then stopped at Missing ingest token. Root's earlier zero-pending receipt is a5:07 AM point-in-time observation. Sibling UM-1649 retains drain-capacity and Mac-token cause work; code reservations released for its TTFT/terminal-status bridge extension on a fresh branch preserving1870. Installed files/hub remain reserved through this finite catch-up. Do not claim queues remain empty without a fresh check.
+
+No memory update was requested or made. Update this handoff after delivery and keep Linear/topic completion boundaries accurate.
+
+## Latest Receipt: Claude Catch-Up Applied Once
+
+The reviewed final v3 plan SHA256 `fc00de07c79d1db4d713dbb10d8f74a2779444bd43502b5377382f2990804b4c` was applied exactly once. Its Mac receipt `/tmp/um1646-sentry-historic-20261103/claude-historic-24h-receipt-v3.json` confirms49,976 token components projected to12,508 unmeasured call logs, zero measured spans, zero Usage Monitor posts, zero checkpoint/source writes. Thirteen bounded drain invocations delivered12,508, quarantined0, final pendingfalse. Do not repeat the apply.
+
+Independent exact-window Sentry queries currently prove5,400 real `claude-code` / `telemetry-hub.mac-claude` chat logs, all without duration_ms, and zero real Claude spans. The fixed window is October29–30 at6:32:30 PM. Four queries completed one page each; canaries excluded, strict pagination binding and ten-page cap. Full12,508 storage is NOT yet proven. Safe evidence `/tmp/um1646-postapply-claude-stored-receipts.json`; worker is checking hub pending/sent metadata and one bounded storage recheck without replay/drain/config changes.
+
+Permanent child source selection requires TWO settings, not just the old draft's one: source-of-truth `OPENCODE_SERVER_ADDITIONAL_DBS_JSON` maps to runtime `OPENCODE_ADDITIONAL_DBS_JSON`, and `BOTFLEET_SERVER_WORKSPACES_DIRS` maps to `BOTFLEET_WORKSPACES_DIRS`. Verified DB/root are documented above. Both settings remain absent; no source-of-truth/local config mutation occurred. Old `configure-opencode-child-source.py` is superseded and MUST NOT execute: it contains the held Automation route. A planning-only two-key replacement is being prepared with no authentication path until AFC-600 establishes scoped custody. Requirement posted637177122.
+
+The exact child replay v3 contains six events: three token components, one context-limit, one model-switch and one session snapshot. The proven root changes only launcher classification, preserving IDs and quantities. Source DB/WAL/frozen project fingerprints are unchanged. A single-attempt apply helper is in preparation; no child apply GO yet. Known existing server env contains the normal USAGE_INGEST_TOKEN and USAGE_MONITOR_INGEST_URL; no new lookup or credential repair is needed for a separately reviewed one-off replay.
+
+Apple Notes handoff create request `um1646-handoff-20261103-v1` is running through the Operator queue, title `[UM, Codex] AI Platforms Telemetry Handoff`. Check request status/readback before calling it saved. No owner action has been requested; the credential dependency is with the active issuer work, not assumed to be the owner's task.
diff --git a/audit-mac-replay-receipt.py b/audit-mac-replay-receipt.py
new file mode 100644
index 00000000..c591b073
--- /dev/null
+++ b/audit-mac-replay-receipt.py
@@ -0,0 +1,23 @@
+"""Read only the named historical replay receipt; expose keys and numeric ACKs."""
+import json
+import subprocess
+
+remote = r'''
+import pathlib,json
+p=pathlib.Path.home()/'apps/usage-monitor-collectors/.um-1646-historical-replay-receipt.json'
+v=json.loads(p.read_text()) if p.is_file() else {}
+allowed={'received','persisted','rejected','duplicates','pruned','attempted','events','batches','http','retryCount','recovered503','recovered502','sentryEnabled','checkpointAdvanced'}
+def counters(value,depth=0):
+ if not isinstance(value,dict) or depth>3:return {}
+ out={}
+ for key,item in value.items():
+ if key in allowed and isinstance(item,(int,bool)):out[key]=item
+ elif isinstance(item,dict):
+ nested=counters(item,depth+1)
+ if nested:out[key]=nested
+ return out
+print(json.dumps({'present':p.is_file(),'keys':sorted(v) if isinstance(v,dict) else [],'counters':counters(v)}))
+'''
+p = subprocess.run(["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=8", "mac", "python3", "-"], input=remote.encode(), capture_output=True, timeout=30)
+if p.returncode: raise SystemExit("Named Mac receipt read failed; no raw output printed")
+print(json.dumps(json.loads(p.stdout)))
diff --git a/audit-runtime-metadata.py b/audit-runtime-metadata.py
new file mode 100644
index 00000000..53f96ce8
--- /dev/null
+++ b/audit-runtime-metadata.py
@@ -0,0 +1,33 @@
+"""Read-only bounded runtime checks; never print log lines or configuration."""
+import datetime
+import json
+import subprocess
+import urllib.request
+from zoneinfo import ZoneInfo
+
+APP = "yagelvqux9e8l1kztif7bf2o"
+result = {"checkedAt": datetime.datetime.now(ZoneInfo("America/Chicago")).strftime("%B %d, %I:%M %p")}
+for endpoint in ("health", "ready?strict=1"):
+ try:
+ req = urllib.request.Request("https://usage.jays.services/api/" + endpoint, headers={"Cache-Control": "no-cache", "User-Agent": "Fleet-Usage-Audit/1"})
+ with urllib.request.urlopen(req, timeout=20) as response:
+ data = json.load(response)
+ safe = {"http": response.status, "ok": data.get("ok"), "status": data.get("status")}
+ revision = data.get("revision")
+ if isinstance(revision, str) and len(revision) == 40 and all(c in "0123456789abcdef" for c in revision):
+ safe["revision"] = revision
+ result[endpoint] = safe
+ except Exception as error:
+ result[endpoint] = {"errorClass": type(error).__name__, "http": getattr(error, "code", None)}
+proc = subprocess.run(["docker", "logs", "--since", "2h", "--tail", "20000", APP], capture_output=True, timeout=30)
+lines = (proc.stdout + proc.stderr).decode("utf-8", errors="replace").splitlines()
+patterns = {
+ "unhandledIngestFailure": "[ingest/usage] unhandled failure",
+ "explicitWriterBusy": "[ingest/usage] SQLite writer busy:",
+ "createMany": "externalUsageEvent.createMany",
+ "operationTimedOut": "Operation has timed out",
+ "genericIngestAdmissionRejection": "receiver_busy",
+}
+result["logs"] = {"exitCode": proc.returncode, "boundedLines": len(lines), "tailCap": 20000,
+ "patternCounts": {name: sum(pattern in line for line in lines) for name, pattern in patterns.items()}}
+print(json.dumps(result))
diff --git a/build-reviewed-hub-image.py b/build-reviewed-hub-image.py
new file mode 100644
index 00000000..b9f25199
--- /dev/null
+++ b/build-reviewed-hub-image.py
@@ -0,0 +1,227 @@
+#!/usr/bin/env python3
+"""Build a telemetry hub image from an exact, reviewed Git commit archive."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import subprocess
+import sys
+import tempfile
+import threading
+from pathlib import Path
+
+
+DOCKERFILE = "deploy/telemetry-hub/Dockerfile"
+IMAGE_NAME = "usage-monitor-telemetry-hub"
+COPY_SOURCES = {
+ "deploy/telemetry-hub/package.json",
+ "deploy/telemetry-hub/package-lock.json",
+ "scripts/telemetry-hub",
+ "scripts/lib/fleet-secrets.mjs",
+}
+REVISION_LABEL = "org.opencontainers.image.revision"
+MAX_LOG_BYTES = 10 * 1024 * 1024
+CHILD_WAIT_SECONDS = 2
+
+
+class Refusal(Exception):
+ pass
+
+
+def stop_child(child: subprocess.Popen[bytes] | None) -> None:
+ if child is None or child.poll() is not None:
+ return
+ try:
+ child.terminate()
+ child.wait(timeout=CHILD_WAIT_SECONDS)
+ except subprocess.TimeoutExpired:
+ child.kill()
+ try:
+ child.wait(timeout=CHILD_WAIT_SECONDS)
+ except subprocess.TimeoutExpired:
+ pass
+ except OSError:
+ try:
+ child.kill()
+ child.wait(timeout=CHILD_WAIT_SECONDS)
+ except (OSError, subprocess.TimeoutExpired):
+ pass
+
+
+def git(repo: Path, *args: str) -> bytes:
+ result = subprocess.run(
+ ["git", *args], cwd=repo, stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL, check=False,
+ )
+ if result.returncode:
+ raise Refusal("git_validation_failed")
+ return result.stdout
+
+
+def run() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--apply", action="store_true", help="build the validated image")
+ parser.add_argument("sha", help="exact merged 40-character commit SHA")
+ args = parser.parse_args()
+
+ sha = args.sha
+ if not re.fullmatch(r"[a-f0-9]{40}", sha):
+ raise Refusal("invalid_sha")
+
+ repo = Path(__file__).resolve().parent
+ git_dir = Path(os.fsdecode(git(repo, "rev-parse", "--show-toplevel")).strip()).resolve()
+ if git_dir != repo:
+ raise Refusal("not_repository_root")
+ git(repo, "cat-file", "-e", f"{sha}^{{commit}}")
+ git(repo, "merge-base", "--is-ancestor", sha, "origin/main")
+
+ dockerfile = git(repo, "show", f"{sha}:{DOCKERFILE}").decode("utf-8")
+ copy_sources = set()
+ for line in dockerfile.splitlines():
+ parts = line.strip().split()
+ if parts and parts[0] == "COPY" and len(parts) >= 3:
+ copy_sources.update(parts[1:-1])
+ if copy_sources != COPY_SOURCES:
+ raise Refusal("unexpected_copy_targets")
+ for source in sorted(COPY_SOURCES):
+ git(repo, "cat-file", "-e", f"{sha}:{source}")
+
+ tree_hash = os.fsdecode(git(repo, "rev-parse", f"{sha}^{{tree}}")).strip()
+ dockerfile_hash = os.fsdecode(git(repo, "rev-parse", f"{sha}:{DOCKERFILE}")).strip()
+ tag = f"{IMAGE_NAME}:{sha}"
+ plan = {
+ "phase": "plan",
+ "commit": sha,
+ "sourceTree": tree_hash,
+ "dockerfileBlob": dockerfile_hash,
+ "copyTargets": sorted(COPY_SOURCES),
+ "imageTag": tag,
+ }
+ if not args.apply:
+ print(json.dumps(plan, sort_keys=True))
+ return 0
+
+ inspect = subprocess.run(
+ ["docker", "image", "inspect", "--format",
+ f'{{{{.Id}}}}\t{{{{index .Config.Labels "{REVISION_LABEL}"}}}}', tag],
+ cwd=repo, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False,
+ text=True,
+ )
+ if inspect.returncode == 0:
+ fields = inspect.stdout.strip().split("\t", 1)
+ if len(fields) != 2 or fields[1] != sha:
+ raise Refusal("existing_tag_revision_mismatch")
+ print(json.dumps({"phase": "existing", "exitCode": 0, "imageId": fields[0],
+ "sourceCommit": sha, "revisionMatches": True}, sort_keys=True))
+ return 0
+
+ log_fd, log_name = tempfile.mkstemp(prefix="usage-monitor-hub-build-", suffix=".log")
+ os.fchmod(log_fd, 0o600)
+ log_path = os.path.abspath(log_name)
+ docker_exit = 1
+ archive_exit = 1
+ archive: subprocess.Popen[bytes] | None = None
+ docker: subprocess.Popen[bytes] | None = None
+ log_reader: threading.Thread | None = None
+ reader_errors: list[str] = []
+ try:
+ with os.fdopen(log_fd, "wb") as log_file:
+ archive = subprocess.Popen(
+ ["git", "archive", "--format=tar", sha], cwd=repo,
+ stdout=subprocess.PIPE, stderr=log_file,
+ )
+ assert archive.stdout is not None
+ docker = subprocess.Popen(
+ ["docker", "build", "--file", DOCKERFILE,
+ "--label", f"{REVISION_LABEL}={sha}", "--tag", tag, "-"],
+ cwd=repo, stdin=archive.stdout, stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ )
+ archive.stdout.close()
+
+ def save_bounded_docker_log() -> None:
+ assert docker.stdout is not None
+ remaining = MAX_LOG_BYTES
+ try:
+ while True:
+ chunk = docker.stdout.read(64 * 1024)
+ if not chunk:
+ break
+ if remaining:
+ kept = chunk[:remaining]
+ try:
+ log_file.write(kept)
+ remaining -= len(kept)
+ except OSError as error:
+ reader_errors.append(type(error).__name__)
+ remaining = 0
+ except OSError as error:
+ reader_errors.append(type(error).__name__)
+ stop_child(docker)
+ finally:
+ docker.stdout.close()
+
+ log_reader = threading.Thread(target=save_bounded_docker_log, daemon=True)
+ log_reader.start()
+ docker_exit = docker.wait()
+ log_reader.join()
+ archive_exit = archive.wait()
+ except Exception as error:
+ stop_child(docker)
+ stop_child(archive)
+ if log_reader is not None and log_reader.is_alive():
+ log_reader.join(timeout=CHILD_WAIT_SECONDS)
+ if docker is not None and docker.stdout is not None:
+ try:
+ docker.stdout.close()
+ except OSError:
+ pass
+ if log_reader is not None and log_reader.is_alive():
+ log_reader.join(timeout=CHILD_WAIT_SECONDS)
+ if archive is not None and archive.stdout is not None:
+ try:
+ archive.stdout.close()
+ except OSError:
+ pass
+ try:
+ os.close(log_fd)
+ except OSError:
+ pass
+ print(json.dumps({"phase": "build", "exitCode": 1,
+ "errorType": type(error).__name__, "logPath": log_path}, sort_keys=True))
+ return 1
+
+ if archive_exit != 0 or docker_exit != 0:
+ print(json.dumps({"phase": "build", "exitCode": docker_exit or archive_exit,
+ "logPath": log_path}, sort_keys=True))
+ return docker_exit or archive_exit
+ if reader_errors:
+ print(json.dumps({"phase": "build", "exitCode": 1,
+ "errorType": reader_errors[0], "logPath": log_path}, sort_keys=True))
+ return 1
+
+ verified = subprocess.run(
+ ["docker", "image", "inspect", "--format",
+ f'{{{{.Id}}}}\t{{{{index .Config.Labels "{REVISION_LABEL}"}}}}', tag],
+ cwd=repo, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False,
+ text=True,
+ )
+ fields = verified.stdout.strip().split("\t", 1) if verified.returncode == 0 else []
+ if len(fields) != 2 or fields[1] != sha:
+ print(json.dumps({"phase": "inspect", "exitCode": 1, "logPath": log_path}, sort_keys=True))
+ return 1
+ print(json.dumps({"phase": "built", "exitCode": 0, "imageId": fields[0],
+ "sourceCommit": sha, "revisionMatches": True,
+ "logPath": log_path}, sort_keys=True))
+ return 0
+
+
+if __name__ == "__main__":
+ try:
+ sys.exit(run())
+ except Refusal as error:
+ print(json.dumps({"phase": "refused", "reason": str(error)}, sort_keys=True))
+ sys.exit(2)
diff --git a/child_config_local_cas.py b/child_config_local_cas.py
new file mode 100644
index 00000000..31ca2503
--- /dev/null
+++ b/child_config_local_cas.py
@@ -0,0 +1,378 @@
+"""Local compare-before-replace coordination guard for two child-source settings."""
+
+from __future__ import annotations
+
+import hashlib
+import os
+import secrets
+import shlex
+import stat
+from dataclasses import dataclass, field
+from pathlib import Path
+
+
+SOURCE = Path("/home/jay/.secrets/usage-monitor.env")
+BACKUP_NAME = "usage-monitor.env.um1646-child-source.before"
+MAX_SOURCE_BYTES = 4 * 1024 * 1024
+DESIRED = {
+ "OPENCODE_ADDITIONAL_DBS_JSON": (
+ '["/mnt/fleet-extra/apps/botfleet-server/home/.local/share/opencode/opencode.db"]'
+ ),
+ "BOTFLEET_WORKSPACES_DIRS": "/mnt/fleet-extra/apps/botfleet-server/data/workspaces",
+}
+
+
+class CASFailure(Exception):
+ """A sanitized refusal; messages contain reason codes only."""
+
+
+@dataclass(frozen=True)
+class Snapshot:
+ source_path: Path
+ content: bytes = field(repr=False)
+ sha256: str
+ device: int
+ inode: int
+ mtime_ns: int
+ size: int
+ uid: int
+ gid: int
+ mode: int
+ key_states: dict[str, str]
+
+
+def _failure(reason: str) -> CASFailure:
+ return CASFailure(reason)
+
+
+def _stat_tuple(value: os.stat_result) -> tuple[int, int, int, int, int, int, int]:
+ return (
+ value.st_dev, value.st_ino, value.st_mtime_ns, value.st_size,
+ value.st_uid, value.st_gid, stat.S_IMODE(value.st_mode),
+ )
+
+
+def _read_fd(fd: int, max_bytes: int) -> bytes:
+ pieces: list[bytes] = []
+ remaining = max_bytes + 1
+ while remaining:
+ block = os.read(fd, min(64 * 1024, remaining))
+ if not block:
+ break
+ pieces.append(block)
+ remaining -= len(block)
+ data = b"".join(pieces)
+ if len(data) > max_bytes:
+ raise _failure("source_too_large")
+ return data
+
+
+def _read_at(
+ parent_fd: int,
+ name: str,
+ *,
+ max_bytes: int,
+ uid: int,
+ gid: int | None = None,
+ mode: int | None = None,
+ owner_only: bool = True,
+) -> tuple[bytes, os.stat_result]:
+ try:
+ before = os.stat(name, dir_fd=parent_fd, follow_symlinks=False)
+ except OSError:
+ raise _failure("file_stat_failed") from None
+ if not stat.S_ISREG(before.st_mode) or before.st_uid != uid:
+ raise _failure("file_type_or_owner_invalid")
+ if gid is not None and before.st_gid != gid:
+ raise _failure("file_group_invalid")
+ actual_mode = stat.S_IMODE(before.st_mode)
+ if (owner_only and actual_mode & 0o077) or (mode is not None and actual_mode != mode):
+ raise _failure("file_mode_invalid")
+ if before.st_size < 0 or before.st_size > max_bytes:
+ raise _failure("source_too_large")
+
+ flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)
+ flags |= getattr(os, "O_NONBLOCK", 0)
+ try:
+ fd = os.open(name, flags, dir_fd=parent_fd)
+ except OSError:
+ raise _failure("file_open_failed") from None
+ try:
+ opened = os.fstat(fd)
+ if not stat.S_ISREG(opened.st_mode) or _stat_tuple(opened) != _stat_tuple(before):
+ raise _failure("file_changed_during_open")
+ data = _read_fd(fd, max_bytes)
+ after_fd = os.fstat(fd)
+ try:
+ after_path = os.stat(name, dir_fd=parent_fd, follow_symlinks=False)
+ except OSError:
+ raise _failure("file_changed_during_read") from None
+ if (_stat_tuple(after_fd) != _stat_tuple(before)
+ or _stat_tuple(after_path) != _stat_tuple(before)
+ or len(data) != before.st_size):
+ raise _failure("file_changed_during_read")
+ return data, before
+ finally:
+ os.close(fd)
+
+
+class ChildConfigLocalCAS:
+ """Read and append only the two approved settings with repeated CAS checks."""
+
+ def __init__(self, source_path: os.PathLike[str] | str = SOURCE) -> None:
+ self.source_path = Path(source_path).absolute()
+ if self.source_path.name != "usage-monitor.env":
+ raise _failure("unexpected_source_name")
+
+ def _open_parent(self) -> int:
+ flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0)
+ flags |= getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)
+ try:
+ return os.open(self.source_path.parent, flags)
+ except OSError:
+ raise _failure("parent_open_failed") from None
+
+ def _parse_states(self, content: bytes) -> dict[str, str]:
+ try:
+ text = content.decode("utf-8")
+ except UnicodeDecodeError:
+ raise _failure("source_encoding_invalid") from None
+ found: dict[str, str] = {}
+ for line in text.splitlines():
+ try:
+ tokens = shlex.split(line, comments=True, posix=True)
+ except ValueError:
+ if any(key in line for key in DESIRED):
+ raise _failure("target_line_invalid") from None
+ continue
+ target_tokens = [
+ token for token in tokens
+ if token in DESIRED or token.partition("=")[0] in DESIRED
+ ]
+ if not target_tokens:
+ continue
+ exported = len(tokens) == 2 and tokens[0] == "export"
+ if ((len(tokens) != 1 and not exported) or len(target_tokens) != 1
+ or "=" not in target_tokens[0]):
+ raise _failure("target_assignment_ambiguous")
+ key, value = target_tokens[0].split("=", 1)
+ if key in found:
+ raise _failure("target_assignment_duplicate")
+ if value != DESIRED[key]:
+ raise _failure("target_assignment_conflict")
+ found[key] = value
+ return {key: "equal" if key in found else "absent" for key in DESIRED}
+
+ def snapshot(self) -> Snapshot:
+ try:
+ parent_fd = self._open_parent()
+ try:
+ data, info = _read_at(
+ parent_fd, self.source_path.name, max_bytes=MAX_SOURCE_BYTES,
+ uid=os.getuid(), owner_only=True,
+ )
+ finally:
+ os.close(parent_fd)
+ except CASFailure:
+ raise
+ except OSError:
+ raise _failure("filesystem_operation_failed") from None
+ states = self._parse_states(data)
+ return Snapshot(
+ source_path=self.source_path,
+ content=data,
+ sha256=hashlib.sha256(data).hexdigest(),
+ device=info.st_dev,
+ inode=info.st_ino,
+ mtime_ns=info.st_mtime_ns,
+ size=info.st_size,
+ uid=info.st_uid,
+ gid=info.st_gid,
+ mode=stat.S_IMODE(info.st_mode),
+ key_states=states,
+ )
+
+ def safePlan(self, snapshot: Snapshot) -> dict[str, object]:
+ self._validate_snapshot_identity(snapshot)
+ return {
+ "sourceSha256": snapshot.sha256,
+ "ownerUid": snapshot.uid,
+ "ownerGid": snapshot.gid,
+ "mode": f"{snapshot.mode:04o}",
+ "keys": dict(snapshot.key_states),
+ "desiredValueSha256": {
+ key: hashlib.sha256(value.encode("utf-8")).hexdigest()
+ for key, value in DESIRED.items()
+ },
+ }
+
+ def _validate_snapshot_identity(self, snapshot: Snapshot) -> None:
+ if not isinstance(snapshot, Snapshot) or snapshot.source_path != self.source_path:
+ raise _failure("snapshot_source_mismatch")
+ if snapshot.uid != os.getuid() or snapshot.mode & 0o077:
+ raise _failure("snapshot_owner_or_mode_invalid")
+ if hashlib.sha256(snapshot.content).hexdigest() != snapshot.sha256:
+ raise _failure("snapshot_hash_invalid")
+ if self._parse_states(snapshot.content) != snapshot.key_states:
+ raise _failure("snapshot_key_state_invalid")
+
+ def _matches_snapshot(self, parent_fd: int, snapshot: Snapshot) -> bool:
+ current, info = _read_at(
+ parent_fd, self.source_path.name, max_bytes=MAX_SOURCE_BYTES,
+ uid=os.getuid(), owner_only=True,
+ )
+ return (
+ hashlib.sha256(current).hexdigest() == snapshot.sha256
+ and current == snapshot.content
+ and info.st_dev == snapshot.device
+ and info.st_ino == snapshot.inode
+ and info.st_mtime_ns == snapshot.mtime_ns
+ and info.st_size == snapshot.size
+ and info.st_uid == snapshot.uid
+ and info.st_gid == snapshot.gid
+ and stat.S_IMODE(info.st_mode) == snapshot.mode
+ )
+
+ def _verify_backup(self, parent_fd: int, snapshot: Snapshot) -> bool:
+ try:
+ backup, info = _read_at(
+ parent_fd, BACKUP_NAME, max_bytes=MAX_SOURCE_BYTES,
+ uid=snapshot.uid, gid=snapshot.gid, mode=0o600,
+ )
+ except CASFailure as error:
+ if str(error) == "file_stat_failed":
+ return False
+ raise
+ if backup != snapshot.content:
+ raise _failure("backup_mismatch")
+ return True
+
+ def prepare_backup(self, snapshot: Snapshot) -> dict[str, object]:
+ self._validate_snapshot_identity(snapshot)
+ parent_fd = self._open_parent()
+ try:
+ if not self._matches_snapshot(parent_fd, snapshot):
+ raise _failure("source_compare_and_swap_failed")
+ if self._verify_backup(parent_fd, snapshot):
+ return {"backup": "verified", "sha256": snapshot.sha256}
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_CLOEXEC", 0)
+ flags |= getattr(os, "O_NOFOLLOW", 0)
+ try:
+ fd = os.open(BACKUP_NAME, flags, 0o600, dir_fd=parent_fd)
+ except OSError:
+ raise _failure("backup_create_failed") from None
+ try:
+ os.fchown(fd, snapshot.uid, snapshot.gid)
+ os.fchmod(fd, 0o600)
+ _write_all(fd, snapshot.content)
+ os.fsync(fd)
+ complete = os.fstat(fd)
+ if (not stat.S_ISREG(complete.st_mode) or complete.st_uid != snapshot.uid
+ or complete.st_gid != snapshot.gid or stat.S_IMODE(complete.st_mode) != 0o600
+ or complete.st_size != snapshot.size):
+ raise _failure("backup_metadata_invalid")
+ except Exception:
+ os.close(fd)
+ raise
+ finally:
+ try:
+ os.close(fd)
+ except OSError:
+ pass
+ os.fsync(parent_fd)
+ backup, info = _read_at(
+ parent_fd, BACKUP_NAME, max_bytes=MAX_SOURCE_BYTES,
+ uid=snapshot.uid, gid=snapshot.gid, mode=0o600,
+ )
+ if backup != snapshot.content or info.st_size != snapshot.size:
+ raise _failure("backup_readback_mismatch")
+ return {"backup": "created_and_verified", "sha256": snapshot.sha256}
+ except CASFailure:
+ raise
+ except OSError:
+ raise _failure("filesystem_operation_failed") from None
+ finally:
+ os.close(parent_fd)
+
+ def apply_local(self, snapshot: Snapshot) -> dict[str, object]:
+ self._validate_snapshot_identity(snapshot)
+ parent_fd = self._open_parent()
+ temp_name: str | None = None
+ temp_identity: tuple[int, int] | None = None
+ try:
+ if not self._matches_snapshot(parent_fd, snapshot):
+ raise _failure("source_compare_and_swap_failed")
+ additions = [
+ f"{key}={shlex.quote(DESIRED[key])}".encode("utf-8")
+ for key, state in snapshot.key_states.items() if state == "absent"
+ ]
+ if not additions:
+ return {"status": "already_equal", "sha256": snapshot.sha256}
+ if not self._verify_backup(parent_fd, snapshot):
+ raise _failure("backup_required")
+ prefix = b"" if not snapshot.content or snapshot.content.endswith(b"\n") else b"\n"
+ updated = snapshot.content + prefix + b"\n".join(additions) + b"\n"
+ temp_name = f".{self.source_path.name}.um1646-{secrets.token_hex(12)}.tmp"
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_CLOEXEC", 0)
+ flags |= getattr(os, "O_NOFOLLOW", 0)
+ try:
+ fd = os.open(temp_name, flags, snapshot.mode, dir_fd=parent_fd)
+ except OSError:
+ raise _failure("temp_create_failed") from None
+ info = os.fstat(fd)
+ temp_identity = (info.st_dev, info.st_ino)
+ try:
+ os.fchown(fd, snapshot.uid, snapshot.gid)
+ os.fchmod(fd, snapshot.mode)
+ _write_all(fd, updated)
+ os.fsync(fd)
+ staged = os.fstat(fd)
+ if (not stat.S_ISREG(staged.st_mode) or staged.st_uid != snapshot.uid
+ or staged.st_gid != snapshot.gid or stat.S_IMODE(staged.st_mode) != snapshot.mode
+ or staged.st_size != len(updated)):
+ raise _failure("temp_metadata_invalid")
+ finally:
+ os.close(fd)
+
+ if not self._matches_snapshot(parent_fd, snapshot):
+ raise _failure("source_compare_and_swap_failed")
+ os.replace(temp_name, self.source_path.name,
+ src_dir_fd=parent_fd, dst_dir_fd=parent_fd)
+ temp_name = None
+ os.fsync(parent_fd)
+ readback, readback_info = _read_at(
+ parent_fd, self.source_path.name, max_bytes=MAX_SOURCE_BYTES,
+ uid=snapshot.uid, gid=snapshot.gid, mode=snapshot.mode,
+ )
+ if readback != updated or readback_info.st_size != len(updated):
+ raise _failure("source_readback_mismatch")
+ states = self._parse_states(readback)
+ if any(state != "equal" for state in states.values()):
+ raise _failure("source_readback_keys_invalid")
+ return {"status": "applied_and_verified", "sha256": hashlib.sha256(updated).hexdigest()}
+ except CASFailure:
+ raise
+ except OSError:
+ raise _failure("filesystem_operation_failed") from None
+ finally:
+ if temp_name is not None and temp_identity is not None:
+ _unlink_owned(parent_fd, temp_name, *temp_identity)
+ os.close(parent_fd)
+
+
+def _write_all(fd: int, content: bytes) -> None:
+ view = memoryview(content)
+ while view:
+ written = os.write(fd, view)
+ if written <= 0:
+ raise _failure("file_write_failed")
+ view = view[written:]
+
+
+def _unlink_owned(parent_fd: int, name: str, device: int, inode: int) -> None:
+ try:
+ current = os.stat(name, dir_fd=parent_fd, follow_symlinks=False)
+ if current.st_dev == device and current.st_ino == inode:
+ os.unlink(name, dir_fd=parent_fd)
+ except OSError:
+ pass
diff --git a/child_config_pair_controller.py b/child_config_pair_controller.py
new file mode 100644
index 00000000..f8709a45
--- /dev/null
+++ b/child_config_pair_controller.py
@@ -0,0 +1,220 @@
+"""Private two-key source-of-truth/CAS controller; no I/O occurs on import."""
+from __future__ import annotations
+
+import hashlib
+import importlib.util
+import json
+import os
+from pathlib import Path
+import re
+import secrets
+import shlex
+import stat
+import subprocess
+import sys
+
+VERIFIED_RELEASE_MESSAGE_ID = 637193996
+VERIFIED_WIRE_MESSAGE_ID = 637192947
+HOLD_MESSAGE_ID = 637192307
+SOURCE_COMMIT = "ca19ad6ab8e98b5ac506d75d15b72dd0b9cd9015"
+ROOT = Path("/mnt/fleet-extra/apps/lanes/Usage-Monitor/codex-um-1646-completion-audit")
+MODULE = ROOT / "child_config_local_cas.py"
+REMOTE_SOURCE = ROOT / "child_config_pair_remote.py"
+REMOTE_STAGED = "/tmp/um1646-child-source-pair/child_config_pair_remote.py"
+PLAN = ROOT / ".um1646-child-pair-plan.json"
+INSTALLED = Path("/mnt/fleet-extra/apps/usage-monitor-collectors")
+MAX_DOCUMENT_BYTES = 128 * 1024
+RELEVANT = (
+ "opencode-usage-collector.mjs", "lib/opencode-session-telemetry.mjs",
+ "lib/run-session-token-collector.mjs", "lib/session-token-collectors.mjs",
+ "lib/collector-sentry-bridge.mjs", "lib/fleet-secrets.mjs",
+ "telemetry-hub/metadata-projection.mjs", "telemetry-hub/allowlist.mjs",
+ "telemetry-hub/sentry-sender.mjs", "telemetry-hub/journal.mjs",
+ "telemetry-hub/internal-event.mjs",
+)
+RUNTIME_DESIRED = {
+ "OPENCODE_ADDITIONAL_DBS_JSON": '["/mnt/fleet-extra/apps/botfleet-server/home/.local/share/opencode/opencode.db"]',
+ "BOTFLEET_WORKSPACES_DIRS": "/mnt/fleet-extra/apps/botfleet-server/data/workspaces",
+}
+
+
+class Refusal(Exception):
+ def __init__(self, code, fields=None):
+ self.code = code
+ self.fields = fields or {}
+
+
+def digest(data):
+ return hashlib.sha256(data).hexdigest()
+
+
+def require_release():
+ if (type(VERIFIED_RELEASE_MESSAGE_ID) is not int or VERIFIED_RELEASE_MESSAGE_ID <= HOLD_MESSAGE_ID
+ or VERIFIED_WIRE_MESSAGE_ID != 637192947):
+ raise Refusal("authorization_route_held")
+
+
+def read_regular(path, maximum, private=False):
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
+ with os.fdopen(fd, "rb") as handle:
+ before = os.fstat(handle.fileno())
+ if not stat.S_ISREG(before.st_mode) or before.st_size > maximum:
+ raise Refusal("document_shape_invalid")
+ if private and (before.st_uid != os.getuid() or stat.S_IMODE(before.st_mode) != 0o600):
+ raise Refusal("private_document_identity_invalid")
+ data = handle.read(maximum + 1)
+ after = os.fstat(handle.fileno())
+ if len(data) > maximum or (before.st_dev, before.st_ino, before.st_mtime_ns, before.st_size) != (after.st_dev, after.st_ino, after.st_mtime_ns, after.st_size):
+ raise Refusal("document_changed_or_exceeded_bound")
+ return data
+
+
+def code_binding():
+ return {"controllerSha256": digest(read_regular(Path(__file__), 256 * 1024)),
+ "remoteSha256": digest(read_regular(REMOTE_SOURCE, 256 * 1024)),
+ "localModuleSha256": digest(read_regular(MODULE, 256 * 1024))}
+
+
+def load_local_module():
+ spec = importlib.util.spec_from_file_location("um1646_child_config_local_cas", MODULE)
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ spec.loader.exec_module(module)
+ if module.DESIRED != RUNTIME_DESIRED:
+ raise Refusal("local_module_key_scope_changed")
+ return module
+
+
+def local_binding(cas, snapshot):
+ return {**cas.safePlan(snapshot), "fileIdentity": {"device": snapshot.device, "inode": snapshot.inode,
+ "mtimeNs": snapshot.mtime_ns, "bytes": snapshot.size}}
+
+
+def installed_binding():
+ hashes = {}
+ for name in RELEVANT:
+ actual = digest(read_regular(INSTALLED / "scripts" / name, 2 * 1024 * 1024))
+ result = subprocess.run(["git", "-C", str(ROOT), "show", SOURCE_COMMIT + ":scripts/" + name], capture_output=True, timeout=20)
+ if result.returncode or actual != digest(result.stdout):
+ raise Refusal("installed_relevant_source_mismatch")
+ hashes[name] = actual
+ return {"sourceCommit": SOURCE_COMMIT, "hashes": hashes}
+
+
+def remote_call(mode, binding, remote_plan=None, root_plan_sha=None):
+ payload = {"releaseMessageId": VERIFIED_RELEASE_MESSAGE_ID, "wireMessageId": VERIFIED_WIRE_MESSAGE_ID,
+ "remoteCodeSha256": binding["remoteSha256"]}
+ if mode == "apply":
+ payload.update(remotePlan=remote_plan, rootPlanSha256=root_plan_sha)
+ command = shlex.join(["python3", REMOTE_STAGED, mode])
+ result = subprocess.run(["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "mac", command],
+ input=json.dumps(payload).encode(), capture_output=True, timeout=390 if mode == "apply" else 180)
+ if len(result.stdout) > MAX_DOCUMENT_BYTES:
+ raise Refusal("remote_result_size_limit")
+ try:
+ value = json.loads(result.stdout)
+ except ValueError:
+ raise Refusal("remote_outcome_unknown_inspect_before_retry") from None
+ if result.returncode or value.get("ok") is not True:
+ reason = value.get("reason")
+ reason = reason if isinstance(reason, str) and re.fullmatch(r"[a-z_]{1,100}", reason) else "unrecognized_remote_refusal"
+ fields = {"remoteReason": reason}
+ names = value.get("fieldNames")
+ if isinstance(names, list) and len(names) <= 120 and all(isinstance(name, str) and re.fullmatch(r"[A-Za-z_][A-Za-z0-9_.\[\]]{0,300}", name) for name in names):
+ fields["fieldNames"] = names
+ raise Refusal("remote_stopped_inspect_before_retry", fields)
+ if mode == "plan" and value.get("remoteCodeSha256") != binding["remoteSha256"]:
+ raise Refusal("remote_code_readback_mismatch")
+ return value
+
+
+def persist(path, value, exclusive=False):
+ data = (json.dumps(value, sort_keys=True, indent=2) + "\n").encode()
+ if len(data) > MAX_DOCUMENT_BYTES:
+ raise Refusal("private_receipt_size_limit")
+ if exclusive:
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
+ with os.fdopen(fd, "wb") as handle:
+ handle.write(data); handle.flush(); os.fsync(handle.fileno())
+ else:
+ temporary = path.with_name(path.name + "." + secrets.token_hex(12) + ".tmp")
+ fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
+ with os.fdopen(fd, "wb") as handle:
+ handle.write(data); handle.flush(); os.fsync(handle.fileno())
+ os.replace(temporary, path)
+ directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
+ try:
+ os.fsync(directory)
+ finally:
+ os.close(directory)
+ return digest(data)
+
+
+def main():
+ mode = sys.argv[1] if len(sys.argv) > 1 else None
+ if mode not in ("plan", "apply") or (mode == "plan" and len(sys.argv) != 2) or (mode == "apply" and len(sys.argv) != 3):
+ raise Refusal("use_plan_or_apply_exact_reviewed_digest")
+ require_release() # Before any production source, custody, SSH or API operation.
+ binding = code_binding()
+ module = load_local_module()
+ cas = module.ChildConfigLocalCAS()
+ snapshot = cas.snapshot()
+ local = local_binding(cas, snapshot)
+ installed = installed_binding()
+ if mode == "plan":
+ remote = remote_call("plan", binding)
+ plan = {"version": 1, "releaseMessageId": VERIFIED_RELEASE_MESSAGE_ID, "wireMessageId": VERIFIED_WIRE_MESSAGE_ID,
+ "code": binding, "local": local, "installed": installed, "remote": remote,
+ "scope": "two-child-source-settings-only"}
+ plan_sha = persist(PLAN, plan, exclusive=True)
+ print(json.dumps({"ok": True, "mode": "plan", "planSha256": plan_sha, "releaseMessageId": VERIFIED_RELEASE_MESSAGE_ID,
+ "sourceSha256": snapshot.sha256, "keyStates": snapshot.key_states, "remoteWrites": False,
+ "localConfigurationWrites": False}))
+ return
+ raw_plan = read_regular(PLAN, MAX_DOCUMENT_BYTES, private=True)
+ if not re.fullmatch(r"[a-f0-9]{64}", sys.argv[2]) or digest(raw_plan) != sys.argv[2]:
+ raise Refusal("exact_reviewed_plan_digest_required")
+ plan = json.loads(raw_plan)
+ if (plan["code"] != binding or plan["local"] != local or plan["installed"] != installed
+ or plan["releaseMessageId"] != VERIFIED_RELEASE_MESSAGE_ID or plan["wireMessageId"] != VERIFIED_WIRE_MESSAGE_ID):
+ raise Refusal("reviewed_plan_binding_changed")
+ receipt_path = ROOT / (".um1646-child-pair-apply-" + sys.argv[2] + ".json")
+ if receipt_path.exists():
+ raise Refusal("prior_attempt_preserved_no_retry")
+ # The private local backup precedes the remote exclusive claim and every POST.
+ backup = cas.prepare_backup(snapshot)
+ receipt = {"rootPlanSha256": sys.argv[2], "releaseMessageId": VERIFIED_RELEASE_MESSAGE_ID,
+ "phase": "local_backup_verified", "backup": backup, "localBefore": local}
+ persist(receipt_path, receipt, exclusive=True)
+ try:
+ canonical = remote_call("apply", binding, plan["remote"], sys.argv[2])
+ except Exception:
+ receipt["phase"] = "remote_outcome_unknown_or_stopped"
+ persist(receipt_path, receipt)
+ raise
+ if canonical.get("sourceOfTruthComplete") is not True:
+ raise Refusal("remote_canonical_completion_unproven")
+ receipt.update(phase="canonical_complete_local_pending", remote=canonical)
+ persist(receipt_path, receipt)
+ if code_binding() != binding or installed_binding() != installed:
+ raise Refusal("canonical_preserved_local_code_or_runtime_changed")
+ result = cas.apply_local(snapshot)
+ after = cas.snapshot()
+ if any(state != "equal" for state in after.key_states.values()) or (after.uid, after.gid, after.mode) != (snapshot.uid, snapshot.gid, snapshot.mode) or not after.content.startswith(snapshot.content):
+ raise Refusal("local_readback_identity_or_preservation_failed")
+ receipt.update(phase="complete", localResult=result, localAfter=local_binding(cas, after), unrelatedBytesPreserved=True)
+ receipt_sha = persist(receipt_path, receipt)
+ print(json.dumps({"ok": True, "mode": "apply", "receiptSha256": receipt_sha, "sourceOfTruthComplete": True,
+ "localReadbackVerified": True, "unrelatedBytesPreserved": True, "changedRuntimeKeys": sorted(RUNTIME_DESIRED),
+ "plistsChanged": False, "credentialMapsChanged": False, "checkpointsChanged": False, "collectorInvoked": False}))
+
+
+if __name__ == "__main__":
+ try:
+ main()
+ except Refusal as error:
+ print(json.dumps({"ok": False, "reason": error.code, **error.fields}))
+ raise SystemExit(1)
+ except Exception as error:
+ print(json.dumps({"ok": False, "reason": "operation_stopped_inspect_before_retry", "errorClass": type(error).__name__}))
+ raise SystemExit(1)
diff --git a/child_config_pair_remote.py b/child_config_pair_remote.py
new file mode 100644
index 00000000..ce9a2be3
--- /dev/null
+++ b/child_config_pair_remote.py
@@ -0,0 +1,378 @@
+"""Private, release-gated two-key controller; token values never leave this process."""
+from __future__ import annotations
+
+import datetime as dt
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import secrets
+import stat
+import sys
+import urllib.error
+import urllib.parse
+import urllib.request
+
+VERIFIED_RELEASE_MESSAGE_ID = 637193996
+VERIFIED_WIRE_MESSAGE_ID = 637192947
+HOLD_MESSAGE_ID = 637192307
+PROJECT = "86e35e51-91bc-4dfd-a045-4484726b9c40"
+ENVIRONMENT = "prod"
+FOLDER = "/telemetry"
+BASE = "https://app.infisical.com"
+MAX_RESPONSE_BYTES = 128 * 1024
+CUSTODY_ROOT = Path("/Users/jay/.config/usage-monitor/infisical-service-tokens")
+CLAIM_ROOT = Path("/Users/jay/.local/state/usage-monitor/um1646-child-config-pair")
+TOKENS = {
+ "read": {"file": "telemetry-read-token", "id": "2da57b07-1bed-4955-85ad-4db24ff60c43", "name": "um-telemetry-read", "expiresAt": "2027-02-01T13:05:31.892Z"},
+ "write": {"file": "telemetry-write-token", "id": "81318b7a-7e2e-41f9-8788-cb0fefa12273", "name": "um-telemetry-write", "expiresAt": "2027-02-01T13:05:32.458Z"},
+}
+DESIRED = {
+ "OPENCODE_SERVER_ADDITIONAL_DBS_JSON": '["/mnt/fleet-extra/apps/botfleet-server/home/.local/share/opencode/opencode.db"]',
+ "BOTFLEET_SERVER_WORKSPACES_DIRS": "/mnt/fleet-extra/apps/botfleet-server/data/workspaces",
+}
+
+
+class Refusal(Exception):
+ def __init__(self, code, fields=None):
+ self.code = code
+ self.fields = fields or {}
+
+
+def digest(value):
+ return hashlib.sha256(value).hexdigest()
+
+
+def encoded(value):
+ return (json.dumps(value, sort_keys=True, separators=(",", ":")) + "\n").encode()
+
+
+def require_release(payload):
+ if (type(VERIFIED_RELEASE_MESSAGE_ID) is not int or VERIFIED_RELEASE_MESSAGE_ID <= HOLD_MESSAGE_ID
+ or VERIFIED_WIRE_MESSAGE_ID != 637192947
+ or payload.get("releaseMessageId") != VERIFIED_RELEASE_MESSAGE_ID
+ or payload.get("wireMessageId") != VERIFIED_WIRE_MESSAGE_ID):
+ raise Refusal("authorization_route_held")
+
+
+def field_names(value, prefix="", depth=0):
+ names = []
+ if depth > 4:
+ return names
+ if isinstance(value, dict):
+ for key, child in list(value.items())[:60]:
+ if isinstance(key, str) and re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]{0,63}", key):
+ path = prefix + "." + key if prefix else key
+ names.append(path)
+ names.extend(field_names(child, path, depth + 1))
+ elif isinstance(value, list):
+ for child in value[:1]:
+ names.extend(field_names(child, prefix + "[]", depth + 1))
+ return sorted(set(names))[:120]
+
+
+def identity(value):
+ if isinstance(value, str):
+ return value
+ if isinstance(value, dict):
+ values = [value[key] for key in ("id", "_id") if key in value]
+ if values and all(isinstance(item, str) and item == values[0] for item in values):
+ return values[0]
+ raise Refusal("explicit_identity_shape_unknown")
+
+
+def assert_explicit_scope(row):
+ for key in ("workspace", "workspaceId", "projectId", "project"):
+ if key in row and identity(row[key]) != PROJECT:
+ raise Refusal("explicit_project_conflict")
+ for key in ("environment", "environmentSlug"):
+ if key in row and row[key] != ENVIRONMENT:
+ raise Refusal("explicit_environment_conflict")
+ for key in ("secretPath", "path"):
+ if key in row and row[key] != FOLDER:
+ raise Refusal("explicit_folder_conflict")
+
+
+def parse_self_metadata(body, role):
+ """Recognize canonical fields only; unknown shape returns field names, never values."""
+ required = {"id", "_id", "name", "workspace", "projectId", "scopes", "permissions", "expiresAt"}
+ if not isinstance(body, dict) or not required.issubset(body):
+ raise Refusal("self_metadata_shape_unknown", {"fieldNames": field_names(body)})
+ row = body
+ expected = TOKENS[role]
+ explicit_ids = {}
+ for key in ("id", "_id"):
+ if key in row:
+ if row[key] != expected["id"]:
+ raise Refusal("self_metadata_id_conflict")
+ explicit_ids[key] = row[key]
+ if row.get("name") != expected["name"]:
+ raise Refusal("self_metadata_name_conflict")
+ if not any(key in row for key in ("workspace", "workspaceId", "projectId", "project")):
+ raise Refusal("self_metadata_project_missing", {"fieldNames": field_names(body)})
+ assert_explicit_scope(row)
+ if row["permissions"] != [role]:
+ raise Refusal("self_metadata_permissions_conflict")
+ scopes = row["scopes"]
+ if not isinstance(scopes, list) or len(scopes) != 1 or not isinstance(scopes[0], dict):
+ raise Refusal("self_metadata_scopes_conflict")
+ scope = scopes[0]
+ if set(scope) != {"environment", "secretPath"}:
+ raise Refusal("self_metadata_scope_fields_unknown", {"fieldNames": field_names(body)})
+ if scope.get("environment") != ENVIRONMENT or scope.get("secretPath") != FOLDER:
+ raise Refusal("self_metadata_scope_shape_or_value_conflict", {"fieldNames": field_names(body)})
+ assert_explicit_scope(scope)
+ if "permissions" in scope and scope["permissions"] != [role]:
+ raise Refusal("self_metadata_scope_permissions_conflict")
+ try:
+ actual_expiry = dt.datetime.fromisoformat(row["expiresAt"].replace("Z", "+00:00"))
+ expected_expiry = dt.datetime.fromisoformat(expected["expiresAt"].replace("Z", "+00:00"))
+ if actual_expiry.tzinfo is None or actual_expiry != expected_expiry or actual_expiry <= dt.datetime.now(dt.timezone.utc):
+ raise ValueError()
+ except (AttributeError, TypeError, ValueError):
+ raise Refusal("self_metadata_expiry_conflict") from None
+ if row.get("isActive") is False or row.get("revoked") is True or row.get("isRevoked") is True:
+ raise Refusal("self_metadata_inactive")
+ verified = {"role": role, "explicitIds": explicit_ids, "nameVerified": True, "projectVerified": True,
+ "singletonPermission": role, "singletonEnvironment": ENVIRONMENT, "singletonFolder": FOLDER,
+ "expiresAt": expected["expiresAt"]}
+ # Usage/updated timestamps are not authorization identity and may change on a read.
+ verified["metadataSha256"] = digest(encoded(verified))
+ return verified
+
+
+def read_token(role, custody_root=None):
+ root = CUSTODY_ROOT if custody_root is None else custody_root
+ parent_fd = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
+ parent_key = lambda value: (value.st_dev, value.st_ino, value.st_uid, value.st_gid, stat.S_IMODE(value.st_mode))
+ try:
+ parent_before = os.fstat(parent_fd)
+ if not stat.S_ISDIR(parent_before.st_mode) or parent_before.st_uid != os.getuid() or stat.S_IMODE(parent_before.st_mode) != 0o700:
+ raise Refusal("custody_directory_identity_invalid")
+ fd = os.open(TOKENS[role]["file"], os.O_RDONLY | os.O_NOFOLLOW, dir_fd=parent_fd)
+ with os.fdopen(fd, "rb") as handle:
+ before = os.fstat(handle.fileno())
+ if not stat.S_ISREG(before.st_mode) or before.st_uid != os.getuid() or stat.S_IMODE(before.st_mode) != 0o600 or not 32 <= before.st_size <= 8192:
+ raise Refusal("custody_file_identity_invalid")
+ raw = handle.read(8193)
+ after = os.fstat(handle.fileno())
+ current = os.stat(TOKENS[role]["file"], dir_fd=parent_fd, follow_symlinks=False)
+ parent_after = os.fstat(parent_fd)
+ parent_path = os.stat(root, follow_symlinks=False)
+ if not stat.S_ISDIR(parent_path.st_mode) or parent_key(parent_before) != parent_key(parent_after) or parent_key(parent_before) != parent_key(parent_path):
+ raise Refusal("custody_directory_changed")
+ finally:
+ os.close(parent_fd)
+ key = lambda value: (value.st_dev, value.st_ino, value.st_mtime_ns, value.st_size, value.st_uid, value.st_gid, stat.S_IMODE(value.st_mode))
+ if key(before) != key(after) or key(before) != key(current) or len(raw) != before.st_size:
+ raise Refusal("custody_file_changed")
+ try:
+ token = raw.decode().strip()
+ except UnicodeDecodeError:
+ raise Refusal("custody_file_encoding_invalid") from None
+ if not re.fullmatch(r"\S{32,8192}", token):
+ raise Refusal("custody_file_shape_invalid")
+ metadata = dict(zip(("device", "inode", "mtimeNs", "bytes", "uid", "gid", "mode"), key(before)))
+ metadata["sha256"] = digest(raw)
+ metadata["parent"] = dict(zip(("device", "inode", "uid", "gid", "mode"), parent_key(parent_before)))
+ return token, metadata
+
+
+def assert_custody_unchanged(expected, custody_root=None):
+ for role in ("read", "write"):
+ # Revalidation never replaces the tokens already captured by Transport.
+ _, current = read_token(role, custody_root=custody_root)
+ if current != expected[role]:
+ raise Refusal("custody_changed_before_create", {"role": role})
+
+
+class NoRedirect(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, *args, **kwargs):
+ return None
+
+
+class Transport:
+ def __init__(self, tokens):
+ self.tokens = tokens
+ self.opener = urllib.request.build_opener(NoRedirect())
+
+ def request(self, role, method, path, body=None):
+ allowed_self = method == "GET" and path == "/api/v2/service-token"
+ raw_paths = {"/api/v3/secrets/raw/" + key for key in DESIRED}
+ parsed = urllib.parse.urlsplit(path)
+ if not (allowed_self or parsed.path in raw_paths and ((role == "read" and method == "GET") or (role == "write" and method == "POST"))):
+ raise Refusal("request_scope_refused")
+ if parsed.scheme or parsed.netloc or parsed.fragment:
+ raise Refusal("request_target_refused")
+ if method == "POST" and (parsed.query or body != {**scope_params(), "secretValue": DESIRED[parsed.path.rsplit("/", 1)[1]]}):
+ raise Refusal("create_body_scope_refused")
+ if not allowed_self and method == "GET" and urllib.parse.parse_qs(parsed.query) != {key: [value] for key, value in scope_params().items()}:
+ raise Refusal("read_query_scope_refused")
+ request = urllib.request.Request(BASE + path, method=method, data=None if body is None else json.dumps(body).encode(), headers={"Authorization": "Bearer " + self.tokens[role], "Content-Type": "application/json", "Accept": "application/json"})
+ try:
+ with self.opener.open(request, timeout=25) as response:
+ raw = response.read(MAX_RESPONSE_BYTES + 1)
+ if len(raw) > MAX_RESPONSE_BYTES:
+ raise Refusal("response_size_limit")
+ try:
+ data = json.loads(raw)
+ except (UnicodeDecodeError, ValueError):
+ raise Refusal("response_json_invalid") from None
+ return response.status, data
+ except urllib.error.HTTPError as error:
+ status = error.code
+ error.close()
+ return status, None
+
+
+def scope_params():
+ return {"workspaceId": PROJECT, "environment": ENVIRONMENT, "secretPath": FOLDER, "type": "shared"}
+
+
+def read_key(transport, key):
+ if key not in DESIRED:
+ raise Refusal("unknown_key_refused")
+ status, body = transport.request("read", "GET", "/api/v3/secrets/raw/" + key + "?" + urllib.parse.urlencode(scope_params()))
+ if status == 404:
+ return {"state": "absent", "valueSha256": None}
+ if status != 200:
+ raise Refusal("raw_read_refused", {"httpStatus": status})
+ if not isinstance(body, dict) or not isinstance(body.get("secret"), dict):
+ raise Refusal("raw_read_shape_unknown", {"fieldNames": field_names(body)})
+ row = body["secret"]
+ if row.get("secretKey") != key or not isinstance(row.get("secretValue"), str):
+ raise Refusal("raw_read_key_or_value_shape_conflict")
+ assert_explicit_scope(body)
+ assert_explicit_scope(row)
+ if row["secretValue"] != DESIRED[key]:
+ raise Refusal("existing_canonical_value_conflict", {"key": key})
+ return {"state": "equal", "valueSha256": digest(DESIRED[key].encode())}
+
+
+def remote_snapshot(transport, custody):
+ metadata = {}
+ for role in ("read", "write"):
+ status, body = transport.request(role, "GET", "/api/v2/service-token")
+ if status != 200:
+ raise Refusal("self_metadata_read_refused", {"role": role, "httpStatus": status})
+ metadata[role] = parse_self_metadata(body, role)
+ return {"custody": custody, "serviceMetadata": metadata, "keys": {key: read_key(transport, key) for key in DESIRED}}
+
+
+def private_json(path, value, exclusive=False):
+ data = encoded(value)
+ if len(data) > MAX_RESPONSE_BYTES:
+ raise Refusal("receipt_size_limit")
+ if exclusive:
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
+ with os.fdopen(fd, "wb") as handle:
+ handle.write(data); handle.flush(); os.fsync(handle.fileno())
+ else:
+ temporary = path.with_name(path.name + "." + secrets.token_hex(12) + ".tmp")
+ fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
+ with os.fdopen(fd, "wb") as handle:
+ handle.write(data); handle.flush(); os.fsync(handle.fileno())
+ os.replace(temporary, path)
+ directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
+ try:
+ os.fsync(directory)
+ finally:
+ os.close(directory)
+ return digest(data)
+
+
+def apply_pair(transport, expected, snapshot, plan_sha, claim_root=CLAIM_ROOT, *, custody_check=None):
+ if snapshot != expected:
+ raise Refusal("remote_plan_compare_and_swap_failed")
+ if not re.fullmatch(r"[a-f0-9]{64}", plan_sha):
+ raise Refusal("root_plan_digest_required")
+ claim_root.mkdir(mode=0o700, parents=True, exist_ok=True)
+ info = claim_root.lstat()
+ if not stat.S_ISDIR(info.st_mode) or stat.S_IMODE(info.st_mode) != 0o700 or info.st_uid != os.getuid():
+ raise Refusal("private_claim_directory_invalid")
+ claim_path = claim_root / "two-key-apply.claim.json"
+ claim = {"version": 1, "rootPlanSha256": plan_sha, "releaseMessageId": VERIFIED_RELEASE_MESSAGE_ID, "wireMessageId": VERIFIED_WIRE_MESSAGE_ID,
+ "phase": "claimed", "keys": {key: {"plannedState": snapshot["keys"][key]["state"], "attempted": False, "postHttpStatus": None, "confirmedCreated": False, "readbackVerified": False} for key in DESIRED}}
+ private_json(claim_path, claim, exclusive=True)
+ # The exclusive claim precedes a fresh reader-only CAS of BOTH keys.
+ current = {key: read_key(transport, key) for key in DESIRED}
+ if current != expected["keys"]:
+ raise Refusal("remote_reader_compare_and_swap_failed")
+ for key in DESIRED:
+ item = claim["keys"][key]
+ if current[key]["state"] == "absent":
+ item.update(attempted=True, status="attempting")
+ private_json(claim_path, claim)
+ try:
+ if custody_check is None:
+ assert_custody_unchanged(expected["custody"])
+ else:
+ custody_check()
+ except Exception:
+ item.update(attempted=False, status="pre_create_custody_refused")
+ private_json(claim_path, claim)
+ raise
+ try:
+ status, body = transport.request("write", "POST", "/api/v3/secrets/raw/" + key, {**scope_params(), "secretValue": DESIRED[key]})
+ except Exception:
+ item["status"] = "outcome_unknown"
+ private_json(claim_path, claim)
+ raise Refusal("create_outcome_unknown", {"key": key}) from None
+ item.update(postHttpStatus=status, status="create_response_received")
+ private_json(claim_path, claim)
+ if status not in (200, 201):
+ raise Refusal("create_refused_or_partial", {"key": key, "httpStatus": status})
+ if not isinstance(body, dict) or not isinstance(body.get("secret"), dict) or body["secret"].get("secretKey") != key:
+ raise Refusal("create_response_identity_unknown", {"key": key})
+ assert_explicit_scope(body)
+ assert_explicit_scope(body["secret"])
+ if "secretValue" in body["secret"] and body["secret"]["secretValue"] != DESIRED[key]:
+ raise Refusal("create_response_value_conflict", {"key": key})
+ if read_key(transport, key)["state"] != "equal":
+ raise Refusal("created_key_readback_failed", {"key": key})
+ item["confirmedCreated"] = True
+ item.update(readbackVerified=True, status="verified_equal")
+ private_json(claim_path, claim)
+ final = {key: read_key(transport, key) for key in DESIRED}
+ if any(row["state"] != "equal" for row in final.values()):
+ raise Refusal("canonical_final_readback_failed")
+ claim["phase"] = "canonical_complete"
+ receipt_sha = private_json(claim_path, claim)
+ return {"sourceOfTruthComplete": True, "keys": claim["keys"], "claimSha256": receipt_sha}
+
+
+def main():
+ payload_raw = sys.stdin.buffer.read(MAX_RESPONSE_BYTES + 1)
+ if len(payload_raw) > MAX_RESPONSE_BYTES:
+ raise Refusal("controller_input_too_large")
+ payload = json.loads(payload_raw)
+ require_release(payload)
+ mode = sys.argv[1] if len(sys.argv) == 2 else None
+ if mode not in ("plan", "apply"):
+ raise Refusal("mode_refused")
+ code_sha = digest(Path(__file__).read_bytes())
+ if payload.get("remoteCodeSha256") != code_sha:
+ raise Refusal("remote_code_changed")
+ token_values = {}
+ custody = {}
+ for role in ("read", "write"):
+ token_values[role], custody[role] = read_token(role)
+ transport = Transport(token_values)
+ snapshot = remote_snapshot(transport, custody)
+ if mode == "plan":
+ print(json.dumps({"ok": True, "remoteCodeSha256": code_sha, "snapshot": snapshot, "remoteWrites": False}))
+ else:
+ result = apply_pair(transport, payload["remotePlan"]["snapshot"], snapshot, payload["rootPlanSha256"])
+ print(json.dumps({"ok": True, **result}))
+
+
+if __name__ == "__main__":
+ try:
+ main()
+ except Refusal as error:
+ print(json.dumps({"ok": False, "reason": error.code, **error.fields}))
+ raise SystemExit(1)
+ except Exception as error:
+ print(json.dumps({"ok": False, "reason": "operation_stopped_inspect_before_retry", "errorClass": type(error).__name__}))
+ raise SystemExit(1)
diff --git a/claude-retained-source-metadata.audit.py b/claude-retained-source-metadata.audit.py
new file mode 100644
index 00000000..ff706052
--- /dev/null
+++ b/claude-retained-source-metadata.audit.py
@@ -0,0 +1,48 @@
+import json
+import os
+import time
+
+
+root = os.path.expanduser("~/.claude/projects")
+result = {
+ "root_exists": os.path.isdir(root),
+ "complete": True,
+ "jsonl_files": 0,
+ "total_bytes": 0,
+ "oldest_age_hours": None,
+ "newest_age_hours": None,
+}
+
+if result["root_exists"]:
+ now = time.time()
+ mtimes = []
+ stack = [root]
+ visited = 0
+ while stack:
+ directory = stack.pop()
+ try:
+ entries = list(os.scandir(directory))
+ except OSError:
+ result["complete"] = False
+ continue
+ for entry in entries:
+ visited += 1
+ if visited > 100000:
+ result["complete"] = False
+ stack.clear()
+ break
+ try:
+ if entry.is_dir(follow_symlinks=False):
+ stack.append(entry.path)
+ elif entry.name.endswith(".jsonl") and entry.is_file(follow_symlinks=False):
+ stat = entry.stat(follow_symlinks=False)
+ result["jsonl_files"] += 1
+ result["total_bytes"] += stat.st_size
+ mtimes.append(stat.st_mtime)
+ except OSError:
+ result["complete"] = False
+ if mtimes:
+ result["oldest_age_hours"] = round(max(0, (now - min(mtimes)) / 3600), 1)
+ result["newest_age_hours"] = round(max(0, (now - max(mtimes)) / 3600), 1)
+
+print(json.dumps(result, sort_keys=True))
diff --git a/configure-opencode-child-source.py b/configure-opencode-child-source.py
new file mode 100644
index 00000000..f4e4e66b
--- /dev/null
+++ b/configure-opencode-child-source.py
@@ -0,0 +1,133 @@
+#!/usr/bin/env python3
+# SUPERSEDED UNSAFE AUTOMATION DRAFT — DO NOT RUN. It includes configuration and local-file writes. Use opencode-child-source-plan.py for plan-only review; it has no apply path.
+"""Guard one non-secret collector setting; credential values never leave custody."""
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import shlex
+import stat
+import subprocess
+import sys
+import tempfile
+
+MODE = sys.argv[1] if len(sys.argv) > 1 else "plan"
+if MODE not in ("plan", "apply"):
+ raise SystemExit("Use plan or apply")
+SOURCE = Path("/home/jay/.secrets/usage-monitor.env")
+PLAN = Path(".um1646-opencode-config-plan.json")
+KEY = "OPENCODE_ADDITIONAL_DBS_JSON"
+INFISICAL_KEY = "OPENCODE_SERVER_ADDITIONAL_DBS_JSON"
+REVIEWED_INSTALL_SHA = "pending-reviewed-merge"
+VALUE = json.dumps(["/mnt/fleet-extra/apps/botfleet-server/home/.local/share/opencode/opencode.db"], separators=(",", ":"))
+digest = lambda value: hashlib.sha256(value).hexdigest()
+fd = os.open(SOURCE, os.O_RDONLY | os.O_NOFOLLOW)
+with os.fdopen(fd, "rb") as handle:
+ info = os.fstat(handle.fileno())
+ if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077:
+ raise SystemExit("Unsafe existing collector configuration")
+ raw = handle.read()
+lines = raw.decode().splitlines(keepends=True)
+matches = [i for i, line in enumerate(lines) if re.match(r"^(?:export\s+)?" + KEY + "=", line)]
+if len(matches) > 1:
+ raise SystemExit("Ambiguous existing setting")
+if matches:
+ existing = shlex.split(lines[matches[0]].split("=", 1)[1], comments=True)
+ if existing != [VALUE]:
+ raise SystemExit("Different existing source selection requires a new reviewed plan")
+if MODE == "plan":
+ plan = {"sourceSha256": digest(raw), "setting": KEY, "sourceOfTruthKey": INFISICAL_KEY, "additionalDatabaseCount": 1, "valueSha256": digest(VALUE.encode()), "alreadyConfigured": bool(matches), "primarySourcePreserved": True}
+ data = (json.dumps(plan, sort_keys=True, indent=2) + "\n").encode()
+ fd = os.open(PLAN, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ with os.fdopen(fd, "wb") as handle: handle.write(data)
+ print(json.dumps({**plan, "planSha256": digest(data), "configurationChanged": False}))
+ raise SystemExit(0)
+data = PLAN.read_bytes()
+if len(sys.argv) != 3 or digest(data) != sys.argv[2]:
+ raise SystemExit("Exact reviewed configuration plan digest required")
+plan = json.loads(data)
+if plan["sourceSha256"] != digest(raw) or plan["valueSha256"] != digest(VALUE.encode()):
+ raise SystemExit("Configuration changed since planning")
+if not re.fullmatch(r"[a-f0-9]{40}", REVIEWED_INSTALL_SHA):
+ raise SystemExit("Reviewed merged collector installation is required before activation")
+installed = Path("/mnt/fleet-extra/apps/usage-monitor-collectors")
+version_match = re.search(r"^sha=([a-f0-9]{7,40})$", (installed / "VERSION").read_text(), re.M)
+if not version_match or not REVIEWED_INSTALL_SHA.startswith(version_match.group(1)):
+ raise SystemExit("Installed collector revision differs from the reviewed merge")
+expected = subprocess.run(["git", "show", REVIEWED_INSTALL_SHA + ":scripts/opencode-usage-collector.mjs"], capture_output=True, check=True).stdout
+if digest((installed / "scripts/opencode-usage-collector.mjs").read_bytes()) != digest(expected):
+ raise SystemExit("Installed collector entry does not match reviewed source")
+backup = SOURCE.with_name(SOURCE.name + ".um-1646-before-opencode-source")
+try:
+ fd = os.open(backup, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
+except FileExistsError:
+ fd = os.open(backup, os.O_RDONLY | os.O_NOFOLLOW)
+ with os.fdopen(fd, "rb") as handle:
+ if handle.read() != raw: raise SystemExit("Existing private backup differs; preserved")
+else:
+ os.fchown(fd, info.st_uid, info.st_gid)
+ with os.fdopen(fd, "wb") as handle:
+ handle.write(raw); handle.flush(); os.fsync(handle.fileno())
+remote = r'''
+import json, subprocess, urllib.request, urllib.error, urllib.parse
+KEY=__KEY__
+VALUE=__VALUE__
+BASE='https://app.infisical.com'
+class NoRedirect(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self,*args,**kwargs):return None
+opener=urllib.request.build_opener(NoRedirect())
+def fleet(name):
+ p=subprocess.run(['fleet-secrets','get',name],capture_output=True,timeout=30)
+ if p.returncode:raise RuntimeError('Scoped credential route unavailable')
+ return p.stdout.decode().strip()
+def request(url,method='GET',body=None,token=None):
+ headers={'Content-Type':'application/json','User-Agent':'Fleet-Collector-Config/1'}
+ if token:headers['Authorization']='Bearer '+token
+ req=urllib.request.Request(url,data=None if body is None else json.dumps(body).encode(),headers=headers,method=method)
+ try:
+ with opener.open(req,timeout=25) as response:return response.status,json.load(response)
+ except urllib.error.HTTPError as error:return error.code,{}
+try:
+ status,body=request(BASE+'/api/v1/auth/universal-auth/login','POST',{'clientId':fleet('INFISICAL_AUTOMATION_CLIENT_ID'),'clientSecret':fleet('INFISICAL_AUTOMATION_CLIENT_SECRET')})
+ if status!=200:raise RuntimeError('Source-of-truth authentication failed')
+ token=body['accessToken']
+ params={'workspaceId':'86e35e51-91bc-4dfd-a045-4484726b9c40','environment':'prod','secretPath':'/telemetry','type':'shared'}
+ url=BASE+'/api/v3/secrets/raw/'+KEY
+ status,body=request(url+'?'+urllib.parse.urlencode(params),token=token)
+ if status==200 and body['secret']['secretValue']!=VALUE:raise RuntimeError('Different existing source-of-truth setting preserved')
+ created=status==404
+ if status==404:
+ status,body=request(url,'POST',{**params,'secretValue':VALUE},token)
+ if status not in (200,201):raise RuntimeError('Source-of-truth creation refused')
+ elif status!=200:raise RuntimeError('Source-of-truth read refused')
+ status,body=request(url+'?'+urllib.parse.urlencode(params),token=token)
+ if status!=200 or body['secret']['secretValue']!=VALUE:raise RuntimeError('Source-of-truth readback mismatch')
+ print(json.dumps({'sourceOfTruthVerified':True,'sourceOfTruthCreated':created,'setting':KEY,'additionalDatabaseCount':1}))
+except Exception as error:
+ print(json.dumps({'sourceOfTruthVerified':False,'errorClass':type(error).__name__}))
+ raise SystemExit(1)
+'''.replace("__KEY__", repr(INFISICAL_KEY)).replace("__VALUE__", repr(VALUE))
+proc = subprocess.run(["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "mac", "python3", "-"], input=remote.encode(), capture_output=True, timeout=120)
+try: result = json.loads(proc.stdout)
+except ValueError: raise SystemExit("Source-of-truth operation outcome unknown; inspect before retry")
+if proc.returncode or result.get("sourceOfTruthVerified") is not True:
+ print(json.dumps(result)); raise SystemExit(1)
+if SOURCE.read_bytes() != raw:
+ raise SystemExit("Source-of-truth verified; local configuration changed concurrently and was preserved")
+addition = ("" if not raw or raw.endswith(b"\n") else "\n") + KEY + "=" + shlex.quote(VALUE) + "\n"
+updated = raw if matches else raw + addition.encode()
+fd, temp = tempfile.mkstemp(prefix=".um1646-source-", dir=SOURCE.parent)
+try:
+ os.fchmod(fd, stat.S_IMODE(info.st_mode))
+ os.fchown(fd, info.st_uid, info.st_gid)
+ with os.fdopen(fd, "wb") as handle:
+ handle.write(updated); handle.flush(); os.fsync(handle.fileno())
+ if SOURCE.read_bytes() != raw: raise RuntimeError("Concurrent local configuration change preserved")
+ os.replace(temp, SOURCE)
+finally:
+ if os.path.exists(temp): os.unlink(temp)
+if SOURCE.read_bytes() != updated: raise SystemExit("Local configuration readback mismatch")
+print(json.dumps({**result, "localReadbackVerified": True, "unrelatedBytesPreserved": updated.startswith(raw), "primarySourcePreserved": True, "reloadPerformed": False}))
+#!/usr/bin/env python3
+# SUPERSEDED UNSAFE AUTOMATION DRAFT — DO NOT RUN. It includes configuration and local-file writes. Use opencode-child-source-plan.py for plan-only review; it has no apply path.
diff --git a/final-child-hub-readback.py b/final-child-hub-readback.py
new file mode 100644
index 00000000..b25a4b9b
--- /dev/null
+++ b/final-child-hub-readback.py
@@ -0,0 +1,14 @@
+import json,pathlib,subprocess,os
+p=json.loads(pathlib.Path('/tmp/um1646-child-sentry-storage-read-plan-20261103.json').read_text())
+image='usage-monitor-telemetry-hub:0a92fcfa39f5b576f498dabc43963c89c47b3713'
+def run(a):return subprocess.check_output(a,text=True,timeout=30)
+ids=run(['docker','ps','--filter','ancestor='+image,'--format','{{.ID}}']).splitlines()
+if len(ids)!=1:raise SystemExit('Expected one exact merged hub')
+code="""const fs=require('node:fs'),id=process.argv[1],d='/data/state';const sent=JSON.parse(fs.readFileSync(d+'/sentry.sent.json')).eventIds;const base=JSON.parse(fs.readFileSync(d+'/journal.base.json')).base,offset=JSON.parse(fs.readFileSync(d+'/sentry.offset.json')).offset,bytes=fs.statSync('/data/journal.jsonl').size;const rows=fs.readFileSync('/data/journal.jsonl','utf8').split('\\n').filter(Boolean).map(JSON.parse).filter(e=>e.eventId===id);console.log(JSON.stringify({exactHubEventJournalRows:rows.length,exactHubEventSent:sent.includes(id),sentryPendingBytes:base+bytes-offset,intentPresent:fs.existsSync(d+'/sentry-request.json')}));"""
+v=json.loads(run(['docker','exec',ids[0],'node','-e',code,p['hubEventId']]))
+c=json.loads(run(['docker','inspect',ids[0]]))[0]
+v.update(sourceCommit=c['Config']['Labels']['org.opencontainers.image.revision'],healthy=c['State']['Health']['Status']=='healthy',exactHubEventIdDigest=__import__('hashlib').sha256(p['hubEventId'].encode()).hexdigest())
+if not v['healthy'] or not v['exactHubEventSent'] or v['sentryPendingBytes']!=0 or v['intentPresent']:raise SystemExit('Exact child delivery not fully confirmed in hub state')
+out=pathlib.Path('/tmp/um1646-child-final-hub-readback-20261103.json');fd=os.open(out,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
+with os.fdopen(fd,'w') as f:json.dump(v,f)
+print(json.dumps(v))
diff --git a/inspect-tool-schemas.py b/inspect-tool-schemas.py
new file mode 100644
index 00000000..f55eb487
--- /dev/null
+++ b/inspect-tool-schemas.py
@@ -0,0 +1,36 @@
+"""Inspect only named tool schemas through the assigned CODEX wrapper."""
+import json
+import subprocess
+import sys
+
+wanted = set(sys.argv[1:])
+process = subprocess.Popen(["/home/jay/.local/libexec/codex-simple-tools"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
+def send(value):
+ process.stdin.write(json.dumps(value) + "\n")
+ process.stdin.flush()
+def receive(identifier):
+ for line in process.stdout:
+ try:
+ value = json.loads(line)
+ except ValueError:
+ continue
+ if value.get("id") == identifier:
+ return value
+ raise RuntimeError("Assigned wrapper closed before schema response")
+try:
+ send({"jsonrpc":"2.0", "id":1, "method":"initialize", "params":{"protocolVersion":"2024-11-05", "capabilities":{}, "clientInfo":{"name":"codex-um1646-schema-read", "version":"1"}}})
+ response = receive(1)
+ if "error" in response:
+ raise RuntimeError("Assigned wrapper initialization refused")
+ send({"jsonrpc":"2.0", "method":"notifications/initialized"})
+ send({"jsonrpc":"2.0", "id":2, "method":"tools/list", "params":{}})
+ response = receive(2)
+ for tool in response.get("result", {}).get("tools", []):
+ if tool.get("name") in wanted:
+ print(json.dumps({"name":tool["name"], "inputSchema":tool.get("inputSchema")}))
+finally:
+ process.terminate()
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ process.kill()
diff --git a/opencode-child-source-plan.py b/opencode-child-source-plan.py
new file mode 100644
index 00000000..9378b162
--- /dev/null
+++ b/opencode-child-source-plan.py
@@ -0,0 +1,282 @@
+#!/usr/bin/env python3
+"""Create a private two-key plan without contacting or changing configuration."""
+
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import shlex
+import stat
+import sys
+
+
+SOURCE = Path("/home/jay/.secrets/usage-monitor.env")
+PLAN = Path(__file__).with_name(".um1646-opencode-child-source-plan-v2.json")
+SUPERSEDED_PLAN = Path(__file__).with_name(".um1646-opencode-child-source-plan.json")
+SUPERSESSION_MARKER = Path(__file__).with_name(".um1646-opencode-child-source-plan-v1.superseded.json")
+REVIEWED_GUARD_COMMIT = "ca19ad6ab8e98b5ac506d75d15b72dd0b9cd9015"
+MAX_SOURCE_BYTES = 4 * 1024 * 1024
+EXPECTED_VALUES = {
+ "OPENCODE_SERVER_ADDITIONAL_DBS_JSON": json.dumps(
+ ["/mnt/fleet-extra/apps/botfleet-server/home/.local/share/opencode/opencode.db"],
+ separators=(",", ":"),
+ ),
+ "BOTFLEET_SERVER_WORKSPACES_DIRS": "/mnt/fleet-extra/apps/botfleet-server/data/workspaces",
+}
+RUNTIME_KEYS = {
+ "OPENCODE_SERVER_ADDITIONAL_DBS_JSON": "OPENCODE_ADDITIONAL_DBS_JSON",
+ "BOTFLEET_SERVER_WORKSPACES_DIRS": "BOTFLEET_WORKSPACES_DIRS",
+}
+
+
+def fail(message):
+ raise SystemExit(message)
+
+
+def sha256(data):
+ return hashlib.sha256(data).hexdigest()
+
+
+def parse_current_values(raw):
+ try:
+ lines = raw.decode("utf-8").splitlines()
+ except UnicodeDecodeError:
+ fail("Runtime snapshot is not valid UTF-8")
+ values = {}
+ for key in RUNTIME_KEYS.values():
+ pattern = re.compile(r"^(?:export\s+)?" + re.escape(key) + r"=(.*)$")
+ matches = [pattern.match(line) for line in lines]
+ matches = [match for match in matches if match is not None]
+ if not matches:
+ values[key] = None
+ continue
+ if len(matches) != 1:
+ fail("Runtime snapshot has duplicate requested key: " + key)
+ try:
+ parsed = shlex.split(matches[0].group(1), comments=True, posix=True)
+ except ValueError:
+ fail("Runtime snapshot has an invalid requested value for " + key)
+ if len(parsed) != 1:
+ fail("Runtime snapshot has an invalid requested value for " + key)
+ values[key] = parsed[0]
+ return values
+
+
+def read_approved_source():
+ try:
+ before = SOURCE.lstat()
+ if not stat.S_ISREG(before.st_mode):
+ fail("Runtime snapshot must be a regular file")
+ fd = os.open(SOURCE, os.O_RDONLY | os.O_NOFOLLOW)
+ except OSError:
+ fail("Runtime snapshot is unavailable through the no-follow route")
+ try:
+ opened = os.fstat(fd)
+ if (
+ not stat.S_ISREG(opened.st_mode)
+ or opened.st_uid != os.getuid()
+ or opened.st_dev != before.st_dev
+ or opened.st_ino != before.st_ino
+ or stat.S_IMODE(opened.st_mode) & 0o077
+ ):
+ fail("Runtime snapshot owner, mode, or identity is unsafe")
+ chunks = []
+ remaining = MAX_SOURCE_BYTES + 1
+ while remaining:
+ chunk = os.read(fd, min(remaining, 64 * 1024))
+ if not chunk:
+ break
+ chunks.append(chunk)
+ remaining -= len(chunk)
+ raw = b"".join(chunks)
+ after = os.fstat(fd)
+ if (
+ len(raw) > MAX_SOURCE_BYTES
+ or after.st_size != opened.st_size
+ or after.st_mtime_ns != opened.st_mtime_ns
+ or after.st_dev != opened.st_dev
+ or after.st_ino != opened.st_ino
+ ):
+ fail("Runtime snapshot changed during bounded read")
+ finally:
+ os.close(fd)
+ try:
+ final_path = SOURCE.lstat()
+ except OSError:
+ fail("Runtime snapshot changed during bounded read")
+ if (
+ final_path.st_dev != opened.st_dev
+ or final_path.st_ino != opened.st_ino
+ or not stat.S_ISREG(final_path.st_mode)
+ ):
+ fail("Approved source path changed during bounded read")
+ return raw, opened
+
+
+if len(sys.argv) != 1:
+ fail("This planner accepts no arguments and has no apply mode")
+
+source_bytes, source_stat = read_approved_source()
+source_values = parse_current_values(source_bytes)
+
+bindings = []
+for source_key, runtime_key in RUNTIME_KEYS.items():
+ current_value = source_values[runtime_key]
+ desired_value = EXPECTED_VALUES[source_key]
+ if current_value is not None and current_value != desired_value:
+ fail("Runtime snapshot contains a different value for " + runtime_key)
+ if source_key == "OPENCODE_SERVER_ADDITIONAL_DBS_JSON":
+ try:
+ parsed = json.loads(desired_value)
+ except json.JSONDecodeError:
+ fail("Reviewed OpenCode desired value is not valid JSON")
+ if parsed != ["/mnt/fleet-extra/apps/botfleet-server/home/.local/share/opencode/opencode.db"]:
+ fail("Reviewed OpenCode selection differs from the single database")
+ bindings.append({
+ "sourceKey": source_key,
+ "runtimeKey": runtime_key,
+ "currentState": "absent" if current_value is None else "already-equal",
+ "currentValueSha256": None if current_value is None else sha256(current_value.encode()),
+ "desiredValueSha256": sha256(desired_value.encode()),
+ })
+
+plan = {
+ "schema": "usage-monitor-collector-config-plan-v1",
+ "mode": "plan-only",
+ "supersedes": ".um1646-opencode-child-source-plan.json",
+ "supersedesReason": "Earlier planner checked source-key names in the runtime snapshot; this version checks the runtime-key names.",
+ "source": {
+ "kind": "approved-local-runtime-snapshot",
+ "ownerMatchesCurrentUser": True,
+ "modeOctal": format(stat.S_IMODE(source_stat.st_mode), "04o"),
+ "regularFile": True,
+ "nofollowOpen": True,
+ "stableDuringRead": True,
+ "sourceSha256": sha256(source_bytes),
+ },
+ "collectorGuard": {
+ "reviewedCommit": REVIEWED_GUARD_COMMIT,
+ "opencodeRuntimeKey": "OPENCODE_ADDITIONAL_DBS_JSON",
+ "botfleetRuntimeKey": "BOTFLEET_WORKSPACES_DIRS",
+ "runtimeInstallationRechecked": False,
+ },
+ "destination": {
+ "environment": "prod",
+ "secretPath": "/telemetry",
+ "currentState": "not-verified-from-Infisical",
+ "compareAndSwap": {
+ "required": True,
+ "mustBeAbsentBeforeWrite": True,
+ "keys": list(RUNTIME_KEYS.keys()),
+ },
+ },
+ "bindings": bindings,
+ "sourceOfTruthRoute": "HELD_NOT_IMPLEMENTED",
+ "currentStateEvidence": "local runtime snapshot only; Infisical remains unverified",
+ "configurationMutation": False,
+ "credentialAccess": False,
+ "applyAvailable": False,
+}
+
+plan_bytes = (json.dumps(plan, sort_keys=True, indent=2) + "\n").encode()
+try:
+ plan_fd = os.open(PLAN, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
+except FileExistsError:
+ try:
+ old_info = PLAN.lstat()
+ old_fd = os.open(PLAN, os.O_RDONLY | os.O_NOFOLLOW)
+ except OSError:
+ fail("Existing v2 plan cannot be safely inspected")
+ try:
+ old_opened = os.fstat(old_fd)
+ if (
+ not stat.S_ISREG(old_info.st_mode)
+ or old_opened.st_dev != old_info.st_dev
+ or old_opened.st_ino != old_info.st_ino
+ or old_opened.st_uid != os.getuid()
+ or stat.S_IMODE(old_opened.st_mode) & 0o077
+ ):
+ fail("Existing v2 plan owner, mode, or identity is unsafe")
+ old_raw = os.read(old_fd, 128 * 1024)
+ old_plan = json.loads(old_raw)
+ except (json.JSONDecodeError, OSError):
+ fail("Existing v2 plan is not a valid private plan artifact")
+ finally:
+ os.close(old_fd)
+ if (
+ old_plan.get("mode") != "plan-only"
+ or old_plan.get("collectorGuard", {}).get("reviewedCommit") != REVIEWED_GUARD_COMMIT
+ ):
+ fail("Existing v2 plan is not the earlier planner artifact")
+ try:
+ plan_fd = os.open(PLAN, os.O_WRONLY | os.O_NOFOLLOW)
+ except OSError:
+ fail("Existing v2 plan changed before safe regeneration")
+ opened_for_write = os.fstat(plan_fd)
+ if (
+ opened_for_write.st_dev != old_info.st_dev
+ or opened_for_write.st_ino != old_info.st_ino
+ or opened_for_write.st_uid != os.getuid()
+ or stat.S_IMODE(opened_for_write.st_mode) & 0o077
+ ):
+ os.close(plan_fd)
+ fail("Existing v2 plan changed before safe regeneration")
+ os.ftruncate(plan_fd, 0)
+with os.fdopen(plan_fd, "wb") as handle:
+ handle.write(plan_bytes)
+ handle.flush()
+ os.fsync(handle.fileno())
+os.chmod(PLAN, 0o600)
+
+marker_record = {
+ "status": "superseded",
+ "priorPlan": SUPERSEDED_PLAN.name,
+ "supersededBy": PLAN.name,
+ "reason": plan["supersedesReason"],
+}
+marker_bytes = (json.dumps(marker_record, sort_keys=True, indent=2) + "\n").encode()
+try:
+ marker_fd = os.open(
+ SUPERSESSION_MARKER,
+ os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW,
+ 0o600,
+ )
+except FileExistsError:
+ try:
+ marker_info = SUPERSESSION_MARKER.lstat()
+ marker_fd = os.open(SUPERSESSION_MARKER, os.O_RDONLY | os.O_NOFOLLOW)
+ except OSError:
+ fail("Existing supersession marker is unsafe")
+ try:
+ marker_opened = os.fstat(marker_fd)
+ if (
+ not stat.S_ISREG(marker_info.st_mode)
+ or marker_opened.st_dev != marker_info.st_dev
+ or marker_opened.st_ino != marker_info.st_ino
+ or marker_opened.st_uid != os.getuid()
+ or stat.S_IMODE(marker_opened.st_mode) & 0o077
+ or os.read(marker_fd, 16 * 1024) != marker_bytes
+ ):
+ fail("Existing supersession marker differs from the reviewed record")
+ finally:
+ os.close(marker_fd)
+else:
+ with os.fdopen(marker_fd, "wb") as handle:
+ handle.write(marker_bytes)
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.chmod(SUPERSESSION_MARKER, 0o600)
+
+print(json.dumps({
+ "mode": "plan-only",
+ "localSnapshotVerified": True,
+ "keyStates": [binding["currentState"] for binding in bindings],
+ "bindingCount": len(bindings),
+ "sourceSha256": plan["source"]["sourceSha256"],
+ "desiredValueSha256": [binding["desiredValueSha256"] for binding in bindings],
+ "remoteCurrentState": "not-verified-from-Infisical",
+ "configurationMutation": False,
+ "applyAvailable": False,
+ "planSha256": sha256(plan_bytes),
+}))
diff --git a/plan-reviewed-hub-upgrade.py b/plan-reviewed-hub-upgrade.py
new file mode 100644
index 00000000..20504bf9
--- /dev/null
+++ b/plan-reviewed-hub-upgrade.py
@@ -0,0 +1,143 @@
+"""Prepare a private same-service upgrade plan; never mutate the running service."""
+import hashlib
+import base64
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+import sys
+import urllib.request
+import yaml
+
+if len(sys.argv) != 2 or not re.fullmatch(r"[a-f0-9]{40}", sys.argv[1]):
+ raise SystemExit("One exact reviewed merged commit is required")
+target = sys.argv[1]
+root = Path("/tmp/um1646-ops")
+routing = json.loads((root / "hub-routing.json").read_text())
+service = json.loads((root / "hub-service.json").read_text())
+
+def run(args):
+ p = subprocess.run(args, capture_output=True, text=True, timeout=40)
+ if p.returncode:
+ raise RuntimeError("Approved read operation failed")
+ return p.stdout
+
+def sha(value):
+ return hashlib.sha256(value).hexdigest()
+
+def canonical(value):
+ return json.dumps(value, sort_keys=True, separators=(",", ":")).encode()
+
+class NoRedirect(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, *args, **kwargs):
+ return None
+
+opener = urllib.request.build_opener(NoRedirect())
+if routing["base_url"] not in ("http://100.69.77.26:8000/api/v1", "https://host.jays.services/api/v1"):
+ raise SystemExit("Approved Coolify route changed")
+token = run(["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "mac", "fleet-secrets get COOLIFY_AGENTS"]).strip()
+if not token:
+ raise SystemExit("Approved Coolify route unavailable")
+request = urllib.request.Request(routing["base_url"] + "/services/" + service["uuid"], headers={"Authorization": "Bearer " + token, "Accept": "application/json"})
+with opener.open(request, timeout=25) as response:
+ current = json.load(response)
+compose = yaml.safe_load(current.get("docker_compose") or current.get("docker_compose_raw"))
+unit = compose["services"]["telemetry-hub"]
+raw_value = current.get('docker_compose_raw')
+if not isinstance(raw_value, str) or not raw_value:
+ raise SystemExit('Original raw compose is unavailable; preserve the service')
+raw_compose = yaml.safe_load(raw_value)
+if not isinstance(raw_compose, dict):
+ try:
+ raw_compose = yaml.safe_load(base64.b64decode(raw_value, validate=True).decode())
+ except Exception:
+ raise SystemExit('Original raw compose shape is unsupported')
+if not isinstance(raw_compose, dict) or set(raw_compose.get('services', {})) != {'telemetry-hub'}:
+ raise SystemExit('Original raw compose service membership changed')
+raw_unit = raw_compose['services']['telemetry-hub']
+if os.environ.get('UM1651_RAW_SHAPE_ONLY') == '1':
+ raw_env = raw_unit.get('environment', {})
+ if isinstance(raw_env, list): raw_env = dict(item.split('=', 1) for item in raw_env if '=' in item)
+ prepared = json.loads((root / 'hub-compose.json').read_text())
+ print(json.dumps({'rawSourceAvailable': True, 'rawEnvironmentKeyNames': sorted(raw_env), 'rawEqualsRetainedPreparedCompose': raw_compose == prepared, 'rawImageMatchesRecord': raw_unit.get('image') == 'usage-monitor-telemetry-hub:' + service['source_commit'], 'rawAndGeneratedVolumeKeysEqual': set(raw_compose.get('volumes', {})) == set(compose.get('volumes', {})), 'rawDataMountCount': sum('/data' in str(v) for v in raw_unit.get('volumes', [])), 'rawConfigMountCount': sum(isinstance(v, dict) and v.get('target') == '/run/secrets/telemetry-hub.json' for v in raw_unit.get('volumes', []))}))
+ raise SystemExit(0)
+if raw_unit.get('image') != 'usage-monitor-telemetry-hub:' + service['source_commit'] or raw_unit.get('network_mode') != 'host' or raw_unit.get('ports') or raw_unit.get('networks') or raw_unit.get('read_only') is not True:
+ raise SystemExit('Raw service invariants changed')
+env = unit.get("environment", {})
+if isinstance(env, list):
+ env = dict(item.split("=", 1) for item in env if "=" in item)
+if os.environ.get("UM1651_PLAN_SHAPE_ONLY") == "1":
+ print(json.dumps({"environmentKeyNames": sorted(env), "configFileMatches": env.get("TELEMETRY_HUB_CONFIG_FILE") == "/run/secrets/telemetry-hub.json", "bindMatches": env.get("TELEMETRY_HUB_BIND_HOST") == routing["tailnet_bind"], "hostNetwork": unit.get("network_mode") == "host", "portsPresent": bool(unit.get("ports")), "networksPresent": bool(unit.get("networks")), "imageMatches": unit.get("image") == "usage-monitor-telemetry-hub:" + service["source_commit"], "readOnly": unit.get("read_only"), "readOnlyType": type(unit.get("read_only")).__name__, "serviceKeys": sorted(unit)}))
+ raise SystemExit(0)
+generated_keys = {"COOLIFY_APP_NAME", "COOLIFY_CONTAINER_NAME", "COOLIFY_ENVIRONMENT_NAME", "COOLIFY_PROJECT_NAME", "COOLIFY_RESOURCE_UUID", "COOLIFY_SERVER_IP", "SERVICE_NAME_TELEMETRY_HUB"}
+if (
+ set(env) != {"TELEMETRY_HUB_CONFIG_FILE", "TELEMETRY_HUB_BIND_HOST"} | generated_keys
+ or env["TELEMETRY_HUB_CONFIG_FILE"] != "/run/secrets/telemetry-hub.json"
+ or env["TELEMETRY_HUB_BIND_HOST"] != routing["tailnet_bind"]
+ or env.get("COOLIFY_RESOURCE_UUID") != service["uuid"]
+ or unit.get("network_mode") != "host"
+ or unit.get("ports") or unit.get("networks")
+ or unit.get("image") != "usage-monitor-telemetry-hub:" + service["source_commit"]
+ or unit.get("read_only") is not True
+):
+ raise SystemExit("Live service shape differs; inspect without changing it")
+new_image = "usage-monitor-telemetry-hub:" + target
+new = json.loads(run(["docker", "image", "inspect", new_image]))[0]
+if new.get("Config", {}).get("Labels", {}).get("org.opencontainers.image.revision") != target:
+ raise SystemExit("Reviewed target image is unavailable")
+ids = run(["docker", "ps", "--filter", "ancestor=" + unit["image"], "--format", "{{.ID}}"]).splitlines()
+if len(ids) != 1:
+ raise SystemExit("Expected one active original hub")
+container = json.loads(run(["docker", "inspect", ids[0]]))[0]
+if container["Config"].get("Labels", {}).get("org.opencontainers.image.revision") != service["source_commit"]:
+ raise SystemExit("Original runtime revision changed")
+container_env = dict(item.split('=', 1) for item in container['Config'].get('Env', []) if '=' in item)
+if container_env.get('COOLIFY_RESOURCE_UUID') != service['uuid']:
+ raise SystemExit('Local runtime is not the verified Coolify service')
+names = {entry.split("=", 1)[0] for entry in container["Config"].get("Env", [])}
+if any(name.startswith(("SENTRY_", "INFISICAL_")) or name in {"TELEMETRY_HUB_SOURCES_JSON", "USAGE_INGEST_TOKEN"} for name in names):
+ raise SystemExit("Static runtime credential bindings changed")
+mounts = container["Mounts"]
+volume = [m for m in mounts if m.get("Destination") == "/data" and m.get("Type") == "volume"]
+config = [m for m in mounts if m.get("Destination") == "/run/secrets/telemetry-hub.json" and m.get("Type") == "bind" and not m.get("RW")]
+baseline_volume_hash = json.loads((root / 'hub-runtime-before-restart.json').read_text()).get('volume_hash')
+if os.environ.get('UM1651_MOUNT_SHAPE_ONLY') == '1':
+ print(json.dumps({'dataVolumeCount': len(volume), 'configBindCount': len(config), 'dataMountTypes': [m.get('Type') for m in mounts if m.get('Destination') == '/data'], 'configMountTypes': [m.get('Type') for m in mounts if m.get('Destination') == '/run/secrets/telemetry-hub.json'], 'configReadOnly': [not m.get('RW') for m in mounts if m.get('Destination') == '/run/secrets/telemetry-hub.json'], 'baselineVolumeHashAvailable': isinstance(baseline_volume_hash, str), 'volumeMatchesRetainedReceipt': len(volume) == 1 and sha(volume[0].get('Name', '').encode()) == baseline_volume_hash}))
+ raise SystemExit(0)
+if len(volume) != 1 or sha(volume[0].get("Name", "").encode()) != baseline_volume_hash or len(config) != 1:
+ raise SystemExit("Durable volume or read-only configuration changed")
+if container["State"].get("Health", {}).get("Status") != "healthy" or not container["HostConfig"].get("ReadonlyRootfs"):
+ raise SystemExit("Original hub is not healthy and read-only")
+script = r"""const fs=require('node:fs'),crypto=require('node:crypto');
+const cfg='/run/secrets/telemetry-hub.json',st=fs.statSync(cfg);
+const base=JSON.parse(fs.readFileSync('/data/state/journal.base.json'));
+const offset=JSON.parse(fs.readFileSync('/data/state/sentry.offset.json')).offset;
+const bytes=fs.statSync('/data/journal.jsonl').size;
+if(base.pendingSize!==0||!Number.isSafeInteger(base.base)||!Number.isSafeInteger(offset)||offset>base.base+bytes)throw Error('Unsafe journal snapshot');
+console.log(JSON.stringify({configSha256:crypto.createHash('sha256').update(fs.readFileSync(cfg)).digest('hex'),configUid:st.uid,configMode:st.mode&511,journalBase:base.base,journalBytes:bytes,sentryOffset:offset,pendingBytes:base.base+bytes-offset}));"""
+metadata = json.loads(run(["docker", "exec", ids[0], "node", "-e", script]))
+if metadata["configUid"] != 10001 or metadata["configMode"] != 0o600:
+ raise SystemExit("Configuration custody mode changed")
+if metadata["configSha256"] != "4de53644a6cfc8bc79af1c2f7da1b6b52c1db19fbd8bc806920e30ce6b671579":
+ raise SystemExit("Reserved configuration snapshot changed")
+plan = {
+ "mode": "plan-only", "targetCommit": target, "targetImageId": new["Id"],
+ "service": service, "serviceStatus": current.get("status"),
+ "oldContainer": ids[0], "oldImageId": container["Image"],
+ "currentCompose": compose, "currentComposeSha256": sha(canonical(compose)),
+ "rawCompose": raw_compose, "rawComposeSha256": sha(canonical(raw_compose)),
+ "preparedComposeSha256": sha((root / "hub-compose.json").read_bytes()),
+ "metadata": metadata, "durableVolume": volume[0]["Name"],
+ "configMountSource": config[0]["Source"],
+ "upgradeContract": "Build before stop; recheck live compose/image/config and zero pending bytes before one stop; preserve current compose except image/telemetry.commit; same service/volume/config; inspect unknown outcomes before any retry",
+ "runtimeChanges": False,
+}
+path = Path(".um1651-hub-upgrade-" + target + ".plan.json")
+data = json.dumps(plan, sort_keys=True, indent=2).encode() + b"\n"
+fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
+with os.fdopen(fd, "wb") as handle:
+ handle.write(data)
+ handle.flush()
+ os.fsync(handle.fileno())
+print(json.dumps({"plan": str(path), "planSha256": sha(data), "targetCommit": target, "oldCommit": service["source_commit"], "pendingBytes": metadata["pendingBytes"], "runtimeChanges": False}))
diff --git a/prepare-um1646-inventory-update.py b/prepare-um1646-inventory-update.py
new file mode 100644
index 00000000..56975bf0
--- /dev/null
+++ b/prepare-um1646-inventory-update.py
@@ -0,0 +1,591 @@
+#!/usr/bin/env python3
+"""Prepare or explicitly apply a digest-bound UM-1646 inventory update."""
+
+from __future__ import annotations
+
+import argparse
+import base64
+import difflib
+import hashlib
+import html
+import json
+import os
+from pathlib import Path
+import re
+import shlex
+import stat
+import subprocess
+import sys
+
+
+SESSION = "01a18e51-51e1-7093-9269-0901397a9ec1"
+NOTE_TITLE = "⭐️ Background Jobs Master List"
+INVENTORY_PATH = "/Users/jay/apps/MAC-LOCAL-PROCESSES.md"
+INVENTORY_START = b"## Usage Monitor Telemetry (UM-1646)"
+NOTE_START = b"Usage Monitor Telemetry ("
+NOTE_END = b"Private runtime routing and credentials remain in the private operations inventory and Infisical.
"
+PLAN_PATH = Path(__file__).resolve().parent / ".um1646-inventory-update.plan.json"
+MAX_INVENTORY_BYTES = 4 * 1024 * 1024
+MAX_NOTE_BYTES = 2 * 1024 * 1024
+
+HUB_DESCRIPTION = (
+ "Always-on server container; active; source 0a92fcfa; "
+ "program node /app/scripts/telemetry-hub/start-with-infisical.mjs; restart unless-stopped; "
+ "logs Docker stdout/stderr; generated span/log numeric aliases stored in Sentry; independently "
+ "healthy after the same-service upgrade from Usage-Monitor PR #1874; original durable volume "
+ "and configuration preserved; ambiguous acknowledgements are held for reconciliation."
+)
+HUB_ROW = f"| usage-monitor-telemetry-hub | {HUB_DESCRIPTION} |".encode("utf-8")
+
+BRIDGE_DESCRIPTION = (
+ "Server collector installation: 55 files at ca19ad6; Mac: 54 files at ca19ad6 plus the Muse "
+ "file at 7424ae0; both hosts verified "
+ "installed/imported; all four CLI sources configured for authenticated hub delivery; Mac jobs "
+ "reloaded with guarded config readbacks; delivery uses the existing four CLI collector schedules; "
+ "independent durable delivery inside existing invocations; no additional daemon.\u00a0 "
+ "Muse source 7424ae0 is installed but remains unloaded under the injector hold; no Muse job is loaded."
+)
+BRIDGE_ROW = f"| Collector Sentry bridge | {BRIDGE_DESCRIPTION} |".encode("utf-8")
+
+BOTFLEET_OLD_TAIL = (
+ b"Its child OpenCode data-root location remains unverified after the child exited; "
+ b"the standalone source is unchanged."
+)
+BOTFLEET_NEW_TAIL = (
+ "The standalone OpenCode source is unchanged.\u00a0 The permanent server child sources are "
+ "verified: the OpenCode database is /mnt/fleet-extra/apps/botfleet-server/home/.local/share/"
+ "opencode/opencode.db and the workspace root is /mnt/fleet-extra/apps/botfleet-server/data/"
+ "workspaces; all eight retained child events are classified BotFleet."
+).encode("utf-8")
+
+PRUNE_DESCRIPTION = (
+ "On-demand only; bounded receipt pruning requires a verified checkpoint and preserves pending "
+ "or quarantined records."
+)
+RETRY_DESCRIPTION = (
+ "On-demand only; retries explicitly selected quarantined records after correction."
+)
+AUDIT_DESCRIPTION = (
+ "Task-scoped on-demand helper; approved Mac Python read route; stdout aggregate receipt counts only; "
+ "no scheduler."
+)
+
+CAS_REMOTE_SCRIPT = r'''import base64,hashlib,json,os,stat,sys,tempfile
+path="/Users/jay/apps/MAC-LOCAL-PROCESSES.md"
+MAX=4*1024*1024
+def bad(reason):
+ print(json.dumps({"state":"refused","reason":reason},sort_keys=True)); raise SystemExit(2)
+def read_source():
+ try: before=os.lstat(path)
+ except OSError: bad("inventory_unavailable")
+ if not stat.S_ISREG(before.st_mode) or before.st_uid != os.getuid() or before.st_size > MAX: bad("inventory_metadata_invalid")
+ fd=os.open(path,os.O_RDONLY|getattr(os,"O_NOFOLLOW",0)|getattr(os,"O_CLOEXEC",0)|getattr(os,"O_NONBLOCK",0))
+ try:
+ opened=os.fstat(fd)
+ if (opened.st_dev,opened.st_ino,opened.st_size,opened.st_mtime_ns,opened.st_uid,opened.st_gid,stat.S_IMODE(opened.st_mode)) != (before.st_dev,before.st_ino,before.st_size,before.st_mtime_ns,before.st_uid,before.st_gid,stat.S_IMODE(before.st_mode)): bad("inventory_changed")
+ chunks=[]; remaining=MAX+1
+ while remaining:
+ part=os.read(fd,min(65536,remaining))
+ if not part: break
+ chunks.append(part); remaining-=len(part)
+ data=b"".join(chunks); after=os.fstat(fd)
+ if len(data)>MAX or len(data)!=before.st_size or after.st_mtime_ns!=before.st_mtime_ns: bad("inventory_changed")
+ return data,before
+ finally: os.close(fd)
+try:
+ payload=json.load(sys.stdin); expected=payload["beforeSha256"]; old_section=base64.b64decode(payload["beforeSection"],validate=True); new_section=base64.b64decode(payload["afterSection"],validate=True); new_sha=payload["afterSha256"]
+ data,before=read_source(); current=hashlib.sha256(data).hexdigest()
+ marker=b"## Usage Monitor Telemetry (UM-1646)"; start=data.find(marker); end=data.find(b"\n## ",start+len(marker))
+ if start<0 or data.find(marker,start+1)>=0: bad("inventory_section_invalid")
+ end=end if end>=0 else len(data); current_section=data[start:end]
+ if current==new_sha and current_section==new_section:
+ print(json.dumps({"state":"already_applied","sha256":current},sort_keys=True)); raise SystemExit(0)
+ if current!=expected or current_section!=old_section: bad("inventory_compare_failed")
+ new=data[:start]+new_section+data[end:]
+ if hashlib.sha256(new).hexdigest()!=new_sha: bad("inventory_target_hash_invalid")
+ fd,temp_path=tempfile.mkstemp(prefix=".MAC-LOCAL-PROCESSES.um1646-",dir=os.path.dirname(path))
+ temp_info=os.fstat(fd)
+ try:
+ os.fchown(fd,before.st_uid,before.st_gid); os.fchmod(fd,stat.S_IMODE(before.st_mode))
+ view=memoryview(new)
+ while view:
+ n=os.write(fd,view)
+ if n<=0: bad("inventory_write_failed")
+ view=view[n:]
+ os.fsync(fd)
+ staged=os.fstat(fd)
+ if (staged.st_uid,staged.st_gid,stat.S_IMODE(staged.st_mode),staged.st_size)!=(before.st_uid,before.st_gid,stat.S_IMODE(before.st_mode),len(new)): bad("inventory_stage_invalid")
+ except BaseException:
+ os.close(fd)
+ try:
+ cur=os.lstat(temp_path)
+ if (cur.st_dev,cur.st_ino)==(temp_info.st_dev,temp_info.st_ino): os.unlink(temp_path)
+ except OSError: pass
+ raise
+ os.close(fd)
+ latest,info=read_source(); latest_hash=hashlib.sha256(latest).hexdigest(); latest_start=latest.find(marker); latest_end=latest.find(b"\n## ",latest_start+len(marker)); latest_end=latest_end if latest_end>=0 else len(latest)
+ if latest_hash!=expected or latest[latest_start:latest_end]!=old_section or (info.st_dev,info.st_ino,info.st_uid,info.st_gid,stat.S_IMODE(info.st_mode))!=(before.st_dev,before.st_ino,before.st_uid,before.st_gid,stat.S_IMODE(before.st_mode)): bad("inventory_compare_failed")
+ os.replace(temp_path,path)
+ dfd=os.open(os.path.dirname(path),os.O_RDONLY|getattr(os,"O_DIRECTORY",0))
+ try: os.fsync(dfd)
+ finally: os.close(dfd)
+ written,_=read_source(); observed=hashlib.sha256(written).hexdigest()
+ if observed!=new_sha: bad("inventory_readback_mismatch")
+ print(json.dumps({"state":"written","sha256":observed},sort_keys=True))
+except SystemExit: raise
+except Exception as error:
+ print(json.dumps({"state":"failed","errorType":type(error).__name__},sort_keys=True)); raise SystemExit(1)
+'''
+
+NOTE_TEMP_SCRIPT = r'''import json,os,stat,sys,tempfile
+data=sys.stdin.buffer.read(2*1024*1024+1)
+if len(data)>2*1024*1024: raise SystemExit(2)
+fd,path=tempfile.mkstemp(prefix="um1646-note-",suffix=".html",dir="/tmp")
+os.fchmod(fd,0o600)
+with os.fdopen(fd,"wb") as out:
+ out.write(data); out.flush(); os.fsync(out.fileno())
+print(json.dumps({"path":path},sort_keys=True))
+'''
+
+NOTE_CLEANUP_SCRIPT = r'''import json,os,stat,sys
+path=sys.argv[1]
+if not path.startswith("/tmp/um1646-note-") or not path.endswith(".html"): raise SystemExit(2)
+try: st=os.lstat(path)
+except FileNotFoundError: raise SystemExit(0)
+if not stat.S_ISREG(st.st_mode) or st.st_uid!=os.getuid() or stat.S_IMODE(st.st_mode)!=0o600: raise SystemExit(3)
+os.unlink(path)
+'''
+
+
+class UpdateFailure(Exception):
+ """A sanitized refusal containing a reason code only."""
+
+
+def _fail(reason: str) -> UpdateFailure:
+ return UpdateFailure(reason)
+
+
+def _sha(data: bytes) -> str:
+ return hashlib.sha256(data).hexdigest()
+
+
+def _ssh(remote_command: str, *, input_bytes: bytes | None = None,
+ timeout: int = 60) -> bytes:
+ try:
+ result = subprocess.run(
+ ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "mac", remote_command],
+ input=input_bytes, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
+ timeout=timeout, check=False,
+ )
+ except subprocess.TimeoutExpired:
+ raise _fail("mac_route_timeout") from None
+ except OSError as error:
+ raise _fail(type(error).__name__) from None
+ if result.returncode:
+ raise _fail("mac_route_failed")
+ return result.stdout
+
+
+def _read_inventory() -> tuple[bytes, bytes]:
+ reader = (
+ "import hashlib,json; from pathlib import Path; "
+ f"p=Path({INVENTORY_PATH!r}); b=p.read_bytes(); "
+ f"m={INVENTORY_START.decode('utf-8')!r}.encode(); s=b.index(m); "
+ "e=b.find(b'\\n## ',s+len(m)); section=b[s:e if e>=0 else None]; "
+ "print(json.dumps({'sha256':hashlib.sha256(b).hexdigest(),'section':section.decode('utf-8')}))"
+ )
+ output = _ssh("python3 -c " + shlex.quote(reader), timeout=30)
+ try:
+ value = json.loads(output)
+ section = value["section"].encode("utf-8")
+ digest = value["sha256"]
+ except (UnicodeDecodeError, json.JSONDecodeError, KeyError, TypeError):
+ raise _fail("inventory_read_result_invalid") from None
+ if not re.fullmatch(r"[a-f0-9]{64}", digest) or len(section) > MAX_INVENTORY_BYTES:
+ raise _fail("inventory_read_result_invalid")
+ return digest.encode("ascii"), section
+
+
+def _read_note() -> bytes:
+ command = (
+ "simple-notes --as CODEX --session " + SESSION +
+ " read --format html " + shlex.quote(NOTE_TITLE)
+ )
+ data = _ssh(command, timeout=90)
+ if not data or len(data) > MAX_NOTE_BYTES:
+ raise _fail("note_read_size_invalid")
+ return data
+
+
+def _replace_inventory_rows(section: bytes) -> bytes:
+ lines = section.splitlines(keepends=True)
+ replacements = {
+ b"| usage-monitor-telemetry-hub |": HUB_ROW,
+ b"| Collector Sentry bridge |": BRIDGE_ROW,
+ }
+ updated: dict[bytes, int] = {prefix: 0 for prefix in replacements}
+ result: list[bytes] = []
+ for line in lines:
+ matched = False
+ for prefix, value in replacements.items():
+ if line.startswith(prefix):
+ newline = b"\r\n" if line.endswith(b"\r\n") else b"\n" if line.endswith(b"\n") else b""
+ result.append(value + newline)
+ updated[prefix] += 1
+ matched = True
+ break
+ if not matched and line.startswith(b"| botfleet-session-collector.mjs |"):
+ if line.count(BOTFLEET_OLD_TAIL) != 1:
+ raise _fail("botfleet_old_clause_mismatch")
+ line = line.replace(BOTFLEET_OLD_TAIL, BOTFLEET_NEW_TAIL, 1)
+ line = line.replace(b"Linux ordinary native activity remains zero", b"The earlier Linux native audit found no ordinary activity", 1)
+ updated[b"botfleet-session-collector.mjs"] = updated.get(b"botfleet-session-collector.mjs", 0) + 1
+ result.append(line)
+ matched = True
+ if not matched:
+ result.append(line)
+ if updated.get(b"| usage-monitor-telemetry-hub |") != 1 or updated.get(b"| Collector Sentry bridge |") != 1 or updated.get(b"botfleet-session-collector.mjs") != 1:
+ raise _fail("inventory_target_rows_not_unique")
+ return b"".join(result)
+
+
+def _note_rows(inventory_section: bytes) -> bytes:
+ labels = (
+ b"usage-monitor-telemetry-hub",
+ b"Collector Sentry bridge",
+ b"scripts/prune-collector-sentry-outbox.mjs",
+ b"scripts/retry-collector-sentry-outbox.mjs",
+ b"botfleet-session-collector.mjs",
+ b"UM-1646 Sentry Receipt Audit",
+ )
+ found: dict[bytes, bytes] = {}
+ for line in inventory_section.splitlines():
+ if not line.startswith(b"|"):
+ continue
+ fields = line.split(b"|", 2)
+ if len(fields) != 3:
+ continue
+ label, description = fields[1].strip(), fields[2].rsplit(b"|", 1)[0].strip()
+ if label in labels:
+ if label in found:
+ raise _fail("inventory_note_row_not_unique")
+ found[label] = description
+ if tuple(label for label in labels if label in found) != labels:
+ raise _fail("inventory_note_rows_incomplete")
+ values = []
+ for label in labels:
+ values.append(
+ "" + html.escape(label.decode("utf-8")) + ": "
+ + html.escape(found[label].decode("utf-8")) + ""
+ )
+ return ("").encode("utf-8")
+
+
+def _note_section(html_body: bytes) -> tuple[int, int, int, bytes]:
+ text_start = html_body.rfind(NOTE_START)
+ if text_start < 0 or html_body.find(NOTE_START) != text_start:
+ raise _fail("note_section_start_not_unique")
+ start = html_body.rfind(b"", 0, text_start)
+ if start < 0:
+ raise _fail("note_section_start_invalid")
+ end = html_body.find(NOTE_END, start)
+ if end < 0 or html_body.find(NOTE_END, end + len(NOTE_END)) >= 0:
+ raise _fail("note_section_end_not_unique")
+ heading_end = html_body.find(b"
", start)
+ if heading_end < 0 or heading_end + len(b"") > end:
+ raise _fail("note_heading_invalid")
+ heading_end += len(b"")
+ return start, end, heading_end, html_body[start:end]
+
+
+def _note_after(note: bytes, inventory_section: bytes) -> tuple[bytes, bytes, bytes]:
+ start, end, heading_end, before_section = _note_section(note)
+ body = note[heading_end:end]
+ if body != b"\n
\n
\n":
+ raise _fail("note_target_section_not_blank")
+ body = b"\n" + _note_rows(inventory_section) + b"\n
\n"
+ new_section = note[start:heading_end] + body
+ after = note[:start] + new_section + note[end:]
+ return after, before_section, new_section
+
+
+def _read_local_plan(path: Path, digest: str) -> tuple[dict[str, object], bytes]:
+ try:
+ before = os.lstat(path)
+ except OSError:
+ raise _fail("plan_unavailable") from None
+ if (not stat.S_ISREG(before.st_mode) or before.st_uid != os.getuid()
+ or stat.S_IMODE(before.st_mode) != 0o600 or before.st_size > MAX_NOTE_BYTES):
+ raise _fail("plan_metadata_invalid")
+ flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0)
+ try:
+ fd = os.open(path, flags)
+ except OSError:
+ raise _fail("plan_open_failed") from None
+ try:
+ chunks = []
+ remaining = MAX_NOTE_BYTES + 1
+ while remaining:
+ chunk = os.read(fd, min(65536, remaining))
+ if not chunk:
+ break
+ chunks.append(chunk)
+ remaining -= len(chunk)
+ data = b"".join(chunks)
+ finally:
+ os.close(fd)
+ if len(data) > MAX_NOTE_BYTES or _sha(data) != digest:
+ raise _fail("plan_digest_mismatch")
+ try:
+ value = json.loads(data)
+ except (UnicodeDecodeError, json.JSONDecodeError):
+ raise _fail("plan_json_invalid") from None
+ if not isinstance(value, dict) or value.get("schema") != 1:
+ raise _fail("plan_schema_invalid")
+ return value, data
+
+
+def _write_plan(plan: dict[str, object]) -> str:
+ data = json.dumps(plan, ensure_ascii=False, sort_keys=True, indent=2).encode("utf-8") + b"\n"
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
+ try:
+ fd = os.open(PLAN_PATH, flags, 0o600)
+ except OSError:
+ raise _fail("plan_already_exists_or_unavailable") from None
+ try:
+ os.fchmod(fd, 0o600)
+ view = memoryview(data)
+ while view:
+ written = os.write(fd, view)
+ if written <= 0:
+ raise _fail("plan_write_failed")
+ view = view[written:]
+ os.fsync(fd)
+ finally:
+ os.close(fd)
+ parent = os.open(PLAN_PATH.parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
+ try:
+ os.fsync(parent)
+ finally:
+ os.close(parent)
+ return _sha(data)
+
+
+def prepare_plan() -> dict[str, object]:
+ inventory_before_sha, inventory_before = _read_inventory()
+ note_before = _read_note()
+ inventory_after_section = _replace_inventory_rows(inventory_before)
+ inventory_after_sha = _remote_inventory_after_hash(
+ inventory_before_sha.decode("ascii"), inventory_before, inventory_after_section,
+ )
+ note_after, note_before_section, note_after_section = _note_after(note_before, inventory_after_section)
+ inventory_diff = "".join(difflib.unified_diff(
+ inventory_before.decode("utf-8").splitlines(keepends=True),
+ inventory_after_section.decode("utf-8").splitlines(keepends=True),
+ fromfile="MAC-LOCAL-PROCESSES.md:UM-1646 before",
+ tofile="MAC-LOCAL-PROCESSES.md:UM-1646 after",
+ ))
+ note_diff = "".join(difflib.unified_diff(
+ note_before_section.decode("utf-8").splitlines(keepends=True),
+ note_after_section.decode("utf-8").splitlines(keepends=True),
+ fromfile="Background Jobs Master List:UM-1646 before",
+ tofile="Background Jobs Master List:UM-1646 after",
+ ))
+ return {
+ "schema": 1,
+ "task": "UM-1646 inventory completion",
+ "session": SESSION,
+ "inventory": {
+ "path": INVENTORY_PATH,
+ "beforeSha256": inventory_before_sha.decode("ascii"),
+ "beforeSectionSha256": _sha(inventory_before),
+ "afterSectionSha256": _sha(inventory_after_section),
+ "afterSha256": inventory_after_sha,
+ "sectionBefore": inventory_before.decode("utf-8"),
+ "sectionAfter": inventory_after_section.decode("utf-8"),
+ "diff": inventory_diff,
+ },
+ "note": {
+ "title": NOTE_TITLE,
+ "beforeSha256": _sha(note_before),
+ "beforeSectionSha256": _sha(note_before_section),
+ "afterSectionSha256": _sha(note_after_section),
+ "afterSha256": _sha(note_after),
+ "sectionBefore": note_before_section.decode("utf-8"),
+ "sectionAfter": note_after_section.decode("utf-8"),
+ "diff": note_diff,
+ },
+ "applyRequiresExactPlanSha256": True,
+ "writes": False,
+ }
+
+
+def _read_inventory_section_and_hash() -> tuple[str, bytes]:
+ digest, section = _read_inventory()
+ return digest.decode("ascii"), section
+
+
+def _apply_inventory(before_sha: str, expected_after_sha: str, updated_section: bytes,
+ original_section: bytes) -> None:
+ current_sha, current_section = _read_inventory_section_and_hash()
+ if current_sha == expected_after_sha:
+ return
+ if current_sha != before_sha or current_section != original_section:
+ raise _fail("inventory_fresh_compare_failed")
+ # The remote writer receives only the changed target section and checks the full source hash itself.
+ payload = {
+ "beforeSha256": before_sha,
+ "afterSha256": expected_after_sha,
+ "beforeSection": base64.b64encode(original_section).decode("ascii"),
+ "afterSection": base64.b64encode(updated_section).decode("ascii"),
+ }
+ result = _ssh("python3 -c " + shlex.quote(CAS_REMOTE_SCRIPT),
+ input_bytes=json.dumps(payload, separators=(",", ":")).encode("utf-8"), timeout=45)
+ try:
+ status = json.loads(result)
+ except (UnicodeDecodeError, json.JSONDecodeError):
+ raise _fail("inventory_write_receipt_invalid") from None
+ if not isinstance(status, dict) or status.get("state") not in {"written", "already_applied"} or status.get("sha256") != expected_after_sha:
+ raise _fail("inventory_write_failed")
+
+
+def _write_note_temp(data: bytes) -> str:
+ result = _ssh("python3 -c " + shlex.quote(NOTE_TEMP_SCRIPT), input_bytes=data, timeout=30)
+ try:
+ path = json.loads(result)["path"]
+ except (UnicodeDecodeError, json.JSONDecodeError, KeyError, TypeError):
+ raise _fail("note_temp_creation_failed") from None
+ if not isinstance(path, str) or not re.fullmatch(r"/tmp/um1646-note-[A-Za-z0-9_-]+\.html", path):
+ raise _fail("note_temp_path_invalid")
+ return path
+
+
+def _cleanup_note_temp(path: str) -> None:
+ command = "python3 -c " + shlex.quote(NOTE_CLEANUP_SCRIPT) + " " + shlex.quote(path)
+ try:
+ _ssh(command, timeout=15)
+ except UpdateFailure:
+ pass
+
+
+def _update_note(path: str, plan_sha: str) -> None:
+ command = (
+ "simple-notes --as CODEX --session " + SESSION + " update " + shlex.quote(NOTE_TITLE)
+ + " --html " + shlex.quote(path) + " --request-id um1646-" + plan_sha[:40]
+ )
+ _ssh(command, timeout=150)
+
+
+def apply_plan(plan: dict[str, object], plan_sha: str) -> dict[str, object]:
+ inv = plan["inventory"]
+ note = plan["note"]
+ inv_before = inv["beforeSha256"]
+ note_before = note["beforeSha256"]
+ inv_after_section = inv["sectionAfter"].encode("utf-8")
+ inv_before_section = inv["sectionBefore"].encode("utf-8")
+ note_after_section = note["sectionAfter"].encode("utf-8")
+
+ inventory_sha, inventory_section = _read_inventory_section_and_hash()
+ note_html = _read_note()
+ note_sha = _sha(note_html)
+ if inventory_sha not in {inv_before, inv.get("afterSha256")} or note_sha not in {note_before, note["afterSha256"]}:
+ raise _fail("fresh_full_source_compare_failed")
+ if inventory_sha == inv_before and inventory_section != inv_before_section:
+ raise _fail("inventory_section_compare_failed")
+ if inventory_sha == inv.get("afterSha256") and inventory_section != inv_after_section:
+ raise _fail("inventory_after_section_mismatch")
+ if note_sha == note_before:
+ fresh_note_after, fresh_note_before_section, fresh_note_after_section = _note_after(note_html, inv_after_section)
+ if (_sha(fresh_note_before_section) != note["beforeSectionSha256"]
+ or fresh_note_after_section != note_after_section
+ or _sha(fresh_note_after) != note["afterSha256"]):
+ raise _fail("note_section_compare_failed")
+ elif note_sha == note["afterSha256"]:
+ _, _, _, current_note_section = _note_section(note_html)
+ if current_note_section != note_after_section:
+ raise _fail("note_after_section_mismatch")
+
+ if inventory_sha == inv_before:
+ inventory_hash_again, inventory_section_again = _read_inventory_section_and_hash()
+ note_html_again = _read_note()
+ if (inventory_hash_again != inv_before or inventory_section_again != inv_before_section
+ or _sha(note_html_again) != note_before):
+ raise _fail("prewrite_full_source_compare_failed")
+ updated_full_section = _replace_inventory_rows(inventory_section_again)
+ _apply_inventory(inv_before, inv["afterSha256"], updated_full_section, inventory_section_again)
+
+ if _sha(_read_note()) == note_before:
+ current_note = _read_note()
+ if _sha(current_note) != note_before:
+ raise _fail("note_prewrite_compare_failed")
+ new_note, _, _ = _note_after(current_note, inv_after_section)
+ if _sha(new_note) != note["afterSha256"]:
+ raise _fail("note_after_hash_mismatch")
+ temp_path = _write_note_temp(new_note)
+ try:
+ if _sha(_read_note()) != note_before:
+ raise _fail("note_prewrite_compare_failed")
+ _update_note(temp_path, plan_sha)
+ finally:
+ _cleanup_note_temp(temp_path)
+
+ inventory_final, _ = _read_inventory_section_and_hash()
+ note_final = _sha(_read_note())
+ if inventory_final != inv["afterSha256"] or note_final != note["afterSha256"]:
+ raise _fail("final_readback_hash_mismatch")
+ return {"state": "applied_and_verified", "inventorySha256": inventory_final,
+ "noteSha256": note_final, "planSha256": plan_sha}
+
+
+def _remote_inventory_after_hash(before_sha: str, before_section: bytes,
+ after_section: bytes) -> str:
+ code = (
+ "import hashlib,json; from pathlib import Path; "
+ f"p=Path({INVENTORY_PATH!r}); b=p.read_bytes(); "
+ "start=b.index(b'## Usage Monitor Telemetry (UM-1646)'); "
+ "end=b.find(b'\\n## ',start+1); end=end if end>=0 else len(b); "
+ "assert hashlib.sha256(b).hexdigest()==" + repr(before_sha) + "; "
+ "assert b[start:end]==" + repr(before_section) + "; "
+ "a=b[:start]+" + repr(after_section) + "+b[end:]; "
+ "print(hashlib.sha256(a).hexdigest())"
+ )
+ # This read-only hash calculation uses the exact current source bytes and the target section bytes.
+ output = _ssh("python3 -c " + shlex.quote(code), timeout=30).decode("ascii", "strict").strip()
+ if not re.fullmatch(r"[a-f0-9]{64}", output):
+ raise _fail("inventory_after_hash_invalid")
+ return output
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--apply", metavar="PLAN_SHA256", help="apply only this exact private plan")
+ args = parser.parse_args()
+ if args.apply is None:
+ plan = prepare_plan()
+ plan_sha = _write_plan(plan)
+ print(json.dumps({
+ "phase": "plan",
+ "planPath": str(PLAN_PATH),
+ "planSha256": plan_sha,
+ "inventoryBeforeSha256": plan["inventory"]["beforeSha256"],
+ "noteBeforeSha256": plan["note"]["beforeSha256"],
+ "writes": False,
+ }, sort_keys=True))
+ return 0
+ if not re.fullmatch(r"[a-f0-9]{64}", args.apply):
+ raise _fail("invalid_plan_sha256")
+ plan, _ = _read_local_plan(PLAN_PATH, args.apply)
+ result = apply_plan(plan, args.apply)
+ print(json.dumps(result, sort_keys=True))
+ return 0
+
+
+if __name__ == "__main__":
+ try:
+ sys.exit(main())
+ except UpdateFailure as error:
+ print(json.dumps({"phase": "refused", "reason": str(error)}, sort_keys=True))
+ sys.exit(2)
+ except Exception as error:
+ print(json.dumps({"phase": "failed", "errorType": type(error).__name__}, sort_keys=True))
+ sys.exit(1)
diff --git a/preserve-final-safe-receipts.py b/preserve-final-safe-receipts.py
new file mode 100644
index 00000000..80938cc1
--- /dev/null
+++ b/preserve-final-safe-receipts.py
@@ -0,0 +1,13 @@
+import pathlib,json,os,hashlib
+root=pathlib.Path(__file__).resolve().parent
+dest=pathlib.Path('/home/jay/.codex/outputs/um-1646')
+names=[root/'.um1651-final-runtime-verification.json',root/'.um1646-child-pair-apply-ae3a6cbb3461248daad470f024b766a4b11ab189cce28af3894fc96616bb34b7.json',pathlib.Path('/tmp/um1646-child-sentry-apply-receipt-20261103.json'),pathlib.Path('/tmp/um1646-child-final-hub-readback-20261103.json'),pathlib.Path('/tmp/um1646-child-sentry-stored-baseline-20261103.json'),pathlib.Path('/tmp/um1646-child-metadata-two-receipt-20261103.json'),pathlib.Path('/tmp/um1646-child-metadata-two-receiver-read-20261103.json')]
+for source in names:
+ data=source.read_bytes();json.loads(data)
+ target=dest/source.name.lstrip('.')
+ if target.exists():
+ if target.read_bytes()!=data:raise SystemExit('Preserved receipt differs')
+ else:
+ fd=os.open(target,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600)
+ with os.fdopen(fd,'wb')as handle:handle.write(data);handle.flush();os.fsync(handle.fileno())
+ print(json.dumps({'receipt':str(target),'sha256':hashlib.sha256(data).hexdigest()}))
diff --git a/probe-sentry-empty-ack.py b/probe-sentry-empty-ack.py
new file mode 100644
index 00000000..21f3356b
--- /dev/null
+++ b/probe-sentry-empty-ack.py
@@ -0,0 +1,41 @@
+"""Inspect the ACK shape for zero-event envelopes using existing hub custody."""
+import json
+from pathlib import Path
+import subprocess
+
+service = json.loads(Path('/tmp/um1646-ops/hub-service.json').read_text())
+image = 'usage-monitor-telemetry-hub:' + service['source_commit']
+p = subprocess.run(['docker', 'ps', '--filter', 'ancestor=' + image, '--format', '{{.ID}}'], capture_output=True, text=True, check=True)
+ids = p.stdout.splitlines()
+if len(ids) != 1:
+ raise SystemExit('Expected one known hub')
+script = r"""
+const fs=require('node:fs'),zlib=require('node:zlib');
+const cfg=JSON.parse(fs.readFileSync('/run/secrets/telemetry-hub.json'));
+const endpoint=cfg.SENTRY_OTLP_ENDPOINT?.replace(/\/+$/,'');
+if(!endpoint||!cfg.SENTRY_PUBLIC_KEY)throw Error('Existing custody unavailable');
+const outputs=[];
+for(const signal of ['logs','traces']){
+ const body=zlib.gzipSync(Buffer.from(JSON.stringify(signal==='logs'?{resourceLogs:[]}:{resourceSpans:[]})));
+ try{
+ const response=await fetch(endpoint+'/v1/'+signal,{method:'POST',headers:{'content-type':'application/json','content-encoding':'gzip','x-sentry-auth':'sentry sentry_key='+cfg.SENTRY_PUBLIC_KEY},body,redirect:'error',signal:AbortSignal.timeout(10000)});
+ const reader=response.body?.getReader();let length=0;const chunks=[];
+ if(reader){for(;;){const next=await reader.read();if(next.done)break;length+=next.value.byteLength;if(length>65536){await reader.cancel();throw Error('ACK size bound');}chunks.push(next.value);}}
+ const text=Buffer.concat(chunks).toString('utf8');let parsed;
+ try{parsed=JSON.parse(text);}catch{}
+ const obj=parsed&&typeof parsed==='object'&&!Array.isArray(parsed);
+ outputs.push({signal,submittedEvents:0,status:response.status,contentType:response.headers.get('content-type'),responseBytes:length,empty:text.trim()==='',jsonObject:Boolean(obj),emptyJsonObject:obj&&Object.keys(parsed).length===0,partialSuccessPresent:Boolean(obj&&(parsed.partialSuccess||parsed.partial_success))});
+ }catch(error){outputs.push({signal,submittedEvents:0,errorClass:error.name});}
+}
+console.log(JSON.stringify({existingCustody:true,envelopesContainNoEvents:true,outputs}));
+"""
+p = subprocess.run(['docker', 'exec', '-i', ids[0], 'node', '--input-type=module', '-e', script.replace("const fs=require('node:fs'),zlib=require('node:zlib');", "import fs from 'node:fs';import zlib from 'node:zlib';")], capture_output=True, text=True, timeout=30)
+if p.returncode:
+ raise SystemExit('Empty-envelope probe failed; no raw stderr printed')
+data = json.loads(p.stdout)
+path = Path('.um1651-empty-sentry-ack-receipt.json')
+import os
+fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
+with os.fdopen(fd, 'w') as handle:
+ json.dump(data, handle)
+print(json.dumps(data))
diff --git a/publish-reviewed-files.py b/publish-reviewed-files.py
new file mode 100644
index 00000000..944dad88
--- /dev/null
+++ b/publish-reviewed-files.py
@@ -0,0 +1,33 @@
+"""Publish four reviewed files using the assigned own-seat Relay connection."""
+import base64
+import json
+from pathlib import Path
+import subprocess
+
+paths = ["scripts/opencode-usage-collector.mjs", "scripts/__tests__/opencode-profiles.node-test.mjs"]
+arguments = {"identity":"CODEX", "repo":"Simple-With-Us/Usage-Monitor", "branch":"codex/um-1646-completion-audit", "expected_head_sha":"09f22f9ecb14b51af99cfea61fb00139830e7e81", "message":"Treat Blocked Implicit OpenCode Paths As Empty", "files":[{"path":path, "content_b64":base64.b64encode(Path(path).read_bytes()).decode()} for path in paths]}
+process = subprocess.Popen(["/home/jay/.local/libexec/codex-simple-tools"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
+def send(value):
+ process.stdin.write(json.dumps(value) + "\n")
+ process.stdin.flush()
+def receive(identifier):
+ for line in process.stdout:
+ try: value = json.loads(line)
+ except ValueError: continue
+ if value.get("id") == identifier: return value
+ raise RuntimeError("Assigned wrapper closed before response; inspect destination before retry")
+try:
+ send({"jsonrpc":"2.0", "id":1, "method":"initialize", "params":{"protocolVersion":"2024-11-05", "capabilities":{}, "clientInfo":{"name":"codex-um1646-publication", "version":"1"}}})
+ if "error" in receive(1): raise RuntimeError("Assigned wrapper initialization refused")
+ send({"jsonrpc":"2.0", "method":"notifications/initialized"})
+ send({"jsonrpc":"2.0", "id":2, "method":"tools/call", "params":{"name":"gr_wf_files_put", "arguments":arguments}})
+ result = receive(2)
+ Path(".um1646-relay-publication-receipt.json").write_text(json.dumps(result))
+ # The action returns commit metadata, never credentials or source configuration.
+ for content in result.get("result", {}).get("content", []):
+ if content.get("type") == "text": print(content["text"])
+ if "error" in result: print(json.dumps({"rpcError":True}))
+finally:
+ process.terminate()
+ try: process.wait(timeout=5)
+ except subprocess.TimeoutExpired: process.kill()
diff --git a/publish-um1651-main-merge.py b/publish-um1651-main-merge.py
new file mode 100644
index 00000000..42f53952
--- /dev/null
+++ b/publish-um1651-main-merge.py
@@ -0,0 +1,63 @@
+"""Publish the reviewed merge tree with both real parents through CODEX Relay."""
+import json
+import os
+from pathlib import Path
+import subprocess
+
+root = Path('/mnt/fleet-extra/apps/lanes/Usage-Monitor/codex-um1646-sentry-partial-ack')
+local_head = '276ba0e955b255a445282a44072b22af0e50c6d6'
+remote_head = 'd5441d9b500d553f096d8beac9c9340e4aaf38b7'
+main_head = '5c218189851cbc44dfc7271e3879cda8b481d446'
+expected_tree = 'b0effe5d5afb89f68a7f382a1e92bdccf85b95e1'
+paths = ['package.json', 'scripts/telemetry-hub/journal.mjs', 'scripts/telemetry-hub/sentry-sender.mjs', 'scripts/sentry-partial-ack.node-test.mjs', 'docs/rollouts/2026-11-03-sentry-partial-acks.md']
+def git(*args):
+ return subprocess.check_output(['git', '-C', str(root), *args], text=True).strip()
+if git('rev-parse', 'HEAD') != local_head or git('rev-parse', 'HEAD^2') != main_head or git('rev-parse', 'HEAD^{tree}') != expected_tree or git('status', '--porcelain'):
+ raise SystemExit('Reviewed merge source changed')
+if set(git('diff', '--name-only', main_head, local_head).splitlines()) != set(paths):
+ raise SystemExit('Merge includes an unexpected changed file')
+receipt_path = Path('.um1651-main-merge-publish-receipt.json')
+fd = os.open(receipt_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
+receipt = {'phase':'prepared','localHead':local_head,'remoteHead':remote_head,'mainHead':main_head,'expectedTree':expected_tree}
+def save():
+ os.lseek(fd,0,os.SEEK_SET); os.ftruncate(fd,0)
+ os.write(fd,(json.dumps(receipt)+'\n').encode()); os.fsync(fd)
+save()
+p = subprocess.Popen(['/home/jay/.local/libexec/codex-simple-tools'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
+def rpc(method, params, identifier):
+ p.stdin.write(json.dumps({'jsonrpc':'2.0','id':identifier,'method':method,'params':params})+'\n');p.stdin.flush()
+ for line in p.stdout:
+ try: result=json.loads(line)
+ except ValueError: continue
+ if result.get('id')==identifier:return result
+ raise RuntimeError('Assigned Relay closed; inspect before retry')
+def call(name, args, identifier):
+ reply=rpc('tools/call',{'name':name,'arguments':{'identity':'CODEX','repo':'Simple-With-Us/Usage-Monitor',**args}},identifier)
+ if 'error' in reply:raise RuntimeError('Relay RPC refused')
+ result=reply.get('result',{}); data=result.get('structuredContent')
+ if data is None:
+ for block in result.get('content',[]):
+ if block.get('type')=='text':
+ try:data=json.loads(block['text']);break
+ except ValueError:continue
+ if not isinstance(data,dict) or result.get('isError') or data.get('code'):
+ raise RuntimeError('Relay operation refused; inspect receipt and destination')
+ return data
+try:
+ if 'error' in rpc('initialize',{'protocolVersion':'2024-11-05','capabilities':{},'clientInfo':{'name':'codex-um1651-merge-publication','version':'1'}},1):raise RuntimeError('Assigned connection refused')
+ p.stdin.write(json.dumps({'jsonrpc':'2.0','method':'notifications/initialized'})+'\n');p.stdin.flush()
+ result=call('gr_wf_git_tree_create',{'base_tree':git('rev-parse',main_head+'^{tree}'),'files':[{'path':path,'mode':'100644','text':(root/path).read_text()} for path in paths]},2)
+ tree=(result.get('tree') or result).get('sha')
+ receipt.update(phase='treeCreated',tree=tree);save()
+ if tree!=expected_tree:raise RuntimeError('Published merge tree differs')
+ result=call('gr_wf_git_commit_create',{'tree_sha':tree,'parents':[remote_head,main_head],'message':'Merge Main And Preserve Both Collector Runtime Gates'},3)
+ commit=(result.get('commit') or result).get('sha')
+ if not isinstance(commit,str) or len(commit)!=40:raise RuntimeError('Created merge commit identity unavailable')
+ receipt.update(phase='commitCreated',commit=commit);save()
+ call('gr_wf_branch_update',{'branch':'codex/um1646-sentry-partial-ack','expected_sha':remote_head,'sha':commit},4)
+ receipt.update(phase='branchUpdated');save()
+ print(json.dumps({'phase':receipt['phase'],'commit':commit,'tree':tree,'parents':[remote_head,main_head]}))
+finally:
+ os.close(fd);p.terminate()
+ try:p.wait(timeout=5)
+ except subprocess.TimeoutExpired:p.kill();p.wait(timeout=5)
diff --git a/publish-um1651-merge-gh-fallback.py b/publish-um1651-merge-gh-fallback.py
new file mode 100644
index 00000000..1e694111
--- /dev/null
+++ b/publish-um1651-merge-gh-fallback.py
@@ -0,0 +1,48 @@
+"""Use the owner's thread-only fallback after the Relay merge-tree refusal."""
+import json
+import os
+from pathlib import Path
+import subprocess
+
+source=Path('/mnt/fleet-extra/apps/lanes/Usage-Monitor/codex-um1646-sentry-partial-ack')
+old='d5441d9b500d553f096d8beac9c9340e4aaf38b7'
+main='5c218189851cbc44dfc7271e3879cda8b481d446'
+local='276ba0e955b255a445282a44072b22af0e50c6d6'
+tree='b0effe5d5afb89f68a7f382a1e92bdccf85b95e1'
+repo='Simple-With-Us/Usage-Monitor'
+branch='codex/um1646-sentry-partial-ack'
+paths=['package.json','scripts/telemetry-hub/journal.mjs','scripts/telemetry-hub/sentry-sender.mjs','scripts/sentry-partial-ack.node-test.mjs','docs/rollouts/2026-11-03-sentry-partial-acks.md']
+def git(*args):return subprocess.check_output(['git','-C',str(source),*args],text=True).strip()
+if git('rev-parse','HEAD')!=local or git('rev-parse','HEAD^{tree}')!=tree or git('status','--porcelain'):
+ raise SystemExit('Reviewed merge source changed')
+def private(path,value):
+ fd=os.open(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600)
+ with os.fdopen(fd,'w') as handle:json.dump(value,handle);handle.flush();os.fsync(handle.fileno())
+def api(path,method='GET',body_path=None):
+ args=['gh','api','repos/'+repo+'/'+path,'--method',method]
+ if body_path:args+=['--input',str(body_path)]
+ p=subprocess.run(args,capture_output=True,text=True)
+ if p.returncode:raise RuntimeError('GitHub operation failed; inspect destination before retry')
+ return json.loads(p.stdout)
+if api('git/ref/heads/'+branch)['object']['sha']!=old:
+ raise SystemExit('Remote branch changed')
+receipt={'phase':'prepared','expectedOldHead':old,'mainParent':main,'localHead':local,'expectedTree':tree}
+receipt_path=Path('.um1651-gh-merge-receipt.json')
+private(receipt_path,receipt)
+def save():
+ with receipt_path.open('w') as handle:json.dump(receipt,handle);handle.flush();os.fsync(handle.fileno())
+body=Path('.um1651-gh-tree-body.json')
+private(body,{'base_tree':git('rev-parse',main+'^{tree}'),'tree':[{'path':p,'mode':'100644','type':'blob','content':(source/p).read_text()} for p in paths]})
+actual=api('git/trees','POST',body)['sha']
+receipt.update(phase='treeCreated',tree=actual);save()
+if actual!=tree:raise SystemExit('Published tree differs from reviewed tree')
+body=Path('.um1651-gh-commit-body.json')
+identity={'name':'Codex','email':'344783151+swu-codex[bot]@users.noreply.github.com'}
+private(body,{'message':'Merge Main And Preserve Both Collector Runtime Gates','tree':tree,'parents':[old,main],'author':identity,'committer':identity})
+commit=api('git/commits','POST',body)['sha']
+receipt.update(phase='commitCreated',commit=commit);save()
+body=Path('.um1651-gh-ref-body.json');private(body,{'sha':commit,'force':False})
+updated=api('git/refs/heads/'+branch,'PATCH',body)
+if updated['object']['sha']!=commit:raise SystemExit('Branch outcome requires readback')
+receipt.update(phase='branchUpdated');save()
+print(json.dumps({'phase':'branchUpdated','commit':commit,'tree':tree,'force':False,'threadSpecificOwnerException':True}))
diff --git a/publish-um1651-reviewed.py b/publish-um1651-reviewed.py
new file mode 100644
index 00000000..50401a6a
--- /dev/null
+++ b/publish-um1651-reviewed.py
@@ -0,0 +1,41 @@
+"""Publish the five reviewed source files through the assigned CODEX Relay."""
+import base64
+import json
+from pathlib import Path
+import subprocess
+
+source = Path('/mnt/fleet-extra/apps/lanes/Usage-Monitor/codex-um1646-sentry-partial-ack')
+expected_commit = '3b7884b096656b9a0e7a274548408a47c97d382d'
+if subprocess.check_output(['git', '-C', str(source), 'rev-parse', 'HEAD'], text=True).strip() != expected_commit:
+ raise SystemExit('Reviewed source commit changed')
+if subprocess.check_output(['git', '-C', str(source), 'status', '--porcelain'], text=True).strip():
+ raise SystemExit('Reviewed source worktree is not clean')
+paths = ['scripts/telemetry-hub/sentry-sender.mjs', 'scripts/telemetry-hub/journal.mjs', 'scripts/sentry-partial-ack.node-test.mjs', 'docs/rollouts/2026-11-03-sentry-partial-acks.md']
+args = {'identity': 'CODEX', 'repo': 'Simple-With-Us/Usage-Monitor', 'branch': 'codex/um1646-sentry-partial-ack', 'expected_head_sha': 'f9c75027e85dab5f9983cbe119128acaad2baf13', 'message': 'Document Reconciled Sentry Hold Recovery And Preserve Its Latch', 'files': [{'path': path, 'content_b64': base64.b64encode((source / path).read_bytes()).decode()} for path in paths]}
+p = subprocess.Popen(['/home/jay/.local/libexec/codex-simple-tools'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
+def send(value):
+ p.stdin.write(json.dumps(value) + '\n')
+ p.stdin.flush()
+def receive(identifier):
+ for line in p.stdout:
+ try: value = json.loads(line)
+ except ValueError: continue
+ if value.get('id') == identifier: return value
+ raise RuntimeError('Assigned wrapper closed; inspect destination before retry')
+try:
+ send({'jsonrpc':'2.0','id':1,'method':'initialize','params':{'protocolVersion':'2024-11-05','capabilities':{},'clientInfo':{'name':'codex-um1651-publication','version':'1'}}})
+ if 'error' in receive(1): raise RuntimeError('Assigned connection initialization refused')
+ send({'jsonrpc':'2.0','method':'notifications/initialized'})
+ send({'jsonrpc':'2.0','id':2,'method':'tools/call','params':{'name':'gr_wf_files_put','arguments':args}})
+ result = receive(2)
+ path = Path('.um1651-relay-publication-' + expected_commit[:12] + '.json')
+ import os
+ fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
+ with os.fdopen(fd, 'w') as handle: json.dump(result, handle)
+ for block in result.get('result', {}).get('content', []):
+ if block.get('type') == 'text': print(block['text'])
+ if 'error' in result: raise SystemExit('Publication outcome requires readback')
+finally:
+ p.terminate()
+ try: p.wait(timeout=5)
+ except subprocess.TimeoutExpired: p.kill(); p.wait(timeout=5)
diff --git a/read-current-operations.py b/read-current-operations.py
new file mode 100644
index 00000000..052b3985
--- /dev/null
+++ b/read-current-operations.py
@@ -0,0 +1,9 @@
+import subprocess,json,urllib.request
+code='from pathlib import Path; t=Path("/Users/jay/apps/MAC-LOCAL-PROCESSES.md").read_text(); s=t.index("## Usage Monitor Telemetry (UM-1646)"); e=t.find("\\n## ",s+4); print(t[s:e if e>=0 else None])'
+r=subprocess.run(['ssh','mac','python3','-'],input=code,text=True,capture_output=True,timeout=30)
+print(r.stdout if r.returncode==0 else json.dumps({'inventoryReadFailed':True,'exit':r.returncode}))
+for path in ['/api/health','/api/ready?strict=1']:
+ try:
+ with urllib.request.urlopen(urllib.request.Request('https://usage.jays.services'+path,headers={'User-Agent':'Mozilla/5.0'}),timeout=15) as response:
+ v=json.load(response);print(json.dumps({'route':path,'http':response.status,'ok':v.get('ok'),'status':v.get('status'),'revision':v.get('revision')}))
+ except Exception as e: print(json.dumps({'route':path,'error':type(e).__name__}))
diff --git a/read-final-suppression-flag.py b/read-final-suppression-flag.py
new file mode 100644
index 00000000..cb043263
--- /dev/null
+++ b/read-final-suppression-flag.py
@@ -0,0 +1,9 @@
+import json,pathlib,re,subprocess
+inventory=pathlib.Path('/mnt/fleet-extra/Code/Fleet-OPS/ATTACK-MAP.md').read_text()
+row=next(x for x in inventory.splitlines()if x.startswith('| Usage Monitor |'))
+name=re.findall(r'`([^`]+)`',row)[0]
+p=subprocess.run(['docker','inspect',name],capture_output=True,text=True,check=True,timeout=20)
+v=json.loads(p.stdout)[0]
+env=dict(s.split('=',1)for s in v['Config'].get('Env',[])if'='in s)
+raw=env.get('BOTFLEET_CHILD_COVERAGE_DROP')
+print(json.dumps({'flag':'BOTFLEET_CHILD_COVERAGE_DROP','present':raw is not None,'enabled':raw in('1','true'),'unknownValue':raw is not None and raw not in('0','false','1','true',''),'containerRunning':v['State']['Running']}))
diff --git a/read-mounted-hub-metadata.py b/read-mounted-hub-metadata.py
new file mode 100644
index 00000000..3498469e
--- /dev/null
+++ b/read-mounted-hub-metadata.py
@@ -0,0 +1,9 @@
+import json,subprocess,pathlib
+root=pathlib.Path('/tmp/um1646-ops')
+s=json.loads((root/'hub-service.json').read_text())
+def run(args):return subprocess.check_output(args,text=True,timeout=30)
+ids=run(['docker','ps','--filter','ancestor=usage-monitor-telemetry-hub:'+s['source_commit'],'--format','{{.ID}}']).splitlines()
+if len(ids)!=1:raise SystemExit('Expected exactly one current hub')
+code="""const fs=require('node:fs'),crypto=require('node:crypto');const p='/run/secrets/telemetry-hub.json',b=fs.readFileSync(p),c=JSON.parse(b),st=fs.statSync(p),raw=c.TELEMETRY_HUB_SOURCES_JSON;const sources=JSON.parse(raw);const sha=x=>crypto.createHash('sha256').update(x).digest('hex');console.log(JSON.stringify({configSha256:sha(b),sourceMapRawSha256:sha(raw),sourceMembership:sources.map(s=>({id:s.id,platform:s.platform})),configUid:st.uid,configMode:st.mode&511,bindHost:process.env.TELEMETRY_HUB_BIND_HOST,sourceCount:sources.length}));"""
+v=json.loads(run(['docker','exec',ids[0],'node','-e',code]));v['sourceCommit']=s['source_commit']
+print(json.dumps(v))
diff --git a/recover-verified-stop.py b/recover-verified-stop.py
new file mode 100644
index 00000000..6160171a
--- /dev/null
+++ b/recover-verified-stop.py
@@ -0,0 +1,22 @@
+import importlib.util,json,pathlib
+root=pathlib.Path(__file__).resolve().parent
+spec=importlib.util.spec_from_file_location('hub_upgrade',root/'upgrade-reviewed-hub.py');m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
+digest='7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0'
+path=root/'.um1651-hub-upgrade-0a92fcfa39f5b576f498dabc43963c89c47b3713.plan.json'
+p,_=m._plan(path,digest)
+original=m._receipt_path(path,digest,'stop','receipt.json');r=json.loads(m._read_private(original))
+if r.get('state')!='verification_failed' or r.get('reason')!='docker_command_failed':raise SystemExit('Unexpected original outcome')
+base,bind=m._load_routing();api=m._Coolify(base,m._coolify_token(),p['service']['uuid'])
+v,_=m._service_view(api,p)
+if v.get('status') not in m.STOPPED_STATUSES:raise SystemExit('Service not stopped')
+if m._running_ids(m.IMAGE_NAME+':'+p['service']['source_commit']) or m._running_ids(m.IMAGE_NAME+':'+p['targetCommit']):raise SystemExit('Unexpected running hub')
+if m._docker(['ps','-a','--filter','ancestor='+m.IMAGE_NAME+':'+p['service']['source_commit'],'--format','{{.ID}}']).strip():raise SystemExit('Old container still exists; inspect separately')
+m._port_is_free(bind);m._image_identity(p)
+vol=m._docker_json(['volume','inspect',p['durableVolume']])
+if len(vol)!=1 or vol[0].get('Name')!=p['durableVolume']:raise SystemExit('Volume changed')
+code="const fs=require('node:fs'),c=require('node:crypto'),p='/run/secrets/telemetry-hub.json',s=fs.statSync(p);console.log(JSON.stringify({configSha256:c.createHash('sha256').update(fs.readFileSync(p)).digest('hex'),configUid:s.uid,configMode:s.mode&511}));"
+data=json.loads(m._docker(['run','--rm','--network','none','--read-only','--cap-drop','ALL','--security-opt','no-new-privileges','--mount','type=bind,src='+p['configMountSource']+',dst=/run/secrets/telemetry-hub.json,readonly','--entrypoint','node',m.IMAGE_NAME+':'+p['targetCommit'],'-e',code]))
+if any(data[k]!=p['metadata'][k] for k in data):raise SystemExit('Configuration changed')
+receipt={'phase':'stop','state':'verified','planSha256':digest,'originalReceiptSha256':m._sha(m._read_private(original)),'independentReadOnlyVerification':True,'serviceStopped':True,'oldContainerRemoved':True,'privatePortFree':True,'durableVolumePreserved':True,**data}
+m._write_exclusive(m._receipt_path(path,digest,'stop','independent-readback.json'),receipt)
+print(json.dumps(receipt))
diff --git a/sentry-historic-claude-receipts.audit.py b/sentry-historic-claude-receipts.audit.py
new file mode 100644
index 00000000..5c2920dc
--- /dev/null
+++ b/sentry-historic-claude-receipts.audit.py
@@ -0,0 +1,137 @@
+import json
+import math
+import re
+import subprocess
+import urllib.parse
+import urllib.request
+import urllib.error
+
+
+START = "2026-10-29T05:00:00Z"
+END = "2026-10-31T05:00:00Z"
+EVENTS_PATH = "/api/0/organizations/simple-with-us/events/"
+
+
+auth = subprocess.run(
+ ["fleet-secrets", "get", "SENTRY_ADMIN"],
+ capture_output=True,
+ text=True,
+ timeout=30,
+)
+if auth.returncode:
+ raise SystemExit("Approved Sentry read route unavailable")
+token = auth.stdout.strip()
+if not token:
+ raise SystemExit("Approved Sentry read route unavailable")
+
+
+class NoRedirect(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, *args, **kwargs):
+ return None
+
+
+opener = urllib.request.build_opener(NoRedirect())
+
+
+def get(url):
+ parsed = urllib.parse.urlparse(url)
+ if (
+ parsed.scheme != "https"
+ or parsed.hostname != "sentry.io"
+ or parsed.username
+ or parsed.password
+ ):
+ raise SystemExit("Untrusted Sentry query target")
+ request = urllib.request.Request(
+ url,
+ headers={"Authorization": "Bearer " + token, "Accept": "application/json"},
+ )
+ with opener.open(request, timeout=30) as response:
+ return json.load(response), response.headers
+
+
+project, _ = get("https://sentry.io/api/0/projects/simple-with-us/agent-sessions/")
+project_id = str(project.get("id", ""))
+if not project_id.isdigit():
+ raise SystemExit("Sentry project identity unavailable")
+
+
+def safe_label(value):
+ if value is None:
+ return None
+ if isinstance(value, str) and len(value) <= 160 and re.fullmatch(r"[a-zA-Z0-9._:/@+-]*", value):
+ return value
+ raise ValueError("Invalid aggregate label")
+
+
+for dataset in ("spans", "logs"):
+ params = [
+ ("dataset", dataset),
+ ("project", project_id),
+ ("field", "agent.platform"),
+ ("field", "service.name"),
+ ("field", "count()"),
+ ("start", START),
+ ("end", END),
+ ("per_page", "100"),
+ (
+ "query",
+ "agent.platform:claude-code service.name:telemetry-hub* "
+ "!gen_ai.request.model:telemetry-verification*",
+ ),
+ ]
+ url = "https://sentry.io" + EVENTS_PATH + "?" + urllib.parse.urlencode(params)
+ totals = {}
+ pages = 0
+ try:
+ while url:
+ result, headers = get(url)
+ data = result.get("data") if isinstance(result, dict) else None
+ if not isinstance(data, list):
+ raise ValueError("Invalid aggregate response")
+ for row in data:
+ count = row.get("count()")
+ platform = safe_label(row.get("agent.platform"))
+ source = safe_label(row.get("service.name"))
+ if (
+ isinstance(count, bool)
+ or not isinstance(count, (int, float))
+ or not math.isfinite(count)
+ or count < 0
+ or platform != "claude-code"
+ or not isinstance(source, str)
+ or not source.startswith("telemetry-hub")
+ ):
+ raise ValueError("Invalid aggregate row")
+ totals[(platform, source)] = totals.get((platform, source), 0) + count
+ pages += 1
+ next_url = None
+ for link in headers.get("Link", "").split(","):
+ if 'rel="next"' in link and 'results="true"' in link:
+ match = re.search(r"<([^>]+)>", link)
+ if match:
+ next_url = match.group(1)
+ if next_url:
+ parsed = urllib.parse.urlparse(next_url)
+ next_params = urllib.parse.parse_qs(parsed.query)
+ if (
+ parsed.path != EVENTS_PATH
+ or parsed.hostname != "sentry.io"
+ or next_params.get("project") != [project_id]
+ or next_params.get("start") != [START]
+ or next_params.get("end") != [END]
+ or next_params.get("dataset") != [dataset]
+ ):
+ raise ValueError("Invalid pagination target")
+ url = next_url
+ if pages >= 10 and url:
+ raise ValueError("Receipt pagination bound reached")
+ rows = [
+ {"platform": platform, "source": source, "count": count}
+ for (platform, source), count in sorted(totals.items())
+ ]
+ print(json.dumps({"dataset": dataset, "start": START, "end": END, "rows": rows, "complete": True}))
+ except urllib.error.HTTPError as error:
+ print(json.dumps({"dataset": dataset, "start": START, "end": END, "http_status": error.code, "complete": False}))
+ except Exception as error:
+ print(json.dumps({"dataset": dataset, "start": START, "end": END, "error_type": type(error).__name__, "complete": False}))
diff --git a/test_child_config_local_cas.py b/test_child_config_local_cas.py
new file mode 100644
index 00000000..ae58647b
--- /dev/null
+++ b/test_child_config_local_cas.py
@@ -0,0 +1,130 @@
+"""Fixture-only tests for the private child configuration CAS helper."""
+
+from __future__ import annotations
+
+import os
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+import child_config_local_cas as cas
+
+
+class ChildConfigLocalCASTests(unittest.TestCase):
+ def setUp(self) -> None:
+ self.tempdir = tempfile.TemporaryDirectory(prefix="child-config-cas-")
+ self.root = Path(self.tempdir.name)
+ self.source = self.root / "usage-monitor.env"
+ self.original = b"UNRELATED_SECRET=fixture-only-value\nOTHER_SETTING=keep-this-byte-for-byte\n"
+ self.source.write_bytes(self.original)
+ self.source.chmod(0o600)
+ self.subject = cas.ChildConfigLocalCAS(self.source)
+
+ def tearDown(self) -> None:
+ self.tempdir.cleanup()
+
+ def test_backup_and_append_preserve_unrelated_bytes_and_metadata(self) -> None:
+ before = self.subject.snapshot()
+ backup_result = self.subject.prepare_backup(before)
+ self.assertEqual(backup_result["backup"], "created_and_verified")
+ backup = self.root / cas.BACKUP_NAME
+ self.assertEqual(backup.read_bytes(), self.original)
+ self.assertEqual(backup.stat().st_mode & 0o777, 0o600)
+ self.assertEqual(backup.stat().st_uid, os.getuid())
+
+ result = self.subject.apply_local(before)
+ self.assertEqual(result["status"], "applied_and_verified")
+ updated = self.source.read_bytes()
+ self.assertTrue(updated.startswith(self.original))
+ self.assertIn(
+ b"OPENCODE_ADDITIONAL_DBS_JSON='[\"/mnt/fleet-extra/apps/botfleet-server/home/.local/share/opencode/opencode.db\"]'\n",
+ updated,
+ )
+ self.assertIn(
+ b"BOTFLEET_WORKSPACES_DIRS=/mnt/fleet-extra/apps/botfleet-server/data/workspaces\n",
+ updated,
+ )
+ source_stat = self.source.stat()
+ self.assertEqual(source_stat.st_mode & 0o777, 0o600)
+ self.assertEqual(source_stat.st_uid, os.getuid())
+ self.assertEqual(source_stat.st_gid, before.gid)
+
+ def test_change_after_backup_aborts_without_overwriting_concurrent_bytes(self) -> None:
+ before = self.subject.snapshot()
+ self.subject.prepare_backup(before)
+ concurrent = self.original + b"CONCURRENT=preserve\n"
+ self.source.write_bytes(concurrent)
+ self.source.chmod(0o600)
+
+ with self.assertRaises(cas.CASFailure):
+ self.subject.apply_local(before)
+ self.assertEqual(self.source.read_bytes(), concurrent)
+
+ def test_different_and_duplicate_target_assignments_are_rejected(self) -> None:
+ cases = (
+ b'OPENCODE_ADDITIONAL_DBS_JSON="[]"\n',
+ (b'BOTFLEET_WORKSPACES_DIRS=/first\n'
+ b'BOTFLEET_WORKSPACES_DIRS=/second\n'),
+ )
+ for contents in cases:
+ with self.subTest(contents=contents):
+ self.source.write_bytes(contents)
+ self.source.chmod(0o600)
+ with self.assertRaises(cas.CASFailure):
+ self.subject.snapshot()
+
+ def test_symlink_source_and_backup_are_rejected(self) -> None:
+ real_source = self.root / "real.env"
+ real_source.write_bytes(self.original)
+ self.source.unlink()
+ self.source.symlink_to(real_source)
+ with self.assertRaises(cas.CASFailure):
+ self.subject.snapshot()
+
+ self.source.unlink()
+ self.source.write_bytes(self.original)
+ self.source.chmod(0o600)
+ before = self.subject.snapshot()
+ backup_target = self.root / "backup-target"
+ backup_target.write_bytes(self.original)
+ (self.root / cas.BACKUP_NAME).symlink_to(backup_target)
+ with self.assertRaises(cas.CASFailure):
+ self.subject.prepare_backup(before)
+
+ def test_exported_equal_keys_are_recognized_without_backup(self) -> None:
+ exported = (
+ b"export OPENCODE_ADDITIONAL_DBS_JSON='"
+ b'["/mnt/fleet-extra/apps/botfleet-server/home/.local/share/opencode/opencode.db"]'
+ b"'\nexport BOTFLEET_WORKSPACES_DIRS="
+ b"/mnt/fleet-extra/apps/botfleet-server/data/workspaces\n"
+ )
+ self.source.write_bytes(exported)
+ self.source.chmod(0o600)
+ before = self.subject.snapshot()
+ self.assertTrue(all(state == "equal" for state in before.key_states.values()))
+
+ result = self.subject.apply_local(before)
+ self.assertEqual(result["status"], "already_equal")
+ self.assertEqual(self.source.read_bytes(), exported)
+ self.assertFalse((self.root / cas.BACKUP_NAME).exists())
+
+ def test_partial_new_backup_is_preserved_after_write_failure(self) -> None:
+ before = self.subject.snapshot()
+
+ def fail_after_partial_write(fd: int, content: bytes) -> None:
+ os.write(fd, content[:1])
+ raise cas.CASFailure("injected_write_failure")
+
+ with mock.patch.object(cas, "_write_all", side_effect=fail_after_partial_write):
+ with self.assertRaises(cas.CASFailure):
+ self.subject.prepare_backup(before)
+
+ backup = self.root / cas.BACKUP_NAME
+ self.assertTrue(backup.exists())
+ self.assertEqual(backup.read_bytes(), self.original[:1])
+ self.assertEqual(backup.stat().st_mode & 0o777, 0o600)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_um1646_inventory_update_fixture.py b/test_um1646_inventory_update_fixture.py
new file mode 100644
index 00000000..2f0f4469
--- /dev/null
+++ b/test_um1646_inventory_update_fixture.py
@@ -0,0 +1,67 @@
+import importlib.util
+from pathlib import Path
+import unittest
+
+
+HELPER = Path(__file__).with_name("prepare-um1646-inventory-update.py")
+SPEC = importlib.util.spec_from_file_location("um1646_inventory_update", HELPER)
+MODULE = importlib.util.module_from_spec(SPEC)
+assert SPEC and SPEC.loader
+SPEC.loader.exec_module(MODULE)
+
+
+class InventoryUpdateFixtureTests(unittest.TestCase):
+ def test_note_inserts_six_rows_and_preserves_surrounding_and_peer_bytes(self):
+ prefix = b"Unrelated prior content
\n"
+ heading = (
+ b''
+ )
+ gap = b"\n
\n
\n"
+ private = b"Private runtime routing and credentials remain in the private operations inventory and Infisical.
"
+ peer = b"\nMuse is installed but remains unloaded under the injector hold.
\n"
+ source = prefix + heading + gap + private + peer
+ botfleet = (
+ b"| botfleet-session-collector.mjs | Mac and server active; first Mac pass stored 152 "
+ b"authentic turn spans; " + MODULE.BOTFLEET_OLD_TAIL + b" |"
+ )
+ inventory = b"\n".join((
+ b"## Usage Monitor Telemetry (UM-1646)",
+ b"| Process / Helper | Schedule And Purpose |",
+ MODULE.HUB_ROW,
+ MODULE.BRIDGE_ROW,
+ b"| scripts/prune-collector-sentry-outbox.mjs | " + MODULE.PRUNE_DESCRIPTION.encode() + b" |",
+ b"| scripts/retry-collector-sentry-outbox.mjs | " + MODULE.RETRY_DESCRIPTION.encode() + b" |",
+ botfleet,
+ b"| UM-1646 Sentry Receipt Audit | " + MODULE.AUDIT_DESCRIPTION.encode() + b" |",
+ )) + b"\n"
+ inventory_after = MODULE._replace_inventory_rows(inventory)
+
+ after, old_section, new_section = MODULE._note_after(source, inventory_after)
+
+ self.assertEqual(old_section, heading + gap)
+ self.assertEqual(after[:len(prefix)], prefix)
+ self.assertTrue(after.endswith(private + peer))
+ self.assertEqual(new_section.count(b""), 6)
+ self.assertIn(b"scripts/prune-collector-sentry-outbox.mjs", new_section)
+ self.assertIn(b"scripts/retry-collector-sentry-outbox.mjs", new_section)
+ self.assertIn(b"UM-1646 Sentry Receipt Audit", new_section)
+ self.assertIn(b"all eight retained child events are classified BotFleet", new_section)
+ self.assertIn(b"first Mac pass stored 152 authentic turn spans", new_section)
+ self.assertIn(b"/mnt/fleet-extra/apps/botfleet-server/data/workspaces", new_section)
+
+ def test_nonblank_note_section_is_refused_without_changing_fixture(self):
+ heading = b"Usage Monitor Telemetry (UM-1646)
"
+ source = (
+ heading + b"\nPeer addition that must remain untouched.
\n"
+ b"Private runtime routing and credentials remain in the private operations inventory and Infisical.
"
+ )
+ with self.assertRaisesRegex(MODULE.UpdateFailure, "note_target_section_not_blank"):
+ MODULE._note_after(source, b"")
+ self.assertIn(b"Peer addition that must remain untouched.", source)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test_upgrade_reviewed_hub.py b/test_upgrade_reviewed_hub.py
new file mode 100644
index 00000000..24378163
--- /dev/null
+++ b/test_upgrade_reviewed_hub.py
@@ -0,0 +1,327 @@
+"""Mocked phase tests; every file and service response is a temporary fixture."""
+
+from __future__ import annotations
+
+import base64
+import contextlib
+import copy
+import hashlib
+import importlib.util
+import io
+import json
+import os
+from pathlib import Path
+import sys
+import tempfile
+import unittest
+from unittest import mock
+
+import yaml
+
+
+MODULE_PATH = Path(__file__).with_name("upgrade-reviewed-hub.py")
+SPEC = importlib.util.spec_from_file_location("upgrade_reviewed_hub_fixture", MODULE_PATH)
+assert SPEC is not None and SPEC.loader is not None
+UPGRADE = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(UPGRADE)
+
+
+TARGET = "a" * 40
+OLD = "b" * 40
+SERVICE_UUID = "a4tp0kk9jmfibzvbmsxvmtqg"
+BIND_HOST = "127.0.0.1"
+CONFIG_SOURCE = "/tmp/fixture-secrets/telemetry-hub.json"
+CONFIG_SHA = "4de" + "1" * 61
+TARGET_IMAGE_ID = "sha256:target-image-fixture"
+OLD_IMAGE_ID = "sha256:old-image-fixture"
+OLD_CONTAINER_ID = "old-container-fixture"
+NEW_CONTAINER_ID = "new-container-fixture"
+VOLUME_NAME = "botfleet-server_telemetry-hub-journal"
+
+
+def compose_fixture() -> dict[str, object]:
+ return {
+ "services": {
+ "telemetry-hub": {
+ "image": f"{UPGRADE.IMAGE_NAME}:{OLD}",
+ "network_mode": "host",
+ "read_only": True,
+ "labels": {"telemetry.commit": OLD, "fixture.keep": "unchanged"},
+ "environment": {
+ "TELEMETRY_HUB_CONFIG_FILE": "/run/secrets/telemetry-hub.json",
+ "TELEMETRY_HUB_BIND_HOST": BIND_HOST,
+ },
+ "volumes": [
+ "journal:/data",
+ {"type": "bind", "source": CONFIG_SOURCE,
+ "target": "/run/secrets/telemetry-hub.json", "read_only": True},
+ ],
+ },
+ },
+ "volumes": {
+ "journal": {"name": VOLUME_NAME, "external": True},
+ },
+ }
+
+
+def plan_fixture() -> dict[str, object]:
+ raw = compose_fixture()
+ return {
+ "mode": "plan-only",
+ "targetCommit": TARGET,
+ "targetImageId": TARGET_IMAGE_ID,
+ "service": {"uuid": SERVICE_UUID, "source_commit": OLD},
+ "serviceStatus": "running:healthy",
+ "oldContainer": OLD_CONTAINER_ID,
+ "oldImageId": OLD_IMAGE_ID,
+ "rawCompose": raw,
+ "rawComposeSha256": hashlib.sha256(UPGRADE._canonical(raw)).hexdigest(),
+ "targetComposeSha256": "0" * 64,
+ "currentCompose": raw,
+ "currentComposeSha256": hashlib.sha256(UPGRADE._canonical(raw)).hexdigest(),
+ "preparedComposeSha256": "1" * 64,
+ "metadata": {
+ "configSha256": CONFIG_SHA,
+ "configUid": 10001,
+ "configMode": 0o600,
+ "journalBase": 0,
+ "journalBytes": 128,
+ "sentryOffset": 128,
+ "pendingBytes": 0,
+ },
+ "durableVolume": VOLUME_NAME,
+ "configMountSource": CONFIG_SOURCE,
+ "upgradeContract": "fixture",
+ "runtimeChanges": False,
+ }
+
+
+class FakeCoolify:
+ def __init__(self, plan: dict[str, object], *, wrong_uuid: bool = False,
+ unknown_stop: bool = False, stop_pending_reads: int = 0,
+ repin_pending_reads: int = 0, start_pending_reads: int = 0):
+ self.plan = plan
+ self.compose = copy.deepcopy(plan["rawCompose"])
+ self.status = "running:healthy"
+ self.uuid = "wrong-uuid-fixture" if wrong_uuid else SERVICE_UUID
+ self.old_running = True
+ self.target_running = False
+ self.unknown_stop = unknown_stop
+ self.stop_pending_reads = stop_pending_reads
+ self.repin_pending_reads = repin_pending_reads
+ self.start_pending_reads = start_pending_reads
+ self.stop_posts = 0
+ self.patch_posts = 0
+ self.start_posts = 0
+ self.requests: list[tuple[str, str]] = []
+
+ def request(self, suffix: str = "", *, method: str = "GET",
+ payload: dict[str, object] | None = None,
+ timeout: float = UPGRADE.HTTP_TIMEOUT_SECONDS) -> object:
+ self.requests.append((method, suffix))
+ if method == "GET":
+ result = self._view()
+ if self.stop_posts and self.stop_pending_reads:
+ self.stop_pending_reads -= 1
+ if not self.stop_pending_reads:
+ self.status = "degraded:unhealthy"
+ elif self.patch_posts and self.repin_pending_reads:
+ self.repin_pending_reads -= 1
+ if not self.repin_pending_reads:
+ self.status = "degraded:unhealthy"
+ elif self.start_posts and self.start_pending_reads:
+ self.start_pending_reads -= 1
+ if not self.start_pending_reads:
+ self.status = "running:healthy"
+ return result
+ if method == "POST" and suffix == "/stop?docker_cleanup=false":
+ self.stop_posts += 1
+ self.old_running = False
+ if self.unknown_stop:
+ raise UPGRADE.fail("HTTPError")
+ if not self.stop_pending_reads:
+ self.status = "degraded:unhealthy"
+ return {"accepted": True}
+ if method == "PATCH" and suffix == "":
+ self.patch_posts += 1
+ encoded = payload["docker_compose_raw"]
+ self.compose = json.loads(base64.b64decode(encoded, validate=True))
+ if self.repin_pending_reads:
+ self.status = "running:healthy"
+ else:
+ self.status = "degraded:unhealthy"
+ return {"updated": True}
+ if method == "POST" and suffix == "/start":
+ self.start_posts += 1
+ self.target_running = True
+ if self.start_pending_reads:
+ self.status = "degraded:unhealthy"
+ else:
+ self.status = "running:healthy"
+ return {"accepted": True}
+ raise AssertionError("unexpected mocked API request")
+
+ def _view(self) -> dict[str, object]:
+ return {
+ "uuid": self.uuid,
+ "status": self.status,
+ "docker_compose_raw": yaml.safe_dump(self.compose, sort_keys=False),
+ }
+
+
+class FakeDocker:
+ def __init__(self, api: FakeCoolify, plan: dict[str, object]):
+ self.api = api
+ self.plan = plan
+ self.metadata = copy.deepcopy(plan["metadata"])
+
+ def json(self, args: list[str], **kwargs: object) -> object:
+ if args[:2] == ["image", "inspect"]:
+ return [{"Id": TARGET_IMAGE_ID, "Config": {"Labels": {
+ UPGRADE.REVISION_LABEL: TARGET,
+ }}}]
+ if args[:1] == ["inspect"] and args[1] in {OLD_CONTAINER_ID, NEW_CONTAINER_ID}:
+ is_target = args[1] == NEW_CONTAINER_ID
+ running = self.api.target_running if is_target else self.api.old_running
+ image_ref = f"{UPGRADE.IMAGE_NAME}:{TARGET if is_target else OLD}"
+ image_id = TARGET_IMAGE_ID if is_target else OLD_IMAGE_ID
+ revision = TARGET if is_target else OLD
+ return [{
+ "Id": args[1],
+ "Image": image_id,
+ "Config": {
+ "Image": image_ref,
+ "User": "10001:10001",
+ "Labels": {UPGRADE.REVISION_LABEL: revision},
+ "Env": [
+ f"COOLIFY_RESOURCE_UUID={SERVICE_UUID}",
+ "TELEMETRY_HUB_CONFIG_FILE=/run/secrets/telemetry-hub.json",
+ f"TELEMETRY_HUB_BIND_HOST={BIND_HOST}",
+ ],
+ },
+ "HostConfig": {
+ "ReadonlyRootfs": True,
+ "NetworkMode": "host",
+ "PortBindings": None,
+ },
+ "Mounts": [
+ {"Type": "volume", "Name": VOLUME_NAME, "Destination": "/data"},
+ {"Type": "bind", "Source": CONFIG_SOURCE,
+ "Destination": "/run/secrets/telemetry-hub.json", "RW": False},
+ ],
+ "State": {
+ "Running": running,
+ "Health": {"Status": "healthy" if running else "unhealthy"},
+ },
+ }]
+ raise AssertionError("unexpected mocked Docker JSON call")
+
+ def bytes(self, args: list[str], **kwargs: object) -> bytes:
+ if args[:1] == ["ps"]:
+ ancestor = next(item.split("=", 1)[1] for item in args if item.startswith("ancestor="))
+ if ancestor.endswith(OLD) and self.api.old_running:
+ return (OLD_CONTAINER_ID + "\n").encode()
+ if ancestor.endswith(TARGET) and self.api.target_running:
+ return (NEW_CONTAINER_ID + "\n").encode()
+ return b""
+ if args[:1] == ["exec"]:
+ return json.dumps(self.metadata).encode()
+ raise AssertionError("unexpected mocked Docker call")
+
+
+class UpgradeReviewedHubTests(unittest.TestCase):
+ def setUp(self) -> None:
+ self.tempdir = tempfile.TemporaryDirectory(prefix="upgrade-reviewed-hub-")
+ self.root = Path(self.tempdir.name)
+ self.plan = plan_fixture()
+ self.plan_path = self.root / f".um1651-hub-upgrade-{TARGET}.plan.json"
+ self.plan_bytes = json.dumps(self.plan, sort_keys=True, indent=2).encode() + b"\n"
+ self.plan_path.write_bytes(self.plan_bytes)
+ self.plan_path.chmod(0o600)
+ self.plan_sha = hashlib.sha256(self.plan_bytes).hexdigest()
+ self.api = FakeCoolify(self.plan)
+ self.docker = FakeDocker(self.api, self.plan)
+
+ def tearDown(self) -> None:
+ self.tempdir.cleanup()
+
+ def execute_phase(self, phase: str) -> dict[str, object]:
+ stdout = io.StringIO()
+ with contextlib.redirect_stdout(stdout), \
+ mock.patch.object(sys, "argv", ["upgrade-reviewed-hub.py", phase,
+ str(self.plan_path), self.plan_sha]), \
+ mock.patch.object(UPGRADE, "_load_routing", return_value=(
+ "https://host.jays.services/api/v1", BIND_HOST)), \
+ mock.patch.object(UPGRADE, "_coolify_token", return_value="fixture-only-token"), \
+ mock.patch.object(UPGRADE, "_Coolify", return_value=self.api), \
+ mock.patch.object(UPGRADE, "_docker_json", side_effect=self.docker.json), \
+ mock.patch.object(UPGRADE, "_docker", side_effect=self.docker.bytes), \
+ mock.patch.object(UPGRADE, "_port_is_free"), \
+ mock.patch.object(UPGRADE, "POSTCONDITION_POLL_SECONDS", 0):
+ self.assertEqual(UPGRADE.run(), 0)
+ return json.loads(stdout.getvalue())
+
+ def test_three_phases_preserve_raw_generated_volume_and_update_once(self) -> None:
+ self.api.stop_pending_reads = 1
+ self.api.repin_pending_reads = 1
+ self.api.start_pending_reads = 1
+ self.assertEqual(self.execute_phase("stop")["state"], "verified")
+ self.assertEqual(self.execute_phase("repin")["state"], "verified")
+ result = self.execute_phase("start")
+ self.assertEqual(result["state"], "verified")
+ self.assertEqual(self.api.stop_posts, 1)
+ self.assertEqual(self.api.patch_posts, 1)
+ self.assertEqual(self.api.start_posts, 1)
+
+ expected = copy.deepcopy(self.plan["rawCompose"])
+ expected["services"]["telemetry-hub"]["image"] = f"{UPGRADE.IMAGE_NAME}:{TARGET}"
+ expected["services"]["telemetry-hub"]["labels"]["telemetry.commit"] = TARGET
+ self.assertEqual(self.api.compose, expected)
+ self.assertEqual(self.api.compose["volumes"], self.plan["rawCompose"]["volumes"])
+ self.assertEqual(
+ self.api.compose["services"]["telemetry-hub"]["labels"]["fixture.keep"],
+ "unchanged",
+ )
+
+ def test_raw_compose_compare_failure_prevents_stop(self) -> None:
+ self.api.compose["services"]["telemetry-hub"]["environment"]["DRIFT"] = "fixture"
+ with self.assertRaises(UPGRADE.PhaseFailure):
+ self.execute_phase("stop")
+ self.assertEqual(self.api.stop_posts, 0)
+
+ def test_mismatched_service_uuid_prevents_stop(self) -> None:
+ self.api.uuid = "z" * 24
+ with self.assertRaises(UPGRADE.PhaseFailure):
+ self.execute_phase("stop")
+ self.assertEqual(self.api.stop_posts, 0)
+
+ def test_duplicate_claim_prevents_any_api_call(self) -> None:
+ claim = UPGRADE._receipt_path(self.plan_path, self.plan_sha, "stop", "claim.json")
+ claim.write_text("fixture claim")
+ claim.chmod(0o600)
+ with self.assertRaises(UPGRADE.PhaseFailure):
+ self.execute_phase("stop")
+ self.assertEqual(self.api.requests, [])
+
+ def test_unknown_stop_response_records_claim_and_never_retries_post(self) -> None:
+ self.api.unknown_stop = True
+ with self.assertRaises(UPGRADE.PhaseFailure):
+ self.execute_phase("stop")
+ self.assertEqual(self.api.stop_posts, 1)
+ receipt = UPGRADE._receipt_path(self.plan_path, self.plan_sha, "stop", "receipt.json")
+ value = json.loads(receipt.read_bytes())
+ self.assertEqual(value["state"], "outcome_unknown")
+ with self.assertRaises(UPGRADE.PhaseFailure):
+ self.execute_phase("stop")
+ self.assertEqual(self.api.stop_posts, 1)
+
+ def test_coolify_path_allowlist_rejects_non_service_route_without_opening(self) -> None:
+ client = UPGRADE._Coolify("https://example.invalid/api/v1", "fixture-token", SERVICE_UUID)
+ with mock.patch.object(client, "_opener") as opener:
+ with self.assertRaises(UPGRADE.PhaseFailure):
+ client.request("/other", method="DELETE")
+ opener.open.assert_not_called()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/upgrade-reviewed-hub.py b/upgrade-reviewed-hub.py
new file mode 100644
index 00000000..7f66fc69
--- /dev/null
+++ b/upgrade-reviewed-hub.py
@@ -0,0 +1,807 @@
+#!/usr/bin/env python3
+"""Run one explicitly selected, plan-bound telemetry hub upgrade phase."""
+
+from __future__ import annotations
+
+import argparse
+import base64
+import copy
+import hashlib
+import ipaddress
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import socket
+import stat
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.request
+
+import yaml
+
+
+OPS_ROOT = Path("/tmp/um1646-ops")
+IMAGE_NAME = "usage-monitor-telemetry-hub"
+REVISION_LABEL = "org.opencontainers.image.revision"
+MAX_PRIVATE_JSON = 4 * 1024 * 1024
+HTTP_TIMEOUT_SECONDS = 25
+COMMAND_TIMEOUT_SECONDS = 35
+POSTCONDITION_TIMEOUT_SECONDS = 20
+POSTCONDITION_POLL_SECONDS = 2
+STOPPED_STATUSES = {"exited", "stopped", "degraded:unhealthy"}
+STARTED_STATUSES = {"running", "healthy", "running:healthy"}
+METADATA_KEYS = {
+ "configSha256", "configUid", "configMode", "journalBase",
+ "journalBytes", "sentryOffset", "pendingBytes",
+}
+
+
+class PhaseFailure(Exception):
+ """A sanitized refusal containing a reason code only."""
+
+
+def fail(reason: str) -> PhaseFailure:
+ return PhaseFailure(reason)
+
+
+def _sha(data: bytes) -> str:
+ return hashlib.sha256(data).hexdigest()
+
+
+def _canonical(value: object) -> bytes:
+ return json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8")
+
+
+def _open_private(path: Path) -> tuple[int, os.stat_result]:
+ try:
+ before = os.lstat(path)
+ except OSError:
+ raise fail("private_file_unavailable") from None
+ if (not stat.S_ISREG(before.st_mode) or before.st_uid != os.getuid()
+ or stat.S_IMODE(before.st_mode) != 0o600
+ or before.st_size < 0 or before.st_size > MAX_PRIVATE_JSON):
+ raise fail("private_file_metadata_invalid")
+ flags = (os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)
+ | getattr(os, "O_NONBLOCK", 0))
+ try:
+ fd = os.open(path, flags)
+ except OSError:
+ raise fail("private_file_open_failed") from None
+ opened = os.fstat(fd)
+ if (not stat.S_ISREG(opened.st_mode) or opened.st_dev != before.st_dev
+ or opened.st_ino != before.st_ino or opened.st_uid != before.st_uid
+ or opened.st_size != before.st_size or opened.st_mtime_ns != before.st_mtime_ns
+ or stat.S_IMODE(opened.st_mode) != 0o600):
+ os.close(fd)
+ raise fail("private_file_changed")
+ return fd, before
+
+
+def _read_private(path: Path) -> bytes:
+ fd, before = _open_private(path)
+ try:
+ chunks: list[bytes] = []
+ remaining = MAX_PRIVATE_JSON + 1
+ while remaining:
+ chunk = os.read(fd, min(64 * 1024, remaining))
+ if not chunk:
+ break
+ chunks.append(chunk)
+ remaining -= len(chunk)
+ data = b"".join(chunks)
+ after_fd = os.fstat(fd)
+ after_path = os.lstat(path)
+ if (len(data) > MAX_PRIVATE_JSON or len(data) != before.st_size
+ or after_fd.st_dev != before.st_dev or after_fd.st_ino != before.st_ino
+ or after_fd.st_size != before.st_size or after_fd.st_mtime_ns != before.st_mtime_ns
+ or after_path.st_dev != before.st_dev or after_path.st_ino != before.st_ino
+ or after_path.st_size != before.st_size or after_path.st_mtime_ns != before.st_mtime_ns):
+ raise fail("private_file_changed")
+ return data
+ finally:
+ os.close(fd)
+
+
+def _write_all(fd: int, data: bytes) -> None:
+ view = memoryview(data)
+ while view:
+ size = os.write(fd, view)
+ if size <= 0:
+ raise fail("private_write_failed")
+ view = view[size:]
+
+
+def _write_exclusive(path: Path, value: dict[str, object]) -> None:
+ payload = json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8") + b"\n"
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_CLOEXEC", 0)
+ flags |= getattr(os, "O_NOFOLLOW", 0)
+ try:
+ fd = os.open(path, flags, 0o600)
+ except OSError:
+ raise fail("phase_record_exists_or_unavailable") from None
+ try:
+ os.fchmod(fd, 0o600)
+ os.fchown(fd, os.getuid(), os.getgid())
+ _write_all(fd, payload)
+ os.fsync(fd)
+ finally:
+ os.close(fd)
+ parent_fd = os.open(path.parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
+ try:
+ os.fsync(parent_fd)
+ finally:
+ os.close(parent_fd)
+
+
+def _plan(path: Path, claimed_sha: str) -> tuple[dict[str, object], str]:
+ data = _read_private(path)
+ digest = _sha(data)
+ if digest != claimed_sha:
+ raise fail("plan_sha256_mismatch")
+ try:
+ value = json.loads(data)
+ except (UnicodeDecodeError, json.JSONDecodeError):
+ raise fail("plan_json_invalid") from None
+ if not isinstance(value, dict) or value.get("mode") != "plan-only" or value.get("runtimeChanges") is not False:
+ raise fail("plan_shape_invalid")
+ target = value.get("targetCommit")
+ service = value.get("service")
+ if (not isinstance(target, str) or not re.fullmatch(r"[a-f0-9]{40}", target)
+ or not isinstance(service, dict)
+ or not isinstance(service.get("uuid"), str)
+ or not re.fullmatch(r"[a-z0-9]{24}", service["uuid"])
+ or not isinstance(service.get("source_commit"), str)
+ or not re.fullmatch(r"[a-f0-9]{40}", service["source_commit"])):
+ raise fail("plan_identity_invalid")
+ raw_compose = value.get("rawCompose")
+ if (not isinstance(raw_compose, dict)
+ or _sha(_canonical(raw_compose)) != value.get("rawComposeSha256")):
+ raise fail("plan_raw_compose_hash_invalid")
+ if (not isinstance(value.get("targetImageId"), str)
+ or not isinstance(value.get("oldContainer"), str)
+ or not isinstance(value.get("oldImageId"), str)
+ or not isinstance(value.get("durableVolume"), str)
+ or not isinstance(value.get("configMountSource"), str)
+ or not isinstance(value.get("metadata"), dict)
+ or set(value["metadata"]) != METADATA_KEYS):
+ raise fail("plan_runtime_metadata_invalid")
+ if set(raw_compose.get("services", {})) != {"telemetry-hub"}:
+ raise fail("plan_service_membership_invalid")
+ unit = raw_compose["services"]["telemetry-hub"]
+ if (not isinstance(unit, dict)
+ or unit.get("image") != f"{IMAGE_NAME}:{service['source_commit']}"
+ or unit.get("network_mode") != "host"
+ or unit.get("read_only") is not True
+ or unit.get("ports") or unit.get("networks")):
+ raise fail("plan_original_service_invariants_invalid")
+ labels = unit.get("labels")
+ if not isinstance(labels, dict) or labels.get("telemetry.commit") != service["source_commit"]:
+ raise fail("plan_commit_label_invalid")
+ return value, digest
+
+
+def _load_routing() -> tuple[str, str]:
+ try:
+ routing = json.loads((OPS_ROOT / "hub-routing.json").read_bytes())
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError):
+ raise fail("routing_inventory_unavailable") from None
+ base_url = routing.get("base_url") if isinstance(routing, dict) else None
+ bind = routing.get("tailnet_bind") if isinstance(routing, dict) else None
+ if base_url not in ("http://100.69.77.26:8000/api/v1", "https://host.jays.services/api/v1"):
+ raise fail("coolify_route_not_approved")
+ try:
+ ipaddress.ip_address(bind)
+ except (ValueError, TypeError):
+ raise fail("private_bind_invalid") from None
+ return base_url, bind
+
+
+def _coolify_token() -> str:
+ try:
+ result = subprocess.run(
+ ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "mac",
+ "fleet-secrets", "get", "COOLIFY_AGENTS"],
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=30, check=False,
+ )
+ except OSError as error:
+ raise fail(type(error).__name__) from None
+ except subprocess.TimeoutExpired:
+ raise fail("credential_route_timeout") from None
+ if result.returncode:
+ raise fail("credential_route_failed")
+ try:
+ token = result.stdout.decode("utf-8", "strict").strip()
+ except UnicodeDecodeError:
+ raise fail("credential_encoding_invalid") from None
+ if not token:
+ raise fail("credential_unavailable")
+ return token
+
+
+class _NoRedirect(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
+ return None
+
+
+class _Coolify:
+ def __init__(self, base_url: str, token: str, service_uuid: str):
+ if not re.fullmatch(r"[a-z0-9]{24}", service_uuid):
+ raise fail("service_uuid_invalid")
+ self._base = base_url
+ self._token = token
+ self._service_path = "/services/" + service_uuid
+ self._opener = urllib.request.build_opener(_NoRedirect())
+
+ def request(self, suffix: str = "", *, method: str = "GET",
+ payload: dict[str, object] | None = None,
+ timeout: float = HTTP_TIMEOUT_SECONDS) -> object:
+ if (method, suffix) not in {
+ ("GET", ""), ("PATCH", ""),
+ ("POST", "/stop?docker_cleanup=false"), ("POST", "/start"),
+ }:
+ raise fail("coolify_path_not_allowed")
+ if (method == "PATCH") != (payload is not None):
+ raise fail("coolify_payload_not_allowed")
+ body = None if payload is None else json.dumps(payload, separators=(",", ":")).encode()
+ if body is not None and set(payload) != {"docker_compose_raw", "instant_deploy"}:
+ raise fail("coolify_payload_shape_invalid")
+ request = urllib.request.Request(
+ self._base + self._service_path + suffix,
+ data=body,
+ headers={"Authorization": "Bearer " + self._token,
+ "Accept": "application/json", "Content-Type": "application/json"},
+ method=method,
+ )
+ try:
+ with self._opener.open(request, timeout=timeout) as response:
+ data = response.read(MAX_PRIVATE_JSON + 1)
+ if len(data) > MAX_PRIVATE_JSON:
+ raise fail("coolify_response_too_large")
+ return json.loads(data)
+ except (OSError, urllib.error.URLError, urllib.error.HTTPError) as error:
+ raise fail(type(error).__name__) from None
+ except (UnicodeDecodeError, json.JSONDecodeError):
+ raise fail("coolify_response_invalid") from None
+
+
+def _docker_binary() -> str:
+ path = shutil.which("docker")
+ if not path:
+ raise fail("docker_unavailable")
+ return path
+
+
+def _docker(args: list[str], *, check: bool = True,
+ timeout: float = COMMAND_TIMEOUT_SECONDS) -> bytes:
+ try:
+ result = subprocess.run(
+ [_docker_binary(), *args], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
+ timeout=timeout, check=False,
+ )
+ except subprocess.TimeoutExpired:
+ raise fail("docker_command_timeout") from None
+ except OSError as error:
+ raise fail(type(error).__name__) from None
+ if check and result.returncode:
+ raise fail("docker_command_failed")
+ return result.stdout
+
+
+def _docker_json(args: list[str], *, timeout: float = COMMAND_TIMEOUT_SECONDS) -> object:
+ data = _docker(args, timeout=timeout)
+ try:
+ return json.loads(data)
+ except (UnicodeDecodeError, json.JSONDecodeError):
+ raise fail("docker_json_invalid") from None
+
+
+def _image_identity(plan: dict[str, object]) -> None:
+ target = plan["targetCommit"]
+ image = f"{IMAGE_NAME}:{target}"
+ inspect = _docker_json(["image", "inspect", image])
+ if not isinstance(inspect, list) or len(inspect) != 1:
+ raise fail("target_image_missing_or_ambiguous")
+ item = inspect[0]
+ if (item.get("Id") != plan["targetImageId"]
+ or item.get("Config", {}).get("Labels", {}).get(REVISION_LABEL) != target):
+ raise fail("target_image_identity_changed")
+
+
+def _parse_raw_compose(service: object) -> dict[str, object]:
+ if not isinstance(service, dict):
+ raise fail("service_response_invalid")
+ raw = service.get("docker_compose_raw")
+ if not isinstance(raw, str) or not raw:
+ raise fail("raw_compose_missing")
+ try:
+ parsed = yaml.safe_load(raw)
+ except yaml.YAMLError:
+ parsed = None
+ if isinstance(parsed, str):
+ parsed = None
+ if not isinstance(parsed, dict):
+ try:
+ decoded = base64.b64decode(raw, validate=True).decode("utf-8")
+ parsed = yaml.safe_load(decoded)
+ except Exception:
+ raise fail("raw_compose_invalid") from None
+ if not isinstance(parsed, dict):
+ raise fail("raw_compose_invalid")
+ return parsed
+
+
+def _service_view(api: _Coolify, plan: dict[str, object],
+ expected: dict[str, object] | None = None,
+ timeout: float = HTTP_TIMEOUT_SECONDS) -> tuple[dict[str, object], dict[str, object]]:
+ response, compose = _live_service_compose(api, plan, timeout=timeout)
+ comparison = plan["rawCompose"] if expected is None else expected
+ expected_hash = plan["rawComposeSha256"] if expected is None else _sha(_canonical(expected))
+ if _sha(_canonical(compose)) != expected_hash or compose != comparison:
+ raise fail("live_raw_compose_compare_failed")
+ return response, compose
+
+
+def _live_service_compose(api: _Coolify, plan: dict[str, object],
+ *, timeout: float = HTTP_TIMEOUT_SECONDS) -> tuple[dict[str, object], dict[str, object]]:
+ response = api.request(timeout=timeout)
+ if not isinstance(response, dict):
+ raise fail("service_response_invalid")
+ if response.get("uuid") != plan["service"]["uuid"]:
+ raise fail("live_service_identity_mismatch")
+ compose = _parse_raw_compose(response)
+ return response, compose
+
+
+def _target_image_revision(plan: dict[str, object], image: dict[str, object]) -> bool:
+ labels = image.get("Config", {}).get("Labels", {})
+ return labels.get(REVISION_LABEL) == plan["targetCommit"]
+
+
+def _running_ids(image_ref: str, *, timeout: float = COMMAND_TIMEOUT_SECONDS) -> list[str]:
+ data = _docker(["ps", "--filter", "ancestor=" + image_ref, "--format", "{{.ID}}"],
+ timeout=timeout)
+ return [line.strip() for line in data.decode("utf-8", "strict").splitlines() if line.strip()]
+
+
+def _container(container_id: str, *, timeout: float = COMMAND_TIMEOUT_SECONDS) -> dict[str, object]:
+ data = _docker_json(["inspect", container_id], timeout=timeout)
+ if not isinstance(data, list) or len(data) != 1 or not isinstance(data[0], dict):
+ raise fail("container_inspect_invalid")
+ return data[0]
+
+
+def _validate_mounts(container: dict[str, object], plan: dict[str, object]) -> None:
+ mounts = container.get("Mounts")
+ if not isinstance(mounts, list):
+ raise fail("container_mounts_invalid")
+ data = [m for m in mounts if isinstance(m, dict) and m.get("Destination") == "/data"]
+ config = [m for m in mounts if isinstance(m, dict)
+ and m.get("Destination") == "/run/secrets/telemetry-hub.json"]
+ if (len(data) != 1 or data[0].get("Type") != "volume"
+ or data[0].get("Name") != plan["durableVolume"]
+ or len(config) != 1 or config[0].get("Type") != "bind"
+ or config[0].get("Source") != plan["configMountSource"]
+ or config[0].get("RW") is not False):
+ raise fail("container_mount_compare_failed")
+
+
+def _validate_container_identity(container: dict[str, object], plan: dict[str, object],
+ *, target: bool, bind_host: str) -> None:
+ image = container.get("Config", {}).get("Image")
+ expected_ref = f"{IMAGE_NAME}:{plan['targetCommit']}" if target else f"{IMAGE_NAME}:{plan['service']['source_commit']}"
+ expected_image_id = plan["targetImageId"] if target else plan["oldImageId"]
+ expected_revision = plan["targetCommit"] if target else plan["service"]["source_commit"]
+ config = container.get("Config", {})
+ labels = config.get("Labels", {})
+ env = {}
+ for item in config.get("Env", []):
+ if isinstance(item, str) and "=" in item:
+ key, value = item.split("=", 1)
+ env[key] = value
+ host_config = container.get("HostConfig", {})
+ user_uid = str(config.get("User", "")).split(":", 1)[0]
+ if (image != expected_ref or container.get("Image") != expected_image_id
+ or labels.get(REVISION_LABEL) != expected_revision
+ or env.get("COOLIFY_RESOURCE_UUID") != plan["service"]["uuid"]
+ or env.get("TELEMETRY_HUB_CONFIG_FILE") != "/run/secrets/telemetry-hub.json"
+ or env.get("TELEMETRY_HUB_BIND_HOST") != bind_host
+ or user_uid != "10001"
+ or host_config.get("ReadonlyRootfs") is not True
+ or host_config.get("NetworkMode") != "host"
+ or bool(host_config.get("PortBindings"))
+ or any(key.startswith(("SENTRY_", "INFISICAL_"))
+ or key in {"TELEMETRY_HUB_SOURCES_JSON", "USAGE_INGEST_TOKEN"} for key in env)):
+ raise fail("container_identity_or_static_env_invalid")
+ _validate_mounts(container, plan)
+
+
+def _metadata_script() -> str:
+ return r"""const fs=require('node:fs'),crypto=require('node:crypto');
+const cfg='/run/secrets/telemetry-hub.json',st=fs.statSync(cfg);
+const base=JSON.parse(fs.readFileSync('/data/state/journal.base.json'));
+const offset=JSON.parse(fs.readFileSync('/data/state/sentry.offset.json')).offset;
+const bytes=fs.statSync('/data/journal.jsonl').size;
+if(base.pendingSize!==0||!Number.isSafeInteger(base.base)||base.base<0||!Number.isSafeInteger(offset)||offsetbase.base+bytes)throw Error('Unsafe journal snapshot');
+console.log(JSON.stringify({configSha256:crypto.createHash('sha256').update(fs.readFileSync(cfg)).digest('hex'),configUid:st.uid,configMode:st.mode&511,journalBase:base.base,journalBytes:bytes,sentryOffset:offset,pendingBytes:base.base+bytes-offset}));"""
+
+
+def _runtime_metadata(container_id: str, *, timeout: float = COMMAND_TIMEOUT_SECONDS) -> dict[str, object]:
+ output = _docker(["exec", container_id, "node", "-e", _metadata_script()], timeout=timeout)
+ try:
+ value = json.loads(output)
+ except (UnicodeDecodeError, json.JSONDecodeError):
+ raise fail("runtime_metadata_invalid") from None
+ if (not isinstance(value, dict) or set(value) != METADATA_KEYS
+ or not isinstance(value["configSha256"], str)
+ or not re.fullmatch(r"[a-f0-9]{64}", value["configSha256"])
+ or any(not isinstance(value[key], int) or isinstance(value[key], bool)
+ for key in METADATA_KEYS - {"configSha256"})):
+ raise fail("runtime_metadata_shape_invalid")
+ return value
+
+
+def _check_metadata_against_plan(actual: dict[str, object], plan: dict[str, object], *, before_stop: bool) -> None:
+ baseline = plan["metadata"]
+ for key in ("configSha256", "configUid", "configMode"):
+ if actual[key] != baseline[key]:
+ raise fail("runtime_config_compare_failed")
+ if actual["configUid"] != 10001 or actual["configMode"] != 0o600:
+ raise fail("runtime_config_custody_invalid")
+ if before_stop:
+ if actual["pendingBytes"] != 0:
+ raise fail("journal_pending_bytes_nonzero")
+ for key in ("journalBase", "journalBytes", "sentryOffset", "pendingBytes"):
+ if actual[key] != baseline[key]:
+ raise fail("journal_source_compare_failed")
+
+
+def _old_runtime(plan: dict[str, object], bind_host: str) -> tuple[str, dict[str, object], dict[str, object]]:
+ image_ref = f"{IMAGE_NAME}:{plan['service']['source_commit']}"
+ ids = _running_ids(image_ref)
+ if ids != [plan["oldContainer"]]:
+ raise fail("original_container_set_changed")
+ container = _container(ids[0])
+ _validate_container_identity(container, plan, target=False, bind_host=bind_host)
+ if container.get("State", {}).get("Running") is not True:
+ raise fail("original_container_not_running")
+ if container.get("State", {}).get("Health", {}).get("Status") != "healthy":
+ raise fail("original_container_not_healthy")
+ metadata = _runtime_metadata(ids[0])
+ _check_metadata_against_plan(metadata, plan, before_stop=True)
+ return ids[0], container, metadata
+
+
+def _receipt_path(plan_path: Path, plan_sha: str, phase: str, suffix: str) -> Path:
+ return plan_path.parent / f".um1651-hub-upgrade-{plan_sha}-{phase}.{suffix}"
+
+
+def _record_claim(plan_path: Path, plan_sha: str, phase: str) -> Path:
+ path = _receipt_path(plan_path, plan_sha, phase, "claim.json")
+ _write_exclusive(path, {"planSha256": plan_sha, "phase": phase, "state": "claimed"})
+ return path
+
+
+def _record_receipt(plan_path: Path, plan_sha: str, phase: str,
+ state: str, metadata: dict[str, object]) -> None:
+ value = {"planSha256": plan_sha, "phase": phase, "state": state, **metadata}
+ _write_exclusive(_receipt_path(plan_path, plan_sha, phase, "receipt.json"), value)
+
+
+def _record_failure_if_missing(plan_path: Path, plan_sha: str, phase: str,
+ state: str, metadata: dict[str, object]) -> None:
+ path = _receipt_path(plan_path, plan_sha, phase, "receipt.json")
+ if not os.path.lexists(path):
+ _record_receipt(plan_path, plan_sha, phase, state, metadata)
+
+
+def _postcondition_delay(deadline: float, reason: str) -> None:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise fail(reason)
+ time.sleep(min(POSTCONDITION_POLL_SECONDS, remaining))
+
+
+def _remaining_timeout(deadline: float, ceiling: float) -> float:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise fail("postcondition_timeout")
+ return min(ceiling, remaining)
+
+
+def _read_receipt(plan_path: Path, plan_sha: str, phase: str) -> dict[str, object]:
+ path = _receipt_path(plan_path, plan_sha, phase, "receipt.json")
+ try:
+ value = json.loads(_read_private(path))
+ except (UnicodeDecodeError, json.JSONDecodeError):
+ raise fail("phase_receipt_invalid") from None
+ if (not isinstance(value, dict) or value.get("planSha256") != plan_sha
+ or value.get("phase") != phase or value.get("state") != "verified"):
+ recovery = _receipt_path(plan_path, plan_sha, phase, "independent-readback.json")
+ try:
+ checked = json.loads(_read_private(recovery))
+ except (OSError, PhaseFailure, ValueError):
+ raise fail("prior_phase_not_verified") from None
+ if (phase != "stop" or checked.get("planSha256") != plan_sha
+ or checked.get("phase") != phase or checked.get("state") != "verified"
+ or checked.get("originalReceiptSha256") != _sha(_read_private(path))):
+ raise fail("independent_readback_invalid")
+ return checked
+ return value
+
+
+def _claim_unused(plan_path: Path, plan_sha: str, phase: str) -> None:
+ claim = _receipt_path(plan_path, plan_sha, phase, "claim.json")
+ receipt = _receipt_path(plan_path, plan_sha, phase, "receipt.json")
+ if claim.exists() or receipt.exists():
+ raise fail("phase_already_claimed_or_recorded")
+
+
+def _claim_after_preflight(plan_path: Path, plan_sha: str, phase: str) -> None:
+ _claim_unused(plan_path, plan_sha, phase)
+ _record_claim(plan_path, plan_sha, phase)
+
+
+def _stop_phase(plan_path: Path, plan_sha: str, plan: dict[str, object],
+ api: _Coolify, bind_host: str) -> dict[str, object]:
+ _claim_unused(plan_path, plan_sha, "stop")
+ service, _ = _service_view(api, plan)
+ if service.get("status") != plan.get("serviceStatus"):
+ raise fail("service_status_compare_failed")
+ _image_identity(plan)
+ container_id, _, metadata = _old_runtime(plan, bind_host)
+ _claim_after_preflight(plan_path, plan_sha, "stop")
+ try:
+ response = api.request("/stop?docker_cleanup=false", method="POST")
+ except PhaseFailure:
+ _record_receipt(plan_path, plan_sha, "stop", "outcome_unknown", {
+ "containerId": container_id,
+ "sourceComposeSha256": plan["rawComposeSha256"],
+ "configSha256": metadata["configSha256"],
+ })
+ raise
+ try:
+ deadline = time.monotonic() + POSTCONDITION_TIMEOUT_SECONDS
+ while True:
+ stopped, _ = _service_view(
+ api, plan, timeout=_remaining_timeout(deadline, HTTP_TIMEOUT_SECONDS),
+ )
+ if stopped.get("status") not in STOPPED_STATUSES:
+ _postcondition_delay(deadline, "stop_postcondition_timeout")
+ continue
+ old = _container(container_id, timeout=_remaining_timeout(deadline, COMMAND_TIMEOUT_SECONDS))
+ if (old.get("State", {}).get("Running") is not False
+ or _running_ids(f"{IMAGE_NAME}:{plan['service']['source_commit']}",
+ timeout=_remaining_timeout(deadline, COMMAND_TIMEOUT_SECONDS))):
+ _postcondition_delay(deadline, "stop_postcondition_timeout")
+ continue
+ break
+ _record_receipt(plan_path, plan_sha, "stop", "verified", {
+ "containerId": container_id,
+ "sourceComposeSha256": plan["rawComposeSha256"],
+ "configSha256": metadata["configSha256"],
+ "stopResponseKeys": sorted(response) if isinstance(response, dict) else [],
+ })
+ except PhaseFailure as error:
+ _record_failure_if_missing(plan_path, plan_sha, "stop", "verification_failed",
+ {"reason": str(error), "containerId": container_id})
+ raise
+ except Exception as error:
+ _record_failure_if_missing(plan_path, plan_sha, "stop", "verification_failed",
+ {"errorType": type(error).__name__, "containerId": container_id})
+ raise fail("stop_verification_failed") from None
+ return {"phase": "stop", "state": "verified"}
+
+
+def _expected_target_compose(plan: dict[str, object]) -> dict[str, object]:
+ result = copy.deepcopy(plan["rawCompose"])
+ unit = result["services"]["telemetry-hub"]
+ labels = unit["labels"]
+ unit["image"] = f"{IMAGE_NAME}:{plan['targetCommit']}"
+ labels["telemetry.commit"] = plan["targetCommit"]
+ return result
+
+
+def _compose_payload(compose: dict[str, object]) -> dict[str, object]:
+ encoded = base64.b64encode(json.dumps(compose, separators=(",", ":")).encode()).decode("ascii")
+ return {"docker_compose_raw": encoded, "instant_deploy": False}
+
+
+def _repin_phase(plan_path: Path, plan_sha: str, plan: dict[str, object],
+ api: _Coolify) -> dict[str, object]:
+ _read_receipt(plan_path, plan_sha, "stop")
+ _claim_unused(plan_path, plan_sha, "repin")
+ current, compose = _service_view(api, plan)
+ if current.get("status") not in STOPPED_STATUSES:
+ raise fail("service_not_stopped")
+ if _running_ids(f"{IMAGE_NAME}:{plan['service']['source_commit']}"):
+ raise fail("old_container_still_running")
+ _image_identity(plan)
+ target_compose = _expected_target_compose(plan)
+ target_hash = _sha(_canonical(target_compose))
+ _claim_after_preflight(plan_path, plan_sha, "repin")
+ try:
+ response = api.request("", method="PATCH", payload=_compose_payload(target_compose))
+ except PhaseFailure:
+ _record_receipt(plan_path, plan_sha, "repin", "outcome_unknown", {
+ "sourceComposeSha256": plan["rawComposeSha256"],
+ "targetComposeSha256": target_hash,
+ "targetImageId": plan["targetImageId"],
+ })
+ raise
+ try:
+ deadline = time.monotonic() + POSTCONDITION_TIMEOUT_SECONDS
+ while True:
+ after, live_compose = _live_service_compose(
+ api, plan, timeout=_remaining_timeout(deadline, HTTP_TIMEOUT_SECONDS),
+ )
+ if live_compose == plan["rawCompose"]:
+ _postcondition_delay(deadline, "repin_postcondition_timeout")
+ continue
+ if live_compose != target_compose or _sha(_canonical(live_compose)) != target_hash:
+ raise fail("repin_postcondition_compare_failed")
+ if after.get("status") not in STOPPED_STATUSES:
+ _postcondition_delay(deadline, "repin_postcondition_timeout")
+ continue
+ if _running_ids(f"{IMAGE_NAME}:{plan['targetCommit']}",
+ timeout=_remaining_timeout(deadline, COMMAND_TIMEOUT_SECONDS)):
+ _postcondition_delay(deadline, "repin_postcondition_timeout")
+ continue
+ break
+ _record_receipt(plan_path, plan_sha, "repin", "verified", {
+ "sourceComposeSha256": plan["rawComposeSha256"],
+ "targetComposeSha256": target_hash,
+ "targetImageId": plan["targetImageId"],
+ "patchResponseKeys": sorted(response) if isinstance(response, dict) else [],
+ })
+ except PhaseFailure as error:
+ _record_failure_if_missing(plan_path, plan_sha, "repin", "verification_failed",
+ {"reason": str(error), "targetComposeSha256": target_hash})
+ raise
+ except Exception as error:
+ _record_failure_if_missing(plan_path, plan_sha, "repin", "verification_failed",
+ {"errorType": type(error).__name__, "targetComposeSha256": target_hash})
+ raise fail("repin_verification_failed") from None
+ return {"phase": "repin", "state": "verified"}
+
+
+def _port_is_free(bind: str) -> None:
+ sock = socket.socket()
+ try:
+ sock.bind((bind, 4318))
+ except OSError:
+ raise fail("private_receiver_port_unavailable") from None
+ finally:
+ sock.close()
+
+
+def _start_phase(plan_path: Path, plan_sha: str, plan: dict[str, object],
+ api: _Coolify, bind: str) -> dict[str, object]:
+ repin = _read_receipt(plan_path, plan_sha, "repin")
+ _claim_unused(plan_path, plan_sha, "start")
+ current, compose = api.request(), None
+ if (not isinstance(current, dict)
+ or current.get("uuid") != plan["service"]["uuid"]):
+ raise fail("service_response_invalid")
+ compose = _parse_raw_compose(current)
+ target_compose = _expected_target_compose(plan)
+ target_hash = _sha(_canonical(target_compose))
+ if compose != target_compose or _sha(_canonical(compose)) != repin.get("targetComposeSha256"):
+ raise fail("target_raw_compose_compare_failed")
+ if current.get("status") not in STOPPED_STATUSES:
+ raise fail("service_not_stopped")
+ if _running_ids(f"{IMAGE_NAME}:{plan['targetCommit']}"):
+ raise fail("target_container_already_running")
+ _image_identity(plan)
+ _port_is_free(bind)
+ _claim_after_preflight(plan_path, plan_sha, "start")
+ try:
+ response = api.request("/start", method="POST")
+ except PhaseFailure:
+ _record_receipt(plan_path, plan_sha, "start", "outcome_unknown", {
+ "targetComposeSha256": target_hash,
+ "targetImageId": plan["targetImageId"],
+ })
+ raise
+ try:
+ deadline = time.monotonic() + POSTCONDITION_TIMEOUT_SECONDS
+ while True:
+ after, after_compose = _live_service_compose(
+ api, plan, timeout=_remaining_timeout(deadline, HTTP_TIMEOUT_SECONDS),
+ )
+ if after_compose != target_compose:
+ raise fail("start_postcondition_compose_changed")
+ if after.get("status") not in STARTED_STATUSES:
+ _postcondition_delay(deadline, "start_postcondition_timeout")
+ continue
+ ids = _running_ids(f"{IMAGE_NAME}:{plan['targetCommit']}",
+ timeout=_remaining_timeout(deadline, COMMAND_TIMEOUT_SECONDS))
+ if not ids:
+ _postcondition_delay(deadline, "start_postcondition_timeout")
+ continue
+ if len(ids) != 1:
+ raise fail("target_container_count_invalid")
+ container = _container(ids[0], timeout=_remaining_timeout(deadline, COMMAND_TIMEOUT_SECONDS))
+ _validate_container_identity(container, plan, target=True, bind_host=bind)
+ if container.get("State", {}).get("Running") is not True:
+ _postcondition_delay(deadline, "start_postcondition_timeout")
+ continue
+ health = container.get("State", {}).get("Health", {}).get("Status")
+ if health not in {"healthy", "starting"}:
+ raise fail("target_container_health_invalid")
+ metadata = _runtime_metadata(ids[0], timeout=_remaining_timeout(deadline, COMMAND_TIMEOUT_SECONDS))
+ _check_metadata_against_plan(metadata, plan, before_stop=False)
+ break
+ health = container.get("State", {}).get("Health", {}).get("Status")
+ phase_state = "verified" if health == "healthy" else "started"
+ _record_receipt(plan_path, plan_sha, "start", phase_state, {
+ "targetComposeSha256": target_hash,
+ "targetImageId": plan["targetImageId"],
+ "containerId": ids[0],
+ "containerHealth": health,
+ "configSha256": metadata["configSha256"],
+ "volumeNameSha256": _sha(plan["durableVolume"].encode()),
+ "configSourceSha256": _sha(plan["configMountSource"].encode()),
+ "startResponseKeys": sorted(response) if isinstance(response, dict) else [],
+ })
+ except PhaseFailure as error:
+ _record_failure_if_missing(plan_path, plan_sha, "start", "verification_failed",
+ {"reason": str(error), "targetComposeSha256": target_hash})
+ raise
+ except Exception as error:
+ _record_failure_if_missing(plan_path, plan_sha, "start", "verification_failed",
+ {"errorType": type(error).__name__, "targetComposeSha256": target_hash})
+ raise fail("start_verification_failed") from None
+ return {"phase": "start", "state": phase_state, "containerId": ids[0],
+ "health": container.get("State", {}).get("Health", {}).get("Status")}
+
+
+def run() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("phase", choices=("stop", "repin", "start"))
+ parser.add_argument("plan", type=Path)
+ parser.add_argument("plan_sha256")
+ args = parser.parse_args()
+ if not re.fullmatch(r"[a-f0-9]{64}", args.plan_sha256):
+ raise fail("invalid_plan_sha256")
+ plan_path = args.plan.absolute()
+ if plan_path.name != f".um1651-hub-upgrade-{_plan_target_from_name(plan_path)}.plan.json":
+ raise fail("plan_filename_invalid")
+ plan, plan_sha = _plan(plan_path, args.plan_sha256)
+ if plan_path.name != f".um1651-hub-upgrade-{plan['targetCommit']}.plan.json":
+ raise fail("plan_target_filename_mismatch")
+ base_url, bind = _load_routing()
+ token = _coolify_token()
+ api = _Coolify(base_url, token, plan["service"]["uuid"])
+ if args.phase == "stop":
+ result = _stop_phase(plan_path, plan_sha, plan, api, bind)
+ elif args.phase == "repin":
+ result = _repin_phase(plan_path, plan_sha, plan, api)
+ else:
+ result = _start_phase(plan_path, plan_sha, plan, api, bind)
+ print(json.dumps({**result, "planSha256": plan_sha}, sort_keys=True))
+ return 0
+
+
+def _plan_target_from_name(path: Path) -> str:
+ match = re.fullmatch(r"\.um1651-hub-upgrade-([a-f0-9]{40})\.plan\.json", path.name)
+ if not match:
+ raise fail("plan_filename_invalid")
+ return match.group(1)
+
+
+if __name__ == "__main__":
+ try:
+ sys.exit(run())
+ except PhaseFailure as error:
+ print(json.dumps({"phase": "refused", "reason": str(error)}, sort_keys=True))
+ sys.exit(2)
+ except (OSError, subprocess.SubprocessError) as error:
+ print(json.dumps({"phase": "failed", "errorType": type(error).__name__}, sort_keys=True))
+ sys.exit(1)
+ except Exception as error:
+ print(json.dumps({"phase": "failed", "errorType": type(error).__name__}, sort_keys=True))
+ sys.exit(1)
diff --git a/verify-reviewed-hub-image.py b/verify-reviewed-hub-image.py
new file mode 100644
index 00000000..8a5570ff
--- /dev/null
+++ b/verify-reviewed-hub-image.py
@@ -0,0 +1,168 @@
+#!/usr/bin/env python3
+"""Verify a telemetry hub image against one exact Git commit without starting the hub."""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+
+IMAGE_NAME = "usage-monitor-telemetry-hub"
+REVISION_LABEL = "org.opencontainers.image.revision"
+FIXED_IMPORTS = (
+ "scripts/telemetry-hub/journal.mjs",
+ "scripts/telemetry-hub/sentry-sender.mjs",
+ "scripts/telemetry-hub/metadata-projection.mjs",
+ "scripts/telemetry-hub/allowlist.mjs",
+)
+RESULT_KEYS = {"fileCount", "hashMatch", "nodeVersion", "importsOk"}
+CONTAINER_CHECK = r"""
+import { createHash } from 'node:crypto';
+import { readFile } from 'node:fs/promises';
+const manifest = JSON.parse(process.argv[1]);
+let hashMatch = Array.isArray(manifest);
+for (const entry of manifest) {
+ const digest = createHash('sha256').update(await readFile(`/app/${entry.path}`)).digest('hex');
+ if (digest !== entry.sha256) hashMatch = false;
+}
+await import('file:///app/scripts/telemetry-hub/journal.mjs');
+await import('file:///app/scripts/telemetry-hub/sentry-sender.mjs');
+await import('file:///app/scripts/telemetry-hub/metadata-projection.mjs');
+await import('file:///app/scripts/telemetry-hub/allowlist.mjs');
+process.stdout.write(JSON.stringify({
+ fileCount: manifest.length,
+ hashMatch,
+ nodeVersion: process.version,
+ importsOk: true
+}));
+"""
+
+
+class Refusal(Exception):
+ pass
+
+
+def git(repo: Path, *args: str) -> bytes:
+ result = subprocess.run(
+ ["git", *args], cwd=repo, stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL, check=False,
+ )
+ if result.returncode:
+ raise Refusal("git_validation_failed")
+ return result.stdout
+
+
+def docker_call(docker: str, args: list[str]) -> subprocess.CompletedProcess[bytes]:
+ return subprocess.run(
+ [docker, *args], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
+ check=False,
+ )
+
+
+def run() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--apply", action="store_true", help="run the isolated image checks")
+ parser.add_argument("sha", help="exact 40-character commit SHA")
+ args = parser.parse_args()
+
+ sha = args.sha
+ if not re.fullmatch(r"[a-f0-9]{40}", sha):
+ raise Refusal("invalid_sha")
+
+ repo = Path(__file__).resolve().parent
+ git_dir = Path(os.fsdecode(git(repo, "rev-parse", "--show-toplevel")).strip()).resolve()
+ if git_dir != repo:
+ raise Refusal("not_repository_root")
+ git(repo, "cat-file", "-e", f"{sha}^{{commit}}")
+ names = git(repo, "ls-tree", "-r", "-z", "--name-only", sha,
+ "--", "scripts/telemetry-hub", "scripts/lib/fleet-secrets.mjs")
+ paths = sorted({
+ os.fsdecode(item) for item in names.split(b"\0") if item.endswith(b".mjs")
+ })
+ if "scripts/lib/fleet-secrets.mjs" not in paths or not paths:
+ raise Refusal("expected_sources_missing")
+ if not set(FIXED_IMPORTS).issubset(paths):
+ raise Refusal("expected_import_sources_missing")
+
+ manifest = []
+ for path in paths:
+ content = git(repo, "show", f"{sha}:{path}")
+ manifest.append({"path": path, "sha256": hashlib.sha256(content).hexdigest()})
+ manifest_json = json.dumps(manifest, sort_keys=True, separators=(",", ":"))
+ manifest_digest = hashlib.sha256(manifest_json.encode("utf-8")).hexdigest()
+ image = f"{IMAGE_NAME}:{sha}"
+ if not args.apply:
+ print(json.dumps({"phase": "plan", "commit": sha, "fileCount": len(manifest),
+ "manifestSha256": manifest_digest, "image": image}, sort_keys=True))
+ return 0
+
+ docker = shutil.which("docker")
+ if docker is None:
+ print(json.dumps({"phase": "inspect", "exitCode": 1,
+ "errorType": "FileNotFoundError"}, sort_keys=True))
+ return 1
+
+ inspect_format = f'{{{{.Id}}}}\t{{{{index .Config.Labels "{REVISION_LABEL}"}}}}'
+ try:
+ inspected = docker_call(docker, ["image", "inspect", "--format", inspect_format, image])
+ except OSError as error:
+ print(json.dumps({"phase": "inspect", "exitCode": 1,
+ "errorType": type(error).__name__}, sort_keys=True))
+ return 1
+ fields = inspected.stdout.decode("utf-8", "replace").strip().split("\t", 1)
+ if inspected.returncode != 0 or len(fields) != 2 or fields[1] != sha:
+ print(json.dumps({"phase": "inspect", "exitCode": inspected.returncode or 1,
+ "revisionMatches": False}, sort_keys=True))
+ return inspected.returncode or 1
+
+ container_args = [
+ "run", "--rm", "--network", "none", "--read-only", "--cap-drop", "ALL",
+ "--security-opt", "no-new-privileges",
+ "--env", "TELEMETRY_HUB_SENTRY_ONLY=",
+ "--env", "TELEMETRY_HUB_METADATA_ONLY=",
+ "--env", "TELEMETRY_HUB_READINESS_FILE=",
+ "--entrypoint", "node", image,
+ "--input-type=module", "-e", CONTAINER_CHECK, manifest_json,
+ ]
+ try:
+ checked = docker_call(docker, container_args)
+ except OSError as error:
+ print(json.dumps({"phase": "container", "exitCode": 1,
+ "errorType": type(error).__name__}, sort_keys=True))
+ return 1
+ if checked.returncode != 0:
+ print(json.dumps({"phase": "container", "exitCode": checked.returncode}, sort_keys=True))
+ return checked.returncode
+
+ try:
+ result = json.loads(checked.stdout)
+ except (UnicodeDecodeError, json.JSONDecodeError):
+ result = None
+ if (not isinstance(result, dict) or set(result) != RESULT_KEYS
+ or not isinstance(result["fileCount"], int)
+ or not isinstance(result["hashMatch"], bool)
+ or not isinstance(result["nodeVersion"], str)
+ or not re.fullmatch(r"v\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?", result["nodeVersion"])
+ or not isinstance(result["importsOk"], bool)):
+ print(json.dumps({"phase": "container_result", "exitCode": 1}, sort_keys=True))
+ return 1
+ ok = result["fileCount"] == len(manifest) and result["hashMatch"] and result["importsOk"]
+ result.update({"phase": "verified", "exitCode": 0 if ok else 1, "sourceCommit": sha,
+ "revisionMatches": True})
+ print(json.dumps(result, sort_keys=True))
+ return 0 if ok else 1
+
+
+if __name__ == "__main__":
+ try:
+ sys.exit(run())
+ except Refusal as error:
+ print(json.dumps({"phase": "refused", "reason": str(error)}, sort_keys=True))
+ sys.exit(2)
diff --git a/verify-upgraded-hub-and-track.py b/verify-upgraded-hub-and-track.py
new file mode 100644
index 00000000..2dc60b38
--- /dev/null
+++ b/verify-upgraded-hub-and-track.py
@@ -0,0 +1,40 @@
+import importlib.util,json,pathlib,os,secrets
+root=pathlib.Path(__file__).resolve().parent
+spec=importlib.util.spec_from_file_location('hub_upgrade',root/'upgrade-reviewed-hub.py');m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
+digest='7d71eb6faf24e6992eddbd7a32911a2689a8216750fd4dc87a97b1f3cc3afea0'
+path=root/'.um1651-hub-upgrade-0a92fcfa39f5b576f498dabc43963c89c47b3713.plan.json';p,_=m._plan(path,digest)
+start=json.loads(m._read_private(m._receipt_path(path,digest,'start','receipt.json')))
+if start.get('state') not in ('started','verified'):raise SystemExit('No confirmed start request')
+base,bind=m._load_routing();api=m._Coolify(base,m._coolify_token(),p['service']['uuid'])
+target=m._expected_target_compose(p);service,_=m._service_view(api,p,target)
+if service.get('status') not in m.STARTED_STATUSES:raise SystemExit('Service not running')
+ids=m._running_ids(m.IMAGE_NAME+':'+p['targetCommit'])
+if len(ids)!=1 or ids[0]!=start['containerId']:raise SystemExit('Unexpected target container')
+c=m._container(ids[0]);m._validate_container_identity(c,p,target=True,bind_host=bind)
+if c['State'].get('Health',{}).get('Status')!='healthy':raise SystemExit('Target is not healthy yet')
+meta=m._runtime_metadata(ids[0]);m._check_metadata_against_plan(meta,p,before_stop=False)
+code="const fs=require('node:fs'),d='/data/state';console.log(JSON.stringify({intentPresent:fs.existsSync(d+'/sentry-request.json'),sentCounts:Object.fromEntries(fs.readdirSync(d).filter(n=>n.endsWith('.sent.json')).map(n=>[n.replace('.sent.json',''),JSON.parse(fs.readFileSync(d+'/'+n)).eventIds.length]))}));"
+state=json.loads(m._docker(['exec',ids[0],'node','-e',code]))
+if state['intentPresent'] or meta['pendingBytes']!=0:raise SystemExit('Sentry delivery is pending or held; inspect before closing')
+ops=m.OPS_ROOT
+old_service=json.loads(m._read_private(ops/'hub-service.json'))
+if old_service!=p['service']:raise SystemExit('Private service tracking changed')
+old_compose=m._read_private(ops/'hub-compose.json')
+if m._sha(old_compose)!=p['preparedComposeSha256']:raise SystemExit('Private prepared compose changed')
+for name in ['hub-service.json','hub-compose.json','hub-image.json']:
+ old=m._read_private(ops/name);backup=ops/(name+'.before-um1651-0a92fcfa')
+ fd=os.open(backup,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600)
+ try:m._write_all(fd,old);os.fsync(fd)
+ finally:os.close(fd)
+def replace(name,value):
+ dest=ops/name;tmp=ops/(name+'.'+secrets.token_hex(12)+'.tmp')
+ m._write_exclusive(tmp,value);os.replace(tmp,dest)
+ directory=os.open(ops,os.O_RDONLY|os.O_DIRECTORY)
+ try:os.fsync(directory)
+ finally:os.close(directory)
+updated={**old_service,'source_commit':p['targetCommit'],'image_id':p['targetImageId']}
+replace('hub-service.json',updated);replace('hub-compose.json',target)
+replace('hub-image.json',{'tag':m.IMAGE_NAME+':'+p['targetCommit'],'image_id':p['targetImageId'],'source_commit':p['targetCommit']})
+report={'phase':'independent-final-runtime-verification','planSha256':digest,'sourceCommit':p['targetCommit'],'imageId':p['targetImageId'],'containerId':ids[0],'healthy':True,'sameService':True,'sameDurableVolume':True,'configUnchanged':True,'configSha256':meta['configSha256'],'uid10001':True,'readonlyRootAndConfig':True,'privateHostListener':True,'noPublishedPorts':True,'sentryPendingBytes':meta['pendingBytes'],'intentPresent':state['intentPresent'],'sentCounts':state['sentCounts'],'privateTrackingUpdated':True}
+m._write_exclusive(root/'.um1651-final-runtime-verification.json',report)
+print(json.dumps(report))
From 654a648c195cc197483b3a7649c6ace38a11bb2f Mon Sep 17 00:00:00 2001
From: "swu-wise[bot]" <344778455+swu-wise[bot]@users.noreply.github.com>
Date: Wed, 18 Nov 2026 08:21:29 +0000
Subject: [PATCH 6/6] =?UTF-8?q?Address=20UM-1646=20audit=20review=20findin?=
=?UTF-8?q?gs:=20validate=20approved=20plan=20schema=20before=20property?=
=?UTF-8?q?=20access,=20run=20the=20reviewed=20catch-up=20script=20via=20?=
=?UTF-8?q?=5F=5Ffile=5F=5F-relative=20path,=20parse=20raw=20compose=20thr?=
=?UTF-8?q?ough=20the=20base64-aware=20path=20before=20deriving=20the=20un?=
=?UTF-8?q?it,=20and=20wire=20the=20three=20Python=20test=20suites=20into?=
=?UTF-8?q?=20npm=20test=20with=20CI=20PyYAML=20install.=C2=A0=20(Journal-?=
=?UTF-8?q?counter=20floor-check=20and=20HANDOFF-doc=20removal=20follow=20?=
=?UTF-8?q?in=20separate=20commits.)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.github/workflows/ci.yml | 3 +++
.um1646-claude-historic24h.mjs | 14 +++++++++++++-
.um1646-claude-historic24h.py | 2 +-
package.json | 7 ++++---
plan-reviewed-hub-upgrade.py | 7 +++++--
5 files changed, 26 insertions(+), 7 deletions(-)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e25f1a60..eecec027 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -232,6 +232,9 @@ jobs:
# Coverage-instrumented run of the same suite `npm test` executes; the
# thresholds in vitest.config.ts (ratcheted to measured reality) make
# this step fail on a genuine coverage regression.
+ - name: Install Python test dependencies
+ run: python3 -m pip install --break-system-packages pyyaml
+
- name: Test (with coverage gate)
run: npm run test:coverage
diff --git a/.um1646-claude-historic24h.mjs b/.um1646-claude-historic24h.mjs
index 52938f0f..bd5ef760 100644
--- a/.um1646-claude-historic24h.mjs
+++ b/.um1646-claude-historic24h.mjs
@@ -43,11 +43,23 @@ const config=collectorSentryConfig(process.env,identity.producerId);
assert.equal(config?.destination,'hub');
const deliveryConfiguration={destination:config.destination,endpoint:config.endpoint,stateRoot:config.stateRoot};
const deliveryConfigDigest=hash(JSON.stringify(deliveryConfiguration));
+const validateApprovedPlan=value=>{
+ assert.ok(value&&typeof value==='object'&&!Array.isArray(value),'approved plan must be a JSON object');
+ const pick={};
+ for(const key of ['commit','sourceHashDigest','identityDigest','deliveryConfigDigest','lower','upper']){
+ assert.ok(typeof value[key]==='string','approved plan string field missing: '+key);
+ pick[key]=value[key];
+ }
+ assert.match(pick.commit,/^[a-f0-9]{40}$/,'approved plan commit shape');
+ for(const key of ['sourceHashDigest','identityDigest','deliveryConfigDigest'])assert.match(pick[key],/^[a-f0-9]{64}$/,'approved plan digest shape: '+key);
+ assert.ok(Number.isFinite(Date.parse(pick.lower))&&Number.isFinite(Date.parse(pick.upper)),'approved plan dates must parse');
+ return pick;
+};
let approved,planBytes;
if(mode==='apply'){
planBytes=await readFile(planFile);
assert.equal(hash(planBytes),process.env.UM_CLAUDE_CATCHUP_APPROVED_PLAN_SHA256);
- approved=JSON.parse(planBytes);
+ approved=validateApprovedPlan(JSON.parse(planBytes));
assert.equal(approved.commit,commit);
assert.equal(approved.sourceHashDigest,hash(JSON.stringify(sourceHashes)));
assert.equal(approved.identityDigest,hash(JSON.stringify(identity)));
diff --git a/.um1646-claude-historic24h.py b/.um1646-claude-historic24h.py
index f3980a64..60a72af2 100644
--- a/.um1646-claude-historic24h.py
+++ b/.um1646-claude-historic24h.py
@@ -10,7 +10,7 @@
env['COLLECTOR_TELEMETRY_HUB_TOKENS_JSON']=json.dumps({'claude-code':tokens['claude-code']},separators=(',',':'))
env['UM_CLAUDE_CATCHUP_MODE']=mode
if mode=='apply' and len(env.get('UM_CLAUDE_CATCHUP_APPROVED_PLAN_SHA256',''))!=64:raise SystemExit('Exact approved plan digest required')
-code=pathlib.Path('/tmp/um1646-sentry-historic-20261103/claude-historic-24h.mjs').read_text()
+code=pathlib.Path(__file__).with_name('.um1646-claude-historic24h.mjs').read_text()
result=subprocess.run([job['ProgramArguments'][0],'--input-type=module'],input=code,text=True,capture_output=True,env=env,timeout=180)
if result.returncode:raise SystemExit('Catch-up guard failed; no source or configuration values printed')
rows=[json.loads(line) for line in result.stdout.splitlines() if line.startswith('{')]
diff --git a/package.json b/package.json
index 30e4daa0..fda944d3 100644
--- a/package.json
+++ b/package.json
@@ -47,8 +47,8 @@
"audit:provider-duplicates": "node scripts/audit-provider-duplicates.mjs",
"audit:subscription-links": "node scripts/audit-subscription-links.mjs",
"ensure:subscription-link-index": "node scripts/ensure-subscription-link-unique-index.mjs",
- "test": "vitest run && npm run test:infisical-fetch && npm run test:alert-timestamps && npm run test:budget-guard",
- "test:coverage": "vitest run --coverage && npm run test:infisical-fetch && npm run test:alert-timestamps && npm run test:budget-guard",
+ "test": "vitest run && npm run test:infisical-fetch && npm run test:alert-timestamps && npm run test:budget-guard && npm run test:um1646-python",
+ "test:coverage": "vitest run --coverage && npm run test:infisical-fetch && npm run test:alert-timestamps && npm run test:budget-guard && npm run test:um1646-python",
"test:budget-guard": "node --test \"workers/**/budget-guard.test.mjs\"",
"test:infisical-fetch": "node --test scripts/infisical-fetch.node-test.mjs scripts/infisical-fetch-expand.node-test.mjs scripts/infisical-run.node-test.mjs scripts/collector-injector.node-test.mjs",
"test:alert-timestamps": "node --test scripts/normalize-alert-timestamps.node-test.mjs",
@@ -73,7 +73,8 @@
"test:audit-ci": "node scripts/test-audit-ci.mjs",
"test:sentry-ci-report": "python3 scripts/test-sentry-ci-report.py",
"verify": "npm run test:node-runtime && npm run test:sentry-ci-report && npm run test:security-ancestry && npm run lint && npm run typecheck && npm test && npm run test:receipt-inbox-worker && npm run test:expenses-worker && npm run test:migrate-safe && npm run test:sqlite-backup && npm run test:backup-concurrent-startup && npm run test:r2-archive && npm run test:startup-config && npm run test:oracle-deploy && npm run test:apple-projects && npm run test:antigravity-collector && npm run test:session-token-collectors && npm run test:collector-runtime && npm run test:cf-token-map && npm run test:replica-status-probe && npm run test:quota-wrapper && npm run test:audit-ci && npm run build",
- "test:security-ancestry": "python3 scripts/telemetry-hub/test_audit_security_ancestry.py"
+ "test:security-ancestry": "python3 scripts/telemetry-hub/test_audit_security_ancestry.py",
+ "test:um1646-python": "python3 test_child_config_local_cas.py && python3 test_um1646_inventory_update_fixture.py && python3 test_upgrade_reviewed_hub.py"
},
"dependencies": {
"@datadog/browser-logs": "^7.15.0",
diff --git a/plan-reviewed-hub-upgrade.py b/plan-reviewed-hub-upgrade.py
index 20504bf9..784cd528 100644
--- a/plan-reviewed-hub-upgrade.py
+++ b/plan-reviewed-hub-upgrade.py
@@ -42,8 +42,6 @@ def redirect_request(self, *args, **kwargs):
request = urllib.request.Request(routing["base_url"] + "/services/" + service["uuid"], headers={"Authorization": "Bearer " + token, "Accept": "application/json"})
with opener.open(request, timeout=25) as response:
current = json.load(response)
-compose = yaml.safe_load(current.get("docker_compose") or current.get("docker_compose_raw"))
-unit = compose["services"]["telemetry-hub"]
raw_value = current.get('docker_compose_raw')
if not isinstance(raw_value, str) or not raw_value:
raise SystemExit('Original raw compose is unavailable; preserve the service')
@@ -56,6 +54,11 @@ def redirect_request(self, *args, **kwargs):
if not isinstance(raw_compose, dict) or set(raw_compose.get('services', {})) != {'telemetry-hub'}:
raise SystemExit('Original raw compose service membership changed')
raw_unit = raw_compose['services']['telemetry-hub']
+compose_value = current.get("docker_compose")
+compose = yaml.safe_load(compose_value) if isinstance(compose_value, str) and compose_value else raw_compose
+if not isinstance(compose, dict) or "services" not in compose:
+ raise SystemExit('Current compose shape is unsupported')
+unit = compose["services"]["telemetry-hub"]
if os.environ.get('UM1651_RAW_SHAPE_ONLY') == '1':
raw_env = raw_unit.get('environment', {})
if isinstance(raw_env, list): raw_env = dict(item.split('=', 1) for item in raw_env if '=' in item)