From a7b11e72eb74508ff2c694b42b489cff7f620a06 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Sat, 14 Nov 2026 11:41:32 -0600 Subject: [PATCH] pm-stack: invariant sweeper (#10139) + silent-failure surfacing (#10141) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #10139: pm-stack/invariant-sweeper.py — daily deep sweep of the four Kaneo-synced repos for (a) closed issues with open sub-issues, (b) open issues carrying status:done, (c) Kaneo<->GitHub mismatches. GraphQL-first via fleet gh (never the personal token for bulk calls), report-first per the close-authority design (P4); --act carries the post-review auto-reopen policy with the watchdog guards. Daily user timer; state + reports under ~/.local/state/pm-invariant-sweeper; posts the inventory to epic #10136 when the violation set changes. code#9060 is evaluated as a known positive on every run. #10141: silent failures now surface on the aggregator watchdog tier. pm-stack/host-health-collector.py (5-min user timer) snapshots the claimant mode file and the pm-git-sync / pm-projector-reconcile / pm-kaneo-sync-guard / pm-dashboard-backup unit+timer states to ~/.local/state/pm-aggregator/host-health.json; the aggregator derives needs-orchestrator items from it (new src/host-health.ts + watchdog derivation + cfg.hostHealthFile), incl. snapshot-absent/stale so the surfacer cannot fail silently. claimant.py read_mode() logs a loud CLAIMANT-MODE-WARNING on every missing/unreadable/invalid read — shadow stays the fail-safe default (P5); the fix is visibility. Tests: aggregator host-health.test.ts (12 new) + watchdog suite pass; claimant read_mode tests added (8/8). Schedules registered in doc/fleet-schedule-registry.md. --- doc/fleet-schedule-registry.md | 4 +- pm-stack/aggregator/src/config.ts | 8 + pm-stack/aggregator/src/host-health.ts | 126 ++++ pm-stack/aggregator/src/server.ts | 9 +- pm-stack/aggregator/src/watchdog.ts | 181 ++++- pm-stack/aggregator/test/host-health.test.ts | 191 ++++++ pm-stack/host-health-collector.py | 187 +++++ pm-stack/invariant-sweeper.py | 645 ++++++++++++++++++ pm-stack/opencode-claimant/claimant.py | 40 +- .../opencode-claimant/test/test_claimant.py | 46 ++ pm-stack/systemd/pm-host-health.service | 7 + pm-stack/systemd/pm-host-health.timer | 11 + pm-stack/systemd/pm-invariant-sweeper.service | 7 + pm-stack/systemd/pm-invariant-sweeper.timer | 10 + 14 files changed, 1463 insertions(+), 9 deletions(-) create mode 100644 pm-stack/aggregator/src/host-health.ts create mode 100644 pm-stack/aggregator/test/host-health.test.ts create mode 100644 pm-stack/host-health-collector.py create mode 100644 pm-stack/invariant-sweeper.py create mode 100644 pm-stack/systemd/pm-host-health.service create mode 100644 pm-stack/systemd/pm-host-health.timer create mode 100644 pm-stack/systemd/pm-invariant-sweeper.service create mode 100644 pm-stack/systemd/pm-invariant-sweeper.timer diff --git a/doc/fleet-schedule-registry.md b/doc/fleet-schedule-registry.md index f90df4c0f0..8f10d48932 100644 --- a/doc/fleet-schedule-registry.md +++ b/doc/fleet-schedule-registry.md @@ -235,7 +235,7 @@ Execution route/pool is recorded separately from work scope: the repo-health que | `aea12c82-c5af-4e5a-9b66-f8e360f87177` | Queue lane (scheduled) - code | `*/40 * * * *` | True | `~/.config/openchamber/projects/path_L2hvbWUvdXNlci9naXQvY29kZQ.json` | not recorded | not recorded | not recorded | not recorded | 2026-11-03 | | `f1b4a33b-14d5-4a69-9ad6-d221e42e3ac9` | Opencode lane claimant/executor - #3026 | `*/10 * * * *` | True | `~/.config/openchamber/projects/path_L2hvbWUvdXNlci9naXQvY29kZQ.json` | opencode-route / workhorse | not recorded | not recorded | not recorded | 2026-11-03 | -### 2b. Laptop systemd user timers (42 listed: 38 enabled, 1 installed-but-disabled; 4 Nix-configured pending deployment) +### 2b. Laptop systemd user timers (44 listed: 40 enabled, 1 installed-but-disabled; 4 Nix-configured pending deployment) The OS-timer half of surface 2. Cadence is the unit's own `OnCalendar`/`OnUnitActiveUSec` spec, read live from `systemctl --user show`. Specs are recorded **complete** — the full effective calendar expression, date **and** time components (e.g. `*-*-* *:*:00`); never truncate a spec to a date-only prefix, because a bare `*-*-*` normalizes to daily at midnight and misstates the cadence (issue #5313). Prompt/brief pointer is the unit file in `~/.config/systemd/user/` (or its Nix store target for linked units). Installed-but-disabled timer units ARE listed in this table and marked `(disabled)` after the unit name: the registry inventories what is installed on the laptop, not only what is currently scheduled, so a disabled unit stays visible until it is uninstalled (reconciled 2026-11-04, issue #5661). @@ -274,6 +274,8 @@ The OS-timer half of surface 2. Cadence is the unit's own `OnCalendar`/`OnUnitAc | `pm-digest-daily.timer` | `OnCalendar=*-*-* 07:00:00` | `pm-digest-daily.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `pm-digest-weekly.timer` | `OnCalendar=Mon *-*-* 07:05:00` | `pm-digest-weekly.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `pm-git-sync.timer` | `OnUnitActiveUSec=30s,OnBootUSec=30s` | `pm-git-sync.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | +| `pm-host-health.timer` | `OnCalendar=*-*-* *:00/5:00,OnBootUSec=1min` | `pm-host-health.service` | laptop (user systemd; code#10141) | not recorded | not recorded | 2026-11-14 | 2026-11-14 | +| `pm-invariant-sweeper.timer` | `OnCalendar=*-*-* 05:47:00` | `pm-invariant-sweeper.service` | laptop (user systemd; code#10139) | not recorded | not recorded | 2026-11-14 | 2026-11-14 | | `pm-kaneo.timer` | `OnUnitActiveUSec=30min,OnBootUSec=1min` | `pm-kaneo.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `pm-projector-reconcile.timer` | `OnCalendar=*-*-* *:00/15:00` | `pm-projector-reconcile.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `pm-tunnel-watchdog.timer` (Nix-configured; not yet loaded) | `OnUnitActiveSec=2min,OnBootSec=2min` (not live-verified) | `pm-tunnel-watchdog.service` | laptop (user systemd) | not recorded | not recorded | 2026-11-11 | 2026-11-11 | diff --git a/pm-stack/aggregator/src/config.ts b/pm-stack/aggregator/src/config.ts index 5794be17bb..6561e9bbcd 100644 --- a/pm-stack/aggregator/src/config.ts +++ b/pm-stack/aggregator/src/config.ts @@ -86,6 +86,10 @@ export interface Config { decisionsOutboxFile: string; /** Stack-health state written by the sentinel intake extension (#8568). */ stackHealthFile: string; + /** Host-health snapshot written by pm-stack/host-health-collector.py + * (#10141): claimant mode + PM unit states the watchdog derives + * silent-failure tier items from. Read-only for the aggregator. */ + hostHealthFile: string; /** Versioned item-history JSONL (#3981) the forecast contract * (#3984) derives from: one cutoff per line, read via * ItemHistoryStore. */ @@ -228,6 +232,10 @@ export function loadConfig(env: Record = process.env env.PM_AGG_STACK_HEALTH_FILE, join(homedir(), ".local", "state", "pm-aggregator", "stack-health.json"), ), + hostHealthFile: s( + env.PM_AGG_HOST_HEALTH_FILE, + join(homedir(), ".local", "state", "pm-aggregator", "host-health.json"), + ), quotaViewFile: s( env.PM_AGG_QUOTA_VIEW, join( diff --git a/pm-stack/aggregator/src/host-health.ts b/pm-stack/aggregator/src/host-health.ts new file mode 100644 index 0000000000..325313bc66 --- /dev/null +++ b/pm-stack/aggregator/src/host-health.ts @@ -0,0 +1,126 @@ +// Host-health snapshot (#10141): the reader half of silent-failure +// surfacing. pm-stack/host-health-collector.py runs on the laptop as a +// user timer (5 min cadence) and writes one JSON snapshot of the host +// facts the close-authority design (code#10136, P5) says must never be +// silent: the opencode claimant's mode file, and the systemd user unit +// states for pm-git-sync, pm-projector-reconcile, pm-kaneo-sync-guard +// and pm-dashboard-backup (plus their timers). +// +// The aggregator only READS the snapshot — the watchdog derivation in +// watchdog.ts turns breaches into NEEDS ORCHESTRATOR tier items, and +// recovery clears them on the next derivation, exactly like the +// staleness watchdog (#1148). Nothing here is persisted by the +// aggregator, and nothing here invents a state: an absent or corrupt +// snapshot reads as null and the watchdog says so, out loud. +import { readFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import { join } from "node:path"; + +/** Collector cadence is 5 min; 3 missed cycles (15 min) = stale. */ +export const HOST_HEALTH_STALE_MS = 15 * 60_000; +/** pm-dashboard-backup runs daily (~04:30); stale past 1.5 cadences. */ +export const HOST_HEALTH_BACKUP_STALE_MS = 36 * 60 * 60_000; +/** pm-projector-reconcile normally finishes in seconds on a 15 min + * timer; sitting in `activating` past 10 min means it is stuck. */ +export const HOST_HEALTH_RECONCILE_STUCK_MS = 10 * 60_000; + +export type ClaimantModeState = "live" | "shadow" | "missing" | "unreadable" | "invalid" | "unknown"; + +export interface ClaimantModeHealth { + state: ClaimantModeState; + detail?: string; +} + +export interface HostUnitHealth { + /** systemctl ActiveState ("active" | "inactive" | "failed" | "activating" | ...). */ + activeState: string; + subState?: string | null; + /** systemctl Result of the last run ("success" | "exit-code" | ...). */ + result?: string | null; + execMainStatus?: number | null; + stateChangedAt?: string | null; + lastSuccessAt?: string | null; + /** Set when the collector itself could not read the unit. */ + state?: string; + detail?: string; +} + +export interface HostHealthSnapshot { + generatedAt: string; + claimantMode: ClaimantModeHealth; + units: Record; + timers: Record; +} + +/** Default snapshot path (mirrors src/config.ts hostHealthFile). */ +export function defaultHostHealthFile(env: Record = process.env): string { + const v = env.PM_AGG_HOST_HEALTH_FILE?.trim(); + return v ? v : join(homedir(), ".local", "state", "pm-aggregator", "host-health.json"); +} + +const CLAIMANT_STATES: readonly string[] = ["live", "shadow", "missing", "unreadable", "invalid", "unknown"]; + +function asRecord(v: unknown): Record | null { + return v && typeof v === "object" && !Array.isArray(v) ? (v as Record) : null; +} + +function strOrNull(v: unknown): string | null { + return typeof v === "string" && v ? v : null; +} + +/** Validate a parsed snapshot loosely: known-bad shapes read as null + * (absent), never as a partial truth the watchdog would trust. */ +export function normalizeHostHealthSnapshot(parsed: unknown): HostHealthSnapshot | null { + const root = asRecord(parsed); + if (!root) return null; + const generatedAt = strOrNull(root.generatedAt); + if (!generatedAt || Number.isNaN(Date.parse(generatedAt))) return null; + const cm = asRecord(root.claimantMode); + if (!cm || typeof cm.state !== "string" || !CLAIMANT_STATES.includes(cm.state)) return null; + const unitsRaw = asRecord(root.units); + if (!unitsRaw) return null; + const units: Record = {}; + for (const [id, raw] of Object.entries(unitsRaw)) { + const u = asRecord(raw); + if (!u) return null; + units[id] = { + activeState: typeof u.activeState === "string" ? u.activeState : "unknown", + subState: strOrNull(u.subState), + result: strOrNull(u.result), + execMainStatus: typeof u.execMainStatus === "number" ? u.execMainStatus : null, + stateChangedAt: strOrNull(u.stateChangedAt), + lastSuccessAt: strOrNull(u.lastSuccessAt), + ...(typeof u.state === "string" ? { state: u.state } : {}), + ...(typeof u.detail === "string" ? { detail: u.detail } : {}), + }; + } + const timers: HostHealthSnapshot["timers"] = {}; + const timersRaw = asRecord(root.timers) ?? {}; + for (const [id, raw] of Object.entries(timersRaw)) { + const t = asRecord(raw); + if (!t) continue; + timers[id] = { + active: typeof t.active === "boolean" ? t.active : null, + ...(typeof t.activeState === "string" ? { activeState: t.activeState } : {}), + }; + } + return { + generatedAt, + claimantMode: { + state: cm.state as ClaimantModeState, + ...(typeof cm.detail === "string" ? { detail: cm.detail } : {}), + }, + units, + timers, + }; +} + +/** Read + normalize the snapshot; null when absent/corrupt (the + * watchdog turns that into its own visible item in live mode). */ +export async function readHostHealthSnapshot(file: string): Promise { + try { + return normalizeHostHealthSnapshot(JSON.parse(await readFile(file, "utf8"))); + } catch { + return null; + } +} diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index ae275e741b..954a7997c2 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -112,6 +112,7 @@ import { import { manifestRouteFor } from "./pages.ts"; import { conflictInbox, type ConflictInbox } from "./conflicts.ts"; import { watchdogTierItems, WATCHDOG_PROBE_SERVICE_IDS } from "./watchdog.ts"; +import { readHostHealthSnapshot } from "./host-health.ts"; import { allRefs, buildAttention, @@ -1558,9 +1559,14 @@ const enqueueWatchdogGapSync = createWatchdogGapSyncQueue(); // registry age from the source's already-loaded feed. async function deriveWatchdogItems(diagnosis?: ReturnType>["orchestration"]) { if (cfg.source !== "live") return []; - const [health, projectAudit] = await Promise.all([ + const [health, projectAudit, hostHealth] = await Promise.all([ healthContext(false), source.projectAudit ? source.projectAudit().catch(() => null) : Promise.resolve(null), + // #10141: the host-health collector's snapshot (claimant mode + + // PM unit states). A read failure yields null, which the watchdog + // surfaces as the snapshot-absent item — the surfacer's own + // silence is a breach, never a pass. + readHostHealthSnapshot(cfg.hostHealthFile).catch(() => null), ]); const items = watchdogTierItems({ now: Date.now(), @@ -1578,6 +1584,7 @@ async function deriveWatchdogItems(diagnosis?: ReturnType = { + "pm-git-sync": "pm-git-sync", + "pm-projector-reconcile": "pm-projector-reconcile", + "pm-kaneo-sync-guard": "Kaneo sync guard", + "pm-dashboard-backup": "PM dashboard backup", +}; + +/** #10141 derivation: claimant mode + PM unit states from the + * host-health snapshot. Pure, like the rest of this module: same + * snapshot in, same items out; recovery = the next snapshot no + * longer breaches, and the card clears itself. Thresholds are the + * constants in host-health.ts, named at their definition site. */ +function deriveHostHealthItems( + snapshot: HostHealthSnapshot | null, + now: number, + put: (it: TierItem) => void, +): void { + if (snapshot === null) { + put( + item( + "host-health", + "Watchdog: host-health snapshot is absent — claimant mode and PM unit states are unobserved", + "watchdog: host health absent", + "The host-health collector (#10141) has produced no readable snapshot, so the silent-failure surface itself is down: claimant mode, pm-git-sync, pm-projector-reconcile, the Kaneo sync guard, and the dashboard backup are all unobserved right now.", + now, + now, + "Check the pm-host-health user timer/service on the laptop and the snapshot at ~/.local/state/pm-aggregator/host-health.json; the card clears itself when a fresh snapshot lands.", + HOST_HEALTH_REF, + ), + ); + return; + } + + const generatedMs = Date.parse(snapshot.generatedAt); + if (!Number.isNaN(generatedMs) && now - generatedMs > HOST_HEALTH_STALE_MS) { + put( + item( + "host-health", + `Watchdog: host-health snapshot is stale — last collected ${ageMsText(now - generatedMs)} ago`, + "watchdog: host health stale", + `The host-health collector (#10141) runs every 5 min; its snapshot is ${ageMsText(now - generatedMs)} old, past the 15 min bound (3 missed cycles), so every host-health verdict below may itself be out of date.`, + generatedMs + HOST_HEALTH_STALE_MS, + now, + "Check the pm-host-health user timer on the laptop; the card clears itself when the collector runs again.", + HOST_HEALTH_REF, + ), + ); + } + + // Claimant mode: missing/unreadable/invalid means read_mode() is + // silently defaulting to shadow — dispatch stalls with no other + // signal. A file that says "shadow" is a deliberate setting and + // does not breach; "live" is the healthy dispatch state. + const mode = snapshot.claimantMode; + if (mode.state === "missing" || mode.state === "unreadable" || mode.state === "invalid") { + put( + item( + "claimant-mode", + `Watchdog: opencode claimant mode file is ${mode.state} — claimant is silently in shadow`, + `watchdog: claimant mode ${mode.state}`, + `The claimant's mode file (~/.local/state/opencode-claimant/mode) is ${mode.state}${mode.detail ? ` (${mode.detail})` : ""}. read_mode() defaults to shadow, so dispatch returns mode_not_live and stalls — the safety default is correct, the silence was the bug (#10141).`, + Number.isNaN(generatedMs) ? now : generatedMs, + now, + "Restore the mode file with the intended mode (live or shadow) — the parallel #9106 unpark owns today's instance; this card clears itself when the collector reads a valid file.", + HOST_HEALTH_REF, + ), + ); + } + + // PM unit states: a failed last run, a dead timer, a stuck + // activation, or a stale backup each breach immediately — there is + // no grace period for a unit whose whole job is not failing + // silently. Units the collector could not read (state "unknown" + // with no activeState verdict) never breach on their own; the + // snapshot-level items above cover a dead collector. + for (const [unitId, label] of Object.entries(HOST_UNIT_LABELS)) { + const unit = snapshot.units[unitId]; + if (!unit) continue; + const changedMs = unit.stateChangedAt ? Date.parse(unit.stateChangedAt) : NaN; + const since = Number.isNaN(changedMs) ? (Number.isNaN(generatedMs) ? now : generatedMs) : changedMs; + const failed = unit.activeState === "failed" || (unit.result != null && unit.result !== "success"); + if (failed) { + put( + item( + `unit-${unitId}`, + `Watchdog: ${label} is failing — last run result ${unit.result ?? unit.activeState}`, + "watchdog: unit failing", + `${label} (${unitId}.service) last ran with result ${unit.result ?? "unknown"} (ActiveState ${unit.activeState}${unit.execMainStatus != null ? `, exit ${unit.execMainStatus}` : ""}). ${unitId === "pm-git-sync" ? "While it fails, merged repo changes stop reaching the laptop checkout — the deploy-by-merge path (#8171) is down." : unitId === "pm-kaneo-sync-guard" ? "While the guard fails, Kaneo statusTransitions drift can go unhealed — the close-authority guard (#10137) is not asserting." : ""} Diagnosed from the host-health snapshot (#10141).`, + since, + now, + `Check ${unitId}.service on the laptop (journalctl --user -u ${unitId}); the card clears itself when a run succeeds.`, + HOST_HEALTH_REF, + ), + ); + continue; + } + if (unitId === "pm-projector-reconcile" && unit.activeState === "activating") { + const stuckFor = Number.isNaN(changedMs) ? 0 : now - changedMs; + if (stuckFor > HOST_HEALTH_RECONCILE_STUCK_MS) { + put( + item( + `unit-${unitId}`, + `Watchdog: ${label} is stuck activating — ${ageMsText(stuckFor)} in this state`, + "watchdog: unit stuck", + `pm-projector-reconcile has been in ActiveState 'activating' for ${ageMsText(stuckFor)}, past the 10 min stuck bound (#10141); its runs normally finish in seconds, so the projector's GitHub reconcile is not completing.`, + since, + now, + "Check pm-projector-reconcile.service on the laptop (journalctl --user -u pm-projector-reconcile); the card clears itself when the unit leaves 'activating'.", + HOST_HEALTH_REF, + ), + ); + continue; + } + } + if (unitId === "pm-dashboard-backup") { + const lastOk = unit.lastSuccessAt ? Date.parse(unit.lastSuccessAt) : NaN; + if (Number.isNaN(lastOk) || now - lastOk > HOST_HEALTH_BACKUP_STALE_MS) { + put( + item( + `unit-${unitId}`, + `Watchdog: ${label} is stale — last success ${Number.isNaN(lastOk) ? "never recorded" : `${ageMsText(now - lastOk)} ago`}`, + "watchdog: backup stale", + `pm-dashboard-backup runs daily (~04:30, code#1516); no successful run is recorded within the 36 h bound (1.5 cadences, #10141), so the dashboard/Kaneo backup chain may have stopped without a failed unit to show for it.`, + Number.isNaN(lastOk) ? now : lastOk + HOST_HEALTH_BACKUP_STALE_MS, + now, + "Check pm-dashboard-backup.service and its timer on the laptop; the card clears itself after the next successful backup.", + HOST_HEALTH_REF, + ), + ); + continue; + } + } + const timer = snapshot.timers[`${unitId}.timer`]; + if (timer && timer.active === false) { + put( + item( + `unit-${unitId}`, + `Watchdog: ${label} timer is not active — the unit will not run on schedule`, + "watchdog: timer inactive", + `The ${unitId}.timer unit is ${timer.activeState ?? "not active"} in the host-health snapshot (#10141); a stopped timer fails silently exactly like a failed service.`, + Number.isNaN(generatedMs) ? now : generatedMs, + now, + `Re-enable ${unitId}.timer on the laptop (systemctl --user enable --now ${unitId}.timer); the card clears itself when the collector sees it active.`, + HOST_HEALTH_REF, + ), + ); + } + } +} diff --git a/pm-stack/aggregator/test/host-health.test.ts b/pm-stack/aggregator/test/host-health.test.ts new file mode 100644 index 0000000000..18a59fe818 --- /dev/null +++ b/pm-stack/aggregator/test/host-health.test.ts @@ -0,0 +1,191 @@ +import { describe, expect, test } from "bun:test"; +import { + normalizeHostHealthSnapshot, + HOST_HEALTH_BACKUP_STALE_MS, + HOST_HEALTH_STALE_MS, + type HostHealthSnapshot, +} from "../src/host-health.ts"; +import { watchdogTierItems, type WatchdogInputs } from "../src/watchdog.ts"; +import type { ProjectAudit } from "../src/model.ts"; + +// #10141: silent-failure surfacing. The host-health collector writes a +// snapshot; the watchdog derives exactly one NEEDS ORCHESTRATOR item +// per breached host fact, and recovery (a healthy next snapshot) +// clears them. Pure fixtures only — no service is ever touched. + +const NOW = Date.parse("2026-11-14T18:00:00Z"); +const iso = (ms: number) => new Date(ms).toISOString(); + +const freshProjectAudit: ProjectAudit = { + title: "Developing Today", + number: 4, + url: "https://github.com/orgs/developing-today/projects/4", + generatedAt: iso(NOW), + totalItems: 1, + fields: [], + views: [], + counts: { status: { Todo: 1 }, area: { "(unset)": 1 }, repo: { "developing-today/code": 1 } }, +}; + +function healthyUnit(over: Record = {}) { + return { + activeState: "inactive", + subState: "dead", + result: "success", + execMainStatus: 0, + stateChangedAt: iso(NOW - 60_000), + lastSuccessAt: iso(NOW - 60_000), + ...over, + }; +} + +function healthySnapshot(over: Partial = {}): HostHealthSnapshot { + return { + generatedAt: iso(NOW - 60_000), + claimantMode: { state: "live", detail: "mode file content: live" }, + units: { + "pm-git-sync": healthyUnit(), + "pm-projector-reconcile": healthyUnit(), + "pm-kaneo-sync-guard": healthyUnit(), + "pm-dashboard-backup": healthyUnit({ lastSuccessAt: iso(NOW - 6 * 3600_000) }), + }, + timers: { + "pm-git-sync.timer": { active: true, activeState: "active" }, + "pm-projector-reconcile.timer": { active: true, activeState: "active" }, + "pm-kaneo-sync-guard.timer": { active: true, activeState: "active" }, + "pm-dashboard-backup.timer": { active: true, activeState: "active" }, + }, + ...over, + }; +} + +function inputs(hostHealth: HostHealthSnapshot | null | undefined): WatchdogInputs { + return { + now: NOW, + feedAgeMs: 60_000, + feedGeneratedAt: iso(NOW - 60_000), + orchestration: { state: "live", generatedAt: iso(NOW - 30 * 60_000), ageMs: 30 * 60_000, runId: "orch-1" }, + registryAgeMs: 5 * 60_000, + projectAudit: freshProjectAudit, + probes: [], + ...(hostHealth !== undefined ? { hostHealth } : {}), + }; +} + +describe("host-health watchdog derivation (#10141)", () => { + test("no hostHealth input (fixtures mode) produces no host items", () => { + expect(watchdogTierItems(inputs(undefined))).toEqual([]); + }); + + test("a healthy snapshot produces no items", () => { + expect(watchdogTierItems(inputs(healthySnapshot()))).toEqual([]); + }); + + test("an absent snapshot is itself one visible item", () => { + const items = watchdogTierItems(inputs(null)); + expect(items.map((i) => i.id)).toEqual(["watchdog:host-health"]); + expect(items[0]!.state).toContain("absent"); + expect(items[0]!.ref).toBe("developing-today/code#10141"); + }); + + test("a stale snapshot breaches, and its unit facts still derive", () => { + const snap = healthySnapshot({ generatedAt: iso(NOW - HOST_HEALTH_STALE_MS - 60_000) }); + const items = watchdogTierItems(inputs(snap)); + expect(items.map((i) => i.id)).toEqual(["watchdog:host-health"]); + expect(items[0]!.state).toContain("stale"); + }); + + test("a missing claimant mode file produces exactly one item; shadow-by-file and live do not", () => { + const missing = healthySnapshot({ + claimantMode: { state: "missing", detail: "mode file does not exist" }, + }); + const items = watchdogTierItems(inputs(missing)); + expect(items.map((i) => i.id)).toEqual(["watchdog:claimant-mode"]); + expect(items[0]!.title).toContain("missing"); + const shadow = healthySnapshot({ claimantMode: { state: "shadow" } }); + expect(watchdogTierItems(inputs(shadow))).toEqual([]); + }); + + test("a failed pm-git-sync produces one item and recovery clears it", () => { + const snap = healthySnapshot(); + snap.units["pm-git-sync"] = healthyUnit({ + activeState: "failed", + result: "exit-code", + execMainStatus: 1, + lastSuccessAt: null, + }); + const items = watchdogTierItems(inputs(snap)); + expect(items.map((i) => i.id)).toEqual(["watchdog:unit-pm-git-sync"]); + expect(items[0]!.title).toContain("pm-git-sync is failing"); + expect(watchdogTierItems(inputs(healthySnapshot()))).toEqual([]); + }); + + test("pm-projector-reconcile stuck in activating past the bound breaches; a fresh activation does not", () => { + const stuck = healthySnapshot(); + stuck.units["pm-projector-reconcile"] = healthyUnit({ + activeState: "activating", + result: null, + stateChangedAt: iso(NOW - 11 * 60_000), + lastSuccessAt: iso(NOW - 15 * 60_000), + }); + const items = watchdogTierItems(inputs(stuck)); + expect(items.map((i) => i.id)).toEqual(["watchdog:unit-pm-projector-reconcile"]); + expect(items[0]!.state).toContain("stuck"); + const fresh = healthySnapshot(); + fresh.units["pm-projector-reconcile"] = healthyUnit({ + activeState: "activating", + result: null, + stateChangedAt: iso(NOW - 30_000), + lastSuccessAt: iso(NOW - 15 * 60_000), + }); + expect(watchdogTierItems(inputs(fresh))).toEqual([]); + }); + + test("a kaneo-sync-guard failure (drift exit) breaches", () => { + const snap = healthySnapshot(); + snap.units["pm-kaneo-sync-guard"] = healthyUnit({ + activeState: "failed", + result: "exit-code", + execMainStatus: 1, + lastSuccessAt: null, + }); + const items = watchdogTierItems(inputs(snap)); + expect(items.map((i) => i.id)).toEqual(["watchdog:unit-pm-kaneo-sync-guard"]); + }); + + test("backup staleness past 36h breaches even when the unit last exited cleanly long ago", () => { + const snap = healthySnapshot(); + snap.units["pm-dashboard-backup"] = healthyUnit({ + lastSuccessAt: iso(NOW - HOST_HEALTH_BACKUP_STALE_MS - 3600_000), + }); + const items = watchdogTierItems(inputs(snap)); + expect(items.map((i) => i.id)).toEqual(["watchdog:unit-pm-dashboard-backup"]); + expect(items[0]!.state).toContain("stale"); + }); + + test("an inactive unit timer breaches", () => { + const snap = healthySnapshot(); + snap.timers["pm-git-sync.timer"] = { active: false, activeState: "inactive" }; + const items = watchdogTierItems(inputs(snap)); + expect(items.map((i) => i.id)).toEqual(["watchdog:unit-pm-git-sync"]); + expect(items[0]!.state).toContain("timer inactive"); + }); +}); + +describe("host-health snapshot normalization (#10141)", () => { + test("a well-formed collector snapshot round-trips", () => { + const snap = normalizeHostHealthSnapshot(JSON.parse(JSON.stringify(healthySnapshot()))); + expect(snap).not.toBeNull(); + expect(snap!.claimantMode.state).toBe("live"); + expect(snap!.units["pm-git-sync"]!.result).toBe("success"); + }); + + test("absent, corrupt, or shapeless input reads as null, never as health", () => { + expect(normalizeHostHealthSnapshot(null)).toBeNull(); + expect(normalizeHostHealthSnapshot({})).toBeNull(); + expect(normalizeHostHealthSnapshot({ generatedAt: "not-a-date", claimantMode: { state: "live" }, units: {} })).toBeNull(); + expect( + normalizeHostHealthSnapshot({ generatedAt: iso(NOW), claimantMode: { state: "banana" }, units: {} }), + ).toBeNull(); + }); +}); diff --git a/pm-stack/host-health-collector.py b/pm-stack/host-health-collector.py new file mode 100644 index 0000000000..fccdc791ca --- /dev/null +++ b/pm-stack/host-health-collector.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +"""PM host-health collector (close-authority program code#10136, slice #10141). + +The data half of silent-failure surfacing. The aggregator's watchdog +tier items are DERIVED, never persisted — but the aggregator runs as a +packaged system service and cannot see the laptop user's systemd +manager or the claimant's state directory. This collector runs as a +laptop user service on a 5-minute timer, reads the host facts the +close-authority design (P5: fail-safe = no-mutation + a signal) says +must never be silent, and writes one JSON snapshot the aggregator +derives its watchdog items from: + + - the opencode claimant mode file (~/.local/state/opencode-claimant/mode): + missing / unreadable / invalid contents, or the live|shadow value; + - user unit states: pm-git-sync (the deploy-by-merge path, #8171), + pm-projector-reconcile, pm-kaneo-sync-guard (#10137), and + pm-dashboard-backup (daily ~04:30 cadence; last success recorded so + the aggregator can flag staleness past 36h); + - the matching .timer states, so a dead timer is as visible as a + failed service. + +Snapshot: ~/.local/state/pm-aggregator/host-health.json (override with +--output), written atomically (tmp + rename). A fact that cannot be +read is recorded as state "unknown" WITH the reason — this collector +never invents a healthy value and never fails the run over one bad +fact; it exits non-zero only when the snapshot itself cannot be +written, or on usage errors (exit 2). + +Argument contract (repo #3352): the whole command line is declared +below and parsed strictly before any subprocess or file write; +unknown flags, stray positionals, and valueless options are usage +errors naming the offending argument. + +Run on the laptop: + python3 pm-stack/host-health-collector.py + python3 pm-stack/host-health-collector.py --output /tmp/host-health.json +""" +import argparse +import json +import re +import subprocess +import sys +import time +from datetime import datetime, timezone +from pathlib import Path + +HOME = Path.home() +DEFAULT_OUTPUT = HOME / ".local" / "state" / "pm-aggregator" / "host-health.json" +DEFAULT_MODE_FILE = HOME / ".local" / "state" / "opencode-claimant" / "mode" + +UNITS = ["pm-git-sync", "pm-projector-reconcile", "pm-kaneo-sync-guard", + "pm-dashboard-backup"] +TIMERS = [f"{u}.timer" for u in UNITS] + ["pm-host-health.timer"] + +SHOW_PROPS = ["Id", "ActiveState", "SubState", "Result", "ExecMainStatus", + "ExecMainExitTimestamp", "InactiveEnterTimestamp", + "ActiveEnterTimestamp", "StateChangeTimestamp"] + + +def parse_args(argv): + parser = argparse.ArgumentParser( + prog="host-health-collector.py", allow_abbrev=False, + description="Collect claimant-mode + PM unit health into the " + "aggregator's host-health snapshot (code#10141).") + parser.add_argument("--output", default=str(DEFAULT_OUTPUT), metavar="PATH", + help="snapshot path (default: %(default)s).") + parser.add_argument("--mode-file", default=str(DEFAULT_MODE_FILE), metavar="PATH", + help="claimant mode file (default: %(default)s).") + return parser.parse_args(argv) + + +def iso_from_systemd(value): + """systemd timestamp string -> ISO 8601 UTC, or None. + + `systemctl show` prints timestamps in the host's local time with a + tz abbreviation strptime cannot reliably parse, so the wall-clock + part is extracted and interpreted as local time via time.mktime + (which resolves the correct UTC offset for that date).""" + if not value or value in ("n/a", "0"): + return None + m = re.search(r"(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})", value) + if not m: + return None + parts = tuple(int(g) for g in m.groups()) + epoch = time.mktime(parts + (0, 0, -1)) + return datetime.fromtimestamp(epoch, timezone.utc).isoformat() + + +def show_unit(unit): + out = subprocess.run( + ["systemctl", "--user", "show", unit, + "--property=" + ",".join(SHOW_PROPS)], + capture_output=True, text=True) + if out.returncode != 0: + return {"state": "unknown", + "detail": f"systemctl show failed: {out.stderr.strip()[:200]}"} + props = {} + for line in out.stdout.splitlines(): + key, _, val = line.partition("=") + props[key.strip()] = val.strip() + if not props.get("Id"): + return {"state": "unknown", "detail": "unit not found"} + result = props.get("Result") or None + try: + exec_status = int(props.get("ExecMainStatus") or 0) + except ValueError: + exec_status = None + record = { + "activeState": props.get("ActiveState") or "unknown", + "subState": props.get("SubState") or None, + "result": result, + "execMainStatus": exec_status, + "stateChangedAt": iso_from_systemd(props.get("StateChangeTimestamp")), + "activeEnterAt": iso_from_systemd(props.get("ActiveEnterTimestamp")), + "inactiveEnterAt": iso_from_systemd(props.get("InactiveEnterTimestamp")), + } + # Last success: for a oneshot that finished cleanly, inactive-enter + # is its completion time; only trust it while Result says success. + if result == "success": + record["lastSuccessAt"] = (iso_from_systemd(props.get("ExecMainExitTimestamp")) + or record["inactiveEnterAt"]) + else: + record["lastSuccessAt"] = None + return record + + +def read_claimant_mode(mode_file): + path = Path(mode_file) + if not path.exists(): + return {"state": "missing", + "detail": f"mode file {path} does not exist; claimant " + "read_mode() defaults to shadow (#10141)"} + try: + raw = path.read_text() + except Exception as exc: + return {"state": "unreadable", "detail": f"mode file unreadable: {exc}"} + value = raw.strip().lower() + if value in ("live", "shadow"): + return {"state": value, "detail": f"mode file content: {value}"} + return {"state": "invalid", + "detail": f"mode file content {raw.strip()[:40]!r} is not live|shadow; " + "claimant read_mode() defaults to shadow"} + + +def main(argv=None): + args = parse_args(argv) + snapshot = { + "generatedAt": datetime.now(timezone.utc).isoformat(), + "claimantMode": read_claimant_mode(args.mode_file), + "units": {}, + "timers": {}, + } + for unit in UNITS: + try: + snapshot["units"][unit] = show_unit(f"{unit}.service") + except Exception as exc: + snapshot["units"][unit] = {"state": "unknown", "detail": str(exc)[:200]} + for timer in TIMERS: + try: + rec = show_unit(timer) + snapshot["timers"][timer] = { + "active": rec.get("activeState") == "active", + "activeState": rec.get("activeState"), + } + except Exception as exc: + snapshot["timers"][timer] = {"active": None, "detail": str(exc)[:200]} + + output = Path(args.output) + try: + output.parent.mkdir(parents=True, exist_ok=True) + tmp = output.with_suffix(".json.tmp") + tmp.write_text(json.dumps(snapshot, indent=2) + "\n") + tmp.replace(output) + except Exception as exc: + print(f"host-health-collector: FAIL cannot write {output}: {exc}", + file=sys.stderr) + return 1 + bad_units = [u for u, r in snapshot["units"].items() + if r.get("activeState") == "failed" or ( + r.get("result") not in (None, "success"))] + print(f"host-health-collector: claimant={snapshot['claimantMode']['state']} " + f"units_bad={bad_units or 'none'} -> {output}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pm-stack/invariant-sweeper.py b/pm-stack/invariant-sweeper.py new file mode 100644 index 0000000000..f3e78d51c0 --- /dev/null +++ b/pm-stack/invariant-sweeper.py @@ -0,0 +1,645 @@ +#!/usr/bin/env python3 +"""Epic-invariant sweeper (close-authority program code#10136, slice #10139). + +A slow-cadence, deep sweep across all four Kaneo-synced repos +(developing-today/code, developing-today-forks/opencode, +developing-today-forks/openchamber, dezren39/nix) for the state the +closure watchdog (code#10105/#10138) cannot see: closes that predate +its watermark, drift that never produced a close event, and +Kaneo<->GitHub disagreement. Three invariants per run: + + (a) a CLOSED issue whose sub-issues are not all completed + (the epic invariant: a parent with open children is never done); + (b) an OPEN issue carrying Kaneo's `status:done` label; + (c) Kaneo<->GitHub state mismatch for linked tasks (Kaneo task done + while the GitHub issue is open, or not-done while it is closed). + +Policy (design doc doc/2026-11-14T17-00-00Z_design_pm-stack-close-authority, +P4): REPORT FIRST. The default mode inventories and reports; it changes +nothing on GitHub. Auto-repair is a separate, explicit mode (--act) to +be enabled only after the first inventory has been reviewed: in --act +mode the sweeper reopens invariant-(a) issues that a bot closed with +open sub-issues and no closing keyword (the watchdog's guards, incl. +the human-echo guard), strips bot-applied `status:done` labels under +invariant (b), and still only reports invariant (c) — Kaneo is a board +view, GitHub is the truth, and a mismatch is for the sync or a human +to heal, never for this sweeper to force. + +Data discipline: enumeration is GraphQL-first via `fleet gh api +graphql` (Drew, 2026-11-14: bulk/automated calls never use the +personal token — `fleet gh` rotates personal -> fleet App -> +developing.today App -> backup App with failover; the personal token +rate-limiting the closure watchdog's cycle is the failure this +avoids). GraphQL also has its own pool, separate from the REST core +budget the 15-minute watchdog shares. REST is used only by --act +repairs, likewise via `fleet gh`. If `fleet` is not on PATH the +sweeper falls back to bare `gh` and records that loudly in the report +(`gh_route`) — a silent fallback would recreate the problem. Every +repo is swept in isolation: one repo's failure is recorded in the +report and the sweep continues; the run exits 1 when any part failed, +0 when the sweep completed (findings are data, not failure), 2 on +usage errors. + +Known-positive verification: code#9060 (bot-closed 2026-11-12 with all +12 sub-issues open) is evaluated by the same classifier on every run +and reported by name. If it is closed when a run happens, it is a +live invariant-(a) finding; if the closure-audit pass has already +reopened it, the report says so (resolved-by-audit) with the close +actor/timestamp evidence the acceptance asks for. + +State: ~/.local/state/pm-invariant-sweeper/state.json (override with +--state-file) — survives restarts, records run history, the last +violation fingerprint, and the fingerprint last posted to the epic so +the daily run comments on code#10136 only when the violation set +changes (or with --force-post). Reports are written next to it as +last-report.md / last-report.json unless --report-dir says otherwise. + +Argument contract (repo #3352): the whole command line is declared +below and parsed strictly before any subprocess, network, or file +write; unknown flags, stray positionals, `--opt=value` forms for +flags that take no value, and valueless options are usage errors +(exit 2) naming the offending argument. + +Run on the laptop (Kaneo's Postgres lives there): + python3 pm-stack/invariant-sweeper.py # report (default) + python3 pm-stack/invariant-sweeper.py --post-epic # + epic comment if changed + python3 pm-stack/invariant-sweeper.py --act # after review (see above) +""" +import argparse +import hashlib +import json +import re +import subprocess +import sys +from datetime import datetime, timedelta, timezone +from pathlib import Path + +DEFAULT_REPOS = [ + "developing-today/code", + "developing-today-forks/opencode", + "developing-today-forks/openchamber", + "dezren39/nix", +] +EPIC_REPO = "developing-today/code" +EPIC_NUMBER = 10136 +KNOWN_POSITIVE = ("developing-today/code", 9060) +BOT_LOGINS = {"developing-today[bot]", "developing-today"} +DONE_LABEL = "status:done" +CLOSE_WINDOW = timedelta(minutes=15) # PR merge -> bot close gap (watchdog parity) +HUMAN_ECHO_WINDOW = timedelta(seconds=120) # human close just before a bot echo close +MAX_EPIC_ROWS = 50 + +STATE_DIR = Path.home() / ".local" / "state" / "pm-invariant-sweeper" + +CLOSING_KEYWORDS = r"(?:close|closes|closed|fix|fixes|fixed|resolve|resolves|resolved)" + + +def parse_args(argv): + """Strict declaration of the whole command line (#3352).""" + parser = argparse.ArgumentParser( + prog="invariant-sweeper.py", allow_abbrev=False, + description="Epic-invariant sweeper (code#10139): inventory closed-with-" + "open-sub-issues, open-with-status:done, and Kaneo<->GitHub " + "mismatches across the four Kaneo-synced repos.") + parser.add_argument("--act", action="store_true", + help="enable auto-repair (reopen eligible invariant-(a) " + "issues, strip bot-applied status:done). Default is " + "report-only, per the report-first policy.") + parser.add_argument("--post-epic", action="store_true", + help="comment the inventory on epic code#10136 when the " + "violation fingerprint changed since the last post.") + parser.add_argument("--force-post", action="store_true", + help="with --post-epic, post even if the fingerprint is " + "unchanged.") + parser.add_argument("--repo", action="append", default=None, metavar="OWNER/NAME", + help="limit the sweep to this repo (repeatable). Default: " + "all four Kaneo-synced repos.") + parser.add_argument("--state-file", default=str(STATE_DIR / "state.json"), + metavar="PATH", help="state file path.") + parser.add_argument("--report-dir", default=str(STATE_DIR), + metavar="PATH", help="directory for last-report.md/.json.") + parser.add_argument("--skip-kaneo", action="store_true", + help="skip invariant (c) (Kaneo Postgres unreachable from " + "here); the report records the section as skipped.") + args = parser.parse_args(argv) + repos = args.repo if args.repo else list(DEFAULT_REPOS) + for repo in repos: + if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repo): + parser.error(f"--repo: invalid owner/name {repo!r}") + args.repos = repos + return args + + +# ---------------------------------------------------------------- gh access + +# Resolved in main() before any gh call: ["fleet", "gh"] where the +# fleet binary exists (the laptop), else ["gh"] with the fallback +# recorded in the report. See the header's data-discipline note. +GH_CMD = ["gh"] +GH_ROUTE = "gh (unresolved)" + + +def resolve_gh_route(): + global GH_CMD, GH_ROUTE + import shutil + if shutil.which("fleet"): + GH_CMD = ["fleet", "gh"] + GH_ROUTE = "fleet gh (rotating app tiers)" + else: + GH_CMD = ["gh"] + GH_ROUTE = "gh (FALLBACK: fleet binary not on PATH — personal token)" + + +def gh_graphql(query, **variables): + """One GraphQL call via the gh CLI. Raises RuntimeError on failure.""" + cmd = [*GH_CMD, "api", "graphql", "-f", f"query={query}"] + for key, value in variables.items(): + # -F types the value (ints stay ints); -f keeps strings verbatim + # (pagination cursors must never be re-typed). + cmd += ["-F" if isinstance(value, int) else "-f", f"{key}={value}"] + out = subprocess.run(cmd, capture_output=True, text=True) + if out.returncode != 0: + raise RuntimeError(f"gh api graphql failed: {out.stderr.strip()[:300]}") + data = json.loads(out.stdout) + if data.get("errors"): + raise RuntimeError(f"graphql errors: {json.dumps(data['errors'])[:300]}") + return data["data"] + + +def gh_run(*args): + out = subprocess.run([*GH_CMD, *args], capture_output=True, text=True) + if out.returncode != 0: + raise RuntimeError(f"gh {' '.join(args)} failed: {out.stderr.strip()[:300]}") + return out.stdout + + +ISSUES_QUERY = """ +query($owner:String!,$name:String!,$cursor:String){ + repository(owner:$owner,name:$name){ + issues(first:100, after:$cursor, states:[OPEN,CLOSED], + orderBy:{field:CREATED_AT,direction:ASC}){ + pageInfo{ hasNextPage endCursor } + nodes{ number state title + labels(first:30){ nodes{ name } } + subIssuesSummary{ total completed } } + } + } +} +""" + +CLOSE_EVIDENCE_QUERY = """ +query($owner:String!,$name:String!,$number:Int!){ + repository(owner:$owner,name:$name){ + issue(number:$number){ + number state title + subIssuesSummary{ total completed } + timelineItems(itemTypes:[CLOSED_EVENT], last:5){ + nodes{ ... on ClosedEvent{ createdAt actor{ login } } } + } + crossRefs: timelineItems(itemTypes:[CROSS_REFERENCED_EVENT], last:50){ + nodes{ ... on CrossReferencedEvent{ + source{ ... on PullRequest{ number merged mergedAt title body } } } } + } + } + } +} +""" + +LABELED_QUERY = """ +query($owner:String!,$name:String!,$number:Int!){ + repository(owner:$owner,name:$name){ + issue(number:$number){ + timelineItems(itemTypes:[LABELED_EVENT], last:100){ + nodes{ ... on LabeledEvent{ createdAt actor{ login } label{ name } } } + } + } + } +} +""" + + +def enumerate_issues(repo): + owner, name = repo.split("/", 1) + issues, cursor = [], None + while True: + data = gh_graphql(ISSUES_QUERY, owner=owner, name=name, + **({"cursor": cursor} if cursor else {})) + conn = data["repository"]["issues"] + issues.extend(conn["nodes"]) + if not conn["pageInfo"]["hasNextPage"]: + return issues + cursor = conn["pageInfo"]["endCursor"] + + +def parse_ts(s): + return datetime.fromisoformat(s.replace("Z", "+00:00")) + + +def is_bot(login): + return bool(login) and (login.endswith("[bot]") or login in BOT_LOGINS) + + +def closing_keyword_re(repo, number): + owner_repo = re.escape(repo) + num = re.escape(str(number)) + ref = rf"(?:https://github\.com/{owner_repo}/issues/{num}|{owner_repo}#{num}|#{num}\b)" + return re.compile(rf"\b{CLOSING_KEYWORDS}\b\s*:?\s*{ref}", re.IGNORECASE) + + +def classify_close(repo, number): + """Close evidence for one issue: last close actor/time, trigger PR, + closing-keyword presence, human-echo guard. Mirrors the watchdog.""" + owner, name = repo.split("/", 1) + data = gh_graphql(CLOSE_EVIDENCE_QUERY, owner=owner, name=name, number=number) + issue = data["repository"]["issue"] + closes = [n for n in issue["timelineItems"]["nodes"] if n] + evidence = {"open_sub_issues": None, "close_actor": None, "closed_at": None, + "trigger_pr": None, "closing_keyword": False, "human_echo": None} + summary = issue.get("subIssuesSummary") or {} + total, completed = summary.get("total") or 0, summary.get("completed") or 0 + evidence["open_sub_issues"] = total - completed + if not closes: + return evidence + last = closes[-1] + evidence["close_actor"] = (last.get("actor") or {}).get("login") + evidence["closed_at"] = last.get("createdAt") + closed_at = parse_ts(last["createdAt"]) + # Human-echo guard: a human close within 120s before the last close + # means the last close is Kaneo echoing the human, not a bot act. + for ev in closes[:-1]: + actor = (ev.get("actor") or {}).get("login", "") + if is_bot(actor): + continue + at = parse_ts(ev["createdAt"]) + if closed_at - HUMAN_ECHO_WINDOW <= at <= closed_at: + evidence["human_echo"] = actor + kw_re = closing_keyword_re(repo, number) + for node in issue["crossRefs"]["nodes"]: + src = (node or {}).get("source") or {} + if not src.get("merged") or not src.get("mergedAt"): + continue + merged_at = parse_ts(src["mergedAt"]) + if closed_at - CLOSE_WINDOW <= merged_at <= closed_at + timedelta(minutes=2): + evidence["trigger_pr"] = src["number"] + text = f"{src.get('title', '')}\n{src.get('body') or ''}" + evidence["closing_keyword"] = bool(kw_re.search(text)) + break + return evidence + + +def label_actor(repo, number, label): + """Actor of the most recent application of `label`, or None.""" + owner, name = repo.split("/", 1) + data = gh_graphql(LABELED_QUERY, owner=owner, name=name, number=number) + actor = None + for node in data["repository"]["issue"]["timelineItems"]["nodes"]: + if node and (node.get("label") or {}).get("name") == label: + actor = (node.get("actor") or {}).get("login") + return actor + + +# ---------------------------------------------------------------- Kaneo (c) + +KAN_CONTAINER = "pm-stack-postgres-1" +KAN_PSQL = ["docker", "exec", KAN_CONTAINER, "psql", "-U", "kaneo", + "-d", "kaneo", "-tA", "-v", "ON_ERROR_STOP=1"] + + +def kaneo_links(): + """{(repo, issue_number): kaneo_task_status} for GitHub issue links.""" + sql = ("SELECT el.url, t.status FROM external_link el " + "JOIN task t ON t.id = el.task_id " + "WHERE el.resource_type='issue'") + out = subprocess.run(KAN_PSQL + ["-c", sql], capture_output=True, text=True) + if out.returncode != 0: + raise RuntimeError(f"kaneo psql failed: {out.stderr.strip()[:300]}") + links = {} + pat = re.compile(r"^https://github\.com/([^/]+/[^/]+)/issues/(\d+)$") + for line in out.stdout.splitlines(): + url, _, status = line.partition("|") + m = pat.match(url.strip()) + if m: + links[(m.group(1), int(m.group(2)))] = status.strip() + return links + + +# ---------------------------------------------------------------- repairs + +def act_on_finding(kind, repo, number, evidence): + """--act repairs. Returns an action string. Only called for findings + the design's policy makes eligible; everything else stays report-only.""" + if kind == "a": + gh_run("issue", "reopen", str(number), "--repo", repo) + issue_labels = evidence.get("labels") or [] + if DONE_LABEL in issue_labels: + gh_run("issue", "edit", str(number), "--repo", repo, + "--remove-label", DONE_LABEL) + body = ( + "**Invariant sweeper (code#10139): reopening a wrongful auto-close.**\n\n" + f"- Closed by `{evidence.get('close_actor')}` at {evidence.get('closed_at')}.\n" + f"- The issue still has {evidence.get('open_sub_issues')} open sub-issue(s); " + "a parent with open children is never done (epic invariant, code#10136).\n" + f"- Trigger PR: #{evidence.get('trigger_pr')} (no closing keyword for this issue).\n" + "- Reopened under the sweeper's post-review auto-reopen policy " + "(design: doc/2026-11-14T17-00-00Z_design_pm-stack-close-authority). " + "Defect: #7610. Watchdog: #10105.") + gh_run("issue", "comment", str(number), "--repo", repo, "--body", body) + return "reopened" + if kind == "b": + gh_run("issue", "edit", str(number), "--repo", repo, + "--remove-label", DONE_LABEL) + gh_run("issue", "comment", str(number), "--repo", repo, "--body", + "**Invariant sweeper (code#10139): removed a bot-applied " + "`status:done` label from an open issue.** The label is Kaneo's " + "mirror of a Done task; on an open issue it is contradictory " + "state (close-authority program code#10136).") + return "stripped-done-label" + return "report-only" + + +# ---------------------------------------------------------------- the sweep + +def sweep_repo(repo, act): + """Returns (section_dict, error_or_None). Never raises: per-repo + isolation is part of the design (one repo down must not blind the rest).""" + section = {"repo": repo, "issues_total": 0, "closed_total": 0, "open_total": 0, + "a_closed_open_subs": [], "b_open_done_label": [], "actions": []} + try: + issues = enumerate_issues(repo) + except Exception as exc: + return section, str(exc)[:300] + section["issues_total"] = len(issues) + by_number = {} + for issue in issues: + by_number[issue["number"]] = issue + labels = [l["name"] for l in issue["labels"]["nodes"]] + if issue["state"] == "CLOSED": + section["closed_total"] += 1 + summary = issue.get("subIssuesSummary") or {} + open_subs = (summary.get("total") or 0) - (summary.get("completed") or 0) + if open_subs > 0: + finding = {"number": issue["number"], "title": issue["title"], + "open_sub_issues": open_subs, "labels": labels} + try: + ev = classify_close(repo, issue["number"]) + finding.update({k: ev[k] for k in + ("close_actor", "closed_at", "trigger_pr", + "closing_keyword", "human_echo")}) + finding["eligible_reopen"] = bool( + is_bot(ev["close_actor"]) and not ev["closing_keyword"] + and not ev["human_echo"]) + except Exception as exc: + finding["evidence_error"] = str(exc)[:200] + finding["eligible_reopen"] = False + section["a_closed_open_subs"].append(finding) + else: + section["open_total"] += 1 + if DONE_LABEL in labels: + finding = {"number": issue["number"], "title": issue["title"]} + try: + finding["label_actor"] = label_actor(repo, issue["number"], DONE_LABEL) + except Exception as exc: + finding["label_actor_error"] = str(exc)[:200] + section["b_open_done_label"].append(finding) + if act: + for finding in section["a_closed_open_subs"]: + if finding.get("eligible_reopen"): + try: + action = act_on_finding("a", repo, finding["number"], finding) + section["actions"].append({"number": finding["number"], "action": action}) + finding["action"] = action + except Exception as exc: + section["actions"].append({"number": finding["number"], + "error": str(exc)[:200]}) + for finding in section["b_open_done_label"]: + if is_bot(finding.get("label_actor")): + try: + action = act_on_finding("b", repo, finding["number"], finding) + section["actions"].append({"number": finding["number"], "action": action}) + finding["action"] = action + except Exception as exc: + section["actions"].append({"number": finding["number"], + "error": str(exc)[:200]}) + section["_by_number"] = by_number + return section, None + + +def known_positive_status(): + """Evaluate code#9060 with the same classifier the sweep uses.""" + repo, number = KNOWN_POSITIVE + out = {"repo": repo, "number": number} + try: + owner, name = repo.split("/", 1) + data = gh_graphql(CLOSE_EVIDENCE_QUERY, owner=owner, name=name, number=number) + issue = data["repository"]["issue"] + out["state"] = issue["state"] + summary = issue.get("subIssuesSummary") or {} + out["open_sub_issues"] = (summary.get("total") or 0) - (summary.get("completed") or 0) + closes = [n for n in issue["timelineItems"]["nodes"] if n] + if closes: + last = closes[-1] + out["last_close_actor"] = (last.get("actor") or {}).get("login") + out["last_closed_at"] = last.get("createdAt") + out["detected_as_wrongful_close"] = bool( + closes and is_bot(out.get("last_close_actor")) and out["open_sub_issues"] > 0) + out["verdict"] = ("live-violation" if issue["state"] == "CLOSED" + else "resolved-by-audit") + except Exception as exc: + out["error"] = str(exc)[:300] + return out + + +def fingerprint(report): + parts = [] + for sec in report["repos"]: + for f in sec["a_closed_open_subs"]: + parts.append(f"a:{sec['repo']}#{f['number']}") + for f in sec["b_open_done_label"]: + parts.append(f"b:{sec['repo']}#{f['number']}") + for m in report.get("c_kaneo_mismatches", {}).get("items", []): + parts.append(f"c:{m['repo']}#{m['number']}:{m['kind']}") + return hashlib.sha256("\n".join(sorted(parts)).encode()).hexdigest()[:16] + + +def render_markdown(report): + lines = [f"## Invariant sweeper inventory — {report['run_at']}", + "", + f"Mode: **{report['mode']}** · Program: code#10136 · Sweeper: code#10139 · " + "Watchdog: code#10105", + f"GitHub route: {report.get('gh_route', 'unknown')}", + ""] + kp = report["known_positive"] + lines += ["### Known positive — code#9060", ""] + if kp.get("error"): + lines.append(f"- evaluation error: {kp['error']}") + else: + lines.append( + f"- code#9060: closed by `{kp.get('last_close_actor')}` at " + f"{kp.get('last_closed_at')} with {kp.get('open_sub_issues')} sub-issue(s) " + f"still open — classifier verdict: " + f"{'WRONGFUL CLOSE detected' if kp.get('detected_as_wrongful_close') else 'not detected'}; " + f"current state **{kp.get('state')}** " + f"({kp.get('verdict')}).") + lines.append("") + for sec in report["repos"]: + lines += [f"### {sec['repo']}", ""] + if sec.get("error"): + lines += [f"- **SWEEP ERROR:** {sec['error']}", ""] + continue + lines.append(f"- Issues enumerated: {sec['issues_total']} " + f"({sec['closed_total']} closed, {sec['open_total']} open).") + a = sec["a_closed_open_subs"] + lines.append(f"- (a) Closed with open sub-issues: **{len(a)}**") + for f in a[:MAX_EPIC_ROWS]: + lines.append( + f" - #{f['number']} — {f['open_sub_issues']} open sub-issue(s); " + f"closed by `{f.get('close_actor')}` at {f.get('closed_at')}; " + f"trigger PR: {('#' + str(f['trigger_pr'])) if f.get('trigger_pr') else 'none found'}; " + f"closing keyword: {'yes' if f.get('closing_keyword') else 'no'}" + + (f"; action: {f['action']}" if f.get("action") else "") + + ("; **eligible for auto-reopen**" if f.get("eligible_reopen") else "")) + if len(a) > MAX_EPIC_ROWS: + lines.append(f" - … and {len(a) - MAX_EPIC_ROWS} more (full list in the run's JSON report).") + b = sec["b_open_done_label"] + lines.append(f"- (b) Open with `status:done` label: **{len(b)}**") + for f in b[:MAX_EPIC_ROWS]: + lines.append(f" - #{f['number']} — label applied by `{f.get('label_actor')}`" + + (f"; action: {f['action']}" if f.get("action") else "")) + if len(b) > MAX_EPIC_ROWS: + lines.append(f" - … and {len(b) - MAX_EPIC_ROWS} more.") + if sec["actions"]: + lines.append(f"- Actions taken: {json.dumps(sec['actions'])}") + lines.append("") + c = report.get("c_kaneo_mismatches") + lines += ["### Kaneo ↔ GitHub mismatches (c)", ""] + if c is None: + lines.append("- Section skipped (--skip-kaneo).") + elif c.get("error"): + lines.append(f"- **UNAVAILABLE:** {c['error']}") + else: + lines.append(f"- Linked GitHub issues in Kaneo: {c['linked']}; " + f"mismatches: **{c['count']}** " + f"(Kaneo done / GitHub open: {c['kaneo_done_gh_open']}; " + f"Kaneo not-done / GitHub closed: {c['kaneo_open_gh_closed']}). " + "Report-only by policy: GitHub is the truth; the sync or a " + "human heals Kaneo.") + for m in c["items"][:MAX_EPIC_ROWS]: + lines.append(f" - {m['repo']}#{m['number']} — Kaneo task `{m['kaneo_status']}` " + f"vs GitHub `{m['github_state']}`") + if len(c["items"]) > MAX_EPIC_ROWS: + lines.append(f" - … and {len(c['items']) - MAX_EPIC_ROWS} more.") + lines.append("") + lines.append(f"Violation fingerprint: `{report['fingerprint']}`") + return "\n".join(lines) + "\n" + + +def main(argv=None): + args = parse_args(argv) + resolve_gh_route() + run_at = datetime.now(timezone.utc).isoformat() + report = {"run_at": run_at, "mode": "act" if args.act else "report", + "gh_route": GH_ROUTE, "repos": [], "errors": []} + sections = [] + for repo in args.repos: + section, error = sweep_repo(repo, args.act) + if error: + section["error"] = error + report["errors"].append(f"{repo}: {error}") + by_number = section.pop("_by_number", {}) + sections.append((section, by_number)) + report["repos"].append(section) + + # Invariant (c): cross-reference the Kaneo link dump with the + # states this same sweep just enumerated (no second GitHub pass). + if args.skip_kaneo: + report["c_kaneo_mismatches"] = None + else: + try: + links = kaneo_links() + gh_state = {} + for section, by_number in sections: + for number, issue in by_number.items(): + gh_state[(section["repo"], number)] = issue["state"] + items, done_open, open_closed = [], 0, 0 + for (repo, number), status in sorted(links.items()): + state = gh_state.get((repo, number)) + if state is None: + continue + if status == "done" and state == "OPEN": + done_open += 1 + items.append({"repo": repo, "number": number, "kind": "kaneo-done-gh-open", + "kaneo_status": status, "github_state": state}) + elif status != "done" and state == "CLOSED": + open_closed += 1 + items.append({"repo": repo, "number": number, "kind": "kaneo-open-gh-closed", + "kaneo_status": status, "github_state": state}) + report["c_kaneo_mismatches"] = { + "linked": len(links), "count": len(items), + "kaneo_done_gh_open": done_open, "kaneo_open_gh_closed": open_closed, + "items": items} + except Exception as exc: + report["c_kaneo_mismatches"] = {"error": str(exc)[:300]} + report["errors"].append(f"kaneo: {exc}"[:300]) + + report["known_positive"] = known_positive_status() + report["fingerprint"] = fingerprint(report) + + # State + report files (state survives restarts; the fingerprint + # history is what makes epic posting change-only). + state_file = Path(args.state_file) + state = {} + if state_file.exists(): + try: + state = json.loads(state_file.read_text()) + except Exception: + state = {} + report_dir = Path(args.report_dir) + report_dir.mkdir(parents=True, exist_ok=True) + (report_dir / "last-report.json").write_text(json.dumps(report, indent=2) + "\n") + md = render_markdown(report) + (report_dir / "last-report.md").write_text(md) + + posted = False + if args.post_epic and (args.force_post + or state.get("last_posted_fingerprint") != report["fingerprint"]): + body_file = report_dir / "epic-comment.md" + body_file.write_text(md) + gh_run("issue", "comment", str(EPIC_NUMBER), "--repo", EPIC_REPO, + "--body-file", str(body_file)) + posted = True + state["last_posted_fingerprint"] = report["fingerprint"] + + state["last_run"] = run_at + state["last_fingerprint"] = report["fingerprint"] + state["mode"] = report["mode"] + runs = state.setdefault("runs", []) + runs.append({"at": run_at, "mode": report["mode"], + "fingerprint": report["fingerprint"], "posted_epic": posted, + "counts": {sec["repo"]: {"a": len(sec["a_closed_open_subs"]), + "b": len(sec["b_open_done_label"])} + for sec in report["repos"]}, + "errors": report["errors"]}) + state["runs"] = runs[-30:] + state_file.parent.mkdir(parents=True, exist_ok=True) + tmp = state_file.with_suffix(".json.tmp") + tmp.write_text(json.dumps(state, indent=2) + "\n") + tmp.replace(state_file) + + summary = {"run_at": run_at, "mode": report["mode"], "gh_route": GH_ROUTE, + "fingerprint": report["fingerprint"], "posted_epic": posted, + "known_positive": report["known_positive"], + "counts": {sec["repo"]: {"total": sec["issues_total"], + "a": len(sec["a_closed_open_subs"]), + "b": len(sec["b_open_done_label"]), + "actions": sec["actions"]} + for sec in report["repos"]}, + "c_kaneo_mismatches": (None if report["c_kaneo_mismatches"] is None + else {k: v for k, v in report["c_kaneo_mismatches"].items() + if k != "items"}), + "errors": report["errors"]} + print(json.dumps(summary, indent=2)) + return 1 if report["errors"] else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pm-stack/opencode-claimant/claimant.py b/pm-stack/opencode-claimant/claimant.py index f5d17344b6..274af6dcf1 100755 --- a/pm-stack/opencode-claimant/claimant.py +++ b/pm-stack/opencode-claimant/claimant.py @@ -164,17 +164,45 @@ def _delete_session(session_id: str) -> bool: def read_mode() -> str: - """Read the execution mode from the mode file.""" + """Read the execution mode from the mode file. + + Fail-safe default (#10141, close-authority program #10136 P5): + a missing, unreadable, or invalid mode file still defaults to + "shadow" — the non-mutating behaviour is the right safety + default — but it is NEVER silent about it. Before #10141 a + missing file was indistinguishable from an intentional shadow + and summit dispatch stalled on it with no signal anywhere; now + every such read logs a loud CLAIMANT-MODE-WARNING line, and the + aggregator's host-health watchdog surfaces the same fact as a + needs-attention tier item. + """ if not MODE_FILE.exists(): + print( + f"CLAIMANT-MODE-WARNING (#10141): mode file {MODE_FILE} is MISSING " + "- defaulting to shadow; dispatch will return mode_not_live and " + "stall until the file is restored with the intended mode.", + file=sys.stderr, + ) return "shadow" try: - mode = MODE_FILE.read_text().strip().lower() - if mode in ("shadow", "live"): - return mode - return "shadow" - except Exception: + raw = MODE_FILE.read_text() + except Exception as exc: + print( + f"CLAIMANT-MODE-WARNING (#10141): mode file {MODE_FILE} is " + f"UNREADABLE ({exc}) - defaulting to shadow.", + file=sys.stderr, + ) return "shadow" + mode = raw.strip().lower() + if mode in ("shadow", "live"): + return mode + print( + f"CLAIMANT-MODE-WARNING (#10141): mode file {MODE_FILE} content " + f"{raw.strip()[:40]!r} is not live|shadow - defaulting to shadow.", + file=sys.stderr, + ) + return "shadow" def ensure_state_dir() -> None: diff --git a/pm-stack/opencode-claimant/test/test_claimant.py b/pm-stack/opencode-claimant/test/test_claimant.py index c1b345b946..06bc061c3b 100644 --- a/pm-stack/opencode-claimant/test/test_claimant.py +++ b/pm-stack/opencode-claimant/test/test_claimant.py @@ -247,5 +247,51 @@ def fake_fetch(queue): self.assertIn(claimant.LAUNCHED_BY_RECOVERY_ZERO_MESSAGE, bind_argv) +class ReadModeLoudDefaultTests(unittest.TestCase): + """#10141: read_mode() keeps shadow as the fail-safe default for a + missing/unreadable/invalid mode file, but logs a loud + CLAIMANT-MODE-WARNING line on every such read — the silence was + the bug, not the default. Oracle: captured stderr.""" + + def _read_with_file(self, tmp: Path, content): + mode_file = tmp / "mode" + if content is not None: + mode_file.write_text(content) + import io + from contextlib import redirect_stderr + + buf = io.StringIO() + with patch.object(claimant, "MODE_FILE", mode_file), redirect_stderr(buf): + result = claimant.read_mode() + return result, buf.getvalue() + + def test_missing_file_defaults_shadow_and_warns_loudly(self): + import tempfile + + with tempfile.TemporaryDirectory() as td: + result, err = self._read_with_file(Path(td), None) + self.assertEqual(result, "shadow") + self.assertIn("CLAIMANT-MODE-WARNING", err) + self.assertIn("MISSING", err) + + def test_invalid_content_defaults_shadow_and_warns_loudly(self): + import tempfile + + with tempfile.TemporaryDirectory() as td: + result, err = self._read_with_file(Path(td), "banana\n") + self.assertEqual(result, "shadow") + self.assertIn("CLAIMANT-MODE-WARNING", err) + + def test_valid_modes_are_returned_quietly(self): + import tempfile + + with tempfile.TemporaryDirectory() as td: + for content, want in (("live\n", "live"), ("shadow", "shadow"), + (" LIVE ", "live")): + result, err = self._read_with_file(Path(td), content) + self.assertEqual(result, want) + self.assertNotIn("CLAIMANT-MODE-WARNING", err) + + if __name__ == "__main__": unittest.main() diff --git a/pm-stack/systemd/pm-host-health.service b/pm-stack/systemd/pm-host-health.service new file mode 100644 index 0000000000..d7da7893ee --- /dev/null +++ b/pm-stack/systemd/pm-host-health.service @@ -0,0 +1,7 @@ +[Unit] +Description=PM host-health collector — claimant mode + pm unit states for the aggregator watchdog (code#10141) +After=network.target + +[Service] +Type=oneshot +ExecStart=/bin/sh -lc 'python3 /home/user/pm-stack/host-health-collector.py' diff --git a/pm-stack/systemd/pm-host-health.timer b/pm-stack/systemd/pm-host-health.timer new file mode 100644 index 0000000000..f4ea9d15cb --- /dev/null +++ b/pm-stack/systemd/pm-host-health.timer @@ -0,0 +1,11 @@ +[Unit] +Description=PM host-health collector every 5 minutes (code#10141) + +[Timer] +OnCalendar=*-*-* *:00/5:00 +OnBootUSec=1min +Persistent=true +Unit=pm-host-health.service + +[Install] +WantedBy=timers.target diff --git a/pm-stack/systemd/pm-invariant-sweeper.service b/pm-stack/systemd/pm-invariant-sweeper.service new file mode 100644 index 0000000000..6235a578cd --- /dev/null +++ b/pm-stack/systemd/pm-invariant-sweeper.service @@ -0,0 +1,7 @@ +[Unit] +Description=Epic-invariant sweeper — closed-with-open-sub-issues, open status:done, Kaneo<->GitHub mismatches (code#10139) +After=network.target docker.service + +[Service] +Type=oneshot +ExecStart=/bin/sh -lc 'python3 /home/user/pm-stack/invariant-sweeper.py --post-epic' diff --git a/pm-stack/systemd/pm-invariant-sweeper.timer b/pm-stack/systemd/pm-invariant-sweeper.timer new file mode 100644 index 0000000000..8dc6c9cab8 --- /dev/null +++ b/pm-stack/systemd/pm-invariant-sweeper.timer @@ -0,0 +1,10 @@ +[Unit] +Description=Daily epic-invariant sweeper (code#10139) + +[Timer] +OnCalendar=*-*-* 05:47:00 +Persistent=true +Unit=pm-invariant-sweeper.service + +[Install] +WantedBy=timers.target