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: count observer instinct files using loader eligibility

affaan-m57da51c74bc6
diff --cc manifests/context-packs/[email protected]
index 000000000,d591dee56..1df906979
mode 000000,100644..100644
--- a/manifests/context-packs/[email protected]
+++ b/manifests/context-packs/[email protected]
@@@ -1,0 -1,1 +1,1 @@@
-{"coverage":{"skills":292,"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":"2c24ec8ddbe6837f0187e2c953e17e14d83b45d348850643e9bd806e00efe70c","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":292,"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":"2f8d851a507b266125a2148fe56efe6c2a1d4f2f89f283c958a0b2c2e84aa17f","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"}
diff --cc skills/continuous-learning-v2/agents/start-observer.sh
index 5dc311b70,5485a79e3..d00ffcf06
--- a/skills/continuous-learning-v2/agents/start-observer.sh
+++ b/skills/continuous-learning-v2/agents/start-observer.sh
@@@ -156,14 -156,8 +156,14 @@@ case "$ACTION" i
echo "Observer is running (PID: $pid)"
echo "Log: $LOG_FILE"
echo "Observations: $(wc -l < "$OBSERVATIONS_FILE" 2>/dev/null || echo 0) lines"
- # Also show instinct count. Count every extension the loader accepts
- # (ALLOWED_INSTINCT_EXTENSIONS in scripts/instinct-cli.py) - the
- # observer prompt tells the analyzer to write "<id>.md", so a
- # *.yaml-only count reports 0 on a working install. Depth and case
- # match the loader's iterdir() + suffix.lower(): top level only,
- # case-insensitive. tr strips the padding BSD wc emits.
- # Also show instinct count
- instinct_count=$(find "$INSTINCTS_DIR" -name "*.yaml" 2>/dev/null | wc -l)
++ # Count eligible files, not parsed records: the loader accepts these
++ # suffixes case-insensitively and follows links to regular files.
++ # Stay at the top level, excluding dot-only names with no Path.suffix.
++ # Count NUL records so newlines in filenames cannot inflate the result.
+ instinct_find_expr=( \( -iname "*.yaml" -o -iname "*.yml" -o -iname "*.md" \) )
- instinct_count=$(find "$INSTINCTS_DIR" -maxdepth 1 -type f "${instinct_find_expr[@]}" 2>/dev/null | wc -l | tr -d "[:space:]")
++ instinct_count=$(find -L "$INSTINCTS_DIR" -mindepth 1 -maxdepth 1 -type f \
++ "${instinct_find_expr[@]}" ! -iname ".yaml" ! -iname ".yml" ! -iname ".md" \
++ -print0 2>/dev/null | tr -cd '\000' | wc -c | tr -d '[:space:]')
echo "Instincts: $instinct_count"
exit 0
else
diff --cc tests/skills/observer-status-instinct-count.test.js
index d65a850ca,000000000..4b59cd188
mode 100644,000000..100644
--- a/tests/skills/observer-status-instinct-count.test.js
+++ b/tests/skills/observer-status-instinct-count.test.js
@@@ -1,213 -1,0 +1,272 @@@
+/**
- * Regression tests for #2859: `start-observer.sh status` counted only *.yaml.
- *
- * The producer writes `<id>.md` (agents/observer-loop.sh instructs the analyzer
- * to) and the loader accepts .yaml/.yml/.md (ALLOWED_INSTINCT_EXTENSIONS in
- * scripts/instinct-cli.py), so the one command an operator runs to confirm that
- * learning works reported `Instincts: 0` on a working install — and an operator
- * cannot tell that apart from a silently dead observer.
++ * Regression tests for #2859: status counts eligible top-level instinct files.
++ * The loader accepts .yaml/.yml/.md; files can contain zero or many instincts,
++ * so this count does not establish parsed-record counts or observer health.
+ */
+
+'use strict';
+
+const assert = require('assert');
+const { spawnSync } = require('child_process');
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+
+const repoRoot = path.resolve(__dirname, '..', '..');
+const skillRoot = path.join(repoRoot, 'skills', 'continuous-learning-v2');
+const observerScript = path.join(skillRoot, 'agents', 'start-observer.sh');
- const detectProject = path.join(skillRoot, 'scripts', 'detect-project.sh');
+const instinctCli = path.join(skillRoot, 'scripts', 'instinct-cli.py');
- const bashBinary = process.env.ECC_TEST_BASH || (process.platform === 'win32' ? null : 'bash');
++const bashBinary = process.env.ECC_TEST_BASH || (process.platform === 'win32' ? null : '/bin/bash');
++const childTimeoutMs = 3000;
++const childMaxBuffer = 64 * 1024;
++
++class SkipTest extends Error {}
+
+function toShellPath(filePath) {
+ const normalized = filePath.split(path.sep).join('/');
+ return normalized.replace(/^([A-Za-z]):\//, (_, drive) => `/${drive.toLowerCase()}/`);
+}
+
+function readAllowedExtensions() {
+ const cliSource = fs.readFileSync(instinctCli, 'utf8');
+ const match = cliSource.match(/ALLOWED_INSTINCT_EXTENSIONS\s*=\s*\(([^)]*)\)/);
+ assert.ok(match, 'ALLOWED_INSTINCT_EXTENSIONS not found in instinct-cli.py');
- return match[1]
- .split(',')
++ return match[1].split(',')
+ .map(part => part.trim().replace(/^["']|["']$/g, ''))
+ .filter(Boolean);
+}
+
- function readStatusCounter() {
- const observerSource = fs.readFileSync(observerScript, 'utf8');
- const counter = observerSource
- .split('\n')
- .filter(line => line.includes('instinct_count=') || line.includes('instinct_find_expr='))
- .join('\n');
- assert.ok(counter, 'status branch no longer computes an instinct count');
- return counter;
++function fixtureAt(root) {
++ const home = path.join(root, 'home');
++ const temp = path.join(root, 'tmp');
++ const bin = path.join(root, 'bin');
++ const homunculus = path.join(root, 'homunculus');
++ const instincts = path.join(homunculus, 'instincts', 'personal');
++ const unexpected = path.join(root, 'unexpected-command');
++ for (const directory of [home, temp, bin, instincts]) fs.mkdirSync(directory, { recursive: true });
++ for (const command of ['python', 'python3', 'git', 'claude']) {
++ fs.writeFileSync(path.join(bin, command),
++ '#!/bin/sh\nprintf unexpected > "$FIXTURE_UNEXPECTED_COMMAND"\nexit 97\n', { mode: 0o700 });
++ }
++ fs.writeFileSync(path.join(homunculus, 'observations.jsonl'), '');
++ return {
++ root, instincts, unexpected,
++ env: {
++ PATH: [toShellPath(bin), '/usr/bin', '/bin'].join(':'),
++ HOME: toShellPath(home), USERPROFILE: home, TMPDIR: toShellPath(temp),
++ TMP: temp, TEMP: temp, LC_ALL: 'C',
++ ...(process.platform === 'win32' ? { SystemRoot: process.env.SystemRoot } : {}),
++ CLV2_NO_PROJECT: '1', CLV2_HOMUNCULUS_DIR: toShellPath(homunculus),
++ CLV2_CONFIG: toShellPath(path.join(root, 'absent-config.json')),
++ CLV2_PYTHON_CMD: toShellPath(path.join(bin, 'python3')),
++ FIXTURE_UNEXPECTED_COMMAND: toShellPath(unexpected),
++ },
++ };
+}
+
- function resolvePython() {
- for (const candidate of [process.env.ECC_TEST_PYTHON, 'python3', 'python']) {
- if (!candidate) continue;
- const probe = spawnSync(candidate, ['-c', 'print(1)'], { encoding: 'utf8' });
- if (probe.status === 0) return candidate;
++function withFixture(callback, remove = fs.rmSync) {
++ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-observer-')));
++ let failed = false; let primary; let result;
++ try {
++ result = callback(fixtureAt(root));
++ } catch (error) {
++ failed = true;
++ primary = error;
+ }
- return null;
++ try { remove(root, { recursive: true, force: true }); }
++ catch (error) { if (!failed) throw error; }
++ if (failed) throw primary;
++ return result;
+}
+
- const pythonCmd = bashBinary ? resolvePython() : null;
++function checkChild(result) {
++ if (result.error) throw result.error;
++ assert.strictEqual(result.status, 0, result.stderr || result.stdout || `child signal: ${result.signal}`);
++}
+
- function runStatus(files) {
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-observer-'));
- try {
- const projectDir = path.join(tmp, 'proj');
- fs.mkdirSync(projectDir, { recursive: true });
- const writes = files
- .map(name => `printf 'id: x' > "$INST/${name}"`)
- .join('\n ');
- const script = [
- `source "${toShellPath(detectProject)}"`,
- 'INST="$PROJECT_DIR/instincts/personal"',
- 'mkdir -p "$INST/nested"',
- writes,
- ': > "$PROJECT_DIR/observations.jsonl"',
- 'sleep 10 &',
- 'OBSERVER_PID=$!',
- 'echo "$OBSERVER_PID" > "$PROJECT_DIR/.observer.pid"',
- `bash "${toShellPath(observerScript)}" status`,
- 'status=$?',
- 'kill "$OBSERVER_PID" 2>/dev/null || true',
- 'exit $status',
- ].join('\n');
- const result = spawnSync(bashBinary, ['-c', script], {
- encoding: 'utf8',
- env: {
- ...process.env,
- CLV2_HOMUNCULUS_DIR: toShellPath(path.join(tmp, 'homunculus')),
- CLAUDE_PROJECT_DIR: toShellPath(projectDir),
- CLV2_PYTHON_CMD: pythonCmd,
- },
++function runStatus(files, { run = spawnSync, setup = () => {}, remove = fs.rmSync } = {}) {
++ return withFixture(fixture => {
++ for (const name of files) {
++ const target = path.join(fixture.instincts, name);
++ fs.mkdirSync(path.dirname(target), { recursive: true });
++ fs.writeFileSync(target, 'id: fixture\n');
++ }
++ setup(fixture);
++ // Only this foreground shell's own PID is advertised. No observer, sleep,
++ // provider or other background child is started or signalled.
++ const program = 'printf "%s\\n" "$$" > "$CLV2_HOMUNCULUS_DIR/.observer.pid"\nexec "$BASH" "$1" status';
++ const result = run(bashBinary, ['--noprofile', '--norc', '-c', program,
++ 'observer-status-test', toShellPath(observerScript)], {
++ cwd: fixture.root, encoding: 'utf8', env: fixture.env,
++ timeout: childTimeoutMs, maxBuffer: childMaxBuffer, killSignal: 'SIGKILL',
+ });
- assert.strictEqual(result.status, 0, result.stderr || result.stdout);
- const line = (result.stdout || '').split('\n').find(l => l.startsWith('Instincts:'));
- assert.ok(line, `no "Instincts:" line in status output:\n${result.stdout}`);
- return Number(line.split(':')[1].trim());
- } finally {
- fs.rmSync(tmp, { recursive: true, force: true });
- }
++ checkChild(result);
++ assert.ok(!fs.existsSync(fixture.unexpected), 'status must not invoke Git, Python or a provider');
++ const lines = (result.stdout || '').split('\n').filter(line => line.startsWith('Instincts:'));
++ assert.strictEqual(lines.length, 1, `expected one count in status output:\n${result.stdout}`);
++ assert.match(lines[0], /^Instincts:\s+\d+\s*$/);
++ return Number(lines[0].split(':')[1].trim());
++ }, remove);
+}
+
- function buildTests() {
- const tests = [];
-
- // ── The counter must accept every extension the loader accepts ──
-
- tests.push(['the loader still declares several instinct extensions', () => {
- const allowed = readAllowedExtensions();
- assert.ok(allowed.length >= 3, `expected several extensions, got ${allowed}`);
- }]);
-
- for (const ext of readAllowedExtensions()) {
- tests.push([`status counts ${ext} — the loader accepts it`, () => {
- const counter = readStatusCounter();
- assert.ok(
- counter.includes(`*${ext}"`) || counter.includes(`*${ext}'`),
- `status count must match ${ext} (ALLOWED_INSTINCT_EXTENSIONS)`
- );
- }]);
++function fileLink(target, link, type = 'file') {
++ try { fs.symlinkSync(target, link, type); }
++ catch (error) {
++ const unsupported = ['ENOSYS', 'ENOTSUP'].includes(error.code)
++ || (process.platform === 'win32' && ['EPERM', 'EACCES'].includes(error.code));
++ if (unsupported) throw new SkipTest(`symlink capability unavailable: ${error.code}`);
++ throw error;
+ }
++}
+
- // Depth and case must match the loader: Path.iterdir() is top-level only and
- // is_file() skips directories; suffix.lower() makes the match case-insensitive.
- tests.push(['status does not recurse — the loader does not', () => {
- assert.ok(readStatusCounter().includes('-maxdepth 1'));
- }]);
- tests.push(['status skips directories', () => {
- assert.ok(readStatusCounter().includes('-type f'));
- }]);
- tests.push(['status matches case-insensitively', () => {
- assert.ok(!/-name\s+["']\*/.test(readStatusCounter()),
- 'status count must use -iname, not -name');
- }]);
-
- // ── The shipped script, run for real ──
-
- if (!(bashBinary && pythonCmd)) return tests;
-
- tests.push(['start-observer.sh parses', () => {
- const syntax = spawnSync(bashBinary, ['-n', toShellPath(observerScript)], { encoding: 'utf8' });
- assert.strictEqual(syntax.status, 0, syntax.stderr);
- }]);
-
- // The reported shape: every instinct on disk is a .md file.
- tests.push(['markdown instincts are counted', () => {
- assert.strictEqual(runStatus(['a.md', 'b.md', 'c.md']), 3);
- }]);
-
- // Every accepted extension, mixed case, plus the two things the loader skips:
- // a non-instinct file and a nested directory.
- tests.push(['the count matches the loader exactly', () => {
- assert.strictEqual(
- runStatus(['a.md', 'b.yaml', 'c.yml', 'd.YAML', 'notes.txt', 'nested/deep.md']),
- 4
- );
- }]);
-
- tests.push(['an empty instincts directory reports 0', () => {
- assert.strictEqual(runStatus([]), 0);
- }]);
-
- return tests;
++function shellTest(fn) {
++ return () => {
++ if (!bashBinary) throw new SkipTest('requires bash; set ECC_TEST_BASH on Windows');
++ return fn();
++ };
+}
+
- function runTest(name, fn) {
- try {
- fn();
- console.log(` ✓ ${name}`);
- return true;
- } catch (error) {
- console.log(` ✗ ${name}`);
- console.error(` ${error.message}`);
- return false;
- }
++function cleanupTests() {
++ return [
++ ['status child has a private environment and bounded execution', () => {
++ let root;
++ assert.strictEqual(runStatus([], { run: (_command, args, options) => {
++ root = options.cwd;
++ assert.strictEqual(options.timeout, childTimeoutMs);
++ assert.strictEqual(options.maxBuffer, childMaxBuffer);
++ assert.strictEqual(options.killSignal, 'SIGKILL');
++ assert.strictEqual(options.env.CLV2_NO_PROJECT, '1');
++ for (const key of ['BASH_ENV', 'ENV', 'NODE_OPTIONS', 'ANTHROPIC_API_KEY', 'CLAUDE_PROJECT_DIR']) {
++ assert.ok(!Object.hasOwn(options.env, key), `unexpected inherited ${key}`);
++ }
++ assert.ok(options.env.CLV2_CONFIG.endsWith('/absent-config.json'));
++ assert.ok(!fs.existsSync(options.env.CLV2_CONFIG));
++ assert.strictEqual(args.at(-1), toShellPath(observerScript));
++ assert.match(args[3], /\nexec "\$BASH" "\$1" status$/);
++ assert.doesNotMatch(args[3], /sleep|kill|&/);
++ return { status: 0, stdout: 'Instincts: 0\n', stderr: '' };
++ } }), 0);
++ assert.ok(!fs.existsSync(root));
++ }],
++ ...['timeout', 'nonzero', 'spawn error'].map(kind => [`${kind} cleans its private fixture`, () => {
++ let root;
++ const failure = Object.assign(new Error(kind), { code: kind === 'timeout' ? 'ETIMEDOUT' : 'EIO' });
++ assert.throws(() => runStatus([], { run: (_command, _args, options) => {
++ root = options.cwd;
++ return kind === 'nonzero' ? { status: 7, stdout: '', stderr: 'fixture rejected' } : { error: failure };
++ } }), error => kind === 'nonzero' ? /fixture rejected/.test(error.message) : error === failure);
++ assert.ok(!fs.existsSync(root));
++ }]),
++ ['cleanup preserves frozen and falsy primary failures', () => {
++ for (const primary of [Object.freeze(new Error('primary')), null, false, 0, undefined]) {
++ let root; let caught = false;
++ try {
++ withFixture(value => { root = value.root; throw primary; }, (value, options) => {
++ fs.rmSync(value, options); throw new Error('cleanup');
++ });
++ } catch (error) { caught = true; assert.strictEqual(error, primary); }
++ assert.ok(caught);
++ assert.ok(!fs.existsSync(root));
++ }
++ }],
++ ['cleanup failure is reported when the fixture otherwise succeeds', () => {
++ let root;
++ const failure = new Error('cleanup');
++ assert.throws(() => withFixture(value => { root = value.root; }, (value, options) => {
++ fs.rmSync(value, options); throw failure;
++ }), error => error === failure);
++ assert.ok(!fs.existsSync(root));
++ }],
++ ];
++}
++
++function buildTests() {
++ const allowed = readAllowedExtensions();
++ return [
++ ['the loader still declares several instinct extensions', () => {
++ assert.ok(allowed.length >= 3, `expected several extensions, got ${allowed}`);
++ }],
++ ...allowed.map(ext => [`status counts ${ext} - the loader accepts it`, shellTest(() => {
++ assert.strictEqual(runStatus([`one${ext}`]), 1);
++ })]),
++ ['status does not recurse - the loader does not', shellTest(() => {
++ assert.strictEqual(runStatus(['a.md', 'nested/deep.yaml']), 1);
++ })],
++ ['status skips directories', shellTest(() => {
++ assert.strictEqual(runStatus([], { setup: value => fs.mkdirSync(path.join(value.instincts, 'directory.md')) }), 0);
++ })],
++ ['status matches case-insensitively', shellTest(() => {
++ assert.strictEqual(runStatus(['a.YAML', 'b.YmL', 'c.MD']), 3);
++ })],
++ ['start-observer.sh parses', shellTest(() => withFixture(fixture => {
++ checkChild(spawnSync(bashBinary, ['--noprofile', '--norc', '-n', toShellPath(observerScript)], {
++ cwd: fixture.root, env: fixture.env, encoding: 'utf8',
++ timeout: childTimeoutMs, maxBuffer: childMaxBuffer, killSignal: 'SIGKILL',
++ }));
++ }))],
++ ['markdown instincts are counted', shellTest(() => {
++ assert.strictEqual(runStatus(['a.md', 'b.md', 'c.md']), 3);
++ })],
++ ['the count matches the loader eligible-file rules', shellTest(() => {
++ assert.strictEqual(runStatus(['a.md', 'b.yaml', 'c.yml', 'd.YAML', 'notes.txt', 'nested/deep.md']), 4);
++ })],
++ ['an empty instincts directory reports 0', shellTest(() => {
++ assert.strictEqual(runStatus([]), 0);
++ })],
++ ['hidden stems count but dot-only extension names have no suffix', shellTest(() => {
++ assert.strictEqual(runStatus(['.note.MD', '.yaml', '.YML', '.md']), 1);
++ })],
++ ['newlines and spaces in one eligible filename count once', shellTest(() => {
++ assert.strictEqual(runStatus(['two\nlines with spaces.MD']), 1);
++ })],
++ ['shell metacharacters in a filename remain inert data', shellTest(() => {
++ assert.strictEqual(runStatus(['$(touch unwanted).md'], { setup: value => {
++ assert.ok(!fs.existsSync(path.join(value.root, 'unwanted')));
++ }, run: (command, args, options) => {
++ const result = spawnSync(command, args, options);
++ assert.ok(!fs.existsSync(path.join(options.cwd, 'unwanted')));
++ return result;
++ } }), 1);
++ })],
++ ['linked regular files count without traversing directory links', shellTest(() => {
++ assert.strictEqual(runStatus(['a.md', 'b.yaml', 'c.yml', 'd.YAML', '.note.MD',
++ '.md', '.yaml', '.YML', 'notes.txt', 'nested/deep.md'], { setup: value => {
++ const outside = path.join(value.root, 'outside');
++ fs.mkdirSync(outside);
++ const target = path.join(outside, 'regular.txt');
++ fs.writeFileSync(target, 'private fixture\n');
++ fs.writeFileSync(path.join(outside, 'deep.md'), 'not top-level\n');
++ fs.mkdirSync(path.join(value.instincts, 'directory.md'));
++ fileLink(target, path.join(value.instincts, 'linked.MD'));
++ fileLink(outside, path.join(value.instincts, 'directory-link.yaml'), 'dir');
++ fileLink(path.join(outside, 'missing'), path.join(value.instincts, 'dangling.yml'));
++ } }), 6);
++ })],
++ ...cleanupTests(),
++ ];
+}
+
+function main() {
+ console.log('\n=== Testing observer status instinct count (#2859) ===\n');
-
- let passed = 0;
- let failed = 0;
- let tests;
-
- // Collecting the cases reads instinct-cli.py and start-observer.sh, so a
- // missing or renamed file has to be reported as a failure rather than crash
- // the process — tests/run-all.js totals the "Passed:"/"Failed:" tokens below.
- try {
- tests = buildTests();
- } catch (error) {
- console.log(' ✗ could not build the test list');
- console.error(` ${error.message}`);
- tests = [];
- failed += 1;
++ let passed = 0; let failed = 0; let skipped = 0; let tests;
++ try { tests = buildTests(); }
++ catch (error) {
++ console.error(` FAIL could not build the test list: ${error.message}`);
++ tests = []; failed += 1;
+ }
-
+ for (const [name, fn] of tests) {
- if (runTest(name, fn)) passed += 1;
- else failed += 1;
++ try { fn(); console.log(` PASS ${name}`); passed += 1; }
++ catch (error) {
++ if (error instanceof SkipTest) {
++ console.log(` SKIP ${name}: ${error.message}`); skipped += 1;
++ } else {
++ console.error(` FAIL ${name}: ${error.message}`); failed += 1;
++ }
++ }
+ }
-
- if (!(bashBinary && pythonCmd)) {
- console.log(' - integration coverage skipped (needs bash + python; set ECC_TEST_BASH/ECC_TEST_PYTHON)');
- }
-
- console.log(`\n Passed: ${passed}`);
- console.log(` Failed: ${failed}`);
- // exitCode, not exit(1): stdout is async when it is a pipe, which is how
- // tests/run-all.js runs this, and process.exit() does not wait for pending
- // writes — it could drop the two lines above, which the aggregator totals.
++ console.log(`\n Passed: ${passed}\n Failed: ${failed}\n Skipped: ${skipped}`);
++ // Let piped summary output drain before the aggregate runner reads it.
+ if (failed > 0) process.exitCode = 1;
+}
+
+main();