harness-reflex 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/README.md +103 -23
- package/USER_GUIDE.md +121 -43
- package/dist/adapters/agy.js +1 -1
- package/dist/adapters/agy.js.map +1 -1
- package/dist/adapters/codex.d.ts +133 -4
- package/dist/adapters/codex.js +325 -2
- package/dist/adapters/codex.js.map +1 -1
- package/dist/backend/defaults.d.ts +31 -0
- package/dist/backend/defaults.js +32 -0
- package/dist/backend/defaults.js.map +1 -0
- package/dist/backend/jev.js +6 -5
- package/dist/backend/jev.js.map +1 -1
- package/dist/backend/mock.d.ts +12 -1
- package/dist/backend/mock.js +34 -0
- package/dist/backend/mock.js.map +1 -1
- package/dist/backend/simple-jev.js +5 -4
- package/dist/backend/simple-jev.js.map +1 -1
- package/dist/backend/types.d.ts +34 -0
- package/dist/backend/types.js.map +1 -1
- package/dist/cli/index.js +5 -3
- package/dist/cli/index.js.map +1 -1
- package/dist/core/closing.d.ts +90 -0
- package/dist/core/closing.js +111 -0
- package/dist/core/closing.js.map +1 -0
- package/dist/core/evidence.d.ts +119 -0
- package/dist/core/evidence.js +209 -0
- package/dist/core/evidence.js.map +1 -0
- package/dist/core/judge.d.ts +221 -0
- package/dist/core/judge.js +251 -0
- package/dist/core/judge.js.map +1 -0
- package/dist/core/orchestrate-closing.d.ts +237 -0
- package/dist/core/orchestrate-closing.js +250 -0
- package/dist/core/orchestrate-closing.js.map +1 -0
- package/dist/core/orchestrate-correction.d.ts +209 -0
- package/dist/core/orchestrate-correction.js +141 -0
- package/dist/core/orchestrate-correction.js.map +1 -0
- package/dist/core/orchestrate-host.d.ts +225 -0
- package/dist/core/orchestrate-host.js +80 -0
- package/dist/core/orchestrate-host.js.map +1 -0
- package/dist/core/orchestrate-stagnation.d.ts +259 -0
- package/dist/core/orchestrate-stagnation.js +270 -0
- package/dist/core/orchestrate-stagnation.js.map +1 -0
- package/dist/core/orchestrate.d.ts +357 -0
- package/dist/core/orchestrate.js +418 -0
- package/dist/core/orchestrate.js.map +1 -0
- package/dist/core/policy.d.ts +122 -0
- package/dist/core/policy.js +102 -0
- package/dist/core/policy.js.map +1 -0
- package/dist/core/prune-plan.d.ts +141 -0
- package/dist/core/prune-plan.js +390 -0
- package/dist/core/prune-plan.js.map +1 -0
- package/dist/core/score.d.ts +2 -2
- package/dist/core/score.js.map +1 -1
- package/dist/core/text.d.ts +36 -0
- package/dist/core/text.js +66 -0
- package/dist/core/text.js.map +1 -0
- package/dist/hook/cli.d.ts +9 -0
- package/dist/hook/cli.js +52 -0
- package/dist/hook/cli.js.map +1 -0
- package/dist/hook/contract.d.ts +125 -0
- package/dist/hook/contract.js +159 -0
- package/dist/hook/contract.js.map +1 -0
- package/dist/hook/decision.d.ts +97 -0
- package/dist/hook/decision.js +955 -0
- package/dist/hook/decision.js.map +1 -0
- package/dist/hook/memory-store.d.ts +81 -0
- package/dist/hook/memory-store.js +157 -0
- package/dist/hook/memory-store.js.map +1 -0
- package/dist/hook/payload.d.ts +55 -0
- package/dist/hook/payload.js +129 -0
- package/dist/hook/payload.js.map +1 -0
- package/dist/hook/run.d.ts +48 -0
- package/dist/hook/run.js +218 -0
- package/dist/hook/run.js.map +1 -0
- package/dist/hook/store-port.d.ts +72 -0
- package/dist/hook/store-port.js +2 -0
- package/dist/hook/store-port.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/ports/audit.d.ts +18 -0
- package/dist/ports/audit.js +11 -0
- package/dist/ports/audit.js.map +1 -0
- package/dist/ports/clock.d.ts +14 -0
- package/dist/ports/clock.js +11 -0
- package/dist/ports/clock.js.map +1 -0
- package/dist/ports/decision.d.ts +75 -0
- package/dist/ports/decision.js +2 -0
- package/dist/ports/decision.js.map +1 -0
- package/dist/ports/index.d.ts +14 -0
- package/dist/ports/index.js +2 -0
- package/dist/ports/index.js.map +1 -0
- package/dist/ports/log.d.ts +22 -0
- package/dist/ports/log.js +12 -0
- package/dist/ports/log.js.map +1 -0
- package/dist/ports/state.d.ts +46 -0
- package/dist/ports/state.js +13 -0
- package/dist/ports/state.js.map +1 -0
- package/dist/state/clock.d.ts +40 -0
- package/dist/state/clock.js +43 -0
- package/dist/state/clock.js.map +1 -0
- package/dist/state/file-store.d.ts +340 -0
- package/dist/state/file-store.js +849 -0
- package/dist/state/file-store.js.map +1 -0
- package/dist/state/paths.d.ts +41 -0
- package/dist/state/paths.js +73 -0
- package/dist/state/paths.js.map +1 -0
- package/docs/USER_GUIDE.en.md +79 -36
- package/docs/claude-code.md +281 -0
- package/docs/design/v0.2.0-harness-plugins.md +381 -0
- package/docs/design/v0.3.0-orchestration-unification.md +580 -0
- package/docs/dsh-plugin.md +54 -54
- package/docs/release-checklist-v0.1.0.md +32 -21
- package/docs/release-handbook-porting-notes.md +11 -11
- package/docs/release-handbook.md +55 -30
- package/docs/release-notes-v0.1.0.md +27 -14
- package/docs/release-notes-v0.3.0.md +152 -0
- package/docs/research/claude-code-harness.md +607 -0
- package/docs/research/pi-harness.md +621 -0
- package/package.json +16 -7
package/dist/backend/mock.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DecisionBackend, ChoiceRequest, ChoiceResponse, GateRequest, GateResponse, PruneRequest, PruneResponse, StagnationCheckRequest, StagnationCheckResponse, RouteRequest, RouteResponse } from './types.js';
|
|
1
|
+
import { DecisionBackend, ChoiceRequest, ChoiceResponse, GateRequest, GateResponse, PruneRequest, PruneResponse, StagnationCheckRequest, StagnationCheckResponse, RouteRequest, RouteResponse, ClaimClassificationRequest, ClaimClassificationResponse } from './types.js';
|
|
2
2
|
/**
|
|
3
3
|
* Mock & Heuristic Decision Backend
|
|
4
4
|
* Provides instant (<5ms) deterministic decision evaluation for testing,
|
|
@@ -12,4 +12,15 @@ export declare class MockDecisionBackend implements DecisionBackend {
|
|
|
12
12
|
prune(req: PruneRequest): Promise<PruneResponse>;
|
|
13
13
|
checkStagnation(req: StagnationCheckRequest): Promise<StagnationCheckResponse>;
|
|
14
14
|
route(req: RouteRequest): Promise<RouteResponse>;
|
|
15
|
+
/**
|
|
16
|
+
* Deterministic stand-in for the closing-claim classification.
|
|
17
|
+
*
|
|
18
|
+
* The mock exists to keep the offline path honest, not to be the semantic
|
|
19
|
+
* judge: it reads a negated outcome first and only then looks for a completion
|
|
20
|
+
* word, which is enough to cover the English/Chinese and negation cases the
|
|
21
|
+
* hook fixtures exercise.
|
|
22
|
+
* @param req - candidate sentences plus the turn's intent.
|
|
23
|
+
* @returns one classification per candidate, in submission order.
|
|
24
|
+
*/
|
|
25
|
+
classifyClaims(req: ClaimClassificationRequest): Promise<ClaimClassificationResponse>;
|
|
15
26
|
}
|
package/dist/backend/mock.js
CHANGED
|
@@ -282,5 +282,39 @@ export class MockDecisionBackend {
|
|
|
282
282
|
latencyMs: Math.round(performance.now() - start)
|
|
283
283
|
};
|
|
284
284
|
}
|
|
285
|
+
/**
|
|
286
|
+
* Deterministic stand-in for the closing-claim classification.
|
|
287
|
+
*
|
|
288
|
+
* The mock exists to keep the offline path honest, not to be the semantic
|
|
289
|
+
* judge: it reads a negated outcome first and only then looks for a completion
|
|
290
|
+
* word, which is enough to cover the English/Chinese and negation cases the
|
|
291
|
+
* hook fixtures exercise.
|
|
292
|
+
* @param req - candidate sentences plus the turn's intent.
|
|
293
|
+
* @returns one classification per candidate, in submission order.
|
|
294
|
+
*/
|
|
295
|
+
async classifyClaims(req) {
|
|
296
|
+
const start = performance.now();
|
|
297
|
+
const statements = Array.isArray(req.statements) ? req.statements : [];
|
|
298
|
+
return {
|
|
299
|
+
results: statements.map(mockClaimClassification),
|
|
300
|
+
latencyMs: Math.round(performance.now() - start)
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
/** A negated or unfinished outcome, which is never a completion claim. */
|
|
305
|
+
const MOCK_CLAIM_NEGATION = /(not\s+(?:yet\s+)?(?:complete|completed|done|finished|passing|passed|successful|success)|isn'?t\s+(?:complete|done|finished)|still\s+(?:failing|fails|broken|running)|没有通过|未通过|尚未完成|尚未通过|还没完成|还没通过|并未完成|仍然失败|仍有失败|还有失败)/i;
|
|
306
|
+
/** A completion assertion in English or Chinese. */
|
|
307
|
+
const MOCK_CLAIM_WORD = /(\b(?:pass|passed|passing|green|success|successful|succeed|succeeded|complete|completed|finished|done|verified|works)\b|全部通过|所有测试通过|已完成|完成了|已通过|通过|成功|跑通|全绿|搞定)/i;
|
|
308
|
+
/**
|
|
309
|
+
* Classify one candidate sentence.
|
|
310
|
+
* @param statement - one candidate sentence.
|
|
311
|
+
* @returns whether it reads as a completion claim and with what certainty.
|
|
312
|
+
*/
|
|
313
|
+
function mockClaimClassification(statement) {
|
|
314
|
+
if (MOCK_CLAIM_NEGATION.test(statement))
|
|
315
|
+
return { statement, isClaim: false, confidence: 0.96 };
|
|
316
|
+
if (MOCK_CLAIM_WORD.test(statement))
|
|
317
|
+
return { statement, isClaim: true, confidence: 0.92 };
|
|
318
|
+
return { statement, isClaim: false, confidence: 0.9 };
|
|
285
319
|
}
|
|
286
320
|
//# sourceMappingURL=mock.js.map
|
package/dist/backend/mock.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mock.js","sourceRoot":"","sources":["../../src/backend/mock.ts"],"names":[],"mappings":"AAgBA;;;;;;;;;;;;;GAaG;AACH,SAAS,UAAU,CAAC,IAAY;IAC9B,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,4BAA4B,CAAC,EAAE,CAAC;QAC3E,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;YAAE,SAAS;QACjC,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YACnC,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC;gBA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I;gBACf,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;gBAC/B,MAAM,EAAE,WAAW,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,iBAAiB;aACjF,CAAC;QACJ,CAAC,CAAC,CAAC;QAEH,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC;QACzC,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC;QAC3B,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;QAErC,OAAO;YACL,gBAAgB,EAAE,MAAM;YACxB,aAAa,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI;YAC9B,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC;SACjD,CAAC;IACJ,CAAC;CACF","sourcesContent":["import {\n DecisionBackend,\n ChoiceRequest,\n ChoiceResponse,\n GateRequest,\n GateResponse,\n PruneRequest,\n PruneResponse,\n StagnationCheckRequest,\n StagnationCheckResponse,\n RouteRequest,\n RouteResponse,\n GateResultItem,\n GateOutcome\n} from './types.js';\n\n/**\n * Vocabulary one option contributes to the overlap score.\n *\n * ASCII words keep the historical `length > 2` filter. Chinese is written\n * without spaces and nearly every technical term is two characters (并发, 证明,\n * 迁移), so a whitespace split drops the entire vocabulary of a Chinese turn and\n * collapses every option into an indistinguishable tie — which then reads as a\n * confident decision. A Han run therefore contributes its two-character grams as\n * well as the run itself, so an option's cue word matches inside an unspaced\n * sentence.\n *\n * @param text - one candidate option.\n * @returns distinct matchable terms, in option order.\n */\nfunction matchTerms(text: string): string[] {\n const terms: string[] = [];\n for (const chunk of text.toLowerCase().split(/[^\\p{Script=Han}a-z0-9_]+/u)) {\n if (chunk.length === 0) continue;\n if (!/\\p{Script=Han}/u.test(chunk)) {\n if (chunk.length > 2) terms.push(chunk);\n continue;\n }\n for (let i = 0; i + 2 <= chunk.length; i++) terms.push(chunk.slice(i, i + 2));\n if (chunk.length > 2) terms.push(chunk);\n }\n return terms;\n}\n\n/**\n * Ignore explicit zero counters, not failure words in general. Both count-first\n * (pytest/Jest) and label-first (node:test) summaries occur in captured output.\n * Replace nonzero counters with a cue so another zero counter cannot hide them.\n * This is only a mock heuristic, not semantic verification of arbitrary logs.\n */\nfunction hasFailureEvidence(evidence: string): boolean {\n const withoutCounters = evidence.replace(\n /\\b(\\d+(?:[.,]\\d+)*|zero)\\s+(fail(?:ed|ures?)?|errors?)\\b|\\b(fail(?:ed|ures?)?|errors?)\\s*[:=]?\\s*(\\d+(?:[.,]\\d+)*|zero)\\b/g,\n (_match, before: string | undefined, _beforeLabel: string | undefined, _afterLabel: string | undefined, after: string | undefined) => {\n const count = before ?? after!;\n return count === 'zero' || Number(count.replaceAll(',', '')) === 0 ? '' : ' failure ';\n }\n );\n // An explicit error diagnostic is not a summary, even if its message starts with 0.\n return evidence.includes('error:') || /fail|\\berrors?\\b/.test(withoutCounters);\n}\n\n/**\n * Mock & Heuristic Decision Backend\n * Provides instant (<5ms) deterministic decision evaluation for testing,\n * local development, and offline baseline comparisons.\n */\nexport class MockDecisionBackend implements DecisionBackend {\n readonly name = 'mock-heuristic-v1';\n readonly model = 'mock-system-one';\n\n async choice(req: ChoiceRequest): Promise<ChoiceResponse> {\n const start = performance.now();\n if (req.options.length === 0) {\n throw new Error('Choice options cannot be empty');\n }\n\n // Heuristic: rank options based on semantic relevance to question & context\n const qLower = req.question.toLowerCase();\n const ctxLower = (req.context || '').toLowerCase();\n\n const scores = req.options.map((opt) => {\n let score = 1.0;\n // Match the option's own vocabulary against the question and the context.\n for (const term of matchTerms(opt)) {\n if (qLower.includes(term)) score += 2.0;\n if (ctxLower.includes(term)) score += 1.5;\n }\n return score;\n });\n\n const sum = scores.reduce((a, b) => a + b, 0);\n const options = req.options.map((opt, i) => ({\n label: opt,\n probability: Number((scores[i] / sum).toFixed(4))\n }));\n\n // Sort descending\n options.sort((a, b) => b.probability - a.probability);\n\n return {\n options,\n bestOption: options[0].label,\n confidence: options[0].probability,\n uncalibrated: true,\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n async gate(req: GateRequest): Promise<GateResponse> {\n const start = performance.now();\n const evidenceLower = req.evidence.toLowerCase();\n const hasErrorOrFail = hasFailureEvidence(evidenceLower);\n const results: GateResultItem[] = [];\n let allPassed = true;\n let needsEscalation = false;\n\n for (const assertion of req.assertions) {\n const stmt = assertion.statement;\n const stmtLower = stmt.toLowerCase();\n\n // Check for contradiction cues\n const claimsSuccess = stmtLower.includes('success') || stmtLower.includes('pass') || stmtLower.includes('finished') || stmtLower.includes('complete');\n\n let outcome: GateOutcome = 'not_addressed';\n let confidence = 0.85;\n let explanation = 'Evaluated against evidence.';\n\n if (claimsSuccess && hasErrorOrFail) {\n outcome = 'contradicted';\n explanation = 'Assertion claims success, but evidence contains explicit error or failure output.';\n allPassed = false;\n } else {\n // Keyword overlap\n const words = stmtLower.replace(/[^a-z0-9_\\s]/g, '').split(/\\s+/).filter((w) => w.length > 3);\n const matches = words.filter((w) => evidenceLower.includes(w));\n const matchRatio = words.length > 0 ? matches.length / words.length : 0;\n\n if (matchRatio >= 0.4) {\n outcome = 'verified';\n explanation = `Direct evidence found supporting assertion (matching terms: ${matches.slice(0, 3).join(', ')}).`;\n } else if (words.length > 0) {\n outcome = 'not_addressed';\n explanation = 'Evidence does not contain sufficient details to verify this assertion.';\n allPassed = false;\n if (req.strictness === 'high') {\n needsEscalation = true;\n }\n } else {\n outcome = 'escalate';\n explanation = 'Insufficient assertion details to determine truth.';\n needsEscalation = true;\n allPassed = false;\n }\n }\n\n results.push({\n statement: stmt,\n outcome,\n confidence,\n explanation\n });\n }\n\n return {\n passed: allPassed && !needsEscalation,\n results,\n needsEscalation,\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n async prune(req: PruneRequest): Promise<PruneResponse> {\n const start = performance.now();\n const raw = req.rawOutput;\n const lines = raw.split('\\n');\n\n // Deterministic + Semantic pruning:\n // Drop repetitive progress bars, redundant empty lines, unhelpful stack traces\n const filteredLines: string[] = [];\n const intentWords = req.intent.toLowerCase().split(/\\s+/).filter((w) => w.length > 2);\n\n let consecutiveEmpty = 0;\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) {\n consecutiveEmpty++;\n if (consecutiveEmpty <= 1) filteredLines.push(line);\n continue;\n }\n consecutiveEmpty = 0;\n\n // Filter progress bar indicators\n if (line.includes('[===') || line.includes('████') || line.includes('\\r')) {\n continue;\n }\n\n // Filter typical node_modules / site-packages deep internals unless relevant\n if (line.includes('node_modules/') && !intentWords.some((w) => line.toLowerCase().includes(w))) {\n continue;\n }\n\n filteredLines.push(line);\n }\n\n const prunedOutput = filteredLines.join('\\n');\n const originalChars = raw.length;\n const prunedChars = prunedOutput.length;\n const estOriginalTokens = Math.ceil(originalChars / 4);\n const estPrunedTokens = Math.ceil(prunedChars / 4);\n const tokensSaved = Math.max(0, estOriginalTokens - estPrunedTokens);\n const reduction = originalChars > 0 ? Number((((originalChars - prunedChars) / originalChars) * 100).toFixed(1)) : 0;\n\n return {\n processedOutput: req.shadowMode ? raw : prunedOutput,\n originalChars,\n prunedChars,\n estimatedTokensSaved: tokensSaved,\n reductionPercentage: reduction,\n shadow: !!req.shadowMode,\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n async checkStagnation(req: StagnationCheckRequest): Promise<StagnationCheckResponse> {\n const start = performance.now();\n const history = req.history || [];\n const window = req.windowSize || 6;\n const recent = history.slice(-window);\n\n if (recent.length < 3) {\n return {\n isStuck: false,\n confidence: 0.95,\n diagnosis: 'Action history too short to establish stagnation.',\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n // Check 1: Identical consecutive tool calls\n const tools = recent.map((r) => `${r.tool}:${r.input.trim()}`);\n let identicalCount = 1;\n for (let i = tools.length - 1; i > 0; i--) {\n if (tools[i] === tools[i - 1]) {\n identicalCount++;\n } else {\n break;\n }\n }\n\n if (identicalCount >= 3) {\n return {\n isStuck: true,\n patternType: 'repetition',\n confidence: 0.98,\n diagnosis: `Identical tool execution repeated ${identicalCount} times consecutively with no change in input.`,\n recommendedIntervention: 'Interrupt execution. Suggest alternative tool or inspect previous failure output.',\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n // Check 2: Repeated failure / error cycle\n const failingSteps = recent.filter((r) => !!r.error || (r.output && (r.output.includes('Error') || r.output.includes('Failed'))));\n if (failingSteps.length >= 3 && recent.length >= 4) {\n return {\n isStuck: true,\n patternType: 'failing_retry',\n confidence: 0.91,\n diagnosis: `${failingSteps.length} of the last ${recent.length} actions failed with recurring errors.`,\n recommendedIntervention: 'Step back to analyze root cause before attempting the same action again.',\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n // Check 3: Oscillation between two files or two commands\n if (recent.length >= 4) {\n const last4 = recent.slice(-4);\n if (last4[0].tool === last4[2].tool && last4[1].tool === last4[3].tool && last4[0].input === last4[2].input && last4[1].input === last4[3].input) {\n return {\n isStuck: true,\n patternType: 'oscillation',\n confidence: 0.94,\n diagnosis: 'Agent is oscillating between two identical alternating commands/edits.',\n recommendedIntervention: 'Break loop: stop alternating and clarify requirements or test independently.',\n latencyMs: Math.round(performance.now() - start)\n };\n }\n }\n\n return {\n isStuck: false,\n patternType: 'none',\n confidence: 0.88,\n diagnosis: 'Execution flow appears progressive.',\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n async route(req: RouteRequest): Promise<RouteResponse> {\n const start = performance.now();\n const goalLower = req.goal.toLowerCase();\n \n const scored = req.candidates.map((cand) => {\n let score = 0.1;\n const text = `${cand.name} ${cand.description}`.toLowerCase();\n const words = goalLower.split(/\\s+/).filter((w) => w.length > 2);\n for (const w of words) {\n if (text.includes(w)) score += 1.0;\n }\n return {\n name: cand.name,\n score: Number(score.toFixed(3)),\n reason: `Matched ${words.filter((w) => text.includes(w)).length} query keywords`\n };\n });\n\n scored.sort((a, b) => b.score - a.score);\n const topK = req.topK || 3;\n const ranked = scored.slice(0, topK);\n\n return {\n rankedCandidates: ranked,\n bestCandidate: ranked[0]?.name,\n latencyMs: Math.round(performance.now() - start)\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"mock.js","sourceRoot":"","sources":["../../src/backend/mock.ts"],"names":[],"mappings":"AAmBA;;;;;;;;;;;;;GAaG;AACH,SAAS,UAAU,CAAC,IAAY;IAC9B,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,4BAA4B,CAAC,EAAE,CAAC;QAC3E,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;YAAE,SAAS;QACjC,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YACnC,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC;gBAAE,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACxC,SAAS;QACX,CAAC;QACD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE;YAAE,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QAC9E,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC;YAAE,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC1C,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;;GAKG;AACH,SAAS,kBAAkB,CAAC,QAAgB;IAC1C,MAAM,eAAe,GAAG,QAAQ,CAAC,OAAO,CACtC,4HAA4H,EAC5H,CAAC,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,\n StagnationCheckRequest,\n StagnationCheckResponse,\n RouteRequest,\n RouteResponse,\n GateResultItem,\n GateOutcome,\n ClaimClassification,\n ClaimClassificationRequest,\n ClaimClassificationResponse\n} from './types.js';\n\n/**\n * Vocabulary one option contributes to the overlap score.\n *\n * ASCII words keep the historical `length > 2` filter. Chinese is written\n * without spaces and nearly every technical term is two characters (并发, 证明,\n * 迁移), so a whitespace split drops the entire vocabulary of a Chinese turn and\n * collapses every option into an indistinguishable tie — which then reads as a\n * confident decision. A Han run therefore contributes its two-character grams as\n * well as the run itself, so an option's cue word matches inside an unspaced\n * sentence.\n *\n * @param text - one candidate option.\n * @returns distinct matchable terms, in option order.\n */\nfunction matchTerms(text: string): string[] {\n const terms: string[] = [];\n for (const chunk of text.toLowerCase().split(/[^\\p{Script=Han}a-z0-9_]+/u)) {\n if (chunk.length === 0) continue;\n if (!/\\p{Script=Han}/u.test(chunk)) {\n if (chunk.length > 2) terms.push(chunk);\n continue;\n }\n for (let i = 0; i + 2 <= chunk.length; i++) terms.push(chunk.slice(i, i + 2));\n if (chunk.length > 2) terms.push(chunk);\n }\n return terms;\n}\n\n/**\n * Ignore explicit zero counters, not failure words in general. Both count-first\n * (pytest/Jest) and label-first (node:test) summaries occur in captured output.\n * Replace nonzero counters with a cue so another zero counter cannot hide them.\n * This is only a mock heuristic, not semantic verification of arbitrary logs.\n */\nfunction hasFailureEvidence(evidence: string): boolean {\n const withoutCounters = evidence.replace(\n /\\b(\\d+(?:[.,]\\d+)*|zero)\\s+(fail(?:ed|ures?)?|errors?)\\b|\\b(fail(?:ed|ures?)?|errors?)\\s*[:=]?\\s*(\\d+(?:[.,]\\d+)*|zero)\\b/g,\n (_match, before: string | undefined, _beforeLabel: string | undefined, _afterLabel: string | undefined, after: string | undefined) => {\n const count = before ?? after!;\n return count === 'zero' || Number(count.replaceAll(',', '')) === 0 ? '' : ' failure ';\n }\n );\n // An explicit error diagnostic is not a summary, even if its message starts with 0.\n return evidence.includes('error:') || /fail|\\berrors?\\b/.test(withoutCounters);\n}\n\n/**\n * Mock & Heuristic Decision Backend\n * Provides instant (<5ms) deterministic decision evaluation for testing,\n * local development, and offline baseline comparisons.\n */\nexport class MockDecisionBackend implements DecisionBackend {\n readonly name = 'mock-heuristic-v1';\n readonly model = 'mock-system-one';\n\n async choice(req: ChoiceRequest): Promise<ChoiceResponse> {\n const start = performance.now();\n if (req.options.length === 0) {\n throw new Error('Choice options cannot be empty');\n }\n\n // Heuristic: rank options based on semantic relevance to question & context\n const qLower = req.question.toLowerCase();\n const ctxLower = (req.context || '').toLowerCase();\n\n const scores = req.options.map((opt) => {\n let score = 1.0;\n // Match the option's own vocabulary against the question and the context.\n for (const term of matchTerms(opt)) {\n if (qLower.includes(term)) score += 2.0;\n if (ctxLower.includes(term)) score += 1.5;\n }\n return score;\n });\n\n const sum = scores.reduce((a, b) => a + b, 0);\n const options = req.options.map((opt, i) => ({\n label: opt,\n probability: Number((scores[i] / sum).toFixed(4))\n }));\n\n // Sort descending\n options.sort((a, b) => b.probability - a.probability);\n\n return {\n options,\n bestOption: options[0].label,\n confidence: options[0].probability,\n uncalibrated: true,\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n async gate(req: GateRequest): Promise<GateResponse> {\n const start = performance.now();\n const evidenceLower = req.evidence.toLowerCase();\n const hasErrorOrFail = hasFailureEvidence(evidenceLower);\n const results: GateResultItem[] = [];\n let allPassed = true;\n let needsEscalation = false;\n\n for (const assertion of req.assertions) {\n const stmt = assertion.statement;\n const stmtLower = stmt.toLowerCase();\n\n // Check for contradiction cues\n const claimsSuccess = stmtLower.includes('success') || stmtLower.includes('pass') || stmtLower.includes('finished') || stmtLower.includes('complete');\n\n let outcome: GateOutcome = 'not_addressed';\n let confidence = 0.85;\n let explanation = 'Evaluated against evidence.';\n\n if (claimsSuccess && hasErrorOrFail) {\n outcome = 'contradicted';\n explanation = 'Assertion claims success, but evidence contains explicit error or failure output.';\n allPassed = false;\n } else {\n // Keyword overlap\n const words = stmtLower.replace(/[^a-z0-9_\\s]/g, '').split(/\\s+/).filter((w) => w.length > 3);\n const matches = words.filter((w) => evidenceLower.includes(w));\n const matchRatio = words.length > 0 ? matches.length / words.length : 0;\n\n if (matchRatio >= 0.4) {\n outcome = 'verified';\n explanation = `Direct evidence found supporting assertion (matching terms: ${matches.slice(0, 3).join(', ')}).`;\n } else if (words.length > 0) {\n outcome = 'not_addressed';\n explanation = 'Evidence does not contain sufficient details to verify this assertion.';\n allPassed = false;\n if (req.strictness === 'high') {\n needsEscalation = true;\n }\n } else {\n outcome = 'escalate';\n explanation = 'Insufficient assertion details to determine truth.';\n needsEscalation = true;\n allPassed = false;\n }\n }\n\n results.push({\n statement: stmt,\n outcome,\n confidence,\n explanation\n });\n }\n\n return {\n passed: allPassed && !needsEscalation,\n results,\n needsEscalation,\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n async prune(req: PruneRequest): Promise<PruneResponse> {\n const start = performance.now();\n const raw = req.rawOutput;\n const lines = raw.split('\\n');\n\n // Deterministic + Semantic pruning:\n // Drop repetitive progress bars, redundant empty lines, unhelpful stack traces\n const filteredLines: string[] = [];\n const intentWords = req.intent.toLowerCase().split(/\\s+/).filter((w) => w.length > 2);\n\n let consecutiveEmpty = 0;\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) {\n consecutiveEmpty++;\n if (consecutiveEmpty <= 1) filteredLines.push(line);\n continue;\n }\n consecutiveEmpty = 0;\n\n // Filter progress bar indicators\n if (line.includes('[===') || line.includes('████') || line.includes('\\r')) {\n continue;\n }\n\n // Filter typical node_modules / site-packages deep internals unless relevant\n if (line.includes('node_modules/') && !intentWords.some((w) => line.toLowerCase().includes(w))) {\n continue;\n }\n\n filteredLines.push(line);\n }\n\n const prunedOutput = filteredLines.join('\\n');\n const originalChars = raw.length;\n const prunedChars = prunedOutput.length;\n const estOriginalTokens = Math.ceil(originalChars / 4);\n const estPrunedTokens = Math.ceil(prunedChars / 4);\n const tokensSaved = Math.max(0, estOriginalTokens - estPrunedTokens);\n const reduction = originalChars > 0 ? Number((((originalChars - prunedChars) / originalChars) * 100).toFixed(1)) : 0;\n\n return {\n processedOutput: req.shadowMode ? raw : prunedOutput,\n originalChars,\n prunedChars,\n estimatedTokensSaved: tokensSaved,\n reductionPercentage: reduction,\n shadow: !!req.shadowMode,\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n async checkStagnation(req: StagnationCheckRequest): Promise<StagnationCheckResponse> {\n const start = performance.now();\n const history = req.history || [];\n const window = req.windowSize || 6;\n const recent = history.slice(-window);\n\n if (recent.length < 3) {\n return {\n isStuck: false,\n confidence: 0.95,\n diagnosis: 'Action history too short to establish stagnation.',\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n // Check 1: Identical consecutive tool calls\n const tools = recent.map((r) => `${r.tool}:${r.input.trim()}`);\n let identicalCount = 1;\n for (let i = tools.length - 1; i > 0; i--) {\n if (tools[i] === tools[i - 1]) {\n identicalCount++;\n } else {\n break;\n }\n }\n\n if (identicalCount >= 3) {\n return {\n isStuck: true,\n patternType: 'repetition',\n confidence: 0.98,\n diagnosis: `Identical tool execution repeated ${identicalCount} times consecutively with no change in input.`,\n recommendedIntervention: 'Interrupt execution. Suggest alternative tool or inspect previous failure output.',\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n // Check 2: Repeated failure / error cycle\n const failingSteps = recent.filter((r) => !!r.error || (r.output && (r.output.includes('Error') || r.output.includes('Failed'))));\n if (failingSteps.length >= 3 && recent.length >= 4) {\n return {\n isStuck: true,\n patternType: 'failing_retry',\n confidence: 0.91,\n diagnosis: `${failingSteps.length} of the last ${recent.length} actions failed with recurring errors.`,\n recommendedIntervention: 'Step back to analyze root cause before attempting the same action again.',\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n // Check 3: Oscillation between two files or two commands\n if (recent.length >= 4) {\n const last4 = recent.slice(-4);\n if (last4[0].tool === last4[2].tool && last4[1].tool === last4[3].tool && last4[0].input === last4[2].input && last4[1].input === last4[3].input) {\n return {\n isStuck: true,\n patternType: 'oscillation',\n confidence: 0.94,\n diagnosis: 'Agent is oscillating between two identical alternating commands/edits.',\n recommendedIntervention: 'Break loop: stop alternating and clarify requirements or test independently.',\n latencyMs: Math.round(performance.now() - start)\n };\n }\n }\n\n return {\n isStuck: false,\n patternType: 'none',\n confidence: 0.88,\n diagnosis: 'Execution flow appears progressive.',\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n async route(req: RouteRequest): Promise<RouteResponse> {\n const start = performance.now();\n const goalLower = req.goal.toLowerCase();\n \n const scored = req.candidates.map((cand) => {\n let score = 0.1;\n const text = `${cand.name} ${cand.description}`.toLowerCase();\n const words = goalLower.split(/\\s+/).filter((w) => w.length > 2);\n for (const w of words) {\n if (text.includes(w)) score += 1.0;\n }\n return {\n name: cand.name,\n score: Number(score.toFixed(3)),\n reason: `Matched ${words.filter((w) => text.includes(w)).length} query keywords`\n };\n });\n\n scored.sort((a, b) => b.score - a.score);\n const topK = req.topK || 3;\n const ranked = scored.slice(0, topK);\n\n return {\n rankedCandidates: ranked,\n bestCandidate: ranked[0]?.name,\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n /**\n * Deterministic stand-in for the closing-claim classification.\n *\n * The mock exists to keep the offline path honest, not to be the semantic\n * judge: it reads a negated outcome first and only then looks for a completion\n * word, which is enough to cover the English/Chinese and negation cases the\n * hook fixtures exercise.\n * @param req - candidate sentences plus the turn's intent.\n * @returns one classification per candidate, in submission order.\n */\n async classifyClaims(req: ClaimClassificationRequest): Promise<ClaimClassificationResponse> {\n const start = performance.now();\n const statements = Array.isArray(req.statements) ? req.statements : [];\n return {\n results: statements.map(mockClaimClassification),\n latencyMs: Math.round(performance.now() - start)\n };\n }\n}\n\n/** A negated or unfinished outcome, which is never a completion claim. */\nconst MOCK_CLAIM_NEGATION =\n /(not\\s+(?:yet\\s+)?(?:complete|completed|done|finished|passing|passed|successful|success)|isn'?t\\s+(?:complete|done|finished)|still\\s+(?:failing|fails|broken|running)|没有通过|未通过|尚未完成|尚未通过|还没完成|还没通过|并未完成|仍然失败|仍有失败|还有失败)/i;\n\n/** A completion assertion in English or Chinese. */\nconst MOCK_CLAIM_WORD =\n /(\\b(?:pass|passed|passing|green|success|successful|succeed|succeeded|complete|completed|finished|done|verified|works)\\b|全部通过|所有测试通过|已完成|完成了|已通过|通过|成功|跑通|全绿|搞定)/i;\n\n/**\n * Classify one candidate sentence.\n * @param statement - one candidate sentence.\n * @returns whether it reads as a completion claim and with what certainty.\n */\nfunction mockClaimClassification(statement: string): ClaimClassification {\n if (MOCK_CLAIM_NEGATION.test(statement)) return { statement, isClaim: false, confidence: 0.96 };\n if (MOCK_CLAIM_WORD.test(statement)) return { statement, isClaim: true, confidence: 0.92 };\n return { statement, isClaim: false, confidence: 0.9 };\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { buildRouteContext } from './route-prompt.js';
|
|
2
|
+
import { LOGITS_DEFAULT_API_KEY, LOGITS_DEFAULT_BASE_URL, LOGITS_DEFAULT_MODEL, LOGITS_DEFAULT_TIMEOUT_MS } from './defaults.js';
|
|
2
3
|
/**
|
|
3
4
|
* Logits-based System One Provider (Zero-RLCD, Next-Token Logits Scoring via vLLM / OpenAI API)
|
|
4
5
|
*
|
|
@@ -16,19 +17,19 @@ export class LogitsSystemOneBackend {
|
|
|
16
17
|
process.env.SYSTEM_ONE_BASE_URL ||
|
|
17
18
|
process.env.VLLM_BASE_URL ||
|
|
18
19
|
process.env.OPENAI_BASE_URL ||
|
|
19
|
-
|
|
20
|
+
LOGITS_DEFAULT_BASE_URL).replace(/\/$/, '');
|
|
20
21
|
this.apiKey =
|
|
21
22
|
config?.apiKey ||
|
|
22
23
|
process.env.SYSTEM_ONE_API_KEY ||
|
|
23
24
|
process.env.VLLM_API_KEY ||
|
|
24
25
|
process.env.OPENAI_API_KEY ||
|
|
25
|
-
|
|
26
|
+
LOGITS_DEFAULT_API_KEY;
|
|
26
27
|
this.model =
|
|
27
28
|
config?.model ||
|
|
28
29
|
process.env.SYSTEM_ONE_MODEL ||
|
|
29
30
|
process.env.VLLM_MODEL ||
|
|
30
|
-
|
|
31
|
-
this.timeoutMs = config?.timeoutMs ||
|
|
31
|
+
LOGITS_DEFAULT_MODEL;
|
|
32
|
+
this.timeoutMs = config?.timeoutMs || LOGITS_DEFAULT_TIMEOUT_MS;
|
|
32
33
|
}
|
|
33
34
|
/**
|
|
34
35
|
* Request next-token logprobs from vLLM /v1/completions
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"simple-jev.js","sourceRoot":"","sources":["../../src/backend/simple-jev.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAStD;;;;;GAKG;AACH,MAAM,OAAO,sBAAsB;IACxB,IAAI,GAAG,mBAAmB,CAAC;IAC3B,KAAK,CAAS;IACN,OAAO,CAAS;IAChB,MAAM,CAAS;IACf,SAAS,CAAS;IAEnC,YAAY,MAAwB;QAClC,IAAI,CAAC,OAAO,GAAG,CACb,MAAM,EAAE,WAAW;YACnB,OAAO,CAAC,GAAG,CAAC,mBAAmB;YAC/B,OAAO,CAAC,GAAG,CAAC,aAAa;YACzB,OAAO,CAAC,GAAG,CAAC,eAAe;YAC3B,uBAAuB,CACxB,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QACrB,IAAI,CAAC,MAAM;YACT,MAAM,EAAE,MAAM;gBACd,OAAO,CAAC,GAAG,CAAC,kBAAkB;gBAC9B,OAAO,CAAC,GAAG,CAAC,YAAY;gBACxB,OAAO,CAAC,GAAG,CAAC,cAAc;gBAC1B,OAAO,CAAC;QACV,IAAI,CAAC,KAAK;YACR,MAAM,EAAE,KAAK;gBACb,OAAO,CAAC,GAAG,CAAC,gBAAgB;gBAC5B,OAAO,CAAC,GAAG,CAAC,UAAU;gBACtB,0BAA0B,CAAC;QAC7B,IAAI,CAAC,SAAS,GAAG,MAAM,EAAE,SAAS,IAAI,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AAW,CAAC,GAAG,EAAE,CAAC;QAChC,MAAM,OAAO,GAAG,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;QAClD,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC;YAClC,QAAQ,EAAE,4DAA4D,GAAG,CAAC,IAAI,IAAI;YAClF,OAAO;YACP,OAAO,EAAE,iBAAiB,CAAC,GAAG,CAAC;SAChC,CAAC,CAAC;QAEH,OAAO;YACL,gBAAgB,EAAE,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;YACzF,aAAa,EAAE,SAAS,CAAC,UAAU;YACnC,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC;SACjD,CAAC;IACJ,CAAC;CACF;AAED,MAAM,CAAC,MAAM,wBAAwB,GAAG,sBAAsB,CAAC","sourcesContent":["import {\n DecisionBackend,\n ChoiceRequest,\n ChoiceResponse,\n GateRequest,\n GateResponse,\n PruneRequest,\n PruneResponse,\n StagnationCheckRequest,\n StagnationCheckResponse,\n RouteRequest,\n RouteResponse\n} from './types.js';\nimport { buildRouteContext } from './route-prompt.js';\n\nexport interface SimpleJevConfig {\n vllmBaseUrl?: string;\n apiKey?: string;\n model?: string;\n timeoutMs?: number;\n}\n\n/**\n * Logits-based System One Provider (Zero-RLCD, Next-Token Logits Scoring via vLLM / OpenAI API)\n *\n * Implements System One decision API on top of standard open LLM weights (e.g. Qwen2.5 / DeepSeek)\n * using next-token logprobs with max_tokens: 1.\n */\nexport class LogitsSystemOneBackend implements DecisionBackend {\n readonly name = 'system-one-logits';\n readonly model: string;\n private readonly baseUrl: string;\n private readonly apiKey: string;\n private readonly timeoutMs: number;\n\n constructor(config?: SimpleJevConfig) {\n this.baseUrl = (\n config?.vllmBaseUrl ||\n process.env.SYSTEM_ONE_BASE_URL ||\n process.env.VLLM_BASE_URL ||\n process.env.OPENAI_BASE_URL ||\n 'http://localhost:8000'\n ).replace(/\\/$/, '');\n this.apiKey =\n config?.apiKey ||\n process.env.SYSTEM_ONE_API_KEY ||\n process.env.VLLM_API_KEY ||\n process.env.OPENAI_API_KEY ||\n 'dummy';\n this.model =\n config?.model ||\n process.env.SYSTEM_ONE_MODEL ||\n process.env.VLLM_MODEL ||\n 'Qwen/Qwen2.5-7B-Instruct';\n this.timeoutMs = config?.timeoutMs || 8000;\n }\n\n /**\n * Request next-token logprobs from vLLM /v1/completions\n */\n private async getNextTokenLogprobs(prompt: string, topLogprobs: number = 20): Promise<Record<string, number>> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n try {\n const resp = await fetch(`${this.baseUrl}/v1/completions`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`\n },\n body: JSON.stringify({\n model: this.model,\n prompt,\n max_tokens: 1,\n temperature: 0.0,\n logprobs: topLogprobs\n }),\n signal: controller.signal\n });\n\n if (!resp.ok) {\n throw new Error(`vLLM endpoint error: ${resp.status} ${resp.statusText}`);\n }\n\n const data = await resp.json() as any;\n const firstChoice = data?.choices?.[0];\n const logprobsObj = firstChoice?.logprobs?.top_logprobs?.[0] || {};\n return logprobsObj;\n } finally {\n clearTimeout(timer);\n }\n }\n\n /**\n * Normalizes logprobs across target token labels via Softmax\n */\n private computeNormalizedProbabilities(\n logprobsMap: Record<string, number>,\n labels: string[]\n ): Array<{ label: string; probability: number }> {\n // Extract logprobs for each label (accounting for leading spaces)\n const logValues = labels.map((label) => {\n let maxLog = -Infinity;\n for (const [token, logp] of Object.entries(logprobsMap)) {\n if (token.trim().toLowerCase() === label.trim().toLowerCase()) {\n if (logp > maxLog) maxLog = logp;\n }\n }\n return maxLog === -Infinity ? -20 : maxLog; // baseline floor for unseen tokens\n });\n\n const maxLogVal = Math.max(...logValues);\n const expValues = logValues.map((v) => Math.exp(v - maxLogVal));\n const sumExp = expValues.reduce((a, b) => a + b, 0);\n\n return labels.map((label, idx) => ({\n label,\n probability: Number((expValues[idx] / sumExp).toFixed(4))\n }));\n }\n\n async choice(req: ChoiceRequest): Promise<ChoiceResponse> {\n const start = performance.now();\n const optionsLetters = req.options.map((_, i) => String.fromCharCode(65 + i)); // A, B, C...\n\n const prompt = `Context: ${req.context || 'None'}\nQuestion: ${req.question}\nOptions:\n${req.options.map((opt, i) => `${optionsLetters[i]}. ${opt}`).join('\\n')}\n\nAnswer with the single letter of the best option:`;\n\n try {\n const topLogprobs = await this.getNextTokenLogprobs(prompt, 20);\n const probabilities = this.computeNormalizedProbabilities(topLogprobs, optionsLetters);\n\n const mappedOptions = req.options.map((opt, i) => ({\n label: opt,\n probability: probabilities[i].probability\n }));\n\n mappedOptions.sort((a, b) => b.probability - a.probability);\n\n return {\n options: mappedOptions,\n bestOption: mappedOptions[0].label,\n confidence: mappedOptions[0].probability,\n uncalibrated: true,\n latencyMs: Math.round(performance.now() - start)\n };\n } catch (err: any) {\n throw new Error(`[SimpleJevBackend.choice] Failed: ${err.message}`);\n }\n }\n\n async gate(req: GateRequest): Promise<GateResponse> {\n const start = performance.now();\n const results = [];\n let allPassed = true;\n let needsEscalation = false;\n\n try {\n for (const assertion of req.assertions) {\n const prompt = `Evidence:\n\"\"\"\n${req.evidence.slice(0, 3000)}\n\"\"\"\n\nStatement: \"${assertion.statement}\"\n\nIs this statement strictly verified by the evidence?\nOptions:\nA. Yes (Verified)\nB. No (Contradicted or False)\nC. Unknown (Not addressed in evidence)\n\nBest Answer (A, B, or C):`;\n\n const logprobs = await this.getNextTokenLogprobs(prompt, 10);\n const probs = this.computeNormalizedProbabilities(logprobs, ['A', 'B', 'C']);\n const top = probs.sort((a, b) => b.probability - a.probability)[0];\n\n let outcome: 'verified' | 'contradicted' | 'not_addressed' | 'escalate' = 'not_addressed';\n if (top.label === 'A') outcome = 'verified';\n else if (top.label === 'B') outcome = 'contradicted';\n else outcome = 'not_addressed';\n\n if (outcome !== 'verified') {\n allPassed = false;\n }\n\n results.push({\n statement: assertion.statement,\n outcome,\n confidence: top.probability,\n explanation: `Classified via token logits: P(${top.label}) = ${top.probability}`\n });\n }\n\n return {\n passed: allPassed,\n results,\n needsEscalation,\n latencyMs: Math.round(performance.now() - start)\n };\n } catch (err: any) {\n // Fail-closed to escalate\n return {\n passed: false,\n needsEscalation: true,\n results: req.assertions.map((a) => ({\n statement: a.statement,\n outcome: 'escalate' as const,\n confidence: 0,\n explanation: `SimpleJev backend failed: ${err.message}. Fail-closed escalation.`\n })),\n latencyMs: Math.round(performance.now() - start)\n };\n }\n }\n\n async prune(req: PruneRequest): Promise<PruneResponse> {\n const start = performance.now();\n // In Simple-Jev, line scoring can be done by heuristic filter + teacher-forcing scoring\n // Here we provide high-throughput line extraction\n const raw = req.rawOutput;\n const lines = raw.split('\\n');\n const intentLower = req.intent.toLowerCase();\n\n const selectedLines = lines.filter((line) => {\n const lower = line.toLowerCase();\n if (lower.includes('error') || lower.includes('fail') || lower.includes('warning')) return true;\n if (lower.includes('passed') || lower.includes('complete') || lower.includes('status')) return true;\n return intentLower.split(/\\s+/).some((term) => term.length > 3 && lower.includes(term));\n });\n\n const prunedOutput = selectedLines.length > 0 ? selectedLines.join('\\n') : lines.slice(0, 30).join('\\n');\n const originalChars = raw.length;\n const prunedChars = prunedOutput.length;\n const reduction = originalChars > 0 ? Number((((originalChars - prunedChars) / originalChars) * 100).toFixed(1)) : 0;\n const tokensSaved = Math.max(0, Math.ceil((originalChars - prunedChars) / 4));\n\n return {\n processedOutput: req.shadowMode ? raw : prunedOutput,\n originalChars,\n prunedChars,\n estimatedTokensSaved: tokensSaved,\n reductionPercentage: reduction,\n shadow: !!req.shadowMode,\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n async checkStagnation(req: StagnationCheckRequest): Promise<StagnationCheckResponse> {\n const start = performance.now();\n const history = req.history || [];\n if (history.length < 3) {\n return {\n isStuck: false,\n confidence: 0.9,\n diagnosis: 'Action history short.',\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n const summary = history.slice(-5).map((h, i) => `${i + 1}. Tool: ${h.tool} | Input: ${h.input.slice(0, 80)} | Output: ${(h.output || h.error || '').slice(0, 80)}`).join('\\n');\n const prompt = `Inspect this recent agent execution trajectory:\n${summary}\n\nIs the agent stuck in an unproductive loop (repeating failing actions or oscillating without progress)?\nOptions:\nA. Yes, stuck\nB. No, making progress\n\nAnswer (A or B):`;\n\n try {\n const logprobs = await this.getNextTokenLogprobs(prompt, 5);\n const probs = this.computeNormalizedProbabilities(logprobs, ['A', 'B']);\n const aProb = probs.find((p) => p.label === 'A')?.probability ?? 0;\n const isStuck = aProb > 0.6;\n\n return {\n isStuck,\n patternType: isStuck ? 'repetition' : 'none',\n confidence: probs[0].probability,\n diagnosis: isStuck ? 'Logits classified execution trajectory as unproductive repeating loop.' : 'Trajectory classified as progressive.',\n recommendedIntervention: isStuck ? 'Stop repeating this command. Change approach or review inputs.' : undefined,\n latencyMs: Math.round(performance.now() - start)\n };\n } catch (err: any) {\n return {\n isStuck: false,\n confidence: 0.5,\n diagnosis: `SimpleJev stagnation check failed: ${err.message}`,\n latencyMs: Math.round(performance.now() - start)\n };\n }\n }\n\n async route(req: RouteRequest): Promise<RouteResponse> {\n const start = performance.now();\n const options = req.candidates.map((c) => c.name);\n const choiceRes = await this.choice({\n question: `Which tool or skill is best suited to achieve the goal: \"${req.goal}\"?`,\n options,\n context: buildRouteContext(req)\n });\n\n return {\n rankedCandidates: choiceRes.options.map((o) => ({ name: o.label, score: o.probability })),\n bestCandidate: choiceRes.bestOption,\n latencyMs: Math.round(performance.now() - start)\n };\n }\n}\n\nexport const SimpleJevDecisionBackend = LogitsSystemOneBackend;\n\n"]}
|
|
1
|
+
{"version":3,"file":"simple-jev.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,IAAI;YAClF,OAAO;YACP,OAAO,EAAE,iBAAiB,CAAC,GAAG,CAAC;SAChC,CAAC,CAAC;QAEH,OAAO;YACL,gBAAgB,EAAE,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;YACzF,aAAa,EAAE,SAAS,CAAC,UAAU;YACnC,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC;SACjD,CAAC;IACJ,CAAC;CACF;AAED,MAAM,CAAC,MAAM,wBAAwB,GAAG,sBAAsB,CAAC","sourcesContent":["import {\n DecisionBackend,\n ChoiceRequest,\n ChoiceResponse,\n GateRequest,\n GateResponse,\n PruneRequest,\n PruneResponse,\n StagnationCheckRequest,\n StagnationCheckResponse,\n RouteRequest,\n RouteResponse\n} from './types.js';\nimport { buildRouteContext } from './route-prompt.js';\nimport {\n LOGITS_DEFAULT_API_KEY,\n LOGITS_DEFAULT_BASE_URL,\n LOGITS_DEFAULT_MODEL,\n LOGITS_DEFAULT_TIMEOUT_MS\n} from './defaults.js';\n\nexport interface SimpleJevConfig {\n vllmBaseUrl?: string;\n apiKey?: string;\n model?: string;\n timeoutMs?: number;\n}\n\n/**\n * Logits-based System One Provider (Zero-RLCD, Next-Token Logits Scoring via vLLM / OpenAI API)\n *\n * Implements System One decision API on top of standard open LLM weights (e.g. Qwen2.5 / DeepSeek)\n * using next-token logprobs with max_tokens: 1.\n */\nexport class LogitsSystemOneBackend implements DecisionBackend {\n readonly name = 'system-one-logits';\n readonly model: string;\n private readonly baseUrl: string;\n private readonly apiKey: string;\n private readonly timeoutMs: number;\n\n constructor(config?: SimpleJevConfig) {\n this.baseUrl = (\n config?.vllmBaseUrl ||\n process.env.SYSTEM_ONE_BASE_URL ||\n process.env.VLLM_BASE_URL ||\n process.env.OPENAI_BASE_URL ||\n LOGITS_DEFAULT_BASE_URL\n ).replace(/\\/$/, '');\n this.apiKey =\n config?.apiKey ||\n process.env.SYSTEM_ONE_API_KEY ||\n process.env.VLLM_API_KEY ||\n process.env.OPENAI_API_KEY ||\n LOGITS_DEFAULT_API_KEY;\n this.model =\n config?.model ||\n process.env.SYSTEM_ONE_MODEL ||\n process.env.VLLM_MODEL ||\n LOGITS_DEFAULT_MODEL;\n this.timeoutMs = config?.timeoutMs || LOGITS_DEFAULT_TIMEOUT_MS;\n }\n\n /**\n * Request next-token logprobs from vLLM /v1/completions\n */\n private async getNextTokenLogprobs(prompt: string, topLogprobs: number = 20): Promise<Record<string, number>> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n try {\n const resp = await fetch(`${this.baseUrl}/v1/completions`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`\n },\n body: JSON.stringify({\n model: this.model,\n prompt,\n max_tokens: 1,\n temperature: 0.0,\n logprobs: topLogprobs\n }),\n signal: controller.signal\n });\n\n if (!resp.ok) {\n throw new Error(`vLLM endpoint error: ${resp.status} ${resp.statusText}`);\n }\n\n const data = await resp.json() as any;\n const firstChoice = data?.choices?.[0];\n const logprobsObj = firstChoice?.logprobs?.top_logprobs?.[0] || {};\n return logprobsObj;\n } finally {\n clearTimeout(timer);\n }\n }\n\n /**\n * Normalizes logprobs across target token labels via Softmax\n */\n private computeNormalizedProbabilities(\n logprobsMap: Record<string, number>,\n labels: string[]\n ): Array<{ label: string; probability: number }> {\n // Extract logprobs for each label (accounting for leading spaces)\n const logValues = labels.map((label) => {\n let maxLog = -Infinity;\n for (const [token, logp] of Object.entries(logprobsMap)) {\n if (token.trim().toLowerCase() === label.trim().toLowerCase()) {\n if (logp > maxLog) maxLog = logp;\n }\n }\n return maxLog === -Infinity ? -20 : maxLog; // baseline floor for unseen tokens\n });\n\n const maxLogVal = Math.max(...logValues);\n const expValues = logValues.map((v) => Math.exp(v - maxLogVal));\n const sumExp = expValues.reduce((a, b) => a + b, 0);\n\n return labels.map((label, idx) => ({\n label,\n probability: Number((expValues[idx] / sumExp).toFixed(4))\n }));\n }\n\n async choice(req: ChoiceRequest): Promise<ChoiceResponse> {\n const start = performance.now();\n const optionsLetters = req.options.map((_, i) => String.fromCharCode(65 + i)); // A, B, C...\n\n const prompt = `Context: ${req.context || 'None'}\nQuestion: ${req.question}\nOptions:\n${req.options.map((opt, i) => `${optionsLetters[i]}. ${opt}`).join('\\n')}\n\nAnswer with the single letter of the best option:`;\n\n try {\n const topLogprobs = await this.getNextTokenLogprobs(prompt, 20);\n const probabilities = this.computeNormalizedProbabilities(topLogprobs, optionsLetters);\n\n const mappedOptions = req.options.map((opt, i) => ({\n label: opt,\n probability: probabilities[i].probability\n }));\n\n mappedOptions.sort((a, b) => b.probability - a.probability);\n\n return {\n options: mappedOptions,\n bestOption: mappedOptions[0].label,\n confidence: mappedOptions[0].probability,\n uncalibrated: true,\n latencyMs: Math.round(performance.now() - start)\n };\n } catch (err: any) {\n throw new Error(`[SimpleJevBackend.choice] Failed: ${err.message}`);\n }\n }\n\n async gate(req: GateRequest): Promise<GateResponse> {\n const start = performance.now();\n const results = [];\n let allPassed = true;\n let needsEscalation = false;\n\n try {\n for (const assertion of req.assertions) {\n const prompt = `Evidence:\n\"\"\"\n${req.evidence.slice(0, 3000)}\n\"\"\"\n\nStatement: \"${assertion.statement}\"\n\nIs this statement strictly verified by the evidence?\nOptions:\nA. Yes (Verified)\nB. No (Contradicted or False)\nC. Unknown (Not addressed in evidence)\n\nBest Answer (A, B, or C):`;\n\n const logprobs = await this.getNextTokenLogprobs(prompt, 10);\n const probs = this.computeNormalizedProbabilities(logprobs, ['A', 'B', 'C']);\n const top = probs.sort((a, b) => b.probability - a.probability)[0];\n\n let outcome: 'verified' | 'contradicted' | 'not_addressed' | 'escalate' = 'not_addressed';\n if (top.label === 'A') outcome = 'verified';\n else if (top.label === 'B') outcome = 'contradicted';\n else outcome = 'not_addressed';\n\n if (outcome !== 'verified') {\n allPassed = false;\n }\n\n results.push({\n statement: assertion.statement,\n outcome,\n confidence: top.probability,\n explanation: `Classified via token logits: P(${top.label}) = ${top.probability}`\n });\n }\n\n return {\n passed: allPassed,\n results,\n needsEscalation,\n latencyMs: Math.round(performance.now() - start)\n };\n } catch (err: any) {\n // Fail-closed to escalate\n return {\n passed: false,\n needsEscalation: true,\n results: req.assertions.map((a) => ({\n statement: a.statement,\n outcome: 'escalate' as const,\n confidence: 0,\n explanation: `SimpleJev backend failed: ${err.message}. Fail-closed escalation.`\n })),\n latencyMs: Math.round(performance.now() - start)\n };\n }\n }\n\n async prune(req: PruneRequest): Promise<PruneResponse> {\n const start = performance.now();\n // In Simple-Jev, line scoring can be done by heuristic filter + teacher-forcing scoring\n // Here we provide high-throughput line extraction\n const raw = req.rawOutput;\n const lines = raw.split('\\n');\n const intentLower = req.intent.toLowerCase();\n\n const selectedLines = lines.filter((line) => {\n const lower = line.toLowerCase();\n if (lower.includes('error') || lower.includes('fail') || lower.includes('warning')) return true;\n if (lower.includes('passed') || lower.includes('complete') || lower.includes('status')) return true;\n return intentLower.split(/\\s+/).some((term) => term.length > 3 && lower.includes(term));\n });\n\n const prunedOutput = selectedLines.length > 0 ? selectedLines.join('\\n') : lines.slice(0, 30).join('\\n');\n const originalChars = raw.length;\n const prunedChars = prunedOutput.length;\n const reduction = originalChars > 0 ? Number((((originalChars - prunedChars) / originalChars) * 100).toFixed(1)) : 0;\n const tokensSaved = Math.max(0, Math.ceil((originalChars - prunedChars) / 4));\n\n return {\n processedOutput: req.shadowMode ? raw : prunedOutput,\n originalChars,\n prunedChars,\n estimatedTokensSaved: tokensSaved,\n reductionPercentage: reduction,\n shadow: !!req.shadowMode,\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n async checkStagnation(req: StagnationCheckRequest): Promise<StagnationCheckResponse> {\n const start = performance.now();\n const history = req.history || [];\n if (history.length < 3) {\n return {\n isStuck: false,\n confidence: 0.9,\n diagnosis: 'Action history short.',\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n const summary = history.slice(-5).map((h, i) => `${i + 1}. Tool: ${h.tool} | Input: ${h.input.slice(0, 80)} | Output: ${(h.output || h.error || '').slice(0, 80)}`).join('\\n');\n const prompt = `Inspect this recent agent execution trajectory:\n${summary}\n\nIs the agent stuck in an unproductive loop (repeating failing actions or oscillating without progress)?\nOptions:\nA. Yes, stuck\nB. No, making progress\n\nAnswer (A or B):`;\n\n try {\n const logprobs = await this.getNextTokenLogprobs(prompt, 5);\n const probs = this.computeNormalizedProbabilities(logprobs, ['A', 'B']);\n const aProb = probs.find((p) => p.label === 'A')?.probability ?? 0;\n const isStuck = aProb > 0.6;\n\n return {\n isStuck,\n patternType: isStuck ? 'repetition' : 'none',\n confidence: probs[0].probability,\n diagnosis: isStuck ? 'Logits classified execution trajectory as unproductive repeating loop.' : 'Trajectory classified as progressive.',\n recommendedIntervention: isStuck ? 'Stop repeating this command. Change approach or review inputs.' : undefined,\n latencyMs: Math.round(performance.now() - start)\n };\n } catch (err: any) {\n return {\n isStuck: false,\n confidence: 0.5,\n diagnosis: `SimpleJev stagnation check failed: ${err.message}`,\n latencyMs: Math.round(performance.now() - start)\n };\n }\n }\n\n async route(req: RouteRequest): Promise<RouteResponse> {\n const start = performance.now();\n const options = req.candidates.map((c) => c.name);\n const choiceRes = await this.choice({\n question: `Which tool or skill is best suited to achieve the goal: \"${req.goal}\"?`,\n options,\n context: buildRouteContext(req)\n });\n\n return {\n rankedCandidates: choiceRes.options.map((o) => ({ name: o.label, score: o.probability })),\n bestCandidate: choiceRes.bestOption,\n latencyMs: Math.round(performance.now() - start)\n };\n }\n}\n\nexport const SimpleJevDecisionBackend = LogitsSystemOneBackend;\n\n"]}
|
package/dist/backend/types.d.ts
CHANGED
|
@@ -214,6 +214,38 @@ export interface RouteResponse {
|
|
|
214
214
|
bestCandidate?: string;
|
|
215
215
|
latencyMs: number;
|
|
216
216
|
}
|
|
217
|
+
/**
|
|
218
|
+
* One batch of sentences a closing check must classify before it may verify
|
|
219
|
+
* anything.
|
|
220
|
+
*
|
|
221
|
+
* The candidates are chosen deterministically (the last few sentences of the
|
|
222
|
+
* turn), but *which* of them claims completion is a semantic question: a word
|
|
223
|
+
* list would miss a Chinese "全部通过" and read a negated "not complete" as the
|
|
224
|
+
* opposite. A backend that can answer exposes `classifyClaims`; one that cannot
|
|
225
|
+
* leaves the closing check on its fail-open path.
|
|
226
|
+
*/
|
|
227
|
+
export interface ClaimClassificationRequest {
|
|
228
|
+
/** Candidate sentences, in the order the caller will treat them. */
|
|
229
|
+
statements: string[];
|
|
230
|
+
/** What the turn was doing, so the classifier reads the sentences in context. */
|
|
231
|
+
intent: string;
|
|
232
|
+
/** Extra context (the turn's own summary) when the caller has one. */
|
|
233
|
+
context?: string;
|
|
234
|
+
}
|
|
235
|
+
/** One sentence's classification. */
|
|
236
|
+
export interface ClaimClassification {
|
|
237
|
+
statement: string;
|
|
238
|
+
/** Whether the winning criterion says the sentence claims completion. */
|
|
239
|
+
isClaim: boolean;
|
|
240
|
+
/** Probability of the completion-claim criterion, in `[0, 1]`. */
|
|
241
|
+
confidence: number;
|
|
242
|
+
}
|
|
243
|
+
/** The classification answer for one closing candidate batch. */
|
|
244
|
+
export interface ClaimClassificationResponse {
|
|
245
|
+
/** One entry per submitted statement, in submission order when answered. */
|
|
246
|
+
results: ClaimClassification[];
|
|
247
|
+
latencyMs: number;
|
|
248
|
+
}
|
|
217
249
|
/**
|
|
218
250
|
* Common interface for decision backends (Jev official, Simple-Jev, vLLM, mock)
|
|
219
251
|
*/
|
|
@@ -225,6 +257,8 @@ export interface DecisionBackend {
|
|
|
225
257
|
prune(req: PruneRequest): Promise<PruneResponse>;
|
|
226
258
|
checkStagnation(req: StagnationCheckRequest): Promise<StagnationCheckResponse>;
|
|
227
259
|
route(req: RouteRequest): Promise<RouteResponse>;
|
|
260
|
+
/** Classify completion-claim candidates, when the backend can answer at all. */
|
|
261
|
+
classifyClaims?(req: ClaimClassificationRequest): Promise<ClaimClassificationResponse>;
|
|
228
262
|
/**
|
|
229
263
|
* Health of the backend's outbound conversation, when it has one.
|
|
230
264
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/backend/types.ts"],"names":[],"mappings":"AAAA;;GAEG","sourcesContent":["/**\n * Core types for System One Decision Runtime & APIs (Jev, vLLM/Simple-Jev, DSPy, etc.)\n */\n\nexport interface ChoiceOption {\n label: string;\n probability: number;\n}\n\nexport interface ChoiceRequest {\n question: string;\n options: string[];\n context?: string;\n temperature?: number;\n}\n\nexport interface ChoiceResponse {\n options: ChoiceOption[];\n bestOption: string;\n confidence: number;\n uncalibrated?: boolean;\n latencyMs: number;\n}\n\nexport type GateOutcome = 'verified' | 'contradicted' | 'not_addressed' | 'escalate';\n\nexport interface GateAssertion {\n statement: string;\n criteria?: string;\n}\n\nexport interface GateRequest {\n assertions: GateAssertion[];\n evidence: string;\n context?: string;\n strictness?: 'high' | 'normal' | 'lenient';\n}\n\nexport interface GateResultItem {\n statement: string;\n outcome: GateOutcome;\n confidence: number;\n explanation: string;\n}\n\nexport interface GateResponse {\n passed: boolean;\n results: GateResultItem[];\n needsEscalation: boolean;\n latencyMs: number;\n}\n\nexport interface PruneRequest {\n rawOutput: string;\n intent: string;\n maxTokens?: number;\n shadowMode?: boolean;\n /**\n * Character count from which the backend judges segments through System One.\n * The caller's resolved `interventions.pruneJudgeMinChars`; when omitted the\n * backend's own configuration/environment/default applies.\n */\n pruneJudgeMinChars?: number;\n}\n\nexport interface PruneResponse {\n processedOutput: string;\n originalChars: number;\n prunedChars: number;\n estimatedTokensSaved: number;\n reductionPercentage: number;\n shadow: boolean;\n latencyMs: number;\n /**\n * Which judging path produced the candidate: `segmented` ran the per-segment\n * System One scoring for a payload at/above `interventions.pruneJudgeMinChars`;\n * `local` used the deterministic candidates (small payload, or a fallback).\n * Optional so existing response literals stay valid.\n */\n judgePath?: 'segmented' | 'local' | 'fallback';\n /** Why the segmented path fell back to the local candidates, when it did. */\n fallbackReason?: string;\n /**\n * How the returned text was reduced, when it was.\n *\n * `none` means the returned text is the payload: a judgment that ran scored\n * every segment and kept everything (honoured as-is), or the degraded path's\n * template compression could not reduce it either. `fallbackReason` and\n * `judgePath` tell the two apart.\n */\n compression?: 'segmented' | 'local' | 'template' | 'none';\n /** Segments handed to System One in one request (0 when the local path ran). */\n judgedSegments?: number;\n /** Segments beyond the per-request limit, kept deterministically instead. */\n unjudgedSegments?: number;\n /**\n * Segments the composed scored candidate kept whole, out of all segments.\n *\n * The count belongs to the candidate that was installed; when no scored\n * candidate reduced the payload it is the balanced candidate's count, which is\n * what explains \"the judge kept five segments and nothing shrank\". It counts\n * the segments kept without a score too, which is why\n * {@link autoKeptSegments} is reported beside it. Absent on paths that never\n * selected segments by score (local, or a judgment with no usable score).\n */\n keptSegments?: number;\n /** Characters of the aggressive-budget candidate, before one is installed. */\n aggressiveChars?: number;\n /** Characters of the balanced-budget candidate, before one is installed. */\n balancedChars?: number;\n /** Characters of the conservative-budget candidate, before one is installed. */\n conservativeChars?: number;\n /**\n * Segments System One really scored (`scores.size`).\n *\n * `judgedSegments` counts the questions sent; this counts the answers that\n * were usable. A gap between the two is a judgment that could not be read.\n */\n scoredSegments?: number;\n /**\n * Segments kept whole because they carried no score.\n *\n * They are the unjudged safety margin (no answer, an unreadable answer, or a\n * segment beyond the per-request limit), counted over the whole payload. When\n * this is close to the segment count the candidate cannot shrink through the\n * scored budgets, because almost nothing was judged.\n */\n autoKeptSegments?: number;\n /** Answers returned for a judged segment that carried no usable keep score. */\n unparsedScoreAnswers?: number;\n}\n\n/**\n * Diagnostic fields of a prune response.\n *\n * Every path reports what it measured and omits the rest, so a reader can tell\n * a field that was not measured from one that measured zero.\n */\nexport type PruneDiagnostics = Pick<\n PruneResponse,\n | 'judgePath'\n | 'fallbackReason'\n | 'compression'\n | 'judgedSegments'\n | 'unjudgedSegments'\n | 'keptSegments'\n | 'aggressiveChars'\n | 'balancedChars'\n | 'conservativeChars'\n | 'scoredSegments'\n | 'autoKeptSegments'\n | 'unparsedScoreAnswers'\n>;\n\n/**\n * In-memory health of one System One backend.\n *\n * Every request the backend sends updates it: a success clears the failure\n * fields, a failure records when and why it happened and counts the run. It is\n * deliberately not persisted — a restarted Host starts healthy and discovers\n * the truth with its first call.\n */\nexport interface BackendHealth {\n /** Whether the most recent request succeeded (true before the first request). */\n available: boolean;\n /** Reason of the most recent failure; cleared by a success. */\n lastFailureReason?: string;\n /** ISO timestamp of the most recent failure; cleared by a success. */\n lastFailureAt?: string;\n /** Consecutive failed requests; a single success resets it to 0. */\n consecutiveFailures: number;\n}\n\nexport interface ActionStep {\n tool: string;\n input: string;\n output?: string;\n error?: string;\n timestamp?: number;\n}\n\nexport interface StagnationCheckRequest {\n history: ActionStep[];\n goal?: string;\n windowSize?: number;\n}\n\nexport interface StagnationCheckResponse {\n isStuck: boolean;\n patternType?: 'repetition' | 'oscillation' | 'failing_retry' | 'zero_progress' | 'none';\n confidence: number;\n diagnosis?: string;\n recommendedIntervention?: string;\n latencyMs: number;\n}\n\n/**\n * Session facts one routing decision reasons about.\n *\n * They exist for prompt-cache affinity: switching a session onto another\n * physical model invalidates the upstream prompt prefix cache, so the decision\n * needs to know which model holds the cached prefix and how much context is\n * already in it. Every field is optional — a caller that knows nothing about\n * the session (a hand-built one-shot call) simply omits the block.\n */\nexport interface RouteRequestState {\n /** Physical `provider:model` the session is currently using, when known. */\n currentModel?: string;\n /** Estimated tokens of the session context accumulated so far. */\n contextTokens?: number;\n /** Character count the token estimate was derived from. */\n contextChars?: number;\n}\n\n/** One candidate of a {@link RouteRequest}. */\nexport interface RouteCandidateItem {\n name: string;\n description: string;\n type?: 'tool' | 'skill' | 'action';\n /**\n * Whether this candidate is the physical model the session already uses.\n * Returning it costs no cache miss; a backend that builds a prompt should\n * say so next to the candidate.\n */\n current?: boolean;\n}\n\nexport interface RouteRequest {\n goal: string;\n candidates: RouteCandidateItem[];\n topK?: number;\n /** Cache-affinity facts: the model in use and the accumulated context size. */\n state?: RouteRequestState;\n /**\n * Decision instructions the backend must carry into its prompt — the\n * cache-affinity policy (\"keep the current model unless clearly outmatched\").\n */\n instructions?: string;\n}\n\nexport interface RouteResponse {\n rankedCandidates: Array<{ name: string; score: number; reason?: string }>;\n bestCandidate?: string;\n latencyMs: number;\n}\n\n/**\n * Common interface for decision backends (Jev official, Simple-Jev, vLLM, mock)\n */\nexport interface DecisionBackend {\n readonly name: string;\n readonly model: string;\n \n choice(req: ChoiceRequest): Promise<ChoiceResponse>;\n gate(req: GateRequest): Promise<GateResponse>;\n prune(req: PruneRequest): Promise<PruneResponse>;\n checkStagnation(req: StagnationCheckRequest): Promise<StagnationCheckResponse>;\n route(req: RouteRequest): Promise<RouteResponse>;\n /**\n * Health of the backend's outbound conversation, when it has one.\n *\n * In-process backends (mock) serve every call locally and simply omit this:\n * absence means \"healthy by construction\", not \"unknown\".\n */\n health?(): BackendHealth;\n}\n\nexport type SystemOneBackend = DecisionBackend;\n\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/backend/types.ts"],"names":[],"mappings":"AAAA;;GAEG","sourcesContent":["/**\n * Core types for System One Decision Runtime & APIs (Jev, vLLM/Simple-Jev, DSPy, etc.)\n */\n\nexport interface ChoiceOption {\n label: string;\n probability: number;\n}\n\nexport interface ChoiceRequest {\n question: string;\n options: string[];\n context?: string;\n temperature?: number;\n}\n\nexport interface ChoiceResponse {\n options: ChoiceOption[];\n bestOption: string;\n confidence: number;\n uncalibrated?: boolean;\n latencyMs: number;\n}\n\nexport type GateOutcome = 'verified' | 'contradicted' | 'not_addressed' | 'escalate';\n\nexport interface GateAssertion {\n statement: string;\n criteria?: string;\n}\n\nexport interface GateRequest {\n assertions: GateAssertion[];\n evidence: string;\n context?: string;\n strictness?: 'high' | 'normal' | 'lenient';\n}\n\nexport interface GateResultItem {\n statement: string;\n outcome: GateOutcome;\n confidence: number;\n explanation: string;\n}\n\nexport interface GateResponse {\n passed: boolean;\n results: GateResultItem[];\n needsEscalation: boolean;\n latencyMs: number;\n}\n\nexport interface PruneRequest {\n rawOutput: string;\n intent: string;\n maxTokens?: number;\n shadowMode?: boolean;\n /**\n * Character count from which the backend judges segments through System One.\n * The caller's resolved `interventions.pruneJudgeMinChars`; when omitted the\n * backend's own configuration/environment/default applies.\n */\n pruneJudgeMinChars?: number;\n}\n\nexport interface PruneResponse {\n processedOutput: string;\n originalChars: number;\n prunedChars: number;\n estimatedTokensSaved: number;\n reductionPercentage: number;\n shadow: boolean;\n latencyMs: number;\n /**\n * Which judging path produced the candidate: `segmented` ran the per-segment\n * System One scoring for a payload at/above `interventions.pruneJudgeMinChars`;\n * `local` used the deterministic candidates (small payload, or a fallback).\n * Optional so existing response literals stay valid.\n */\n judgePath?: 'segmented' | 'local' | 'fallback';\n /** Why the segmented path fell back to the local candidates, when it did. */\n fallbackReason?: string;\n /**\n * How the returned text was reduced, when it was.\n *\n * `none` means the returned text is the payload: a judgment that ran scored\n * every segment and kept everything (honoured as-is), or the degraded path's\n * template compression could not reduce it either. `fallbackReason` and\n * `judgePath` tell the two apart.\n */\n compression?: 'segmented' | 'local' | 'template' | 'none';\n /** Segments handed to System One in one request (0 when the local path ran). */\n judgedSegments?: number;\n /** Segments beyond the per-request limit, kept deterministically instead. */\n unjudgedSegments?: number;\n /**\n * Segments the composed scored candidate kept whole, out of all segments.\n *\n * The count belongs to the candidate that was installed; when no scored\n * candidate reduced the payload it is the balanced candidate's count, which is\n * what explains \"the judge kept five segments and nothing shrank\". It counts\n * the segments kept without a score too, which is why\n * {@link autoKeptSegments} is reported beside it. Absent on paths that never\n * selected segments by score (local, or a judgment with no usable score).\n */\n keptSegments?: number;\n /** Characters of the aggressive-budget candidate, before one is installed. */\n aggressiveChars?: number;\n /** Characters of the balanced-budget candidate, before one is installed. */\n balancedChars?: number;\n /** Characters of the conservative-budget candidate, before one is installed. */\n conservativeChars?: number;\n /**\n * Segments System One really scored (`scores.size`).\n *\n * `judgedSegments` counts the questions sent; this counts the answers that\n * were usable. A gap between the two is a judgment that could not be read.\n */\n scoredSegments?: number;\n /**\n * Segments kept whole because they carried no score.\n *\n * They are the unjudged safety margin (no answer, an unreadable answer, or a\n * segment beyond the per-request limit), counted over the whole payload. When\n * this is close to the segment count the candidate cannot shrink through the\n * scored budgets, because almost nothing was judged.\n */\n autoKeptSegments?: number;\n /** Answers returned for a judged segment that carried no usable keep score. */\n unparsedScoreAnswers?: number;\n}\n\n/**\n * Diagnostic fields of a prune response.\n *\n * Every path reports what it measured and omits the rest, so a reader can tell\n * a field that was not measured from one that measured zero.\n */\nexport type PruneDiagnostics = Pick<\n PruneResponse,\n | 'judgePath'\n | 'fallbackReason'\n | 'compression'\n | 'judgedSegments'\n | 'unjudgedSegments'\n | 'keptSegments'\n | 'aggressiveChars'\n | 'balancedChars'\n | 'conservativeChars'\n | 'scoredSegments'\n | 'autoKeptSegments'\n | 'unparsedScoreAnswers'\n>;\n\n/**\n * In-memory health of one System One backend.\n *\n * Every request the backend sends updates it: a success clears the failure\n * fields, a failure records when and why it happened and counts the run. It is\n * deliberately not persisted — a restarted Host starts healthy and discovers\n * the truth with its first call.\n */\nexport interface BackendHealth {\n /** Whether the most recent request succeeded (true before the first request). */\n available: boolean;\n /** Reason of the most recent failure; cleared by a success. */\n lastFailureReason?: string;\n /** ISO timestamp of the most recent failure; cleared by a success. */\n lastFailureAt?: string;\n /** Consecutive failed requests; a single success resets it to 0. */\n consecutiveFailures: number;\n}\n\nexport interface ActionStep {\n tool: string;\n input: string;\n output?: string;\n error?: string;\n timestamp?: number;\n}\n\nexport interface StagnationCheckRequest {\n history: ActionStep[];\n goal?: string;\n windowSize?: number;\n}\n\nexport interface StagnationCheckResponse {\n isStuck: boolean;\n patternType?: 'repetition' | 'oscillation' | 'failing_retry' | 'zero_progress' | 'none';\n confidence: number;\n diagnosis?: string;\n recommendedIntervention?: string;\n latencyMs: number;\n}\n\n/**\n * Session facts one routing decision reasons about.\n *\n * They exist for prompt-cache affinity: switching a session onto another\n * physical model invalidates the upstream prompt prefix cache, so the decision\n * needs to know which model holds the cached prefix and how much context is\n * already in it. Every field is optional — a caller that knows nothing about\n * the session (a hand-built one-shot call) simply omits the block.\n */\nexport interface RouteRequestState {\n /** Physical `provider:model` the session is currently using, when known. */\n currentModel?: string;\n /** Estimated tokens of the session context accumulated so far. */\n contextTokens?: number;\n /** Character count the token estimate was derived from. */\n contextChars?: number;\n}\n\n/** One candidate of a {@link RouteRequest}. */\nexport interface RouteCandidateItem {\n name: string;\n description: string;\n type?: 'tool' | 'skill' | 'action';\n /**\n * Whether this candidate is the physical model the session already uses.\n * Returning it costs no cache miss; a backend that builds a prompt should\n * say so next to the candidate.\n */\n current?: boolean;\n}\n\nexport interface RouteRequest {\n goal: string;\n candidates: RouteCandidateItem[];\n topK?: number;\n /** Cache-affinity facts: the model in use and the accumulated context size. */\n state?: RouteRequestState;\n /**\n * Decision instructions the backend must carry into its prompt — the\n * cache-affinity policy (\"keep the current model unless clearly outmatched\").\n */\n instructions?: string;\n}\n\nexport interface RouteResponse {\n rankedCandidates: Array<{ name: string; score: number; reason?: string }>;\n bestCandidate?: string;\n latencyMs: number;\n}\n\n/**\n * One batch of sentences a closing check must classify before it may verify\n * anything.\n *\n * The candidates are chosen deterministically (the last few sentences of the\n * turn), but *which* of them claims completion is a semantic question: a word\n * list would miss a Chinese \"全部通过\" and read a negated \"not complete\" as the\n * opposite. A backend that can answer exposes `classifyClaims`; one that cannot\n * leaves the closing check on its fail-open path.\n */\nexport interface ClaimClassificationRequest {\n /** Candidate sentences, in the order the caller will treat them. */\n statements: string[];\n /** What the turn was doing, so the classifier reads the sentences in context. */\n intent: string;\n /** Extra context (the turn's own summary) when the caller has one. */\n context?: string;\n}\n\n/** One sentence's classification. */\nexport interface ClaimClassification {\n statement: string;\n /** Whether the winning criterion says the sentence claims completion. */\n isClaim: boolean;\n /** Probability of the completion-claim criterion, in `[0, 1]`. */\n confidence: number;\n}\n\n/** The classification answer for one closing candidate batch. */\nexport interface ClaimClassificationResponse {\n /** One entry per submitted statement, in submission order when answered. */\n results: ClaimClassification[];\n latencyMs: number;\n}\n\n/**\n * Common interface for decision backends (Jev official, Simple-Jev, vLLM, mock)\n */\nexport interface DecisionBackend {\n readonly name: string;\n readonly model: string;\n \n choice(req: ChoiceRequest): Promise<ChoiceResponse>;\n gate(req: GateRequest): Promise<GateResponse>;\n prune(req: PruneRequest): Promise<PruneResponse>;\n checkStagnation(req: StagnationCheckRequest): Promise<StagnationCheckResponse>;\n route(req: RouteRequest): Promise<RouteResponse>;\n /** Classify completion-claim candidates, when the backend can answer at all. */\n classifyClaims?(req: ClaimClassificationRequest): Promise<ClaimClassificationResponse>;\n /**\n * Health of the backend's outbound conversation, when it has one.\n *\n * In-process backends (mock) serve every call locally and simply omit this:\n * absence means \"healthy by construction\", not \"unknown\".\n */\n health?(): BackendHealth;\n}\n\nexport type SystemOneBackend = DecisionBackend;\n\n"]}
|
package/dist/cli/index.js
CHANGED
|
@@ -12,6 +12,7 @@ import { ToolResultPruner } from '../core/prune.js';
|
|
|
12
12
|
import { DecisionLedger } from '../core/ledger.js';
|
|
13
13
|
import { ReflexScreenService } from '../core/screen.js';
|
|
14
14
|
import { fitIsotonicRegression, calculateECE } from '../core/calibrate.js';
|
|
15
|
+
import { runHookCli } from '../hook/cli.js';
|
|
15
16
|
const __filename = fileURLToPath(import.meta.url);
|
|
16
17
|
const __dirname = path.dirname(__filename);
|
|
17
18
|
async function main() {
|
|
@@ -238,9 +239,9 @@ async function main() {
|
|
|
238
239
|
break;
|
|
239
240
|
}
|
|
240
241
|
case 'hook': {
|
|
241
|
-
//
|
|
242
|
-
|
|
243
|
-
|
|
242
|
+
// Command-hook dispatcher: reads one host event on stdin and writes one
|
|
243
|
+
// protocol JSON object on stdout. See docs/design/v0.2.0-harness-plugins.md §2.5.
|
|
244
|
+
await runHookCli(args.slice(1));
|
|
244
245
|
break;
|
|
245
246
|
}
|
|
246
247
|
case 'help':
|
|
@@ -256,6 +257,7 @@ Commands:
|
|
|
256
257
|
setup [target] Configure target harness (claude | codex | agy | all)
|
|
257
258
|
gate [options] Evaluate assertions against evidence (fail-closed)
|
|
258
259
|
prune [options] Prune lengthy tool outputs on stdin
|
|
260
|
+
hook <event> Command-hook entry (pretooluse|posttooluse|postfailure|stop|substop|sessionstart|sessionend)
|
|
259
261
|
ledger Show decision ledger summary and token savings
|
|
260
262
|
help Display this help message
|
|
261
263
|
|
package/dist/cli/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/cli/index.ts"],"names":[],"mappings":";AACA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,qBAAqB,EAAE,YAAY,EAAgC,MAAM,sBAAsB,CAAC;AAEzG,MAAM,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAClD,MAAM,SAA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9C,OAAO,CAAC,GAAG,CAAC,mBAAmB,SAAS,kBAAkB,QAAQ,KAAK,CAAC,CAAC,CAAC,SAAS,GAAG,QAAQ,CAAC,GAAG,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC;YAC3J,OAAO,CAAC,GAAG,CAAC,mBAAmB,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;YAC9C,MAAM;QACR,CAAC;QAED,KAAK,MAAM,CAAC,CAAC,CAAC;YACZ,gDAAgD;YAChD,MAAM,QAAQ,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,SAAS,CAAC;YACtC,yBAAyB;YACzB,MAAM;QACR,CAAC;QAED,KAAK,MAAM,CAAC;QACZ,OAAO,CAAC,CAAC,CAAC;YACR,OAAO,CAAC,GAAG,CAAC;;;;;;;;;;;;;;;;;;;CAmBjB,CAAC,CAAC;YACG,MAAM;QACR,CAAC;IACH,CAAC;AACH,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;IACnB,OAAO,CAAC,KAAK,CAAC,wBAAwB,EAAE,GAAG,CAAC,CAAC;IAC7C,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { fileURLToPath } from 'url';\nimport { ReflexMcpServer } from '../mcp/server.js';\nimport { ClaudeAdapter } from '../adapters/claude.js';\nimport { CodexAdapter } from '../adapters/codex.js';\nimport { AgyAdapter } from '../adapters/agy.js';\nimport { createDecisionBackend } from '../backend/factory.js';\nimport { ReflexGateService } from '../core/gate.js';\nimport { ToolResultPruner } from '../core/prune.js';\nimport { DecisionLedger } from '../core/ledger.js';\nimport { ReflexScreenService } from '../core/screen.js';\nimport { fitIsotonicRegression, calculateECE, CalibrationCurve, Calibrator } from '../core/calibrate.js';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nasync function main() {\n const args = process.argv.slice(2);\n const command = args[0] || 'help';\n\n switch (command) {\n case 'mcp': {\n const server = new ReflexMcpServer();\n server.start();\n break;\n }\n\n case 'setup': {\n const target = args[1] || 'all';\n const workspaceDir = process.cwd();\n // Locate the CLI entrypoint\n const entrypoint = path.resolve(__dirname, 'index.js');\n\n console.log(`[Harness Reflex] Setting up plugin for target: ${target}`);\n console.log(`[Harness Reflex] Workspace: ${workspaceDir}`);\n console.log(`[Harness Reflex] Binary: ${entrypoint}\\n`);\n\n if (target === 'claude' || target === 'all') {\n const { configPath } = ClaudeAdapter.configureMcp(workspaceDir, entrypoint);\n console.log(` ✓ Claude Code MCP config written to ${configPath}`);\n console.log(` (Added 'harness-reflex' server to .mcp.json)`);\n }\n\n if (target === 'codex' || target === 'all') {\n const { configPath } = CodexAdapter.configureCodex(workspaceDir, entrypoint);\n console.log(` ✓ Codex CLI MCP config written to ${configPath}`);\n }\n\n if (target === 'agy' || target === 'all') {\n const { pluginDir } = AgyAdapter.configureAgy(workspaceDir, entrypoint);\n console.log(` ✓ Antigravity (AGY) plugin written to ${pluginDir}`);\n console.log(` (Includes plugin.json, mcp_config.json, hooks.json, rules/AGENTS.md)`);\n }\n\n console.log('\\nSetup complete! You can now start or reload Claude Code, Codex, or AGY.');\n break;\n }\n\n case 'gate': {\n // CLI gate runner: harness-reflex gate --statement \"Tests pass\" --evidence \"...\"\n let statement = '';\n let evidence = '';\n for (let i = 1; i < args.length; i++) {\n if (args[i] === '--statement' || args[i] === '-s') statement = args[++i];\n if (args[i] === '--evidence' || args[i] === '-e') evidence = args[++i];\n }\n\n if (!statement) {\n console.error('Error: --statement is required.');\n process.exit(1);\n }\n\n if (!evidence && !process.stdin.isTTY) {\n // Read evidence from stdin\n evidence = fs.readFileSync(0, 'utf8');\n }\n\n const backend = createDecisionBackend();\n const gate = new ReflexGateService(backend);\n const res = await gate.verify([{ statement }], evidence);\n\n console.log(JSON.stringify(res, null, 2));\n process.exit(res.passed ? 0 : 1);\n }\n\n case 'prune': {\n let intent = 'extract error and results';\n let raw = '';\n for (let i = 1; i < args.length; i++) {\n if (args[i] === '--intent') intent = args[++i];\n }\n\n if (!process.stdin.isTTY) {\n raw = fs.readFileSync(0, 'utf8');\n }\n\n const backend = createDecisionBackend();\n const pruner = new ToolResultPruner(backend);\n const res = await pruner.prune(raw, { intent });\n\n console.log(res.processedOutput);\n break;\n }\n\n case 'ledger': {\n const ledger = DecisionLedger.getInstance();\n const summary = ledger.getSummary();\n console.log('=== Harness Reflex Decision Ledger ===');\n console.log(`Total Decisions: ${summary.totalCalls}`);\n console.log(`Calls by Type: ${JSON.stringify(summary.callsByType)}`);\n console.log(`Tokens Saved: ${summary.totalTokensSaved.toLocaleString()}`);\n console.log(`Est. Cost Saved: $${summary.estimatedCostSavedUsd.toFixed(4)} USD`);\n console.log(`Avg Latency: ${summary.avgLatencyMs} ms`);\n console.log(`Gate Pass/Fail: ${summary.gatePassedCount} passed / ${summary.gateFailedCount} failed`);\n console.log(`Stagnation Alarms: ${summary.stagnationAlerts}`);\n break;\n }\n\n case 'screen': {\n let content = '';\n let strict = false;\n for (let i = 1; i < args.length; i++) {\n if (args[i] === '--content' || args[i] === '-c') content = args[++i];\n if (args[i] === '--strict') strict = true;\n }\n if (!content && !process.stdin.isTTY) {\n content = fs.readFileSync(0, 'utf8');\n }\n\n const backend = createDecisionBackend();\n const screener = new ReflexScreenService(backend);\n const res = await screener.screen({ content, strict });\n console.log(JSON.stringify(res, null, 2));\n process.exit(res.isSafe ? 0 : 1);\n }\n\n case 'choice': {\n let question = '';\n let optionsStr = '';\n let context = '';\n for (let i = 1; i < args.length; i++) {\n if (args[i] === '--question' || args[i] === '-q') question = args[++i];\n if (args[i] === '--options' || args[i] === '-o') optionsStr = args[++i];\n if (args[i] === '--context') context = args[++i];\n }\n if (!question || !optionsStr) {\n console.error('Usage: harness-reflex choice --question \"...\" --options \"opt1,opt2\" [--context \"...\"]');\n process.exit(1);\n }\n const options = optionsStr.split(',').map((o) => o.trim());\n const backend = createDecisionBackend();\n const res = await backend.choice({ question, options, context });\n console.log(JSON.stringify(res, null, 2));\n break;\n }\n\n case 'score': {\n let statement = '';\n let criteria = 'Rate alignment on a scale from 0.0 to 1.0';\n for (let i = 1; i < args.length; i++) {\n if (args[i] === '--statement' || args[i] === '-s') statement = args[++i];\n if (args[i] === '--criteria' || args[i] === '-c') criteria = args[++i];\n }\n if (!statement && !process.stdin.isTTY) {\n statement = fs.readFileSync(0, 'utf8');\n }\n const backend = createDecisionBackend();\n const evalRes = await backend.choice({\n question: `Evaluate statement against criteria: \"${criteria}\". Is alignment high, moderate, or low?`,\n options: ['High alignment (~0.9)', 'Moderate alignment (~0.5)', 'Poor alignment (~0.1)'],\n context: statement\n });\n const pHigh = evalRes.options.find((o) => o.label.includes('High'))?.probability || 0;\n const pMed = evalRes.options.find((o) => o.label.includes('Moderate'))?.probability || 0;\n const pLow = evalRes.options.find((o) => o.label.includes('Poor'))?.probability || 0;\n const score = Number((pHigh * 0.9 + pMed * 0.5 + pLow * 0.1).toFixed(3));\n console.log(JSON.stringify({ statement, score, distribution: { pHigh, pMed, pLow } }, null, 2));\n break;\n }\n\n case 'calibrate': {\n let datasetPath = '';\n let outputPath = path.join(process.cwd(), '.reflex', 'calibration.json');\n let targetModel = process.env.SYSTEM_ONE_MODEL || 'default-model';\n for (let i = 1; i < args.length; i++) {\n if (args[i] === '--dataset' || args[i] === '-d') datasetPath = args[++i];\n if (args[i] === '--output' || args[i] === '-o') outputPath = args[++i];\n if (args[i] === '--model' || args[i] === '-m') targetModel = args[++i];\n }\n\n if (!datasetPath) {\n console.error('Error: --dataset <file.json> is required for calibration.');\n process.exit(1);\n }\n\n console.log(`[Calibration] Loading samples from ${datasetPath}...`);\n const rawData = fs.readFileSync(datasetPath, 'utf8');\n const samples = JSON.parse(rawData);\n\n // Samples format: Array<{ rawProbability: number, groundTruth: 0 | 1 }>\n // If samples contain assertions/evidence, run backend.gate() first to obtain raw probabilities\n const fittedSamples: Array<{ rawProbability: number; groundTruth: 0 | 1 }> = [];\n const backend = createDecisionBackend();\n\n for (const s of samples) {\n if (typeof s.rawProbability === 'number') {\n fittedSamples.push({ rawProbability: s.rawProbability, groundTruth: s.groundTruth });\n } else if (s.assertion && s.evidence) {\n const res = await backend.gate({\n assertions: [{ statement: s.assertion }],\n evidence: s.evidence\n });\n const rawProb = res.results[0]?.confidence ?? 0.5;\n fittedSamples.push({ rawProbability: rawProb, groundTruth: s.groundTruth });\n }\n }\n\n console.log(`[Calibration] Fitting Isotonic Regression on ${fittedSamples.length} samples...`);\n const bins = fitIsotonicRegression(fittedSamples);\n const eceBefore = calculateECE(fittedSamples.map((s) => ({ probability: s.rawProbability, groundTruth: s.groundTruth })));\n\n // Calibrate samples to compute ECE after\n const calibratedSamples = fittedSamples.map((s) => {\n let cal = s.rawProbability;\n for (const bin of bins) {\n if (s.rawProbability >= bin.rawMin && s.rawProbability <= bin.rawMax) {\n cal = bin.calibrated;\n break;\n }\n }\n return { probability: cal, groundTruth: s.groundTruth };\n });\n const eceAfter = calculateECE(calibratedSamples);\n\n const curve: CalibrationCurve = {\n targetModel,\n taskType: 'gate_verification',\n method: 'isotonic',\n createdAt: new Date().toISOString(),\n bins,\n eceBefore,\n eceAfter\n };\n\n const outDir = path.dirname(outputPath);\n if (!fs.existsSync(outDir)) {\n fs.mkdirSync(outDir, { recursive: true });\n }\n fs.writeFileSync(outputPath, JSON.stringify(curve, null, 2), 'utf8');\n\n console.log(`✓ Calibration curve saved to ${outputPath}`);\n console.log(` Target Model: ${targetModel}`);\n console.log(` ECE Before: ${eceBefore} -> ECE After: ${eceAfter} (${(((eceBefore - eceAfter) / (eceBefore || 1)) * 100).toFixed(1)}% error reduction)`);\n console.log(` Fitted Bins: ${bins.length}`);\n break;\n }\n\n case 'hook': {\n // Internal hook dispatcher for AGY/Claude hooks\n const hookType = args[1] || 'default';\n // Hook executed silently\n break;\n }\n\n case 'help':\n default: {\n console.log(`\nHarness Reflex - System One Decision Runtime for Codex, Claude Code & AGY\n\nUsage:\n harness-reflex <command> [options]\n\nCommands:\n mcp Start Model Context Protocol (MCP) server over stdio\n setup [target] Configure target harness (claude | codex | agy | all)\n gate [options] Evaluate assertions against evidence (fail-closed)\n prune [options] Prune lengthy tool outputs on stdin\n ledger Show decision ledger summary and token savings\n help Display this help message\n\nEnvironment Variables:\n SYSTEM_ONE_BACKEND System One provider: 'jev' | 'vllm' | 'simple-jev' | 'mock' (default: mock)\n SYSTEM_ONE_API_KEY API key for the chosen System One provider (or JEV_API_KEY)\n SYSTEM_ONE_BASE_URL Base URL for System One provider (or JEV_BASE_URL, VLLM_BASE_URL)\n SYSTEM_ONE_MODEL Model identifier (e.g. 'jev-1.13.0', 'Qwen/Qwen2.5-7B-Instruct')\n`);\n break;\n }\n }\n}\n\nmain().catch((err) => {\n console.error('[Harness Reflex Error]', err);\n process.exit(1);\n});\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/cli/index.ts"],"names":[],"mappings":";AACA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,mBA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,CAAC;YAC5C,CAAC;YACD,EAAE,CAAC,aAAa,CAAC,UAAU,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;YAErE,OAAO,CAAC,GAAG,CAAC,gCAAgC,UAAU,EAAE,CAAC,CAAC;YAC1D,OAAO,CAAC,GAAG,CAAC,mBAAmB,WAAW,EAAE,CAAC,CAAC;YAC9C,OAAO,CAAC,GAAG,CAAC,mBAAmB,SAAS,kBAAkB,QAAQ,KAAK,CAAC,CAAC,CAAC,SAAS,GAAG,QAAQ,CAAC,GAAG,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC;YAC3J,OAAO,CAAC,GAAG,CAAC,mBAAmB,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;YAC9C,MAAM;QACR,CAAC;QAED,KAAK,MAAM,CAAC,CAAC,CAAC;YACZ,wEAAwE;YACxE,kFAAkF;YAClF,MAAM,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;YAChC,MAAM;QACR,CAAC;QAED,KAAK,MAAM,CAAC;QACZ,OAAO,CAAC,CAAC,CAAC;YACR,OAAO,CAAC,GAAG,CAAC;;;;;;;;;;;;;;;;;;;;CAoBjB,CAAC,CAAC;YACG,MAAM;QACR,CAAC;IACH,CAAC;AACH,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;IACnB,OAAO,CAAC,KAAK,CAAC,wBAAwB,EAAE,GAAG,CAAC,CAAC;IAC7C,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { fileURLToPath } from 'url';\nimport { ReflexMcpServer } from '../mcp/server.js';\nimport { ClaudeAdapter } from '../adapters/claude.js';\nimport { CodexAdapter } from '../adapters/codex.js';\nimport { AgyAdapter } from '../adapters/agy.js';\nimport { createDecisionBackend } from '../backend/factory.js';\nimport { ReflexGateService } from '../core/gate.js';\nimport { ToolResultPruner } from '../core/prune.js';\nimport { DecisionLedger } from '../core/ledger.js';\nimport { ReflexScreenService } from '../core/screen.js';\nimport { fitIsotonicRegression, calculateECE, CalibrationCurve, Calibrator } from '../core/calibrate.js';\nimport { runHookCli } from '../hook/cli.js';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nasync function main() {\n const args = process.argv.slice(2);\n const command = args[0] || 'help';\n\n switch (command) {\n case 'mcp': {\n const server = new ReflexMcpServer();\n server.start();\n break;\n }\n\n case 'setup': {\n const target = args[1] || 'all';\n const workspaceDir = process.cwd();\n // Locate the CLI entrypoint\n const entrypoint = path.resolve(__dirname, 'index.js');\n\n console.log(`[Harness Reflex] Setting up plugin for target: ${target}`);\n console.log(`[Harness Reflex] Workspace: ${workspaceDir}`);\n console.log(`[Harness Reflex] Binary: ${entrypoint}\\n`);\n\n if (target === 'claude' || target === 'all') {\n const { configPath } = ClaudeAdapter.configureMcp(workspaceDir, entrypoint);\n console.log(` ✓ Claude Code MCP config written to ${configPath}`);\n console.log(` (Added 'harness-reflex' server to .mcp.json)`);\n }\n\n if (target === 'codex' || target === 'all') {\n const { configPath } = CodexAdapter.configureCodex(workspaceDir, entrypoint);\n console.log(` ✓ Codex CLI MCP config written to ${configPath}`);\n }\n\n if (target === 'agy' || target === 'all') {\n const { pluginDir } = AgyAdapter.configureAgy(workspaceDir, entrypoint);\n console.log(` ✓ Antigravity (AGY) plugin written to ${pluginDir}`);\n console.log(` (Includes plugin.json, mcp_config.json, hooks.json, rules/AGENTS.md)`);\n }\n\n console.log('\\nSetup complete! You can now start or reload Claude Code, Codex, or AGY.');\n break;\n }\n\n case 'gate': {\n // CLI gate runner: harness-reflex gate --statement \"Tests pass\" --evidence \"...\"\n let statement = '';\n let evidence = '';\n for (let i = 1; i < args.length; i++) {\n if (args[i] === '--statement' || args[i] === '-s') statement = args[++i];\n if (args[i] === '--evidence' || args[i] === '-e') evidence = args[++i];\n }\n\n if (!statement) {\n console.error('Error: --statement is required.');\n process.exit(1);\n }\n\n if (!evidence && !process.stdin.isTTY) {\n // Read evidence from stdin\n evidence = fs.readFileSync(0, 'utf8');\n }\n\n const backend = createDecisionBackend();\n const gate = new ReflexGateService(backend);\n const res = await gate.verify([{ statement }], evidence);\n\n console.log(JSON.stringify(res, null, 2));\n process.exit(res.passed ? 0 : 1);\n }\n\n case 'prune': {\n let intent = 'extract error and results';\n let raw = '';\n for (let i = 1; i < args.length; i++) {\n if (args[i] === '--intent') intent = args[++i];\n }\n\n if (!process.stdin.isTTY) {\n raw = fs.readFileSync(0, 'utf8');\n }\n\n const backend = createDecisionBackend();\n const pruner = new ToolResultPruner(backend);\n const res = await pruner.prune(raw, { intent });\n\n console.log(res.processedOutput);\n break;\n }\n\n case 'ledger': {\n const ledger = DecisionLedger.getInstance();\n const summary = ledger.getSummary();\n console.log('=== Harness Reflex Decision Ledger ===');\n console.log(`Total Decisions: ${summary.totalCalls}`);\n console.log(`Calls by Type: ${JSON.stringify(summary.callsByType)}`);\n console.log(`Tokens Saved: ${summary.totalTokensSaved.toLocaleString()}`);\n console.log(`Est. Cost Saved: $${summary.estimatedCostSavedUsd.toFixed(4)} USD`);\n console.log(`Avg Latency: ${summary.avgLatencyMs} ms`);\n console.log(`Gate Pass/Fail: ${summary.gatePassedCount} passed / ${summary.gateFailedCount} failed`);\n console.log(`Stagnation Alarms: ${summary.stagnationAlerts}`);\n break;\n }\n\n case 'screen': {\n let content = '';\n let strict = false;\n for (let i = 1; i < args.length; i++) {\n if (args[i] === '--content' || args[i] === '-c') content = args[++i];\n if (args[i] === '--strict') strict = true;\n }\n if (!content && !process.stdin.isTTY) {\n content = fs.readFileSync(0, 'utf8');\n }\n\n const backend = createDecisionBackend();\n const screener = new ReflexScreenService(backend);\n const res = await screener.screen({ content, strict });\n console.log(JSON.stringify(res, null, 2));\n process.exit(res.isSafe ? 0 : 1);\n }\n\n case 'choice': {\n let question = '';\n let optionsStr = '';\n let context = '';\n for (let i = 1; i < args.length; i++) {\n if (args[i] === '--question' || args[i] === '-q') question = args[++i];\n if (args[i] === '--options' || args[i] === '-o') optionsStr = args[++i];\n if (args[i] === '--context') context = args[++i];\n }\n if (!question || !optionsStr) {\n console.error('Usage: harness-reflex choice --question \"...\" --options \"opt1,opt2\" [--context \"...\"]');\n process.exit(1);\n }\n const options = optionsStr.split(',').map((o) => o.trim());\n const backend = createDecisionBackend();\n const res = await backend.choice({ question, options, context });\n console.log(JSON.stringify(res, null, 2));\n break;\n }\n\n case 'score': {\n let statement = '';\n let criteria = 'Rate alignment on a scale from 0.0 to 1.0';\n for (let i = 1; i < args.length; i++) {\n if (args[i] === '--statement' || args[i] === '-s') statement = args[++i];\n if (args[i] === '--criteria' || args[i] === '-c') criteria = args[++i];\n }\n if (!statement && !process.stdin.isTTY) {\n statement = fs.readFileSync(0, 'utf8');\n }\n const backend = createDecisionBackend();\n const evalRes = await backend.choice({\n question: `Evaluate statement against criteria: \"${criteria}\". Is alignment high, moderate, or low?`,\n options: ['High alignment (~0.9)', 'Moderate alignment (~0.5)', 'Poor alignment (~0.1)'],\n context: statement\n });\n const pHigh = evalRes.options.find((o) => o.label.includes('High'))?.probability || 0;\n const pMed = evalRes.options.find((o) => o.label.includes('Moderate'))?.probability || 0;\n const pLow = evalRes.options.find((o) => o.label.includes('Poor'))?.probability || 0;\n const score = Number((pHigh * 0.9 + pMed * 0.5 + pLow * 0.1).toFixed(3));\n console.log(JSON.stringify({ statement, score, distribution: { pHigh, pMed, pLow } }, null, 2));\n break;\n }\n\n case 'calibrate': {\n let datasetPath = '';\n let outputPath = path.join(process.cwd(), '.reflex', 'calibration.json');\n let targetModel = process.env.SYSTEM_ONE_MODEL || 'default-model';\n for (let i = 1; i < args.length; i++) {\n if (args[i] === '--dataset' || args[i] === '-d') datasetPath = args[++i];\n if (args[i] === '--output' || args[i] === '-o') outputPath = args[++i];\n if (args[i] === '--model' || args[i] === '-m') targetModel = args[++i];\n }\n\n if (!datasetPath) {\n console.error('Error: --dataset <file.json> is required for calibration.');\n process.exit(1);\n }\n\n console.log(`[Calibration] Loading samples from ${datasetPath}...`);\n const rawData = fs.readFileSync(datasetPath, 'utf8');\n const samples = JSON.parse(rawData);\n\n // Samples format: Array<{ rawProbability: number, groundTruth: 0 | 1 }>\n // If samples contain assertions/evidence, run backend.gate() first to obtain raw probabilities\n const fittedSamples: Array<{ rawProbability: number; groundTruth: 0 | 1 }> = [];\n const backend = createDecisionBackend();\n\n for (const s of samples) {\n if (typeof s.rawProbability === 'number') {\n fittedSamples.push({ rawProbability: s.rawProbability, groundTruth: s.groundTruth });\n } else if (s.assertion && s.evidence) {\n const res = await backend.gate({\n assertions: [{ statement: s.assertion }],\n evidence: s.evidence\n });\n const rawProb = res.results[0]?.confidence ?? 0.5;\n fittedSamples.push({ rawProbability: rawProb, groundTruth: s.groundTruth });\n }\n }\n\n console.log(`[Calibration] Fitting Isotonic Regression on ${fittedSamples.length} samples...`);\n const bins = fitIsotonicRegression(fittedSamples);\n const eceBefore = calculateECE(fittedSamples.map((s) => ({ probability: s.rawProbability, groundTruth: s.groundTruth })));\n\n // Calibrate samples to compute ECE after\n const calibratedSamples = fittedSamples.map((s) => {\n let cal = s.rawProbability;\n for (const bin of bins) {\n if (s.rawProbability >= bin.rawMin && s.rawProbability <= bin.rawMax) {\n cal = bin.calibrated;\n break;\n }\n }\n return { probability: cal, groundTruth: s.groundTruth };\n });\n const eceAfter = calculateECE(calibratedSamples);\n\n const curve: CalibrationCurve = {\n targetModel,\n taskType: 'gate_verification',\n method: 'isotonic',\n createdAt: new Date().toISOString(),\n bins,\n eceBefore,\n eceAfter\n };\n\n const outDir = path.dirname(outputPath);\n if (!fs.existsSync(outDir)) {\n fs.mkdirSync(outDir, { recursive: true });\n }\n fs.writeFileSync(outputPath, JSON.stringify(curve, null, 2), 'utf8');\n\n console.log(`✓ Calibration curve saved to ${outputPath}`);\n console.log(` Target Model: ${targetModel}`);\n console.log(` ECE Before: ${eceBefore} -> ECE After: ${eceAfter} (${(((eceBefore - eceAfter) / (eceBefore || 1)) * 100).toFixed(1)}% error reduction)`);\n console.log(` Fitted Bins: ${bins.length}`);\n break;\n }\n\n case 'hook': {\n // Command-hook dispatcher: reads one host event on stdin and writes one\n // protocol JSON object on stdout. See docs/design/v0.2.0-harness-plugins.md §2.5.\n await runHookCli(args.slice(1));\n break;\n }\n\n case 'help':\n default: {\n console.log(`\nHarness Reflex - System One Decision Runtime for Codex, Claude Code & AGY\n\nUsage:\n harness-reflex <command> [options]\n\nCommands:\n mcp Start Model Context Protocol (MCP) server over stdio\n setup [target] Configure target harness (claude | codex | agy | all)\n gate [options] Evaluate assertions against evidence (fail-closed)\n prune [options] Prune lengthy tool outputs on stdin\n hook <event> Command-hook entry (pretooluse|posttooluse|postfailure|stop|substop|sessionstart|sessionend)\n ledger Show decision ledger summary and token savings\n help Display this help message\n\nEnvironment Variables:\n SYSTEM_ONE_BACKEND System One provider: 'jev' | 'vllm' | 'simple-jev' | 'mock' (default: mock)\n SYSTEM_ONE_API_KEY API key for the chosen System One provider (or JEV_API_KEY)\n SYSTEM_ONE_BASE_URL Base URL for System One provider (or JEV_BASE_URL, VLLM_BASE_URL)\n SYSTEM_ONE_MODEL Model identifier (e.g. 'jev-1.13.0', 'Qwen/Qwen2.5-7B-Instruct')\n`);\n break;\n }\n }\n}\n\nmain().catch((err) => {\n console.error('[Harness Reflex Error]', err);\n process.exit(1);\n});\n"]}
|