Commit Graph

228 Commits

  • fix: make saveAliases atomic on Unix by skipping unnecessary unlink before rename
    On Unix/macOS, rename(2) atomically replaces the destination file.
    The previous code ran unlinkSync before renameSync on all platforms,
    creating an unnecessary non-atomic window where a crash could lose
    data. Now the delete-before-rename is gated behind process.platform
    === 'win32', where rename cannot overwrite an existing file.
  • fix: sync Cursor suggest-compact.js with corrected hooks version
    The .cursor copy had diverged from scripts/hooks/suggest-compact.js:
    - Fixed interval calculation: count % 25 → (count - threshold) % 25
      so suggestions fire relative to the configured threshold
    - Added upper bound clamp (<=1000000) to prevent counter corruption
      from large values converting to scientific notation strings
    - Removed unreliable String(process.ppid) fallback for session ID
  • fix: correct box() off-by-one width calculation in skill-create-output
    The box() helper produced lines that were width+1 characters instead of
    the requested width. Adjusted all three formulas (top border, middle
    content, bottom border) by -1 each. Added 4 tests verifying box width
    accuracy across instincts(), analysisResults(), and nextSteps() output.
  • fix: header subtitle width mismatch in skill-create-output; add 9 tests (Round 34)
    - Fix subtitle padding 55→59 so line 94 matches 64-char border width
    - Add 4 header width alignment tests (skill-create-output)
    - Add 3 getExecCommand non-string args tests (package-manager)
    - Add 2 detectFromPackageJson non-string type tests (package-manager)
  • test: add 10 tests for birthtime fallback, stdin error, alias rollback (Round 33)
    Cover createdTime/birthtime fallback in session-manager, readStdinJson
    error event settled-flag guard in utils, renameAlias rollback on naming
    conflict in session-aliases, and saveAliases backup preservation on
    serialization failure. Total: 713 tests.
  • test: add 17 tests for validators, hooks, and edge cases (Round 32)
    Coverage improvements:
    - validate-agents: empty frontmatter block, no-content frontmatter,
      partial frontmatter, mixed valid/invalid agents
    - validate-rules: directory with .md name (stat.isFile check),
      deeply nested subdirectory rules
    - validate-commands: 3-agent workflow chain, broken middle agent
    - post-edit-typecheck: spaces in paths, shell metacharacters, .tsx
    - check-console-log: git failure passthrough, large stdin
    - post-edit-console-warn: console.error only, null tool_input
    - session-end: empty transcript, whitespace-only transcript
    
    Total tests: 686 → 703
  • fix: reject flags passed as package manager names in setup-package-manager CLI
    When --global or --project was followed by another flag (e.g., --global --project),
    the flag was treated as a package manager name. Added pmName.startsWith('-') check
    to both handlers. Added 20 tests across 4 test files covering argument validation,
    ensureDir error propagation, runCommand stderr handling, and saveAliases failure paths.
  • fix: use local-time Date constructor in session-manager to prevent timezone day shift
    new Date('YYYY-MM-DD') creates UTC midnight, which in negative UTC offset
    timezones (e.g., Hawaii) causes getDate() to return the previous day.
    Replaced with new Date(year, month - 1, day) for correct local-time behavior.
    
    Added 15 tests: session-manager datetime verification and edge cases (7),
    package-manager getCommandPattern special characters (4), and
    validators model/skill-reference validation (4). Tests: 651 → 666.
  • fix: add cwd to prettier hook, consistent process.exit(0), and stdout pass-through
    - post-edit-format.js: add cwd based on file directory so npx resolves
      correct local prettier binary
    - post-edit-typecheck.js, post-edit-format.js: replace console.log(data)
      with process.stdout.write(data) to avoid trailing newline corruption
    - Add process.exit(0) to 4 hooks for consistent termination
      (check-console-log, post-edit-console-warn, post-edit-format,
      post-edit-typecheck)
    - run-all.js: switch from execSync to spawnSync so stderr is visible
      on the success path (hook warnings were silently discarded)
    - Add 21 tests: cwd verification, process.exit(0) checks, exact
      stdout pass-through, extension edge cases, exclusion pattern
      matching, threshold boundary values (630 → 651)
  • test: add 22 tests for readStdinJson, evaluate-session config, and suggest-compact hook
    - utils.test.js: 5 tests for readStdinJson maxSize truncation, whitespace-only stdin, trailing whitespace, and BOM prefix handling
    - evaluate-session.test.js: 4 tests for config file parsing, assistant-only transcripts, malformed JSON lines, and empty stdin
    - suggest-compact.test.js: 13 new tests covering counter file creation/increment, threshold suggestion, interval suggestion, env var handling, corrupted/empty counter files, and session isolation
  • test: add 15 tests for session-manager and session-aliases edge cases
    Cover 30-day month validation (Sep/Nov 31 rejection), getSessionStats
    path heuristic with multiline content, combined date+search+pagination
    in getAllSessions, ambiguous prefix matching in getSessionById, unclosed
    code fence in parseSessionMetadata, empty checklist item behavior,
    reserved name case sensitivity (LIST/Help/Set), negative limit in
    listAliases, and undefined title in setAlias.
  • fix: exact byte pass-through in post-edit-console-warn, add 7 tests
    Replace console.log(data) with process.stdout.write(data) in both
    pass-through paths to prevent appending a trailing newline that
    corrupts the hook output. Add 7 tests covering exact byte fidelity,
    malformed JSON, missing file_path, non-existent files, exclusion
    patterns in check-console-log, non-git repo handling, and empty stdin.
  • fix: consistent periodic interval spacing in suggest-compact, add 10 tests
    - suggest-compact.js: count % 25 → (count - threshold) % 25 for consistent
      spacing regardless of threshold value
    - Update existing periodic interval test to match corrected behavior
    - 10 new tests: interval fix regression (non-25-divisible threshold, false
      suggestion prevention), corrupted counter file, 1M boundary, malformed
      JSON pass-through, non-TS extension pass-through, empty sessions dir,
      blank template skip
  • fix: nullish coalescing in evaluate-session config, narrow pre-compact glob, add 11 tests
    - evaluate-session.js: || 10 → ?? 10 for min_session_length (0 is valid)
    - pre-compact.js: *.tmp → *-session.tmp to match only session files
    - 11 new tests: config loading (min=0, null, custom path, invalid JSON),
      session-end update path (timestamp, template replace, preserve content),
      pre-compact glob specificity, extractSessionSummary edge cases
  • fix: reject empty/invalid array commands in hooks validator, add 19 tests
    validate-hooks.js: Empty arrays [] and arrays with non-string elements
    (e.g., [123, null]) passed command validation due to JS truthiness of
    empty arrays (![] === false). Added explicit length and element type
    checks.
    
    19 new tests covering: non-array event type values, null/string matcher
    entries, string/number top-level data, empty string/array commands,
    non-string array elements, non-string type field, non-number timeout,
    timeout boundary (0), unwrapped hooks format, legacy format error paths,
    empty agent directory, whitespace-only command files, valid skill refs,
    mixed valid/invalid rules and skills.
  • fix: sanitize getExecCommand args, escape regex in getCommandPattern, clean up readStdinJson timeout, add 10 tests
    Validate args parameter in getExecCommand() against SAFE_ARGS_REGEX to
    prevent command injection when returned string is passed to a shell.
    Escape regex metacharacters in getCommandPattern() generic action branch
    to prevent malformed patterns and unintended matching. Clean up stdin
    listeners in readStdinJson() timeout path to prevent process hanging.
  • fix: eliminate command injection in hooks, fix pass-through newline corruption, add 8 tests
    Replace shell: true with npx.cmd on Windows in post-edit-format.js and
    post-edit-typecheck.js to prevent command injection via crafted file paths.
    Replace console.log(data) with process.stdout.write(data) in
    check-console-log.js to avoid appending extra newlines to pass-through data.
  • fix: clamp getAllSessions pagination params, add cleanupAliases success field, add 10 tests
    - session-manager: clamp offset/limit to safe non-negative integers to
      prevent negative offset counting from end and NaN returning empty results
    - session-aliases: add success field to cleanupAliases return value for
      API contract consistency with setAlias/deleteAlias/renameAlias
  • fix: reject whitespace-only command/field values in CI validators, add 10 tests
    validate-hooks.js: whitespace-only command strings now fail validation
    validate-agents.js: whitespace-only model/tools values now fail validation
  • fix: clamp progressBar to prevent RangeError on overflow, add 10 tests
    progressBar() in skill-create-output.js could crash with RangeError when
    percent > 100 because repeat() received a negative count. Fixed by
    clamping filled to [0, width].
    
    New tests:
    - progressBar edge cases: 0%, 100%, and >100% confidence
    - Empty patterns/instincts arrays
    - post-edit-format: null tool_input, missing file_path, prettier failure
    - setup-package-manager: --detect output completeness, current marker
  • fix: clamp suggest-compact counter overflow, add 9 boundary tests
    Counter file could contain huge values (e.g. 999999999999) that pass
    Number.isFinite() but cause unbounded growth. Added range clamp to
    reject values outside [1, 1000000].
    
    New tests cover:
    - Counter overflow reset (huge number, negative number)
    - COMPACT_THRESHOLD zero fallback
    - session-end empty sections (no tools/files omits headers)
    - session-end slice boundaries (10 messages, 20 tools, 30 files)
    - post-edit-console-warn 5-match limit
    - post-edit-console-warn ignores console.warn/error/debug
  • fix: greedy regex in validate-commands captures all refs per line, add 18 tests
    The command cross-reference regex /^.*`\/(...)`.*$/gm only captured the
    LAST command ref per line due to greedy .* consuming earlier refs.
    Replaced with line-by-line processing using non-anchored regex to
    capture ALL command references.
    
    New tests:
    - 4 validate-commands multi-ref-per-line tests (regression)
    - 8 evaluate-session threshold boundary tests (new file)
    - 6 session-aliases edge case tests (cleanup, rename, path matching)
  • fix: sync .opencode/ package version to 1.4.1
    The OpenCode sub-package had stale 1.0.0 versions in package.json,
    index.ts VERSION export, and package-lock.json while the main package
    is at 1.4.1. Updated all three to match.
  • fix: calendar-accurate date validation in parseSessionFilename, add 22 tests
    - Fix parseSessionFilename to reject impossible dates (Feb 31, Apr 31,
      Feb 29 non-leap) using Date constructor month/day roundtrip check
    - Add 6 session-manager tests for calendar date validation edge cases
    - Add 3 session-manager tests for code blocks/special chars in getSessionStats
    - Add 10 package-manager tests for PM-specific command formats (getRunCommand
      and getExecCommand for pnpm, yarn, bun, npm)
    - Add 3 integration tests for session-end transcript parsing (mixed JSONL
      formats, malformed lines, nested user messages)
  • test: add 7 package-manager priority and source detection tests
    - Test valid project-config detection (.claude/package-manager.json)
    - Test priority order: project-config > package.json > lock-file
    - Test package.json > lock-file priority
    - Test default fallback to npm
    - Test setPreferredPackageManager success case
    - Test getCommandPattern for test and build actions
  • fix: box alignment in test runner, update metadata counts, add 18 tests
    - Fix run-all.js box alignment (hardcoded spaces 1 char short, now using dynamic padEnd)
    - Update .opencode/index.ts metadata (12→13 agents, 24→31 commands, 16→37 skills)
    - Add commandExists edge case tests (empty, spaces, path separators, metacharacters)
    - Add findFiles edge case tests (? wildcard, mtime sorting, maxAge filtering)
    - Add ensureDir race condition and return value tests
    - Add runCommand output trimming and failure tests
    - Add pre-compact session annotation and compaction log timestamp tests
    - Add check-console-log invalid JSON handling test
    - Add replaceInFile capture group test
    - Add readStdinJson Promise type check
  • fix: typecheck hook false positives, add 11 session-manager tests
    - Fix post-edit-typecheck.js error filtering: use relative/absolute path
      matching instead of basename, preventing false positives when multiple
      files share the same name (e.g., src/utils.ts vs tests/utils.ts)
    - Add writeSessionContent tests (create, overwrite, invalid path)
    - Add appendSessionContent test (append to existing file)
    - Add deleteSession tests (delete existing, non-existent)
    - Add sessionExists tests (file, non-existent, directory)
    - Add getSessionStats empty content edge case
    - Add post-edit-typecheck stdout passthrough test
    - Total: 391 → 402 tests, all passing
  • fix: include .md files in instinct-cli glob (completes #216)
    The observer agent creates instinct files as .md with YAML frontmatter,
    but load_all_instincts() only globbed *.yaml and *.yml. Add *.md to the
    glob so instinct-cli status discovers all instinct files.
  • fix: add missing ReplaceInFileOptions to utils.d.ts type declaration
    The replaceInFile function in utils.js accepts an optional `options`
    parameter with `{ all?: boolean }` for replacing all occurrences, but
    the .d.ts type declaration was missing this parameter entirely.
  • fix: grepFile global regex lastIndex bug, add 12 tests
    Fix grepFile() silently skipping matches when called with /g flag regex.
    The global flag makes .test() stateful, causing alternating match/miss
    on consecutive matching lines. Strip g flag since per-line testing
    doesn't need global state.
    
    Add first-ever tests for evaluate-session.js (5 tests: short session,
    long session, missing transcript, malformed stdin, env var fallback)
    and suggest-compact.js (5 tests: counter increment, threshold trigger,
    periodic suggestions, below-threshold silence, invalid threshold).
  • chore: add dist, __pycache__, and tasks to .gitignore
    Prevents accidental commits of build output, Python bytecode
    cache, and Claude Code team task files.
  • test: add tsconfig depth limit and cleanupAliases exception tests
    - post-edit-typecheck: verify 25-level-deep directory completes without
      hanging (tests the max depth=20 walk-up guard)
    - cleanupAliases: document behavior when sessionExists callback throws
      (propagates to caller, which is acceptable)
  • fix: instinct-cli glob and evolve --generate (fixes #216, #217)
    - Load both .yaml and .yml files in load_all_instincts() (#216)
      The *.yaml-only glob missed .yml files, causing 'No instincts found'
    - Implement evolve --generate to create skill/command/agent files (#217)
      Previously printed a stub message. Now generates SKILL.md, command .md,
      and agent .md files from the clustering analysis into ~/.claude/homunculus/evolved/
  • test: add coverage for Claude Code JSONL format and assistant tool blocks
    Tests the new transcript parsing from PR #215:
    - entry.message.content format (string and array content)
    - tool_use blocks nested in assistant message content arrays
    - Verifies file paths and tool names extracted from both formats
  • fix: add missing validation in renameAlias, add 6 tests
    renameAlias was missing length (>128), reserved name, and empty string
    validation that setAlias enforced. This inconsistency allowed renaming
    aliases to reserved names like 'list' or 'delete'.
    
    Also adds tests for:
    - renameAlias empty string, reserved name, and length limit
    - validate-skills whitespace-only SKILL.md rejection
    - validate-rules whitespace-only file and recursive subdirectory scan
  • docs(zh-CN): sync Chinese docs with latest upstream changes (#202)
    * docs(zh-CN): sync Chinese docs with latest upstream changes
    
    * docs: improve Chinese translation consistency in go-test.md
    
    * docs(zh-CN): update image paths to use shared assets directory
    
    - Update image references from ./assets/ to ../../assets/
    - Remove zh-CN/assets directory to use shared assets
    
    ---------
    
    Co-authored-by: neo <neo.dowithless@gmail.com>
  • docs(opencode): clarify OpenCode-specific usage (#214)
    * docs(opencode): clarify OpenCode-specific usage
    
    Signed-off-by: Siddhi Khandelwal <siddhi.200727@gmail.com>
    
    * docs(opencode): close bash code fence in CLI example
    
    Signed-off-by: Siddhi Khandelwal <siddhi.200727@gmail.com>
    
    ---------
    
    Signed-off-by: Siddhi Khandelwal <siddhi.200727@gmail.com>
  • fix: Windows compatibility for hook scripts (execFileSync + tmux) (#215)
    * fix: Windows compatibility for hook scripts
    
    - post-edit-format.js: add `shell: process.platform === 'win32'` to
      execFileSync options so npx.cmd is resolved via cmd.exe on Windows
    - post-edit-typecheck.js: same fix for tsc invocation via npx
    - hooks.json: skip tmux-dependent hooks on Windows where tmux is
      unavailable (dev-server blocker and long-running command reminder)
    
    On Windows, execFileSync('npx', ...) without shell:true fails with
    ENOENT because Node.js cannot directly execute .cmd files. These
    hooks silently fail on all Windows installations.
    
    The tmux hooks unconditionally block dev server commands (exit 2) or
    warn about tmux on Windows where tmux is not available.
    
    Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
    
    * fix: parse Claude Code JSONL transcript format correctly
    
    The session-end hook expected user messages at entry.content, but
    Claude Code's actual JSONL format nests them at entry.message.content.
    This caused all session files to be blank templates (0 user messages
    despite 136+ actual entries).
    
    - Check entry.message?.content in addition to entry.content
    - Extract tool_use blocks from assistant message.content arrays
    
    Verified with Claude Code v2.1.41 JSONL transcripts.
    
    Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
    
    ---------
    
    Co-authored-by: ddungan <sckim@mococo.co.kr>
    Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
  • fix: use valid model name in colon-in-values frontmatter test
    The test was using 'claude-sonnet-4-5-20250929' which isn't in VALID_MODELS
    (haiku/sonnet/opus). Use 'sonnet' with a description field containing
    colons to properly test colon handling in frontmatter values.
  • fix: add input validation, date range checks, and security hardening
    - validate-agents.js: reject invalid model names in agent frontmatter
    - package-manager.js: validate script/binary names against shell injection
    - session-manager.js: reject impossible month/day values in filenames
    - utils.js: support options.all for replaceInFile string patterns
    - strategic-compact/SKILL.md: fix hook matcher syntax and script reference
    - install.sh: warn when overwriting existing rule customizations
    - Add 24 new tests covering all validation and edge cases
  • test: add 6 tests for command validation and session content verification
    - validate-commands: creates: line skipping, valid cross-refs, unclosed
      code blocks, valid workflow diagrams
    - session-end: backtick escaping in session files, tools/files in output
  • fix: use execFileSync with input option for Windows-compatible stdin tests
    Windows cmd.exe treats single quotes literally, so `echo '...' | node -e '...'`
    fails. Switched to execFileSync with the `input` option to pipe stdin data
    directly without shell quoting issues.
  • fix: add 7 missing commands to README, remove phantom /security entry
    Added: /python-review, /multi-plan, /multi-execute, /multi-backend,
    /multi-frontend, /multi-workflow, /pm2, /sessions
    Removed: /security (no matching command file; use security-review skill)
    Updated count: 24 → 31 commands
  • test: add regression tests for empty frontmatter field rejection
    Add 2 tests verifying validate-agents correctly rejects agents with
    empty model and empty tools values in YAML frontmatter.