1<!--
2SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
3
4SPDX-License-Identifier: CC0-1.0
5-->
6
7# AGENTS.md
8
9Guidance for AI coding agents working in this repository. Document only reflects what exists in code/docs.
10
11## Project Type
12
13- Language: Go
14- CLI: Cobra executed via charmbracelet/fang
15- Module path: `git.secluded.site/np`
16- Binary name: `np`
17
18## Development Commands (Taskfile)
19
20- Format: `task fmt` (installs and runs gofumpt)
21- Lint: `task lint` (golangci-lint)
22- Static analysis: `task staticcheck`
23- Tests: `task test` (go test -v ./...)
24- Vulnerabilities: `task vuln` (govulncheck)
25- License compliance: `task reuse` (REUSE)
26- Build: `task build` (produces `./np`, injects version via ldflags)
27- Run: `task run -- <flags>` (runs with ldflags)
28- Docs: `task docs` (generates CLI docs via internal/tools/docgen)
29- Pack: `task pack` (UPX compresses `np`)
30- Clean: `task clean` / `task clean-all`
31- Release: `task release` (interactive semver release with gum/svu)
32- Full check: `task` (default runs fmt, lint, staticcheck, test, vuln, reuse)
33
34Single test:
35
36```bash
37go test -v -run TestName ./path/to/package
38```
39
40## Repository Layout
41
42- `main.go`: wires fang.Execute(RootCmd) and sets version from build info
43- `cmd/`: Cobra commands
44 - Root and top-level: `a` (archive), `m` (monitor/TUI stub), `p` (plan printout stub), `r` (resume), `s` (start)
45 - `cmd/g/`: goal command group; `g` (show stub), `g s` (set goal stub with -t/-d)
46 - `cmd/t/`: task command group; `t` (list stub with status filter flag), `t a` (add, supports batch via repeatable -t/-d), `t u` (update, supports batch status updates via repeatable -i/-s)
47- `internal/`:
48 - `db/`: Badger wrapper: options, tx helpers, key builders, path hashing
49 - `goal/`: goal document + store
50 - `task/`: task types + store (status index, deterministic IDs)
51 - `event/`: event types + store + payload builders
52 - `timeutil/`: clocks and UTC helpers
53 - `testutil/`: temp DB and test clocks
54 - `tools/docgen/`: CLI doc generator
55- `docs/`: additional design docs (e.g., `Potential schema.md`)
56
57## CLI Commands (current state)
58
59Commands exist and are registered, but most are stubs that print placeholder output:
60
61```bash
62np s # start session
63np a # archive session
64np p # print plan
65np r # resume session
66np m # monitor TUI (stub)
67np g # goal; np g s -t -d (set), np g u -t -d -r (update)
68np t # tasks; -s status flag for filtering
69np t a # add tasks; supports batch: -t "one" -d "desc" -t "two" -d "desc"
70np t u # update tasks; supports batch status: -i id1 -s status1 -i id2 -s status2
71```
72
73Fang is used for execution/versioning; Cobra provides the command tree.
74
75## Data Layer and Storage
76
77Implemented under `internal/db`, `internal/goal`, `internal/task`, `internal/event`.
78
79- Database options (internal/db/options.go)
80 - Default path: `os.UserConfigDir()/nasin-pali/data`
81 - Retries: `MaxTxnRetries` (default 5) with exponential `ConflictBackoff` (default 10ms)
82 - `SyncWrites` defaults to true when not ReadOnly
83 - No-op logger by default; Badger logger bridged via adapter
84- Database helpers (internal/db/db.go)
85 - `View(ctx, fn)` for read-only; `Update(ctx, fn)` for read-write with retries
86 - Txn helpers: `Get`, `Set`, `Delete`, `GetJSON`, `SetJSON`, `Exists`, `Iterate`, `IncrementUint64`
87 - Errors normalized: `ErrClosed`, `ErrReadOnly`, `ErrKeyNotFound`, `ErrTxnAborted`
88 - Iterator uses prefix scans; `IterateOptions{Prefix, Reverse, PrefetchValues}`
89 - Value log size set to 64 MiB when writable
90- Keyspace builders (internal/db/keys.go)
91 - Meta/schema: `meta/schema_version`
92 - Per-directory: `dir/{dir_hash}/active`, `dir/{dir_hash}/archived/{ts_hex}/{sid}`
93 - Global indexes: `idx/active/{sid}`, `idx/archived/{ts_hex}/{sid}`
94 - Per-session: `s/{sid}/meta`, `s/{sid}/goal`, `s/{sid}/task/{id}`
95 - Status index: `s/{sid}/idx/status/{status}/{id}`
96 - Events: `s/{sid}/meta/evt_seq` (counter), `s/{sid}/evt/{seq_hex}`; prefixes for scans exist
97- Path handling (internal/db/path.go)
98 - `CanonicalizeDir`: abs + EvalSymlinks + Clean + ToSlash; lowercase on Windows
99 - `DirHash`: blake3-256 of canonical path (hex)
100 - `ParentWalk`: yields canonical parents up to root
101- Encoding helpers (internal/db/encoding.go)
102 - Big-endian u64 encode/decode; `Uint64Hex` for zero-padded lower-hex
103
104## Domain Stores
105
106- Goal (internal/goal)
107 - Document: `{title, description, updated_at}` (UTC)
108 - Store: `Get`, `Exists`, `Set`; title is trimmed and required
109 - Transaction-scoped `TxnStore` mirrors operations
110- Task (internal/task)
111 - Status: `pending`, `in_progress`, `completed`, `failed`, `cancelled` with validation helpers
112 - Task: `{id, title, description, status, created_at, updated_at, created_seq}` (UTC)
113 - ID: `GenerateID(sid, title, description)` uses blake3 of normalized (trim + squash spaces) title/description + sid; first 6 hex
114 - Store: `Create`, `Get`, `Update`, `UpdateStatus`, `Delete`, `List`, `ListByStatus`, `Exists`
115 - Maintains status membership keys; sorts by `created_seq`, then `created_at`, then `id`
116- Event (internal/event)
117 - Types: `goal_set`, `goal_updated`, `task_added`, `task_updated`, `task_status_changed`
118 - Record: `{seq, at, type, reason?, cmd, payload}`; `reason` optional; `cmd` required and trimmed
119 - Store: `Append`, `List` (supports `After` and `Limit`), `LatestSequence`
120 - Sequence stored as 8-byte big-endian counter at `s/{sid}/meta/evt_seq`; keys use hex-encoded seq
121 - Payload helpers in `payloads.go` build stable snapshots for events
122
123All stores accept an optional `timeutil.Clock`; default is a UTC system clock. `timeutil.EnsureUTC` normalizes timestamps.
124
125## Testing
126
127- Tests live under `internal/*_test.go` (goal, task, event)
128- Helpers: `testutil.OpenDB(t)` opens a temp Badger DB with cleanup; `testutil.SequenceClock` yields deterministic times
129- Run: `task test` or `go test -v ./...`
130- Example single test pattern: `go test -v -run TestName ./internal/task`
131
132## Doc Generation
133
134- Tool: `internal/tools/docgen` (cobra/doc based)
135- `task docs` runs two invocations: one tree under `docs/cli/`, and a single-file reference `docs/llm-reference.md`
136- Note: the Taskfile passes `-exclude m` but `docgen` has no `-exclude` flag; adjust if this causes failures
137
138## Output Format for LLMs
139
140- Status icons: ☐ pending, ⟳ in progress, ☑ completed, ☒ failed, ⊗ cancelled (only show failed/cancelled in legend when present)
141- Commands that change state should print the full plan immediately (current CLI commands are stubs)
142
143## Conventions
144
145- Formatting: gofumpt (not `go fmt`)
146- Errors and validation follow idiomatic Go patterns visible in stores
147- All source files include SPDX headers; source is AGPL-3.0-or-later; docs/config are CC0-1.0
148
149## Gotchas
150
151- `task docs` may fail due to `-exclude` flag unsupported by docgen
152- `db.Options` sets `SyncWrites=true` by default when not read-only (durability over throughput)
153- Event sequence counter is raw 8-byte big-endian; do not store decimal strings
154- Windows: directory canonicalization lowercases paths; hashes derive from canonicalized form
155
156## Implementation Status
157
158- CLI commands exist but are stubs that print placeholders
159- Data layer (db, goal, task, event) is implemented with tests; session orchestration and wiring from CLI to stores is not yet implemented
160- `docs/Potential schema.md` captures intended end-state for sessions, indexes, and events; use as design context, not as a guarantee