From ce3670193f94424b95388def042601adb758e34d Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 1 Oct 2026 10:43:30 +0100 Subject: [PATCH] feat: show cockpit actions and honest observation freshness --- AGENTS.md | 20 ++++++ README.md | 21 ++++++ cockpit/index.html | 144 ++++++++++++++++++++++++++++------------ cockpit/sw.js | 2 +- tests/cockpit-state.cjs | 114 +++++++++++++++++++++++++++++++ 5 files changed, 259 insertions(+), 42 deletions(-) create mode 100644 tests/cockpit-state.cjs diff --git a/AGENTS.md b/AGENTS.md index 169a20b..d18b049 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -109,3 +109,23 @@ body and hands them to the human (sessions cannot create Discussions). Only the development flow — Mind prompt → `/start_dev` → `/create_issue` → one issue per task → PR — opens issues here. Why: `PyAutoMind/policy/community_surface.md`. + +## Human-first structured state + +Keep the dashboard and future tools on the same owner-published JSON truth. +The v1 contract now accepts optional item identity/state/reason, action records, +recommended action and explicit decision metadata; see Brain's schema for the +exact definitions. Preserve legacy feeds and prompts. Never infer a scientific +choice just from a blocked gate. Action links open evidence; prompt/command +buttons only copy their targets, never execute them. Absent safety is unknown. + +`observation()` is the pure freshness model used by cards, header and navigation: +source status, fetch outcome and last-good context remain distinct. Validate +persisted feeds before rendering, including organ identity. Failed fetching +must not retain verified-green presentation. Keep generated/checked timestamps +separate and respect producer `valid_until` without guessing a global TTL. +Keep source transition notifications distinct from transport failures. + +Tests: `node --test tests/cockpit-state.cjs`; no runtime dependency or build step. +For future enhancements favour small additions that help a human immediately; +no speculative agent, bus, permissions engine or automation service. diff --git a/README.md b/README.md index cbf601c..6edf05c 100644 --- a/README.md +++ b/README.md @@ -52,3 +52,24 @@ be integrated with the shell; test full navigation on the shared Pages origin. feed (PyAutoNerves#172) — a read-only browser of every config file and option across the libraries and workspaces: yellow when a config file does not parse or a workspace sets keys no library defines. + +### Actionable state and freshness + +The cockpit remains a human interface over the organs' shared `state.json` +feeds. Brain's optional v1 metadata adds reasons, labelled actions and explicit +human decisions. It renders old and enriched feeds together. Actions link to +evidence or copy existing commands/prompts; viewing a problem never executes +its remedy. Approval and scientific-judgement labels describe the source's +constraints, and missing safety information is unclassified. + +Cards distinguish feed generation from the browser's last check. Failed fetches +show last-known results as stale, keeping previous failures visible. Invalid or +future timestamps cannot show current green. Producer-declared `valid_until` +deadlines are respected; without one the cockpit displays the age and invents +no expiry interval. Source verdicts, transport failure and freshness stay +separate. No persistent agent or new notification service is included. + +Run the dependency-free contract/model checks with +`node --test tests/cockpit-state.cjs`. Browser checks should additionally cover +mobile/light/dark layout, clipboard, navigation and a selected board remaining +in place during polling. The runtime still needs no packages or build step. diff --git a/cockpit/index.html b/cockpit/index.html index 8cb4c5c..d7cea2d 100644 --- a/cockpit/index.html +++ b/cockpit/index.html @@ -116,6 +116,11 @@ flex: none; width: 2rem; height: 1.7rem; border: 1px solid var(--line); border-radius: 6px; background: var(--code-bg); color: var(--text); cursor: pointer; font-size: 0.85rem; line-height: 1; } + .reason, .decision { display: block; margin-top: 0.25rem; } + .reason, .action-safety { color: var(--text-soft); font-size: 0.8rem; } + .decision { border-left: 3px solid var(--yellow); padding-left: 0.5rem; } + ul.items .actions { display: flex; flex-wrap: wrap; align-items: center; gap: 0.4rem; margin: 0.35rem 0; } + ul.items .action, ul.items button.copy.action { display: inline-flex; align-items: center; min-height: 44px; width: auto; height: auto; padding: 0.45rem 0.6rem; white-space: normal; text-align: left; line-height: 1.3; } button.copy:hover { border-color: var(--brand); } button.copy.ok { border-color: var(--green); color: var(--green); } @@ -263,7 +268,8 @@

