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
feat: score an issue or PR against the repo's own PRD.md and GOALS.md, locally and advisory-only (#7643)
[._.]/ Adam Eivy8d91fc9a8ae0
diff --git a/client/src/components/apps/ScopeAdherenceCheck.jsx b/client/src/components/apps/ScopeAdherenceCheck.jsxnew file mode 100644index 0000000000..7f0195cad5--- /dev/null+++ b/client/src/components/apps/ScopeAdherenceCheck.jsx@@ -0,0 +1,93 @@+import { useCallback, useState } from 'react';+import { Scale } from 'lucide-react';+import Pill from '../ui/Pill';+import BrailleSpinner from '../BrailleSpinner';+import { useInstanceFeatures } from '../../hooks/useInstanceFeatures';+import { scoreAppScopeAdherence } from '../../services/api';++/**+ * An on-demand, ADVISORY answer to "does this change advance what the product+ * says it is for?", rendered under one issue or pull-request row.+ *+ * Three deliberate constraints:+ *+ * 1. **Nothing is gated on it.** No button is disabled by a verdict, no row is+ * hidden, no claim or merge is blocked. The output is a sentence naming a+ * clause the reader can go and argue with.+ * 2. **It runs only when clicked.** The scorer is a 9 GB local model that+ * loads on first use; scoring every visible row on mount would be exactly+ * the cold-bootstrap work the AI Provider Usage Policy forbids.+ * 3. **It disappears when the feature is off.** An install that has not+ * opted into the jev scorer never sees a button whose only outcome would+ * be "not installed".+ */++const TONE = { aligned: 'success', contradicts: 'warning', unrelated: 'muted' };+const LABEL = { aligned: 'Advances', contradicts: 'Works against', unrelated: 'Unrelated' };++// Operator-facing wording for the failure codes this surface can actually+// produce. An unmapped code is a bug, not something to render raw at someone.+const REASON = {+ 'scope-adherence-disabled': 'The local scope scorer is turned off for this install.',+ 'scope-adherence-change-empty': 'This row has no title or description to score.',+ 'scope-adherence-corpus-missing': 'This repository has no PRD.md or GOALS.md to score against.',+ 'scope-adherence-corpus-unreadable': 'This repository\'s PRD.md / GOALS.md could not be read.',+ 'scope-adherence-no-clause': 'No stated goal in this repository is close enough to score against.',+ 'jev-not-installed': 'The local scorer is not installed yet — see Models > LLMs > jev.',+ 'jev-start-failed': 'The local scorer could not start. Check Models > LLMs > jev.',+ 'jev-timeout': 'The local scorer did not answer in time.',+};++const reasonFor = (code) => REASON[code] || 'The local scorer could not answer for this change.';++export default function ScopeAdherenceCheck({ appId, kind, title, body = '', diffSummary = '' }) {+ const { isFeatureEnabled } = useInstanceFeatures();+ const [result, setResult] = useState(null);+ const [scoring, setScoring] = useState(false);++ const check = useCallback(() => {+ setScoring(true);+ setResult(null);+ scoreAppScopeAdherence(appId, { kind, title, body, diffSummary })+ .then((response) => setResult(response || { ok: false }))+ // The tab owns its error UI and an uninstalled scorer is an ordinary+ // answer here, so a failed request reads as "no advisory", never a toast.+ .catch(() => setResult({ ok: false }))+ .finally(() => setScoring(false));+ }, [appId, kind, title, body, diffSummary]);++ if (!isFeatureEnabled('jev')) return null;++ return (+ <div className="mt-2 flex flex-wrap items-center gap-2 text-xs">+ <button+ type="button"+ onClick={check}+ disabled={scoring}+ className="inline-flex items-center gap-1 rounded border border-port-border px-2 py-0.5 text-gray-400 hover:text-port-accent hover:border-port-accent/40 disabled:opacity-50"+ title="Advisory only — scores this change against the repository's PRD.md and GOALS.md locally"+ >+ {scoring ? <BrailleSpinner /> : <Scale size={12} />}+ {scoring ? 'Scoring…' : 'Check scope'}+ </button>++ {result?.ok && result.verdict !== 'abstained' && (+ <>+ <Pill tone={TONE[result.verdict]} size="xs">{LABEL[result.verdict]}</Pill>+ {/* The clause, not just the score. A bare margin is noise. */}+ <span className="text-gray-400">+ {result.clause?.sourceFile}+ {result.clause?.headingPath ? ` § ${result.clause.headingPath}` : ''}+ </span>+ <span className="text-gray-600 italic">advisory only</span>+ </>+ )}++ {result?.ok && result.verdict === 'abstained' && (+ <span className="text-gray-500">No advisory — the scorer could not separate the options.</span>+ )}++ {result && !result.ok && <span className="text-gray-500">{reasonFor(result.code)}</span>}+ </div>+ );+}diff --git a/client/src/components/apps/ScopeAdherenceCheck.test.jsx b/client/src/components/apps/ScopeAdherenceCheck.test.jsxnew file mode 100644index 0000000000..e541701530--- /dev/null+++ b/client/src/components/apps/ScopeAdherenceCheck.test.jsx@@ -0,0 +1,89 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import ScopeAdherenceCheck from './ScopeAdherenceCheck';++const isFeatureEnabled = vi.fn();+vi.mock('../../hooks/useInstanceFeatures', () => ({+ useInstanceFeatures: () => ({ isFeatureEnabled }),+}));++const scoreAppScopeAdherence = vi.fn();+vi.mock('../../services/api', () => ({+ scoreAppScopeAdherence: (...args) => scoreAppScopeAdherence(...args),+}));++const props = { appId: 'app-001', kind: 'pr', title: 'Expose the dashboard publicly', body: 'Opens the port.' };++beforeEach(() => {+ vi.clearAllMocks();+ isFeatureEnabled.mockReturnValue(true);+});++describe('ScopeAdherenceCheck', () => {+ it('renders nothing at all when the jev feature is off', () => {+ isFeatureEnabled.mockReturnValue(false);+ const { container } = render(<ScopeAdherenceCheck {...props} />);+ expect(container).toBeEmptyDOMElement();+ });++ it('scores nothing until the operator asks', () => {+ render(<ScopeAdherenceCheck {...props} />);+ // The scorer is a 9 GB local model. Scoring every visible row on mount is+ // exactly the cold-bootstrap work the AI Provider Usage Policy forbids.+ expect(scoreAppScopeAdherence).not.toHaveBeenCalled();+ expect(screen.getByRole('button', { name: /check scope/i })).toBeInTheDocument();+ });++ it('names the clause a contradiction was scored against, and says it is advisory', async () => {+ scoreAppScopeAdherence.mockResolvedValue({+ ok: true,+ verdict: 'contradicts',+ clauseId: 'PRD.md#out-of-scope:abc12345',+ clause: { sourceFile: 'PRD.md', headingPath: 'Out of Scope' },+ margin: 0.41,+ });++ await userEvent.click(render(<ScopeAdherenceCheck {...props} />)+ .getByRole('button', { name: /check scope/i }));++ await waitFor(() => expect(screen.getByText('Works against')).toBeInTheDocument());+ // A bare verdict is noise; the citation is what a human can go argue with.+ expect(screen.getByText('PRD.md § Out of Scope')).toBeInTheDocument();+ expect(screen.getByText('advisory only')).toBeInTheDocument();+ expect(scoreAppScopeAdherence).toHaveBeenCalledWith('app-001', {+ kind: 'pr',+ title: 'Expose the dashboard publicly',+ body: 'Opens the port.',+ diffSummary: '',+ });+ });++ it('reads an abstention as no advisory rather than as a verdict', async () => {+ scoreAppScopeAdherence.mockResolvedValue({ ok: true, verdict: 'abstained', clauseId: null, clause: null, margin: 0.04 });++ await userEvent.click(render(<ScopeAdherenceCheck {...props} />)+ .getByRole('button', { name: /check scope/i }));++ await waitFor(() => expect(screen.getByText(/could not separate the options/i)).toBeInTheDocument());+ expect(screen.queryByText(/Works against|Advances|Unrelated/)).not.toBeInTheDocument();+ });++ it('explains an uninstalled scorer instead of leaving the row silent', async () => {+ scoreAppScopeAdherence.mockResolvedValue({ ok: false, code: 'jev-not-installed' });++ await userEvent.click(render(<ScopeAdherenceCheck {...props} />)+ .getByRole('button', { name: /check scope/i }));++ await waitFor(() => expect(screen.getByText(/not installed yet/i)).toBeInTheDocument());+ });++ it('swallows a failed request into "no advisory" rather than a toast', async () => {+ scoreAppScopeAdherence.mockRejectedValue(new Error('network'));++ await userEvent.click(render(<ScopeAdherenceCheck {...props} />)+ .getByRole('button', { name: /check scope/i }));++ await waitFor(() => expect(screen.getByText(/could not answer for this change/i)).toBeInTheDocument());+ });+});diff --git a/client/src/components/apps/tabs/IssuesTab.jsx b/client/src/components/apps/tabs/IssuesTab.jsxindex e074f88c5e..0150b99643 100644--- a/client/src/components/apps/tabs/IssuesTab.jsx+++ b/client/src/components/apps/tabs/IssuesTab.jsx@@ -15,6 +15,7 @@ import { useCosTaskUpdates } from '../../../hooks/useCosTaskUpdates';import useProviderModels from '../../../hooks/useProviderModels';import useClaimReviewers from '../../../hooks/useClaimReviewers';import ClaimReviewerSource from '../ClaimReviewerSource';+import ScopeAdherenceCheck from '../ScopeAdherenceCheck';import ReviewerPicker from '../../cos/ReviewerPicker';import useReviewerModelOptions from '../../../hooks/useReviewerModelOptions';import { chipColors } from '../../../lib/chipContrast';@@ -893,6 +894,15 @@ export default function IssuesTab({ appId, appName }) {) : (<p className="text-xs text-gray-500 italic">No description.</p>)}+ {/* Advisory only, and only under an expanded row: the+ reader has the description in front of them, so the+ clause the scorer cites is something they can check. */}+ <ScopeAdherenceCheck+ appId={appId}+ kind="issue"+ title={issue.title || ''}+ body={issue.body || ''}+ /></div>)}</div>diff --git a/client/src/components/apps/tabs/PullRequestsTab.jsx b/client/src/components/apps/tabs/PullRequestsTab.jsxindex aec58b8cc2..6e90357874 100644--- a/client/src/components/apps/tabs/PullRequestsTab.jsx+++ b/client/src/components/apps/tabs/PullRequestsTab.jsx@@ -10,6 +10,7 @@ import ConfirmButtonPair from '../../ui/ConfirmButtonPair';import Pill from '../../ui/Pill';import toast from '../../ui/Toast';import ProviderModelSelector from '../../ProviderModelSelector';+import ScopeAdherenceCheck from '../ScopeAdherenceCheck';import { useConfirmDelete } from '../../../hooks/useConfirmDelete';import { useCosTaskUpdates } from '../../../hooks/useCosTaskUpdates';import useProviderModels from '../../../hooks/useProviderModels';@@ -648,6 +649,17 @@ export default function PullRequestsTab({ appId, appName }) {)}{pullRequest.updatedAt && <span>updated {timeAgo(pullRequest.updatedAt)}</span>}</div>++ {/* Advisory only — never gates the merge button beside it.+ The listing carries no PR description, so the branch+ pair stands in for the change's code-side vocabulary;+ it is the second retrieval view, not the premise. */}+ <ScopeAdherenceCheck+ appId={appId}+ kind="pr"+ title={pullRequest.title || ''}+ diffSummary={[pullRequest.headBranch, pullRequest.baseBranch].filter(Boolean).join(' → ')}+ /></div><div className="shrink-0 lg:pt-0.5 flex flex-wrap items-start gap-2">diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.jsindex 77a7f4deb3..0d0ac83ae0 100644--- a/client/src/services/apiApps.js+++ b/client/src/services/apiApps.js@@ -85,6 +85,20 @@ export const getAppIssues = (id, options) =>// default to silent.export const getAppPullRequests = (id, options) =>request(`/apps/${id}/pull-requests`, { silent: true, ...options });+// ADVISORY ONLY: score one issue or PR against the app checkout's own PRD.md /+// GOALS.md with the local entailment scorer, and get back a verdict plus the+// clause it was scored against. Nothing branches on the answer — it is rendered+// beside the row and never gates a claim, a merge, or a label. POST because a+// body does not fit a query string, and because waking the scorer has to be an+// explicit operator action in the same request. The caller owns its own error+// UI (an uninstalled scorer is an ordinary answer here), so default to silent.+export const scoreAppScopeAdherence = (id, change, options = {}) =>+ request(`/apps/${id}/scope-adherence`, {+ method: 'POST',+ body: JSON.stringify(change),+ silent: true,+ ...options,+ });// Queue the shared review-loop follow-up for one freshly verified open PR/MR.// The server, not the browser, owns the forge URL/branch and duplicate guard.// `settings` is the same provider/model/effort pin `createSlashdoTask` takes —diff --git a/docs/README.md b/docs/README.mdindex 27ec7abd7b..694cecd068 100644--- a/docs/README.md+++ b/docs/README.md@@ -50,7 +50,7 @@ Chief of Staff: [chief-of-staff](./features/chief-of-staff.md) · [cos-agent-runIdentity & self: [digital-twin](./features/digital-twin.md) · [identity-system](./features/identity-system.md) · [soul-system](./features/soul-system.md) · [privacy-center](./features/privacy-center.md) · [post](./features/post.md) (insights design spike: [plans/2026-06-03](./plans/2026-06-03-cross-domain-insights-engine.md))-Knowledge: [brain-system](./features/brain-system.md) · [untrusted messages and GitHub automation](./features/messages-security.md)+Knowledge: [brain-system](./features/brain-system.md) · [untrusted messages and GitHub automation](./features/messages-security.md) · [scope adherence](./features/scope-adherence.md)Create: [writers-room](./features/writers-room.md) · [fableloom](./features/fableloom.md) · [Eidoverse Worlds integration](./features/eidoverse.md) · [OpenWorld historical reference](./features/openworld.md) · [sprite-export-contract](./features/sprite-export-contract.md) · [video-text-encoders](./features/video-text-encoders.md) · [video-speed-profiles](./features/video-speed-profiles.md) · [video-render-batches](./features/video-render-batches.md) · [video-upscale](./features/video-upscale.md)diff --git a/docs/features/scope-adherence.md b/docs/features/scope-adherence.mdnew file mode 100644index 0000000000..7b9b7ce6cc--- /dev/null+++ b/docs/features/scope-adherence.md@@ -0,0 +1,91 @@+# Scope adherence — does this change advance what the product says it is for?++A repository's `PRD.md` and `GOALS.md` state what it is supposed to be. Until now nothing read them. Scope adherence scores one filed issue or one open pull request against those files with the local entailment scorer ([JEV_SETUP.md](../JEV_SETUP.md)) and prints one sentence naming the clause it scored against.++**It is advisory and it will stay advisory.** No auto-close, no gating label, no CI check, no blocked agent. [ETHOS.md](../../ETHOS.md) asks that supervision gates be justified before they are added, and a 4B classifier disagreeing with prose is not a justification. The output exists so a human can go read a named clause and decide — including deciding the classifier is wrong.++## Where it appears++Under an expanded row in an app's **Issues** tab, and under each row in its **Pull Requests** tab, as a *Check scope* button. It runs only on that click:++- The scorer is a ~9 GB local model that loads on first use, so scoring every visible row on mount would be exactly the cold-bootstrap work the AI Provider Usage Policy in [AGENTS.md](../../AGENTS.md) forbids.+- The button is absent entirely when the `jev` instance feature is off (**Settings > Features**), which is the shipped default.++## How a verdict is produced++```+screenUntrustedContent() ← Prompt Guard. Unchanged, and not optional.+ ↓ safe+parse PRD.md + GOALS.md ← server/lib/prdClauses.js+ ↓ clauses+retrieve top-k candidates ← BM25 × 2 views, fused with RRF+ ↓ ≤ k clauses+decide() per clause ← server/services/jev.js. Abstains on a near-tie.+ ↓+one advisory naming the clause+```++An issue or PR body is attacker-controlled text, so it passes phase 1 of the untrusted-content ladder before anything reasons over it — the same contract described in [messages-security](./messages-security.md). Scope adherence is a **phase-2 reasoner**, never a replacement for the screen.++### Clause parsing++`server/lib/prdClauses.js` splits each document into one clause per paragraph, top-level list item, blockquote, or table data row. Fenced code, table headers and horizontal rules are dropped — they are syntax, not statements about the product. PortOS's own two files yield ~175 clauses.++A clause id is `<sourceFile>#<heading-path-slug>:<content-hash>` — **no line number and no document ordinal**, so inserting an unrelated paragraph above a requirement does not re-key it. A verdict recorded last week still addresses the same clause today. Two byte-identical clauses under one heading are disambiguated with a `~<n>` suffix.++### Retrieval, not exhaustive scoring++Each clause is a separate forward pass through a 4B model, so scoring all of them would cost minutes for a verdict that cites one. `selectCandidateClauses` builds two BM25 rankings of the same corpus — one from the change's prose (title + body), one from its code-side vocabulary (changed files, or the branch pair when the listing carries no description) — and fuses them with the `fuseRankingsRRF` the memory retrieval stack already uses. Fusing beats concatenating: whichever view is longer would otherwise dominate the term frequencies. Only the top `k` (default 3) are scored.++### The three hypotheses++Frozen in `server/lib/scopeAdherence.js`, for the same reason `lib/jevDecisions.js` freezes its own: they are the entire instruction surface of the feature, and a caller that inlined its own phrasing would drift from the wording any recorded verdict was produced under.++| Verdict | Hypothesis |+|---|---|+| `aligned` | The proposed change advances the stated product goal. |+| `unrelated` | The proposed change is unrelated to the stated product goal. |+| `contradicts` | The proposed change works against the stated product goal. |++The premise is the clause first and in full, then the change — the change is what gets truncated if the pair does not fit, because a clipped goal would have the scorer answering about half a requirement with no way to tell.++### Abstention and reporting++The floor is `0.20` top-1 margin, wider than the scorer's own `0.15` default: `unrelated` and `contradicts` read very differently to a human, and calling a PR "works against" a goal on a hair's separation would burn the feature's credibility faster than saying nothing. Below it the row reads *No advisory*.++When several clauses answer, the reported one is ranked by **informativeness**, not retrieval position: `contradicts` → `aligned` → `unrelated`, widest margin breaking a tie. A contradiction found on the third-ranked clause is the single most useful thing this feature can say, and ranking by margin alone would bury it under a confident `aligned`.++## Privacy++Everything is machine-local. The corpus is two files in a checkout, the scorer is a loopback sidecar, and no verdict, premise, or clause is persisted, federated, or included in a status or capability payload — consistent with the ADR [privacy records machine-local](../decisions/2026-08-08-privacy-records-machine-local.md).++The repository path comes from the loaded app record, never from the request: `POST /api/apps/:id/scope-adherence` takes only `kind`, `title`, `body` and `diffSummary`, and its schema is `.strict()`, so a client-supplied checkout path cannot turn an advisory endpoint into an arbitrary-file reader. An app with no repository is refused rather than silently graded against this install's own PRD.++## Failure modes++| Code | What it means |+|---|---|+| `scope-adherence-disabled` | The `jev` instance feature is off. Nothing was screened or scored. |+| `scope-adherence-change-empty` | The row has no title or description to score. |+| `scope-adherence-corpus-missing` | The checkout has no `PRD.md` or `GOALS.md` (or the app has no repository). |+| `scope-adherence-corpus-unreadable` | The files exist but could not be read — a broken install, not an empty one. |+| `scope-adherence-no-clause` | No stated goal was close enough to the change to be worth a forward pass. |+| `untrusted-content-*` | Phase 1 blocked the content, or the abuse guard could not run. See [messages-security](./messages-security.md). |+| `jev-*` | The scorer itself is unavailable. See [JEV_SETUP.md](../JEV_SETUP.md). |++Each reads as "no advisory" in the UI, never as a verdict.++## What is deliberately not here++- **A trained, project-specific head.** Fitting a small head on the frozen encoder from this install's merged PRs, closed-unmerged PRs and triage corrections — with a hand-labeled gold set and a "must beat both the stock zero-shot and the majority-class baseline to be adopted" rule — is tracked separately. Zero-shot ships first because it is useful on its own and needs no corpus.+- **Any enforcement**, now or later. See the opening paragraph.++## Source++| Piece | File |+|---|---|+| Clause parser | `server/lib/prdClauses.js` |+| Hypotheses, retrieval, premise, route schema | `server/lib/scopeAdherence.js` |+| The ladder (screen → retrieve → decide) | `server/services/scopeAdherence.js` |+| HTTP surface | `server/routes/apps/scopeAdherence.js` |+| UI | `client/src/components/apps/ScopeAdherenceCheck.jsx` |diff --git a/server/lib/README.md b/server/lib/README.mdindex 6be79cff95..c2c1c9c09b 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -503,6 +503,8 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `localPersistentMindRecommendation.js` | CPU-only / low-RAM Persistent Mind defaults (Grok-box path): recommended Ollama + Qwen2.5 7B instruct profile, model aliases, and host gates so GPU coding-agent presets are not steered here. Pure. || `jev.js` | Pinned local entailment ("jev") contract: the `JEV_MODEL` descriptor (repo, revision, `qwen3.5-4b-nli` subfolder, MIT/ungated), the four-file required allowlist, pinned Python packages, `JEV_STAGES` / `jevStageReadiness()` for the operator install checklist, the premise/hypothesis bounds, the `jevScoreRequestSchema` / `jevScoreResponseSchema` wire pair, `normalizeJevScores` (rejects a reply describing a different hypothesis list), and `decideFromScores` — the margin arithmetic that ABSTAINS rather than picking a near-tie. Pure. Lifecycle is `services/jev.js`; see [docs/JEV_SETUP.md](../../docs/JEV_SETUP.md). || `jevDecisions.js` | `JEV_DECISIONS` — the closed-set decisions PortOS may answer with the local scorer instead of a chat completion, each with its frozen hypothesis wording and its abstention floor. `getJevDecision` / `jevHypotheses` / `jevValueForHypothesis` map between an enum value and the hypothesis that stands for it; `jevMinMarginFor` composes the per-decision floor, the per-OPTION floor (a destructive `delete` clears a far wider margin than the `archive` beside it), and the operator setting, which can only RAISE the bar. `isValidJevDecision` is the contract every shipped descriptor is tested against. Pure. Routing, mode resolution and the counts-only agreement store live in `services/jevRouter.js`. |+| `prdClauses.js` | Chops `PRD.md` / `GOALS.md` into addressable clauses — one per paragraph, top-level list item, blockquote or table data row — each carrying its heading path, source file and line. Clause ids are `<file>#<heading-slug>:<content-hash>` with NO line number and NO document ordinal, so a clause keeps its id when an unrelated paragraph is inserted above it. `indexClausesById` / `formatClauseCitation` render a verdict back to a citation a human can go read. Pure; the files are read by `services/scopeAdherence.js`. |+| `scopeAdherence.js` | The "does this change advance the stated product goal?" question in the shape an entailment scorer can answer: the three frozen hypotheses (aligned / unrelated / contradicts), the abstention floor, `selectCandidateClauses` (two BM25 views of the change fused with `fuseRankingsRRF`, so scoring is bounded by k rather than the whole corpus), `composeAdherencePremise` (clause first and in full, change truncated), `verdictForHypothesis`, `formatAdherenceAdvisory`, and the route-input `scopeAdherenceRequestSchema`. ADVISORY ONLY — nothing here returns a gateable boolean. Pure; the ladder lives in `services/scopeAdherence.js`. || `pythonRuntimeDiagnosis.js` | `diagnosePythonRuntimeText(text, { subject, repairLabel, imports, fallback })` — maps raw pip/interpreter output onto the fixed operator-facing diagnosis vocabulary (`package-missing`, `certificate-failed`, `wheel-unavailable`, `dependency-conflict`, `disk-full`, `network-failed`), naming the specific pinned import when one is missing. Evidence is matched and DISCARDED: nothing from the subprocess output (tokens, authenticated index URLs, local paths) is ever returned. Shared by the Prompt Guard and jev installers. Pure. || `modelAbuseGuard.js` | Pinned model-abuse boundary contract: Prompt Guard metadata, deterministic abuse signals (`hiddenCodePointSummary` for invisible/direction-control/C0-C1 code points, `invisibleClusterSummary` for a dense cluster of the exempt ones, `describeEncodedPayload` for compressed/opaque blobs — the last scoped to `CODE_CONTENT_SOURCES` so a private message carrying base64 is not model abuse — plus hidden HTML comments/collapsed markup that address a model), complete classifier-window coverage validation, chunk/timeout limits, fixed dependency versions (`MODEL_ABUSE_GUARD_PYTHON_PACKAGES`), and `MODEL_ABUSE_GUARD_STAGES` / `modelAbuseGuardStageReadiness` for the operator-facing install checklist. Pure. || `diffHiddenContentScan.js` | Pre-LLM gate over a unified diff — `scanDiffForHiddenContent(diff)` reports invisible/direction-control Unicode (added lines and filenames), dense clusters of the invisible characters the rules otherwise exempt, compressed or opaque encoded payloads, a new symlink that leaves the repository or a new git submodule, a non-media binary patch, and inline script in SVG/HTML/XML, keyed `path:line`; `formatHiddenContentFindings` renders them for a CI log. Detectors for the Unicode/encoded rules are shared with `modelAbuseGuard.js` (same rules, applied to external PR content). Lockfiles skip the encoded rule but never the Unicode ones, a leading BOM is allowed, and `portos-allow-hidden-content` on the line itself opts out of the added-line rules. Driven by `scripts/scan-diff-hidden-content.js`, which CI runs on every pull request before any reviewer reads the diff (`core.quotepath=false` so a stealth filename is not octal-escaped past the detector). Pure. |diff --git a/server/lib/index.js b/server/lib/index.jsindex e8a4dcf768..07116f9202 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -463,6 +463,8 @@ export * from './localLlmCatalog.js';export * from './localPersistentMindRecommendation.js';export * from './jev.js';export * from './jevDecisions.js';+export * from './prdClauses.js';+export * from './scopeAdherence.js';export * from './modelAbuseGuard.js';export * from './pythonRuntimeDiagnosis.js';export * from './diffHiddenContentScan.js';diff --git a/server/lib/prdClauses.js b/server/lib/prdClauses.jsnew file mode 100644index 0000000000..38fe53108c--- /dev/null+++ b/server/lib/prdClauses.js@@ -0,0 +1,204 @@+/**+ * Chop a product-requirements document into addressable clauses.+ *+ * `PRD.md` and `GOALS.md` state what the product is supposed to be. Nothing+ * reads them. This module turns that prose into the premise corpus the local+ * entailment scorer needs: a flat list of short, self-contained statements,+ * each one carrying the heading path it came from so a verdict can name the+ * clause a human can go and argue with.+ *+ * THE CORPUS IS NOT A TRAINING SET. 373 lines of product prose is nowhere near+ * one. Its only job is to be split into premises.+ *+ * Pure: no I/O, no module state. `services/scopeAdherence.js` reads the files.+ *+ * ## Clause identity+ *+ * An id is `<sourceFile>#<heading-path-slug>:<content-hash>`, with `~<n>`+ * appended for the second and later identical clauses under one heading. It+ * deliberately carries NO line number and NO document-wide ordinal: a clause+ * has to keep its id when an unrelated paragraph is inserted above it, or an+ * adherence verdict recorded last week would address a different clause today.+ * The hash covers the clause's own normalized text before any truncation, so+ * shortening the display cap does not re-key the corpus.+ */++import { createHash } from 'crypto';++/** The documents PortOS scores its own changes against. */+export const PRD_CLAUSE_SOURCES = Object.freeze(['PRD.md', 'GOALS.md']);++/**+ * Per-clause character cap.+ *+ * Far below the scorer's premise bound (`JEV_MAX_PREMISE_CHARS`), because the+ * premise is the clause PLUS the change being scored against it — the clause+ * is the small half. A single requirement that needs more than this to state+ * itself is a requirement nobody can check either.+ */+export const PRD_MAX_CLAUSE_CHARS = 2_000;++/** Below this a "clause" is a stray fragment, not a statement of intent. */+const MIN_CLAUSE_CHARS = 24;++const HEADING = /^(#{1,6})\s+(.*)$/;+const FENCE = /^\s*(```|~~~)/;+const RULE = /^\s*(-{3,}|\*{3,}|_{3,})\s*$/;+const LIST_ITEM = /^\s{0,3}(?:[-*+]|\d{1,3}[.)])\s+/;+const TABLE_ROW = /^\s*\|.*\|\s*$/;+const TABLE_DIVIDER = /^\s*\|[\s:|-]+\|\s*$/;+const BLOCKQUOTE = /^\s*>+\s?/;++const slug = (text) => text+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '')+ .slice(0, 60);++/** Strip the markdown that carries no meaning for an entailment scorer. */+function flatten(text) {+ return text+ .replace(/^\s*>+\s?/gm, '')+ .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')+ .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')+ .replace(/[*_`]+/g, '')+ .replace(/\s+/g, ' ')+ .trim();+}++/** A table row rendered as one sentence: `FR-1 — The system MUST … — Must — …`. */+function flattenTableRow(line) {+ const cells = line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|')+ .map((cell) => flatten(cell))+ .filter(Boolean);+ return cells.join(' — ');+}++const contentHash = (text) => createHash('sha256').update(text).digest('hex').slice(0, 8);++/** H1 count outside fenced code, so a `# comment` in a shell example doesn't vote. */+function countTopLevelHeadings(lines) {+ let fenced = false;+ let count = 0;+ for (const line of lines) {+ if (FENCE.test(line)) { fenced = !fenced; continue; }+ if (!fenced && /^#\s/.test(line)) count += 1;+ }+ return count;+}++/**+ * Split one markdown document into clauses.+ *+ * A clause is a paragraph, a top-level list item (with its nested lines+ * folded in), a blockquote, or a table data row. Headings build the path;+ * fenced code, table headers, and horizontal rules are dropped — they are+ * syntax or examples, not statements about the product.+ *+ * @param {string} markdown Raw file contents.+ * @param {{ sourceFile?: string }} options `sourceFile` is part of every id.+ * @returns {Array<{ id, heading, headingPath, text, sourceFile, line }>}+ */+export function parsePrdClauses(markdown, { sourceFile = 'PRD.md' } = {}) {+ if (typeof markdown !== 'string' || !markdown.trim()) return [];++ const lines = markdown.split(/\r?\n/);+ const clauses = [];+ // Occurrence counter per (headingPath, hash). Two byte-identical clauses+ // under one heading are rare but legal, and they must not share an id.+ const seen = new Map();+ const headings = [];+ let fenced = false;+ // The block being accumulated: paragraph lines, or one list item plus its+ // continuation lines.+ let buffer = [];+ let bufferLine = 0;++ // A document with exactly one H1 is using it as a title, not as a section,+ // so it is dropped from every citation — `PRD.md § PRD.md — PortOS ›+ // Overview` reads as a bug. A document that sections with H1s keeps them.+ const titleH1 = countTopLevelHeadings(lines) === 1;+ const headingPath = () => headings.slice(titleH1 ? 1 : 0).filter(Boolean).join(' › ');++ const flush = () => {+ if (!buffer.length) return;+ const raw = flatten(buffer.join(' '));+ buffer = [];+ if (raw.length < MIN_CLAUSE_CHARS) return;+ push(raw, bufferLine);+ };++ const push = (raw, line) => {+ const path = headingPath();+ const hash = contentHash(raw);+ const key = `${path}:${hash}`;+ const occurrence = seen.get(key) || 0;+ seen.set(key, occurrence + 1);+ clauses.push({+ id: `${sourceFile}#${slug(path) || 'document'}:${hash}${occurrence ? `~${occurrence}` : ''}`,+ heading: headings.filter(Boolean).at(-1) || sourceFile,+ headingPath: path,+ text: raw.length > PRD_MAX_CLAUSE_CHARS ? `${raw.slice(0, PRD_MAX_CLAUSE_CHARS - 1)}…` : raw,+ sourceFile,+ line,+ });+ };++ lines.forEach((line, index) => {+ const lineNumber = index + 1;++ if (FENCE.test(line)) {+ flush();+ fenced = !fenced;+ return;+ }+ if (fenced) return;++ const heading = HEADING.exec(line);+ if (heading) {+ flush();+ const depth = heading[1].length;+ headings.length = Math.max(depth - 1, 0);+ headings[depth - 1] = flatten(heading[2]);+ return;+ }++ if (!line.trim() || RULE.test(line)) {+ flush();+ return;+ }++ if (TABLE_ROW.test(line)) {+ flush();+ // Look AHEAD for the divider rather than retracting an already-pushed+ // row: a retraction would leave the duplicate-occurrence counter+ // incremented, and a later identical clause would silently take a `~1`+ // id that nothing else agrees with.+ if (TABLE_DIVIDER.test(line) || TABLE_DIVIDER.test(lines[index + 1] || '')) return;+ const row = flattenTableRow(line);+ if (row.length >= MIN_CLAUSE_CHARS) push(row, lineNumber);+ return;+ }++ const content = line.replace(BLOCKQUOTE, '');+ // A new list item ends the previous block; an indented continuation of one+ // does not, so a nested bullet stays with the item it qualifies.+ if (LIST_ITEM.test(content)) flush();+ if (!buffer.length) bufferLine = lineNumber;+ buffer.push(content.replace(LIST_ITEM, '').trim());+ });++ flush();+ return clauses;+}++/** Clause lookup by id, for rendering a verdict's cited clause. */+export function indexClausesById(clauses) {+ return new Map((Array.isArray(clauses) ? clauses : []).map((clause) => [clause.id, clause]));+}++/** `PRD.md § Functional Requirements › AI Agent Orchestration` — a human-readable citation. */+export function formatClauseCitation(clause) {+ if (!clause?.sourceFile) return '';+ return clause.headingPath ? `${clause.sourceFile} § ${clause.headingPath}` : clause.sourceFile;+}diff --git a/server/lib/prdClauses.test.js b/server/lib/prdClauses.test.jsnew file mode 100644index 0000000000..6aafcbe235--- /dev/null+++ b/server/lib/prdClauses.test.js@@ -0,0 +1,108 @@+import { describe, it, expect } from 'vitest';+import { readFile } from 'fs/promises';+import { join } from 'path';+import {+ formatClauseCitation,+ indexClausesById,+ parsePrdClauses,+ PRD_CLAUSE_SOURCES,+ PRD_MAX_CLAUSE_CHARS,+} from './prdClauses.js';++const DOC = `# Example Product++A one-line pitch that is long enough to count as a clause on its own.++## Goals++1. **Thing one** — the product does the first thing it promises to do.+2. **Thing two** — the product also does the second thing it promises.++## Functional Requirements++| ID | Requirement | Priority |+|---|---|---|+| FR-1 | The system MUST keep every record on the operator's own machine. | Must |+| FR-2 | The system SHOULD surface a digest of what it decided. | Should |++## Notes++> A quoted note that states an intention and is long enough to survive.++\`\`\`bash+# This heading-looking comment lives in a fence and must be ignored+echo hi+\`\`\`+`;++const parse = (text = DOC) => parsePrdClauses(text, { sourceFile: 'PRD.md' });++describe('parsePrdClauses', () => {+ it('splits paragraphs, list items, table rows and blockquotes into clauses under their heading path', () => {+ const clauses = parse();+ const byText = (needle) => clauses.find((clause) => clause.text.includes(needle));++ expect(byText('one-line pitch')?.headingPath).toBe('');+ expect(byText('Thing one')?.headingPath).toBe('Goals');+ expect(byText('Thing two')?.headingPath).toBe('Goals');++ const fr1 = byText('FR-1');+ expect(fr1.headingPath).toBe('Functional Requirements');+ // The row is flattened into one sentence, acceptance column included, and+ // the header row + divider are not clauses of their own.+ expect(fr1.text).toBe("FR-1 — The system MUST keep every record on the operator's own machine. — Must");+ expect(clauses.some((clause) => clause.text.startsWith('ID —'))).toBe(false);++ // The blockquote marker is stripped; the fenced `#` line is not a heading+ // and its body is not a clause.+ expect(byText('quoted note')?.text.startsWith('A quoted note')).toBe(true);+ expect(clauses.some((clause) => clause.text.includes('heading-looking comment'))).toBe(false);+ expect(clauses.some((clause) => clause.headingPath.includes('This heading-looking'))).toBe(false);+ });++ it('keeps a clause id stable when unrelated text is inserted earlier in the file', () => {+ const before = parse();+ const target = before.find((clause) => clause.text.includes('FR-2'));++ const edited = DOC.replace(+ '## Goals\n',+ '## Goals\n\nAn entirely new paragraph inserted ahead of everything that follows it.\n',+ );+ const after = parsePrdClauses(edited, { sourceFile: 'PRD.md' });+ const moved = after.find((clause) => clause.text.includes('FR-2'));++ // This is the regression the id scheme exists for: a verdict recorded+ // against a clause last week must still address that clause today.+ expect(moved.id).toBe(target.id);+ expect(moved.line).toBeGreaterThan(target.line);+ expect(after.length).toBe(before.length + 1);+ });++ it('gives byte-identical clauses under one heading distinct ids', () => {+ const repeated = '## Repeats\n\nThe very same sentence twice over, stated identically.\n\nThe very same sentence twice over, stated identically.\n';+ const ids = parsePrdClauses(repeated, { sourceFile: 'GOALS.md' }).map((clause) => clause.id);+ expect(ids).toHaveLength(2);+ expect(new Set(ids).size).toBe(2);+ });++ it('caps a clause at the premise budget and drops the document title from the citation', () => {+ const long = `# Title\n\n## Long\n\n${'word '.repeat(2000)}\n`;+ const [clause] = parsePrdClauses(long, { sourceFile: 'PRD.md' });+ expect(clause.text.length).toBeLessThanOrEqual(PRD_MAX_CLAUSE_CHARS);+ // A single H1 is a title, not a section, so it never appears in a citation.+ expect(formatClauseCitation(clause)).toBe('PRD.md § Long');+ });++ it('parses this repository\'s own PRD.md and GOALS.md into a unique, non-empty corpus', async () => {+ // The corpus is the feature's whole input. A parser change that silently+ // collapsed these two files would leave scoring with nothing to retrieve.+ const root = join(import.meta.dirname, '..', '..');+ const clauses = [];+ for (const sourceFile of PRD_CLAUSE_SOURCES) {+ clauses.push(...parsePrdClauses(await readFile(join(root, sourceFile), 'utf8'), { sourceFile }));+ }+ expect(clauses.length).toBeGreaterThan(50);+ expect(indexClausesById(clauses).size).toBe(clauses.length);+ expect(clauses.every((clause) => clause.text.length <= PRD_MAX_CLAUSE_CHARS)).toBe(true);+ });+});diff --git a/server/lib/scopeAdherence.js b/server/lib/scopeAdherence.jsnew file mode 100644index 0000000000..a3f13c674e--- /dev/null+++ b/server/lib/scopeAdherence.js@@ -0,0 +1,188 @@+/**+ * The closed-set question "does this change advance what the product says it+ * is for?", expressed the way an entailment cross-encoder can answer it.+ *+ * ADVISORY ONLY, BY CONSTRUCTION. Nothing in this module or its service+ * returns a boolean a caller could gate on. The output is a verdict, the+ * clause it was scored against, and a margin — a named clause a human can go+ * read and argue with. [ETHOS.md](../../ETHOS.md) asks that supervision gates+ * be justified before they are added, and a 4B classifier disagreeing with a+ * prose PRD is not a justification. There is no auto-close, no gating label,+ * and no CI check anywhere downstream of this.+ *+ * Pure: no I/O, no scorer, no file reads. `services/scopeAdherence.js` owns+ * the ladder (screen → jev → advisory verdict).+ */++import { z } from 'zod';+import { search, buildInvertedIndex } from './bm25.js';+import { fuseRankingsRRF } from './memoryQuery.js';+import { JEV_MAX_PREMISE_CHARS } from './jev.js';+import { formatClauseCitation } from './prdClauses.js';++/**+ * The hypotheses, frozen here rather than inlined at the call site.+ *+ * These are PROMPTS — the entire instruction surface of the feature — and+ * they follow the same rule as `lib/jevDecisions.js`: wording lives in one+ * reviewable module, versioned with the file, because a caller that inlined+ * its own phrasing would drift from the wording any recorded verdict was+ * produced under.+ *+ * Kept OUT of `JEV_DECISIONS`: every entry there is a rung of the+ * untrusted-content ladder and is contractually bound to an+ * `UNTRUSTED_CONTENT_SOURCES` channel and to that ladder's enum machinery.+ * Scope adherence answers a question about the operator's own product, not+ * about a message that arrived from somewhere.+ */+export const SCOPE_ADHERENCE_OPTIONS = Object.freeze([+ Object.freeze({+ verdict: 'aligned',+ hypothesis: 'The proposed change advances the stated product goal.',+ }),+ Object.freeze({+ verdict: 'unrelated',+ hypothesis: 'The proposed change is unrelated to the stated product goal.',+ }),+ Object.freeze({+ verdict: 'contradicts',+ hypothesis: 'The proposed change works against the stated product goal.',+ }),+]);++export const SCOPE_ADHERENCE_HYPOTHESES = Object.freeze(SCOPE_ADHERENCE_OPTIONS.map((option) => option.hypothesis));++/**+ * Abstention floor.+ *+ * Wider than the scorer's 0.15 default: `unrelated` and `contradicts` read+ * very differently to a human, and telling an operator their PR "works+ * against" a goal on a hair's separation would burn the feature's credibility+ * faster than staying quiet ever could.+ */+export const SCOPE_ADHERENCE_MIN_MARGIN = 0.2;++/**+ * How many clauses are scored per change.+ *+ * The corpus is a few hundred clauses and each one is a separate forward pass+ * through a 4B model, so scoring them all would cost minutes for a verdict+ * that only ever cites one clause. Retrieval picks the few worth asking about.+ */+export const SCOPE_ADHERENCE_TOP_K = 3;++/** Weights for the two retrieval views fused below. Narrative leads; code confirms. */+const NARRATIVE_WEIGHT = 1;+const CODE_WEIGHT = 0.7;++const changeText = (change) => [change?.title, change?.body].filter(Boolean).join('\n').trim();+const changeCode = (change) => String(change?.diffSummary || '').trim();++const asRanking = (results) => (results || []).map((result) => ({ id: result.docId }));++/**+ * Pick the clauses worth scoring, newest-relevance first.+ *+ * TWO BM25 rankings, fused with RRF — not one query over a concatenated blob.+ * A change describes itself twice, in different vocabularies: prose in the+ * title and body, and identifiers in the changed-file list. Concatenating them+ * lets whichever is longer dominate the term frequencies; fusing their+ * rankings lets a clause that only one view found still surface. RRF is the+ * same fusion the memory retrieval stack already uses, so this reuses+ * `fuseRankingsRRF` rather than re-deriving rank arithmetic.+ *+ * @returns {Array} up to `k` clauses, in fused-rank order.+ */+export function selectCandidateClauses(clauses, change, { k = SCOPE_ADHERENCE_TOP_K } = {}) {+ const corpus = Array.isArray(clauses) ? clauses.filter((clause) => clause?.id && clause.text) : [];+ if (!corpus.length || k <= 0) return [];++ const narrative = changeText(change);+ const code = changeCode(change);+ if (!narrative && !code) return [];++ const index = buildInvertedIndex(corpus.map((clause) => ({ id: clause.id, text: clause.text })));+ // Over-fetch each view: RRF ranks by agreement, so a clause that placed 5th+ // in both views can legitimately beat one that placed 1st in a single view.+ const limit = Math.max(k * 4, 12);+ const fused = fuseRankingsRRF(+ asRanking(narrative ? search(narrative, index, { limit }) : []),+ asRanking(code ? search(code, index, { limit }) : []),+ { ftsWeight: NARRATIVE_WEIGHT, vectorWeight: CODE_WEIGHT },+ );++ const byId = new Map(corpus.map((clause) => [clause.id, clause]));+ return [...fused.entries()]+ .sort((a, b) => b[1].rrfScore - a[1].rrfScore)+ .slice(0, k)+ .map(([id]) => byId.get(id))+ .filter(Boolean);+}++/** A change rendered as the evidence half of a premise, with a hard budget. */+function formatChange(change, budget) {+ const kindLabel = change?.kind === 'pr' ? 'pull request' : 'issue';+ const lines = [`Proposed change (${kindLabel}):`];+ if (change?.title) lines.push(`Title: ${change.title}`);+ if (change?.body) lines.push(`Description: ${change.body}`);+ if (change?.diffSummary) lines.push(`Changed files: ${change.diffSummary}`);+ const text = lines.join('\n');+ return text.length > budget ? `${text.slice(0, budget - 1)}…` : text;+}++/**+ * Build the premise for one (clause, change) pair.+ *+ * The clause is stated FIRST and in full; the change is what gets truncated+ * when the pair does not fit. A clipped goal would have the scorer answering+ * about half a requirement without any way to tell that it had.+ */+export function composeAdherencePremise({ clause, change, maxChars = JEV_MAX_PREMISE_CHARS } = {}) {+ if (!clause?.text) return null;+ const head = `Stated product goal (${formatClauseCitation(clause)}):\n${clause.text}\n\n`;+ const budget = maxChars - head.length;+ if (budget < 1) return null;+ const tail = formatChange(change, budget);+ return tail.trim() ? `${head}${tail}` : null;+}++/** The verdict a returned hypothesis stands for, or null if it is not ours. */+export function verdictForHypothesis(hypothesis) {+ return SCOPE_ADHERENCE_OPTIONS.find((option) => option.hypothesis === hypothesis)?.verdict ?? null;+}++/**+ * The one-line advisory a surface renders.+ *+ * Always names the clause. A bare `0.31` is noise; "contradicts PRD.md §+ * Out of Scope" is something a human can act on — including by deciding the+ * classifier is wrong.+ */+export function formatAdherenceAdvisory({ verdict, clause, margin } = {}) {+ if (!clause || !verdict) return 'No scope advisory: the scorer could not separate the options.';+ const phrase = { aligned: 'advances', unrelated: 'is unrelated to', contradicts: 'works against' }[verdict];+ const confidence = Number.isFinite(margin) ? ` (margin ${margin.toFixed(2)})` : '';+ return `Advisory: this change ${phrase} ${formatClauseCitation(clause)}${confidence}. Not a gate — read the clause and decide.`;+}++/**+ * Route input for the advisory endpoint.+ *+ * Validated from HERE rather than through `lib/validation.js`, for the same+ * reason `jevScoreRequestSchema` is: re-exporting a one-route schema through+ * that barrel drags this module into the static import closure of every suite+ * that reaches it, which is exactly the growth `lib/importScoping.test.js`+ * exists to catch.+ *+ * `.strict()` — the endpoint is advisory and fixed-shape, so an unexpected key+ * is a caller reaching for a knob that does not exist, not something to drop.+ * There is deliberately no `repoPath` and no `appId`: the checkout comes from+ * the route's own loaded app record, because a client-supplied path would turn+ * an advisory endpoint into an arbitrary-file reader.+ */+export const scopeAdherenceRequestSchema = z.object({+ kind: z.enum(['issue', 'pr']),+ title: z.string().trim().min(1).max(1_000),+ body: z.string().max(100_000).optional(),+ diffSummary: z.string().max(20_000).optional(),+}).strict();diff --git a/server/routes/apps/index.js b/server/routes/apps/index.jsindex 64ad5ad7c4..72628434d5 100644--- a/server/routes/apps/index.js+++ b/server/routes/apps/index.js@@ -17,6 +17,7 @@* documents — planning-doc read/list/commit* agents — recent CoS agent history* repositorySources — checkout origin/upstream status and fork synchronization+ * scopeAdherence — advisory PRD/GOALS alignment score for one issue or PR** Route ordering is safe across sub-routers: every param route is either the* single-segment `/:id` or a deeper `/:id/...`, and the static routes@@ -40,6 +41,7 @@ import documentRoutes from './documents.js';import agentRoutes from './agents.js';import spriteBindingRoutes from './spriteBindings.js';import repositorySourceRoutes from './repositorySources.js';+import scopeAdherenceRoutes from './scopeAdherence.js';const router = Router();@@ -56,5 +58,6 @@ router.use(documentRoutes);router.use(agentRoutes);router.use(spriteBindingRoutes);router.use(repositorySourceRoutes);+router.use(scopeAdherenceRoutes);export default router;diff --git a/server/routes/apps/scopeAdherence.js b/server/routes/apps/scopeAdherence.jsnew file mode 100644index 0000000000..06b7c64b4c--- /dev/null+++ b/server/routes/apps/scopeAdherence.js@@ -0,0 +1,48 @@+/**+ * Advisory scope-adherence scoring for a managed app's Issues / Pull Requests+ * tabs.+ *+ * POST /:id/scope-adherence → { ok, verdict, clauseId, clause, margin, advisory }+ *+ * ADVISORY, NEVER A GATE. The handler writes nothing: no label, no close, no+ * task, no persisted record. It reads `PRD.md` / `GOALS.md` out of the app's+ * own checkout and asks the local entailment scorer whether the change in the+ * request advances what those files say the product is for. The answer is+ * rendered next to the row; nothing downstream may branch on it.+ *+ * POST rather than GET because an issue or PR body is too large for a query+ * string, and because starting the scorer is an explicit operator action in+ * the same request (AI Provider Usage Policy) — this never runs on its own.+ *+ * The repository path comes from the LOADED APP RECORD, never from the+ * request. A client-supplied checkout path would turn an advisory endpoint+ * into an arbitrary-file reader.+ */++import { Router } from 'express';+import { asyncHandler } from '../../lib/errorHandler.js';+import { validateRequest } from '../../lib/validation.js';+import { scopeAdherenceRequestSchema } from '../../lib/scopeAdherence.js';+import { loadApp } from './shared.js';++const router = Router();++router.post('/:id/scope-adherence', loadApp, asyncHandler(async (req, res) => {+ const { kind, title, body, diffSummary } = validateRequest(scopeAdherenceRequestSchema, req.body);+ // Deferred: the scorer carries the sidecar lifecycle and the pinned 9 GB+ // model contract, and this route is the only thing in the apps graph that+ // reaches it (`server/lib/importScoping.test.js`).+ const { scoreAdherence } = await import('../../services/scopeAdherence.js');+ res.json(await scoreAdherence({+ kind,+ title,+ body,+ diffSummary,+ // `?? ''` rather than letting it fall through as `undefined`: the service+ // defaults an ABSENT path to this install's own checkout, and an app+ // record with no repository would then be graded against PortOS's PRD.+ repoPath: req.loadedApp.repoPath ?? '',+ }));+}));++export default router;diff --git a/server/routes/apps/scopeAdherence.test.js b/server/routes/apps/scopeAdherence.test.jsnew file mode 100644index 0000000000..8ca82f78b0--- /dev/null+++ b/server/routes/apps/scopeAdherence.test.js@@ -0,0 +1,85 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../../lib/testHelper.js';+import scopeAdherenceRoutes from './scopeAdherence.js';++vi.mock('../../services/apps.js', () => ({ getAppById: vi.fn() }));+vi.mock('../../services/scopeAdherence.js', () => ({ scoreAdherence: vi.fn() }));++import * as appsService from '../../services/apps.js';+import { scoreAdherence } from '../../services/scopeAdherence.js';++const ADVISORY = {+ ok: true,+ verdict: 'contradicts',+ clauseId: 'PRD.md#out-of-scope:abc12345',+ clause: { id: 'PRD.md#out-of-scope:abc12345', sourceFile: 'PRD.md', headingPath: 'Out of Scope', text: '…', line: 12 },+ margin: 0.41,+ advisory: 'Advisory: this change works against PRD.md § Out of Scope (margin 0.41). Not a gate — read the clause and decide.',+ scored: 3,+};++describe('POST /api/apps/:id/scope-adherence', () => {+ let app;++ beforeEach(() => {+ app = express();+ app.use(express.json());+ app.use('/api/apps', scopeAdherenceRoutes);+ vi.clearAllMocks();+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'Widget', repoPath: '/repo' });+ scoreAdherence.mockResolvedValue(ADVISORY);+ });++ const post = (body) => request(app).post('/api/apps/app-001/scope-adherence').send(body);++ it('scores against the loaded app\'s own checkout and returns the advisory verbatim', async () => {+ const response = await post({ kind: 'pr', title: 'Expose the dashboard publicly', body: 'Opens :5555 to the internet.' });++ expect(response.status).toBe(200);+ expect(response.body).toEqual(ADVISORY);+ expect(scoreAdherence).toHaveBeenCalledWith({+ kind: 'pr',+ title: 'Expose the dashboard publicly',+ body: 'Opens :5555 to the internet.',+ diffSummary: undefined,+ repoPath: '/repo',+ });+ });++ it('refuses a client-supplied repository path', async () => {+ // The endpoint reads PRD.md out of a checkout. A caller-controlled path+ // would make it an arbitrary-file reader, so the schema is `.strict()`.+ const response = await post({ kind: 'pr', title: 'Anything', repoPath: '/etc' });++ expect(response.status).toBe(400);+ expect(scoreAdherence).not.toHaveBeenCalled();+ });++ it('never falls back to this install\'s own checkout for an app with no repository', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'app-002', name: 'Docs only' });++ await request(app).post('/api/apps/app-002/scope-adherence').send({ kind: 'issue', title: 'Something' });++ // An absent `repoPath` must reach the service as an explicit empty, not as+ // `undefined` — the service defaults an ABSENT path to PortOS's own+ // checkout, which would grade another repository against PortOS's PRD.+ expect(scoreAdherence).toHaveBeenCalledWith(expect.objectContaining({ repoPath: '' }));+ });++ it('404s for an unknown app without scoring anything', async () => {+ appsService.getAppById.mockResolvedValue(null);++ const response = await post({ kind: 'issue', title: 'Something' });++ expect(response.status).toBe(404);+ expect(scoreAdherence).not.toHaveBeenCalled();+ });++ it('rejects an unknown change kind', async () => {+ const response = await post({ kind: 'discussion', title: 'Something' });++ expect(response.status).toBe(400);+ expect(scoreAdherence).not.toHaveBeenCalled();+ });+});diff --git a/server/services/scopeAdherence.js b/server/services/scopeAdherence.jsnew file mode 100644index 0000000000..108b61e9b2--- /dev/null+++ b/server/services/scopeAdherence.js@@ -0,0 +1,197 @@+/**+ * Score a filed issue or an opened pull request against what the product says+ * it is for, using the local entailment scorer instead of a chat completion.+ *+ * screenUntrustedContent() ← phase 1, Prompt Guard. UNCHANGED.+ * ↓ safe+ * retrieve top-k clauses ← BM25 + RRF over PRD.md / GOALS.md+ * ↓+ * decide() per clause ← phase 2, local. Abstains rather than guessing.+ * ↓+ * one advisory line naming the clause+ *+ * ADVISORY, NEVER A GATE. This module has no write path: it closes nothing,+ * labels nothing, blocks nothing, and no caller of it may either. That is a+ * deliberate reading of [ETHOS.md](../../ETHOS.md) — unsupervised operation is+ * the design target, and a 4B classifier's disagreement with prose is not+ * grounds to stop a human or an agent. `scoreAdherence` returns a verdict, the+ * clause it was scored against, and a margin; what a surface does with that is+ * render it.+ *+ * Machine-local throughout: the corpus is two files in the checkout, the+ * scorer is a loopback sidecar, and nothing here is persisted, federated, or+ * included in a status or capability payload.+ */++import { join } from 'path';+import { stat } from 'fs/promises';+import { tryReadFileStrict } from '../lib/jsonIo.js';+import { PATHS } from '../lib/paths.js';+import { parsePrdClauses, PRD_CLAUSE_SOURCES } from '../lib/prdClauses.js';+import {+ composeAdherencePremise,+ formatAdherenceAdvisory,+ SCOPE_ADHERENCE_HYPOTHESES,+ SCOPE_ADHERENCE_MIN_MARGIN,+ SCOPE_ADHERENCE_TOP_K,+ selectCandidateClauses,+ verdictForHypothesis,+} from '../lib/scopeAdherence.js';++/** Every way `scoreAdherence` can decline to produce a verdict. */+export const SCOPE_ADHERENCE_FAILURE_CODES = Object.freeze([+ 'scope-adherence-disabled',+ 'scope-adherence-change-empty',+ 'scope-adherence-corpus-missing',+ 'scope-adherence-corpus-unreadable',+ 'scope-adherence-no-clause',+]);++const failure = (code) => ({ ok: false, code });++/**+ * Which verdict gets reported when several clauses answered.+ *+ * Informativeness, not retrieval rank. A `contradicts` on the third-ranked+ * clause is the single most useful thing this feature can say, and reporting+ * `unrelated` from the top-ranked clause instead would bury it. Within a tier,+ * the widest margin wins.+ */+const VERDICT_RANK = { contradicts: 0, aligned: 1, unrelated: 2 };++// Cache the parsed corpus per repository, invalidated on either file's mtime.+// Parsing ~400 lines is cheap, but the scorer is called from a UI button and+// re-reading two files on every click for an unchanged checkout is waste.+const corpusCache = new Map();++async function fileStamp(path) {+ return stat(path).then((info) => `${info.mtimeMs}:${info.size}`, () => null);+}++/**+ * Parse `PRD.md` and `GOALS.md` from one checkout into a clause corpus.+ *+ * `ok: false` distinguishes "this repository states no product intent" from+ * "we could not read the files that state it" — the first is a legitimate+ * empty an operator can fix by writing a PRD, the second is a broken install,+ * and collapsing them would advertise the wrong remedy.+ */+export async function loadClauseCorpus(repoPath = PATHS.root) {+ // An app record with no checkout has no product intent to score against, and+ // silently falling back to THIS install's PRD would grade someone else's+ // repository against PortOS's goals.+ if (typeof repoPath !== 'string' || !repoPath.trim()) return failure('scope-adherence-corpus-missing');+ const stamps = await Promise.all(PRD_CLAUSE_SOURCES.map((name) => fileStamp(join(repoPath, name))));+ const key = `${repoPath}|${stamps.join('|')}`;+ const cached = corpusCache.get(repoPath);+ if (cached?.key === key) return cached.result;++ const clauses = [];+ let unreadable = false;+ for (const sourceFile of PRD_CLAUSE_SOURCES) {+ const { ok, value } = await tryReadFileStrict(join(repoPath, sourceFile));+ if (!ok) { unreadable = true; continue; }+ if (typeof value === 'string') clauses.push(...parsePrdClauses(value, { sourceFile }));+ }++ const result = unreadable && !clauses.length+ ? failure('scope-adherence-corpus-unreadable')+ : { ok: true, clauses };+ corpusCache.set(repoPath, { key, result });+ return result;+}++/** Test seam, mirroring the cache resets on the sibling local-model services. */+export const resetClauseCorpusCache = () => corpusCache.clear();++/**+ * Score one change against the product's stated intent.+ *+ * @param {object} change+ * @param {'issue'|'pr'} change.kind Which forge object this is; picks the screening channel.+ * @param {string} change.title+ * @param {string} [change.body]+ * @param {string} [change.diffSummary] Changed-file list or a short diff digest.+ * @param {string} [change.repoPath] Checkout holding the PRD; defaults to this install's.+ * @param {number} [change.topK] Clause budget. Bounds the number of forward passes.+ * @returns {Promise<{ok: true, verdict: 'aligned'|'unrelated'|'contradicts'|'abstained', clauseId: string|null, clause: object|null, margin: number|null, advisory: string, scored: number} | {ok: false, code: string}>}+ */+export async function scoreAdherence({+ kind = 'issue',+ title = '',+ body = '',+ diffSummary = '',+ repoPath = PATHS.root,+ topK = SCOPE_ADHERENCE_TOP_K,+} = {}) {+ // Deferred: `jevRouter` reaches the instance-feature graph and `jev.js`+ // carries the sidecar lifecycle and the 9 GB model contract. An install that+ // never opts in must not pay for either in its static import closure+ // (`server/lib/importScoping.test.js`).+ const { isJevFeatureEnabled } = await import('./jevRouter.js');+ if (!await isJevFeatureEnabled()) return failure('scope-adherence-disabled');++ const change = { kind, title: String(title || '').trim(), body: String(body || '').trim(), diffSummary: String(diffSummary || '').trim() };+ if (!change.title && !change.body) return failure('scope-adherence-change-empty');++ // Phase 1 of the ladder, unchanged and not optional: an issue or PR body is+ // attacker-controlled text, and it reaches a model here the same way it does+ // everywhere else in the untrusted-content contract.+ const { screenUntrustedContent } = await import('./untrustedContent.js');+ const screened = await screenUntrustedContent({+ content: [change.title, change.body].filter(Boolean).join('\n\n'),+ source: kind === 'pr' ? 'github-pr' : 'github-issue',+ });+ if (!screened.ok) return failure(screened.code || 'untrusted-content-screening-failed');++ const corpus = await loadClauseCorpus(repoPath);+ if (!corpus.ok) return corpus;+ if (!corpus.clauses.length) return failure('scope-adherence-corpus-missing');++ const candidates = selectCandidateClauses(corpus.clauses, change, { k: topK });+ if (!candidates.length) return failure('scope-adherence-no-clause');++ const { decide } = await import('./jev.js');+ const decided = [];+ let widestAbstention = null;+ for (const clause of candidates) {+ const premise = composeAdherencePremise({ clause, change });+ if (!premise) continue;+ const scored = await decide({ premise, options: [...SCOPE_ADHERENCE_HYPOTHESES], minMargin: SCOPE_ADHERENCE_MIN_MARGIN });+ // An unavailable scorer is reported once, as itself. Falling through to a+ // chat completion is what the untrusted-content ladder does; there is no+ // such fallback here, because an advisory nobody asked for is not worth+ // provider quota.+ if (!scored.ok) return failure(scored.code);+ if (scored.abstained) {+ if (widestAbstention === null || scored.margin > widestAbstention) widestAbstention = scored.margin;+ continue;+ }+ const verdict = verdictForHypothesis(scored.choice);+ if (verdict) decided.push({ verdict, clause, margin: scored.margin });+ }++ if (!decided.length) {+ return {+ ok: true,+ verdict: 'abstained',+ clauseId: null,+ clause: null,+ margin: widestAbstention,+ advisory: formatAdherenceAdvisory({}),+ scored: candidates.length,+ };+ }++ decided.sort((a, b) => (VERDICT_RANK[a.verdict] - VERDICT_RANK[b.verdict]) || (b.margin - a.margin));+ const best = decided[0];+ return {+ ok: true,+ verdict: best.verdict,+ clauseId: best.clause.id,+ clause: best.clause,+ margin: best.margin,+ advisory: formatAdherenceAdvisory(best),+ scored: candidates.length,+ };+}diff --git a/server/services/scopeAdherence.test.js b/server/services/scopeAdherence.test.jsnew file mode 100644index 0000000000..f9bb2faf11--- /dev/null+++ b/server/services/scopeAdherence.test.js@@ -0,0 +1,180 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { mkdtemp, mkdir, rm, writeFile, readFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';++vi.mock('./jevRouter.js', () => ({ isJevFeatureEnabled: vi.fn() }));+vi.mock('./untrustedContent.js', () => ({ screenUntrustedContent: vi.fn() }));+vi.mock('./jev.js', () => ({ decide: vi.fn() }));++const { isJevFeatureEnabled } = await import('./jevRouter.js');+const { screenUntrustedContent } = await import('./untrustedContent.js');+const { decide } = await import('./jev.js');+const { scoreAdherence, loadClauseCorpus, resetClauseCorpusCache } = await import('./scopeAdherence.js');+const { SCOPE_ADHERENCE_OPTIONS } = await import('../lib/scopeAdherence.js');++const hypothesis = (verdict) => SCOPE_ADHERENCE_OPTIONS.find((option) => option.verdict === verdict).hypothesis;++const PRD = `# Example Product++## Agent Orchestration++The system MUST route every agent task to a provider automatically and without human intervention.++The system SHOULD learn provider routing weights from observed agent task outcomes over time.++## Knowledge Capture++The system MUST index every captured note for hybrid retrieval by the operator.++## Out of Scope++The system MUST NOT expose any agent, provider, or task to the public internet.+`;++const GOALS = `# Example Goals++## Knowledge Capture++Captured notes are indexed for hybrid retrieval so the operator can find them again later.++## Autonomous Agents++Agent tasks are generated from goals and routed to the best provider without the operator intervening.+`;++let repoPath;++beforeEach(async () => {+ // resetAllMocks, not clearAllMocks: a leftover `mockResolvedValueOnce`+ // queue would fire in the next test and score a change nobody asked about.+ vi.resetAllMocks();+ resetClauseCorpusCache();+ repoPath = await mkdtemp(join(tmpdir(), 'portos-scope-'));+ await writeFile(join(repoPath, 'PRD.md'), PRD);+ await writeFile(join(repoPath, 'GOALS.md'), GOALS);+ isJevFeatureEnabled.mockResolvedValue(true);+ screenUntrustedContent.mockResolvedValue({ ok: true, safe: true });+ decide.mockResolvedValue({ ok: true, abstained: true, margin: 0.01, choice: null });+});++afterEach(() => rm(repoPath, { force: true, recursive: true }));++const score = (overrides = {}) => scoreAdherence({+ kind: 'pr',+ title: 'Route agent tasks to the best provider automatically',+ body: 'Adds automatic provider routing for every queued agent task.',+ repoPath,+ ...overrides,+});++describe('scoreAdherence', () => {+ it('declines before touching the scorer when the jev feature is off', async () => {+ isJevFeatureEnabled.mockResolvedValue(false);+ expect(await score()).toEqual({ ok: false, code: 'scope-adherence-disabled' });+ // The whole point of the feature gate: an install that never opted in must+ // not screen, read the corpus, or wake a 9 GB sidecar.+ expect(screenUntrustedContent).not.toHaveBeenCalled();+ expect(decide).not.toHaveBeenCalled();+ });++ it('screens the change before scoring it, and reports a block with the screening code', async () => {+ screenUntrustedContent.mockResolvedValue({ ok: false, code: 'untrusted-content-blocked' });+ expect(await score({ kind: 'issue' })).toEqual({ ok: false, code: 'untrusted-content-blocked' });+ expect(screenUntrustedContent).toHaveBeenCalledWith(expect.objectContaining({ source: 'github-issue' }));+ expect(decide).not.toHaveBeenCalled();+ });++ it('scores at most topK clauses, never the whole corpus', async () => {+ const result = await score({ topK: 2 });+ // Retrieval is the cost control: without it every clause is a separate+ // forward pass through a 4B model. Asserting the exact count rather than+ // just a ceiling also catches a retrieval regression that quietly returns+ // one clause (or none) and makes the bound vacuously true.+ expect(decide.mock.calls.length).toBe(2);+ expect(result.scored).toBe(2);+ expect((await loadClauseCorpus(repoPath)).clauses.length).toBeGreaterThan(2);+ for (const [request] of decide.mock.calls) {+ expect(request.options).toEqual(SCOPE_ADHERENCE_OPTIONS.map((option) => option.hypothesis));+ expect(request.premise).toContain('Proposed change (pull request)');+ }+ });++ it('abstains rather than guessing when no clause separates the options', async () => {+ const result = await score();+ expect(result).toMatchObject({ ok: true, verdict: 'abstained', clauseId: null, clause: null });+ expect(result.margin).toBe(0.01);+ expect(result.advisory).not.toMatch(/advances|works against/);+ });++ it('reports a contradiction ahead of an alignment found on a better-ranked clause', async () => {+ decide+ .mockResolvedValueOnce({ ok: true, abstained: false, choice: hypothesis('aligned'), margin: 0.9, confidence: 0.95 })+ .mockResolvedValueOnce({ ok: true, abstained: false, choice: hypothesis('contradicts'), margin: 0.3, confidence: 0.6 })+ .mockResolvedValue({ ok: true, abstained: true, margin: 0.02, choice: null });++ const result = await score();+ // A `contradicts` buried behind a wide `aligned` is the single most useful+ // thing this feature can say; ranking by margin alone would bury it.+ expect(result.verdict).toBe('contradicts');+ expect(result.clauseId).toMatch(/^(PRD|GOALS)\.md#/);+ expect(result.advisory).toContain('works against');+ expect(result.advisory).toContain('Not a gate');+ });++ it('surfaces an unavailable scorer as itself rather than silently reporting no finding', async () => {+ decide.mockResolvedValue({ ok: false, code: 'jev-not-installed' });+ expect(await score()).toEqual({ ok: false, code: 'jev-not-installed' });+ });++ it('refuses a checkout with no product documents instead of grading it against this install\'s PRD', async () => {+ const empty = await mkdtemp(join(tmpdir(), 'portos-scope-empty-'));+ expect(await score({ repoPath: empty })).toEqual({ ok: false, code: 'scope-adherence-corpus-missing' });+ expect(await score({ repoPath: '' })).toEqual({ ok: false, code: 'scope-adherence-corpus-missing' });+ expect(decide).not.toHaveBeenCalled();+ await rm(empty, { recursive: true, force: true });+ });++ it('rereads the corpus after the product documents change on disk', async () => {+ const first = await loadClauseCorpus(repoPath);+ await writeFile(join(repoPath, 'PRD.md'), `${PRD}\n## Added\n\nA newly stated requirement that did not exist a moment ago.\n`);+ const second = await loadClauseCorpus(repoPath);+ expect(second.clauses.length).toBe(first.clauses.length + 1);+ });++ it('distinguishes an unreadable corpus from an absent one', async () => {+ const broken = await mkdtemp(join(tmpdir(), 'portos-scope-broken-'));+ // A directory where a file is expected: readable path, unreadable file.+ await mkdir(join(broken, 'PRD.md'));+ await mkdir(join(broken, 'GOALS.md'));+ expect(await loadClauseCorpus(broken)).toEqual({ ok: false, code: 'scope-adherence-corpus-unreadable' });+ await rm(broken, { recursive: true, force: true });+ });+});++describe('the advisory contract', () => {+ it('returns advisory fields only — nothing a caller could branch a write on', async () => {+ decide.mockResolvedValue({ ok: true, abstained: false, choice: hypothesis('contradicts'), margin: 0.8, confidence: 0.9 });+ const result = await score();+ expect(Object.keys(result).sort()).toEqual(['advisory', 'clause', 'clauseId', 'margin', 'ok', 'scored', 'verdict']);+ });++ it('keeps every scope-adherence module free of write, label, and task-spawn calls', async () => {+ // The acceptance criterion "no write path acts on the verdict", enforced+ // where a regression would actually appear: the day someone adds+ // `gh issue close` or a label write here, this fails. ETHOS.md treats the+ // absence of a gate as the feature, not an omission.+ const root = join(import.meta.dirname, '..');+ const sources = await Promise.all([+ readFile(join(root, 'services', 'scopeAdherence.js'), 'utf8'),+ readFile(join(root, 'lib', 'scopeAdherence.js'), 'utf8'),+ readFile(join(root, 'routes', 'apps', 'scopeAdherence.js'), 'utf8'),+ ]);+ const forbidden = /\b(writeFile|atomicWrite|createCachedStore|addLabel|add-label|issue close|createTask|addTask|spawnAgent)\b/;+ for (const source of sources) {+ // Comments narrate what the feature refuses to do, so only real code lines count.+ const code = source.split('\n').filter((line) => !/^\s*(\*|\/\/|\/\*)/.test(line)).join('\n');+ expect(code).not.toMatch(forbidden);+ }+ });+});