diff --git a/manifests/context-packs/skill-triggers@1.json b/manifests/context-packs/skill-triggers@1.json index dca98a820..b55ffba1d 100644 --- a/manifests/context-packs/skill-triggers@1.json +++ b/manifests/context-packs/skill-triggers@1.json @@ -10,7 +10,7 @@ "id": "hand-seeded", "source": "manual-curation-pending-regeneration" }, - "registryDigest": "cf9879ff972740a7d2af9b56a0f682870375d3abc75eea9164bd2b1838fd5b81", + "registryDigest": "b90e8d8c63181ae5743f7fceaaf14b303c2a12ef93012a8d7ae492257caa6458", "schemaVersion": 1, "triggers": { "skill:agent-runtime-gateway-smoke-test": [ diff --git a/scripts/build-opencode-agents.js b/scripts/build-opencode-agents.js new file mode 100644 index 000000000..a2f23b475 --- /dev/null +++ b/scripts/build-opencode-agents.js @@ -0,0 +1,62 @@ +const fs = require('node:fs'); +const path = require('node:path'); +const yaml = require('js-yaml'); + +const repoRoot = path.resolve(__dirname, '..'); +const outputDir = path.join(repoRoot, '.opencode', 'agents'); +const agentNames = [ + 'code-simplifier', + 'comment-analyzer', + 'pr-test-analyzer', + 'silent-failure-hunter', + 'type-design-analyzer', + 'react-reviewer', + 'typescript-reviewer', + 'react-build-resolver', + 'vue-reviewer', + 'code-architect', + 'code-explorer', + 'fastapi-reviewer', + 'flutter-reviewer', + 'dart-build-resolver', + 'gan-planner', + 'gan-generator', + 'gan-evaluator', + 'conversation-analyzer', + 'marketing-agent', +]; + +function convertAgent(source, sourcePath) { + const match = source.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/); + if (!match) throw new Error(`Expected YAML frontmatter in ${sourcePath}`); + + const [, frontmatter, prompt] = match; + const agent = yaml.load(frontmatter); + const tools = Array.isArray(agent.tools) + ? agent.tools + : String(agent.tools ?? '').split(',').map(tool => tool.trim()); + + const definition = { + description: agent.description, + mode: 'subagent', + permission: { + edit: tools.includes('Edit') || tools.includes('Write') ? 'allow' : 'deny', + bash: tools.includes('Bash') ? 'ask' : 'deny', + }, + }; + + return `---\n${yaml.dump(definition)}---\n${prompt}`; +} + +function buildOpencodeAgents() { + fs.mkdirSync(outputDir, { recursive: true }); + + for (const name of agentNames) { + const sourcePath = path.join(repoRoot, 'agents', `${name}.md`); + const source = fs.readFileSync(sourcePath, 'utf8'); + const output = convertAgent(source, sourcePath); + fs.writeFileSync(path.join(outputDir, `${name}.md`), output); + } +} + +module.exports = { buildOpencodeAgents, convertAgent }; diff --git a/scripts/build-opencode.js b/scripts/build-opencode.js index 73610cd38..50abcc21f 100644 --- a/scripts/build-opencode.js +++ b/scripts/build-opencode.js @@ -24,3 +24,4 @@ execFileSync(process.execPath, [tscEntrypoint, "-p", path.join(opencodeDir, "tsc cwd: rootDir, stdio: "inherit", }) +require("./build-opencode-agents").buildOpencodeAgents() diff --git a/scripts/lib/install/content-transform.js b/scripts/lib/install/content-transform.js index 7c6d0c04c..cb1679330 100644 --- a/scripts/lib/install/content-transform.js +++ b/scripts/lib/install/content-transform.js @@ -1,5 +1,7 @@ 'use strict'; +const path = require('path'); + const { stripPluginNamespace } = require('./plugin-namespace'); const { adaptAntigravityAgent } = require('./antigravity-agent'); const { adaptAntigravityRule } = require('./antigravity-rule'); @@ -180,15 +182,26 @@ function transformInstallContent(operation, content) { } if (operation.contentTransform === 'opencode-home-skills-path') { const config = JSON.parse(content); - if (!Array.isArray(config?.skills?.paths) || !config.skills.paths.includes('../skills')) { - return content; - } + const { opencodeHomeInstructions } = operation; + const hasProjection = Array.isArray(opencodeHomeInstructions); + const hasInstructions = hasProjection && Array.isArray(config.instructions); + const hasBundledSkillsPath = Array.isArray(config.skills?.paths) + && config.skills.paths.includes('../skills'); + if (!hasInstructions && !hasBundledSkillsPath) return content; + // OpenCode resolves relative paths from the active project. Preserve the + // old transform for install records created without a path projection. + const bundledSkills = hasProjection + ? path.join(path.dirname(operation.destinationPath), 'skills') + : './skills'; const installedConfig = { ...config, - skills: { - ...config.skills, - paths: config.skills.paths.map(skillPath => skillPath === '../skills' ? './skills' : skillPath), - }, + ...(hasInstructions ? { instructions: opencodeHomeInstructions } : {}), + ...(hasBundledSkillsPath ? { + skills: { + ...config.skills, + paths: config.skills.paths.map(skillPath => skillPath === '../skills' ? bundledSkills : skillPath), + }, + } : {}), }; return `${JSON.stringify(installedConfig, null, 2)}\n`; } diff --git a/scripts/lib/install/plan.js b/scripts/lib/install/plan.js index 0979546ca..d4694578d 100644 --- a/scripts/lib/install/plan.js +++ b/scripts/lib/install/plan.js @@ -7,7 +7,7 @@ const { execFileSync } = require('child_process'); const { resolveInstallPlan } = require('../install-manifests'); const { getInstallTargetAdapter } = require('../install-targets/registry'); const { resolveInvocationEnvironment } = require('../invocation-environment'); -const { disableUnselectedOpenCodeHooks } = require('./hook-consent'); +const { disableUnselectedOpenCodeHooks, parseJsoncConfig } = require('./hook-consent'); const { readHooksConfig } = require('../hooks-config'); const { isPackageSourcePath, resolvePackageSourcePath } = require('./package-source'); const { @@ -263,6 +263,24 @@ function dedupeCopyFileOperations(operations) { }); } +function projectOpenCodeHomeInstructions(operations) { + const installedFiles = new Set(operations.filter(operation => operation.kind === 'copy-file') + .map(operation => operation.destinationPath)); + return operations.map(operation => { + if (operation.contentTransform !== 'opencode-home-skills-path') return operation; + const { instructions } = parseJsoncConfig( + fs.readFileSync(operation.sourcePath, 'utf8'), + operation.sourceRelativePath + ); + const configRoot = path.dirname(operation.destinationPath); + const opencodeHomeInstructions = (Array.isArray(instructions) ? instructions : []) + .map(instruction => path.resolve(configRoot, instruction)) + .filter(instruction => installedFiles.has(instruction)); + // Record the projection so repair uses the same profile-specific paths. + return { ...operation, opencodeHomeInstructions }; + }); +} + function createManifestInstallPlan(options = {}) { const requestedSourceRoot = options.sourceRoot || getSourceRoot(); const projectRoot = options.projectRoot || process.cwd(); @@ -320,13 +338,16 @@ function createManifestInstallPlan(options = {}) { return operation; }); const ruleLanguages = Array.isArray(options.ruleLanguages) ? [...options.ruleLanguages] : []; - const operations = dedupeCopyFileOperations( + const dedupedOperations = dedupeCopyFileOperations( options.legacyMode && target === 'antigravity' ? materializedOperations.filter(operation => ( isSelectedAntigravityLegacyRule(operation, ruleLanguages) )) : materializedOperations ); + const operations = target === 'opencode' + ? projectOpenCodeHomeInstructions(dedupedOperations) + : dedupedOperations; const source = { repoVersion: preparedSource.sourceVersion || getPackageVersion(sourceRoot), repoUrl: preparedSource.sourceUrl || null, diff --git a/skills/skill-stocktake/scripts/scan.sh b/skills/skill-stocktake/scripts/scan.sh index c9ee98bfa..8b773713d 100755 --- a/skills/skill-stocktake/scripts/scan.sh +++ b/skills/skill-stocktake/scripts/scan.sh @@ -74,25 +74,28 @@ date_ago() { date -u -d "${n} days ago" +%Y-%m-%dT%H:%M:%SZ } -# Count observations matching a file path since a cutoff timestamp -count_obs() { - local file="$1" cutoff="$2" +# Keep paths as JSON keys so characters in filenames never split records. +aggregate_observations() { if [[ ! -f "$OBSERVATIONS" ]]; then echo null return fi - jq -r --arg p "$file" --arg c "$cutoff" \ - 'select(.tool=="Read" and .path==$p and .timestamp>=$c) | 1' \ - "$OBSERVATIONS" 2>/dev/null | wc -l | tr -d ' ' + + local c7 c30 + c7=$(date_ago 7) + c30=$(date_ago 30) + jq -n --arg c7 "$c7" --arg c30 "$c30" ' + reduce inputs as $event ({}; + if $event.tool == "Read" and ($event.path | type) == "string" and $event.timestamp >= $c30 then + .[$event.path].use_30d += 1 + | if $event.timestamp >= $c7 then .[$event.path].use_7d += 1 else . end + else . end) + ' "$OBSERVATIONS" } # Scan a directory and produce a JSON array of skill objects scan_dir_to_json() { local dir="$1" - local c7 c30 - c7=$(date_ago 7) - c30=$(date_ago 30) - local tmpdir tmpdir=$(mktemp -d) # Use a function to avoid embedding $tmpdir in a quoted string (prevents injection @@ -101,23 +104,6 @@ scan_dir_to_json() { _scan_cleanup() { rm -rf "$_scan_tmpdir"; } trap _scan_cleanup RETURN - # Pre-aggregate observation counts in two passes (one per window) instead of - # calling jq per-file — reduces from O(n*m) to O(n+m) jq invocations. - local obs_7d_counts obs_30d_counts - # Zero is meaningful only when an observations file is available. - local usage_default=null - obs_7d_counts="" - obs_30d_counts="" - if [[ -f "$OBSERVATIONS" ]]; then - usage_default=0 - obs_7d_counts=$(jq -r --arg c "$c7" \ - 'select(.tool=="Read" and .timestamp>=$c) | .path' \ - "$OBSERVATIONS" 2>/dev/null | sort | uniq -c) - obs_30d_counts=$(jq -r --arg c "$c30" \ - 'select(.tool=="Read" and .timestamp>=$c) | .path' \ - "$OBSERVATIONS" 2>/dev/null | sort | uniq -c) - fi - local i=0 local find_out="$tmpdir/.find-stdout" local find_err="$tmpdir/.find-stderr" @@ -135,23 +121,10 @@ scan_dir_to_json() { sort_nul_file "$find_out" while IFS= read -r -d '' file; do - local name desc mtime u7 u30 dp record_file + local name desc mtime dp record_file name=$(extract_field "$file" "name") desc=$(extract_field "$file" "description") mtime=$(date -u -r "$file" +%Y-%m-%dT%H:%M:%SZ) - if [[ "$file" == *[[:space:]]* ]]; then - # The aggregated fast path is line-delimited. Preserve unusual paths by - # falling back to the structured JSON matcher for this record. - u7=$(count_obs "$file" "$c7") - u30=$(count_obs "$file" "$c30") - else - # Use awk exact field match to avoid substring false-positives from grep -F. - # uniq -c output format: " N /path/to/file" — path is always field 2. - u7=$(echo "$obs_7d_counts" | awk -v f="$file" '$2 == f {print $1}' | head -1) - u7="${u7:-$usage_default}" - u30=$(echo "$obs_30d_counts" | awk -v f="$file" '$2 == f {print $1}' | head -1) - u30="${u30:-$usage_default}" - fi dp="${file/#$HOME/~}" # Zero-pad record names so the "$tmpdir"/*.json glob below keeps the sorted @@ -162,9 +135,8 @@ scan_dir_to_json() { --arg name "$name" \ --arg description "$desc" \ --arg mtime "$mtime" \ - --argjson use_7d "$u7" \ - --argjson use_30d "$u30" \ - '{path:$path,name:$name,description:$description,use_7d:$use_7d,use_30d:$use_30d,mtime:$mtime}' \ + --arg observation_path "$file" \ + '{path:$path,name:$name,description:$description,mtime:$mtime,observation_path:$observation_path}' \ > "$record_file" i=$((i+1)) done < "$find_out" @@ -172,7 +144,15 @@ scan_dir_to_json() { if [[ $i -eq 0 ]]; then echo "[]" else - jq -s '.' "$tmpdir"/*.json + local usage_file="$tmpdir/.usage" + aggregate_observations >"$usage_file" + jq -s --slurpfile usage "$usage_file" ' + $usage[0] as $counts | + map($counts[.observation_path] as $skill | + .use_7d = (if $counts == null then null else ($skill.use_7d // 0) end) | + .use_30d = (if $counts == null then null else ($skill.use_30d // 0) end) | + del(.observation_path)) + ' "$tmpdir"/*.json fi } diff --git a/tests/lib/install-executor.test.js b/tests/lib/install-executor.test.js index d9af21a30..f26c772e4 100644 --- a/tests/lib/install-executor.test.js +++ b/tests/lib/install-executor.test.js @@ -764,6 +764,54 @@ function runTests() { } })) passed++; else failed++; + for (const profileId of ['minimal', 'full']) { + for (const hookConsent of ['enabled', 'declined']) { + if (test(`fresh OpenCode ${profileId} home install projects instructions with hooks ${hookConsent}`, () => { + const tempDir = createTempDir('install-executor-opencode-instructions-'); + try { + const sourceConfigPath = path.join(REPO_ROOT, '.opencode', 'opencode.json'); + const sourceContent = fs.readFileSync(sourceConfigPath, 'utf8'); + const sourceConfig = JSON.parse(sourceContent); + const plan = createInstallPlanFromRequest(normalizeInstallRequest({ + target: 'opencode', + profileId, + enableHooks: hookConsent === 'enabled', + noHooks: hookConsent === 'declined', + }), { + sourceRoot: REPO_ROOT, + homeDir: path.join(tempDir, 'home with spaces'), + projectRoot: path.join(tempDir, 'unrelated-project'), + exemptValidationCodes: ['opencode-plugin-not-built'], + }); + applyInstallPlan(plan); + + const config = JSON.parse(fs.readFileSync(path.join(plan.targetRoot, 'opencode.json'), 'utf8')); + const installedPaths = new Set(plan.operations.map(operation => operation.destinationPath)); + const expected = sourceConfig.instructions + .filter(instruction => !['AGENTS.md', 'CONTRIBUTING.md'].includes(instruction)) + .map(instruction => path.join(plan.targetRoot, instruction)) + .filter(instruction => installedPaths.has(instruction)); + assert.deepStrictEqual(config.instructions, expected); + assert.deepStrictEqual(config.skills.paths, [path.join(plan.targetRoot, 'skills')]); + assert.ok(config.instructions.includes(path.join(plan.targetRoot, 'instructions', 'INSTRUCTIONS.md'))); + assert.ok(config.instructions.includes(path.join(plan.targetRoot, 'skills', 'tdd-workflow', 'SKILL.md'))); + assert.strictEqual( + config.instructions.includes(path.join(plan.targetRoot, 'skills', 'frontend-slides', 'SKILL.md')), + profileId === 'full' + ); + for (const instruction of config.instructions) { + assert.ok(path.isAbsolute(instruction), `instruction depends on launch directory: ${instruction}`); + assert.ok(fs.statSync(instruction).isFile(), `instruction was not installed: ${instruction}`); + assert.ok(!['AGENTS.md', 'CONTRIBUTING.md'].includes(path.basename(instruction))); + } + assert.strictEqual(fs.readFileSync(sourceConfigPath, 'utf8'), sourceContent); + } finally { + cleanup(tempDir); + } + })) passed++; else failed++; + } + } + if (test('OpenCode home installs resolve bundled skills inside the config root', () => { const tempDir = createTempDir('install-executor-opencode-skills-'); try { @@ -795,7 +843,11 @@ function runTests() { for (const [index, config] of configs.entries()) { const configSourcePath = path.join(sourceRoot, '.opencode', 'opencode.json'); - writeJson(sourceRoot, '.opencode/opencode.json', config); + if (index === 2) { + writeFile(sourceRoot, '.opencode/opencode.json', '{ /* fixture */ "plugin": ["./plugins",], }\n'); + } else { + writeJson(sourceRoot, '.opencode/opencode.json', config); + } const originalContent = fs.readFileSync(configSourcePath, 'utf8'); const plan = createManifestInstallPlan({ sourceRoot, @@ -811,8 +863,12 @@ function runTests() { const dormantConfig = Array.isArray(config.plugin) ? { ...config, plugin: config.plugin.filter(plugin => plugin !== './plugins') } : { ...config }; + if (Array.isArray(config.instructions)) { + // This fixture does not install any of the template's instruction files. + dormantConfig.instructions = []; + } const expected = index === 0 - ? { ...dormantConfig, skills: { ...config.skills, paths: ['./skills', '/custom/skills', '../other-skills'] } } + ? { ...dormantConfig, skills: { ...config.skills, paths: [path.join(plan.targetRoot, 'skills'), '/custom/skills', '../other-skills'] } } : dormantConfig; assert.deepStrictEqual(installed, expected); assert.strictEqual(fs.readFileSync(configSourcePath, 'utf8'), originalContent, 'repository template must stay unchanged'); @@ -1138,7 +1194,7 @@ function runTests() { 'utf8' )); assert.ok(!installedConfig.plugin?.includes('./plugins')); - assert.deepStrictEqual(installedConfig.skills.paths, ['./skills']); + assert.deepStrictEqual(installedConfig.skills.paths, [path.join(defaultPlan.targetRoot, 'skills')]); const enabledWithoutRuntime = createInstallPlanFromRequest( normalizeInstallRequest({ @@ -1192,7 +1248,7 @@ function runTests() { )); assert.strictEqual(enabledConfig.contentTransform, 'opencode-home-skills-path'); applyInstallPlanDirect(enabledPlan); - assert.deepStrictEqual(JSON.parse(fs.readFileSync(enabledConfig.destinationPath, 'utf8')).skills.paths, ['./skills']); + assert.deepStrictEqual(JSON.parse(fs.readFileSync(enabledConfig.destinationPath, 'utf8')).skills.paths, [path.join(enabledPlan.targetRoot, 'skills')]); for (const name of OPENCODE_ENTRYPOINTS) { assert.strictEqual( fs.readFileSync(path.join(homeDir, '.config', 'opencode', 'plugins', name), 'utf8'), diff --git a/tests/opencode-agent-conversion.test.js b/tests/opencode-agent-conversion.test.js new file mode 100644 index 000000000..f2dde5fb5 --- /dev/null +++ b/tests/opencode-agent-conversion.test.js @@ -0,0 +1,31 @@ +const assert = require('node:assert/strict'); +const test = require('node:test'); +const yaml = require('js-yaml'); +const { convertAgent } = require('../scripts/build-opencode-agents'); + +const cases = [ + ['comma-separated read-only tools', 'Read, Grep, Glob', 'deny', 'deny'], + ['array with Edit', ['Read', 'Edit'], 'allow', 'deny'], + ['comma-separated Write and Bash', 'Read, Write, Bash', 'allow', 'ask'], + ['array with Bash and no edit tools', ['Read', 'Bash'], 'deny', 'ask'], +]; + +for (const [name, tools, edit, bash] of cases) { + test(`converts OpenCode agent permissions for ${name}`, () => { + const prompt = '## Review instructions\n\nKeep the original prompt.\n'; + const frontmatter = yaml.dump({ + description: 'Example reviewer', + model: 'sonnet', + tools, + }); + const output = convertAgent(`---\n${frontmatter}---\n${prompt}`, 'example.md'); + const [, generatedFrontmatter, generatedPrompt] = output.split('---\n'); + + assert.deepEqual(yaml.load(generatedFrontmatter), { + description: 'Example reviewer', + mode: 'subagent', + permission: { edit, bash }, + }); + assert.equal(generatedPrompt, prompt); + }); +} diff --git a/tests/opencode-review-agents.test.js b/tests/opencode-review-agents.test.js new file mode 100644 index 000000000..416d3a216 --- /dev/null +++ b/tests/opencode-review-agents.test.js @@ -0,0 +1,80 @@ +const assert = require('node:assert/strict'); +const { execFileSync } = require('node:child_process'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const test = require('node:test'); + +const agentsByCommand = { + 'review-pr': [ + 'code-reviewer', + 'comment-analyzer', + 'pr-test-analyzer', + 'silent-failure-hunter', + 'type-design-analyzer', + 'code-simplifier', + ], + 'react-review': ['react-reviewer', 'typescript-reviewer'], + 'react-test': ['react-reviewer'], + 'react-build': ['react-build-resolver'], + 'vue-review': ['vue-reviewer', 'typescript-reviewer'], + 'feature-dev': ['code-architect', 'code-explorer'], + 'orch-fix-defect': ['code-explorer'], + 'fastapi-review': ['fastapi-reviewer'], + 'flutter-review': ['flutter-reviewer'], + 'flutter-build': ['dart-build-resolver'], + 'flutter-test': ['dart-build-resolver', 'flutter-reviewer'], + 'gan-build': ['gan-planner', 'gan-generator', 'gan-evaluator'], + 'hookify': ['conversation-analyzer'], + 'marketing-campaign': ['marketing-agent'], +}; + +test('a full OpenCode install includes agents required by affected commands', () => { + const repoRoot = path.resolve(__dirname, '..'); + const home = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-review-agents-')); + const configHome = path.join(home, '.config'); + const installRoot = path.join(configHome, 'opencode'); + + try { + execFileSync(process.execPath, ['scripts/build-opencode.js'], { + cwd: repoRoot, + stdio: 'pipe', + }); + + execFileSync(process.execPath, [ + 'scripts/install-apply.js', + '--target', 'opencode', + '--profile', 'full', + '--no-hooks', + ], { + cwd: repoRoot, + env: { + ...process.env, + HOME: home, + USERPROFILE: home, + XDG_CONFIG_HOME: configHome, + OPENCODE_CONFIG_DIR: installRoot, + }, + stdio: ['ignore', 'ignore', 'pipe'], + }); + + const config = JSON.parse( + fs.readFileSync(path.join(installRoot, 'opencode.json'), 'utf8') + ); + const missing = Object.entries(agentsByCommand).flatMap(([command, agents]) => { + const commandFile = path.join(installRoot, 'commands', `${command}.md`); + assert.ok(fs.existsSync(commandFile), `Expected /${command} to be installed`); + + return agents.filter(name => { + const hasAgentFile = ['agents', 'agent'].some(folder => + fs.existsSync(path.join(installRoot, folder, `${name}.md`)) + ); + return !Object.hasOwn(config.agent ?? {}, name) && !hasAgentFile; + }).map(name => `/${command} -> ${name}`); + }); + + assert.deepEqual(missing, [], `Missing OpenCode agents: ${missing.join(', ')}`); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } +}); diff --git a/tests/scripts/build-opencode.test.js b/tests/scripts/build-opencode.test.js index 6023d6f02..cf692903a 100644 --- a/tests/scripts/build-opencode.test.js +++ b/tests/scripts/build-opencode.test.js @@ -370,8 +370,8 @@ function main() { }), "enabled") applyInstallPlan(plan) const config = JSON.parse(fs.readFileSync(path.join(plan.targetRoot, "opencode.json"), "utf8")) - assert.deepStrictEqual(config.skills.paths, ["./skills"]) - assert.ok(fs.existsSync(path.join(plan.targetRoot, config.skills.paths[0], "tdd-workflow", "SKILL.md"))) + assert.deepStrictEqual(config.skills.paths, [path.join(plan.targetRoot, "skills")]) + assert.ok(fs.existsSync(path.join(config.skills.paths[0], "tdd-workflow", "SKILL.md"))) assert.ok(!fs.existsSync(path.join(plan.targetRoot, "tools", "run-tests.js"))) checkRuntime( plan.targetRoot, diff --git a/tests/scripts/skill-stocktake-discovery.test.js b/tests/scripts/skill-stocktake-discovery.test.js index 4d490e05f..9d4b0c8cf 100644 --- a/tests/scripts/skill-stocktake-discovery.test.js +++ b/tests/scripts/skill-stocktake-discovery.test.js @@ -258,6 +258,52 @@ if (process.platform !== 'win32') { } }); + test('scan counts literal backslashes in skill paths without interpreting escape sequences', () => { + const skillsDir = path.join(tempRoot, 'backslash-skills'); + const skillDir = path.join(skillsDir, String.raw`literal\tname\nending`); + writeSkill(skillDir, 'backslash-skill'); + const skillPath = path.join(skillDir, 'SKILL.md'); + const observationsPath = path.join(tempRoot, 'backslash-observations.jsonl'); + const observations = [0, 1, 10, 40].map(days => ({ + tool: 'Read', + path: skillPath, + timestamp: new Date(Date.now() - days * 86400000).toISOString(), + })); + fs.writeFileSync(observationsPath, `${observations.map(record => JSON.stringify(record)).join('\n')}\n`); + const result = runBash(scanScript, [], { + SKILL_STOCKTAKE_GLOBAL_DIR: path.join(tempRoot, 'missing-global'), + SKILL_STOCKTAKE_PROJECT_DIR: skillsDir, + SKILL_STOCKTAKE_OBSERVATIONS: observationsPath, + }); + assert.strictEqual(result.status, 0, result.stderr); + const skills = JSON.parse(result.stdout).skills; + assert.strictEqual(skills.length, 1); + assert.strictEqual(skills[0].path, skillPath); + assert.strictEqual(skills[0].use_7d, 2); + assert.strictEqual(skills[0].use_30d, 3); + }); + + test('scan does not count a newline-delimited path fragment as an observed skill', () => { + const skillPath = path.join(globalSkills, 'active', 'SKILL.md'); + // This is one real file outside the inventory. Its newline is immediately + // followed by the complete path of a different, unobserved tracked skill. + const unrelatedPath = `${tempRoot}/unrelated\n${skillPath}`; + fs.mkdirSync(path.dirname(unrelatedPath), { recursive: true }); + fs.writeFileSync(unrelatedPath, '# unrelated file\n'); + const observationsPath = path.join(tempRoot, 'newline-fragment-observations.jsonl'); + fs.writeFileSync(observationsPath, `${JSON.stringify({ + tool: 'Read', path: unrelatedPath, timestamp: new Date().toISOString(), + })}\n`); + assert.notStrictEqual(unrelatedPath, skillPath); + assert.ok(fs.statSync(unrelatedPath).isFile()); + const result = runBash(scanScript, [], { ...env, SKILL_STOCKTAKE_OBSERVATIONS: observationsPath }); + assert.strictEqual(result.status, 0, result.stderr); + const skill = JSON.parse(result.stdout).skills.find(entry => entry.path === skillPath); + assert.ok(skill, 'the unobserved skill must remain in the inventory'); + assert.strictEqual(skill.use_7d, 0); + assert.strictEqual(skill.use_30d, 0); + }); + test('scan preserves exact usage counts and date windows for normal and whitespace paths', () => { const observationsPath = path.join(tempRoot, 'matching-observations.jsonl'); const observedPaths = [path.join(linkedSkill, 'SKILL.md'),