Your cockpit

({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); } function safeUrl(u) { - return typeof u === "string" && /^https?:\/\//i.test(u) ? u : null; + if (typeof u !== "string" || !/^https?:\/\//i.test(u)) return null; + try { const url = new URL(u); return url.hostname ? url.href : null; } catch (e) { return null; } } function age(iso) { const t = Date.parse(iso); @@ -283,78 +289,131 @@

Your cockpit

try { localStorage.setItem(LS_KEY + repo, JSON.stringify(obj)); } catch (e) { /* private mode */ } } -// Minimal client-side check of the v1 contract; returns an error string or null. -function validate(d) { - if (!d || typeof d !== "object") return "not an object"; +// Additive v1 metadata: older producers need no migration. +const ITEM_STATES = ["healthy", "active", "stale", "blocked", "failed", "action_required", "unknown"]; +const ACTION_SAFETY = ["read_only", "requires_approval", "scientific_judgement", "never_automatic", "unclassified"]; +const oneLine = v => typeof v === "string" && v.trim() !== "" && !/[\r\n]/.test(v); +function utcTime(v) { + if (typeof v !== "string" || !/T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|\+00:00)$/.test(v)) return NaN; + const t = Date.parse(v); + // Date.parse normalizes impossible dates such as February 30. + return Number.isFinite(t) && new Date(t).toISOString().slice(0, 19) === v.slice(0, 19) ? t : NaN; +} +function validate(d, organ = null) { + if (!d || typeof d !== "object" || Array.isArray(d)) return "not an object"; if (d.schema_version !== 1) return "schema_version " + d.schema_version; - if (!STATUSES.includes(d.status)) return "status " + d.status; - if (typeof d.headline !== "string") return "no headline"; + if (!STATUSES.includes(d.status)) return "invalid status"; + if (![d.organ, d.repo, d.pages_url, d.headline].every(oneLine)) return "missing identity or headline"; + if (organ && (d.organ !== organ.organ.toLowerCase() || d.repo !== organ.repo)) return "wrong organ"; + if (!Number.isFinite(utcTime(d.updated))) return "invalid updated timestamp"; + if ("valid_until" in d && (!Number.isFinite(utcTime(d.valid_until)) || utcTime(d.valid_until) < utcTime(d.updated))) return "invalid valid_until"; if (!Array.isArray(d.items)) return "no items"; + const ids = new Set(); for (const it of d.items) { - if (!it || !SEVERITIES.includes(it.severity) || typeof it.text !== "string") return "bad item"; + if (!it || !SEVERITIES.includes(it.severity) || !oneLine(it.text)) return "bad item"; + for (const key of ["url", "prompt"]) if (it[key] != null && typeof it[key] !== "string") return "bad " + key; + for (const key of ["id", "reason", "decision", "recommended_action_id"]) if (key in it && !oneLine(it[key])) return "bad " + key; + if ("id" in it) { if (ids.has(it.id)) return "duplicate item id"; ids.add(it.id); } + if ("state" in it && !ITEM_STATES.includes(it.state)) return "bad item state"; + if ("requires_human_decision" in it && typeof it.requires_human_decision !== "boolean") return "bad decision flag"; + if (it.requires_human_decision && !oneLine(it.decision)) return "missing decision"; + if ("actions" in it && !Array.isArray(it.actions)) return "bad actions"; + const actions = new Set(); + for (const action of it.actions || []) { + if (!action || ![action.id, action.label, action.target].every(oneLine)) return "bad action"; + if (!["link", "command", "prompt"].includes(action.kind)) return "bad action kind"; + if ("safety" in action && !ACTION_SAFETY.includes(action.safety)) return "bad action safety"; + if (action.kind === "link" && !safeUrl(action.target)) return "bad action URL"; + if (actions.has(action.id)) return "duplicate action id"; + actions.add(action.id); + } + if ("recommended_action_id" in it && !actions.has(it.recommended_action_id)) return "missing recommended action"; } return null; } +// Pure observation model. Source health and transport/freshness are separate +// facts. Missing expiry means no declared age policy, not infinite freshness. +function observation(st = {}, now = Date.now()) { + const d = st.feed || st.lastGood || null; + const base = { feed: d, sourceStatus: d ? d.status : null, lastChecked: st.lastChecked || null }; + if (!d) return { ...base, status: "grey", current: false, freshness: "unknown", reason: st.error || "waiting for first check" }; + if (st.error || !st.feed) return { ...base, status: "stale", current: false, freshness: "unavailable", reason: st.error || "not checked this session" }; + if (!Number.isFinite(utcTime(d.updated)) || utcTime(d.updated) > now) return { ...base, status: "grey", current: false, freshness: "unknown", reason: "source timestamp is invalid or in the future" }; + if (d.valid_until && utcTime(d.valid_until) <= now) return { ...base, status: "stale", current: false, freshness: "expired", reason: "source freshness deadline passed" }; + if (d.status === "stale") return { ...base, status: "stale", current: false, freshness: "expired", reason: "source reports stale evidence" }; + if (d.status === "grey") return { ...base, status: "grey", current: false, freshness: "unknown", reason: "source reports insufficient evidence" }; + return { ...base, status: d.status, current: true, freshness: d.valid_until ? "within_policy" : "unspecified", reason: null }; +} + async function fetchOrgan(o) { const st = state[o.organ] || (state[o.organ] = {}); if (!st.lastGood) { const saved = lsGet(o.repo); - if (saved) { st.lastGood = saved.feed; st.lastGoodAt = saved.at; } + if (saved && !validate(saved.feed, o)) { st.lastGood = saved.feed; st.lastGoodAt = saved.at; } } if (!o.feed) { st.feed = null; st.error = null; return; } + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 15000); try { // no-store skips the browser cache; the query string skips the Pages CDN cache. - const r = await fetch(o.feed + "?t=" + Date.now(), { cache: "no-store" }); + const r = await fetch(o.feed + "?t=" + Date.now(), { cache: "no-store", signal: controller.signal }); if (!r.ok) throw new Error("HTTP " + r.status); let d; try { d = await r.json(); } catch (e) { st.feed = null; st.error = "bad feed: not JSON"; return; } - const bad = validate(d); + const bad = validate(d, o); if (bad) { st.feed = null; st.error = "bad feed: " + bad; return; } st.feed = d; st.error = null; st.lastGood = d; st.lastGoodAt = new Date().toISOString(); lsSet(o.repo, { feed: d, at: st.lastGoodAt }); } catch (e) { st.feed = null; st.error = "unreachable"; - } + } finally { clearTimeout(timeout); st.lastChecked = new Date().toISOString(); } } -// The status an organ counts as: live feed, else its last good one, else grey. -function effective(o) { - const st = state[o.organ] || {}; - const d = st.feed || st.lastGood; - return d ? d.status : "grey"; -} -function feedFor(o) { const st = state[o.organ] || {}; return st.feed || st.lastGood || null; } +function viewFor(o) { return observation(state[o.organ]); } +function effective(o) { return viewFor(o).status; } +function feedFor(o) { return viewFor(o).feed; } function redItems(o) { const d = feedFor(o); return d ? d.items.filter(i => i.severity === "red").length : 0; } -function itemsHtml(items) { - if (!items.length) return '

