Commit Graph

168 Commits

Author SHA1 Message Date
Steve Yegge
b4cb636d92 Switch from hex to Base36 encoding for issue IDs (GH #213)
This change improves information density by using Base36 (0-9, a-z) instead
of hex (0-9, a-f) for hash-based issue IDs. Key benefits:

- Shorter IDs: Can now use 3-char IDs (was 4-char minimum)
- Better scaling: 3 chars good for ~160 issues, 4 chars for ~980 issues
- Case-insensitive: Maintains excellent CLI usability
- Backward compatible: Old hex IDs continue to work

Changes:
- Implemented Base36 encoding with proper truncation (keep LSB)
- Updated adaptive length thresholds (3-8 chars instead of 4-8)
- Fixed collision probability math to match encoding (was calculating
  for base36 but encoding in hex - now both use base36)
- Fixed ID parser bug (use prefixWithHyphen for substring matching)
- Updated all tests and test data patterns

Fixes #213

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-03 12:02:15 -08:00
Steve Yegge
178a43dd5d Add external_ref UNIQUE constraint and validation
- Add migration for UNIQUE index on external_ref column (bd-897a)
- Add validation for duplicate external_ref in batch imports (bd-7315)
- Add query planner test to verify index usage (bd-f9a1)
- Add concurrent import tests for external_ref (bd-3f6a)

The migration detects existing duplicates and fails gracefully.
Batch imports now reject duplicates with clear error messages.
Tests verify the index is actually used by SQLite query planner.

Amp-Thread-ID: https://ampcode.com/threads/T-45ca66ed-3912-46c4-963c-caa7724a9a2f
Co-authored-by: Amp <amp@ampcode.com>
2025-11-02 16:27:42 -08:00
Steve Yegge
248cce454c Document and enforce private memory test isolation pattern (bd-2e80)
- Update newTestStore to default to private memory mode
- Add comprehensive documentation explaining test isolation
- Prevents shared :memory: database interference between tests

Amp-Thread-ID: https://ampcode.com/threads/T-97b59814-3d1a-4f32-bcd2-07a7b81c2b65
Co-authored-by: Amp <amp@ampcode.com>
2025-11-02 16:04:36 -08:00
Steve Yegge
55c722a3e3 Implement external_ref as primary matching key for import updates (bd-1022)
- Add GetIssueByExternalRef() query function to storage interface and implementations
- Update DetectCollisions() to prioritize external_ref matching over ID matching
- Modify upsertIssues() to handle external_ref matches in import logic
- Add index on external_ref column for performance
- Add comprehensive tests for external_ref matching in both collision detection and import
- Enables re-syncing from external systems (Jira, GitHub, Linear) without duplicates
- Preserves local issues (no external_ref) from being overwritten
2025-11-02 15:28:09 -08:00
Steve Yegge
2da7487b69 Refactor: consolidate ID generation and shared helpers (bd-0702, bd-1445)
- Created ids.go with ValidateIssueIDPrefix, GenerateIssueID, EnsureIDs
- Created issues.go with insertIssue/insertIssues helpers
- Created events_helpers.go with recordCreatedEvent/recordCreatedEvents
- Created dirty_helpers.go with markDirty/markDirtyBatch
- Refactored sqlite.go and batch_ops.go to use new helpers
- Removed duplicate code from hash_ids.go

Amp-Thread-ID: https://ampcode.com/threads/T-b1ab5a16-96de-4e4d-b255-3617055a89eb
Co-authored-by: Amp <amp@ampcode.com>
2025-11-02 14:49:27 -08:00
Steve Yegge
1abe4e75ad Add migration inspection tools for AI agents (bd-627d Phase 2)
Implemented:
- bd migrate --inspect --json: Shows migration plan, db state, warnings
- bd info --schema --json: Returns schema details for agents
- Migration invariants: Validates migrations post-execution
- Added ListMigrations() for introspection

Phase 1 (invariants) and Phase 2 (inspection) complete.
Next: Wire up MCP tools in beads-mcp server.

Amp-Thread-ID: https://ampcode.com/threads/T-c4674660-d640-405f-a929-b664e8699a48
Co-authored-by: Amp <amp@ampcode.com>
2025-11-02 14:03:14 -08:00
Steve Yegge
229b92b6a8 Merge branch 'main' of github.com:steveyegge/beads 2025-11-02 12:55:59 -08:00
Steve Yegge
7d6d64d2c1 Refactor: Replace manual transaction handling with withTx() helper
Fixes bd-1b0a

Changes:
- Added withTx() helper in util.go for cleaner transaction handling
- Kept ExecInTransaction() as deprecated wrapper for backward compatibility
- Refactored all manual BEGIN/COMMIT/ROLLBACK blocks to use withTx():
  - events.go: AddComment
  - dirty.go: MarkIssuesDirty, ClearDirtyIssuesByID
  - labels.go: executeLabelOperation
  - dependencies.go: AddDependency, RemoveDependency
  - compact.go: ApplyCompaction

All tests pass.

Amp-Thread-ID: https://ampcode.com/threads/T-dfacc972-f6c8-4bb3-8997-faa079b5d070
Co-authored-by: Amp <amp@ampcode.com>
2025-11-02 12:55:47 -08:00
Steve Yegge
a126debb99 bd-b245: Add migration registry and simplify New() 2025-11-02 12:40:55 -08:00
David Laing
50a324db85 Fix #202: Add dependency_type to bd show --json output (#203)
The JSON output from bd show now includes the dependency_type field
for both dependencies and dependents, enabling programmatic
differentiation between dependency types (blocks, related,
parent-child, discovered-from).

Implementation approach:
- Added IssueWithDependencyMetadata type with embedded Issue and
  DependencyType field
- Extended GetDependenciesWithMetadata and GetDependentsWithMetadata
  to include dependency type from SQL JOIN
- Made GetDependencies and GetDependents wrap the WithMetadata
  methods for backward compatibility
- Added scanIssuesWithDependencyType helper to handle scanning with
  dependency type field
- Updated bd show --json to use WithMetadata methods

Tests added:
- TestGetDependenciesWithMetadata - basic functionality
- TestGetDependentsWithMetadata - dependent retrieval
- TestGetDependenciesWithMetadataEmpty - edge case handling
- TestGetDependenciesWithMetadataMultipleTypes - multiple types

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Happy <yesreply@happy.engineering>
2025-11-02 08:40:10 -08:00
Steve Yegge
2b086951c4 fix: Address all errcheck and misspell linter errors 2025-11-01 23:56:03 -07:00
Steve Yegge
c399d177a7 Add comprehensive tests for migrations.go and batch_ops.go (bd-3b7f)
- migrations_test.go: Tests all 10 migration functions
- batch_ops_test.go: Tests batch operations and bulk helpers
- All tests passing
- Completes bd-3b7f and sqlite refactoring epic bd-fc2d

Amp-Thread-ID: https://ampcode.com/threads/T-80ad18be-cff5-46c5-9540-47b55b92b4eb
Co-authored-by: Amp <amp@ampcode.com>
2025-11-01 23:25:44 -07:00
Steve Yegge
1849ffe17a test: add comprehensive Comments API tests (bd-d68f)
- Test AddIssueComment basic functionality
- Test GetIssueComments retrieval and ordering
- Test edge cases (empty, nonexistent issues)
- Test dirty flag marking
- Test comment isolation across issues

Improves sqlite package coverage: 69.1% → 70.6%
2025-11-01 22:53:38 -07:00
Steve Yegge
d86f359e63 fix: DetectCycles SQL bug and add comprehensive tests
- Fix SQL query bug preventing cycle detection (bd-9f20)
  - Allow revisiting start node to complete cycle
  - Remove duplicate start_id concatenation in final SELECT
- Add cycle_detection_test.go with comprehensive test coverage (bd-cdf7)
  - Simple 2-node cycles
  - Complex multi-node cycles (4-node, 10-node)
  - Self-loops
  - Multiple independent cycles
  - Acyclic graphs (diamond, chain)
  - Empty graph and single node edge cases
  - Mixed dependency types

Improves sqlite package coverage: 68.2% → 69.1%
2025-11-01 22:51:58 -07:00
Steve Yegge
e9bb1ac121 test: add sqlite collision and delete test coverage
- Add collision_test.go: comprehensive ID collision handling tests
- Add delete_test.go: test soft delete, cascade, and edge cases
- Improves sqlite package coverage from 57.8% to 68.2%

Amp-Thread-ID: https://ampcode.com/threads/T-f4a96cad-a2a4-4f6f-af47-cd56700429f7
Co-authored-by: Amp <amp@ampcode.com>
2025-11-01 22:47:07 -07:00
Nikolai Prokoschenko
c65cfa1ebd Add dependency and dependent counts to bd list JSON output (#198)
When using `bd list --json`, each issue now includes:
- `dependency_count`: Number of issues this issue depends on
- `dependent_count`: Number of issues that depend on this issue

This provides quick access to dependency relationship counts without
needing to fetch full dependency lists or run multiple bd show commands.

Performance:
- Uses single bulk query (GetDependencyCounts) instead of N individual queries
- Overhead: ~26% for 500 issues (24ms vs 19ms baseline)
- Avoids N+1 query problem that would have caused 2.2x slowdown

Implementation:
- Added GetDependencyCounts() to Storage interface for bulk counting
- Efficient SQLite query using UNION ALL + GROUP BY
- Memory storage implementation for testing
- Moved IssueWithCounts to types package to avoid duplication
- Both RPC and direct modes use optimized bulk query

Tests:
- Added comprehensive tests for GetDependencyCounts
- Tests cover: normal operation, empty list, nonexistent IDs
- All existing tests continue to pass

Backwards compatible: JSON structure is additive, all original fields preserved.

Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-01 19:59:15 -07:00
Steve Yegge
b5db80c412 Refactor sqlite.go: Extract hash IDs, batch ops, validators (bd-90a5, bd-c796, bd-d9e0)
- Extract hash ID generation to hash_ids.go (bd-90a5)
  - generateHashID, getNextChildNumber, GetNextChildID
  - Reduced sqlite.go from 1880 to 1799 lines

- Extract batch operations to batch_ops.go (bd-c796)
  - validateBatchIssues, generateBatchIDs, bulkInsertIssues
  - bulkRecordEvents, bulkMarkDirty, CreateIssues
  - Reduced sqlite.go from 1799 to 1511 lines

- Extract validation functions to validators.go (bd-d9e0)
  - validatePriority, validateStatus, validateIssueType
  - validateTitle, validateEstimatedMinutes, validateFieldUpdate
  - Reduced sqlite.go from 1511 to 1447 lines

- Add comprehensive validator tests (bd-3b7f)
  - validators_test.go with full coverage

Total reduction: 2298 → 1447 lines (851 lines extracted, 37% reduction)

Part of epic bd-fc2d to modularize sqlite.go
All tests pass

Amp-Thread-ID: https://ampcode.com/threads/T-09c4383b-bc5c-455e-be24-02b4f9df7d78
Co-authored-by: Amp <amp@ampcode.com>
2025-11-01 19:55:48 -07:00
Steve Yegge
a4b4778ced test: improve coverage for importer and sqlite utils
- Fix TestImportIssues_Update by adding timestamps to test issue
- Add comprehensive tests for sqlite utility functions (IsUniqueConstraintError, QueryContext, BeginTx, ExecInTransaction)
- Coverage improvements: sqlite util.go 0% -> 95%, sqlite package 56.4% -> 57.1%

Amp-Thread-ID: https://ampcode.com/threads/T-17e6a3e4-f881-4f53-b670-bdd796d58f68
Co-authored-by: Amp <amp@ampcode.com>
2025-11-01 11:35:31 -07:00
Steve Yegge
cc7918daf4 Implement bd stale command (bd-c01f, closes #184)
- Add bd stale command to find abandoned/forgotten issues
- Support --days (default 30), --status, --limit, --json flags
- Implement GetStaleIssues in SQLite and Memory storage
- Add full RPC/daemon support
- Comprehensive test suite (6 tests, all passing)
- Update AGENTS.md documentation

Resolves GitHub issue #184

Amp-Thread-ID: https://ampcode.com/threads/T-f021ddb8-54e3-41bf-ba7a-071749663c1d
Co-authored-by: Amp <amp@ampcode.com>
2025-10-31 23:03:56 -07:00
Steve Yegge
0b852f52d9 Remove obsolete renumber and stale commands, fix test
- Remove renumber.go: Hash IDs eliminated need for ID compaction
- Remove stale.go: Executor/heartbeat tables were never implemented
- Fix TestListCommand: duplicate dependency constraint violation
- Update comments removing references to removed commands

Amp-Thread-ID: https://ampcode.com/threads/T-3dcd8681-c7d3-4fe1-9750-b38279b56cdb
Co-authored-by: Amp <amp@ampcode.com>
2025-10-31 21:27:33 -07:00
Steve Yegge
39d5608497 Merge branch 'main' of github.com:steveyegge/beads
# Conflicts:
#	.beads/beads.jsonl
2025-10-31 15:12:08 -07:00
Steve Yegge
ddab26315f Remove dead code found by deadcode analyzer
- Removed 5 unreachable functions (~200 LOC)
- computeIssueContentHash, shouldSkipExport from autoflush.go
- addDependencyUnchecked, removeDependencyIfExists from dependencies.go
- isUniqueConstraintError alias from util.go
- All tests still pass
- Closes bd-7c5915ae
2025-10-31 15:12:01 -07:00
Steve Yegge
aa567f6b9a feat: add Mermaid.js format for dependency tree visualization (#191)
Adds `bd dep tree --format mermaid` to export dependency trees as Mermaid.js flowcharts.

Features:
- Status indicators: ☐ open, ◧ in_progress, ⚠ blocked, ☑ closed
- Theme-agnostic design
- Works with --reverse flag
- Comprehensive unit tests following TDD

Co-authored-by: David Laing <david@davidlaing.com>
2025-10-31 15:11:29 -07:00
Steve Yegge
d5488cb97f Remove collision-era language from docs and code
- Updated FAQ.md, ADVANCED.md, TROUBLESHOOTING.md to explain hash IDs eliminate collisions
- Removed --resolve-collisions references from all documentation and examples
- Renamed handleCollisions() to detectUpdates() to reflect update semantics
- Updated test names: TestAutoImportWithCollision → TestAutoImportWithUpdate
- Clarified: with hash IDs, same-ID = update operation, not collision

Closes: bd-50a7, bd-b84f, bd-bda8, bd-650c, bd-3ef2, bd-c083, bd-85a6
2025-10-31 14:24:50 -07:00
Steve Yegge
64fe51d6bb Remove obsolete collision remapping code and tests
- Deleted collision remapping tests (obsolete with hash IDs bd-8e05)
- Simplified collision.go from 704 to 138 lines
- Removed RemapCollisions, ScoreCollisions, and reference update code
- Removed issue_counters table dependencies (bd-807b)
- Added COLLISION_MATH.md documentation
- Fixed RenameCounterPrefix and ResetCounter to be no-ops
- Closed bd-a58f, bd-3d65, bd-807b

Hash-based IDs make collision remapping unnecessary since collisions
are extremely rare (same ID = same content).

Amp-Thread-ID: https://ampcode.com/threads/T-cbb0f111-6a95-4598-b03e-c137112f9875
Co-authored-by: Amp <amp@ampcode.com>
2025-10-31 00:19:42 -07:00
Steve Yegge
5d137ffeeb Remove sequential ID generation and SyncAllCounters (bd-c7af, bd-8e05, bd-4c74)
- Removed SyncAllCounters() and all call sites (already no-op with hash IDs)
- Removed AllocateNextID() and getNextIDForPrefix() - sequential ID generation
- Removed collision remapping logic in internal/storage/sqlite/collision.go
- Removed rename collision handling in internal/importer/importer.go
- Removed branch-merge example (collision resolution no longer needed)
- Updated EXTENDING.md to remove counter sync examples

These were all deprecated code paths for sequential IDs that are obsolete
with hash-based IDs. Hash ID collisions are handled by extending the hash,
not by remapping to new sequential IDs.
2025-10-30 22:24:42 -07:00
Steve Yegge
e3afecca37 Remove sequential ID code path (bd-aa744b)
- Removed nextSequentialID() and getIDMode() functions
- Removed issue_counters table from schema
- Made SyncAllCounters() a no-op for backward compatibility
- Simplified ID generation to hash-only (adaptive length)
- Removed id_mode config setting
- Removed sequential ID tests and migration code
- Updated CONFIG.md and AGENTS.md to remove sequential ID references

Follow-up bd-2a70 will remove obsolete test files and renumber command.
2025-10-30 21:51:39 -07:00
Steve Yegge
76d3403d0a Implement adaptive ID length scaling (bd-ea2a13)
- Start with 4-char IDs for small databases (0-500 issues)
- Scale to 5-char at 500-1500 issues, 6-char at 1500+
- Configurable via max_collision_prob, min/max_hash_length
- Birthday paradox math ensures collision probability stays under threshold
- Comprehensive tests and documentation
- Collision calculator tool for analysis

Also filed bd-aa744b to remove sequential ID code path.
2025-10-30 21:40:52 -07:00
Steve Yegge
cd7bdb301d Generate 6-char hash IDs with progressive 7/8-char fallback on collision (bd-7c87cf24)
- Changed generateHashID to start with 6 chars (3 bytes), expand to 7/8 on collision
- Updated both CreateIssue and CreateIssues (batch) to use progressive length fallback
- Updated tests to accept 9-11 char IDs (bd- + 6-8 hex chars)
- All new issues now generate with shorter, more readable IDs
- Existing 8-char IDs preserved (no migration needed)

Amp-Thread-ID: https://ampcode.com/threads/T-8a6058af-9f42-4bff-be02-8c8bce41eeb5
Co-authored-by: Amp <amp@ampcode.com>
2025-10-30 18:16:24 -07:00
Steve Yegge
1fbfe58ba7 Make hash IDs opt-in via id_mode config (bd-5404)
- Add id_mode config (sequential|hash), defaults to sequential
- Update CreateIssue/CreateIssues to check id_mode and generate appropriate IDs
- Implement lazy counter initialization from existing issues
- Update migrate --to-hash-ids to set id_mode=hash after migration
- Fix hash ID tests to set id_mode=hash
- Fix renumber test to use explicit IDs
- All 183 test packages pass

This makes hash IDs backward-compatible opt-in rather than forced default.
2025-10-30 16:50:38 -07:00
Steve Yegge
3ed2aa07cb Implement hierarchical child ID generation (bd-171)
- Add GetNextChildID to storage interface for generating child IDs
- Implement in SQLiteStorage with atomic counter using child_counters table
- Implement in MemoryStorage with in-memory counter
- Add --parent flag to bd create command
- Support hierarchical IDs (bd-a3f8e9.1, bd-a3f8e9.1.5) in CreateIssue
- Validate parent exists when creating hierarchical issues
- Enforce max depth of 3 levels
- Update ID validation to accept hierarchical IDs with dots
- Add comprehensive tests for child ID generation
- Manual testing confirms: sequential children, nested hierarchies, depth enforcement
2025-10-30 14:42:08 -07:00
Steve Yegge
2276d5e428 Implement hash ID generation (bd-168)
- Add generateHashID function with SHA256-based IDs
- Update CreateIssue and CreateIssues to use hash IDs
- Add collision detection with nonce retry logic
- Add comprehensive tests for hash ID generation
- Hash IDs format: prefix-<8 hex chars> (e.g., bd-a3f8e9a2)

Amp-Thread-ID: https://ampcode.com/threads/T-48f75379-427f-4d72-bbc2-42bad0d0d62d
Co-authored-by: Amp <amp@ampcode.com>
2025-10-30 14:16:35 -07:00
Steve Yegge
6091e87cd1 Revert "Implement hash ID generation (bd-168)"
This reverts commit 2480316248.
2025-10-30 14:16:24 -07:00
Steve Yegge
2480316248 Implement hash ID generation (bd-168)
- Add generateHashID function with SHA256-based IDs
- Update CreateIssue and CreateIssues to use hash IDs
- Add collision detection with nonce retry logic
- Add comprehensive tests for hash ID generation
- Hash IDs format: prefix-<8 hex chars> (e.g., bd-a3f8e9a2)

Amp-Thread-ID: https://ampcode.com/threads/T-48f75379-427f-4d72-bbc2-42bad0d0d62d
Co-authored-by: Amp <amp@ampcode.com>
2025-10-30 14:12:29 -07:00
Steve Yegge
2b05ec65f8 Implement 6-char progressive hash IDs (bd-166, bd-167)
- Hash ID generation now returns full 64-char SHA256
- Progressive collision handling: 6→7→8 chars on INSERT failure
- Added child_counters table for hierarchical IDs
- Updated all docs to reflect 6-char design
- Collision math: 97% of 1K issues stay at 6 chars

Next: Implement progressive retry logic in CreateIssue (bd-168)
Amp-Thread-ID: https://ampcode.com/threads/T-9931c1b7-c989-47a1-8e6a-a04469bd937d
Co-authored-by: Amp <amp@ampcode.com>
2025-10-30 14:04:03 -07:00
Steve Yegge
c34b93fa1a Fix bd-160: Implement JSONL integrity validation and prevent export deduplication data loss
## Problem
Export deduplication feature broke when JSONL and export_hashes diverged
(e.g., after git pull/reset). This caused exports to skip issues that
weren't actually in the file, leading to silent data loss.

## Solution
1. JSONL integrity validation before every export
   - Store JSONL file hash after export
   - Validate hash before export, clear export_hashes if mismatch
   - Automatically recovers from git operations changing JSONL

2. Clear export_hashes on all imports
   - Prevents stale hashes from causing future export failures
   - Import operations invalidate export_hashes state

3. Add Storage interface methods:
   - GetJSONLFileHash/SetJSONLFileHash for integrity tracking
   - ClearAllExportHashes for recovery

## Tests Added
- TestJSONLIntegrityValidation: Unit tests for validation logic
- TestImportClearsExportHashes: Verifies imports clear hashes
- TestExportIntegrityAfterJSONLTruncation: Simulates git reset (would have caught bd-160)
- TestExportIntegrityAfterJSONLDeletion: Tests recovery from file deletion
- TestMultipleExportsStayConsistent: Tests repeated export integrity

## Follow-up
Created bd-179 epic for remaining integration test gaps (multi-repo sync,
daemon auto-sync, corruption recovery tests).

Closes bd-160
2025-10-29 21:57:15 -07:00
Steve Yegge
84fd068e3f Add TestSymmetricCollision unit test for deterministic collision resolution 2025-10-29 17:49:46 -07:00
Steve Yegge
55f803a7c9 Fix multi-round convergence for N-way collisions (bd-108)
- Add AllocateNextID() public method to SQLiteStorage for cross-package ID allocation
- Enhance handleRename() to handle collision during rename with retry logic
- Fix stale ID map issue by removing deleted IDs from dbByID after rename
- Update edge case tests to use convergence rounds consistently
- All N-way collision tests now pass (TestFiveCloneCollision, TestEdgeCases)
2025-10-29 11:08:28 -07:00
Steve Yegge
ebb425388c bd-109: Add retry logic and race condition handling for N-way collisions
- Added ExecInTransaction helper for atomic database operations
- Added IsUniqueConstraintError to detect UNIQUE constraint violations
- Wrapped RemapCollisions with retry logic (3 attempts with counter sync)
- Enhanced handleRename to detect race conditions where target ID exists
- Added defensive checks for when old ID has been deleted by another clone

Progress: Improves N-way collision handling, though full solution requires
more work (tracked in bd-108). Tests now reach later convergence rounds
before hitting complex collision scenarios.

Amp-Thread-ID: https://ampcode.com/threads/T-2b850a80-f8bd-4e38-b661-e33d1cfa7281
Co-authored-by: Amp <amp@ampcode.com>
2025-10-29 10:45:25 -07:00
Steve Yegge
ff02615f61 Implement content-first idempotent import (bd-98)
- Refactored upsertIssues to match by content hash first, then by ID
- Added buildHashMap, buildIDMap, and handleRename helper functions
- Import now detects and handles renames (same content, different ID)
- Importing same data multiple times is idempotent (reports Unchanged)
- Exported BuildReplacementCache and ReplaceIDReferencesWithCache for reuse
- All 30+ existing import tests pass
- Improved convergence for N-way collision scenarios

Changes:
- internal/importer/importer.go: Content-first matching in upsertIssues
- internal/storage/sqlite/collision.go: Exported helper functions
- internal/storage/sqlite/collision_test.go: Updated function names

Amp-Thread-ID: https://ampcode.com/threads/T-3df96ad8-7c0e-4190-87b5-6d5327718f0a
Co-authored-by: Amp <amp@ampcode.com>
2025-10-28 20:40:36 -07:00
Steve Yegge
b0d28bbdbd Remove spurious collision-related code after ultrathink review
After 2 weeks of collision/stale-data fixes, reviewed all changes to identify
spurious code that is no longer needed after content-hash resolution was implemented.

**Removed:**
1. countReferences() function from collision.go (lines 274-328)
   - Was used for reference-count based collision scoring
   - Completely unused after switching to content-hash based resolution (commit 2e87329)
   - Still exists in duplicates.go for deduplication (different use case)

2. ReferenceScore field from CollisionDetail struct
   - Marked as DEPRECATED but never removed
   - No longer used by ScoreCollisions() which now uses content hashing

3. TestCountReferences and TestCountReferencesWordBoundary tests
   - Tested the now-deleted countReferences() function
   - No longer relevant

**Fixed:**
- Updated CheckpointWAL comments to remove misleading "staleness detection" claim
  - Staleness detection uses metadata (last_import_time), NOT file mtime
  - CheckpointWAL is still valuable for data persistence and WAL size reduction
  - Comments now accurately reflect actual benefits

**Verified:**
- All tests pass (internal/storage/sqlite)
- Content-hash collision resolution still works correctly
- No behavioral changes, just cleanup

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-28 20:07:01 -07:00
Steve Yegge
9644d61de2 Make DetectCollisions read-only (bd-96)
- Add RenameDetail type to track content matches with different IDs
- Remove deletion logic from DetectCollisions (now read-only)
- Create ApplyCollisionResolution to handle all modifications
- Update importer.go to use two-phase approach (detect then apply)
- Fix dependency preservation in RemapCollisions
  - Collect all dependencies before CASCADE DELETE
  - Recreate with updated IDs after remapping
- Add tests: TestDetectCollisionsReadOnly, TestApplyCollisionResolution
- Update collision tests for content-hash scoring behavior
- Create bd-100 to track fixing autoimport tests
2025-10-28 19:16:51 -07:00
Steve Yegge
d9eb273e15 Complete bd-95: Add content-addressable identity (ContentHash field) 2025-10-28 18:57:16 -07:00
Steve Yegge
ceb1b922a9 bd sync: 2025-10-28 17:19:28 2025-10-28 17:19:28 -07:00
Steve Yegge
2e87329cf8 WIP: Implement content-hash based collision resolution (bd-89)
- Replace timestamp-based collision scoring with deterministic content hashing
- Add hashIssueContent() using SHA-256 of all substantive fields
- Modify ScoreCollisions to compare hashes and set RemapIncoming flag
- Update RemapCollisions to handle both directions (remap incoming OR existing)
- Add CollisionDetail.RemapIncoming field to control which version gets remapped
- Add unit tests for hash function and deterministic collision resolution

Status: Hash-based resolution works correctly, but TestTwoCloneCollision still
fails due to missing rename detection. After Clone B resolves collision,
Clone A needs to recognize its issue was remapped to a different ID.

Next: Add content-based rename detection during import to prevent
re-resolving already-resolved collisions.

Progress on bd-86.

Amp-Thread-ID: https://ampcode.com/threads/T-b19b49e8-b52a-463d-b052-8a526a500260
Co-authored-by: Amp <amp@ampcode.com>
2025-10-28 17:11:40 -07:00
Steve Yegge
d47378cfbc Remove skipped tests and unreachable RPC methods (bd-212, bd-213)
bd-212: Delete 3 permanently skipped test functions (~150 LOC)
- TestImportDependencyUpdates (import_collision_test.go)
- TestImportChainDependencies (import_collision_test.go)
- TestUpdateDependencyReferences (collision_test.go)

bd-213: Remove 4 unreachable RPC methods (~80 LOC)
- Server.GetLastImportTime
- Server.SetLastImportTime
- Server.findJSONLPath
- Client.Import

All tests pass. Phase 1 dead code cleanup continues.
2025-10-27 20:52:52 -07:00
Steve Yegge
298d559407 Remove unreachable utility functions (bd-224, bd-214)
- Remove duplicate computeIssueContentHash from sqlite/hash.go
- Remove FileUsed() from internal/config/config.go
- Remove verifyIssueOpen() test helper from git_sync_test.go
- Remove unimplemented SummarizeTier2 and all tier2 infrastructure from haiku.go

Removes ~120 LOC of dead code identified by deadcode analyzer.

Amp-Thread-ID: https://ampcode.com/threads/T-5f150c35-8d67-4dae-bb92-a7b5887d649d
Co-authored-by: Amp <amp@ampcode.com>
2025-10-27 20:45:59 -07:00
Steve Yegge
db1458bfed Fix bd-206: Handle status transitions and closed_at constraint
- Updated manageClosedAt to handle both string and types.Status type assertions
- Added equalTime function for comparing timestamps in import change detection
- Added tests for open→closed and closed→open transitions
- Added comment clarifying closed_at is managed automatically

The bug occurred when UpdateIssue received types.Status instead of string,
causing manageClosedAt to skip setting closed_at when status changed to closed.

Amp-Thread-ID: https://ampcode.com/threads/T-ee774f6d-3b90-4311-976d-60c8dd8fe677
Co-authored-by: Amp <amp@ampcode.com>
2025-10-27 19:14:46 -07:00
Steve Yegge
adfe177dba Fix bd-132: Implement daemon auto-import after git pull
- Created internal/importer package with all import logic
- Moved import phases from cmd/bd to internal/importer
- Implemented real importFunc in daemon's checkAndAutoImportIfStale()
- Added single-flight concurrency guard to prevent parallel imports
- Added fast mtime check to avoid unnecessary file reads (99% of requests <0.1ms)
- Fixed import options: RenameOnImport=true instead of SkipPrefixValidation
- Added export trigger after ID remapping to prevent collision loops
- Fixed memory storage interface: added GetDirtyIssueHash, GetExportHash, SetExportHash
- Updated GetDependencyTree signature for reverse parameter

Performance:
- Mtime check: ~0.01ms per request
- Import when needed: ~10-100ms (rare, only after git pull)
- Throughput maintained: 4300+ issues/sec
- No duplicate work with single-flight guard

Fixes critical data corruption bug where daemon served stale data after
git pull, causing fresh JSONL changes to be overwritten.

Amp-Thread-ID: https://ampcode.com/threads/T-71224a2d-b2d7-4173-b21e-449b64f9dd71
Co-authored-by: Amp <amp@ampcode.com>
2025-10-27 16:29:12 -07:00
Steve Yegge
49dac2b767 Fix test failures: add missing issue_prefix config and use valid bd- prefixes
- Add SetConfig('issue_prefix', 'bd') to collision tests (bd-166)
- Update test cases to use 'bd-' prefix instead of invalid custom IDs (bd-177)
- Fixes 5 test failures in TestDetectCollisions, TestScoreCollisions, TestRemapCollisions, TestCreateIssues

All tests now pass.

Amp-Thread-ID: https://ampcode.com/threads/T-b2413b0e-2720-45b1-9b3d-acaa7d4cf9b4
Co-authored-by: Amp <amp@ampcode.com>
2025-10-27 13:11:45 -07:00