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: expose parsed JSX disclosure predicates to the reviewer
[._.]/ Adam Eivye3fe53e60cab
diff --git a/server/lib/README.md b/server/lib/README.mdindex 69bd42c61d..bb94869b25 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -573,7 +573,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `avatarStyles.js` | The CoS avatar-style vocabulary (#6253) — `AVATAR_STYLES` (`{id, label, webgl}`), `AVATAR_STYLE_IDS` (the `avatarStyle` zod enum in `cosStatusRoutes.js`), `AVATAR_STYLE_LABELS`, and `WEBGL_AVATAR_STYLE_IDS` (the three.js-stage set). `client/src/lib/avatarStyles.js` re-exports it for the picker and the lazy-load map. || `migrationMarker.js` | Shared marker-file helpers for one-time migration/repair/reconcile scripts — `markerExists(filename)` (boolean gate), `readMarker(filename)` (parsed payload or null), `writeMarker(filename, payload)` (atomic write). All anchor `filename` under `PATHS.data` and use `tryReadFile`/`atomicWrite` so a crash can't leave a truncated marker. || `goalFeatureMap.js` | Deterministic goal `category` → PortOS feature-area map (deep-links sourced from `NAV_COMMANDS`). `getGoalFeatureAreas(goal)` honors the per-goal `featureAreas` override, else the category default. Mirrored byte-for-byte to `client/src/lib/`. |-| `goalFidelity.js` | Goal-fidelity review contract (#5994) — the value half of "does this diff deliver what was asked?", the question the quality-review chain structurally cannot answer because it never sees the request. `GOAL_FIDELITY_VERDICTS` (`ship` / `fix-first` / `rethink`, only `rethink` gating a run via `goalFidelityHoldsRun`), `taskObjective(task)` (the trusted operator-authored objective — the TASK's description + prompt block, never the agent's transcript, since a reviewer handed the transcript inherits the assumptions that produced the drift), `resolveGoalFidelityConfig(codeReview, chain)` (enabled/backend/model/effort, restricted to the local-LLM reviewers PortOS can call server-side and falling back to the quality chain's own local reviewer + its `<backend>Model`/`Effort` scalars), `normalizeGoalFidelityVerdict(parsed)` (`null` = nothing judged the run, never collapsed into a `ship` pass or a `rethink` hold) and `formatGoalFidelitySummary(review)`. `mergeOutcomeObjective(task)` / `mergeOutcomeReview({ number, prState })` / `GOAL_FIDELITY_SOURCE_FORGE` are the second answer shape: a review-loop follow-up is asked to LAND a change request, which no diff evidences, so its verdict is established from forge state (`MERGED` ⇒ `ship`, everything else ⇒ nothing). `isDependencyAuditSummaryDiff` recognizes only edits to the two existing `docs/DEPS.md` audit-summary fields; finalization declines diff-only review for that dependency-audit shape only after independently reading empty alert and PR inventories (no invented `ship` verdict). `MAX_OBJECTIVE_CHARS` / `MAX_FIDELITY_DIFF_CHARS` bound what crosses into a fixed-window local model. Pure. `retainedProductionUses(objective, diff)` supplies exact-token surviving production witnesses for the bounded contradiction check. `SUMMARY_DISCLOSURE_REPAIR_CUE` frames only the bare premature-summary report, with its description and cap preserved. `productionAfterChangeHunks` preserves separate file/hunk provenance while excluding deleted lines and tests for focused production review. |+| `goalFidelity.js` | Goal-fidelity review contract (#5994) — the value half of "does this diff deliver what was asked?", the question the quality-review chain structurally cannot answer because it never sees the request. `GOAL_FIDELITY_VERDICTS` (`ship` / `fix-first` / `rethink`, only `rethink` gating a run via `goalFidelityHoldsRun`), `taskObjective(task)` (the trusted operator-authored objective — the TASK's description + prompt block, never the agent's transcript, since a reviewer handed the transcript inherits the assumptions that produced the drift), `resolveGoalFidelityConfig(codeReview, chain)` (enabled/backend/model/effort, restricted to the local-LLM reviewers PortOS can call server-side and falling back to the quality chain's own local reviewer + its `<backend>Model`/`Effort` scalars), `normalizeGoalFidelityVerdict(parsed)` (`null` = nothing judged the run, never collapsed into a `ship` pass or a `rethink` hold) and `formatGoalFidelitySummary(review)`. `mergeOutcomeObjective(task)` / `mergeOutcomeReview({ number, prState })` / `GOAL_FIDELITY_SOURCE_FORGE` are the second answer shape: a review-loop follow-up is asked to LAND a change request, which no diff evidences, so its verdict is established from forge state (`MERGED` ⇒ `ship`, everything else ⇒ nothing). `isDependencyAuditSummaryDiff` recognizes only edits to the two existing `docs/DEPS.md` audit-summary fields; finalization declines diff-only review for that dependency-audit shape only after independently reading empty alert and PR inventories (no invented `ship` verdict). `MAX_OBJECTIVE_CHARS` / `MAX_FIDELITY_DIFF_CHARS` bound what crosses into a fixed-window local model. Pure. `retainedProductionUses(objective, diff)` supplies exact-token surviving production witnesses for the bounded contradiction check. `SUMMARY_DISCLOSURE_REPAIR_CUE` frames only the bare premature-summary report, with its description and cap preserved. `productionAfterChangeHunks` (hunk-local JSX predicate traces) preserves separate file/hunk provenance while excluding deleted lines and tests for focused production review. || `goalFidelityCalibration.js` | Goal-fidelity CALIBRATION contract — what happens when the follow-up investigation overturns a finding, i.e. the objective WAS delivered and the reviewer misjudged it. `GOAL_FIDELITY_CONTEXT_GAPS` is the closed vocabulary of what the reviewer could not see (`truncated-diff`, `truncated-objective`, `objective-omits-context`, `work-outside-diff`, `execution-step-misread`, `rubric-gap`, `other`), enforced ONLY by `normalizeGoalFidelityContextGap` (the report route takes a bounded string, so a near-miss gap name folds to `other` with its diagnosis intact instead of 400ing the report away). `GOAL_FIDELITY_REVIEW_SURFACES` addresses the reviewer's three context surfaces once — objective / diff / rubric — and `GOAL_FIDELITY_CONTEXT_GAP_FIXES` maps each gap onto one of them, so a rename cannot leave seven prose copies lying (`goalFidelityCalibration.pointers.test.js` walks the table against the real files). `goalFidelityCalibrationFingerprint(gap)` keys the dedup on the GAP alone, so many false positives from one blind spot fold into one fix instead of minting an agent each. `buildGoalFidelityCalibrationTask` composes the PortOS-side task body (including the do-not-disarm-the-detector contract) and `buildGoalFidelityFalsePositiveReportBlock` the `curl` instructions appended to a follow-up task, taking `apiBase` as an argument and the call shape from `agentApiToken.js`. I/O lives in `services/goalFidelityCalibration.js`. || `goalFidelityFollowUp.js` | Goal-fidelity FOLLOW-UP contract — what happens once the review HAS a finding, as opposed to what the finding is. `resolveGoalFidelityFollowUp(codeReview)` (`null` when neither action is configured; reads the RAW block, since a verdict already exists by the time this is asked), `normalizeGoalFidelityFollowUpTrigger` (shared with the settings projection so the form and the runtime cannot disagree), and `goalFidelityFollowUpApplies(review, trigger)` over `GOAL_FIDELITY_FOLLOW_UP_TRIGGERS` (`rethink` = only the verdict that holds a run, the default; `any-finding` also fires on the advisory `fix-first`). `goalFidelityFingerprint(task)` is the one dedup identity three parties share — the issue body marker (`goalFidelityIssueMarker` / `issueMatchesGoalFidelityMarker`), the tracker listing that reads it back, and the queued task fingerprint — keyed on taskType + app + objective slug so a perpetual task regenerating with a fresh id cannot re-file forever. Public issue markers hash that identity while matching legacy markers. `buildGoalFidelityIssue` requires a complete objective with verified tracker provenance and immutable diff references before publication; `buildGoalFidelityFollowUpTask` carries the finding issue snapshot and its resolution lifecycle. I/O and public-text scrubbing live in `services/goalFidelityFollowUp.js`. || `navManifest.js` | Single source of truth for nav (`⌘K` palette + voice). Add an entry when you add a page. Also `getNavPageForPath(pathname)` → `{ label, section, breadcrumb }` for the most specific command that owns a route (`null` for one nothing declares) — how user-facing copy NAMES a page it links to, instead of typing "Models → LLMs" beside the link and stranding it on the next move (#7414). `expandPageToken(text, runtime)` expands a `{page}` token in `text` using `getNavPageForPath(runtime?.manageUrl)`, falling back to generic prose rather than shipping a literal `{page}` (#7419). |diff --git a/server/lib/goalFidelity.js b/server/lib/goalFidelity.jsindex 5de9046769..e9de946112 100644--- a/server/lib/goalFidelity.js+++ b/server/lib/goalFidelity.js@@ -22,6 +22,7 @@import { LOCAL_LLM_REVIEWERS, normalizeReviewerEffort, normalizeReviewerModel } from './reviewerConfig.js';import { taskContextBlock } from './cosTaskPrompt.js';+import { parseExpression } from '@babel/parser';import { isTruthyMeta } from './metadataFlags.js';/**@@ -378,7 +379,8 @@ export function productionAfterChangeHunks(diff) {let lines = [];const flush = () => {if (file && hunk && lines.length && !/(?:\.(?:test|spec)\.[^/]+$|(?:^|\/)(?:tests?|__tests__)\/)/.test(file)) {- rows.push({ file, hunk, source: lines.join('\n') });+ const source = lines.join('\n');+ rows.push({ file, hunk, source, renderPredicates: /\.[jt]sx$/.test(file) ? jsxRenderPredicates(source) : [] });}lines = [];};@@ -396,3 +398,54 @@ export function productionAfterChangeHunks(diff) {flush();return rows;}++// Parse only complete JSX expression containers within ONE hunk. A fragment+// wrapper supplies syntax, never unseen application nesting. Incomplete or+// unsupported fragments produce no trace; the reviewer still gets raw source.+function jsxRenderPredicates(source) {+ const traces = [];+ let consumed = 0;+ let attempts = 0;+ for (const start of source.matchAll(/^[ \t]*\{[^\n]*&&\s*\(?[ \t]*$/gm)) {+ if (start.index < consumed) continue;+ let parsed = false;+ const remainder = source.slice(start.index);+ for (const end of remainder.matchAll(/^[ \t]*(?:\)|<\/>)?\}[ \t]*$/gm)) {+ if (++attempts > 32) break;+ const length = end.index + end[0].length;+ const fragment = `<>${remainder.slice(0, length)}</>`;+ let ast;+ try { ast = parseExpression(fragment, { plugins: ['jsx'] }); }+ catch { continue; }+ const walk = (node, predicates = []) => {+ if (!node || typeof node !== 'object') return;+ if (node.type === 'LogicalExpression' && node.operator === '&&') {+ walk(node.left, predicates);+ walk(node.right, [...predicates, fragment.slice(node.left.start, node.left.end)]);+ return;+ }+ if (node.type === 'JSXElement') {+ const name = node.openingElement.name;+ const summary = name.type === 'JSXIdentifier' && name.name === 'MarkdownOutput'+ && node.openingElement.attributes.some(attribute => attribute.name?.name === 'content'+ && attribute.value?.expression?.type === 'Identifier'+ && attribute.value.expression.name === 'taskSummary');+ if (summary || (name.type === 'JSXIdentifier' && name.name === 'OutputBlocks')) {+ traces.push({ render: summary ? 'taskSummary' : 'transcript', enclosingAndPredicates: predicates });+ }+ }+ for (const value of Object.values(node)) {+ if (Array.isArray(value)) value.forEach(child => { if (child?.type) walk(child, predicates); });+ else if (value?.type) walk(value, predicates);+ }+ };+ walk(ast);+ parsed = true;+ consumed = start.index + length;+ break;+ }+ // A partial outer expression must not turn a nested child into a root.+ if (!parsed) break;+ }+ return traces.filter((trace, index) => traces.findIndex(other => JSON.stringify(other) === JSON.stringify(trace)) === index);+}diff --git a/server/package-lock.json b/server/package-lock.jsonindex ee683f42b4..1dcee8cd03 100644--- a/server/package-lock.json+++ b/server/package-lock.json@@ -8,6 +8,7 @@"name": "portos-server","version": "1.7.1","dependencies": {+ "@babel/parser": "8.0.6","@cantoo/pdf-lib": "2.11.1","@googleapis/calendar": "20.0.1","@googleapis/gmail": "22.0.1",@@ -27,7 +28,6 @@"zod": "4.6.5"},"devDependencies": {- "@babel/parser": "8.0.6","@vitest/coverage-v8": "5.0.2","vitest": "5.0.2"},@@ -60,7 +60,6 @@"version": "8.0.6","resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.6.tgz","integrity": "sha512-LpGDIYJAzc3Y3PT9x+FxBrGYu2PlWxLmyN7SwPTzaX0LSwEmFJBsRnPBqmaXF2r1v+Zhz6lNiEJ+7yKtM5+Ugg==",- "dev": true,"license": "MIT","dependencies": {"@babel/types": "^8.0.6"@@ -76,7 +75,6 @@"version": "8.0.6","resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.0.6.tgz","integrity": "sha512-+6HYEBnsDRZHJtUTAEfMQd0zMDqdFHS7C+5vAsEZqBUr3vEMWOWlHJ0Jz1gS8jJIlCvLsuA6ivmeoqzH936YcA==",- "dev": true,"license": "MIT","engines": {"node": "^22.18.0 || >=24.11.0"@@ -86,7 +84,6 @@"version": "8.0.6","resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.6.tgz","integrity": "sha512-HYx0YmuchRxRSpnjvcNffnPS8DCauKNmnumIuHG3jnQAVewRA7kfJGwF13ayEpSZs7s4R/oBH4eppuXcAQd5JQ==",- "dev": true,"license": "MIT","engines": {"node": "^22.18.0 || >=24.11.0"@@ -96,7 +93,6 @@"version": "8.0.6","resolved": "https://registry.npmjs.org/@babel/types/-/types-8.0.6.tgz","integrity": "sha512-c+xgSWboV2pdwXP67BUWDVRHi2BO5Q3KwxyFVs7taVTY+fsK47/L51ZXQoV9rozHJDNHvJ4v4WEsI/IlxV2l2A==",- "dev": true,"license": "MIT","dependencies": {"@babel/helper-string-parser": "^8.0.6",diff --git a/server/package.json b/server/package.jsonindex c2eb6e991f..2576726738 100644--- a/server/package.json+++ b/server/package.json@@ -21,6 +21,7 @@"test:db:ci": "vitest run --config vitest.config.db.js --bail=1 --reporter=default --reporter=github-actions"},"dependencies": {+ "@babel/parser": "8.0.6","@cantoo/pdf-lib": "2.11.1","@googleapis/calendar": "20.0.1","@googleapis/gmail": "22.0.1",@@ -40,7 +41,6 @@"zod": "4.6.5"},"devDependencies": {- "@babel/parser": "8.0.6","@vitest/coverage-v8": "5.0.2","vitest": "5.0.2"},diff --git a/server/services/codeReview.js b/server/services/codeReview.jsindex 1f348d8043..615b66dc95 100644--- a/server/services/codeReview.js+++ b/server/services/codeReview.js@@ -536,7 +536,7 @@ const GOAL_FIDELITY_TRACE_CONTRACT = `Before choosing a verdict, independently tconst GOAL_FIDELITY_DISCLOSURE_RUBRIC = `For completed-card summary disclosure objectives, a statement reporting an already visible summary or another copy when Show is clicked, without explicitly asking to introduce or retain that behavior, is a bug report even without the words "please fix": hide the summary before Show and render it once immediately after Show. Do not demand the complained-about second copy as a requirement, or treat a supporting separate full-transcript control as unrequested. Explicitly asking to retain a preview or a duplicate is different: honor that stated requirement instead. For the hide/duplicate-removal objective, judge the following conditions IN THE ACTUAL DIFF; these examples are not claims that those conditions are present. Reconstruct the after-change tree using only added (+) and retained (space) hunk lines; discard deleted (-) lines. In a relocation, the deleted old summary outside the panel is NOT a surviving summary.1. Find the enclosing production JSX condition around the ADDED summary. A retained \` {expanded && (\` hides ALL its descendants when expanded=false. The inner taskSummary condition inherits that enclosing guard and does NOT need a second expanded check. A retained \` {true && (\` instead renders unconditionally: return fix-first, missing: ["summary remains visible while collapsed"]. Comments and tests cannot supply a missing outer guard.2. If the objective asks for one summary copy in the initially expanded view, complains about a second copy on Show, or asks for a separate full-transcript disclosure, find the production condition around the transcript. If it asks only to hide the summary until Show, an after-Show transcript duplicate is not a missing requirement; do not impose this second check. With \`transcriptExpanded\` initialized to false, \`(!taskSummary || transcriptExpanded)\` suppresses the transcript while a summary exists, until the separate control toggles transcriptExpanded. An ADDED \`+ {true && <>\` line (regardless of indentation) is an unconditional transcript branch, even when transcriptExpanded and its button still exist. Only the render condition controls visibility; the button cannot hide a branch that uses true. An unconditional transcript condition therefore leaves a duplicate after Show: return fix-first, missing: ["transcript duplicates the summary before its separate disclosure"]. State variables and buttons alone cannot supply this render guard.-3. If BOTH production guards above and the control transition are actually present, the nested summary is hidden while collapsed, renders once after Show, and may repeat only after explicitly opening the full transcript. Those are delivered disclosure requirements, even if the same summary text occurs in raw transcript data. Matching local/remote interaction assertions are verification coverage, not proof that tests ran or passed.+3. First check whether the objective explicitly forbids summary repetition even AFTER opening the full transcript. In that case, gating raw OutputBlocks with transcriptExpanded is insufficient: it delays the repeated summary instead of removing it. Unless the source also removes summary text from that transcript, return fix-first, missing: ["summary can still repeat inside the full transcript"]. Otherwise, if BOTH production guards above and the control transition are actually present, the nested summary is hidden while collapsed, renders once after Show, and may repeat only after explicitly opening the full transcript. Those are delivered disclosure requirements, even if the same summary text occurs in raw transcript data. Matching local/remote interaction assertions are verification coverage, not proof that tests ran or passed.A separate transcript disclosure can support moving a summary into the expanded panel by avoiding a new duplicate beside existing raw output; do not call that supporting control unrequested. Judge each requested outcome independently; for a hide-until-Show-only objective, the matching outer guard delivers the requested visibility without requiring transcript suppression. Check production conditions before considering the tests. A test-only diff lacks the production evidence needed to establish these disclosure requirements: return fix-first or rethink, never ship. Likewise positive tests cannot override a broken production guard. Do not infer guards outside the supplied diff. This interpretation covers only avoiding duplication BEFORE the separate transcript action; do not waive an objective that explicitly forbids summary repetition even after opening the full transcript. For the complete guarded shape with no other missing/unrequested requirement, return ship with empty lists. For an incomplete shape, name its violated disclosure instead.`const GOAL_FIDELITY_SYSTEM_PROMPT = `${GOAL_FIDELITY_INPUT_CONTRACT}@@ -582,7 +582,7 @@ ${GOAL_FIDELITY_TRACE_CONTRACT}${GOAL_FIDELITY_DISCLOSURE_RUBRIC}-The second block contains only AFTER-change production source from the same diff, with file and hunk provenance. Deleted lines and test files are excluded. Separate hunks are not contiguous source: do not invent nesting across a hunk boundary. Trace the actual summary and transcript enclosing predicates in this source independently of any test claims. For a repair objective, tests alone cannot establish its production implementation. This pass checks only production delivery: unrequested must be empty and evidence must not claim tests ran. A ship here cannot clear findings from the primary review.+The second block contains only AFTER-change production source from the same diff, with file and hunk provenance. Deleted lines and test files are excluded. Separate hunks are not contiguous source: do not invent nesting across a hunk boundary. renderPredicates lists syntactically parsed enclosing AND conditions, from outer to inner, for complete JSX expressions within that hunk. A literal true predicate imposes no restriction; it cannot hide a summary before Show. An expanded predicate is inherited by the summary even when its inner condition is only taskSummary. These traces describe the actual source, not expected behavior or test assertions. Trace the actual summary and transcript enclosing predicates in this source independently of any test claims. For a repair objective, tests alone cannot establish its production implementation. This pass checks only production delivery: unrequested must be empty and evidence must not claim tests ran. A ship here cannot clear findings from the primary review.${GOAL_FIDELITY_RESULT_CONTRACT}diff --git a/server/services/codeReview.test.js b/server/services/codeReview.test.jsindex 3a15485a72..cf938820ff 100644--- a/server/services/codeReview.test.js+++ b/server/services/codeReview.test.js@@ -1146,6 +1146,8 @@ describe('codeReview helpers', () => {if (messages[1].content.includes('AFTER-CHANGE PRODUCTION HUNKS')) {const rows = JSON.parse(messages[1].content.match(/AFTER-CHANGE PRODUCTION HUNKS[^\n]*\n(`+)json\n([\s\S]*)\n\1$/)[2])expect(rows).toHaveLength(4)+ expect(rows.flatMap(row => row.renderPredicates)).toContainEqual({ render: 'taskSummary', enclosingAndPredicates: ['expanded', 'taskSummary', 'taskSummary'] })+ expect(rows.flatMap(row => row.renderPredicates)).toContainEqual({ render: 'transcript', enclosingAndPredicates: ['expanded', '!taskSummary || transcriptExpanded', 'output.length > 0'] })expect(new Set(rows.map(row => row.hunk)).size).toBe(4)expect(rows.every(row => row.file === 'client/src/components/cos/tabs/AgentCard.jsx')).toBe(true)expect(messages[1].content).toContain('{expanded && (')@@ -1177,6 +1179,22 @@ describe('codeReview helpers', () => {})).toMatchObject({ ok: true, verdict: 'rethink', missing: ['requested dashboard behavior'] })})+ it.each([+ ['outer summary guard', summaryDisclosureCases[1][1], 'taskSummary', ['true', 'taskSummary', 'taskSummary']],+ ['transcript guard', summaryDisclosureCases[2][1], 'transcript', ['expanded', 'true', 'output.length > 0']],+ ])('exposes the actual parsed %s contradiction despite positive tests', async (_name, diff, render, enclosingAndPredicates) => {+ global.fetch = vi.fn(async (_url, init) => {+ const { messages } = JSON.parse(init.body)+ if (messages[1].content.includes('AFTER-CHANGE PRODUCTION HUNKS')) {+ const rows = JSON.parse(messages[1].content.match(/AFTER-CHANGE PRODUCTION HUNKS[^\n]*\n(`+)json\n([\s\S]*)\n\1$/)[2])+ expect(rows.flatMap(row => row.renderPredicates)).toContainEqual({ render, enclosingAndPredicates })+ }+ return completion(shipVerdict)+ })+ await runLocalGoalFidelityReview({ backend: 'ollama', model: 'example-model', ...summaryDisclosureCase, diff })+ expect(global.fetch).toHaveBeenCalledTimes(2)+ })+it('keeps a primary rejection when the disclosure production pass finds compatible guards', async () => {global.fetch = vi.fn().mockResolvedValueOnce(completion({ verdict: 'fix-first', missing: ['another requested outcome'], unrequested: ['extra scope'], evidence: 'primary verification note' })).mockResolvedValueOnce(completion(shipVerdict))