Skip to content

armgit / ECC

Public Imported from GitHub
0

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

fix: prepare six focused ECC reliability repairs

haelyrac4b83259451c
diff --cc manifests/context-packs/[email protected]
index 7b0d69770,bd5dd19ec,7b0d69770,ed3be0d40,ed3be0d40,ed3be0d40,7b0d69770..80601cda6
--- a/manifests/context-packs/[email protected]
+++ b/manifests/context-packs/[email protected]
@@@@@@@@ -1,295 -1,1 -1,295 -1,295 -1,295 -1,295 -1,295 +1,295 @@@@@@@@
- {"coverage":{"skills":302,"withTriggers":32},"generatedAt":"2026-09-24T23:51:22.784Z","id":"skill-triggers@1","model":{"effort":null,"id":"hand-seeded","source":"manual-curation-pending-regeneration"},"registryDigest":"ffac257ab8a4b8e7450ddf1f933e65335542fc444034c8242dd758346417d76e","schemaVersion":1,"triggers":{"skill:api-connector-builder":["add api integration","new provider connector","match existing integration pattern"],"skill:api-design":["rest endpoint design","pagination api","status codes","api versioning","rate limiting api","resource naming","filtering api","api error responses","offset pagination","limit query parameter","pagination defaults"],"skill:backend-patterns":["express api","node backend architecture","nextjs api routes","server side patterns","data access layer","static file server","url path handling","file server"],"skill:browser-qa":["deployed feature test","visual regression screenshots","core web vitals check","axe accessibility audit","ship do not ship","staging verification"],"skill:canary-watch":["post deploy monitoring","smoke test url","production url check","console errors production","sse stream check","after deploy verification"],"skill:code-tour":["onboarding walkthrough","explain subsystem","architecture tour","pr walkthrough","rca tour"],"skill:coding-standards":["code review standards","naming conventions","readability review","immutability conventions","fix naming typo","export naming","consistent exports"],"skill:content-hash-cache-pattern":["cache file processing","content addressed cache","sha256 hash cache"],"skill:database-migrations":["zero downtime migration","schema change production","add column large table","backfill data","expand contract","concurrent index","migration rollback","prisma migration","django migration"],"skill:deployment-patterns":["ci cd setup","dockerize app","health checks","rollback strategy","production readiness","deploy pipeline","containerize application"],"skill:design-system":["design tokens","visual consistency audit","css custom properties","ui audit","design system bootstrap"],"skill:django-patterns":["django orm","drf api","django rest framework","django caching","django signals","django middleware"],"skill:django-security":["django authentication","csrf protection","sql injection prevention","xss prevention","django deployment security","role based access control","authorization middleware","permissions checks"],"skill:docker-patterns":["dockerfile review","docker compose setup","container security","multi service orchestration"],"skill:error-handling":["error types","retry logic","circuit breaker","user facing errors","exception handling patterns","typed errors","error boundaries","go error handling","custom error class","error codes","config validation"],"skill:evm-token-decimals":["token decimals","wei conversion","erc20 balance off","bridge token precision"],"skill:frontend-a11y":["aria attributes","screen reader support","focus management","semantic html","form labeling","keyboard navigation react","a11y lint errors"],"skill:git-workflow":["merge vs rebase","commit conventions","resolve merge conflict","branching strategy","clean up commits","pull request cleanup","git history tidy"],"skill:hexagonal-architecture":["ports and adapters","dependency injection boundaries","decouple domain from io"],"skill:kubernetes-patterns":["kubernetes manifests","kubectl debugging","pod probes","k8s rbac","autoscaling config","configmap secrets"],"skill:orch-fix-defect":["fix a bug","broken behavior","regression fix","reproduce bug","defect repair"],"skill:postgres-patterns":["slow postgres query","query optimization","index design","rls policies","supabase schema","postgres indexing","database performance","schema design postgres","postgres driver","node postgres","query planner"],"skill:python-patterns":["pythonic code","pep 8","type hints python","python code review","idiomatic python"],"skill:python-testing":["pytest fixtures","mocking python","parametrized tests","coverage python","tdd python"],"skill:redis-patterns":["cache aside pattern","distributed lock","redis rate limiting","cache invalidation"],"skill:regex-vs-llm-structured-text":["parse invoice","extract receipt data","text extraction pipeline","parse form fields","cheap document parser","extract table data","parse log lines","parse access logs","common log format","log line parsing"],"skill:rust-patterns":["rust ownership","borrow checker","rust error handling","traits rust","rust concurrency","idiomatic rust"],"skill:search-first":["find existing library","npm package research","before writing custom code","evaluate existing tools","add dependency research"],"skill:security-review":["security audit","authentication review","sanitize user input","secrets handling","payment security checklist","prevent injection attacks","secure api endpoints","authn authz review","vulnerability checklist","input validation security","parameterized queries","sql injection"],"skill:security-scan":["audit claude config","claudemd security","mcp server audit","agentshield scan","hook configuration audit","settings json security"],"skill:tdd-workflow":["write test first","failing test","red green refactor","test driven development","regression test first","write a regression test"],"skill:verification-loop":["pre pr checks","verification report","quality gates","build lint test coverage","before creating a pr"]},"triggersDigest":"25b97a9e06fc336c7cf95ab854ed1a41033a54bcd6e1fb1cf69dc906332462aa"}
+ {
+ "coverage": {
--- "skills": 306,
+ +++ "skills": 311,
+ "withTriggers": 33
+ },
+ "generatedAt": "2026-09-24T23:51:22.784Z",
+ "id": "skill-triggers@1",
+ "model": {
+ "effort": null,
+ "id": "hand-seeded",
+ "source": "manual-curation-pending-regeneration"
+ },
- - - "registryDigest": "7144a76d4b920efacf5a8d678ec6757ea34410834c82f4e226b6a32af6f8c540",
--- "registryDigest": "16549b53055bf5c106e51ca7fb2fe68f8a705b5f6bad40d388349320caedfa63",
+++++++ "registryDigest": "346c515abe4e1981d9dbf3e92e5532c116c5626c2d2c7d2a4bee4756a3f7c675",
+ "schemaVersion": 1,
+ "triggers": {
+ "skill:agent-runtime-gateway-smoke-test": [
+ "test local agent gateway",
+ "remote sandbox callback smoke test",
+ "agent task stuck after dispatch",
+ "verify gateway tunnel",
+ "restore web api after agent test"
+ ],
+ "skill:api-connector-builder": [
+ "add api integration",
+ "new provider connector",
+ "match existing integration pattern"
+ ],
+ "skill:api-design": [
+ "rest endpoint design",
+ "pagination api",
+ "status codes",
+ "api versioning",
+ "rate limiting api",
+ "resource naming",
+ "filtering api",
+ "api error responses",
+ "offset pagination",
+ "limit query parameter",
+ "pagination defaults"
+ ],
+ "skill:backend-patterns": [
+ "express api",
+ "node backend architecture",
+ "nextjs api routes",
+ "server side patterns",
+ "data access layer",
+ "static file server",
+ "url path handling",
+ "file server"
+ ],
+ "skill:browser-qa": [
+ "deployed feature test",
+ "visual regression screenshots",
+ "core web vitals check",
+ "axe accessibility audit",
+ "ship do not ship",
+ "staging verification"
+ ],
+ "skill:canary-watch": [
+ "post deploy monitoring",
+ "smoke test url",
+ "production url check",
+ "console errors production",
+ "sse stream check",
+ "after deploy verification"
+ ],
+ "skill:code-tour": [
+ "onboarding walkthrough",
+ "explain subsystem",
+ "architecture tour",
+ "pr walkthrough",
+ "rca tour"
+ ],
+ "skill:coding-standards": [
+ "code review standards",
+ "naming conventions",
+ "readability review",
+ "immutability conventions",
+ "fix naming typo",
+ "export naming",
+ "consistent exports"
+ ],
+ "skill:content-hash-cache-pattern": [
+ "cache file processing",
+ "content addressed cache",
+ "sha256 hash cache"
+ ],
+ "skill:database-migrations": [
+ "zero downtime migration",
+ "schema change production",
+ "add column large table",
+ "backfill data",
+ "expand contract",
+ "concurrent index",
+ "migration rollback",
+ "prisma migration",
+ "django migration"
+ ],
+ "skill:deployment-patterns": [
+ "ci cd setup",
+ "dockerize app",
+ "health checks",
+ "rollback strategy",
+ "production readiness",
+ "deploy pipeline",
+ "containerize application"
+ ],
+ "skill:design-system": [
+ "design tokens",
+ "visual consistency audit",
+ "css custom properties",
+ "ui audit",
+ "design system bootstrap"
+ ],
+ "skill:django-patterns": [
+ "django orm",
+ "drf api",
+ "django rest framework",
+ "django caching",
+ "django signals",
+ "django middleware"
+ ],
+ "skill:django-security": [
+ "django authentication",
+ "csrf protection",
+ "sql injection prevention",
+ "xss prevention",
+ "django deployment security",
+ "role based access control",
+ "authorization middleware",
+ "permissions checks"
+ ],
+ "skill:docker-patterns": [
+ "dockerfile review",
+ "docker compose setup",
+ "container security",
+ "multi service orchestration"
+ ],
+ "skill:error-handling": [
+ "error types",
+ "retry logic",
+ "circuit breaker",
+ "user facing errors",
+ "exception handling patterns",
+ "typed errors",
+ "error boundaries",
+ "go error handling",
+ "custom error class",
+ "error codes",
+ "config validation"
+ ],
+ "skill:evm-token-decimals": [
+ "token decimals",
+ "wei conversion",
+ "erc20 balance off",
+ "bridge token precision"
+ ],
+ "skill:frontend-a11y": [
+ "aria attributes",
+ "screen reader support",
+ "focus management",
+ "semantic html",
+ "form labeling",
+ "keyboard navigation react",
+ "a11y lint errors"
+ ],
+ "skill:git-workflow": [
+ "merge vs rebase",
+ "commit conventions",
+ "resolve merge conflict",
+ "branching strategy",
+ "clean up commits",
+ "pull request cleanup",
+ "git history tidy"
+ ],
+ "skill:hexagonal-architecture": [
+ "ports and adapters",
+ "dependency injection boundaries",
+ "decouple domain from io"
+ ],
+ "skill:kubernetes-patterns": [
+ "kubernetes manifests",
+ "kubectl debugging",
+ "pod probes",
+ "k8s rbac",
+ "autoscaling config",
+ "configmap secrets"
+ ],
+ "skill:orch-fix-defect": [
+ "fix a bug",
+ "broken behavior",
+ "regression fix",
+ "reproduce bug",
+ "defect repair"
+ ],
+ "skill:postgres-patterns": [
+ "slow postgres query",
+ "query optimization",
+ "index design",
+ "rls policies",
+ "supabase schema",
+ "postgres indexing",
+ "database performance",
+ "schema design postgres",
+ "postgres driver",
+ "node postgres",
+ "query planner"
+ ],
+ "skill:python-patterns": [
+ "pythonic code",
+ "pep 8",
+ "type hints python",
+ "python code review",
+ "idiomatic python"
+ ],
+ "skill:python-testing": [
+ "pytest fixtures",
+ "mocking python",
+ "parametrized tests",
+ "coverage python",
+ "tdd python"
+ ],
+ "skill:redis-patterns": [
+ "cache aside pattern",
+ "distributed lock",
+ "redis rate limiting",
+ "cache invalidation"
+ ],
+ "skill:regex-vs-llm-structured-text": [
+ "parse invoice",
+ "extract receipt data",
+ "text extraction pipeline",
+ "parse form fields",
+ "cheap document parser",
+ "extract table data",
+ "parse log lines",
+ "parse access logs",
+ "common log format",
+ "log line parsing"
+ ],
+ "skill:rust-patterns": [
+ "rust ownership",
+ "borrow checker",
+ "rust error handling",
+ "traits rust",
+ "rust concurrency",
+ "idiomatic rust"
+ ],
+ "skill:search-first": [
+ "find existing library",
+ "npm package research",
+ "before writing custom code",
+ "evaluate existing tools",
+ "add dependency research"
+ ],
+ "skill:security-review": [
+ "security audit",
+ "authentication review",
+ "sanitize user input",
+ "secrets handling",
+ "payment security checklist",
+ "prevent injection attacks",
+ "secure api endpoints",
+ "authn authz review",
+ "vulnerability checklist",
+ "input validation security",
+ "parameterized queries",
+ "sql injection"
+ ],
+ "skill:security-scan": [
+ "audit claude config",
+ "claudemd security",
+ "mcp server audit",
+ "agentshield scan",
+ "hook configuration audit",
+ "settings json security"
+ ],
+ "skill:tdd-workflow": [
+ "write test first",
+ "failing test",
+ "red green refactor",
+ "test driven development",
+ "regression test first",
+ "write a regression test"
+ ],
+ "skill:verification-loop": [
+ "pre pr checks",
+ "verification report",
+ "quality gates",
+ "build lint test coverage",
+ "before creating a pr"
+ ]
+ },
+ "triggersDigest": "054898acb769893c46e5bd7037141f7be83fb775515ea1dbb52fb1c18aca19e6"
+ }
diff --cc pi/core/skills/agent-self-evaluation/scripts/evaluate.py
index 2d129c407,2d129c407,2d129c407,2d129c407,2d129c407,2d129c407,2d129c407..afedd37a9
--- a/pi/core/skills/agent-self-evaluation/scripts/evaluate.py
+++ b/pi/core/skills/agent-self-evaluation/scripts/evaluate.py
@@@@@@@@ -19,6 -19,6 -19,6 -19,6 -19,6 -19,6 -19,6 +19,7 @@@@@@@@ For production use, pair with an LLM ju
"""
import argparse
+++++++import errno
import re
import sys
from dataclasses import dataclass, field
@@@@@@@@ -368,7 -368,7 -368,7 -368,7 -368,7 -368,7 -368,7 +369,9 @@@@@@@@ def _read_file_or_text(path: Optional[s
try:
with open(path) as f:
return f.read()
------- except FileNotFoundError:
+++++++ except OSError as error:
+++++++ if error.errno not in (errno.ENOENT, errno.ENAMETOOLONG):
+++++++ raise
if required:
print(f"Error: output file '{path}' not found", file=sys.stderr)
sys.exit(1)
@@@@@@@@ -382,7 -382,7 -382,7 -382,7 -382,7 -382,7 -382,7 +385,10 @@@@@@@@ def _read_input(args: argparse.Namespac
print("Paste agent output (Ctrl+D to finish):")
return task, sys.stdin.read()
if args.output:
------- return _read_file_or_text(args.task), _read_file_or_text(args.output, required=True) or ""
+++++++ task = _read_file_or_text(args.task)
+++++++ if task is None and not sys.stdin.isatty():
+++++++ task = sys.stdin.read()
+++++++ return task, _read_file_or_text(args.output, required=True) or ""
return _read_file_or_text(args.task), sys.stdin.read()
diff --cc scripts/hooks/block-no-verify.js
index 1d19e5c35,6774ae75f,1d19e5c35,1d19e5c35,1d19e5c35,1d19e5c35,1d19e5c35..99589b299
--- a/scripts/hooks/block-no-verify.js
+++ b/scripts/hooks/block-no-verify.js
@@@@@@@@ -579,13 -579,24 -579,13 -579,13 -579,13 -579,13 -579,13 +579,24 @@@@@@@@ function readSedExecute(script, i, budg
return { end: j, parts: [], stdinExec: true };
}
-------// Text, label and filename operands run to end of line; all are data.
+++++++// Text and filename operands run to end of line; all are data.
function readSedLineOperand(script, i, budget) {
let end = i + 1;
while (end < script.length && script[end] !== '\n') { budget.spend(); end++; }
return { end, parts: [], stdinExec: false };
}
+ +++++// Branch and label commands (b, t, T, :) take a label that ends at `;` or
- // newline — verified against GNU sed 4.9: ':a;e cmd' and 'ba;e cmd' both
+++++++// newline, verified against GNU sed 4.9: ':a;e cmd' and 'ba;e cmd' both
+ +++++// parse the label up to `;` and still run the following `e`. Commands after
+ +++++// the label therefore continue to be scanned, so return the label end and
+ +++++// let the caller resume command parsing there.
+ +++++function readSedLabel(script, i, budget) {
+ +++++ let end = i + 1;
+ +++++ while (end < script.length && script[end] !== ';' && script[end] !== '\n') { budget.spend(); end++; }
+ +++++ return { end, parts: [], stdinExec: false };
+ +++++}
+ +++++
function readSedCommand(script, i, budget) {
const letter = script[i];
if (letter === 's') {
diff --cc scripts/lib/claude-scope-migration.js
index acb789f3b,acb789f3b,389c3de76,acb789f3b,acb789f3b,acb789f3b,acb789f3b..c4e00bc18
--- a/scripts/lib/claude-scope-migration.js
+++ b/scripts/lib/claude-scope-migration.js
@@@@@@@@ -171,8 -171,8 -229,8 -171,8 -171,8 -171,8 -171,8 +229,10 @@@@@@@@ function plannedActions(migration, dest
function verifySourceAndDestination(run, paths, migration, destinationScope, phase) {
const expectedScopes = [migration.sourceScope, destinationScope];
+++++++ const plugins = readPluginInventory(run, paths.projectRoot, phase);
+++++++ const destination = currentEccPlugins(plugins).find(plugin => plugin.scope === destinationScope);
return validateExpectedScopes(
------- readPluginInventory(run, paths.projectRoot, phase),
+++++++ plugins,
expectedScopes,
{
code: phase === 'concurrency-check'
@@@@@@@@ -183,7 -183,7 -241,7 -183,7 -183,7 -183,7 -183,7 +243,9 @@@@@@@@
? 'Claude plugin scopes changed during migration; the source was not removed.'
: `Could not verify ${CURRENT_PLUGIN_ID} at the destination before source cleanup.`,
phase,
------- recovery: recoveryCommands(null, destinationScope),
+++++++ recovery: destination && destination.enabled !== true
+++++++ ? enableRecoveryCommands(destinationScope)
+++++++ : recoveryCommands(null, destinationScope),
}
);
}
@@@@@@@@ -224,7 -224,7 -286,13 -224,7 -224,7 -224,7 -224,7 +290,12 @@@@@@@@ function uninstallSource(run, paths, mi
{
phase: 'source-uninstall',
observedScopes,
-- ---- recovery: recoveryCommands(migration.sourceScope, destinationScope),
++ ++++ recovery: [
++ ++++ 'claude plugin list --json',
- ...recoveryCommands(
- sourcePresent ? migration.sourceScope : null,
- destinationScope
- ),
+++++++ ...(observedScopes.length === 0
+++++++ ? [`ecc setup --mode claude-plugin --scope ${destinationScope} --yes`]
+++++++ : recoveryCommands(sourcePresent ? migration.sourceScope : null, destinationScope)),
++ ++++ ],
}
);
}
diff --cc scripts/lib/context-profiles.js
index de80d1142,de80d1142,de80d1142,de80d1142,de80d1142,de80d1142,57a0db2c3..31b0a2266
--- a/scripts/lib/context-profiles.js
+++ b/scripts/lib/context-profiles.js
@@@@@@@@ -86,13 -86,13 -86,13 -86,13 -86,13 -86,13 -86,26 +86,28 @@@@@@@@ function estimateMetadata(entries, targ
};
}
------ function compileContextProfile({
------ repoRoot = DEFAULT_REPO_ROOT, profileId = 'lean@1', selectionMode = 'manual',
------ target = 'codex', include = [], exclude = [],
------ } = {}) {
++++++ function validatePlanOptions({ selectionMode = 'manual', target = 'codex' }) {
validateTarget(target);
if (!MODES.includes(selectionMode)) throw new Error(`Unknown selection mode: ${selectionMode}`);
++++++ }
++++++
++++++ function compileContextProfile(options = {}) {
+++++++ return compileContextProfileWithRegistry(options).plan;
+++++++}
+++++++
+++++++// Keep registry reuse inside this call to the canonical loader. Callers can
+++++++// consume the snapshot, but cannot supply a cached or caller-built registry.
+++++++function compileContextProfileWithRegistry({ repoRoot = DEFAULT_REPO_ROOT, ...options } = {}) {
++++++ validatePlanOptions(options);
- return compileContextPlan(loadContextRegistry({ repoRoot: options.repoRoot || DEFAULT_REPO_ROOT }), options);
+ const registry = loadContextRegistry({ repoRoot });
+++++++ return { registry, plan: compileContextPlan(registry, { repoRoot, ...options }) };
++++++ }
++++++
-/**
- * Compile a plan against a registry the caller loaded in the same call, so a
- * caller that also needs the registry hashes its sources once. Callers pass
- * the result of `loadContextRegistry` directly; nothing keeps one across calls.
- */
++++++ function compileContextPlan(registry, {
++++++ repoRoot = DEFAULT_REPO_ROOT, profileId = 'lean@1', selectionMode = 'manual',
++++++ target = 'codex', include = [], exclude = [],
++++++ } = {}) {
++++++ validatePlanOptions({ selectionMode, target });
const profile = loadContextProfile(profileId, { repoRoot });
if (profile.registryId !== registry.id) throw new Error('Profile registry ID mismatch');
const selected = resolveSelection(registry, profile, include, exclude);
@@@@@@@@ -130,4 -130,4 -130,4 -130,4 -130,4 -130,4 -143,4 +145,4 @@@@@@@@
return plan;
}
------ module.exports = { compileContextProfile, explainContextEntry, loadContextProfile };
-module.exports = { compileContextProfile, compileContextPlan, explainContextEntry, loadContextProfile };
+++++++module.exports = { compileContextProfile, compileContextProfileWithRegistry, explainContextEntry, loadContextProfile };
diff --cc scripts/lib/context-selection.js
index 5a642d455,85a496800,5a642d455,6a925c033,6a925c033,6a925c033,eeef1d406..f732543ad
--- a/scripts/lib/context-selection.js
+++ b/scripts/lib/context-selection.js
@@@@@@@@ -1,8 -1,8 -1,8 -1,8 -1,8 -1,8 -1,8 +1,8 @@@@@@@@
'use strict';
const yaml = require('js-yaml');
-------const { loadContextRegistry, loadSkillTriggers } = require('./context-pack-registry');
------ const { compileContextProfile } = require('./context-profiles');
-const { compileContextPlan } = require('./context-profiles');
+++++++const { loadSkillTriggers } = require('./context-pack-registry');
+++++++const { compileContextProfileWithRegistry } = require('./context-profiles');
const { buildRetrievalIndex, searchRetrieval } = require('./context-retrieval');
const { DEFAULT_REPO_ROOT, createSourceReader, digestObject } = require('./context-profile-support');
@@@@@@@@ -26,156 -26,11 -26,156 -26,28 -26,28 -26,28 -26,156 +26,156 @@@@@@@@ const AUTO_ADMIT_MARGIN = 1.5
const FALLBACK_MIN_BM25 = 12;
const FALLBACK_MIN_TERMS = 2;
const FALLBACK_MARGIN = 1.1;
+
+ // Adapted from contributor PR #3480: rankings become suggestions only when
+ // an exact name or the fallback's absolute evidence floor supports them.
+ function meetsFallbackBar(candidate) {
+ return Boolean(candidate && candidate.bm25 >= FALLBACK_MIN_BM25
+ && Array.isArray(candidate.matchedTerms) && candidate.matchedTerms.length >= FALLBACK_MIN_TERMS);
+ }
+
+ function hasSuggestionEvidence(candidate) {
+ return Boolean(candidate && (candidate.exact || meetsFallbackBar(candidate)));
+ }
+
+ // Both tiers also require at least one matched term in the skill's name or
+ // curated triggers. Description-only overlap on common words (two, both, same)
+ // can clear the score bars without naming the skill's subject.
+ const MIN_ANCHOR_TERMS = 1;
// v4: an explicit empty proposal (decline) is honored; the tier-2 fallback no
// longer overrides declines at the launch/selection call sites.
- const ROUTING_POLICY_VERSION = 4;
--- // v5: implicit admission requires a name or trigger anchor term.
--- const ROUTING_POLICY_VERSION = 5;
+ +++ // v5: indirect name citations cannot bypass review through exact or scored admission.
+ +++ // v6: ordered directives and singular named references share the same admission guard.
+ +++ // v7: independent directives scope negation and imperatives allow question punctuation.
+ +++ // v8: only recognized request/rejection scopes can authorize coordinated directives.
+ +++ // v9: neutral task preambles do not suppress a later explicit skill request.
+ +++ // v10: illustrative instructions do not supply or withdraw a direct request.
+ +++ // v11: a contrastive current-task instruction ends the preceding example scope.
+ +++ // v12: preserve current-main evidence floors and anchor checks.
+ +++ const ROUTING_POLICY_VERSION = 12;
const TASK_KEYS = new Set(['sessionId', 'taskId', 'revision', 'phase', 'query', 'explicitIds', 'proposedIds', 'noWorkflow']);
+ +++ const DIRECTIVE_VERB = /\b(use|apply|invoke|run|follow|load)\s+(the\s+)?/i;
+ +++ const DIRECTIVE_REQUEST = /^(?:please )?(?:(?:can|could|would|will) you (?:please )?|do )?(?:use|apply|invoke|run|follow|load)\b/;
+ +++ const DIRECTIVE_REJECTION = /^(?:please )?(?:(?:(?:do )?not|never) (?:use|apply|invoke|run|follow|load)\b|avoid\b)/;
+ +++ const DIRECTIVE_NAME_PREFIX = new RegExp(DIRECTIVE_REQUEST.source + '\\s+(?:the\\s+)?(?:skill\\s*)?$');
+ +++ const QUESTION_START = /^(?!do not\b)(can|could|would|should|shall|will|may|might|must|ought|do|does|did|is|are|why|how|what|when|where|which)\b/;
+ +++ const REPORTED_INSTRUCTION = /\b(say|says|said|reads|told|mentions?|quoted?|document|states?|stated|recommends?|recommended|asserts?|asserted)\b/;
+ +++ const EXAMPLE_PREFIX = /^(?:for (?:example|instance)|as an example|to illustrate)\b/;
+ +++ const CURRENT_TASK_SUFFIX = /\bfor (?:this|the current) task$/;
+ +++ // Subject-led statements may describe someone else's instructions or intentions.
+ +++ const SUBJECT_PREFIX = /^(?:the|a|an|i|you|he|she|it|we|they|my|your|his|her|its|our|their|this|that|these|those)\b/;
+ +++ // Rejections keep their whole list until another instruction/question begins.
+ +++ const INSTRUCTION_BOUNDARY = /(?:,\s*(?:(?:and|but)\s+)?|\s+(?:and|but)\s+)(?=(?:please\s+)?(?:do\s+(?:not\s+)?|not\s+|never\s+)?(?:use|apply|invoke|run|follow|load)\b|(?:can|could|would|should|shall|will|may|might|must|ought|do|does|did|is|are|why|how|what|when|where|which)\b)/i;
+ +++ // Admission additionally checks intervening scopes, including unknown wording.
+ +++ const ADMISSION_BOUNDARY = /(?:,\s*(?:(?:and|but)\s+)?|\s+(?:and|but)\s+)(?=\S)/i;
+ +++
+ +++ /** Track example spans without discarding the connectors between instructions.
+ +++ * A contrast inside an example remains illustrative unless its instruction
+ +++ * explicitly addresses the current task. Earlier non-example scopes stay intact.
+ +++ * @param {string} text Normalized clause with comma boundaries preserved.
+ +++ * @param {string[]} names Known candidate aliases whose internal connectors are names.
+ +++ * @returns {Array<{start: number, text: string, example: boolean}>} Ordered scopes.
+ +++ */
+ +++ function citationScopes(text, names) {
+ +++ const mentions = names.flatMap(name => [...text.matchAll(new RegExp('\\b' + name + '\\b', 'g'))]
+ +++ .map(mention => ({ start: mention.index, end: mention.index + name.length })));
+ +++ const boundaries = [...text.matchAll(new RegExp(ADMISSION_BOUNDARY.source, 'gi'))]
+ +++ .filter(boundary => !mentions.some(mention => boundary.index > mention.start && boundary.index < mention.end));
+ +++ let example = false;
+ +++ return [0, ...boundaries.map(boundary => boundary.index + boundary[0].length)].map((start, index) => {
+ +++ const scope = text.slice(start, boundaries[index]?.index ?? text.length);
+ +++ const currentTask = CURRENT_TASK_SUFFIX.test(scope)
+ +++ && (DIRECTIVE_REQUEST.test(scope) || DIRECTIVE_REJECTION.test(scope));
+ +++ if (currentTask && /\bbut\b/.test(boundaries[index - 1]?.[0] || '')) example = false;
+ +++ if (EXAMPLE_PREFIX.test(scope)) example = true;
+ +++ return { start, text: scope, example };
+ +++ });
+ +++ }
+ +++
+ +++ /** Normalize citation names while preserving contracted negation as a separate word.
+ +++ * @param {string} text Raw query text or a registry alias.
+ +++ * @returns {string} Lowercase alphanumeric words with negation preserved.
+ +++ */
+ +++ const normalizedQueryName = text => text.replace(/n['\u2019]t\b/gi, ' not')
+ +++ .replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/_/g, ' ')
+ +++ .toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
+ +++
+ +++ /** Return canonical/native aliases plus conservative singular forms. Singular
+ +++ * multiword aliases only guard indirect references; they never create exact admission.
+ +++ * @param {object} candidate Ranked skill candidate with its canonical ID and exact alias.
+ +++ * @param {string} nativeName Registry name that may be absent from exact retrieval.
+ +++ * @returns {Array<{name: string, exact: boolean}>} Normalized names and admission eligibility.
+ +++ */
+ +++ function citationAliases(candidate, nativeName) {
+ +++ const names = [...new Set([candidate.exactAlias, candidate.id.slice('skill:'.length), nativeName]
+ +++ .filter(Boolean).map(normalizedQueryName).filter(Boolean))];
+ +++ return names.flatMap(name => [{ name, exact: true },
+ +++ ...(/\s\w+[^s]s$/.test(name) ? [{ name: name.slice(0, -1), exact: false }] : [])]);
+ +++ }
+ +++
+ +++ /** Classify a retrieval candidate's references in query order. Genuine later
+ +++ * directives/rejections replace earlier instructions; questions, quotations and
+ +++ * reported speech do not withdraw a directive. Returns directive, indirect or none.
+ +++ * @param {object} candidate Ranked skill candidate with its canonical ID and exact alias.
+ +++ * @param {string} query Task text to classify without loading skill contents.
+ +++ * @param {string} nativeName Registry name, including aliases absent from exact retrieval.
+ +++ * @param {string[]} names All candidate aliases, used to preserve names across scopes.
+ +++ * @returns {'directive'|'indirect'|'none'} Admission evidence for this skill only.
+ +++ */
+ +++ function citationFor(candidate, query, nativeName, names) {
+ +++ const aliases = citationAliases(candidate, nativeName);
+ +++ let citation = 'none';
+ +++ // Mask quoted instructions before splitting clauses so punctuation inside a
+ +++ // quotation cannot look like a separate instruction. Quoted names remain usable.
+ +++ const unquoted = query.replace(/"[^"]*"|\u201c[^\u201d]*\u201d|(?:^|[\s(:])'[^']*'|\u2018[^\u2019]*\u2019|\x60[^\x60]*\x60/g, part => {
+ +++ const text = normalizedQueryName(part);
+ +++ const instruction = DIRECTIVE_VERB.test(text);
+ +++ // Quoting a task qualifier cannot turn an illustrative instruction into a request.
+ +++ if (!instruction && !CURRENT_TASK_SUFFIX.test(text)) return part;
+ +++ if (instruction && aliases.some(({ name }) => new RegExp('\\b' + name + '\\b').test(text))) citation = 'indirect';
+ +++ return part.replace(/[^.!?;\n]/g, ' ');
+ +++ });
+ +++ // Keep the illustrative abbreviation together when its periods would split clauses.
+ +++ const expanded = unquoted.replace(/\be\.g\.(?=\s|[,;:!?]|$)/gi, 'for example');
+ +++ for (const clause of expanded.match(/[^.!?;\n]+[.!?;\n]*/g) || []) {
+ +++ // Keep comma boundaries for directive scope without changing alias normalization.
+ +++ const text = clause.split(',').map(normalizedQueryName).join(', ');
+ +++ const clauseScopes = citationScopes(text, names);
+ +++ const mentions = aliases.flatMap(({ name, exact }) => [...text.matchAll(new RegExp('\\b' + name + '\\b', 'g'))]
+ +++ .map(mention => ({ index: mention.index, exact }))).sort((a, b) => a.index - b.index);
+ +++ for (const mention of mentions) {
+ +++ const prefix = text.slice(0, mention.index);
+ +++ const precedingScopes = clauseScopes.filter(scope => scope.start <= mention.index);
+ +++ const example = precedingScopes.at(-1)?.example;
+ +++ const scopes = precedingScopes.filter(scope => !scope.example)
+ +++ .map(scope => scope.text.slice(0, mention.index - scope.start));
+ +++ const instructionPrefix = prefix.split(INSTRUCTION_BOUNDARY).at(-1);
+ +++ // A task preamble such as "fix the bug" does not change a later request.
+ +++ // Only preceding scopes may be neutral: an embedded instruction, question,
+ +++ // or subject-led statement still needs review. The final scope must remain
+ +++ // a direct request; neutral text never supplies admission evidence itself.
+ +++ const instruction = scopes.every((scope, index) => DIRECTIVE_REQUEST.test(scope) || DIRECTIVE_REJECTION.test(scope)
+ +++ || (index < scopes.length - 1 && !DIRECTIVE_VERB.test(scope)
+ +++ && !QUESTION_START.test(scope) && !REPORTED_INSTRUCTION.test(scope) && !SUBJECT_PREFIX.test(scope)));
+ +++ const question = (!DIRECTIVE_REQUEST.test(text) && QUESTION_START.test(text))
+ +++ || (!DIRECTIVE_REQUEST.test(instructionPrefix)
+ +++ && (QUESTION_START.test(instructionPrefix) || clause.includes('?')));
+ +++ if (example || question || scopes.some(scope => REPORTED_INSTRUCTION.test(scope)) || /^\s*["'\u201c\u2018\x60]/.test(clause)) {
+ +++ if (citation === 'none') citation = 'indirect';
+ +++ } else if (/\b(do not|never|no|not|avoid)\b/.test(instructionPrefix)) {
+ +++ citation = 'indirect';
+ +++ } else if (!instruction) {
+ +++ if (citation === 'none') citation = 'indirect';
+ +++ } else if (mention.exact && candidate.exact
+ +++ && DIRECTIVE_NAME_PREFIX.test(scopes.at(-1))) {
+ +++ citation = 'directive';
+ +++ }
+ +++ }
+ +++ }
+ +++ return citation;
+ +++ }
+ +++
function validateTask(task) {
if (!task || typeof task !== 'object' || Array.isArray(task)) throw new Error('Task must be an object');
for (const key of Object.keys(task)) if (!TASK_KEYS.has(key)) throw new Error(`Unknown task field: ${key}`);
@@@@@@@@ -288,57 -135,15 -288,57 -160,51 -160,51 -160,51 -288,58 +288,56 @@@@@@@@ function validatePrevious(previous)
}
}
- /** Pure task-scoped resolver. Returned context never invokes a native skill or changes permissions. */
+ const ADMISSION_DENIALS = new Set(['ECC_CONTEXT_EXCLUDED', 'ECC_CONTEXT_MANUAL_ONLY', 'ECC_CONTEXT_AUTHORITY',
+ 'ECC_CONTEXT_SKILL_LIMIT', 'ECC_CONTEXT_BYTE_BUDGET']);
+
+ function admissibility(byId, excluded, reader) {
+ return id => {
+ try {
+ const closure = selectedClosure([id], new Set(), byId, excluded, reader);
+ readSelected(closure, byId, reader);
+ return true;
+ } catch (error) {
+ // Only coded admission denials remove a suggestion. Source drift,
+ // malformed policy and non-UTF-8 resources fail the build instead.
+ if (ADMISSION_DENIALS.has(error.code)) return false;
+ throw error;
+ }
+ };
+ }
+
+ /** Entries the resolver could suggest for a profile: not excluded and admissible
+ * without explicit selection. Metadata only; bodies are never returned. */
+ function routingEntries({ repoRoot = DEFAULT_REPO_ROOT, profileId = 'lean@1', target = 'codex',
+ selectionMode = 'auto', include = [], exclude = [] } = {}) {
- ---- const plan = compileContextProfile({ repoRoot, profileId, target, selectionMode, include, exclude });
- ---- const registry = loadContextRegistry({ repoRoot });
++++++ // One registry load serves the plan and the routing entries.
- const registry = loadContextRegistry({ repoRoot });
- const plan = compileContextPlan(registry, { repoRoot, profileId, target, selectionMode, include, exclude });
+++++++ const { registry, plan } = compileContextProfileWithRegistry({ repoRoot, profileId, target, selectionMode, include, exclude });
+ const { triggers } = loadSkillTriggers({ repoRoot });
- ---- if (registry.registryDigest !== plan.registryDigest) throw new Error('Registry changed during routing index build');
+ const byId = new Map(registry.entries.map(entry => [entry.id, entry]));
+ const excluded = new Set(plan.excludedIds);
+ const admissible = admissibility(byId, excluded, createSourceReader(repoRoot));
+ const entries = registry.entries.filter(entry => !excluded.has(entry.id) && admissible(entry.id))
+ .map(entry => ({ id: entry.id, name: entry.name, description: entry.description,
+ ownerModuleId: entry.ownerModuleId, packId: entry.packId, ...(triggers[entry.id] ? { triggers: triggers[entry.id] } : {}) }));
+ return { profileId: plan.profileId, target, selectionMode, planDigest: plan.planDigest, registryDigest: registry.registryDigest,
+ routingPolicyVersion: ROUTING_POLICY_VERSION, triggersDigest: digestObject(triggers), entries };
+ }
+
--- /** Pure task-scoped resolver. Returned context never invokes a native skill or changes permissions. */
+ +++ /** Resolve task-scoped skill context without invoking native skills or changing permissions.
+ +++ * @param {object} [options] Repository, task, profile, and selection constraints.
+ +++ * @param {object} options.task Task identity, query, and explicit or proposed skill IDs.
+ +++ * @param {boolean} [options.load=false] Include verified resource contents in the result.
+ +++ * @param {object|null} [options.previous=null] Receipt reusable only when its binding matches.
+ +++ * @returns {object} Selection decision, candidates, verified resources, and a bound receipt.
+ +++ */
function resolveTaskContext({ repoRoot = DEFAULT_REPO_ROOT, task, profileId = 'lean@1', target = 'codex',
selectionMode = 'auto', include = [], exclude = [], load = false, previous = null, expectedDigest = null } = {}) {
validateTask(task);
validatePrevious(previous);
------ const plan = compileContextProfile({ repoRoot, profileId, target, selectionMode, include, exclude });
------ const registry = loadContextRegistry({ repoRoot });
++++++ // One registry load serves the plan and the selection; skill bytes are
++++++ // still verified against it when they are read.
- const registry = loadContextRegistry({ repoRoot });
- const plan = compileContextPlan(registry, { repoRoot, profileId, target, selectionMode, include, exclude });
+++++++ const { registry, plan } = compileContextProfileWithRegistry({ repoRoot, profileId, target, selectionMode, include, exclude });
const { triggers } = loadSkillTriggers({ repoRoot });
------ if (registry.registryDigest !== plan.registryDigest) throw new Error('Registry changed during task selection');
const reader = createSourceReader(repoRoot);
const byId = new Map(registry.entries.map(entry => [entry.id, entry]));
const excluded = new Set(plan.excludedIds);
@@@@@@@@ -376,8 -209,7 -376,8 -259,8 -259,8 -259,8 -377,8 +375,8 @@@@@@@@
} else if (!exactAnchors.length) {
const top = candidates[0];
const second = candidates[1];
- --- if (top.bm25 >= AUTO_ADMIT_MIN_BM25 && top.matchedTerms.length >= AUTO_ADMIT_MIN_TERMS
+ +++ if (citations.get(top.id) !== 'indirect' && top.bm25 >= AUTO_ADMIT_MIN_BM25 && top.matchedTerms.length >= AUTO_ADMIT_MIN_TERMS
+ && top.anchorTerms.length >= MIN_ANCHOR_TERMS
&& (!second || top.bm25 >= AUTO_ADMIT_MARGIN * (second.bm25 || 0))) {
autoSelection = { id: top.id, bm25: top.bm25, matchedTerms: top.matchedTerms.length, exact: false };
}
@@@@@@@@ -388,8 -220,7 -388,8 -271,8 -271,8 -271,8 -389,8 +387,8 @@@@@@@@
&& !explicitIds.length && !proposedIds.length && candidates.length && !exactAnchors.length) {
const top = candidates[0];
const second = candidates[1];
- if (top.bm25 >= FALLBACK_MIN_BM25 && top.matchedTerms.length >= FALLBACK_MIN_TERMS
--- if (meetsFallbackBar(top)
+ +++ if (citations.get(top.id) !== 'indirect' && meetsFallbackBar(top)
+ && top.anchorTerms.length >= MIN_ANCHOR_TERMS
&& (!second || top.bm25 >= FALLBACK_MARGIN * (second.bm25 || 0))) {
fallback = { id: top.id, bm25: top.bm25, matchedTerms: top.matchedTerms.length };
}
diff --cc scripts/lib/skill-evolution/tracker.js
index 0ea0ba1cc,0ea0ba1cc,0ea0ba1cc,48d633f92,0ea0ba1cc,0ea0ba1cc,0ea0ba1cc..2b2b945ed
--- a/scripts/lib/skill-evolution/tracker.js
+++ b/scripts/lib/skill-evolution/tracker.js
@@@@@@@@ -53,6 -53,6 -53,6 -53,7 -53,6 -53,6 -53,6 +53,7 @@@@@@@@ function normalizeExecutionRecord(input
const outcome = input.outcome;
const recordedAt = input.recorded_at || options.now || new Date().toISOString();
const userFeedback = input.user_feedback || input.userFeedback || null;
- const failureReason = input.failure_reason ?? input.failureReason ?? null;
+++++++ const failureReasons = [input.failure_reason, input.failureReason];
if (typeof skillId !== 'string' || skillId.trim().length === 0) {
throw new Error('skill_id is required');
@@@@@@@@ -74,6 -74,6 -74,6 -75,10 -74,6 -74,6 -74,6 +75,10 @@@@@@@@
throw new Error('user_feedback must be accepted, corrected, rejected, or null');
}
- if (failureReason !== null && typeof failureReason !== 'string') {
+++++++ if (failureReasons.some(value => value != null && typeof value !== 'string')) {
+++ +++ throw new Error('failure_reason must be a string or null');
+++ +++ }
+++ +++
if (Number.isNaN(Date.parse(recordedAt))) {
throw new Error('recorded_at must be an ISO timestamp');
}
diff --cc skills/agent-self-evaluation/scripts/evaluate.py
index 2d129c407,2d129c407,2d129c407,2d129c407,619a8b284,2d129c407,2d129c407..afedd37a9
--- a/skills/agent-self-evaluation/scripts/evaluate.py
+++ b/skills/agent-self-evaluation/scripts/evaluate.py
@@@@@@@@ -19,6 -19,6 -19,6 -19,6 -19,6 -19,6 -19,6 +19,7 @@@@@@@@ For production use, pair with an LLM ju
"""
import argparse
+++++++import errno
import re
import sys
from dataclasses import dataclass, field
@@@@@@@@ -368,7 -368,7 -368,7 -368,7 -368,7 -368,7 -368,7 +369,9 @@@@@@@@ def _read_file_or_text(path: Optional[s
try:
with open(path) as f:
return f.read()
------- except FileNotFoundError:
+++++++ except OSError as error:
+++++++ if error.errno not in (errno.ENOENT, errno.ENAMETOOLONG):
+++++++ raise
if required:
print(f"Error: output file '{path}' not found", file=sys.stderr)
sys.exit(1)
diff --cc skills/skill-comply/tests/test_runner.py
index f8141d184,f8141d184,f8141d184,f8141d184,f8141d184,e66e66ff1,f8141d184..448d990f4
--- a/skills/skill-comply/tests/test_runner.py
+++ b/skills/skill-comply/tests/test_runner.py
@@@@@@@@ -9,7 -9,7 -9,7 -9,7 -9,7 -9,7 -9,7 +9,13 @@@@@@@@ from pathlib import Pat
from unittest.mock import patch
import pytest
----- -from scripts.runner import _parse_stream_json, _setup_sandbox, run_scenario
- from scripts.runner import SANDBOX_BASE, _parse_stream_json, _safe_sandbox_dir, _setup_sandbox, run_scenario
+++++++from scripts.runner import (
+++++++ SANDBOX_BASE,
+++++++ _parse_stream_json,
+++++++ _safe_sandbox_dir,
+++++++ _setup_sandbox,
+++++++ run_scenario,
+++++++)
@dataclass(frozen=True)
@@@@@@@@ -21,6 -21,6 -21,6 -21,6 -21,6 -21,37 -21,6 +27,37 @@@@@@@@ class _FakeScenario
setup_commands: tuple[str, ...] = ()
+++++ +class TestSafeSandboxDirectory:
- def test_empty_id_cannot_delete_the_shared_base(self):
+++++++ def test_empty_id_cannot_delete_the_shared_base(self) -> None:
+++++ + with (
+++++ + patch("scripts.runner.Path.exists", return_value=True),
+++++ + patch("scripts.runner.shutil.rmtree") as remove,
+++++ + patch("scripts.runner.Path.mkdir") as mkdir,
+++++ + patch("scripts.runner.subprocess.run") as execute,
+++++ + ):
+++++ + execute.return_value = subprocess.CompletedProcess([], 0, stdout="", stderr="")
+++++ + with pytest.raises(ValueError, match="sandbox"):
+++++ + run_scenario(_FakeScenario(id=""))
+++++ + remove.assert_not_called()
+++++ + mkdir.assert_not_called()
+++++ + execute.assert_not_called()
+++++ +
- def test_resolved_base_is_not_a_scenario_directory(self):
+++++++ def test_resolved_base_is_not_a_scenario_directory(self) -> None:
+++++ + with patch("scripts.runner.Path.resolve", return_value=SANDBOX_BASE):
+++++ + with pytest.raises(ValueError, match="sandbox"):
+++++ + _safe_sandbox_dir("alias")
+++++ +
- def test_valid_id_keeps_existing_sanitization(self):
+++++++ def test_valid_id_keeps_existing_sanitization(self) -> None:
+++++ + assert _safe_sandbox_dir("scenario/one") == SANDBOX_BASE / "scenario_one"
+++++ +
- def test_resolved_escape_is_still_rejected(self, tmp_path, monkeypatch):
+++++++ def test_resolved_escape_is_still_rejected(self, tmp_path, monkeypatch) -> None:
+++++ + base = tmp_path / "sandbox"
+++++ + monkeypatch.setattr("scripts.runner.SANDBOX_BASE", base)
+++++ + with patch.object(Path, "resolve", side_effect=[tmp_path / "outside", base]):
+++++ + with pytest.raises(ValueError):
+++++ + _safe_sandbox_dir("escape")
+++++ +
+++++ +
class TestSetupSandboxSkipsShellBuiltins:
"""Setup commands containing shell builtins (cd/pushd/popd) must be skipped.
diff --cc tests/hooks/block-no-verify.test.js
index 56549e721,bf456d050,56549e721,56549e721,56549e721,56549e721,56549e721..2cf25a1e1
--- a/tests/hooks/block-no-verify.test.js
+++ b/tests/hooks/block-no-verify.test.js
@@@@@@@@ -2183,7 -2183,16 -2183,7 -2183,7 -2183,7 -2183,7 -2183,7 +2183,18 @@@@@@@@ const sedCases =
['unknown escape decoding bypass is conservatively blocked', "printf x | sed 's/x/\\git commit --no-verify/e'", 2],
['escaped-newline continued e operand is conservatively blocked', "printf x | sed -e 'e git commit \\\n--no-verify'", 2],
['octal escape decoding bypass is conservatively blocked', "printf x | sed 's/x/\\147it commit --no-verify/e'", 2],
- ----- ['backslash in a non-executing script stays data', "sed 's/a\\/b/c/' 'git commit --no-verify'", 0]
+ +++++ ['backslash in a non-executing script stays data', "sed 's/a\\/b/c/' 'git commit --no-verify'", 0],
+ +++++ // Labels end at `;` and following commands still execute (GNU sed 4.9
+ +++++ // verified: ':a;e cmd' runs cmd). Reading label operands to end of line
+ +++++ // let an e command hide behind a label (CodeRabbit finding, landed via
- // #3495) — the label reader must stop at `;` so the rest is scanned.
+++++++ // #3495). The label reader must stop at `;` so the rest is scanned.
+ +++++ ['e command after a label is scanned', "sed ':a;e git commit --no-verify'", 2],
+ +++++ ['e command after a b branch is scanned', "printf x | sed 'ba;e git commit --no-verify'", 2],
+++++++ ['e command after a T branch is scanned', "printf x | sed 'TX;e git commit --no-verify'", 2],
+++++++ ['e command after a newline label is scanned', "sed ':a\ne git commit --no-verify'", 2],
+ +++++ ['e command after a t branch is scanned', "printf x | sed 'tX;e git commit --no-verify'", 2],
+ +++++ ['plain label without following commands stays data', "sed ':a' 'git commit --no-verify'", 0],
+ +++++ ['b branch alone stays data', "sed 'bx' 'git commit --no-verify'", 0]
];
for (const [name, command, expected] of sedCases) {
if (test(`sed model ${name}`, () => {
diff --cc tests/lib/claude-scope-migration.test.js
index c3ab6606f,91ce940ba,bace9db1c,c3ab6606f,c3ab6606f,c3ab6606f,c3ab6606f..648b591b1
--- a/tests/lib/claude-scope-migration.test.js
+++ b/tests/lib/claude-scope-migration.test.js
@@@@@@@@ -670,5 -669,5 -671,155 -670,5 -670,5 -670,5 -670,5 +671,170 @@@@@@@@ test('migration preserves an explicit i
});
});
++ ++++function writeExplicitDisable(filePath, pluginId = 'ecc@ecc') {
++ ++++ fs.mkdirSync(path.dirname(filePath), { recursive: true });
++ ++++ fs.writeFileSync(filePath, `${JSON.stringify({
++ ++++ enabledPlugins: { [pluginId]: false },
++ ++++ }, null, 2)}\n`);
++ ++++}
++ ++++
++ ++++test('an explicitly disabled resume destination names the setting and the enable recovery', () => {
++ ++++ withFixture({
++ ++++ plugins: [plugin('user'), plugin('local', { enabled: false })],
++ ++++ marketplaces: [marketplace('user')],
++ ++++ }, fixture => {
++ ++++ const localSettings = path.join(
++ ++++ fixture.projectRoot,
++ ++++ '.claude',
++ ++++ 'settings.local.json'
++ ++++ );
++ ++++ writeExplicitDisable(localSettings);
++ ++++ const error = captureError(() => (
++ ++++ migrateClaudePluginScope(migrationOptions(fixture, 'local'))
++ ++++ ));
++ ++++ assert.strictEqual(error.code, 'DESTINATION_EXPLICITLY_DISABLED');
++ ++++ assert.strictEqual(error.phase, 'destination-verification');
++ ++++ assert.match(error.message, /enabledPlugins/);
++ ++++ assert.ok(error.message.includes(localSettings));
++ ++++ assert.deepStrictEqual(error.observedScopes, ['user', 'local']);
++ ++++ assert.deepStrictEqual(error.recovery, [
++ ++++ 'claude plugin enable ecc@ecc --scope local',
++ ++++ 'ecc setup --mode claude-plugin --scope local --move-scope --yes',
++ ++++ ]);
++ ++++ assert.deepStrictEqual(readCalls(fixture), [
++ ++++ ['plugin', 'list', '--json'],
++ ++++ ]);
++ ++++ assert.ok(!readCalls(fixture).some(argv => argv[1] === 'uninstall'));
++ ++++ assert.deepStrictEqual(
++ ++++ readState(fixture).plugins.map(entry => entry.scope).sort(),
++ ++++ ['local', 'user']
++ ++++ );
++ ++++ assert.strictEqual(JSON.parse(
++ ++++ fs.readFileSync(localSettings, 'utf8')
++ ++++ ).enabledPlugins['ecc@ecc'], false);
++ ++++ });
++ ++++});
++ ++++
++ ++++test('a single-scope explicitly disabled destination is not a generic verification failure', () => {
++ ++++ for (const { scope, settingsPath } of [
++ ++++ { scope: 'user', settingsPath: 'config' },
++ ++++ { scope: 'project', settingsPath: 'project-settings' },
++ ++++ { scope: 'local', settingsPath: 'project-settings' },
++ ++++ { scope: 'local', settingsPath: 'project-local-settings' },
++ ++++ ]) {
++ ++++ withFixture({ plugins: [plugin(scope, { enabled: false })] }, fixture => {
++ ++++ const explicitPaths = {
++ ++++ config: fixture.settingsPath,
++ ++++ 'project-settings': path.join(
++ ++++ fixture.projectRoot, '.claude', 'settings.json'
++ ++++ ),
++ ++++ 'project-local-settings': path.join(
++ ++++ fixture.projectRoot, '.claude', 'settings.local.json'
++ ++++ ),
++ ++++ };
++ ++++ const disabledPath = explicitPaths[settingsPath];
++ ++++ writeExplicitDisable(disabledPath);
++ ++++ const error = captureError(() => (
++ ++++ migrateClaudePluginScope(migrationOptions(fixture, scope))
++ ++++ ));
++ ++++ assert.strictEqual(error.code, 'DESTINATION_EXPLICITLY_DISABLED');
++ ++++ assert.ok(error.message.includes(disabledPath));
++ ++++ assert.deepStrictEqual(error.recovery, [
++ ++++ `claude plugin enable ecc@ecc --scope ${scope}`,
++ ++++ `ecc setup --mode claude-plugin --scope ${scope} --move-scope --yes`,
++ ++++ ]);
++ ++++ });
++ ++++ }
++ ++++});
++ ++++
++ ++++test('a disabled destination without an explicit setting stays generic and gains the enable path', () => {
++ ++++ withFixture({ plugins: [plugin('local', { enabled: false })] }, fixture => {
++ ++++ const error = captureError(() => (
++ ++++ migrateClaudePluginScope(migrationOptions(fixture, 'local'))
++ ++++ ));
++ ++++ assert.strictEqual(error.code, 'DESTINATION_VERIFICATION_FAILED');
++ ++++ assert.match(error.message, /exists at local scope but is not enabled/);
++ ++++ assert.deepStrictEqual(error.recovery, [
++ ++++ 'claude plugin enable ecc@ecc --scope local',
++ ++++ 'ecc setup --mode claude-plugin --scope local --move-scope --yes',
++ ++++ ]);
++ ++++ });
++ ++++});
++ ++++
++ ++++test('a source uninstall that errors but removes the source accepts the verified destination', () => {
++ ++++ withFixture({
++ ++++ plugins: [plugin('user'), plugin('project')],
++ ++++ marketplaces: [marketplace('user')],
++ ++++ failures: [{
++ ++++ argv: uninstallArgv('user'),
++ ++++ status: 9,
++ ++++ stderr: 'uninstall failed',
++ ++++ times: 1,
++ ++++ }],
++ ++++ pluginListResponses: [
++ ++++ [plugin('user'), plugin('project')],
++ ++++ [plugin('user'), plugin('project')],
++ ++++ [plugin('user'), plugin('project')],
++ ++++ [plugin('project'), plugin('local')],
++ ++++ [plugin('project')],
++ ++++ ],
++ ++++ }, fixture => {
++ ++++ const result = migrateClaudePluginScope(
++ ++++ migrationOptions(fixture, 'project')
++ ++++ );
++ ++++ assert.strictEqual(result.action, 'resumed');
++ ++++ assert.strictEqual(result.sourceScope, 'user');
++ ++++ assert.deepStrictEqual(result.warnings, [
++ ++++ 'Claude reported an uninstall error, but destination-only state was verified.',
++ ++++ ]);
++ ++++ assert.ok(!readCalls(fixture).slice(-2).some(argv => argv[1] === 'uninstall'));
++ ++++ });
++ ++++});
++ ++++
++ ++++test('source uninstall failure recovery stops suggesting an already-absent source', () => {
++ ++++ withFixture({
++ ++++ plugins: [plugin('user'), plugin('project')],
++ ++++ marketplaces: [marketplace('user')],
++ ++++ failures: [{
++ ++++ argv: uninstallArgv('user'),
++ ++++ status: 9,
++ ++++ stderr: 'uninstall failed',
++ ++++ times: 1,
++ ++++ }],
++ ++++ pluginListResponses: [
++ ++++ [plugin('user'), plugin('project')],
++ ++++ [plugin('user'), plugin('project')],
++ ++++ [plugin('user'), plugin('project')],
++ ++++ [],
++ ++++ ],
++ ++++ }, fixture => {
++ ++++ const error = captureError(() => (
++ ++++ migrateClaudePluginScope(migrationOptions(fixture, 'project'))
++ ++++ ));
++ ++++ assert.strictEqual(error.code, 'SOURCE_UNINSTALL_FAILED');
++ ++++ assert.strictEqual(error.phase, 'source-uninstall');
++ ++++ assert.deepStrictEqual(error.observedScopes, []);
++ ++++ assert.deepStrictEqual(error.recovery, [
++ ++++ 'claude plugin list --json',
+++++++ 'ecc setup --mode claude-plugin --scope project --yes',
+++++++ ]);
+++++++ });
+++++++});
+++++++
+++++++test('a two-scope disabled destination offers enable recovery without removing the source', () => {
+++++++ withFixture({
+++++++ plugins: [plugin('user'), plugin('project', { enabled: false })],
+++++++ marketplaces: [marketplace('user')],
+++++++ }, fixture => {
+++++++ const error = captureError(() => migrateClaudePluginScope(migrationOptions(fixture, 'project')));
+++++++ assert.strictEqual(error.code, 'DESTINATION_VERIFICATION_FAILED');
+++++++ assert.deepStrictEqual(error.recovery, [
+++++++ 'claude plugin enable ecc@ecc --scope project',
++ ++++ 'ecc setup --mode claude-plugin --scope project --move-scope --yes',
++ ++++ ]);
+++++++ assert.ok(!readCalls(fixture).some(argv => argv[1] === 'uninstall'));
++ ++++ });
++ ++++});
++ ++++
console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`);
process.exit(failed > 0 ? 1 : 0);
diff --cc tests/lib/context-selection.test.js
index c04f943d0,4e3be6169,c04f943d0,281f646d5,281f646d5,281f646d5,473de5924..53755c62e
--- a/tests/lib/context-selection.test.js
+++ b/tests/lib/context-selection.test.js
@@@@@@@@ -333,397 -301,3 -333,397 -319,28 -319,28 -319,28 -353,397 +353,405 @@@@@@@@ test('invalid input and oversized bodie
overrides: [{ id: 'skill:feature', requiredResources: ['skills/feature/references/details.md'] }] }));
assert.throws(() => resolve(repoRoot, { explicitIds: ['skill:feature'] }, { load: true }), /budget/);
}));
+
+ test('routing entries drop only coded admission denials; a corrupt source still fails the build', () => withFixture(root => {
+ const { routingEntries } = require('../../scripts/lib/context-selection');
+ write(root, 'skills/shared/SKILL.md', '---\nname: shared\ndescription: Shared helper\ndisable-model-invocation: true\n---\nShared');
+ assert.equal(routingEntries({ repoRoot: root, target: 'claude' }).entries.some(entry => entry.id === 'skill:shared'), false);
+ const file = path.join(root, 'skills/feature/SKILL.md');
+ fs.writeFileSync(file, Buffer.concat([fs.readFileSync(file), Buffer.from([0xff, 0x0a])]));
+ assert.throws(() => routingEntries({ repoRoot: root, target: 'claude' }), /UTF-8/);
+ }));
+
+ test('admission denials carry stable codes', () => withFixture(root => {
+ write(root, 'skills/shared/SKILL.md', '---\nname: shared\ndescription: Shared helper\ndisable-model-invocation: true\n---\nShared');
+ assert.throws(() => resolve(root, { query: 'shared', proposedIds: ['skill:shared'] }, { load: true }),
+ error => error.code === 'ECC_CONTEXT_MANUAL_ONLY');
+ }));
+
+ test('suggestion evidence requires an exact name or the absolute fallback floor', () => {
+ const { hasSuggestionEvidence } = require('../../scripts/lib/context-selection');
+ const candidate = values => ({ exact: false, bm25: 12, matchedTerms: ['feature', 'work'], ...values });
+ assert.equal(hasSuggestionEvidence(candidate()), true);
+ assert.equal(hasSuggestionEvidence(candidate({ bm25: 11.99 })), false);
+ assert.equal(hasSuggestionEvidence(candidate({ matchedTerms: ['feature'] })), false);
+ assert.equal(hasSuggestionEvidence(candidate({ exact: true, bm25: 1, matchedTerms: ['feature'] })), true);
+ assert.equal(hasSuggestionEvidence(null), false);
+ });
+ +++
+ +++ for (const query of [
+ +++ "You shouldn't use feature.",
+ +++ "You can\u2019t use feature.",
+ +++ "For feature, don't use the feature skill.",
+ +++ 'For feature, never invoke feature.',
+ +++ 'The phrase "Use feature" is an example.',
+ +++ 'The phrase "Use feature." is an example.',
+ +++ 'The phrase \u201cUse feature\u201d is an example.',
+ +++ 'The phrase `Use feature` is an example.',
+ +++ "Don't use the feature skill.",
+ +++ 'Don\u2019t use the feature skill.',
+ +++ 'Do not use the feature skill.',
+ +++ 'Never use the feature skill.',
+ +++ 'Can I use the feature skill?',
+ +++ 'Should we use the feature skill?',
+ +++ 'Why use the feature skill?',
+ +++ 'The README says to use the feature skill.',
+ +++ 'The docs say use feature.',
+ +++ 'The docs say to use feature.',
+ +++ 'The docs said use feature.',
+ +++ '"Use the feature skill" is an example.',
+ +++ ]) {
+ +++ test('indirect name citation needs an agent decision: ' + query, () => withFixture(repoRoot => {
+ +++ const result = resolve(repoRoot, { query }, { load: true });
+ +++ assert.ok(result.candidates.some(candidate => candidate.id === 'skill:feature'));
+ +++ assert.deepEqual(result.loadedIds, []);
+ +++ assert.equal(result.reason, 'agent-selection-required');
+ +++ assert.equal(result.fallback, null);
+ +++ }));
+ +++ }
+ +++
+ +++ test('a negated citation does not suppress a separate affirmative directive', () => withFixture(repoRoot => {
+ +++ for (const query of [
+ +++ "Don't use feature. Use shared guidance.",
+ +++ 'Don\u2019t use feature; please use shared guidance.',
+ +++ 'The document says use feature. Use shared guidance.',
+ +++ ]) {
+ +++ const result = resolve(repoRoot, { query }, { load: true });
+ +++ assert.deepEqual(result.loadedIds, ['skill:shared']);
+ +++ }
+ +++ }));
+ +++
+ +++ for (const query of [
+ +++ "Don't use feature, use shared guidance.",
+ +++ "Don't use feature and use shared guidance.",
+ +++ "Don't use feature but use shared guidance.",
+ +++ 'Do not use feature, please use shared guidance.',
+ +++ 'Don\u2019t use feature, and please use shared guidance.',
+ +++ "Don't use feature, do use shared guidance.",
+ +++ "Don't use feature, use shared guidance, okay?",
+ +++ "Don't use feature and use shared guidance, okay?",
+ +++ "Don't use feature but use shared guidance, okay?",
+ +++ 'Do not use feature, please use shared guidance?',
+ +++ 'Do not use feature and please use shared guidance?',
+ +++ 'Do not use feature but please use shared guidance?',
+ +++ ]) {
+ +++ test('a new directive scopes an earlier rejection: ' + query, () => withFixture(repoRoot => {
+ +++ const result = resolve(repoRoot, { query }, { load: true });
+ +++ assert.deepEqual(result.selectedIds, ['skill:shared']);
+ +++ assert.deepEqual(result.loadedIds, ['skill:shared']);
+ +++ assert.equal(result.reason, 'auto-selection');
+ +++ assert.equal(result.receipt.autoSelection.exact, true);
+ +++ }));
+ +++ }
+ +++
+ +++ for (const query of [
+ +++ 'The docs say do not use feature and use shared guidance.',
+ +++ 'The docs say do not use feature, use shared guidance.',
+ +++ 'The docs say do not use feature, use shared guidance, okay?',
+ +++ 'Use standard tools, the spec states do not use feature and use shared guidance.',
+ +++ 'The spec states do not use feature and use shared guidance.',
+ +++ 'The spec stated do not use feature, use shared guidance.',
+ +++ 'The spec recommends we do not use feature and use shared guidance.',
+ +++ 'The spec asserts we should not use feature and use shared guidance.',
+ +++ 'Use standard tools, the spec stipulates do not use feature and use shared guidance.',
+ +++ 'Use the documentation that says do not use feature and use shared guidance.',
+ +++ 'Should we avoid feature and use shared guidance?',
+ +++ 'Should we avoid feature, use shared guidance?',
+ +++ 'Do not use feature and shared guidance.',
+ +++ 'Do not use feature, shared guidance.',
+ +++ ]) {
+ +++ test('a connector preserves indirect or negated context: ' + query, () => withFixture(repoRoot => {
+ +++ const result = resolve(repoRoot, { query }, { load: true });
+ +++ assert.ok(result.candidates.some(candidate => candidate.id === 'skill:shared'));
+ +++ assert.deepEqual(result.selectedIds, []);
+ +++ assert.deepEqual(result.loadedIds, []);
+ +++ assert.equal(result.reason, 'agent-selection-required');
+ +++ assert.equal(result.fallback, null);
+ +++ }));
+ +++ }
+ +++
+ +++ for (const query of [
+ +++ 'Use standard tools, should we use feature?',
+ +++ 'Use standard tools, shall we use feature?',
+ +++ 'Use standard tools, will we use feature?',
+ +++ 'Use standard tools, ought we to use feature?',
+ +++ 'Please use the existing code, can I use feature?',
+ +++ 'Use standard tools and should we use feature?',
+ +++ 'Use standard tools but should we use feature?',
+ +++ ]) {
+ +++ test('a generic directive does not authorize a later question: ' + query, () => withFixture(repoRoot => {
+ +++ const result = resolve(repoRoot, { query }, { load: true });
+ +++ assert.ok(result.candidates.some(candidate => candidate.id === 'skill:feature'));
+ +++ assert.deepEqual(result.selectedIds, []);
+ +++ assert.deepEqual(result.loadedIds, []);
+ +++ assert.equal(result.reason, 'agent-selection-required');
+ +++ assert.equal(result.fallback, null);
+ +++ }));
+ +++ }
+ +++
+ +++ for (const query of ['Use feature?', 'Please use feature?', 'Use feature to fix the bug, okay?']) {
+ +++ test('an imperative with question punctuation remains a directive: ' + query, () => withFixture(repoRoot => {
+ +++ const result = resolve(repoRoot, { query }, { load: true });
+ +++ assert.deepEqual(result.selectedIds, ['skill:feature']);
+ +++ assert.deepEqual(result.loadedIds, ['skill:feature']);
+ +++ assert.equal(result.reason, 'auto-selection');
+ +++ assert.equal(result.receipt.autoSelection.exact, true);
+ +++ }));
+ +++ }
+ +++
+ +++ test('ordinary and polite directives preserve automatic and explicit selection', () => withFixture(repoRoot => {
+ +++ for (const query of ['Please use the feature skill.', 'Can you use the feature skill?',
+ +++ 'Use feature without changing the code.', 'Use feature to document the change.',
+ +++ 'Use "feature".', 'Use `feature`.', 'Do use feature.', 'Please can you use feature?']) {
+ +++ assert.deepEqual(resolve(repoRoot, { query }, { load: true }).loadedIds, ['skill:feature']);
+ +++ }
+ +++ for (const field of ['explicitIds', 'proposedIds']) {
+ +++ assert.deepEqual(resolve(repoRoot, { query: 'Should we use feature?', [field]: ['skill:feature'] },
+ +++ { load: true }).loadedIds, ['skill:feature']);
+ +++ }
+ +++ }));
+ +++
+ +++ for (const [query, expectedId] of [
+ +++ ['Fix the bug, use feature', 'skill:feature'],
+ +++ ['Fix the bug and use feature.', 'skill:feature'],
+ +++ ['Please fix the bug, please use feature.', 'skill:feature'],
+ +++ ['Write the regression test, use feature.', 'skill:feature'],
+ +++ ['Investigate the bug but use feature.', 'skill:feature'],
+ +++ ['For this task, use feature.', 'skill:feature'],
+ +++ ["Fix the bug, don't use feature and use shared guidance.", 'skill:shared'],
+ +++ ]) {
+ +++ test('a general task preamble preserves a later directive: ' + query, () => withFixture(repoRoot => {
+ +++ const result = resolve(repoRoot, { query }, { load: true });
+ +++ assert.deepEqual(result.selectedIds, [expectedId]);
+ +++ assert.deepEqual(result.loadedIds, [expectedId]);
+ +++ assert.equal(result.reason, 'auto-selection');
+ +++ assert.equal(result.receipt.autoSelection.exact, true);
+ +++ }));
+ +++ }
+ +++
+ +++ for (const query of [
+ +++ 'Fix the bug, shall we use feature?',
+ +++ 'Fix the bug, the spec states do not use feature and use shared guidance.',
+ +++ 'The docs say fix the bug and use feature.',
+ +++ 'Can we fix the bug and use feature?',
+ +++ 'The spec stipulates: fix the bug and use feature.',
+ +++ 'Our policy stipulates repair the bug and use feature.',
+ +++ 'Fix the bug, ought we to repair it and use feature?',
+ +++ 'Fix the bug, must we repair it and use feature?',
+ +++ 'Fix the bug, feature.',
+ +++ ]) {
+ +++ test('a general task preamble cannot promote an indirect citation: ' + query, () => withFixture(repoRoot => {
+ +++ const result = resolve(repoRoot, { query }, { load: true });
+ +++ assert.ok(result.candidates.some(candidate => candidate.id === 'skill:feature'));
+ +++ assert.deepEqual(result.selectedIds, []);
+ +++ assert.deepEqual(result.loadedIds, []);
+ +++ assert.equal(result.reason, 'agent-selection-required');
+ +++ assert.equal(result.fallback, null);
+ +++ }));
+ +++ }
+ +++
+ +++ for (const prefix of ['database-migrations:', "Don't use database-migrations.", 'Do not use database-migrations.',
+ +++ 'Should we use database-migrations?', 'The README says use database-migrations.']) {
+ +++ test('strong retrieval cannot bypass an indirect citation: ' + prefix, () => {
+ +++ const query = prefix + ' Review a PostgreSQL migration that adds an indexed nullable column without downtime.';
+ +++ const result = resolveTaskContext({ task: task({ query }), load: true });
+ +++ const candidate = result.candidates.find(value => value.id === 'skill:database-migrations');
+ +++ assert.ok(candidate && candidate.bm25 >= 20, 'Exercise the BM25 auto-admission threshold');
+ +++ assert.deepEqual(result.loadedIds, []);
+ +++ assert.equal(result.fallback, null);
+ +++ });
+ +++ }
+ +++
+ +++ for (const query of [
+ +++ 'For example, use feature',
+ +++ 'For instance, use feature.',
+ +++ 'As an example, use feature.',
+ +++ 'To illustrate, use feature.',
+ +++ 'Fix the bug, for example, use feature.',
+ +++ 'For example, use feature and use feature.',
+ +++ 'For example, use feature but use shared guidance.',
+ +++ "For example, don't use feature but use shared guidance.",
+ +++ 'For example, use feature and use feature for this task.',
+ +++ 'For example, use feature, but should we use feature for this task?',
+ +++ 'For example, use feature, but the docs say use feature for this task.',
+ +++ 'For example, use feature, but "use feature for this task" is an example.',
+ +++ 'The docs say for example, use feature, but use feature for this task.',
+ +++ 'For example, use feature, but use feature "for this task"',
+ +++ 'Should we, for example, use shared guidance, but use feature for this task?',
+ +++ 'Our policy stipulates, for example, use shared guidance, but use feature for this task.',
+ +++ 'e.g., use feature.',
+ +++ 'E.g. use feature.',
+ +++ ]) {
+ +++ test('an illustrative citation needs an agent decision: ' + query, () => withFixture(repoRoot => {
+ +++ const result = resolve(repoRoot, { query }, { load: true });
+ +++ assert.ok(result.candidates.some(candidate => candidate.id === 'skill:feature'));
+ +++ assert.deepEqual(result.selectedIds, []);
+ +++ assert.deepEqual(result.loadedIds, []);
+ +++ assert.equal(result.reason, 'agent-selection-required');
+ +++ assert.equal(result.fallback, null);
+ +++ }));
+ +++ }
+ +++
+ +++ for (const [routingPolicyVersion, query] of [
+ +++ [7, 'Use standard tools, shall we use feature?'],
+ +++ [9, 'For example, use feature'],
+ +++ ]) {
+ +++ test('an old policy ' + routingPolicyVersion + ' selected receipt is invalidated after policy changes', () => withFixture(repoRoot => {
+ +++ const first = resolve(repoRoot, { query, explicitIds: ['skill:feature'] });
+ +++ const { digestObject } = require('../../scripts/lib/context-profile-support');
+ +++ const { compileContextProfile } = require('../../scripts/lib/context-profiles');
+ +++ const plan = compileContextProfile({ repoRoot, selectionMode: 'auto' });
+ +++ const bindingDigest = digestObject({ sessionId: 'session-1', taskId: 'task-1', revision: 1,
+ +++ phase: 'implement', planDigest: plan.planDigest, routingPolicyVersion,
+ +++ triggersDigest: digestObject({}), queryDigest: digestObject(query) });
+ +++ const { receiptDigest: _receiptDigest, ...receipt } = first.receipt;
+ +++ const oldReceipt = { ...receipt, bindingDigest, explicitIds: [],
+ +++ selectionDigest: digestObject({ bindingDigest, selectedIds: ['skill:feature'], explicitIds: [] }) };
+ +++ const previous = { ...oldReceipt, receiptDigest: digestObject(oldReceipt) };
+ +++ const result = resolve(repoRoot, { query }, { previous, load: true });
+ +++ assert.equal(result.reused, false);
+ +++ assert.notEqual(result.receipt.bindingDigest, previous.bindingDigest);
+ +++ assert.deepEqual(result.selectedIds, []);
+ +++ assert.deepEqual(result.loadedIds, []);
+ +++ assert.equal(result.fallback, null);
+ +++ }));
+ +++ }
+ +++
+ +++ for (const [routingPolicyVersion, query, expectedId] of [
+ +++ [6, "Don't use feature, use shared guidance.", 'skill:shared'],
+ +++ [8, 'Fix the bug, use feature', 'skill:feature'],
+ +++ [10, 'For example, use feature, but use feature for this task', 'skill:feature'],
+ +++ ]) {
+ +++ test('an old policy ' + routingPolicyVersion + ' empty selection is reconsidered after policy changes', () => withFixture(repoRoot => {
+ +++ const first = resolve(repoRoot, { query });
+ +++ const { digestObject } = require('../../scripts/lib/context-profile-support');
+ +++ const { compileContextProfile } = require('../../scripts/lib/context-profiles');
+ +++ const plan = compileContextProfile({ repoRoot, selectionMode: 'auto' });
+ +++ const bindingDigest = digestObject({ sessionId: 'session-1', taskId: 'task-1', revision: 1,
+ +++ phase: 'implement', planDigest: plan.planDigest, routingPolicyVersion,
+ +++ triggersDigest: digestObject({}), queryDigest: digestObject(query) });
+ +++ const { receiptDigest: _receiptDigest, autoSelection: _autoSelection, ...receipt } = first.receipt;
+ +++ const oldReceipt = { ...receipt, bindingDigest, decision: 'none', selectedIds: [], explicitIds: [],
+ +++ loadedIds: [], resources: [], selectionDigest: digestObject({ bindingDigest, selectedIds: [], explicitIds: [] }) };
+ +++ const previous = { ...oldReceipt, receiptDigest: digestObject(oldReceipt) };
+ +++ const result = resolve(repoRoot, { query }, { previous, load: true });
+ +++ assert.equal(result.reused, false);
+ +++ assert.notEqual(result.receipt.bindingDigest, previous.bindingDigest);
+ +++ assert.deepEqual(result.selectedIds, [expectedId]);
+ +++ assert.deepEqual(result.loadedIds, [expectedId]);
+ +++ assert.equal(result.reason, 'auto-selection');
+ +++ }));
+ +++ }
+ +++
+ +++ for (const query of [
+ +++ 'Should we use feature? Use feature.',
+ +++ 'Use feature. Should we use feature?',
+ +++ 'Use feature, should we use feature?',
+ +++ 'Use feature. Shall we use feature?',
+ +++ 'Use feature, shall we use shared guidance?',
+ +++ 'Shall we use shared guidance? Use feature.',
+ +++ 'The docs say use feature. Use feature.',
+ +++ 'Use feature. The docs say use feature.',
+ +++ 'Use feature. The spec states do not use feature and use shared guidance.',
+ +++ 'Use feature. Use the warning that says never use feature.',
+ +++ 'The spec states do not use feature and use shared guidance. Use feature.',
+ +++ 'The phrase "Use feature." is an example. Use feature.',
+ +++ 'The docs say "Use feature." Use feature.',
+ +++ 'The docs say "Should we use feature?" Use feature.',
+ +++ `Use feature. The docs say "don’t use feature."`,
+ +++ 'Use feature. The phrase "Use feature." is an example.',
+ +++ "Don't use feature. Use feature.",
+ +++ "Don't use feature, use feature.",
+ +++ "Don't use feature and use feature.",
+ +++ "Don't use feature but use feature.",
+ +++ 'The docs say never use feature. Use feature.',
+ +++ 'Use feature. The docs say never use feature.',
+ +++ 'Use feature to inspect the essay.',
+ +++ 'Use feature. For example, use shared guidance.',
+ +++ 'For example, use shared guidance. Use feature.',
+ +++ "Use feature. For example, don't use feature.",
+ +++ 'Use feature to build an example.',
+ +++ 'Fix the example, use feature.',
+ +++ 'Fix e.g.js, use feature.',
+ +++ "Use feature. E.g., don't use feature.",
+ +++ 'For example, use feature, but use feature for this task',
+ +++ 'For example, use shared guidance, but please use feature for this task.',
+ +++ 'For instance, use shared guidance but use feature for this task.',
+ +++ 'For example use shared guidance, but use feature for this task.',
+ +++ 'For example, use shared guidance, but use feature for the current task.',
+ +++ 'For example, use shared guidance, but use feature for this task, for instance, do not use feature.',
+ +++ 'For example, the docs say use shared guidance, but use feature for this task.',
+ +++ ]) {
+ +++ test('a genuine directive survives surrounding discussion: ' + query, () => withFixture(repoRoot => {
+ +++ const result = resolve(repoRoot, { query }, { load: true });
+ +++ assert.deepEqual(result.loadedIds, ['skill:feature']);
+ +++ assert.equal(result.reason, 'auto-selection');
+ +++ assert.equal(result.receipt.autoSelection.exact, true);
+ +++ }));
+ +++ }
+ +++
+ +++ for (const query of [
+ +++ "Use feature. Don't use feature.",
+ +++ 'Use feature. Avoid feature.',
+ +++ 'Use feature. You should not use feature.',
+ +++ 'Use feature. You shouldn\u2019t use feature.',
+ +++ 'Use feature, no feature.',
+ +++ 'Use feature. For this task, do not use feature.',
+ +++ "Use feature, don't use feature.",
+ +++ "Use feature and don't use feature.",
+ +++ "Use feature but don't use feature.",
+ +++ 'Use feature. Never use feature.',
+ +++ "Use feature. Don't use feature. Should we use feature?",
+ +++ 'Use feature. For example, use shared guidance, but do not use feature for this task.',
+ +++ 'For example, use shared guidance, but use feature for this task and do not use feature.',
+ +++ ]) {
+ +++ test('a later rejection withdraws an earlier directive: ' + query, () => withFixture(repoRoot => {
+ +++ const result = resolve(repoRoot, { query }, { load: true });
+ +++ assert.deepEqual(result.loadedIds, []);
+ +++ assert.equal(result.fallback, null);
+ +++ }));
+ +++ }
+ +++
+ +++ test('a later grouped rejection withdraws a previously requested skill', () => withFixture(repoRoot => {
+ +++ for (const query of ["Use shared. Don't use feature and shared guidance.",
+ +++ 'Use shared. Do not use feature and our shared guidance.',
+ +++ 'Use shared. Do not use feature and the existing shared guidance.',
+ +++ 'Use shared. Do not use feature, manual, and shared guidance.',
+ +++ "Use shared. Don't use feature and the shared skill."]) {
+ +++ const result = resolve(repoRoot, { query }, { load: true });
+ +++ assert.deepEqual(result.loadedIds, [], query);
+ +++ assert.equal(result.fallback, null);
+ +++ }
+ +++ }));
+ +++
+ +++ for (const prefix of [
+ +++ "Don't use the database migration skill.",
+ +++ 'Don\u2019t use the database migration skill.',
+ +++ 'Never use database migration.',
+ +++ 'Should we use the database migration skill?',
+ +++ 'The docs say use the database migration skill.',
+ +++ ]) {
+ +++ test('singular named references cannot bypass citation review: ' + prefix, () => {
+ +++ const query = prefix + ' Review a PostgreSQL migration that adds an indexed nullable column without downtime.';
+ +++ const result = resolveTaskContext({ task: task({ query }), load: true });
+ +++ const candidate = result.candidates.find(value => value.id === 'skill:database-migrations');
+ +++ assert.ok(candidate && candidate.bm25 >= 20, 'Exercise the BM25 auto-admission threshold');
+ +++ assert.equal(candidate.exact, false, 'Exercise the non-exact candidate path');
+ +++ assert.deepEqual(result.loadedIds, []);
+ +++ assert.equal(result.fallback, null);
+ +++ });
+ +++ }
+ +++
+ +++ test('singular forms do not create exact directive admission', () => {
+ +++ const result = resolveTaskContext({ task: task({ query: 'Use the database migration skill.' }), load: true });
+ +++ assert.ok(result.candidates.some(candidate => candidate.id === 'skill:database-migrations'));
+ +++ assert.ok(!result.receipt.autoSelection || !result.receipt.autoSelection.exact);
+ +++ });
+++++++
+++++++test('invalid resolution and routing options are rejected before reading a missing registry', () => {
+++++++ const repoRoot = path.join(__dirname, 'missing-registry');
+++++++ const values = { repoRoot, target: 'unknown-host' };
+++++++ assert.throws(() => resolveTaskContext({ ...values, task: task() }), /target/i);
+++++++ assert.throws(() => routingEntries(values), /target/i);
+++++++ assert.throws(() => routingEntries({ repoRoot, selectionMode: 'invalid' }), /Unknown selection mode/);
+++++++});
diff --cc tests/lib/skill-evolution.test.js
index f2dd4e6ec,bfff437bf,f2dd4e6ec,f8c826b13,f2dd4e6ec,f2dd4e6ec,f2dd4e6ec..62809d784
--- a/tests/lib/skill-evolution.test.js
+++ b/tests/lib/skill-evolution.test.js
@@@@@@@@ -386,6 -386,6 -386,6 -390,18 -386,6 -386,6 -386,6 +390,32 @@@@@@@@ function runTests()
for (const [payload, expectedError] of cases) {
assert.throws(() => tracker.normalizeExecutionRecord(payload), expectedError);
}
+++ +++ for (const value of [null, '', 'Useful detail']) {
+++ +++ assert.strictEqual(
+++ +++ tracker.normalizeExecutionRecord({ ...valid, failureReason: value }).failure_reason,
+++ +++ value || null
+++ +++ );
+++++++ }
+++++++ for (const snake of ['', null, undefined]) {
+++++++ assert.strictEqual(tracker.normalizeExecutionRecord({
+++++++ ...valid, failure_reason: snake, failureReason: 'Useful detail',
+++++++ }).failure_reason, 'Useful detail');
+++++++ }
+++++++ assert.strictEqual(tracker.normalizeExecutionRecord({
+++++++ ...valid, failure_reason: 'Primary detail', failureReason: 'Other detail',
+++++++ }).failure_reason, 'Primary detail');
+++++++ for (const value of [42, 0, false, {}, []]) {
+++++++ for (const payload of [
+++++++ { ...valid, failure_reason: value, failureReason: 'Useful detail' },
+++++++ { ...valid, failure_reason: '', failureReason: value },
+++++++ ]) assert.throws(() => tracker.normalizeExecutionRecord(payload), /failure_reason must be a string or null/);
+++ +++ }
+++ +++ const invalidRunsFile = path.join(homeDir, '.claude', 'state', 'invalid-reason-runs.jsonl');
+++ +++ assert.throws(
+++ +++ () => tracker.recordSkillExecution({ ...valid, failure_reason: 42 }, { runsFilePath: invalidRunsFile }),
+++ +++ /failure_reason must be a string or null/
+++ +++ );
+++ +++ assert.ok(!fs.existsSync(invalidRunsFile), 'invalid reasons must be rejected before writing a run');
})) passed++; else failed++;
if (test('uses state-store adapters for recording and reading when available', () => {
diff --cc tests/test_agent_self_evaluation.py
index 000000000,000000000,000000000,000000000,b3f7823e8,000000000,000000000..515256f96
mode 000000,000000,000000,000000,100644,000000,000000..100644
--- a/tests/test_agent_self_evaluation.py
+++ b/tests/test_agent_self_evaluation.py
@@@@@@@@ -1,0 -1,0 -1,0 -1,0 -1,87 -1,0 -1,0 +1,107 @@@@@@@@
++++ ++"""Input-mode regressions for the standalone agent output evaluator."""
++++ ++
++++ ++import argparse
+++++++import errno
++++ ++import importlib.util
++++ ++import io
++++ ++import re
++++ ++import subprocess
++++ ++import sys
++++ ++from pathlib import Path
++++ ++from types import SimpleNamespace
++++ ++
++++ ++import pytest
++++ ++
++++ ++SCRIPT = Path(__file__).resolve().parents[1] / "skills/agent-self-evaluation/scripts/evaluate.py"
++++ ++SPEC = importlib.util.spec_from_file_location("agent_self_evaluation", SCRIPT)
++++ ++evaluator = importlib.util.module_from_spec(SPEC)
++++ ++sys.modules[SPEC.name] = evaluator
++++ ++SPEC.loader.exec_module(evaluator)
++++ ++
++++ ++
++++ ++def args(**overrides):
++++ ++ return argparse.Namespace(**{"interactive": False, "task": None, "output": None, **overrides})
++++ ++
++++ ++
++++ ++def test_output_file_uses_piped_task(tmp_path, monkeypatch):
++++ ++ output = tmp_path / "response.txt"
++++ ++ output.write_text("All tests passed.", encoding="utf-8")
++++ ++ monkeypatch.setattr(sys, "stdin", io.StringIO("Add retry logic"))
++++ ++
++++ ++ assert evaluator._read_input(args(output=str(output))) == ("Add retry logic", "All tests passed.")
++++ ++
++++ ++
++++ ++def test_explicit_task_takes_precedence_over_pipe(tmp_path, monkeypatch):
++++ ++ output = tmp_path / "response.txt"
++++ ++ output.write_text("Answer", encoding="utf-8")
++++ ++ stream = io.StringIO("Ignored pipe")
++++ ++ monkeypatch.setattr(sys, "stdin", stream)
++++ ++
++++ ++ assert evaluator._read_input(args(task="Explicit task", output=str(output))) == ("Explicit task", "Answer")
++++ ++ assert stream.tell() == 0
++++ ++
++++ ++
++++ ++def test_output_file_without_task_does_not_read_terminal(tmp_path, monkeypatch):
++++ ++ output = tmp_path / "response.txt"
++++ ++ output.write_text("Answer", encoding="utf-8")
++++ ++ monkeypatch.setattr(sys, "stdin", SimpleNamespace(isatty=lambda: True))
++++ ++
++++ ++ assert evaluator._read_input(args(output=str(output))) == (None, "Answer")
++++ ++
++++ ++
++++ ++def test_no_output_file_keeps_stdin_as_output(monkeypatch):
++++ ++ monkeypatch.setattr(sys, "stdin", io.StringIO("Piped answer"))
++++ ++ assert evaluator._read_input(args(task="Inline task")) == ("Inline task", "Piped answer")
++++ ++
++++ ++
++++ ++def test_interactive_mode_keeps_prompt_and_stdin(monkeypatch):
++++ ++ monkeypatch.setattr("builtins.input", lambda _prompt: " Interactive task ")
++++ ++ monkeypatch.setattr(sys, "stdin", io.StringIO("Interactive answer"))
++++ ++ assert evaluator._read_input(args(interactive=True)) == ("Interactive task", "Interactive answer")
++++ ++
++++ ++
++++ ++def test_task_can_still_be_read_from_file(tmp_path, monkeypatch):
++++ ++ task = tmp_path / "task.txt"
++++ ++ task.write_text("File task", encoding="utf-8")
++++ ++ monkeypatch.setattr(sys, "stdin", io.StringIO("Piped answer"))
++++ ++ assert evaluator._read_input(args(task=str(task))) == ("File task", "Piped answer")
++++ ++
++++ ++
++++ ++def test_missing_output_file_still_fails(tmp_path, monkeypatch, capsys):
++++ ++ monkeypatch.setattr(sys, "stdin", io.StringIO("Task"))
++++ ++ with pytest.raises(SystemExit, match="1"):
++++ ++ evaluator._read_input(args(output=str(tmp_path / "missing.txt")))
++++ ++ assert "not found" in capsys.readouterr().err
++++ ++
++++ ++
++++ ++def test_cli_uses_piped_task_for_conciseness_score(tmp_path):
++++ ++ output = tmp_path / "response.txt"
++++ ++ output.write_text("Verified with tests. " * 25, encoding="utf-8")
++++ ++ result = subprocess.run(
++++ ++ [sys.executable, "-X", "utf8", str(SCRIPT), "--output", str(output)],
++++ ++ input="Fix bug",
++++ ++ capture_output=True,
++++ ++ encoding="utf-8",
++++ ++ check=True,
++++ ++ timeout=10,
++++ ++ )
++++ ++ assert re.search(r"Conciseness[^\n]*3/5", result.stdout)
+++++++
+++++++
+++++++def test_long_inline_task_remains_text(tmp_path, monkeypatch):
+++++++ output = tmp_path / "response.txt"
+++++++ output.write_text("Answer", encoding="utf-8")
+++++++ task = "Long explicit task description. " * 60
+++++++ monkeypatch.setattr(sys, "stdin", io.StringIO("Ignored pipe"))
+++++++ assert evaluator._read_input(args(task=task, output=str(output))) == (task, "Answer")
+++++++
+++++++
[email protected]("error_code", [errno.EACCES, errno.EISDIR])
+++++++def test_task_read_does_not_hide_other_file_errors(monkeypatch, error_code):
+++++++ def fail_open(_path):
+++++++ raise OSError(error_code, "Cannot read task")
+++++++
+++++++ monkeypatch.setattr("builtins.open", fail_open)
+++++++ with pytest.raises(OSError) as captured:
+++++++ evaluator._read_file_or_text("task-file")
+++++++ assert captured.value.errno == error_code