Skip to content

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

refactor: register scope adherence as a shared jev decision instead of a second copy of one (#7643)

[._.]/ Adam Eivyd559a8b8a81e
diff --git a/client/src/components/apps/ScopeAdherenceCheck.jsx b/client/src/components/apps/ScopeAdherenceCheck.jsx
index 7f0195cad5..fabdf1a54f 100644
--- a/client/src/components/apps/ScopeAdherenceCheck.jsx
+++ b/client/src/components/apps/ScopeAdherenceCheck.jsx
@@ -2,6 +2,7 @@ import { useCallback, useState } from 'react';
import { Scale } from 'lucide-react';
import Pill from '../ui/Pill';
import BrailleSpinner from '../BrailleSpinner';
+import { scopeAdherenceReasonLabel } from '../../lib/scopeAdherenceReasons';
import { useInstanceFeatures } from '../../hooks/useInstanceFeatures';
import { scoreAppScopeAdherence } from '../../services/api';
@@ -12,34 +13,19 @@ import { scoreAppScopeAdherence } from '../../services/api';
* 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.
+ * hidden, no claim or merge is blocked. The output is 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".
+ * 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);
@@ -58,6 +44,8 @@ export default function ScopeAdherenceCheck({ appId, kind, title, body = '', dif
if (!isFeatureEnabled('jev')) return null;
+ const verdict = result?.ok ? result.verdict : null;
+
return (
<div className="mt-2 flex flex-wrap items-center gap-2 text-xs">
<button
@@ -71,23 +59,21 @@ export default function ScopeAdherenceCheck({ appId, kind, title, body = '', dif
{scoring ? 'Scoring…' : 'Check scope'}
</button>
- {result?.ok && result.verdict !== 'abstained' && (
+ {verdict && 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>
+ <Pill tone={TONE[verdict]} size="xs">{LABEL[verdict]}</Pill>
+ {/* The clause, not just the score. A bare margin is noise. The
+ citation is composed server-side so its spelling has one home. */}
+ <span className="text-gray-400">{result.clause?.citation}</span>
<span className="text-gray-600 italic">advisory only</span>
</>
)}
- {result?.ok && result.verdict === 'abstained' && (
+ {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>}
+ {result && !result.ok && <span className="text-gray-500">{scopeAdherenceReasonLabel(result.code)}</span>}
</div>
);
}
diff --git a/client/src/components/apps/ScopeAdherenceCheck.test.jsx b/client/src/components/apps/ScopeAdherenceCheck.test.jsx
index e541701530..4f4df4efa2 100644
--- a/client/src/components/apps/ScopeAdherenceCheck.test.jsx
+++ b/client/src/components/apps/ScopeAdherenceCheck.test.jsx
@@ -40,7 +40,7 @@ describe('ScopeAdherenceCheck', () => {
ok: true,
verdict: 'contradicts',
clauseId: 'PRD.md#out-of-scope:abc12345',
- clause: { sourceFile: 'PRD.md', headingPath: 'Out of Scope' },
+ clause: { sourceFile: 'PRD.md', headingPath: 'Out of Scope', citation: 'PRD.md § Out of Scope' },
margin: 0.41,
});
diff --git a/client/src/components/apps/tabs/PullRequestsTab.jsx b/client/src/components/apps/tabs/PullRequestsTab.jsx
index 6e90357874..4035d159bf 100644
--- a/client/src/components/apps/tabs/PullRequestsTab.jsx
+++ b/client/src/components/apps/tabs/PullRequestsTab.jsx
@@ -651,15 +651,11 @@ export default function PullRequestsTab({ appId, appName }) {
</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(' → ')}
- />
+ Title alone: this listing carries no PR description,
+ and branch names here are `claim/issue-N` /
+ `cos/<task>/<agent>`, which would feed the code-side
+ retrieval view pure noise rather than vocabulary. */}
+ <ScopeAdherenceCheck appId={appId} kind="pr" title={pullRequest.title || ''} />
</div>
<div className="shrink-0 lg:pt-0.5 flex flex-wrap items-start gap-2">
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index c979e45b90..3824e021d8 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -266,6 +266,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `mindBundle.js` | Persistent Mind portable-bundle format vocabulary, re-exported from the `server/lib/mindBundleFormat.js` leaf (never copied): file extension, passphrase floor, size cap, export scopes, and the import group ids / source scopes / choice values the import panel renders. The sealing code stays server-side — that module imports node `crypto`. |
| `publicGuestRoutes.js` | `isPublicGuestRoute` identifies standalone guest pages that skip private app bootstrap. |
| `riggingReasons.js` | Client mirror of the character-rigging readiness reason labels in `server/services/rigging/readiness.js`: `RIGGING_UNAVAILABLE_REASONS` (reason code -> user-facing label), `RIGGING_REASON_FALLBACK`, and `riggingReasonLabel(code, fallback?)`. Render these anywhere a `GET /api/rigging/readiness` reason is shown; never re-declare the codes. Parity + code coverage enforced by `server/services/rigging/unavailableReasons.parity.test.js`. |
+| `scopeAdherenceReasons.js` | Client mirror of the failure codes `POST /api/apps/:id/scope-adherence` can return instead of a verdict: `SCOPE_ADHERENCE_REASONS` (code -> operator-facing label), `SCOPE_ADHERENCE_REASON_FALLBACK`, and `scopeAdherenceReasonLabel(code, fallback?)` (own-property lookup, so a code naming an `Object.prototype` key cannot render as a function). Every label reads as "no advisory", never as a verdict. Coverage of the server codes is enforced by `server/services/scopeAdherence.reasons.parity.test.js`. |
| `usagePeriods.js` | The report windows every usage-cost surface offers — `USAGE_PERIOD_OPTIONS`, `DEFAULT_USAGE_PERIOD` (what a URL with no `?period` means) and `resolveUsagePeriod`. Shared because `?period` is a URL param the user carries between the Usage and Subscriptions pages; two copies had already disagreed on the default. |
| `usdzExport.js` | AR Quick Look (USDZ) export for the 3D viewer (#5756): `exportSceneToUsdz(scene, { maxTextureSize })` lazy-loads three's `USDZExporter` and serializes the already-decoded scene to bytes, `countSceneTriangles(object3d)` measures an object graph against `AR_TRIANGLE_BUDGET`, and `supportsArQuickLook()` feature-detects the `<a rel="ar">` handoff (Safari on iOS/iPadOS only — never sniff the user agent) so a desktop is offered a download instead of a button that does nothing. `AR_MAX_TEXTURE_SIZE` bounds the file: USDZ stores every texel raw, with no Draco/meshopt equivalent. |
| `installFailureTask.js` | Build the CoS task payload behind the installer-failure "Queue agent to investigate" button (#5981): `buildInstallFailureTask({ label, stage, error, logs, surface })` → `{ description, prompt }` carrying the installer name, failing stage, error text and a bounded log tail, and `installLogTail(logs)` (the `useInstallStream` `{ kind, text }` entries rendered as text, capped at `INSTALL_FAILURE_LOG_TAIL_LINES` / `INSTALL_FAILURE_LOG_TAIL_CHARS` so a 1000-line pip stream cannot push a huge body through `POST /api/cos/tasks`, cutting on a line boundary, redacting the home-directory paths pip/git echo, and neutralizing a log line that would close the prompt fence). Shared by both install modals and `LocalSetupPanel` so every surface queues the same reproducible context. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 99a839cfab..2abcfa8cec 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -226,6 +226,7 @@ export * from './wrSceneCursor.js';
export * from './writingGuide.js';
export * from './qrCode.js';
export * from './riggingReasons.js';
+export * from './scopeAdherenceReasons.js';
export * from './usagePeriods.js';
export * from './usdzExport.js';
export * from './eidoverseFrame.js';
diff --git a/client/src/lib/scopeAdherenceReasons.js b/client/src/lib/scopeAdherenceReasons.js
new file mode 100644
index 0000000000..e6ca18d382
--- /dev/null
+++ b/client/src/lib/scopeAdherenceReasons.js
@@ -0,0 +1,47 @@
+/**
+ * Operator-facing labels for the codes `scoreAdherence` can return instead of
+ * a verdict (`server/services/scopeAdherence.js`).
+ *
+ * The client can't import the server module — it reaches `node:fs` and, past
+ * the jev router, the sidecar lifecycle — so this is a hand-maintained mirror,
+ * the same shape as `riggingReasons.js`. Coverage is asserted by
+ * `server/services/scopeAdherence.reasons.parity.test.js`, which fails when a
+ * code the service can return has no label here and would therefore render as
+ * the generic fallback with a fully green suite.
+ *
+ * Names are prefixed (`SCOPE_ADHERENCE_…`) because every module in this
+ * directory is a flat `export *` member of one barrel, where a shared
+ * identifier is a collision.
+ *
+ * Every label reads as "no advisory", never as a verdict. A scorer that could
+ * not answer has said nothing about the change.
+ */
+
+export const SCOPE_ADHERENCE_REASONS = Object.freeze({
+ // Reachable only in a race — the panel hides itself when the feature is off,
+ // but the toggle can move between render and response.
+ '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.',
+ 'jev-request-invalid': 'The local scorer rejected the request for this change.',
+ 'jev-response-invalid': 'The local scorer returned an answer PortOS could not read.',
+ 'jev-premise-too-large': 'This change is too large for the local scorer to read at once.',
+});
+
+export const SCOPE_ADHERENCE_REASON_FALLBACK = 'The local scorer could not answer for this change.';
+
+/**
+ * Label for a reason code.
+ *
+ * Own-property lookup only: `REASONS[code] || fallback` on a code that happens
+ * to name an `Object.prototype` key (`toString`, `constructor`) returns a
+ * function, and React throws when one is rendered as a child.
+ */
+export function scopeAdherenceReasonLabel(reason, fallback = SCOPE_ADHERENCE_REASON_FALLBACK) {
+ return Object.hasOwn(SCOPE_ADHERENCE_REASONS, reason ?? '') ? SCOPE_ADHERENCE_REASONS[reason] : fallback;
+}
diff --git a/docs/features/scope-adherence.md b/docs/features/scope-adherence.md
index 7b9b7ce6cc..c81c6c8aa5 100644
--- a/docs/features/scope-adherence.md
+++ b/docs/features/scope-adherence.md
@@ -14,18 +14,20 @@ Under an expanded row in an app's **Issues** tab, and under each row in its **Pu
## How a verdict is produced
```
-screenUntrustedContent() ← Prompt Guard. Unchanged, and not optional.
- ↓ safe
-parse PRD.md + GOALS.md ← server/lib/prdClauses.js
+parse PRD.md + GOALS.md ← server/lib/prdClauses.js. No model.
↓ clauses
-retrieve top-k candidates ← BM25 × 2 views, fused with RRF
+retrieve top-k candidates ← BM25 × 2 views, fused with RRF. No model.
↓ ≤ k clauses
-decide() per clause ← server/services/jev.js. Abstains on a near-tie.
+screenUntrustedContent() ← Prompt Guard. Unchanged, and not optional.
+ ↓ safe
+runJevDecision('scope-adherence') ← once per clause. 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.
+An issue or PR body is attacker-controlled text, so it passes phase 1 of the untrusted-content ladder before any model 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.
+
+The screen is not the first step, because the two steps above it are inert with respect to that text: reading the operator's own files, and tokenizing the change for an in-process BM25 query. A managed app with no PRD, or a change nothing in the corpus matches, can never produce an advisory — and making it pay a full model-abuse classifier run (possibly a sidecar cold start) to be told so is the only cost on this path that repeats per click. **The exact string that is screened is the exact string that enters every premise**, so the screened text and the scored text cannot drift apart.
### Clause parsing
@@ -35,11 +37,11 @@ A clause id is `<sourceFile>#<heading-path-slug>:<content-hash>` — **no line n
### 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.
+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 (a changed-file list, when the caller has one) — 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 Pull Requests tab passes title alone: that listing carries no description, and PortOS branch names (`claim/issue-N`, `cos/<task>/<agent>`) would feed the code-side view noise rather than vocabulary.
### 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.
+Frozen as the `scope-adherence` entry in `server/lib/jevDecisions.js`, beside the four untrusted-content rungs — PortOS's one registry of closed-set questions the local scorer may answer. They are the entire instruction surface of the feature, so one diff shows every question that can be asked, and registering there is also what gives this decision its abstention counters in the jev panel and its scorability contract test. It is the only entry with `source: null`: it asks about the operator's own documents, not about text that arrived on a channel.
| Verdict | Hypothesis |
|---|---|
@@ -47,11 +49,11 @@ Frozen in `server/lib/scopeAdherence.js`, for the same reason `lib/jevDecisions.
| `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.
+The premise is the clause first and in full, then the change. Both halves are capped well below the scorer's 32k premise bound — the clause at 2,000 characters and the change at 4,000 — because the change text is byte-identical in all k × 3 forward passes, so an unbounded issue body makes every pass prefill the same thousands of tokens to tell apart clauses that differ by at most 2,000 characters. Measured, that turns a ~5 s click into a ~40 s one.
### 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*.
+The floor is the decision's `minMargin: 0.2`, 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`.
@@ -85,7 +87,9 @@ Each reads as "no advisory" in the UI, never as a verdict.
| Piece | File |
|---|---|
| Clause parser | `server/lib/prdClauses.js` |
-| Hypotheses, retrieval, premise, route schema | `server/lib/scopeAdherence.js` |
+| The three hypotheses and the abstention floor | `server/lib/jevDecisions.js` (`scope-adherence`) |
+| Retrieval, premise composition, 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` |
+| Failure labels (client mirror) | `client/src/lib/scopeAdherenceReasons.js` |
diff --git a/server/lib/README.md b/server/lib/README.md
index c2c1c9c09b..701e3382ee 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -502,9 +502,9 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `localLlmCatalog.js` | Curated cross-backend (Ollama↔LM Studio) local-LLM catalog + install-id mapping for the migrate flow. Pure. |
| `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`. |
+| `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. `source` names the ingress CHANNEL and is `null` for a decision that has none (`scope-adherence` asks about the operator's own product documents). 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`. |
+| `scopeAdherence.js` | The retrieval and premise half of "does this change advance the stated product goal?" — the QUESTION itself is the `scope-adherence` entry in `jevDecisions.js`. `selectCandidateClauses` fuses two BM25 views of the change (prose, changed files) with `fuseRankingsRRF`, so scoring is bounded by k rather than the whole corpus; `buildClauseIndex` is exported so a caller can cache the index beside the corpus. `formatChangeEvidence` builds the change half ONCE — the same string is screened and scored, so the two cannot drift — and `composeAdherencePremise` puts the clause first and in full. Also 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/jevDecisions.js b/server/lib/jevDecisions.js
index d771262da4..5a07b8a493 100644
--- a/server/lib/jevDecisions.js
+++ b/server/lib/jevDecisions.js
@@ -17,6 +17,18 @@
import { JEV_DEFAULT_MIN_MARGIN, JEV_MAX_HYPOTHESIS_CHARS } from './jev.js';
/**
+ * `source` is the INGRESS CHANNEL a decision's premise arrives on, and it is
+ * `null` for a decision that has none.
+ *
+ * The four untrusted-content rungs each answer a question about text that
+ * arrived from somewhere (`github-issue`, `email`, …), and their channel is
+ * what `resolveUntrustedContentPolicy` keys the operator's per-source `jevMode`
+ * on. `scope-adherence` asks about the operator's OWN product documents
+ * instead, so there is no channel to name and no per-source policy to resolve —
+ * `null` says that explicitly rather than borrowing a channel it does not use.
+ * Nothing in `jevRouter.runJevDecision` reads this field; the contract test is
+ * what keeps a typo out of the four that do have one.
+ *
* Per-decision and per-option abstention floors.
*
* `minMargin` on the decision is the bar every option clears. `minMargin` on an
@@ -117,6 +129,38 @@ export const JEV_DECISIONS = Object.freeze({
}),
]),
}),
+
+ // The one decision here that is not a rung of the untrusted-content ladder:
+ // it asks whether a filed issue or an opened pull request advances a clause
+ // of the repository's own `PRD.md` / `GOALS.md`. It is scored once per
+ // candidate clause, so the premise — not the option set — carries which goal
+ // is being asked about.
+ //
+ // No per-option floor. Every outcome is a sentence rendered beside a row;
+ // none of them closes, labels, or blocks anything, so there is no asymmetry
+ // to protect against. The DECISION floor is wide instead: `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.
+ 'scope-adherence': Object.freeze({
+ source: null,
+ label: 'Product scope adherence',
+ minMargin: 0.2,
+ options: Object.freeze([
+ Object.freeze({
+ value: 'aligned',
+ hypothesis: 'The proposed change advances the stated product goal.',
+ }),
+ Object.freeze({
+ value: 'unrelated',
+ hypothesis: 'The proposed change is unrelated to the stated product goal.',
+ }),
+ Object.freeze({
+ value: 'contradicts',
+ hypothesis: 'The proposed change works against the stated product goal.',
+ }),
+ ]),
+ }),
});
export const JEV_DECISION_IDS = Object.freeze(Object.keys(JEV_DECISIONS));
diff --git a/server/lib/jevDecisions.test.js b/server/lib/jevDecisions.test.js
index d34e6d804b..cee8c4e943 100644
--- a/server/lib/jevDecisions.test.js
+++ b/server/lib/jevDecisions.test.js
@@ -20,7 +20,13 @@ describe('shipped jev decisions', () => {
const decision = JEV_DECISIONS[id];
expect(isValidJevDecision(decision), id).toBe(true);
expect(decision.options.length, id).toBeLessThanOrEqual(JEV_MAX_HYPOTHESES);
- expect(UNTRUSTED_CONTENT_SOURCES, id).toContain(decision.source);
+ // `source` is the ingress CHANNEL, and `null` for a decision that has
+ // none (see the field's note in jevDecisions.js). A channel-free
+ // decision must say so with an explicit null rather than by omitting the
+ // key, or a typo'd channel would read as "not a channel" and skip this
+ // guard entirely.
+ expect(Object.hasOwn(decision, 'source'), id).toBe(true);
+ if (decision.source !== null) expect(UNTRUSTED_CONTENT_SOURCES, id).toContain(decision.source);
expect(typeof decision.label, id).toBe('string');
}
expect(isValidJevDecision({ minMargin: 0.2, options: [{ value: 'a', hypothesis: 'a'.repeat(JEV_MAX_HYPOTHESIS_CHARS + 1) }, { value: 'b', hypothesis: 'b' }] })).toBe(false);
@@ -74,6 +80,7 @@ describe('shipped jev decisions', () => {
'message-triage': z.enum(['reply', 'archive', 'delete', 'review']),
'message-priority': z.enum(['high', 'medium', 'low']),
'forge-maintenance-disposition': z.enum(['inspect-trusted-change', 'defer']),
+ 'scope-adherence': z.enum(['aligned', 'unrelated', 'contradicts']),
};
expect(Object.keys(enums).sort()).toEqual([...JEV_DECISION_IDS].sort());
for (const [id, contract] of Object.entries(enums)) {
diff --git a/server/lib/prdClauses.js b/server/lib/prdClauses.js
index 38fe53108c..25c78a3d8f 100644
--- a/server/lib/prdClauses.js
+++ b/server/lib/prdClauses.js
@@ -23,7 +23,12 @@
* shortening the display cap does not re-key the corpus.
*/
+// Direct `crypto`, not `sha256Text` from `fileCore.js`: that module's closure
+// reaches `fs` and `child_process`, and this file advertises itself as a pure
+// leaf on the request path (`server/lib/importScoping.test.js`).
import { createHash } from 'crypto';
+import { kebabCase, truncateOnBoundary, clampToCharLimit } from './textUtils.js';
+import { stripMarkdownEmphasis } from './markdownText.js';
/** The documents PortOS scores its own changes against. */
export const PRD_CLAUSE_SOURCES = Object.freeze(['PRD.md', 'GOALS.md']);
@@ -49,19 +54,19 @@ 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);
+// `truncateOnBoundary`, not a bare `.slice()`: a clause id is meant to be read
+// by a human, and a hard cut leaves it ending mid-word with a dangling hyphen.
+const slug = (text) => truncateOnBoundary(kebabCase(text), 60);
/** Strip the markdown that carries no meaning for an entailment scorer. */
function flatten(text) {
- return text
+ // Images are unwrapped first: the shared helper's link rule would otherwise
+ // leave the `!` behind. `stripMarkdownEmphasis` additionally drops HTML
+ // comments — an editorial `<!-- note -->` in a PRD would otherwise become
+ // part of a scored "product goal" — and replaces a lone `*_~` with a space
+ // rather than deleting it, so an unbalanced marker cannot fuse two words.
+ return stripMarkdownEmphasis(String(text).replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1'))
.replace(/^\s*>+\s?/gm, '')
- .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')
- .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
- .replace(/[*_`]+/g, '')
.replace(/\s+/g, ' ')
.trim();
}
@@ -97,7 +102,7 @@ function countTopLevelHeadings(lines) {
*
* @param {string} markdown Raw file contents.
* @param {{ sourceFile?: string }} options `sourceFile` is part of every id.
- * @returns {Array<{ id, heading, headingPath, text, sourceFile, line }>}
+ * @returns {Array<{ id, headingPath, text, sourceFile, line }>}
*/
export function parsePrdClauses(markdown, { sourceFile = 'PRD.md' } = {}) {
if (typeof markdown !== 'string' || !markdown.trim()) return [];
@@ -136,9 +141,11 @@ export function parsePrdClauses(markdown, { sourceFile = 'PRD.md' } = {}) {
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,
+ // `clampToCharLimit` backs off to a sentence/clause boundary; a hard cut
+ // mid-word reads as a different requirement to a cross-encoder than the
+ // one that was written.
+ text: clampToCharLimit(raw, PRD_MAX_CLAUSE_CHARS).text,
sourceFile,
line,
});
diff --git a/server/lib/scopeAdherence.js b/server/lib/scopeAdherence.js
index a3f13c674e..bde7761859 100644
--- a/server/lib/scopeAdherence.js
+++ b/server/lib/scopeAdherence.js
@@ -1,113 +1,104 @@
/**
- * 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.
+ * The retrieval and premise half of "does this change advance what the product
+ * says it is for?".
*
- * 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.
+ * The QUESTION itself — the three hypotheses and the abstention floor — is a
+ * `scope-adherence` entry in `lib/jevDecisions.js`, beside the four
+ * untrusted-content rungs, because that is PortOS's one registry of closed-set
+ * questions the local scorer may answer, and registering there is what gives
+ * this decision its agreement counters and its scorability contract test. What
+ * lives here is everything that registry deliberately does not model: which
+ * CLAUSE to ask about, and how a clause plus a change become one premise.
*
- * Pure: no I/O, no scorer, no file reads. `services/scopeAdherence.js` owns
- * the ladder (screen → jev → advisory verdict).
+ * ADVISORY ONLY, BY CONSTRUCTION. Nothing in this module or its service returns
+ * a boolean a caller could gate on. [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 → retrieve → decide → 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 { clampToCharLimit } from './textUtils.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));
+/** The `lib/jevDecisions.js` entry this surface asks. */
+export const SCOPE_ADHERENCE_DECISION_ID = 'scope-adherence';
/**
- * Abstention floor.
+ * How many clauses are scored per change.
*
- * 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.
+ * Each clause costs one forward pass per hypothesis through a 4B model —
+ * `run_jev.py` holds a global lock and does not batch — so scoring the whole
+ * corpus would cost minutes for a verdict that cites one clause. Retrieval
+ * picks the few worth asking about.
*/
-export const SCOPE_ADHERENCE_MIN_MARGIN = 0.2;
+export const SCOPE_ADHERENCE_TOP_K = 3;
/**
- * How many clauses are scored per change.
+ * Per-premise cap on the CHANGE half.
*
- * 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.
+ * Deliberately close to `PRD_MAX_CLAUSE_CHARS` rather than "whatever is left of
+ * the scorer's 32k premise bound": the change text is byte-identical in every
+ * one of the k × 3 forward passes, so an unbounded body makes each pass prefill
+ * thousands of tokens of the same boilerplate in order to tell apart clauses
+ * that differ by at most 2,000 characters. Measured, a 20,000-character issue
+ * body turns a ~5 s click into a ~40 s one, and none of the extra tokens are
+ * informative.
*/
-export const SCOPE_ADHERENCE_TOP_K = 3;
+export const SCOPE_ADHERENCE_MAX_CHANGE_CHARS = 4_000;
/** 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.
+ * The BM25 index for a clause corpus.
+ *
+ * Exported so a caller that already caches the parsed corpus can cache this
+ * beside it: building the index over PortOS's own ~175 clauses measures ~13 ms,
+ * three times the cost of the parse that the corpus cache exists to avoid.
+ */
+export const buildClauseIndex = (clauses) =>
+ buildInvertedIndex(clauses.map((clause) => ({ id: clause.id, text: clause.text })));
+
+/**
+ * Pick the clauses worth scoring, best match 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.
+ * 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.
*
+ * @param {Array} clauses The corpus.
+ * @param {{title?: string, body?: string, diffSummary?: string}} change Already normalized.
+ * @param {{k?: number, index?: object}} options A prebuilt `index` skips the rebuild.
* @returns {Array} up to `k` clauses, in fused-rank order.
*/
-export function selectCandidateClauses(clauses, change, { k = SCOPE_ADHERENCE_TOP_K } = {}) {
+export function selectCandidateClauses(clauses, change, { k = SCOPE_ADHERENCE_TOP_K, index } = {}) {
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);
+ const narrative = [change?.title, change?.body].filter(Boolean).join('\n');
+ const code = change?.diffSummary || '';
if (!narrative && !code) return [];
- const index = buildInvertedIndex(corpus.map((clause) => ({ id: clause.id, text: clause.text })));
+ const bm25Index = index || buildClauseIndex(corpus);
// 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 }) : []),
+ asRanking(narrative ? search(narrative, bm25Index, { limit }) : []),
+ asRanking(code ? search(code, bm25Index, { limit }) : []),
{ ftsWeight: NARRATIVE_WEIGHT, vectorWeight: CODE_WEIGHT },
);
@@ -119,50 +110,34 @@ export function selectCandidateClauses(clauses, change, { k = SCOPE_ADHERENCE_TO
.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 change, rendered as the evidence half of a premise.
*
- * 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.
+ * Built ONCE and handed to both the untrusted-content screen and every
+ * premise. Screening a separately-assembled subset of the same fields is what
+ * lets the screened text and the scored text drift apart, and
+ * `services/untrustedContent.js` states the invariant this inherits: the
+ * scorer never sees content phase 1 has not seen.
*/
-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;
+export function formatChangeEvidence(change) {
+ const lines = [`Proposed change (${change?.kind === 'pr' ? 'pull request' : 'issue'}):`];
+ 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}`);
+ return clampToCharLimit(lines.join('\n'), SCOPE_ADHERENCE_MAX_CHANGE_CHARS).text;
}
/**
- * The one-line advisory a surface renders.
+ * Build the premise for one (clause, evidence) pair.
*
- * 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.
+ * The clause is stated FIRST and in full. Both halves are already capped well
+ * below the scorer's premise bound, so nothing is clipped here — a clipped goal
+ * would have the scorer answering about half a requirement with no way to tell
+ * that it had.
*/
-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.`;
+export function composeAdherencePremise({ clause, evidence } = {}) {
+ if (!clause?.text || !evidence?.trim()) return null;
+ return `Stated product goal (${formatClauseCitation(clause)}):\n${clause.text}\n\n${evidence}`;
}
/**
diff --git a/server/routes/apps/scopeAdherence.js b/server/routes/apps/scopeAdherence.js
index 06b7c64b4c..9917e86698 100644
--- a/server/routes/apps/scopeAdherence.js
+++ b/server/routes/apps/scopeAdherence.js
@@ -38,10 +38,7 @@ router.post('/:id/scope-adherence', loadApp, asyncHandler(async (req, res) => {
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 ?? '',
+ repoPath: req.loadedApp.repoPath,
}));
}));
diff --git a/server/routes/apps/scopeAdherence.test.js b/server/routes/apps/scopeAdherence.test.js
index 8ca82f78b0..350793dcc6 100644
--- a/server/routes/apps/scopeAdherence.test.js
+++ b/server/routes/apps/scopeAdherence.test.js
@@ -13,9 +13,8 @@ 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 },
+ clause: { id: 'PRD.md#out-of-scope:abc12345', sourceFile: 'PRD.md', headingPath: 'Out of Scope', citation: 'PRD.md § 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,
};
@@ -56,15 +55,15 @@ describe('POST /api/apps/:id/scope-adherence', () => {
expect(scoreAdherence).not.toHaveBeenCalled();
});
- it('never falls back to this install\'s own checkout for an app with no repository', async () => {
+ it('forwards an app\'s missing repository as-is rather than inventing one', 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: '' }));
+ // `scoreAdherence` requires `repoPath` and has no default, so an app with
+ // no checkout answers `scope-adherence-corpus-missing` instead of being
+ // graded against PortOS's own PRD.
+ expect(scoreAdherence).toHaveBeenCalledWith(expect.objectContaining({ repoPath: undefined }));
});
it('404s for an unknown app without scoring anything', async () => {
diff --git a/server/services/scopeAdherence.js b/server/services/scopeAdherence.js
index 108b61e9b2..868c4b1964 100644
--- a/server/services/scopeAdherence.js
+++ b/server/services/scopeAdherence.js
@@ -2,13 +2,22 @@
* 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.
+ * read PRD.md + GOALS.md ← the operator's own checkout. No model.
+ * ↓ clauses
+ * retrieve top-k candidates ← BM25 + RRF, in process. No model.
+ * ↓ ≤ k clauses
+ * screenUntrustedContent() ← Prompt Guard. Unchanged, and not optional.
* ↓ safe
- * retrieve top-k clauses ← BM25 + RRF over PRD.md / GOALS.md
+ * runJevDecision() per clause ← the shared `scope-adherence` rung.
* ↓
- * decide() per clause ← phase 2, local. Abstains rather than guessing.
- * ↓
- * one advisory line naming the clause
+ * one advisory naming the clause
+ *
+ * The two inert steps run FIRST on purpose. A managed app with no `PRD.md`, or
+ * a change nothing in the corpus matches, can never produce an advisory, and
+ * making it pay a full model-abuse classifier run — possibly a sidecar cold
+ * start — to be told so is the one cost on this path that repeats per click.
+ * The screen still lands before the first `decide()`, which is where the
+ * untrusted-content contract actually requires it.
*
* 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
@@ -20,25 +29,32 @@
*
* 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.
+ * included in a status or capability payload. The one thing that IS recorded
+ * is the shared jev agreement counter — counts only, never a premise.
*/
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 { formatClauseCitation, parsePrdClauses, PRD_CLAUSE_SOURCES } from '../lib/prdClauses.js';
import {
+ buildClauseIndex,
composeAdherencePremise,
- formatAdherenceAdvisory,
- SCOPE_ADHERENCE_HYPOTHESES,
- SCOPE_ADHERENCE_MIN_MARGIN,
+ formatChangeEvidence,
+ SCOPE_ADHERENCE_DECISION_ID,
SCOPE_ADHERENCE_TOP_K,
selectCandidateClauses,
- verdictForHypothesis,
} from '../lib/scopeAdherence.js';
-/** Every way `scoreAdherence` can decline to produce a verdict. */
+/**
+ * The codes this service adds on top of the shared `JEV_FAILURE_CODES` and the
+ * untrusted-content ones, which it forwards unchanged.
+ *
+ * Load-bearing: `server/services/scopeAdherence.reasons.parity.test.js` asserts
+ * the client's operator-facing label map covers every one of them, so a code
+ * added here without a label fails rather than silently rendering as the
+ * generic fallback.
+ */
export const SCOPE_ADHERENCE_FAILURE_CODES = Object.freeze([
'scope-adherence-disabled',
'scope-adherence-change-empty',
@@ -59,9 +75,10 @@ const failure = (code) => ({ ok: false, code });
*/
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.
+// Cache the parsed corpus AND its BM25 index per repository, invalidated on
+// either file's mtime. The index is the larger half: building it over PortOS's
+// own ~175 clauses measures ~13 ms, three times the parse this cache was
+// introduced to avoid, and it is per-corpus rather than per-change.
const corpusCache = new Map();
async function fileStamp(path) {
@@ -71,32 +88,34 @@ async function fileStamp(path) {
/**
* 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.
+ * `repoPath` is REQUIRED and has no default. Defaulting it to this install's
+ * own checkout would mean an app record with a missing `repoPath` silently
+ * gets graded against PortOS's PRD instead of its own.
+ *
+ * Three outcomes, never collapsed: a corpus, `corpus-missing` (this repository
+ * states no product intent — fixable by writing a PRD), and
+ * `corpus-unreadable` (the files are there and we could not read them — a
+ * broken install). The middle and last point at opposite remedies.
*/
-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.
+export async function loadClauseCorpus(repoPath) {
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 paths = PRD_CLAUSE_SOURCES.map((name) => join(repoPath, name));
+ const stamps = await Promise.all(paths.map(fileStamp));
+ const key = stamps.join('|');
const cached = corpusCache.get(repoPath);
if (cached?.key === key) return cached.result;
+ const reads = await Promise.all(paths.map((path) => tryReadFileStrict(path)));
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 }));
- }
+ reads.forEach(({ ok, value }, position) => {
+ if (!ok) { unreadable = true; return; }
+ if (typeof value === 'string') clauses.push(...parsePrdClauses(value, { sourceFile: PRD_CLAUSE_SOURCES[position] }));
+ });
- const result = unreadable && !clauses.length
- ? failure('scope-adherence-corpus-unreadable')
- : { ok: true, clauses };
+ const result = clauses.length
+ ? { ok: true, clauses, index: buildClauseIndex(clauses) }
+ : failure(unreadable ? 'scope-adherence-corpus-unreadable' : 'scope-adherence-corpus-missing');
corpusCache.set(repoPath, { key, result });
return result;
}
@@ -112,75 +131,78 @@ export const resetClauseCorpusCache = () => corpusCache.clear();
* @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 {string} change.repoPath Checkout holding the product documents. Required.
* @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}>}
+ * @returns {Promise<{ok: true, verdict: 'aligned'|'unrelated'|'contradicts'|'abstained', clauseId: string|null, clause: object|null, margin: number|null, scored: number} | {ok: false, code: string}>}
*/
export async function scoreAdherence({
kind = 'issue',
title = '',
body = '',
diffSummary = '',
- repoPath = PATHS.root,
+ repoPath,
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
+ // Deferred: `jevRouter` reaches the instance-feature graph and, through it,
+ // the sidecar lifecycle and the pinned 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');
+ const { isJevFeatureEnabled, recordJevObservations, runJevDecision } = await import('./jevRouter.js');
if (!await isJevFeatureEnabled()) return failure('scope-adherence-disabled');
+ // Normalized ONCE, here. The route's schema has already trimmed what it
+ // validates, but this is also the entry point for a direct service caller.
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');
+ const corpus = await loadClauseCorpus(repoPath);
+ if (!corpus.ok) return corpus;
+ const candidates = selectCandidateClauses(corpus.clauses, change, { k: topK, index: corpus.index });
+ if (!candidates.length) return failure('scope-adherence-no-clause');
+
// 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.
+ // attacker-controlled text. The screened string is the SAME string that goes
+ // into every premise — screening a separately-assembled subset is what lets
+ // the screened text and the scored text drift apart.
+ const evidence = formatChangeEvidence(change);
const { screenUntrustedContent } = await import('./untrustedContent.js');
const screened = await screenUntrustedContent({
- content: [change.title, change.body].filter(Boolean).join('\n\n'),
+ content: evidence,
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 = [];
+ const observations = [];
let widestAbstention = null;
for (const clause of candidates) {
- const premise = composeAdherencePremise({ clause, change });
+ const premise = composeAdherencePremise({ clause, evidence });
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
+ const scored = await runJevDecision({ decisionId: SCOPE_ADHERENCE_DECISION_ID, premise });
+ observations.push({ decisionId: SCOPE_ADHERENCE_DECISION_ID, kind: scored.kind });
+ // An unavailable scorer is reported once, as itself, and stops the loop —
+ // the remaining clauses would fail identically. 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.ok) {
+ await recordJevObservations(observations);
+ 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 });
+ decided.push({ verdict: scored.value, clause, margin: scored.margin });
}
+ // Counts only — which decision, which bucket. Never a premise, a clause, or
+ // anything about what was analyzed. This is what puts the scope scorer's
+ // abstention rate in the same panel table as the triage decisions.
+ await recordJevObservations(observations);
+
if (!decided.length) {
- return {
- ok: true,
- verdict: 'abstained',
- clauseId: null,
- clause: null,
- margin: widestAbstention,
- advisory: formatAdherenceAdvisory({}),
- scored: candidates.length,
- };
+ return { ok: true, verdict: 'abstained', clauseId: null, clause: null, margin: widestAbstention, scored: candidates.length };
}
decided.sort((a, b) => (VERDICT_RANK[a.verdict] - VERDICT_RANK[b.verdict]) || (b.margin - a.margin));
@@ -189,9 +211,11 @@ export async function scoreAdherence({
ok: true,
verdict: best.verdict,
clauseId: best.clause.id,
- clause: best.clause,
+ // The citation ships as a FIELD rather than being re-spelled in the
+ // browser: the separator and the no-heading-path case would otherwise have
+ // two implementations, and a change to one would leave the other green.
+ clause: { ...best.clause, citation: formatClauseCitation(best.clause) },
margin: best.margin,
- advisory: formatAdherenceAdvisory(best),
scored: candidates.length,
};
}
diff --git a/server/services/scopeAdherence.reasons.parity.test.js b/server/services/scopeAdherence.reasons.parity.test.js
new file mode 100644
index 0000000000..29f63d67b1
--- /dev/null
+++ b/server/services/scopeAdherence.reasons.parity.test.js
@@ -0,0 +1,56 @@
+/**
+ * Cross-package coverage for the scope-adherence failure labels.
+ *
+ * `server/services/scopeAdherence.js` owns the CODES; the labels live in
+ * `client/src/lib/scopeAdherenceReasons.js` because nothing on the server
+ * renders them. The mirror exists for the same reason `riggingReasons.js` does
+ * — the client cannot import the server module — and this suite is what stops
+ * a code added on one side from rendering as the generic fallback with a fully
+ * green suite.
+ *
+ * It asserts COVERAGE, not label equality: there is no server-side label map
+ * to compare against, and inventing one nothing renders would be the thing the
+ * reuse rule warns about.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { JEV_FAILURE_CODES } from '../lib/jev.js';
+import { SCOPE_ADHERENCE_FAILURE_CODES } from './scopeAdherence.js';
+import {
+ SCOPE_ADHERENCE_REASONS,
+ SCOPE_ADHERENCE_REASON_FALLBACK,
+ scopeAdherenceReasonLabel,
+} from '../../client/src/lib/scopeAdherenceReasons.js';
+
+describe('scope-adherence failure labels', () => {
+ it('labels every code the service adds', () => {
+ for (const code of SCOPE_ADHERENCE_FAILURE_CODES) {
+ expect(Object.hasOwn(SCOPE_ADHERENCE_REASONS, code), `${code} has no operator-facing label`).toBe(true);
+ }
+ });
+
+ it('labels every failure the scorer itself can report', () => {
+ // `scoreAdherence` forwards a `jev-*` code verbatim, so a new one in
+ // `lib/jev.js` silently degrades this surface to the generic fallback.
+ for (const code of JEV_FAILURE_CODES) {
+ expect(Object.hasOwn(SCOPE_ADHERENCE_REASONS, code), `${code} has no operator-facing label`).toBe(true);
+ }
+ });
+
+ it('labels nothing it does not need to', () => {
+ const owned = new Set([...SCOPE_ADHERENCE_FAILURE_CODES, ...JEV_FAILURE_CODES]);
+ // An untrusted-content block is forwarded too, but that vocabulary is the
+ // abuse guard's and is deliberately left to the shared fallback rather
+ // than restated here — so anything else is a stale key from a rename.
+ for (const code of Object.keys(SCOPE_ADHERENCE_REASONS)) {
+ expect(owned.has(code), `${code} is labelled but no longer returned`).toBe(true);
+ }
+ });
+
+ it('falls back rather than rendering a prototype member or a raw code', () => {
+ expect(scopeAdherenceReasonLabel('jev-timeout')).toBe(SCOPE_ADHERENCE_REASONS['jev-timeout']);
+ for (const probe of ['not-a-real-code', '', null, undefined, '__proto__', 'constructor', 'toString']) {
+ expect(scopeAdherenceReasonLabel(probe), `label for ${String(probe)}`).toBe(SCOPE_ADHERENCE_REASON_FALLBACK);
+ }
+ });
+});
diff --git a/server/services/scopeAdherence.test.js b/server/services/scopeAdherence.test.js
index f9bb2faf11..54780eb0f5 100644
--- a/server/services/scopeAdherence.test.js
+++ b/server/services/scopeAdherence.test.js
@@ -3,17 +3,20 @@ 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('./jevRouter.js', () => ({
+ isJevFeatureEnabled: vi.fn(),
+ runJevDecision: vi.fn(),
+ recordJevObservations: vi.fn(),
+}));
vi.mock('./untrustedContent.js', () => ({ screenUntrustedContent: vi.fn() }));
-vi.mock('./jev.js', () => ({ decide: vi.fn() }));
-const { isJevFeatureEnabled } = await import('./jevRouter.js');
+const { isJevFeatureEnabled, runJevDecision, recordJevObservations } = 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 { getJevDecision } = await import('../lib/jevDecisions.js');
-const hypothesis = (verdict) => SCOPE_ADHERENCE_OPTIONS.find((option) => option.verdict === verdict).hypothesis;
+const decided = (value, margin) => ({ ok: true, kind: 'decided', value, margin, confidence: margin });
+const abstained = (margin) => ({ ok: true, kind: 'abstained', abstained: true, margin });
const PRD = `# Example Product
@@ -55,7 +58,8 @@ beforeEach(async () => {
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 });
+ runJevDecision.mockResolvedValue(abstained(0.01));
+ recordJevObservations.mockResolvedValue(null);
});
afterEach(() => rm(repoPath, { force: true, recursive: true }));
@@ -75,14 +79,41 @@ describe('scoreAdherence', () => {
// 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();
+ expect(runJevDecision).not.toHaveBeenCalled();
});
- it('screens the change before scoring it, and reports a block with the screening code', async () => {
+ it('asks the shared jev registry entry, not a locally-worded question', async () => {
+ await score({ topK: 1 });
+ // The hypotheses are the whole instruction surface of the feature. They
+ // live in `lib/jevDecisions.js` beside the untrusted-content rungs so one
+ // diff shows every closed-set question the local scorer may be asked.
+ expect(runJevDecision).toHaveBeenCalledWith(expect.objectContaining({ decisionId: 'scope-adherence' }));
+ expect(getJevDecision('scope-adherence').options.map((option) => option.value))
+ .toEqual(['aligned', 'unrelated', 'contradicts']);
+ });
+
+ it('screens the exact text it then scores, 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();
+ expect(await score({ kind: 'issue', diffSummary: 'server/routes/public.js' }))
+ .toEqual({ ok: false, code: 'untrusted-content-blocked' });
+ expect(runJevDecision).not.toHaveBeenCalled();
+
+ const [[screenCall]] = screenUntrustedContent.mock.calls;
+ expect(screenCall.source).toBe('github-issue');
+ // The regression: `diffSummary` reaches the model inside the premise, so
+ // screening a title+body subset would let unscreened text past phase 1.
+ expect(screenCall.content).toContain('server/routes/public.js');
+ expect(screenCall.content).toContain('Route agent tasks');
+ });
+
+ it('reads the corpus and retrieves BEFORE screening, so a hopeless click costs no classifier run', async () => {
+ const empty = await mkdtemp(join(tmpdir(), 'portos-scope-empty-'));
+ expect(await score({ repoPath: empty })).toEqual({ ok: false, code: 'scope-adherence-corpus-missing' });
+ // Both steps are inert with respect to the untrusted text (file reads and
+ // in-process BM25), and most managed apps have no PRD at all — paying a
+ // model-abuse inference to be told so is the one cost that repeats.
+ expect(screenUntrustedContent).not.toHaveBeenCalled();
+ await rm(empty, { recursive: true, force: true });
});
it('scores at most topK clauses, never the whole corpus', async () => {
@@ -91,48 +122,61 @@ describe('scoreAdherence', () => {
// 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(runJevDecision.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 });
+ runJevDecision
+ .mockResolvedValueOnce(decided('aligned', 0.9))
+ .mockResolvedValueOnce(decided('contradicts', 0.3))
+ .mockResolvedValue(abstained(0.02));
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');
+ // The citation ships as a field so the browser never re-spells it.
+ expect(result.clause.citation).toMatch(/^(PRD|GOALS)\.md( § .+)?$/);
+ });
+
+ it('records counts for every clause it asked about, and nothing about the change', async () => {
+ runJevDecision.mockResolvedValueOnce(decided('aligned', 0.8)).mockResolvedValue(abstained(0.02));
+ await score({ topK: 2 });
+
+ const [[rows]] = recordJevObservations.mock.calls;
+ expect(rows).toEqual([
+ { decisionId: 'scope-adherence', kind: 'decided' },
+ { decisionId: 'scope-adherence', kind: 'abstained' },
+ ]);
+ // Counts only. A premise, a clause, or a margin tied to one would make the
+ // shared agreement file unsafe to leave on.
+ expect(JSON.stringify(rows)).not.toMatch(/Route agent tasks|PRD\.md/);
});
- 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('stops at an unavailable scorer, reports it as itself, and still records the attempt', async () => {
+ runJevDecision.mockResolvedValue({ ok: false, kind: 'unavailable', code: 'jev-not-installed' });
+ expect(await score({ topK: 3 })).toEqual({ ok: false, code: 'jev-not-installed' });
+ // The remaining clauses would fail identically, so one call is the whole
+ // cost of an uninstalled scorer.
+ expect(runJevDecision).toHaveBeenCalledTimes(1);
+ expect(recordJevObservations).toHaveBeenCalledWith([{ decisionId: 'scope-adherence', kind: 'unavailable' }]);
});
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' });
+ // No default `repoPath`: an app record that never set one must not silently
+ // be scored against PortOS's own goals.
+ expect(await score({ repoPath: undefined })).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 });
+ expect(runJevDecision).not.toHaveBeenCalled();
});
it('rereads the corpus after the product documents change on disk', async () => {
@@ -140,6 +184,9 @@ describe('scoreAdherence', () => {
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);
+ // The BM25 index is cached beside the corpus and must be rebuilt with it,
+ // or retrieval keeps answering from the superseded clause set.
+ expect(second.index.totalDocs).toBe(second.clauses.length);
});
it('distinguishes an unreadable corpus from an absent one', async () => {
@@ -154,27 +201,30 @@ describe('scoreAdherence', () => {
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 });
+ runJevDecision.mockResolvedValue(decided('contradicts', 0.8));
const result = await score();
- expect(Object.keys(result).sort()).toEqual(['advisory', 'clause', 'clauseId', 'margin', 'ok', 'scored', 'verdict']);
+ expect(Object.keys(result).sort()).toEqual(['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.
+ // where a regression would actually appear: the day someone adds a forge
+ // write or a task spawn 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/;
+ const forbidden = /(writeFile|atomicWrite|createCachedStore|\.mutate\(|addLabel|removeLabel|createTask|addTask|spawnAgent|runGh|execGh|ghJson|glabJson|'close'|"close"|issue close|pr merge)/;
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);
}
+ // The guard is only as good as its window: prove it fires on the shape it
+ // is meant to catch, so a rename cannot quietly turn it into a no-op.
+ expect("const x = await runGh('issue', 'close');").toMatch(forbidden);
});
});