Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Record server-observed source provenance for quality audits
Adam Eivy6d60e7350c18
diff --git a/client/src/components/cos/AuditSourceEvidence.jsx b/client/src/components/cos/AuditSourceEvidence.jsxnew file mode 100644index 0000000000..9eb131fd86--- /dev/null+++ b/client/src/components/cos/AuditSourceEvidence.jsx@@ -0,0 +1,20 @@+import { formatCount } from '../../utils/formatters';++export default function AuditSourceEvidence({ evidence }) {+ if (!evidence) return null;+ if (evidence.status !== 'captured') {+ return <p className="text-xs text-port-text-muted">Audit source provenance unavailable.</p>;+ }+ return (+ <details className="text-xs text-port-text-muted min-w-0">+ <summary className="cursor-pointer">Audit launch source: {evidence.revision.slice(0, 12)}</summary>+ <div className="space-y-1 break-all mt-1">+ <p>Commit: {evidence.revision}</p>+ <p>Committed inventory: {formatCount(evidence.trackedEntryCount)} entries (including symlinks and submodule references).</p>+ <p>Inventory SHA-256: {evidence.inventorySha256}</p>+ <p>Workspace observed at capture: {evidence.workingTreeState}. Captured: {evidence.capturedAt}.</p>+ <p>Server-observed launch context, not reviewed-file coverage. Uncommitted changes and submodule contents are excluded; assessment scan counts remain model-reported.</p>+ </div>+ </details>+ );+}diff --git a/client/src/components/cos/AuditSourceEvidence.test.jsx b/client/src/components/cos/AuditSourceEvidence.test.jsxnew file mode 100644index 0000000000..2d55c74374--- /dev/null+++ b/client/src/components/cos/AuditSourceEvidence.test.jsx@@ -0,0 +1,18 @@+import { cleanup, render, screen } from '@testing-library/react';+import { afterEach, expect, it } from 'vitest';+import AuditSourceEvidence from './AuditSourceEvidence';+afterEach(cleanup);+it('distinguishes committed source context from claimed coverage and shows dirty state', () => {+ render(<AuditSourceEvidence evidence={{ status: 'captured', revision: 'a'.repeat(40), inventorySha256: 'b'.repeat(64), trackedEntryCount: 42, workingTreeState: 'modified', capturedAt: '2026-01-01T00:00:00Z' }} />);+ expect(screen.getByText(/Committed inventory: 42 entries/)).toBeTruthy();+ expect(screen.getByText(/Workspace observed at capture: modified/)).toBeTruthy();+ expect(screen.getByText(/not reviewed-file coverage/)).toBeTruthy();+ expect(screen.getByText(/assessment scan counts remain model-reported/)).toBeTruthy();+});+it('does not invent historical provenance or interpret unavailable evidence as zero coverage', () => {+ const { container, rerender } = render(<AuditSourceEvidence />);+ expect(container.textContent).toBe('');+ rerender(<AuditSourceEvidence evidence={{ status: 'unavailable' }} />);+ expect(screen.getByText('Audit source provenance unavailable.')).toBeTruthy();+ expect(container.textContent).not.toContain('0 entries');+});diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsxindex 379a12f064..75bebaf45e 100644--- a/client/src/components/cos/tabs/AgentCard.jsx+++ b/client/src/components/cos/tabs/AgentCard.jsx@@ -33,6 +33,7 @@ import { copyToClipboard } from '../../../lib/clipboard';import { estimateCosDuration } from '../../../lib/cosDurationEstimate';import { isAgentFeedbackUpdateTarget, isSystemAgent as isSystemAgentRecord } from '../../../lib/cosAgentFeedback';import AgentResultLine from '../AgentResultLine';+import AuditSourceEvidence from '../AuditSourceEvidence';import { DEFAULT_REVIEWER, normalizeReviewers } from '../constants';import { formatBytes, formatCount, formatDurationMs, formatDateTime, formatTimeOfDay, shortClaudeModelName } from '../../../utils/formatters';import { useSocketResource } from '../../../hooks/useSocketResource';@@ -1118,6 +1119,8 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,remainingTime={remainingTime}/>+ <AuditSourceEvidence evidence={agent.metadata?.auditSourceEvidence} />+{agent.result && (<div className="flex items-center gap-4 flex-wrap"><AgentResultLine agent={agent} />diff --git a/server/lib/README.md b/server/lib/README.mdindex 19949d996b..05aa182cd7 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -105,6 +105,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `quotaBurnLegacyConversion.js` | The ONE rule turning a LEGACY quota-burn step (copied prompt + quota-only `jobType`) into a scheduled-task reference, shared by migration 359 and the live compat path so the two cannot drift. `planQuotaBurnStepConversion` decides between three outcomes — a recognized unmodified shipped preset onto its scheduled audit counterpart with issues-only pinned explicitly (`AUDIT_TASK_TYPE_BY_PRESET_ID`, inverted from `auditCatalog.js`), the two programmatic types onto their scheduled handlers, and anything customized or targetless onto a `buildQuotaBurnCustomJob` on-demand custom task addressed by the deterministic `quotaBurnCustomJobId` (which is what makes a repeated or resumed conversion create no duplicate). `legacyAgentTaskMetadata` reproduces the retired executor's dispatch posture; `applyQuotaBurnStepConversion` rewrites the step, preserving id, label, enabled and run-once state. Recognition is `matchStoredAuditPreset`, never a label or a partial match. || `quotaBurnOrigin.js` | Quota-burn PROVENANCE on an on-demand scheduled-task request and on the task it produces. `normalizeQuotaBurnProvenance` reads the request block (burn-step id always required, plus an attribution — the family whose window is spent, OR the manual `maintenanceRunId` alone when the run is pinned outside every subscription family — the limiting-window reset and the provider/model/effort overrides); `QUOTA_BURN_PROVENANCE_FIELDS` is the ONE block definition every persistence and projection hop derives from, spread by `quotaBurnTaskMetadata` (flat task-metadata keys), `quotaBurnAgentMetadata` (the agent projection) and read back by `quotaBurnProvenance` / `hasQuotaBurnProvenance`, which accept both the flat keys and a nested `quotaBurn` block; `burnPlanOwnsTask` / `burnPlanOwnsAgent` are the ONE rule for whether the family plan (not a manual maintenance run) owns a burn-provenanced task. `isManualOnDemandRequest` distinguishes explicit runs from automated cadence gates. `onDemandRequestMetadata` is the single spread both on-demand engines apply. Import-light on purpose — `taskScheduleConstants.js` declares the origin string and must not drag the quota-burn config graph. || `quotaBurnPresets.js` | FROZEN compatibility-and-migration input (#6381). `QUOTA_BURN_PROMPT_PRESETS` — ready-made single-focus audit prompts for `agent-prompt` burn jobs (UX, a11y, mobile, failure paths, perf, test gaps, dead code, data safety, docs, security), each filing GitHub issues and changing no code. Templates: picking one COPIES its prompt into the job, so editing them never rewrites a configured job. `findQuotaBurnPreset(id)`; `matchStoredAuditPreset` is migration 305's recognition rule (match the MISSION half, gated on the shipped contract anchors + headings) and `upgradeStoredAuditPrompt` is the refresh built on it. |+| `auditSourceEvidence.js` | Best-effort server-owned audit launch revision and committed-tree inventory digest/count. Mutable workspace state is observed separately; this is not reviewed-file coverage or score certification. || `auditCatalog.js` | `getAuditScheduleMetadata` derives upgrade-safe display names and cluster labels; `AUDIT_RUN_GUIDANCE` supplies advisory sequencing. Shared catalog of scheduled AUDIT task types (`AUDIT_DEFINITIONS` / `AUDIT_TASK_TYPES`) that can either implement a fix or file tracker issues. Filing presets carry `issueLabel` (category) plus `metricLabel`/`extraLabels` so forge issues can be filtered by focus without putting ids in titles. `DO_BETTER_SCOPE_COVERAGE` maps scheduled task types to the bundled slashdo scope table; `DO_BETTER_LENS_COVERAGE` remains a compatibility alias. `metricLabelFromSlugPrefix`, `isFileIssuesMode`, `isExplicitFileIssuesRequest`, `FILE_ISSUES_DELIVERY_SETTINGS` (the one delivery posture every file-issues lane stamps), `auditDoWorkRequiresWorktree`, `getAuditFilingPreset`, `modeContractFor`, `applyAuditModeWrapper`. Each quota-burn audit preset maps to a scheduled type here (guarded by `auditCatalog.test.js`). Pure — no I/O. || `quotaBurnTaskRef.js` | The quota-burn STEP model: a discriminated scheduled-task reference (`builtin` task type + validated target app, or `custom` app-job id whose own scope is authoritative) plus the per-invocation `overrides` bag (provider/model/effort/params — unset inherits the task's saved settings, and nothing written here edits the schedule). `normalizeQuotaBurnTaskRef` / `normalizeQuotaBurnOverrides` / `normalizeQuotaBurnParams`, the `QUOTA_BURN_UNAVAILABLE` reason codes, `resolveQuotaBurnStepAvailability` (catalog passed IN, so this stays pure) / `applyQuotaBurnAvailability`, `quotaBurnStepIsDispatchable`, and `evaluateOnDemandEligibility` — the ONE on-demand gate ladder (`enabled` / instance feature / invocation eligibility / target scope / per-app switch / master Improve) shared with `taskSchedule.triggerOnDemandTask`, with `enabledAppIdsByTaskType` deriving its per-app input. || `quotaBurnValidation.js` | Zod schemas for the Quota Burn routes (partial config PUT, manual-run body, `run once` re-arm body). |diff --git a/server/lib/agentRegistrationRecord.js b/server/lib/agentRegistrationRecord.jsindex 7f340fc94d..34b45a56fe 100644--- a/server/lib/agentRegistrationRecord.js+++ b/server/lib/agentRegistrationRecord.js@@ -46,6 +46,7 @@ export function buildAgentRegistration({sourceWorkspace,repoIssueUrl,primaryCheckoutBaseline,+ auditSourceEvidence = null,worktreeInfo,explicitWorktree,jiraBranchName,@@ -75,6 +76,8 @@ export function buildAgentRegistration({// worktree. Non-throwing: an unreadable checkout yields null, which the// detector reads as "nothing to check".primaryCheckoutBaseline,+ // Trusted launch capture only; never project a task/model-supplied claim.+ auditSourceEvidence,// The issue-tracker base URL of the repository this run worked in, already// shaped for its forge (`repoIssueUrlBase`) so the browser appends a number// and knows nothing about forges. It is what a bare `#7640` in the agent'sdiff --git a/server/lib/agentRegistrationRecord.test.js b/server/lib/agentRegistrationRecord.test.jsindex b51e8cd8f4..24f8d5f377 100644--- a/server/lib/agentRegistrationRecord.test.js+++ b/server/lib/agentRegistrationRecord.test.js@@ -121,3 +121,10 @@ describe('buildAgentRegistration — claim ownership', () => {expect(record.claimPicksOwnBranch).toBeUndefined();});});++it('accepts audit source provenance only from server capture, never task metadata', () => {+ const injected = { status: 'captured', revision: 'model-claim' };+ expect(buildAgentRegistration(args({ auditSourceEvidence: injected })).auditSourceEvidence).toBeNull();+ const observed = { status: 'unavailable', version: 1 };+ expect(buildAgentRegistration({ ...args({ auditSourceEvidence: injected }), auditSourceEvidence: observed }).auditSourceEvidence).toEqual(observed);+});diff --git a/server/lib/auditSourceEvidence.js b/server/lib/auditSourceEvidence.jsnew file mode 100644index 0000000000..31a2022b14--- /dev/null+++ b/server/lib/auditSourceEvidence.js@@ -0,0 +1,33 @@+import { createHash } from 'node:crypto';+import { execGit } from './execGit.js';++/** Server-observed launch context, NOT a scan manifest or coverage certificate.+ * Hash the captured commit's tree (paths, modes and object IDs), never a later+ * HEAD. Quoted ls-tree output is ASCII and stable even for unusual filenames.+ * Dirty/untracked bytes and submodule contents are not part of this inventory.+ */+export async function captureAuditSourceEvidence(workspacePath, { runGit = execGit } = {}) {+ const capturedAt = new Date().toISOString();+ const unavailable = { version: 1, status: 'unavailable', capturedAt };+ const read = args => runGit(args, workspacePath, { timeout: 5000, maxBuffer: 8 * 1024 * 1024 });+ return (async () => {+ const revision = (await read(['rev-parse', '--verify', 'HEAD^{commit}'])).stdout.trim();+ if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(revision)) return unavailable;+ const [tree, status, finalHead] = await Promise.all([+ read(['-c', 'core.quotePath=true', 'ls-tree', '-r', '--full-tree', revision]),+ read(['status', '--porcelain=v1', '-z', '--untracked-files=normal', '--ignore-submodules=none']).catch(() => null),+ read(['rev-parse', '--verify', 'HEAD^{commit}']).catch(() => null),+ ]);+ return {+ version: 1,+ status: 'captured',+ capturedAt,+ revision,+ inventoryScope: 'committed-tree',+ inventorySha256: createHash('sha256').update(tree.stdout).digest('hex'),+ trackedEntryCount: tree.stdout.split('\n').filter(Boolean).length,+ workingTreeState: !status || finalHead?.stdout.trim() !== revision+ ? 'unknown' : status.stdout ? 'modified' : 'clean',+ };+ })().catch(() => unavailable);+}diff --git a/server/lib/auditSourceEvidence.test.js b/server/lib/auditSourceEvidence.test.jsnew file mode 100644index 0000000000..35ddba5523--- /dev/null+++ b/server/lib/auditSourceEvidence.test.js@@ -0,0 +1,62 @@+import { afterEach, expect, it, vi } from 'vitest';+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { execGit } from './execGit.js';+import { captureAuditSourceEvidence } from './auditSourceEvidence.js';+const roots = [];+afterEach(async () => { await Promise.all(roots.splice(0).map(path => rm(path, { recursive: true, force: true }))); });+async function repository() {+ const path = await mkdtemp(join(tmpdir(), 'audit-source-'));+ roots.push(path);+ await execGit(['init'], path);+ await execGit(['config', 'user.name', 'Fixture'], path);+ await execGit(['config', 'user.email', '[email protected]'], path);+ await writeFile(join(path, 'private\nname.txt'), 'first');+ await execGit(['add', '.'], path);+ await execGit(['commit', '-m', 'fixture'], path);+ return path;+}+it('records immutable committed inventory, distinguishes dirty workspaces and does not invent evidence for missing repositories', async () => {+ const path = await repository();+ const first = await captureAuditSourceEvidence(path);+ expect(first).toMatchObject({ status: 'captured', trackedEntryCount: 1, workingTreeState: 'clean' });+ await writeFile(join(path, 'private\nname.txt'), 'edited');+ await writeFile(join(path, 'untracked.txt'), 'not in commit');+ const dirty = await captureAuditSourceEvidence(path);+ expect(dirty).toMatchObject({ revision: first.revision, inventorySha256: first.inventorySha256, trackedEntryCount: 1, workingTreeState: 'modified' });+ expect(JSON.stringify(dirty)).not.toContain('private');+ await execGit(['add', '.'], path);+ await execGit(['commit', '-m', 'second fixture'], path);+ const second = await captureAuditSourceEvidence(path);+ expect(second.revision).not.toBe(first.revision);+ expect(second.inventorySha256).not.toBe(first.inventorySha256);+ expect(second.trackedEntryCount).toBe(2);+ const unavailable = await captureAuditSourceEvidence(join(path, 'missing'));+ expect(unavailable).toMatchObject({ status: 'unavailable' });+ expect(unavailable).not.toHaveProperty('trackedEntryCount');+});+it('pins the inventory to the initial SHA when real HEAD moves mid-capture', async () => {+ const path = await repository();+ const original = (await execGit(['rev-parse', 'HEAD'], path)).stdout.trim();+ let reads = 0;+ const runGit = async (args, cwd, options) => {+ const result = await execGit(args, cwd, options);+ if (args[0] === 'rev-parse' && ++reads === 1) {+ await writeFile(join(path, 'new.txt'), 'later');+ await execGit(['add', '.'], path);+ await execGit(['commit', '-m', 'concurrent commit'], path);+ }+ return result;+ };+ expect(await captureAuditSourceEvidence(path, { runGit })).toMatchObject({ revision: original, trackedEntryCount: 1, workingTreeState: 'unknown' });+});+it('makes synthetic races and command failure explicit without leaking diagnostics', async () => {+ const original = 'a'.repeat(40);+ const runGit = vi.fn().mockResolvedValueOnce({ stdout: original }).mockResolvedValueOnce({ stdout: '100644 blob abc\tfile\n' }).mockRejectedValueOnce(new Error('private status path')).mockResolvedValueOnce({ stdout: 'b'.repeat(40) });+ const evidence = await captureAuditSourceEvidence('/synthetic', { runGit });+ expect(runGit.mock.calls[1][0]).toEqual(['-c', 'core.quotePath=true', 'ls-tree', '-r', '--full-tree', original]);+ expect(evidence).toMatchObject({ revision: original, workingTreeState: 'unknown' });+ expect(JSON.stringify(evidence)).not.toContain('private');+ expect(await captureAuditSourceEvidence('/synthetic', { runGit: vi.fn().mockRejectedValue(new Error('private')) })).toMatchObject({ status: 'unavailable' });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex b6373f1ec9..2a700ad321 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -258,6 +258,7 @@ export * from './quotaBurnLegacyConversion.js';export * from './quotaBurnOrigin.js';export * from './quotaBurnPresets.js';export * from './auditCatalog.js';+export * from './auditSourceEvidence.js';export * from './quotaBurnTaskRef.js';export * from './quotaBurnValidation.js';export * from './quotaReset.js';diff --git a/server/services/agentLifecycle.postureGate.test.js b/server/services/agentLifecycle.postureGate.test.jsindex ab0315b309..2836f11862 100644--- a/server/services/agentLifecycle.postureGate.test.js+++ b/server/services/agentLifecycle.postureGate.test.js@@ -52,6 +52,8 @@ vi.mock('../lib/fileUtils.js', async () => {return makePathsProxy(actual, { dataRoot: TEMP_ROOT });});+vi.mock('../lib/auditSourceEvidence.js', () => ({ captureAuditSourceEvidence: vi.fn() }));+vi.mock('./cosRunnerClient.js', async (importOriginal) => ({...(await importOriginal()),spawnAgentViaRunner: vi.fn(),@@ -145,6 +147,7 @@ vi.mock('./modelAbuseGuard.js', () => ({validatePublicReviewModel: vi.fn().mockResolvedValue({ ok: true }),}));+import { captureAuditSourceEvidence } from '../lib/auditSourceEvidence.js';import { spawnAgentForTask } from './agentLifecycle.js';import { prepareAgentWorkspace } from './agentWorkspacePrep.js';import { materializePublicReviewInput, materializePublicReviewPatches, readPublicReviewInputSnapshot } from './modelAbuseGuard.js';@@ -660,3 +663,19 @@ describe('agent launch defaults (#7932)', () => {}});});+++it.each(['captured', 'unavailable'])('registers trusted %s audit launch evidence before execution', async (status) => {+ reachDispatch();+ isTuiProvider.mockReturnValue(false);+ const evidence = { version: 1, status, capturedAt: '2026-01-01T00:00:00Z' };+ captureAuditSourceEvidence.mockResolvedValueOnce(evidence);+ await spawnAgentForTask({ id: `audit-evidence-${status}`, taskType: 'user', metadata: {+ analysisType: 'accessibility', auditSourceEvidence: { revision: 'injected' },+ } });+ expect(captureAuditSourceEvidence).toHaveBeenCalledWith(join(TEMP_ROOT, 'workspace'));+ expect(registerAgent).toHaveBeenCalledWith(expect.any(String), `audit-evidence-${status}`, expect.objectContaining({ auditSourceEvidence: evidence }));+ expect(spawnDirectly).toHaveBeenCalledTimes(1);+ expect(captureAuditSourceEvidence.mock.invocationCallOrder[0]).toBeLessThan(registerAgent.mock.invocationCallOrder[0]);+ expect(registerAgent.mock.invocationCallOrder[0]).toBeLessThan(spawnDirectly.mock.invocationCallOrder[0]);+});diff --git a/server/services/agentSpawnDispatch.js b/server/services/agentSpawnDispatch.jsindex bb1f891491..9c9a072db3 100644--- a/server/services/agentSpawnDispatch.js+++ b/server/services/agentSpawnDispatch.js@@ -6,6 +6,9 @@ import { isPrivateSecurityTask } from '../lib/privateSecurityPolicy.js';import { PROVIDER_CONFIG_BLOCKED_CATEGORY } from '../lib/taskBlockCategories.js';import { ensureDir, PATHS, writeFileGuarded } from '../lib/fileUtils.js';import { repoIssueUrlBase, resolveAppForgeTarget, resolveRepoForgeTarget } from '../lib/workTracker.js';+import { captureAuditSourceEvidence } from '../lib/auditSourceEvidence.js';+import { isAuditTaskType } from '../lib/auditCatalog.js';+import { resolveTaskHookType } from './taskTypeHooks.js';import { capturePrimaryCheckoutState } from '../lib/primaryCheckoutGuard.js';import { buildAgentPrompt, getAppWorkspace, isClaimFlowTask, promptOpensOwnPr } from './agentPromptBuilder.js';import { isOllamaClaudeProvider, isClaudeCommand } from '../lib/providerModels.js';@@ -172,11 +175,12 @@ export async function dispatchAgentRun(context, { spawnViaRunner } = {}) {worktreeInfo,});const claimFlowTask = isClaimFlowTask(task);- const [forgeTarget, primaryCheckoutBaseline] = await Promise.all([+ const [forgeTarget, primaryCheckoutBaseline, auditSourceEvidence] = await Promise.all([resolvedApp? resolveAppForgeTarget(resolvedApp, { repoPath: workspacePath }).then(r => r.target): resolveRepoForgeTarget(workspacePath),sourceWorkspace ? capturePrimaryCheckoutState(sourceWorkspace) : null,+ isAuditTaskType(resolveTaskHookType(task)) ? captureAuditSourceEvidence(workspacePath) : null,]);let systemPromptFile = null;const agentDir = join(AGENTS_DIR, agentId);@@ -205,6 +209,7 @@ export async function dispatchAgentRun(context, { spawnViaRunner } = {}) {sourceWorkspace,repoIssueUrl: repoIssueUrlBase(forgeTarget),primaryCheckoutBaseline,+ auditSourceEvidence,worktreeInfo,explicitWorktree,jiraBranchName,