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
fix: rescue a programmatic-I/O payload the agent printed instead of writing to .agent-done (#3640)
[._.]/ Adam Eivye633b69473d1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex a3c832c40e..d59abfdfb7 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -39,6 +39,8 @@- Autonomous CoS runs are no longer marked as having failed their success criteria by a check nothing could ever pass. `evaluateSuccessCriteria` judged a run by grepping for a commit whose subject carried the task id — a marker no prompt, template, or slashdo command ever asked an agent to write, and one the repo's own commit conventions forbid. So every ordinary code-editing run recorded `validationPassed: false`, and because a declared verdict outranks the exit code in task-learning, those fabricated failures filled the learning buckets that drive the Learning card, routing, and duration estimates. The criterion is now the same run-window commit probe the idle reaper already uses (did this run leave a commit stamped inside its own window?), shared as `server/lib/gitCommitProbe.js` by finalize, run completion, runner completion, and orphan recovery. A run with no usable window records the "no criterion declared" sentinel rather than a false miss, the existing exemptions for non-committing task types are unchanged, and a migration purges the buckets the old criterion poisoned.+- A programmatic-I/O run whose model **printed** its JSON answer into the terminal instead of writing `.agent-done` no longer throws the whole run away. For these task types the sentinel JSON *is* the deliverable — a Layered Intelligence proposal becomes a filed tracker issue — so a weaker (typically local) model answering in the TUI rather than through the tool call meant the hook ran with no payload and minutes of reasoning were discarded silently. When no sentinel was written, finalize now scans the ANSI-stripped tail of the run's PTY transcript for the newest complete JSON object and adopts it only if the owning hook's own shape predicate accepts it, logging the rescue so a salvaged run stays distinguishable from a clean one. Scoped to programmatic-I/O types on purpose: everywhere else the sentinel is a completion signal, not a product, and scraping a transcript for one would let an agent that merely discussed finishing be counted as finished.+## Privacy Center- **Your PII vault stays on one machine — permanently, by decision.** The Privacy Center's vault, organization registry, change-of-address inventory and broker opt-out ledger were always machine-local, but that was recorded as a feature not yet built, which left the door open to syncing them to your other PortOS machines later. It is now a documented guarantee: none of it federates, and none of it ever will without a new decision record superseding this one. The reasoning is written up in full — chiefly that PortOS's peer-sync was built for creative work rather than identity data, that the display masks (`••••1234`, `j•••@example.com`) are readable even when the underlying values are encrypted, and that copying one encryption key to several machines would widen the exposure of every one of them. If you want the vault on a second machine, restore a backup and copy the key by hand — a deliberate act, rather than something that happens quietly in the background. Managing PII for other household members is unaffected and remains planned.diff --git a/server/lib/README.md b/server/lib/README.mdindex abc27f6bd3..aab26bcdca 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -25,7 +25,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub|---|---|| `validation.js` | Catch-all Zod schemas (app/process/provider, social accounts, GitHub, backup/sharing, document/legacy-export) + the `validateRequest` middleware + shared helpers (`optionalBooleanMap`, `isSafeRecordId`, `parsePagination`). Re-exports the per-domain validation files below so existing deep imports keep working. || `agentOutputMarkers.js` | Status lines PortOS itself appends to an agent's output buffer: `SENTINEL_COMPLETION_MARKER` (the line `ingestDoneSentinel` writes just before the agent's `.agent-done` summary) plus `isAgentLifecycleLine(line)`/`stripLifecycleLines(lines)`, which match PortOS's telemetry on its actual message shapes rather than on a leading emoji (an agent's own summary may well start a line with `✅`). Pure — shared by the emitter (`services/agentTuiSpawning.js`) and by readers that must show only the agent's own words (notably the generated PR description). |-| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME` + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. |+| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME` + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. `extractSentinelPayloadFromTranscript(transcript, isPayload)` (async) is the third tier for programmatic-I/O types ONLY — scans the ANSI-stripped PTY transcript, newest balanced JSON block first, for a payload the model PRINTED instead of writing, and adopts it only if the owning hook's shape predicate accepts it (#3640). || `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. || `quotaBurnConfig.js` | Quota-burn plan shape: the provider families, the burn-job type alphabet + catalog the config page renders its form from, `QUOTA_BURN_BOUNDS` (the one bounds table the normalizer clamps to, the Zod schemas reject against, and the catalog descriptors publish as min/max), and total normalization (`normalizeQuotaBurnConfig`). Owns the dispatch-cap sentinel too (`QUOTA_BURN_UNLIMITED_DISPATCHES` / `isUnlimitedDispatchCap`) — -1 means the window is not counted, and is the default. Also owns the queued burn task's description shape (`burnTaskDescription` / `quotaBurnFamilyOfDescription`), shared with migration 225. Pure — no storage, no provider I/O. || `quotaBurnPresets.js` | `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)`. |@@ -231,7 +231,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|| `htmlToText.js` | Shared HTML → plain-text converter. `htmlToText(html, { extraEntities?, paragraphBreak?, collapseSpaces? })` — strips script/style/head/noscript blocks, converts `<br>`/block closes to newlines, strips remaining tags, decodes entities via `decodeXmlEntities`, collapses 3+ newlines, trims. Options preserve caller-specific output (Gmail: `paragraphBreak: '\n\n'` + `collapseSpaces`; SongBook import: defaults — space runs preserved for tab alignment). |-| `jsonExtract.js` | Pull JSON blocks out of LLM responses. |+| `jsonExtract.js` | Pull JSON blocks out of LLM responses. `findBalancedBlocks` walks top-level blocks and stops at the first unbalanced one; `findAllBalancedBlocks` is the stack-based variant that scans past stray braces and returns nested blocks in closing order (reverse it for outermost-newest-first). || `taskParser.js` | Parse `TASKS.md` format. || `taskRequeue.js` | The REQUEUE stamp (#3376) — pure metadata helpers for the one BACKWARD lifecycle step (`in_progress → pending`, performed by the orphan sweep and the retry-hold release). `REQUEUED_AT_KEY` / `LAST_SPAWNED_AT_KEY` name the two stamps; `isPostSpawnRequeue(pendingTask, inProgressTask)` answers whether the requeue happened strictly AFTER that spawn, which is how the federated merge tells a real requeue apart from an ordinary edit landing on a peer's stale `pending` copy. Returns false when either stamp is missing, so callers fall back to the lifecycle rank. || `taskRetryHold.js` | The failed-task RETRY HOLD state (#3373) — pure metadata helpers shared by the failure verdict, the post-cleanup release, the spawn guard, and the orphan sweep. `retryHoldMetadata(agentId, now)` arms it (task stays `in_progress`, so no dequeue tier can claim the retry before its resume pointer is resolved); `clearedRetryHoldMetadata()` releases it in the same write that flips the task to `pending`; `isRetryHeld(metadata)` / `isRetryHoldOwner(metadata, agentId)` gate the spawn and the owner-scoped release; `isStaleRetryHold(metadata, now, graceMs)` + `RETRY_HOLD_GRACE_MS` let the orphan sweep finish a transition whose process died. |diff --git a/server/lib/agentSentinel.js b/server/lib/agentSentinel.jsindex a42d40c59b..220a09752f 100644--- a/server/lib/agentSentinel.js+++ b/server/lib/agentSentinel.js@@ -91,3 +91,58 @@ export async function salvageSentinelPayload(contents) {const summary = typeof value.summary === 'string' ? value.summary : '';return { summary, payload: value.payload };}++/**+ * Last-resort rescue for a programmatic-I/O deliverable the agent PRINTED into+ * its terminal instead of writing to `.agent-done` (#3640).+ *+ * For these task types the sentinel JSON *is* the product of the run — a+ * Layered Intelligence proposal becomes a filed tracker issue. A weaker model+ * (typically a local one) commonly answers in the TUI rather than through the+ * tool call, and the run is then discarded with `payload: undefined` even+ * though the reasoning completed. Scanning the transcript recovers it.+ *+ * Deliberately predicate-gated and scoped to programmatic-I/O callers: for+ * every other task type the sentinel is a COMPLETION SIGNAL, not a deliverable,+ * and scraping a transcript for one would let an agent that merely *discussed*+ * finishing be treated as finished. `isPayload` is the owning hook's own shape+ * check (see taskTypeHooks' `getTaskOutputPayloadPredicate`), so a transcript+ * that only contains chatter, a schema example, or partial JSON yields nothing+ * rather than a garbage payload.+ *+ * Blocks are walked in REVERSE closing order — the model's final answer wins+ * over an earlier prompt echo of the same schema, and an enclosing object wins+ * over its own nested children. Strict `safeJSONParse` per block (no lenient+ * repair): a transcript is not a file the agent committed to, so "almost JSON"+ * there stays a miss.+ *+ * Async + LAZY imports for the same reason as `salvageSentinelPayload` — the+ * barrel re-export of this module must not statically pull jsonExtract's+ * transitive chain into every lib consumer / mocked suite.+ *+ * @param {string|null|undefined} transcript — ANSI-bearing raw PTY text+ * @param {(payload:unknown)=>boolean} isPayload — the hook's shape predicate+ * @returns {Promise<{ summary: string, payload: unknown }>}+ */+export async function extractSentinelPayloadFromTranscript(transcript, isPayload) {+ const none = { summary: '', payload: null };+ if (typeof transcript !== 'string' || !transcript.includes('{')) return none;+ if (typeof isPayload !== 'function') return none;++ const { stripAnsi } = await import('./ansiStrip.js');+ const { findAllBalancedBlocks } = await import('./jsonExtract.js');+ const blocks = findAllBalancedBlocks(stripAnsi(transcript));++ for (let i = blocks.length - 1; i >= 0; i -= 1) {+ const parsed = safeJSONParse(blocks[i], null, { allowArray: false });+ if (!parsed) continue;+ // Two shapes reach a transcript: the documented `{ summary, payload }`+ // envelope the agent should have written to the sentinel, and the BARE+ // payload object — what a model answering in the terminal actually prints.+ const candidate = 'payload' in parsed ? parsed.payload : parsed;+ if (!isPayload(candidate)) continue;+ const summary = typeof parsed.summary === 'string' ? parsed.summary : '';+ return { summary, payload: candidate };+ }+ return none;+}diff --git a/server/lib/agentSentinel.test.js b/server/lib/agentSentinel.test.jsindex 37db3ceb0b..f305ae387f 100644--- a/server/lib/agentSentinel.test.js+++ b/server/lib/agentSentinel.test.js@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest';-import { DONE_SENTINEL_NAME, parseSentinelPayload, salvageSentinelPayload } from './agentSentinel.js';+import { DONE_SENTINEL_NAME, extractSentinelPayloadFromTranscript, parseSentinelPayload, salvageSentinelPayload } from './agentSentinel.js';describe('agentSentinel', () => {it('exposes the sentinel filename', () => {@@ -112,4 +112,55 @@ describe('agentSentinel', () => {expect(await salvageSentinelPayload(fenced)).toEqual({ summary: 'nothing to file', payload: null });});});+describe('extractSentinelPayloadFromTranscript', () => {+ const isReasonerPayload = (p) => !!p && typeof p === 'object' && !Array.isArray(p)+ && ['analysis', 'proposal', 'pause'].some(k => Object.hasOwn(p, k));+ const ANSWER = '{"analysis":"quiet cycle","proposal":null,"pause":null}';++ it('recovers a bare payload object the model printed, ANSI and all', async () => {+ const transcript = `\u001b[32m\u25cf\u001b[0m ${ANSWER}\u001b[0m\r\n`;+ const { payload } = await extractSentinelPayloadFromTranscript(transcript, isReasonerPayload);+ expect(payload).toEqual({ analysis: 'quiet cycle', proposal: null, pause: null });+ });++ it('unwraps the documented { summary, payload } envelope when that is what was printed', async () => {+ const transcript = 'done: {"summary":"nothing to file","payload":{"proposal":null}}';+ expect(await extractSentinelPayloadFromTranscript(transcript, isReasonerPayload))+ .toEqual({ summary: 'nothing to file', payload: { proposal: null } });+ });++ it('takes the LAST matching object, so the final answer beats an earlier prompt echo', async () => {+ const transcript = `schema: {"analysis":"<example>","proposal":null}\nanswer: ${ANSWER}`;+ const { payload } = await extractSentinelPayloadFromTranscript(transcript, isReasonerPayload);+ expect(payload.analysis).toBe('quiet cycle');+ });++ it('prefers the enclosing object over its own nested children', async () => {+ const transcript = '{"analysis":"a","proposal":{"scope":"self-improve","title":"t"}}';+ const { payload } = await extractSentinelPayloadFromTranscript(transcript, isReasonerPayload);+ expect(payload.proposal.title).toBe('t');+ });++ it('survives a truncated repaint that leaves an unmatched brace before the answer', async () => {+ const { payload } = await extractSentinelPayloadFromTranscript(`{ half a redraw ${ANSWER}`, isReasonerPayload);+ expect(payload).not.toBeNull();+ });++ it('yields no payload for malformed or partial JSON', async () => {+ expect(await extractSentinelPayloadFromTranscript('{"analysis":"cut off mid-thoug', isReasonerPayload))+ .toEqual({ summary: '', payload: null });+ expect(await extractSentinelPayloadFromTranscript('{analysis: not json}', isReasonerPayload))+ .toEqual({ summary: '', payload: null });+ });++ it('yields no payload for JSON that is not the hook deliverable', async () => {+ expect((await extractSentinelPayloadFromTranscript('{"tokens":1200}', isReasonerPayload)).payload).toBeNull();+ });++ it('yields no payload without a predicate, or for empty/brace-free text', async () => {+ expect((await extractSentinelPayloadFromTranscript(ANSWER, null)).payload).toBeNull();+ expect((await extractSentinelPayloadFromTranscript('no json here', isReasonerPayload)).payload).toBeNull();+ expect((await extractSentinelPayloadFromTranscript(null, isReasonerPayload)).payload).toBeNull();+ });+ });});diff --git a/server/lib/jsonExtract.js b/server/lib/jsonExtract.jsindex ea27977583..fa06f340c6 100644--- a/server/lib/jsonExtract.js+++ b/server/lib/jsonExtract.js@@ -74,6 +74,52 @@ export function findBalancedBlocks(s, { startChar = '{', endChar = '}' } = {}) {return blocks;}+/**+ * Every brace-balanced block in the string — nested ones included — in the+ * order they CLOSE. String-aware like `findBalancedBlocks`, but built on a+ * stack instead of a restart-from-scratch scan, which buys two properties the+ * transcript rescue in `agentSentinel.extractSentinelPayloadFromTranscript`+ * needs and `findBalancedBlocks` deliberately does not provide:+ *+ * 1. An unmatched opening brace does NOT end the walk. `findBalancedBlocks`+ * bails at the first unbalanced segment (see its note); a repaint-heavy+ * PTY transcript is full of stray braces from truncated redraws, and+ * bailing there would discard the complete JSON object the model printed+ * at the very end — the whole point of the scan.+ * 2. Closing order means an enclosing object is emitted AFTER the objects it+ * contains, so a caller walking the result in REVERSE sees the outermost+ * object of the last-printed block before any of its children.+ *+ * Still one linear pass (an unmatched `}` with an empty stack is dropped), so+ * scanning a large tail stays cheap.+ *+ * @param {string} s — input text+ * @param {object} [options]+ * @param {string} [options.startChar='{'] — opening delimiter+ * @param {string} [options.endChar='}'] — matching closing delimiter+ * @returns {string[]} — every balanced block, in the order they close+ */+export function findAllBalancedBlocks(s, { startChar = '{', endChar = '}' } = {}) {+ if (typeof s !== 'string' || !s) return [];+ const blocks = [];+ const opens = [];+ let inString = false;+ let escaped = false;+ for (let i = 0; i < s.length; i += 1) {+ const ch = s[i];+ if (inString) {+ if (escaped) escaped = false;+ else if (ch === '\\') escaped = true;+ else if (ch === '"') inString = false;+ continue;+ }+ if (ch === '"') { inString = true; continue; }+ if (ch === startChar) opens.push(i);+ else if (ch === endChar && opens.length) blocks.push(s.slice(opens.pop(), i + 1));+ }+ return blocks;+}+/*** Apply a regex `replace()` to the input ONLY OUTSIDE quoted JSON* string regions. Walks the input with the same string/escape awarenessdiff --git a/server/lib/jsonExtract.test.js b/server/lib/jsonExtract.test.jsindex 699e9b958f..c34f142aa2 100644--- a/server/lib/jsonExtract.test.js+++ b/server/lib/jsonExtract.test.js@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest';-import { findBalancedBlocks, tryParseWithRepair, extractJson } from './jsonExtract.js';+import { findAllBalancedBlocks, findBalancedBlocks, tryParseWithRepair, extractJson } from './jsonExtract.js';describe('jsonExtract.findBalancedBlocks', () => {it('returns the single top-level brace-balanced block', () => {@@ -252,3 +252,29 @@ describe('jsonExtract.extractJson', () => {expect(extractJson(raw).value).toEqual({ a: 'close-brace-} inside' });});});++describe('findAllBalancedBlocks', () => {+ it('returns nested blocks in closing order, so a reverse walk sees the outer object first', () => {+ const blocks = findAllBalancedBlocks('{"a":{"b":1}}');+ expect(blocks).toEqual(['{"b":1}', '{"a":{"b":1}}']);+ });++ it('keeps scanning past an unmatched opening brace (findBalancedBlocks bails there)', () => {+ const noisy = 'repaint fragment { then the answer {"a":1}';+ expect(findBalancedBlocks(noisy)).toEqual([]);+ expect(findAllBalancedBlocks(noisy)).toEqual(['{"a":1}']);+ });++ it('ignores an unmatched closing brace', () => {+ expect(findAllBalancedBlocks('} {"a":1} }')).toEqual(['{"a":1}']);+ });++ it('is string-aware, so braces inside string values do not shift the depth', () => {+ expect(findAllBalancedBlocks('{"a":"{ not a brace \\" }"}')).toEqual(['{"a":"{ not a brace \\" }"}']);+ });++ it('returns [] for non-string or empty input', () => {+ expect(findAllBalancedBlocks(null)).toEqual([]);+ expect(findAllBalancedBlocks('')).toEqual([]);+ });+});diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex 0abb0edc57..6b2e0885dc 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -34,7 +34,7 @@ import { completeExecution, errorExecution } from './toolStateMachine.js';import { resolveFailedTaskUpdate, resolveTypeFailureSignal } from './agentErrorAnalysis.js';import { completeAgentRun } from './agentRunTracking.js';import { committedDuringRun } from '../lib/gitCommitProbe.js';-import { canRunTaskOutputHookWithoutPayload, isProgrammaticIoTaskType, resolveTaskHookType, declaresNoCommitCriterion } from './taskTypeHooks.js';+import { canRunTaskOutputHookWithoutPayload, getTaskOutputPayloadPredicate, isProgrammaticIoTaskType, resolveTaskHookType, declaresNoCommitCriterion } from './taskTypeHooks.js';import { processAgentCompletion } from './agentCompletion.js';import { extractSimplifySummaries } from './agentSummaryExtraction.js';@@ -726,6 +726,37 @@ export async function finalizeAgent({return { success, prVerdict };}+// Tail of the agent's raw PTY spool scanned by the transcript rescue. The+// deliverable, when printed, is the LAST thing the model emits, and a reasoner+// envelope is a few KB at most — but a repaint-heavy TUI spends most of its+// bytes on escape sequences, so the window is generous relative to the payload.+// Bounded for the same reason RAW_TAIL_ANALYSIS_BYTES is: raw.txt has no upper+// size limit on a long run.+const TRANSCRIPT_RESCUE_TAIL_BYTES = 256 * 1024;++/**+ * Recover a programmatic-I/O deliverable the agent PRINTED to its terminal+ * instead of writing to `.agent-done` (#3640). Returns the payload, or null+ * when the type opts out (no shape predicate), the spool is unreadable, or+ * nothing in the transcript matches the hook's expected shape — in which case+ * the caller behaves exactly as it did before this existed.+ *+ * Gated to programmatic-I/O types on purpose: everywhere else the sentinel is a+ * completion SIGNAL rather than the product, and scraping a transcript for one+ * would let an agent that merely discussed finishing be treated as finished.+ */+async function rescueTranscriptPayload({ agentId, taskType }) {+ if (!agentId || !isProgrammaticIoTaskType(taskType)) return null;+ const isPayload = await getTaskOutputPayloadPredicate(taskType);+ if (!isPayload) return null;+ const { PATHS, readFileTail } = await import('../lib/fileUtils.js');+ const transcript = await readFileTail(join(PATHS.cosAgents, agentId, 'raw.txt'), TRANSCRIPT_RESCUE_TAIL_BYTES);+ if (!transcript) return null;+ const { extractSentinelPayloadFromTranscript } = await import('../lib/agentSentinel.js');+ const { payload } = await extractSentinelPayloadFromTranscript(transcript, isPayload);+ return payload ?? null;+}+/*** Read the finished agent's `.agent-done` payload and run the task type's* `processTaskOutput` hook, if it registers one. No-op for the vast majority of@@ -760,6 +791,18 @@ async function dispatchTaskOutputHook({ agentId, task, success, workspacePath, remitLog('info', `Recovered structured .agent-done payload for ${agentId} (${taskType}) via lenient JSON extraction`, { agentId });}}+ // No sentinel at all: the model may have PRINTED its deliverable into the+ // TUI instead of writing the file (#3640). `contents == null` — not just a+ // null payload — so a sentinel the agent DID write, whose content simply+ // isn't a payload, keeps its own (correct) missing-output verdict instead of+ // being overridden by something older in the transcript.+ if (payload == null && contents == null) {+ const rescued = await rescueTranscriptPayload({ agentId, taskType });+ if (rescued != null) {+ payload = rescued;+ emitLog('info', `Recovered printed payload for ${agentId} (${taskType}) from the transcript — no .agent-done was written`, { agentId });+ }+ }}if (recovery && payload == null && !canRunTaskOutputHookWithoutPayload(taskType)) {return { ran: false, recoveryPayloadUnavailable: true };diff --git a/server/services/agentFinalization.outputHooks.test.js b/server/services/agentFinalization.outputHooks.test.jsindex 33ab93568e..e7f4eb461d 100644--- a/server/services/agentFinalization.outputHooks.test.js+++ b/server/services/agentFinalization.outputHooks.test.js@@ -12,6 +12,7 @@ vi.mock('./cosAgentLifecycle.js', () => ({vi.mock('./taskTypeHooks.js', () => ({canRunTaskOutputHookWithoutPayload: vi.fn(() => true),getTaskOutputHook: vi.fn(),+ getTaskOutputPayloadPredicate: vi.fn(async () => null),declaresNoCommitCriterion: vi.fn(() => false),isProgrammaticIoTaskType: vi.fn(() => true),resolveTaskHookType: vi.fn(task => task?.metadata?.analysisType || null),diff --git a/server/services/agentFinalization.prVerification.test.js b/server/services/agentFinalization.prVerification.test.jsindex 25ecd56665..bdc65268ac 100644--- a/server/services/agentFinalization.prVerification.test.js+++ b/server/services/agentFinalization.prVerification.test.js@@ -76,6 +76,7 @@ vi.mock('./taskTypeHooks.js', () => ({resolveTaskHookType: vi.fn(() => null),declaresNoCommitCriterion: vi.fn(() => false),getTaskOutputHook: vi.fn(async () => null),+ getTaskOutputPayloadPredicate: vi.fn(async () => null),}));vi.mock('./agentCompletion.js', () => ({ processAgentCompletion: vi.fn(async () => null) }));diff --git a/server/services/agentFinalization.providerBench.test.js b/server/services/agentFinalization.providerBench.test.jsindex eb89580be9..073835d8c3 100644--- a/server/services/agentFinalization.providerBench.test.js+++ b/server/services/agentFinalization.providerBench.test.js@@ -70,6 +70,7 @@ vi.mock('./taskTypeHooks.js', () => ({resolveTaskHookType: vi.fn(() => null),declaresNoCommitCriterion: vi.fn(() => false),getTaskOutputHook: vi.fn(async () => null),+ getTaskOutputPayloadPredicate: vi.fn(async () => null),}));vi.mock('./agentCompletion.js', () => ({ processAgentCompletion: vi.fn(async () => null) }));vi.mock('./agentSummaryExtraction.js', () => ({ extractSimplifySummaries: vi.fn(() => null) }));diff --git a/server/services/agentFinalization.transcriptRescue.test.js b/server/services/agentFinalization.transcriptRescue.test.jsnew file mode 100644index 0000000000..66280e6477--- /dev/null+++ b/server/services/agentFinalization.transcriptRescue.test.js@@ -0,0 +1,184 @@+/**+ * Transcript rescue for a programmatic-I/O payload the model PRINTED into its+ * TUI instead of writing to `.agent-done` (#3640).+ *+ * Drives the real `dispatchTaskOutputHookOnce` against an on-disk agent dir+ * (raw.txt spool) and an on-disk workspace, so the "sentinel absent" branch and+ * the tail read are exercised end to end rather than stubbed.+ */+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdirSync, rmSync, writeFileSync } from 'fs';+import { join } from 'path';+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';++// Allocated inside `vi.hoisted` so the binding exists BEFORE the module graph is+// imported: agentFinalization pulls modules (cos.js → appActivity.js, taskLearning)+// that read `PATHS` at import time, which runs the mock factory below while a+// plain module-level `const` would still be in its temporal dead zone.+const { TEMP_ROOT } = await vi.hoisted(async () => {+ const { mkdtempSync } = await import('fs');+ const { tmpdir } = await import('os');+ const { join: joinPath } = await import('path');+ return { TEMP_ROOT: mkdtempSync(joinPath(tmpdir(), 'portos-transcript-rescue-')) };+});++vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return makePathsProxy(actual, {+ dataRoot: TEMP_ROOT,+ extraOverrides: root => ({ cosAgents: join(root, 'cos/agents') }),+ });+});++vi.mock('./cosAgentLifecycle.js', () => ({+ getAgent: vi.fn(async () => ({ id: 'agent-example', status: 'running', metadata: {} })),+ updateAgent: vi.fn(async () => ({})),+ completeAgent: vi.fn(async () => ({})),+}));++vi.mock('./taskTypeHooks.js', () => ({+ canRunTaskOutputHookWithoutPayload: vi.fn(() => false),+ declaresNoCommitCriterion: vi.fn(() => false),+ isProgrammaticIoTaskType: vi.fn(() => true),+ resolveTaskHookType: vi.fn(task => task?.metadata?.analysisType || null),+ getTaskOutputHook: vi.fn(),+ getTaskOutputPayloadPredicate: vi.fn(),+}));++import {+ getTaskOutputHook,+ getTaskOutputPayloadPredicate,+ isProgrammaticIoTaskType,+} from './taskTypeHooks.js';+import { dispatchTaskOutputHookOnce } from './agentFinalization.js';++// Mirrors layered-intelligence's exported `isTaskOutputPayload` predicate. Kept+// local rather than imported: that hook module pulls the whole apps/taskLearning+// chain, which reads PATHS at import time — before this file's temp root exists.+// `layeredIntelligenceHooks.test.js` asserts the real predicate matches this shape.+const isReasonerPayload = (p) => !!p && typeof p === 'object' && !Array.isArray(p)+ && ['analysis', 'proposal', 'pause'].some(k => Object.hasOwn(p, k));++const TASK = {+ id: 'sys-example',+ taskType: 'internal',+ metadata: { analysisType: 'layered-intelligence', app: 'app-example' },+};++// A repaint-heavy TUI transcript: ANSI colour/cursor sequences, a truncated+// redraw leaving a stray `{`, then whatever the model printed to the terminal+// instead of writing it to `.agent-done`. `echoSchema` prepends the prompt's own+// schema example — a well-formed envelope that appears BEFORE the real answer.+const REASONER_ANSWER = '{"analysis": "Nothing worth proposing this cycle.", "proposal": null, "pause": null}';+const printedTranscript = (answer = REASONER_ANSWER, { echoSchema = false } = {}) => [+ '\x1b[2J\x1b[H layered-intelligence run starting\u2026\r\n',+ echoSchema+ ? '\x1b[1mRespond with\x1b[0m {"analysis": "<schema example>", "proposal": null, "pause": null}\r\n'+ : '',+ '\x1b[38;5;240m\u2502\x1b[0m thinking\u2026 { truncated repaint\r\n',+ `\x1b[32m\u25cf\x1b[0m ${answer}\r\n`,+ '\x1b[2mrun complete\x1b[0m\r\n',+].join('');++let agentId = 0;+const setupRun = ({ transcript, sentinel = null }) => {+ agentId += 1;+ const id = `agent-${agentId}`;+ const agentDir = join(TEMP_ROOT, 'cos/agents', id);+ const workspace = join(TEMP_ROOT, 'workspaces', id);+ mkdirSync(agentDir, { recursive: true });+ mkdirSync(workspace, { recursive: true });+ if (transcript !== null) writeFileSync(join(agentDir, 'raw.txt'), transcript);+ if (sentinel !== null) writeFileSync(join(workspace, '.agent-done'), sentinel);+ return { agentId: id, workspacePath: workspace };+};++const runDispatch = async (setup) => {+ const hook = vi.fn().mockResolvedValue({ action: 'no-op' });+ getTaskOutputHook.mockResolvedValue(hook);+ const { agentId: id, workspacePath } = setupRun(setup);+ await dispatchTaskOutputHookOnce({ agentId: id, task: TASK, success: true, workspacePath });+ return hook;+};++describe('printed-payload transcript rescue (#3640)', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ isProgrammaticIoTaskType.mockReturnValue(true);+ getTaskOutputPayloadPredicate.mockResolvedValue(isReasonerPayload);+ });++ afterAll(() => rmSync(TEMP_ROOT, { recursive: true, force: true }));++ it('hands the hook the payload the agent printed when no sentinel was written', async () => {+ const hook = await runDispatch({ transcript: printedTranscript() });++ expect(hook).toHaveBeenCalledWith(expect.objectContaining({+ success: true,+ payload: { analysis: 'Nothing worth proposing this cycle.', proposal: null, pause: null },+ }));+ });++ it('prefers the model final answer over an earlier prompt echo of the schema', async () => {+ const answer = '{"analysis": "Real answer", "proposal": {"scope": "self-improve", "title": "Do the thing"}}';+ const hook = await runDispatch({ transcript: printedTranscript(answer, { echoSchema: true }) });++ const { payload } = hook.mock.calls[0][0];+ expect(payload.analysis).toBe('Real answer');+ expect(payload.proposal.title).toBe('Do the thing');+ });++ it('does not rescue for a non-programmatic-I/O task with the same transcript', async () => {+ isProgrammaticIoTaskType.mockReturnValue(false);++ const hook = await runDispatch({ transcript: printedTranscript() });++ expect(hook).toHaveBeenCalledWith(expect.objectContaining({ payload: null }));+ });++ it('yields no payload for malformed or truncated JSON in the transcript', async () => {+ const hook = await runDispatch({+ transcript: printedTranscript('{"analysis": "cut off mid-thoug'),+ });++ expect(hook).toHaveBeenCalledWith(expect.objectContaining({ payload: null }));+ });++ it('yields no payload for transcript JSON that is not the hook deliverable', async () => {+ const hook = await runDispatch({ transcript: printedTranscript('{"tokens": 1200, "cost": 0.03}') });++ expect(hook).toHaveBeenCalledWith(expect.objectContaining({ payload: null }));+ });++ it('leaves a written sentinel authoritative instead of scraping an older transcript', async () => {+ const hook = await runDispatch({+ transcript: printedTranscript(),+ sentinel: 'plain markdown summary, no structured payload',+ });++ expect(hook).toHaveBeenCalledWith(expect.objectContaining({ payload: null }));+ });++ it('accepts the documented envelope form when that is what was printed', async () => {+ const envelope = '{"summary": "no proposal", "payload": {"analysis": "quiet", "proposal": null}}';+ const hook = await runDispatch({ transcript: printedTranscript(envelope) });++ expect(hook).toHaveBeenCalledWith(expect.objectContaining({+ payload: { analysis: 'quiet', proposal: null },+ }));+ });++ it('skips the rescue when the task type declares no payload predicate', async () => {+ getTaskOutputPayloadPredicate.mockResolvedValue(null);++ const hook = await runDispatch({ transcript: printedTranscript() });++ expect(hook).toHaveBeenCalledWith(expect.objectContaining({ payload: null }));+ });++ it('tolerates a missing raw.txt spool', async () => {+ const hook = await runDispatch({ transcript: null });++ expect(hook).toHaveBeenCalledWith(expect.objectContaining({ payload: null }));+ });+});diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.jsindex 2345c9352e..4b3ca24145 100644--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js@@ -527,6 +527,23 @@ async function recordRun(app, outcome = {}) {// isn't an answer at all — see the envelope resolution in processTaskOutput.const REASONER_ENVELOPE_KEYS = ['analysis', 'proposal', 'pause']+/**+ * Is this a reasoner envelope at all? A bare string/number/array, or an object+ * carrying none of the documented keys ({}, {"foo":1}), is not an answer.+ * `Object.hasOwn` — an inherited key must not qualify a junk object as one.+ *+ * Exported as this hook's `isTaskOutputPayload` (see taskTypeHooks' module+ * header): the finalize-time transcript rescue (#3640) asks the OWNING hook+ * what its deliverable looks like before adopting JSON it scraped out of a+ * terminal, and that must be the same question processTaskOutput asks below —+ * a looser rescue check would hand the hook a shape it would then reject as+ * `unparseable-response`.+ */+export function isTaskOutputPayload(payload) {+ return !!payload && typeof payload === 'object' && !Array.isArray(payload)+ && REASONER_ENVELOPE_KEYS.some(k => Object.hasOwn(payload, k))+}+async function defaultEnqueueHandoff(taskData) {const { addTask } = await import('../cos.js')return addTask(taskData, 'internal')@@ -569,10 +586,7 @@ export async function processTaskOutput({ appId, success, payload, agentId } = {// former was recorded as a successful run. Reachable both ways: the sentinel// envelope only requires `payload` to be an object, and salvageSentinelPayload's// lenient extractor can surface a non-envelope object out of prose.- // `Object.hasOwn` — an inherited key must not qualify a junk object as an answer.- const isEnvelope = !!payload && typeof payload === 'object' && !Array.isArray(payload)- && REASONER_ENVELOPE_KEYS.some(k => Object.hasOwn(payload, k))- const envelope = isEnvelope ? payload : null+ const envelope = isTaskOutputPayload(payload) ? payload : nullconst { proposal, pause } = validateReasonerResponse(envelope)// A reasoner that SUPPLIED a non-null proposal which then failed validationdiff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js b/server/services/autonomousJobs/layeredIntelligenceHooks.test.jsindex f0e490a7fe..5b4594c2de 100644--- a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js@@ -125,7 +125,7 @@ vi.mock('../layeredIntelligenceOutcomes.js', () => ({listOutcomes: vi.fn().mockResolvedValue([])}));-import { buildTaskInput, processTaskOutput } from './layeredIntelligenceHooks.js';+import { buildTaskInput, isTaskOutputPayload, processTaskOutput } from './layeredIntelligenceHooks.js';import * as li from '../layeredIntelligence.js';import { recordFiledProposal, listOutcomesResult, reconcileOutcomes, listOutcomes } from '../layeredIntelligenceOutcomes.js';import * as apps from '../apps.js';@@ -785,3 +785,24 @@ describe('processTaskOutput', () => {expect(out).toEqual({ action: 'no-op', reason: 'app-not-found' });});});++describe('isTaskOutputPayload (#3640)', () => {+ // The transcript rescue in agentFinalization adopts printed JSON only when this+ // says it is a reasoner envelope, and processTaskOutput then judges it by the+ // SAME predicate — a looser rescue would hand the hook a shape it rejects as+ // `unparseable-response`.+ it('accepts an object carrying any documented reasoner key', () => {+ expect(isTaskOutputPayload({ analysis: 'a' })).toBe(true);+ expect(isTaskOutputPayload({ proposal: null })).toBe(true);+ expect(isTaskOutputPayload({ pause: { until: 'x' } })).toBe(true);+ });++ it('rejects a non-envelope: junk objects, arrays, scalars, and inherited keys', () => {+ expect(isTaskOutputPayload({})).toBe(false);+ expect(isTaskOutputPayload({ tokens: 1200 })).toBe(false);+ expect(isTaskOutputPayload([{ analysis: 'a' }])).toBe(false);+ expect(isTaskOutputPayload('analysis')).toBe(false);+ expect(isTaskOutputPayload(null)).toBe(false);+ expect(isTaskOutputPayload(Object.create({ analysis: 'inherited' }))).toBe(false);+ });+});diff --git a/server/services/taskTypeHooks.js b/server/services/taskTypeHooks.jsindex 0c7d45f1d3..8b6e432e11 100644--- a/server/services/taskTypeHooks.js+++ b/server/services/taskTypeHooks.js@@ -30,6 +30,10 @@* the hook does deterministic work on it (e.g. filing a tracker issue) and* returns an outcome. `deps` is an injectable seam for tests.*+ * - `isTaskOutputPayload(payload)` — pure shape check for that hook's own+ * deliverable. Optional, but a type that omits it forfeits the transcript+ * rescue for a payload the model printed instead of writing (#3640).+ ** The agent itself runs through the NORMAL path (visible in the CoS queue +* Active Agents, TUI-capable), so a programmatic-I/O task differs from any other* scheduled task only in these two slots. See@@ -249,3 +253,18 @@ export async function getTaskOutputHook(taskType) {const mod = await loadHookModule(taskType);return mod && typeof mod.processTaskOutput === 'function' ? mod.processTaskOutput : null;}++/**+ * Resolve the hook's own payload SHAPE predicate, or null if it declares none.+ * `isTaskOutputPayload(payload)` → boolean.+ *+ * Only the hook knows what its deliverable looks like, so the transcript rescue+ * in `agentFinalization` (#3640) — which recovers a payload the model printed to+ * the terminal instead of writing to `.agent-done` — asks the hook rather than+ * guessing. A type that exports no predicate simply gets no rescue: without a+ * shape to check against, any JSON-ish blob in the transcript would qualify.+ */+export async function getTaskOutputPayloadPredicate(taskType) {+ const mod = await loadHookModule(taskType);+ return mod && typeof mod.isTaskOutputPayload === 'function' ? mod.isTaskOutputPayload : null;+}