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
stop telling the LI reasoner not to write a bare `.agent-done` — the warning was the only place it learned that name
[._.]/ Adam Eivyab1b9748135a
diff --git a/server/lib/README.md b/server/lib/README.mdindex ed4ac7671c..9fa92c7c40 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -28,7 +28,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `sharedSchemas.js` | Cross-domain Zod fragments that `validation.js` and the per-domain `*Validation.js` files both need, kept in a leaf module so the domain files never import back through `validation.js` (its hoisted `export * from` lines would TDZ). `grokVideoDurationSchema` (grok clip-length union), `cloudModelIdString(message)` (cloud-CLI model-id charset/bounds), `recordRenderPinFields` (the `imageMode`/`imageModelId` per-record render pin pair), and `isSafeSubdirFilter(v)` (relative path with no wildcard, `..` segment, or leading `/`), and `csvIdsParam({ max, maxIdLength, truncate })` (the `?ids=a,b,c` batch-by-id query param: trims, drops empties, reads all-blank as absent, and either 400s or silently slices an over-cap batch). || `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). || `agentRunEvents.js` | CoS run lifecycle-event envelope (#4540) — pure half of the append-only ledger in `services/agentRunEventLog.js`. `AGENT_RUN_EVENT_KINDS` (closed vocabulary), `agentRunEventSchema` (Zod, `.strict()`), `buildRunEvent()` which redacts then mints a CONTENT-derived `eventId` (sha256 of the canonicalized envelope) so a redelivered lifecycle transition dedupes instead of double-counting, `redactRunEventData()` (drops prompt/description/output/result-class keys to a `{ redacted, chars }` stub, scrubs the home-dir prefix out of every remaining string via `scrubHomePath`, runs `redactOutput`, and caps string/array/key/depth per `RUN_EVENT_LIMITS`), and `projectRunStates()` — the clock-free fold that derives current run status from the ordered stream, so replay-after-restart and read-current-status are one code path. Unknown kinds fold as no-ops so a newer install's ledger replays on an older one. |-| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME`, `doneSentinelName(agentId)` → the per-instance filename `.agent-done-<agentId>` (worktree-less agents share one workspace, so a shared name lets concurrent runs clobber — and finalize on — each other's signal), `doneSentinelPath(workspacePath, agentId)` → the single path every producer and consumer resolves, + 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). |+| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME`, `doneSentinelName(agentId)` → the per-instance filename `.agent-done-<agentId>` (worktree-less agents share one workspace, so a shared name lets concurrent runs clobber — and finalize on — each other's signal), `doneSentinelPath(workspacePath, agentId)` → the single path every producer and consumer resolves, + 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). `PROGRAMMATIC_OUTPUT_COMPLETION_HEADING` names the briefing section that prints this run's absolute sentinel path — a task-type hook renders its prompt before spawn, so it points the agent at that section by name rather than at a filename it cannot know. || `heavyJobClaim.js` | Cross-process, machine-wide accelerator claim: `claimHeavyLocalJob({ kind, id, timeoutMs? })` either acquires an ephemeral `data/` lock or reports its active holder; dead-PID claims are reclaimed, and a spawned child can take over the recorded PID across a server restart. || `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, and the `run once` vocabulary (`quotaBurnJobKey` / `jobIsSpent`, plus the two family predicates `familyIsConfigured` and `familyHasRunnableJobs`). Pure — no storage, no provider I/O. |diff --git a/server/lib/agentSentinel.js b/server/lib/agentSentinel.jsindex 7141bc79bc..6883f24fc8 100644--- a/server/lib/agentSentinel.js+++ b/server/lib/agentSentinel.js@@ -26,6 +26,21 @@ import { safeJSONParse, sanitizeFilename } from './fileUtils.js';export const DONE_SENTINEL_NAME = '.agent-done';+/**+ * Heading of the briefing section that prints this run's absolute sentinel path+ * for a reasoning-only (programmatic-output) task — see+ * `buildProgrammaticOutputCompletionSection` in agentPromptBuilder.+ *+ * A task-type hook renders its prompt BEFORE spawn, so it cannot know the+ * per-instance filename (`.agent-done-<agentId>`) and must point the agent at+ * the briefing instead. That pointer only works if both sides agree on the+ * heading, hence one exported constant rather than the string typed twice.+ * Pointing POSITIVELY at this section is also the whole contract: a prompt that+ * warns against some other filename is the only place the agent would learn+ * that filename exists.+ */+export const PROGRAMMATIC_OUTPUT_COMPLETION_HEADING = 'Completion (Reasoning-Only Task)';+/*** The sentinel filename for one agent instance: `.agent-done-<agentId>`.*diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 3e1f8c70a2..3b2184382b 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -19,7 +19,7 @@ import { readJSONFile, PATHS, tryReadFile, expandHome } from '../lib/fileUtils.jimport { loadSlashdoFile, loadSlashdoLib, writeResolvedSlashdoBody } from '../lib/slashdoLoader.js';import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, LOCAL_LLM_REVIEWERS, MODEL_CAPABLE_CLI_REVIEWERS, describeReviewerCli, isCliReviewer, reviewerCliBinary, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds, resolveReviewerConfig, reviewerEffortArgs, reviewerModelArg, buildReviewerEffortNote, resolveKeyedReviewers, buildReviewWithArgs, buildReviewersCsv } from '../lib/validation.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';-import { doneSentinelName } from '../lib/agentSentinel.js';+import { doneSentinelName, PROGRAMMATIC_OUTPUT_COMPLETION_HEADING } from '../lib/agentSentinel.js';import { canTypeSlashCommands, agentOwnsPrWorkflow, resolveSlashdoInvocation, buildSlashdoSection, oversizedBodyPointer, unreachableReviewerIncludes, SLASHDO_INLINE_BUDGET_CHARS } from '../lib/slashdoInvocation.js';import { shellQuote } from '../lib/shellQuote.js';import { TASK_PROMPT_KEY, TASK_CONTEXT_KEY, taskContextBlock } from '../lib/cosTaskPrompt.js';@@ -1441,7 +1441,8 @@ and do NOT revert its commits unless they are actually wrong.*/export function buildProgrammaticOutputCompletionSection(sentinelPath) {return [- '## Completion (Reasoning-Only Task)',+ // Shared constant: a pre-spawn task-type hook's prompt points here BY NAME.+ `## ${PROGRAMMATIC_OUTPUT_COMPLETION_HEADING}`,'This is a reasoning task, not a code change. The worktree you are in is **discarded on exit** — any commits, pushes, or PRs are thrown away and have no effect. Do NOT run `/do:push`, `/do:pr`, `git commit`, `git push`, or open a pull request.','',`When you have finished reasoning, write your result to \`${sentinelPath}\` in the exact payload format described in your task instructions, then stop. PortOS watches this sentinel and finalizes the run shortly after it appears — do NOT run \`/quit\` and do NOT wait for anything after writing the sentinel.`diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex ec53b45f44..bd51978fb9 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -98,6 +98,8 @@ import { isTruthyMeta } from './agentState.js';import { buildPrompt } from './promptService.js'; // mocked above — inspect call argsimport { loadSlashdoFile, writeResolvedSlashdoBody } from '../lib/slashdoLoader.js'; // mocked above — control the inlined bodyimport { SLASHDO_INLINE_BUDGET_CHARS } from '../lib/slashdoInvocation.js';+// The heading a task-type hook's prompt points at to locate the sentinel path.+import { PROGRAMMATIC_OUTPUT_COMPLETION_HEADING } from '../lib/agentSentinel.js';function makeTask(overrides = {}) {return {@@ -2042,6 +2044,12 @@ describe('discardWorktree (reasoning-only) completion contract', () => {const assertReasoningOnly = (prompt) => {expect(prompt).toMatch(/## Completion \(Reasoning-Only Task\)/);+ // Same heading via the exported constant: a pre-spawn task-type hook+ // (layered-intelligence) can't know the per-instance sentinel filename, so+ // its prompt points the agent at THIS section by name. Re-typing the+ // heading as a literal here would aim that pointer at a section the+ // briefing never emits.+ expect(prompt).toContain(`## ${PROGRAMMATIC_OUTPUT_COMPLETION_HEADING}`);expect(prompt).toMatch(/discarded on exit/);expect(prompt).toMatch(/\.agent-done/);// The whole point: no push/PR/merge instructions anywhere.diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.jsindex 97df614379..426a7be11f 100644--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js@@ -79,6 +79,7 @@ function outcomesTrackerSupported(filer) {}import { resolveAppWorkTracker } from '../../lib/workTracker.js'import { tryReadFile } from '../../lib/fileUtils.js'+import { PROGRAMMATIC_OUTPUT_COMPLETION_HEADING } from '../../lib/agentSentinel.js'import { join } from 'path'/**@@ -236,9 +237,17 @@ async function readIssues({ filer, forgeCli, cwd, jira, config }) {/*** The completion contract appended to the reasoning prompt: the agent must NOT* write code or open a PR (its worktree is discarded anyway) — it reasons and- * writes its structured result to the `.agent-done` sentinel so the+ * writes its structured result to the completion sentinel so the* processTaskOutput hook can file it. `payload` is the exact reasoner-JSON shape* buildPrompt already documents.+ *+ * This hook renders the prompt BEFORE spawn, so it cannot know the sentinel's+ * per-instance filename (`.agent-done-<agentId>`) — it names the briefing+ * section that prints the absolute path instead, via the shared heading+ * constant so the two can't drift. It says only where the path IS: an earlier+ * revision also warned against writing a bare `.agent-done` (a leftover from+ * when this contract named that file itself), which in a prompt that mentions+ * it nowhere else only teaches the agent a wrong filename.*/function buildCompletionContract() {return [@@ -251,10 +260,10 @@ function buildCompletionContract() {'commit, or open a pull request — any changes you make to this worktree are','discarded. Your ONLY output is the JSON described above.','',- 'When you have decided, write your completion sentinel — the exact filename',- 'carries your agent id, so use the path given in the completion section of',- 'your briefing, NOT a bare `.agent-done`. It must contain a single JSON',- 'object with this shape:',+ 'When you have decided, write your result to the completion sentinel. Its',+ `absolute path is printed in the **${PROGRAMMATIC_OUTPUT_COMPLETION_HEADING}**`,+ 'section of this briefing — copy that path exactly; its filename is scoped to',+ 'this run. The file must contain a single JSON object with this shape:','','```json','{ "summary": "<one-line human summary of what you proposed, or that you proposed nothing>",',diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js b/server/services/autonomousJobs/layeredIntelligenceHooks.test.jsindex cd1c61cb7a..32d3253ce6 100644--- a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js@@ -141,6 +141,9 @@ import { getTaskInterval } from '../taskSchedule.js';// mock above) — used by the #4166 end-to-end case so the envelope→reason verdict is// exercised through production validation, not a hand-written stub of it.import { validateReasonerResponse as realValidateReasonerResponse } from '../layeredIntelligence/proposal.js';+// The shared heading both sides of the sentinel pointer use: this hook's prompt+// names the section, agentPromptBuilder emits it.+import { PROGRAMMATIC_OUTPUT_COMPLETION_HEADING } from '../../lib/agentSentinel.js';const APP = { id: 'app-1', name: 'App One', repoPath: '/repo', taskTypeOverrides: {} };@@ -298,12 +301,16 @@ describe('buildTaskInput', () => {const res = await buildTaskInput({ app: APP });expect(res.skip).toBeUndefined();expect(res.prompt).toContain('REASONING PROMPT');- // The completion contract is appended. It must point at the sentinel path- // from the briefing (the filename carries the agent id, which this hook- // cannot know) rather than instructing a bare `.agent-done` no poller- // watches.+ // The completion contract is appended. It must point at the briefing section+ // that prints the sentinel path (the filename carries the agent id, which+ // this hook cannot know) — by the SHARED heading constant, so the pointer+ // can't drift from the section agentPromptBuilder emits.expect(res.prompt).toContain('completion sentinel');- expect(res.prompt).toContain('NOT a bare `.agent-done`');+ expect(res.prompt).toContain(PROGRAMMATIC_OUTPUT_COMPLETION_HEADING);+ // ...and it must NOT name any other filename. A prompt that says 'not a bare+ // `.agent-done`' is the only place the agent would learn that wrong+ // filename exists, so naming it at all — even to forbid it — is the bug.+ expect(res.prompt).not.toContain('.agent-done');expect(res.providerId).toBe('ollama');expect(res.model).toBe('qwen');});