nothing needs you

'; +const SAFETY_LABEL = { read_only: "Read only", requires_approval: "Approval required", + scientific_judgement: "Scientific judgement", never_automatic: "Manual only", unclassified: "Safety unclassified" }; +function actionsHtml(it) { + const actions = it.actions || []; + const rendered = actions.map(action => { + const recommended = action.id === it.recommended_action_id; + const safety = SAFETY_LABEL[action.safety || "unclassified"]; + const title = (recommended ? "Recommended · " : "") + safety; + if (action.kind === "link") return `${esc(action.label)}`; + return `${esc(safety)}`; + }); + if (it.prompt && !actions.some(a => a.kind !== "link" && a.target === it.prompt)) rendered.push(``); + return rendered.length ? `${rendered.join("")}` : ""; +} +function itemsHtml(items, current = true) { + if (!items.length) return `

${current ? "nothing needs you" : "no attention items in the last known feed"}

`; const shown = items.slice(0, MAX_ITEMS).map(it => { const url = safeUrl(it.url); const text = url ? `${esc(it.text)}` : esc(it.text); - const copy = it.prompt - ? `` - : ""; + const reason = it.reason ? `${esc(it.reason)}` : ""; + const decision = it.requires_human_decision ? `Your decision: ${esc(it.decision)}` : ""; const sev = it.severity === "info" ? "sev-info" : "s-" + it.severity; - return `
  • ${text}${copy}
  • `; + return `
  • ${text}${reason}${decision}${actionsHtml(it)}
  • `; }); if (items.length > MAX_ITEMS) shown.push(`
  • + ${items.length - MAX_ITEMS} more on the board
  • `); return ``; } function metaHtml(o) { - const st = state[o.organ] || {}; if (!o.feed) return '

    no feed yet

    '; - const d = feedFor(o); - if (st.error) { - const good = st.lastGoodAt ? " · last good " + age(st.lastGoodAt) : " · no last good copy"; - return `

    ${esc(st.error)}${good}

    `; - } - return d ? `

    updated ${esc(age(d.updated))}

    ` : '

    loading…

    '; + const v = viewFor(o), st = state[o.organ] || {}, d = v.feed; + const generated = d ? `generated ${esc(age(d.updated))}` : ""; + const checked = st.lastChecked ? `checked ${esc(age(st.lastChecked))}` : ""; + const warning = v.reason ? `${esc(v.reason)}${d ? " · last known " + esc(d.status) : ""}` : ""; + return `

    ${[warning, generated, checked].filter(Boolean).join(" · ")}

    `; } function boardUrl(o) { @@ -370,7 +429,7 @@

    Your cockpit

    : d ? `

    ${esc(d.headline)}

    ` : ""; return `

    ${esc(o.organ)}${esc(word)}

    - ${head}${metaHtml(o)}${d ? itemsHtml(d.items) : ""} + ${head}${metaHtml(o)}${d ? itemsHtml(d.items, viewFor(o).current) : ""}
    `; } @@ -384,19 +443,21 @@

    ${esc(o.organ)} ${esc(status)} board →

    - ${d ? `

    ${esc(d.headline)}

    ` : ""}${metaHtml(o)}${d ? itemsHtml(d.items) : ""}`; + ${d ? `

    ${esc(d.headline)}

    ` : ""}${metaHtml(o)}${d ? itemsHtml(d.items, viewFor(o).current) : ""}`; } function renderHeader() { const live = ORGANS.filter(o => o.feed); const worst = live.reduce((w, o) => RANK[effective(o)] > RANK[w] ? effective(o) : w, "green"); - const reds = ORGANS.reduce((n, o) => n + redItems(o), 0); + const reds = ORGANS.reduce((n, o) => n + (viewFor(o).current ? redItems(o) : 0), 0); + const previousReds = ORGANS.reduce((n, o) => n + (!viewFor(o).current ? redItems(o) : 0), 0); const el = document.getElementById("overall"); el.className = "overall s-" + worst; el.innerHTML = `${esc(worst)}` + - (reds ? `· ${reds} red` : ""); + (reds ? `· ${reds} red` : "") + + (previousReds ? `· ${previousReds} last-known red` : ""); document.title = (reds ? `(${reds} red) ` : "") + "PyAuto Cockpit"; - updateBadge(reds); + updateBadge(reds + previousReds); } function render() { @@ -465,9 +526,9 @@

    Date.now())) now[o.organ] = st.feed.status; } if (prevStatus) { let changed = false; @@ -682,7 +744,7 @@

    { diff --git a/tests/cockpit-state.cjs b/tests/cockpit-state.cjs new file mode 100644 index 0000000..0644e28 --- /dev/null +++ b/tests/cockpit-state.cjs @@ -0,0 +1,114 @@ +// No application dependencies: exercise the inline contract/model directly. +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); +const html = fs.readFileSync(require('node:path').join(__dirname, '../cockpit/index.html'), 'utf8'); +const script = html.split('')[0]; +new vm.Script(script); // Also syntax-check navigation and startup code. +const now = Date.parse('2026-10-01T12:00:00Z'); +function harness(extra = {}) { + const ctx = vm.createContext({ URL, Date: class extends Date { + constructor(...args) { super(...(args.length ? args : [now])); } + static now() { return now; } + }, setTimeout, clearTimeout, AbortController, ...extra }); + vm.runInContext(script.split('// ---- one-window board navigation ----')[0], ctx); + return { ctx, run: expr => vm.runInContext(expr, ctx) }; +} +const legacy = () => ({ schema_version: 1, organ: 'brain', repo: 'PyAutoBrain', status: 'green', + headline: 'All clear', updated: '2026-10-01T11:00:00Z', pages_url: 'https://example.invalid/', items: [] }); +function view(st) { return harness({ st, now }).run('observation(st, now)'); } +test('legacy feeds remain valid and do not gain an invented freshness deadline', () => { + const h = harness({ data: legacy() }); + assert.equal(h.run('validate(data)'), null); + assert.equal(view({ feed: legacy() }).freshness, 'unspecified'); +}); +test('cached green never presents as currently healthy; cached red stays available as evidence', () => { + for (const status of ['green', 'red']) { + const d = { ...legacy(), status }; + const v = view({ lastGood: d, error: 'unreachable' }); + assert.equal(v.status, 'stale'); assert.equal(v.current, false); + assert.equal(v.sourceStatus, status); assert.equal(v.feed.headline, d.headline); + assert.equal(view({ feed: d, lastGood: d }).status, status); + } + assert.equal(view({}).status, 'grey'); + assert.equal(view({ lastGood: legacy() }).current, false); +}); +test('missing, invalid, impossible and future dates cannot produce current green', () => { + for (const updated of [undefined, 'broken', '2026-02-30T01:00:00Z', '2026-10-02T00:00:00Z']) { + const d = { ...legacy(), updated }; + assert.equal(view({ feed: d }).current, false); + } +}); +test('expiry uses producer policy and the exact deadline is stale', () => { + const d = { ...legacy(), valid_until: '2026-10-01T12:00:00Z' }; + assert.equal(view({ feed: d }).freshness, 'expired'); + d.valid_until = '2026-10-01T12:00:01Z'; + assert.equal(view({ feed: d }).freshness, 'within_policy'); + d.valid_until = '2026-09-30T00:00:00Z'; + assert.match(harness({ d }).run('validate(d)'), /valid_until/); +}); +const item = () => ({ severity: 'red', text: 'Nightly failed', id: 'overnight:Example/Engine/nightly.yml', + state: 'failed', reason: 'GitHub reports failure.', prompt: '/bug nightly', + actions: [{ id: 'investigate', label: 'Copy investigation prompt', kind: 'prompt', target: '/bug nightly', safety: 'requires_approval' }], recommended_action_id: 'investigate' }); +test('enriched feed validates, renders one copy action and escapes all producer text', () => { + const it = item(); it.reason = ''; + const h = harness({ d: { ...legacy(), items: [it] } }); + assert.equal(h.run('validate(d)'), null); + const rendered = h.run('itemsHtml(d.items)'); + assert.equal((rendered.match(/data-cmd=/g) || []).length, 1); + assert.match(rendered, /Approval required/); assert.match(rendered, /<script>/); + assert.doesNotMatch(rendered, /