Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: preserve complete Prompt Guard windows and verify repairs
[._.]/ Adam Eivy8eb618ed3d81
diff --git a/docs/PROMPT_GUARD_SETUP.md b/docs/PROMPT_GUARD_SETUP.mdindex 5e78adb2d2..0d81aa18dd 100644--- a/docs/PROMPT_GUARD_SETUP.md+++ b/docs/PROMPT_GUARD_SETUP.md@@ -18,9 +18,11 @@ node scripts/setup-prompt-guard.js --installBoth commands print JSON to stdout and exit 0 only when ready (1 otherwise).Install progress goes to stderr. `--status` never installs or runs inference;-`--install` explicitly downloads the pinned packages and model and runs the-benign end-to-end verification. It uses the same locally configured Hugging-Face token as the UI, without putting the token in command arguments. Run these commands from the primary installation after updating it. CoS+`--install` repairs the pinned packages, downloads the model only when its+pinned snapshot is missing, and verifies a complete multi-window benign input.+Cached model repairs work without a Hugging Face token or model download.+When downloading, it uses the same locally configured Hugging Face token as+the UI, without putting the token in command arguments. Run these commands from the primary installation after updating it. CoSworktrees deliberately use isolated data and ignore `PORTOS_DATA_ROOT`.Failure codes include `package-missing`, `package-version-mismatch`,@@ -35,3 +37,15 @@ a browser or curl succeeding does not prove Python can connect. Restore thatconnection and rerun `--install`. For `certificate-failed`, repair certificatetrust rather than disabling TLS verification. Gated Hugging Face access stillrequires account approval; a stored token alone does not grant it.++A helper process failure marks the classifier unhealthy until repair succeeds.+Status remains observational and never starts inference or downloads. Run the+existing `--install` command for automated recovery after updating PortOS; it+returns failure if verification fails, so automation must not proceed to review+on a nonzero exit. No repair can bypass a classifier finding.++A previous runner passed the short install canary but failed long PRs with+`security-guard-process-failed`: the installed tokenizer returned only a prefix+of the requested overflow windows. The runner now explicitly disables+truncation while encoding the complete input and slices overlapping windows+from those tokens, preserving full coverage and the pinned special tokens.diff --git a/scripts/run_prompt_guard.py b/scripts/run_prompt_guard.pyindex 35cd68680d..be214f034f 100644--- a/scripts/run_prompt_guard.py+++ b/scripts/run_prompt_guard.py@@ -56,25 +56,17 @@ def main() -> int:model.to("cpu")model.eval()- token_ids = tokenizer.encode(text, add_special_tokens=False)+ token_ids = tokenizer.encode(text, add_special_tokens=False, truncation=False)if not token_ids:raise ValueError("text has no model tokens")- if tokenizer.num_special_tokens_to_add(pair=False) != 2:+ # This pinned DeBERTa classifier uses [CLS] content [SEP]. Build windows+ # from the complete token stream: the installed tokenizer can discard+ # overflow beyond its embedded truncation before returning overflow windows.+ cls_id, sep_id = tokenizer.cls_token_id, tokenizer.sep_token_id+ if (tokenizer.num_special_tokens_to_add(pair=False) != 2+ or not isinstance(cls_id, int) or not isinstance(sep_id, int)):raise ValueError("model tokenizer window format changed")- # The supported tokenizer API works with both older installed runtimes- # and the pinned Transformers 5 runtime (prepare_for_model was removed).- # Overflow windows cover the entire input; truncation here splits windows- # and never discards the tail. The expected window count is checked below.- windows = tokenizer(- text,- add_special_tokens=True,- truncation=True,- max_length=MAX_CHUNK_TOKENS + 2,- stride=CHUNK_OVERLAP,- return_overflowing_tokens=True,- return_attention_mask=True,- )id_to_label = getattr(model.config, "id2label", {}) or {}step = max(1, MAX_CHUNK_TOKENS - CHUNK_OVERLAP)@@ -82,19 +74,17 @@ def main() -> int:start = 0index = 0expected_windows = 1 + max(0, (len(token_ids) - MAX_CHUNK_TOKENS + step - 1) // step)- if len(windows["input_ids"]) != expected_windows or expected_windows > MAX_CHUNKS:+ if expected_windows > MAX_CHUNKS:raise ValueError("incomplete tokenizer windows")with torch.inference_mode():while start < len(token_ids):if index >= MAX_CHUNKS:raise ValueError("text produced too many model windows")end = min(len(token_ids), start + MAX_CHUNK_TOKENS)- if len(windows["input_ids"][index]) != end - start + 2:- raise ValueError("invalid tokenizer window length")+ window_ids = [cls_id, *token_ids[start:end], sep_id]model_inputs = {- key: torch.tensor([value[index]])- for key, value in windows.items()- if key in {"input_ids", "attention_mask", "token_type_ids"}+ "input_ids": torch.tensor([window_ids]),+ "attention_mask": torch.tensor([[1] * len(window_ids)]),}probabilities = torch.softmax(model(**model_inputs).logits[0], dim=-1)class_id = int(torch.argmax(probabilities).item())diff --git a/scripts/run_prompt_guard.test.js b/scripts/run_prompt_guard.test.jsindex 34384a9210..d54a32c7ba 100644--- a/scripts/run_prompt_guard.test.js+++ b/scripts/run_prompt_guard.test.js@@ -8,23 +8,31 @@ const python = resolveTestPython();const script = fileURLToPath(new URL('./run_prompt_guard.py', import.meta.url));describe.skipIf(!python)('Prompt Guard Python wire contract', () => {- it('covers every overflow window using batched tensors and emits a complete Node-verifiable result', () => {+ it('classifies every token in overlapping batched windows without the broken overflow API', () => {// Synthetic tokenizer/model doubles exercise the shipped Python runner// without downloading weights or invoking a provider in the test suite.const program = `import contextlib, io, json, runpy, sys, tempfilefrom types import SimpleNamespacehelper = runpy.run_path(sys.argv[1])-def tokenizer(text, **kwargs):- assert kwargs["return_overflowing_tokens"] is True- assert kwargs["max_length"] == 512 and kwargs["stride"] == 64- return {"input_ids": [[1] * 512, [1] * 256], "attention_mask": [[1] * 512, [1] * 256], "overflow_to_sample_mapping": [0, 0]}-tokenizer.encode = lambda *_args, **_kwargs: [1] * 700+def tokenizer(*_args, **_kwargs):+ raise AssertionError("must not re-tokenize through the truncating overflow API")+def encode(_text, **kwargs):+ assert kwargs == {"add_special_tokens": False, "truncation": False}+ return list(range(10, 710))+tokenizer.encode = encodetokenizer.num_special_tokens_to_add = lambda **_kwargs: 2+tokenizer.cls_token_id = 1+tokenizer.sep_token_id = 2+calls = []def model(**inputs):assert len(inputs["input_ids"]) == 1assert len(inputs["input_ids"][0]) in (512, 256)- assert "overflow_to_sample_mapping" not in inputs+ start = 0 if not calls else 446+ end = 510 if not calls else 700+ assert inputs["input_ids"][0] == [1, *range(10 + start, 10 + end), 2]+ assert inputs["attention_mask"][0] == [1] * (end - start + 2)+ calls.append(start)return SimpleNamespace(logits=[[]])model.config = SimpleNamespace(id2label={0: "BENIGN"})model.to = lambda *_args: Nonediff --git a/server/lib/modelAbuseGuard.js b/server/lib/modelAbuseGuard.jsindex fa55c80c9c..fd8b8cc6f3 100644--- a/server/lib/modelAbuseGuard.js+++ b/server/lib/modelAbuseGuard.js@@ -69,8 +69,7 @@ export const MODEL_ABUSE_GUARD_PYTHON_IMPORTS = Object.freeze([// Independent of the image runtime's package aliases. These releases satisfy// Transformers 5.16's Hub >=1.5,<2 / safetensors >=0.8 requirements. The runner-// uses the supported overflowing-window tokenizer API, not prepare_for_model-// removed in v5. Updating these pins requires the explicit install canary.+// slices the complete token stream into the pinned DeBERTa window format. Updating these pins requires the explicit install canary.export const MODEL_ABUSE_GUARD_PYTHON_PACKAGES = Object.freeze(['torch==2.14.0','transformers==5.16.1',diff --git a/server/services/modelAbuseGuard.js b/server/services/modelAbuseGuard.jsindex 337f096c07..e842df6adc 100644--- a/server/services/modelAbuseGuard.js+++ b/server/services/modelAbuseGuard.js@@ -359,13 +359,10 @@ async function isBasePythonSupported(pythonPath) {.then(({ stdout }) => stdout.trim() === 'supported').catch(() => false);}-// A benign sentence the helper must classify end to end before the installer-// reports success. Importing packages proves prerequisites, not classification:-// a helper that loads the model and then dies on the first window (the-// unbatched-tensor bug that failed every Stage 1 scan on transformers 4.57)-// passed the import probe and only surfaced as a bare-// `security-guard-process-failed` at scan time.-const RUNTIME_CANARY_TEXT = 'The quick brown fox jumps over the lazy dog.';+// Verify classification across several overlapping windows, not just imports+// or a short sentence: both unbatched tensors and broken tokenizer overflow+// have passed weaker probes while making real PR scans fail.+const RUNTIME_CANARY_TEXT = 'The quick brown fox jumps over the lazy dog. '.repeat(100);async function isRuntimeReady(pythonPath) {if (!pythonPath) { runtimeIssue = null; return false; }@@ -391,7 +388,7 @@ async function canaryPasses(pythonPath, modelDir) {.catch(() => ({ ok: false }));if (!result.ok) return false;const verdict = normalizeModelAbuseGuardResult(result.parsed, { minBenignScore: MODEL_ABUSE_GUARD_MIN_BENIGN_SCORE });- return verdict.ok === true && verdict.safe === true;+ return verdict.ok === true && verdict.safe === true && verdict.chunkCount > 1;}/**@@ -456,11 +453,10 @@ export function installModelAbuseGuard({ onEvent } = {}) {return failure(code, { diagnostic: lastInstallFailure });};installInFlight = (async () => {- // Do this before creating a venv or installing packages. The model is gated- // on Hugging Face, so a missing token is an operator prerequisite—not a- // reason to leave a half-useful runtime behind and discover the problem- // only after setup has changed the install.- if (!(await getHfToken())) return failInstall('security-guard-huggingface-token-required');+ // A fresh model download needs access before changing the runtime.+ // A cached snapshot needs no Hugging Face credentials for runtime repair.+ const cachedFiles = await findCachedRepoFiles(MODEL_ABUSE_GUARD.repository, MODEL_ABUSE_GUARD_REQUIRED_FILES, { revision: MODEL_ABUSE_GUARD.revision });+ if (!cachedFiles && !(await getHfToken())) return failInstall('security-guard-huggingface-token-required');activeStage = 'python';const basePython = detectVenvBasePythonSync();if (!await isBasePythonSupported(basePython)) return failInstall('security-guard-python-unavailable');@@ -494,24 +490,26 @@ export function installModelAbuseGuard({ onEvent } = {}) {});activeStage = 'model';- emitInstall(onEvent, 'stage', 'Downloading the pinned Prompt Guard model snapshot…', 'model');- const download = downloadHfRepo({- repo: MODEL_ABUSE_GUARD.repository,- revision: MODEL_ABUSE_GUARD.revision,- only: [...MODEL_ABUSE_GUARD_REQUIRED_FILES],- pythonPath,- onEvent: (event) => {- if (event?.type === 'error') emitInstall(onEvent, 'error', 'Prompt Guard model download failed.', 'model');- else if (event?.type === 'progress') emitInstall(onEvent, 'progress', event.stage || 'Downloading Prompt Guard…', 'model');- else if (event?.type === 'complete') emitInstall(onEvent, 'stage', 'Pinned Prompt Guard model snapshot downloaded.', 'model');- },- });- installKill = download.kill;- const downloadResult = await download.promise;- installKill = null;- if (!downloadResult?.ok) return failInstall(downloadResult?.errorKind === 'gated_repo'- ? 'security-guard-huggingface-access-required'- : 'security-guard-model-download-failed', setupIssue(downloadResult?.errorMessage, 'model-download-failed'));+ if (!cachedFiles) {+ emitInstall(onEvent, 'stage', 'Downloading the pinned Prompt Guard model snapshot…', 'model');+ const download = downloadHfRepo({+ repo: MODEL_ABUSE_GUARD.repository,+ revision: MODEL_ABUSE_GUARD.revision,+ only: [...MODEL_ABUSE_GUARD_REQUIRED_FILES],+ pythonPath,+ onEvent: (event) => {+ if (event?.type === 'error') emitInstall(onEvent, 'error', 'Prompt Guard model download failed.', 'model');+ else if (event?.type === 'progress') emitInstall(onEvent, 'progress', event.stage || 'Downloading Prompt Guard…', 'model');+ else if (event?.type === 'complete') emitInstall(onEvent, 'stage', 'Pinned Prompt Guard model snapshot downloaded.', 'model');+ },+ });+ installKill = download.kill;+ const downloadResult = await download.promise;+ installKill = null;+ if (!downloadResult?.ok) return failInstall(downloadResult?.errorKind === 'gated_repo'+ ? 'security-guard-huggingface-access-required'+ : 'security-guard-model-download-failed', setupIssue(downloadResult?.errorMessage, 'model-download-failed'));+ }activeStage = 'verification';const status = await getModelAbuseGuardStatus();@@ -660,11 +658,17 @@ export async function runModelAbuseScan({: MODEL_ABUSE_GUARD_TIMEOUT_MS;const processResult = await runClassifier({ pythonPath, modelDir, content, timeoutMs: boundedTimeout }).catch(() => ({ ok: false, code: 'security-guard-process-failed' }));- if (!processResult.ok) return failure(processResult.code || 'security-guard-process-failed', {- guardId: MODEL_ABUSE_GUARD_ID,- model: MODEL_ABUSE_GUARD.name,- revision: MODEL_ABUSE_GUARD.revision,- });+ if (!processResult.ok) {+ if (processResult.code === 'security-guard-process-failed') {+ cachedRuntime = null;+ selfTestFailed = true;+ }+ return failure(processResult.code || 'security-guard-process-failed', {+ guardId: MODEL_ABUSE_GUARD_ID,+ model: MODEL_ABUSE_GUARD.name,+ revision: MODEL_ABUSE_GUARD.revision,+ });+ }const verdict = normalizeModelAbuseGuardResult(processResult.parsed, {minBenignScore,});diff --git a/server/services/modelAbuseGuard.runtime.test.js b/server/services/modelAbuseGuard.runtime.test.jsindex fb59d7dd96..c99151e4f3 100644--- a/server/services/modelAbuseGuard.runtime.test.js+++ b/server/services/modelAbuseGuard.runtime.test.js@@ -4,7 +4,7 @@ import { MODEL_ABUSE_GUARD_PYTHON_PACKAGES } from '../lib/modelAbuseGuard.js';const mock = vi.hoisted(() => ({spawn: vi.fn(), execFile: vi.fn(), createVenv: vi.fn(), installPackages: vi.fn(),- downloadHfRepo: vi.fn(), verdict: null,+ downloadHfRepo: vi.fn(), verdict: null, cached: true, token: 'example-read-token',}));vi.mock('../lib/childProcess.js', () => ({ spawn: mock.spawn, execFile: mock.execFile }));vi.mock('node:fs', async (original) => ({ ...await original(), existsSync: () => true }));@@ -13,9 +13,9 @@ vi.mock('../lib/pythonSetup.js', () => ({detectVenvBasePythonSync: () => '/example/python3', createVenv: mock.createVenv, installPackages: mock.installPackages,}));vi.mock('../lib/hfCache.js', () => ({- findCachedRepoFiles: async () => ['/example/model/config.json'], getHfCacheRoot: () => '/example/cache',+ findCachedRepoFiles: async () => mock.cached ? ['/example/model/config.json'] : null, getHfCacheRoot: () => '/example/cache',}));-vi.mock('./hfToken.js', () => ({ getHfToken: async () => 'example-read-token' }));+vi.mock('./hfToken.js', () => ({ getHfToken: async () => mock.token }));vi.mock('./hfDownload.js', () => ({ downloadHfRepo: mock.downloadHfRepo }));vi.mock('./localLlm.js', () => ({ listModels: vi.fn() }));vi.mock('./ollamaManager.js', () => ({ getModelCapabilities: vi.fn() }));@@ -23,7 +23,9 @@ vi.mock('./ollamaManager.js', () => ({ getModelCapabilities: vi.fn() }));beforeEach(() => {vi.resetModules();vi.clearAllMocks();- mock.verdict = { schemaVersion: 1, complete: true, tokenCount: 4, chunks: [{ index: 0, label: 'BENIGN', score: 0.99, tokenStart: 0, tokenEnd: 4 }] };+ mock.cached = true;+ mock.token = 'example-read-token';+ mock.verdict = { schemaVersion: 1, complete: true, tokenCount: 700, chunks: [{ index: 0, label: 'BENIGN', score: 0.99, tokenStart: 0, tokenEnd: 510 }, { index: 1, label: 'BENIGN', score: 0.99, tokenStart: 446, tokenEnd: 700 }] };mock.execFile.mockImplementation((...args) => args.at(-1)(null, { stdout: args[1][1].startsWith('import sys;') ? 'supported' : '{"ready":true}', stderr: '' }));mock.createVenv.mockResolvedValue('/example/venv/bin/python3');mock.installPackages.mockReturnValue({ promise: Promise.resolve({ ok: true }), kill: vi.fn() });@@ -51,6 +53,11 @@ describe('Prompt Guard runtime lifecycle', () => {});it('installs the dedicated versioned packages and verifies the full runner only on request', async () => {+ mock.cached = false;+ mock.downloadHfRepo.mockImplementation(() => {+ mock.cached = true;+ return { promise: Promise.resolve({ ok: true }), kill: vi.fn() };+ });const { installModelAbuseGuard } = await import('./modelAbuseGuard.js');await expect(installModelAbuseGuard()).resolves.toMatchObject({ ok: true, ready: true });expect(mock.installPackages).toHaveBeenCalledWith('/example/venv/bin/python3', [...MODEL_ABUSE_GUARD_PYTHON_PACKAGES], expect.any(Function), { preferUv: true });@@ -58,8 +65,44 @@ describe('Prompt Guard runtime lifecycle', () => {expect(mock.spawn).toHaveBeenCalledOnce();});+ it('repairs cached installations without Hugging Face credentials or model downloads', async () => {+ mock.token = null;+ const { installModelAbuseGuard } = await import('./modelAbuseGuard.js');+ await expect(installModelAbuseGuard()).resolves.toMatchObject({ ok: true, ready: true });+ expect(mock.downloadHfRepo).not.toHaveBeenCalled();+ expect(mock.installPackages).toHaveBeenCalledOnce();+ });++ it('refuses a fresh install without model access before changing the runtime', async () => {+ mock.cached = false;+ mock.token = null;+ const { installModelAbuseGuard } = await import('./modelAbuseGuard.js');+ await expect(installModelAbuseGuard()).resolves.toMatchObject({ ok: false, code: 'security-guard-huggingface-token-required' });+ expect(mock.createVenv).not.toHaveBeenCalled();+ });++ it('exposes a scan process failure as unhealthy and recovers after a verified repair', async () => {+ const healthySpawn = mock.spawn.getMockImplementation();+ mock.spawn.mockImplementationOnce(() => {+ const child = healthySpawn();+ child.stdin.end = () => queueMicrotask(() => child.emit('close', 1));+ return child;+ });+ const { runModelAbuseScan, getModelAbuseGuardStatus, installModelAbuseGuard } = await import('./modelAbuseGuard.js');+ await expect(runModelAbuseScan({ content: 'Update the dialog.' })).resolves.toMatchObject({ ok: false, code: 'security-guard-process-failed' });+ await expect(getModelAbuseGuardStatus()).resolves.toMatchObject({ ready: false, selfTestFailed: true });+ await expect(installModelAbuseGuard()).resolves.toMatchObject({ ok: true, ready: true });+ await expect(runModelAbuseScan({ content: 'Update the dialog.' })).resolves.toMatchObject({ ok: true, safe: true });+ });++ it('rejects a canary that only verifies one window', async () => {+ mock.verdict = { schemaVersion: 1, complete: true, tokenCount: 4, chunks: [{ index: 0, label: 'BENIGN', score: 0.99, tokenStart: 0, tokenEnd: 4 }] };+ const { installModelAbuseGuard } = await import('./modelAbuseGuard.js');+ await expect(installModelAbuseGuard()).resolves.toMatchObject({ ok: false, code: 'security-guard-self-test-failed' });+ });+it('rejects a successful subprocess that omitted part of the classified input', async () => {- mock.verdict.tokenCount = 700;+ mock.verdict.chunks.pop();mock.verdict.chunks[0].tokenEnd = 510;const { runModelAbuseScan, buildModelAbuseGuardEnv } = await import('./modelAbuseGuard.js');await expect(runModelAbuseScan({ content: 'Fix the empty import dialog.' })).resolves.toMatchObject({ ok: false, passed: false, code: 'security-guard-verdict-invalid' });