mirror of
https://github.com/lukaszraczylo/harness-sync.git
synced 2026-10-12 00:45:22 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3979583fe3 | ||
|
|
581f656824 | ||
|
|
e78bfb9f53 | ||
|
|
b5e3bcd301 | ||
|
|
fd6519eed1 | ||
|
|
bca4a4be1a | ||
|
|
fa17e9a289 | ||
|
|
f30c0f65a6 | ||
|
|
0892cb317e | ||
|
|
1053d223e5 | ||
|
|
e01f3419ea | ||
|
|
5704ede5c7 |
@@ -1,2 +1,4 @@
|
||||
{"action":"prune","keep":10,"kept":[],"removed":[],"auditedAt":"2026-05-23T19:08:40.613Z"}
|
||||
{"action":"prune","keep":10,"kept":[],"removed":[],"auditedAt":"2026-05-23T19:55:51.755Z"}
|
||||
{"action":"prune","keep":10,"kept":[],"removed":[],"auditedAt":"2026-06-27T23:46:20.411Z"}
|
||||
{"action":"prune","keep":10,"kept":[],"removed":[],"auditedAt":"2026-06-27T23:48:27.473Z"}
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
{"exportedAt":"2026-06-27T23:47:20.367Z","snapshots":[{"type":"counter","name":"crew.run.count","description":"Total runs by status","values":[]},{"type":"counter","name":"crew.task.count","description":"Total tasks by status","values":[]},{"type":"counter","name":"crew.subagent.count","description":"Total subagent records by status","values":[]},{"type":"counter","name":"crew.mailbox.count","description":"Total mailbox messages by direction","values":[]},{"type":"counter","name":"crew.task.retry_attempt_total","description":"Retry attempts by run and task","values":[]},{"type":"counter","name":"crew.task.deadletter_total","description":"Deadletter triggers by reason","values":[]},{"type":"counter","name":"crew.task.overflow_phase_total","description":"Overflow recovery phase transitions","values":[]},{"type":"counter","name":"crew.task.supervisor_contact_total","description":"Supervisor contact requests by reason","values":[]},{"type":"gauge","name":"crew.heartbeat.staleness_ms","description":"Heartbeat elapsed since last seen, milliseconds","values":[]},{"type":"histogram","name":"crew.run.duration_ms","description":"Run end-to-end duration, milliseconds","values":[]},{"type":"histogram","name":"crew.task.duration_ms","description":"Task duration, milliseconds","values":[]},{"type":"histogram","name":"crew.task.retry_count","description":"Retries per task","values":[]},{"type":"histogram","name":"crew.task.tokens_total","description":"Token usage per task","values":[]}]}
|
||||
{"exportedAt":"2026-06-27T23:48:20.367Z","snapshots":[{"type":"counter","name":"crew.run.count","description":"Total runs by status","values":[]},{"type":"counter","name":"crew.task.count","description":"Total tasks by status","values":[]},{"type":"counter","name":"crew.subagent.count","description":"Total subagent records by status","values":[]},{"type":"counter","name":"crew.mailbox.count","description":"Total mailbox messages by direction","values":[]},{"type":"counter","name":"crew.task.retry_attempt_total","description":"Retry attempts by run and task","values":[]},{"type":"counter","name":"crew.task.deadletter_total","description":"Deadletter triggers by reason","values":[]},{"type":"counter","name":"crew.task.overflow_phase_total","description":"Overflow recovery phase transitions","values":[]},{"type":"counter","name":"crew.task.supervisor_contact_total","description":"Supervisor contact requests by reason","values":[]},{"type":"gauge","name":"crew.heartbeat.staleness_ms","description":"Heartbeat elapsed since last seen, milliseconds","values":[]},{"type":"histogram","name":"crew.run.duration_ms","description":"Run end-to-end duration, milliseconds","values":[]},{"type":"histogram","name":"crew.task.duration_ms","description":"Task duration, milliseconds","values":[]},{"type":"histogram","name":"crew.task.retry_count","description":"Retries per task","values":[]},{"type":"histogram","name":"crew.task.tokens_total","description":"Token usage per task","values":[]}]}
|
||||
{"exportedAt":"2026-06-27T23:49:20.368Z","snapshots":[{"type":"counter","name":"crew.run.count","description":"Total runs by status","values":[]},{"type":"counter","name":"crew.task.count","description":"Total tasks by status","values":[]},{"type":"counter","name":"crew.subagent.count","description":"Total subagent records by status","values":[]},{"type":"counter","name":"crew.mailbox.count","description":"Total mailbox messages by direction","values":[]},{"type":"counter","name":"crew.task.retry_attempt_total","description":"Retry attempts by run and task","values":[]},{"type":"counter","name":"crew.task.deadletter_total","description":"Deadletter triggers by reason","values":[]},{"type":"counter","name":"crew.task.overflow_phase_total","description":"Overflow recovery phase transitions","values":[]},{"type":"counter","name":"crew.task.supervisor_contact_total","description":"Supervisor contact requests by reason","values":[]},{"type":"gauge","name":"crew.heartbeat.staleness_ms","description":"Heartbeat elapsed since last seen, milliseconds","values":[]},{"type":"histogram","name":"crew.run.duration_ms","description":"Run end-to-end duration, milliseconds","values":[]},{"type":"histogram","name":"crew.task.duration_ms","description":"Task duration, milliseconds","values":[]},{"type":"histogram","name":"crew.task.retry_count","description":"Retries per task","values":[]},{"type":"histogram","name":"crew.task.tokens_total","description":"Token usage per task","values":[]}]}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"history": []
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<strong>One canonical source of truth</strong> for skills, agents, MCP servers, LLM endpoints, and global instructions across every LLM harness on your machine.
|
||||
<strong>One canonical source of truth</strong> for skills, agents, rules, MCP servers, LLM endpoints, and global instructions across every LLM harness on your machine.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -40,6 +40,7 @@ Edit once. Forget the others. They drift. Things stop working in odd places.
|
||||
│ • profiles/<name>.yaml │
|
||||
│ • skills/<name>/SKILL.md │
|
||||
│ • agents/<name>.md │
|
||||
│ • rules/<name>.md │
|
||||
│ • mcp.yaml │
|
||||
│ • instructions/global.md │
|
||||
└──────────────┬───────────────────┘
|
||||
@@ -139,27 +140,38 @@ harness-sync goes out of its way to avoid.
|
||||
| **crush** | `~/.config/crush/crush.json` (merged) | `mcp` (`type: stdio`/`http`/`sse`) | `providers` map + `default_model` | `~/.config/crush/skills/` |
|
||||
| **kilo** | `~/.config/kilo/kilo.json` (merged) | `mcp` (`type: local`/`remote`) | `provider` map + `model` + `small_model` | `~/.kilo/skills/` |
|
||||
| **opencode** | `~/.config/opencode/opencode.jsonc` (merged) | `mcp` (`type: local`/`remote`) | `provider` map + `model` | `~/.config/opencode/skills/` |
|
||||
| **pi** | `~/.pi/agent/settings.json` (merged) + `~/.pi/agent/models.json` | — | `defaultProvider` + `defaultModel` + `models.json` provider | `~/.pi/agent/skills/` |
|
||||
| **goose** | `~/.config/goose/config.yaml` (merged) + `custom_providers/<name>.json` | `extensions` map (`type: stdio`) | `GOOSE_PROVIDER` + `GOOSE_MODEL` | `~/.agents/skills/` |
|
||||
| **cagent** | `~/.config/cagent/default.yaml` (starter) | `mcps` | `providers` map + per-agent `model:` | — |
|
||||
| **zed** | `~/.config/zed/settings.json` (merged) | `context_servers` | `language_models.openai.{api_url, available_models}` + `agent.default_model` | — |
|
||||
|
||||
### Capability matrix
|
||||
|
||||
What harness-sync writes per harness. Harnesses with a **built-in subscription** receive MCP + skills + instructions only — provider/model/endpoint config is skipped to avoid conflicting with the harness's own auth.
|
||||
What harness-sync writes per harness. Harnesses with a **built-in subscription** receive MCP + skills + agents + rules + instructions only — provider/model/endpoint config is skipped to avoid conflicting with the harness's own auth.
|
||||
|
||||
Skills paths are grounded in each harness's official documentation (kilo.ai, opencode.ai, goose-docs.ai). kilo, opencode, and goose also scan `~/.claude/skills/` as a compatibility path, so the claude-code symlink passively reaches them already.
|
||||
|
||||
| Harness | Built-in sub | Providers | Models | MCP | Skills | Instructions |
|
||||
|---|:---:|:---:|:---:|:---:|:---:|:---:|
|
||||
| **claude-code** | ✓ | — | — | ✓ | ✓ | ✓ |
|
||||
| **crush** | — | ✓ | ✓ | ✓ | ✓ | — |
|
||||
| **kilo** | — | ✓ | ✓ | ✓ | ✓ | — |
|
||||
| **opencode** | — | ✓ | ✓ | ✓ | ✓ | ✓ |
|
||||
| **goose** | — | ✓ | ✓ | ✓ | ✓ | — |
|
||||
| **cagent** | — | ✓ | ✓ | ✓ | — | ✓ |
|
||||
| **zed** | — | ✓ | ✓ | ✓ | — | — |
|
||||
| Harness | Built-in sub | Providers | Models | MCP | Skills | Agents | Rules | Instructions |
|
||||
|---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
|
||||
| **claude-code** | ✓ | — | — | ✓ | ✓ | ✓ | ✓ⁿ | ✓ |
|
||||
| **crush** | — | ✓ | ✓ | ✓ | ✓ | — | ✓ᶠ | ✓ᶠ |
|
||||
| **kilo** | — | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ᶠ | ✓ᶠ |
|
||||
| **opencode** | — | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ᶠ | ✓ |
|
||||
| **pi** | — | ✓ | ✓ | — | ✓ | — | ✓ᶠ | ✓ᶠ |
|
||||
| **goose** | — | ✓ | ✓ | ✓ | ✓ | — | ✓ᶠ | ✓ᶠ |
|
||||
| **cagent** | — | ✓ | ✓ | ✓ | — | — | ✓ᶠ | ✓ |
|
||||
| **zed** | — | ✓ | ✓ | — | — | — | ✓ᶠ | ✓ᶠ |
|
||||
|
||||
The matrix is machine-readable via `adapter.Capabilities()` — every adapter implements `HarnessCapabilities` so tooling can inspect what will change before running `apply`.
|
||||
The matrix is machine-readable via `adapter.Capabilities()` — every adapter implements `HarnessCapabilities` (`ManagesProviders/Models/MCP/Skills/Agents/Rules/Instructions`) so tooling can inspect what will change before running `apply`.
|
||||
|
||||
### Agents & rules — native where possible, folded where necessary
|
||||
|
||||
Each kind is delivered the way the target harness actually loads it (grounded in each harness's docs and config source — a wrong path is a silent no-op):
|
||||
|
||||
- **Agents** are markdown subagents. They map cleanly to **claude-code** (`~/.claude/agents/`), **kilo** (`~/.config/kilo/agents/` — plural; the older singular `agent/` is a no-op on current Kilo CLI), and **opencode** (`~/.config/opencode/agents/`), all as directory symlinks. **goose** (YAML recipes) and **cagent** (inline YAML `agents:`) use incompatible agent formats, and **crush**/**zed** have no markdown-subagent concept — so agents are not propagated there.
|
||||
- **Rules** (`rules/<name>.md`) are topic-scoped instruction fragments. **claude-code** auto-loads a rules *directory* natively (ⁿ), so they're delivered as a `~/.claude/rules` symlink — preserving each rule's optional path-scoping frontmatter. No other harness has a rules directory, so their bodies are **folded** (ᶠ) into that harness's global always-on instructions file — `AGENTS.md` (opencode/kilo/zed/crush), `.goosehints` (goose), or the per-agent `instruction:` (cagent). crush has no global instructions file, so harness-sync writes `~/.config/crush/AGENTS.md` and registers its absolute path in `options.context_paths` (crush always re-adds its built-in defaults at load, so nothing is clobbered).
|
||||
|
||||
ⁿ delivered as a native rules directory ᶠ folded into the harness's global instructions file
|
||||
|
||||
> **Merged, not replaced.** For harnesses with user-managed config keys (every one
|
||||
> except cagent), harness-sync reads the existing file, overlays only the keys
|
||||
@@ -279,7 +291,7 @@ end-to-end test that runs the real binary against a fake `$HOME`.
|
||||
|
||||
```
|
||||
cmd/harness-sync/main.go # cobra entrypoint + adapter registration
|
||||
internal/canonical/ # Bundle, Profile, MCPRegistry, Skill, Agent types + loader
|
||||
internal/canonical/ # Bundle, Profile, MCPRegistry, Skill, Agent, Rule types + loader
|
||||
internal/adapter/ # Adapter interface, Registry, FileSet
|
||||
internal/adapter/common/ # shared building blocks (BuildProviders, BuildMCPMapStyled, MergeJSONKeys, MergeYAMLKeys, …)
|
||||
internal/adapters/<harness>/ # one package per harness, ~50-100 LOC of harness-specific glue
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/lukaszraczylo/harness-sync/internal/adapters/goose"
|
||||
"github.com/lukaszraczylo/harness-sync/internal/adapters/kilo"
|
||||
"github.com/lukaszraczylo/harness-sync/internal/adapters/opencode"
|
||||
"github.com/lukaszraczylo/harness-sync/internal/adapters/pi"
|
||||
"github.com/lukaszraczylo/harness-sync/internal/adapters/zed"
|
||||
"github.com/lukaszraczylo/harness-sync/internal/cli"
|
||||
"github.com/lukaszraczylo/oss-telemetry"
|
||||
@@ -28,6 +29,7 @@ func main() {
|
||||
reg.Register(crush.New())
|
||||
reg.Register(kilo.New())
|
||||
reg.Register(opencode.New())
|
||||
reg.Register(pi.New())
|
||||
reg.Register(goose.New())
|
||||
reg.Register(cagent.New())
|
||||
reg.Register(zed.New())
|
||||
|
||||
@@ -4,8 +4,8 @@ go 1.25.0
|
||||
|
||||
require (
|
||||
github.com/charmbracelet/huh v1.0.0
|
||||
github.com/lukaszraczylo/oss-telemetry v0.2.1
|
||||
github.com/pelletier/go-toml/v2 v2.3.1
|
||||
github.com/lukaszraczylo/oss-telemetry v0.2.3
|
||||
github.com/pelletier/go-toml/v2 v2.4.3
|
||||
github.com/spf13/afero v1.15.0
|
||||
github.com/spf13/cobra v1.10.2
|
||||
github.com/stretchr/testify v1.9.0
|
||||
@@ -42,6 +42,6 @@ require (
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
github.com/spf13/pflag v1.0.10 // indirect
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
|
||||
golang.org/x/sys v0.45.0 // indirect
|
||||
golang.org/x/text v0.37.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
)
|
||||
|
||||
@@ -53,8 +53,8 @@ github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/lucasb-eyer/go-colorful v1.4.0 h1:UtrWVfLdarDgc44HcS7pYloGHJUjHV/4FwW4TvVgFr4=
|
||||
github.com/lucasb-eyer/go-colorful v1.4.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||
github.com/lukaszraczylo/oss-telemetry v0.2.1 h1:6ULyfzXplpdmIY/i01OPM1jeod9+L1RAhI0jtbVnJI0=
|
||||
github.com/lukaszraczylo/oss-telemetry v0.2.1/go.mod h1:+Cn78qZo8rc3T9eZt0v3oICYRdd75wORtSidc8lNjDQ=
|
||||
github.com/lukaszraczylo/oss-telemetry v0.2.3 h1:xoDtBqeZGmXj7IteiE1M5WMuzeoqag58qEleI0Cf2Ms=
|
||||
github.com/lukaszraczylo/oss-telemetry v0.2.3/go.mod h1:+Cn78qZo8rc3T9eZt0v3oICYRdd75wORtSidc8lNjDQ=
|
||||
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
|
||||
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
|
||||
github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
|
||||
@@ -69,8 +69,8 @@ github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELU
|
||||
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
|
||||
github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
|
||||
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
|
||||
github.com/pelletier/go-toml/v2 v2.3.1 h1:MYEvvGnQjeNkRF1qUuGolNtNExTDwct51yp7olPtrEc=
|
||||
github.com/pelletier/go-toml/v2 v2.3.1/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY=
|
||||
github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||
@@ -91,10 +91,10 @@ go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
|
||||
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
|
||||
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
|
||||
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
|
||||
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
|
||||
@@ -31,6 +31,8 @@ type HarnessCapabilities struct {
|
||||
ManagesModels bool // writes model selection config
|
||||
ManagesMCP bool // writes MCP server config
|
||||
ManagesSkills bool // writes skills symlink or equivalent
|
||||
ManagesAgents bool // writes agents symlink or equivalent
|
||||
ManagesRules bool // delivers rules (native rules dir, or folded into instructions)
|
||||
ManagesInstructions bool // writes instructions file (CLAUDE.md, AGENTS.md, etc.)
|
||||
HasBuiltInSub bool // has its own subscription; provider/model config is skipped
|
||||
}
|
||||
@@ -47,6 +49,7 @@ type ImportResult struct {
|
||||
Instructions string
|
||||
Skills []canonical.Skill
|
||||
Agents []canonical.Agent
|
||||
Rules []canonical.Rule
|
||||
MCP []canonical.MCPServer
|
||||
Profiles []canonical.Profile
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package adapter
|
||||
|
||||
import "github.com/lukaszraczylo/harness-sync/internal/adapter/common"
|
||||
|
||||
// Base holds the cross-adapter defaults (currently just the home directory
|
||||
// used to compute target paths). Embed it in each adapter struct to inherit
|
||||
// the WithHome/New constructor pattern without re-implementing it.
|
||||
type Base struct {
|
||||
Home string
|
||||
}
|
||||
|
||||
// BaseOption configures a Base. Returned by WithHome and consumed by NewBase.
|
||||
type BaseOption func(*Base)
|
||||
|
||||
// WithHome overrides the home directory used for target paths. Defaults to
|
||||
// common.DefaultHome() (current $HOME) when no option is supplied.
|
||||
func WithHome(h string) BaseOption {
|
||||
return func(b *Base) { b.Home = h }
|
||||
}
|
||||
|
||||
// NewBase returns a Base populated from opts, with Home defaulting to the
|
||||
// current user's home directory.
|
||||
func NewBase(opts ...BaseOption) *Base {
|
||||
b := &Base{Home: common.DefaultHome()}
|
||||
for _, o := range opts {
|
||||
o(b)
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package adapter_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/lukaszraczylo/harness-sync/internal/adapter"
|
||||
)
|
||||
|
||||
func TestNewBaseDefaultsHomeFromEnv(t *testing.T) {
|
||||
b := adapter.NewBase()
|
||||
// DefaultHome returns either $HOME or "". We only assert that the
|
||||
// helper does not panic and that Home is a string (Go zero value is "").
|
||||
// Environment-dependence: skip if HOME is unset (CI minimal envs).
|
||||
if b.Home == "" {
|
||||
t.Skip("HOME unset in test env; cannot verify default")
|
||||
}
|
||||
assert.NotEmpty(t, b.Home)
|
||||
}
|
||||
|
||||
func TestNewBaseWithHomeOverrides(t *testing.T) {
|
||||
b := adapter.NewBase(adapter.WithHome("/custom/home/path"))
|
||||
assert.Equal(t, "/custom/home/path", b.Home)
|
||||
}
|
||||
|
||||
func TestNewBaseOptionsApplyInOrder(t *testing.T) {
|
||||
// Last write wins — covers the basic Apply loop in NewBase.
|
||||
b := adapter.NewBase(
|
||||
adapter.WithHome("/first"),
|
||||
adapter.WithHome("/second"),
|
||||
)
|
||||
assert.Equal(t, "/second", b.Home)
|
||||
}
|
||||
|
||||
func TestBaseOptionTypedCorrectly(t *testing.T) {
|
||||
// adapter.BaseOption is the public type; WithHome must return it.
|
||||
opt := adapter.WithHome("/x")
|
||||
require.NotNil(t, opt)
|
||||
|
||||
// Apply it manually to confirm signature.
|
||||
var b adapter.Base
|
||||
opt(&b)
|
||||
assert.Equal(t, "/x", b.Home)
|
||||
}
|
||||
@@ -29,6 +29,19 @@ func ReadIfExists(path string) (string, error) {
|
||||
return ReadIfExistsFS(fsx.OS(), path)
|
||||
}
|
||||
|
||||
// ReadExistingFile returns the file body or (nil, nil) when missing.
|
||||
// Other errors (permission denied, I/O failure) are returned verbatim so
|
||||
// read-modify-write callers can distinguish a fresh first-run state from a
|
||||
// broken read. Treating every error as "file is empty" silently overwrites
|
||||
// the user's on-disk edits during apply.
|
||||
func ReadExistingFile(path string) ([]byte, error) {
|
||||
b, err := os.ReadFile(path) //nolint:gosec // caller-controlled path
|
||||
if err != nil && os.IsNotExist(err) {
|
||||
return nil, nil
|
||||
}
|
||||
return b, err
|
||||
}
|
||||
|
||||
// DirExistsFS reports whether path is an existing directory on fs.
|
||||
func DirExistsFS(fs fsx.FS, path string) bool {
|
||||
info, err := fs.Stat(path)
|
||||
@@ -155,6 +168,7 @@ func parseMCPEntry(name string, raw json.RawMessage) (canonical.MCPServer, bool)
|
||||
Cmd json.RawMessage `json:"cmd"`
|
||||
Args []string `json:"args"`
|
||||
URL string `json:"url"`
|
||||
Headers map[string]string `json:"headers"`
|
||||
Env map[string]string `json:"env"`
|
||||
Environment map[string]string `json:"environment"`
|
||||
}
|
||||
@@ -185,6 +199,7 @@ func parseMCPEntry(name string, raw json.RawMessage) (canonical.MCPServer, bool)
|
||||
Args: args,
|
||||
URL: e.URL,
|
||||
Transport: transport,
|
||||
Headers: e.Headers,
|
||||
Env: env,
|
||||
}, true
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package common_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/lukaszraczylo/harness-sync/internal/adapter/common"
|
||||
)
|
||||
|
||||
// ReadExistingFile: missing file returns (nil, nil). Permission errors and
|
||||
// other I/O failures must NOT be silently swallowed — those would let
|
||||
// read-modify-write code clobber the user's on-disk state.
|
||||
|
||||
func TestReadExistingFileMissing(t *testing.T) {
|
||||
got, err := common.ReadExistingFile(filepath.Join(t.TempDir(), "absent"))
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, got)
|
||||
}
|
||||
|
||||
func TestReadExistingFileContent(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "ok.txt")
|
||||
require.NoError(t, os.WriteFile(path, []byte("body\n"), 0o600))
|
||||
|
||||
got, err := common.ReadExistingFile(path)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []byte("body\n"), got)
|
||||
}
|
||||
|
||||
func TestReadExistingFilePropagatesError(t *testing.T) {
|
||||
// Create a directory the OS will refuse us read access to.
|
||||
if os.Geteuid() == 0 {
|
||||
t.Skip("running as root; cannot test permission denial")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
require.NoError(t, os.Mkdir(filepath.Join(dir, "locked"), 0o000))
|
||||
t.Cleanup(func() { _ = os.Chmod(filepath.Join(dir, "locked"), 0o755) })
|
||||
|
||||
_, err := common.ReadExistingFile(filepath.Join(dir, "locked", "file"))
|
||||
require.Error(t, err)
|
||||
assert.False(t, os.IsNotExist(err), "permission denied must not be reported as not-exist")
|
||||
assert.True(t, errors.Is(err, os.ErrPermission) || isPermission(err),
|
||||
"expected permission error, got %v", err)
|
||||
}
|
||||
|
||||
func isPermission(err error) bool {
|
||||
// Some platforms wrap the error in *os.PathError. Check the string too
|
||||
// for portability — it's a coarse signal but adequate here.
|
||||
return err != nil && (contains(err.Error(), "permission") || contains(err.Error(), "access denied"))
|
||||
}
|
||||
|
||||
func contains(s, sub string) bool {
|
||||
for i := 0; i+len(sub) <= len(s); i++ {
|
||||
if s[i:i+len(sub)] == sub {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -42,6 +42,7 @@ func TestImportMCPFromJSONFileFSExtractsServers(t *testing.T) {
|
||||
"myserver": {
|
||||
"command": "/usr/bin/mytool",
|
||||
"args": ["--flag"],
|
||||
"headers": {"Authorization": "Bearer ${MCP_TOKEN}"},
|
||||
"type": "stdio"
|
||||
}
|
||||
}
|
||||
@@ -55,6 +56,7 @@ func TestImportMCPFromJSONFileFSExtractsServers(t *testing.T) {
|
||||
assert.Equal(t, "/usr/bin/mytool", servers[0].Command)
|
||||
assert.Equal(t, []string{"--flag"}, servers[0].Args)
|
||||
assert.Equal(t, "stdio", servers[0].Transport)
|
||||
assert.Equal(t, map[string]string{"Authorization": "Bearer ${MCP_TOKEN}"}, servers[0].Headers)
|
||||
}
|
||||
|
||||
func TestImportMCPFromJSONFileFSReadOnlyFS(t *testing.T) {
|
||||
|
||||
@@ -39,6 +39,9 @@ func mcpEntry(s canonical.MCPServer, style MCPStyle) map[string]any {
|
||||
}
|
||||
e["type"] = t
|
||||
e["url"] = s.URL
|
||||
if len(s.Headers) > 0 {
|
||||
e["headers"] = s.Headers
|
||||
}
|
||||
} else {
|
||||
// Claude honours Transport field; Crush always uses "stdio".
|
||||
t := "stdio"
|
||||
@@ -60,6 +63,9 @@ func mcpEntry(s canonical.MCPServer, style MCPStyle) map[string]any {
|
||||
if s.URL != "" {
|
||||
e["type"] = "remote"
|
||||
e["url"] = s.URL
|
||||
if len(s.Headers) > 0 {
|
||||
e["headers"] = s.Headers
|
||||
}
|
||||
} else {
|
||||
e["type"] = "local"
|
||||
cmd := []string{}
|
||||
@@ -79,6 +85,9 @@ func mcpEntry(s canonical.MCPServer, style MCPStyle) map[string]any {
|
||||
// fail all of them. Omitting "enabled" defaults to true.
|
||||
if s.URL != "" {
|
||||
e["url"] = s.URL
|
||||
if len(s.Headers) > 0 {
|
||||
e["headers"] = s.Headers
|
||||
}
|
||||
} else {
|
||||
if s.Command != "" {
|
||||
e["command"] = s.Command
|
||||
|
||||
@@ -26,11 +26,16 @@ func TestBuildMCPMapStyledClaudeStyle(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestBuildMCPMapStyledClaudeStyleURL(t *testing.T) {
|
||||
r := reg(canonical.MCPServer{Name: "remote", URL: "https://example.com"})
|
||||
r := reg(canonical.MCPServer{
|
||||
Name: "remote",
|
||||
URL: "https://example.com",
|
||||
Headers: map[string]string{"Authorization": "Bearer ${MCP_TOKEN}"},
|
||||
})
|
||||
out := BuildMCPMapStyled(r, MCPClaudeStyle)
|
||||
e := out["remote"].(map[string]any)
|
||||
assert.Equal(t, "https://example.com", e["url"])
|
||||
assert.Equal(t, "http", e["type"])
|
||||
assert.Equal(t, map[string]string{"Authorization": "Bearer ${MCP_TOKEN}"}, e["headers"])
|
||||
}
|
||||
|
||||
func TestBuildMCPMapStyledCrushStdio(t *testing.T) {
|
||||
@@ -70,12 +75,17 @@ func TestBuildMCPMapStyledOpencodeLocal(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestBuildMCPMapStyledOpencodeRemote(t *testing.T) {
|
||||
r := reg(canonical.MCPServer{Name: "r", URL: "https://example.com"})
|
||||
r := reg(canonical.MCPServer{
|
||||
Name: "r",
|
||||
URL: "https://example.com",
|
||||
Headers: map[string]string{"X-Tenant": "tenant-a"},
|
||||
})
|
||||
out := BuildMCPMapStyled(r, MCPOpencodeStyle)
|
||||
e := out["r"].(map[string]any)
|
||||
assert.Equal(t, "remote", e["type"])
|
||||
assert.Equal(t, true, e["enabled"])
|
||||
assert.Equal(t, "https://example.com", e["url"])
|
||||
assert.Equal(t, map[string]string{"X-Tenant": "tenant-a"}, e["headers"])
|
||||
}
|
||||
|
||||
func TestBuildMCPMapStyledOpencodeEnv(t *testing.T) {
|
||||
|
||||
@@ -19,21 +19,16 @@ import (
|
||||
const name = "cagent"
|
||||
|
||||
// Adapter implements adapter.Adapter for the cagent harness.
|
||||
type Adapter struct{ home string }
|
||||
type Adapter struct {
|
||||
*adapter.Base
|
||||
}
|
||||
|
||||
// Option configures an Adapter.
|
||||
type Option func(*Adapter)
|
||||
|
||||
// WithHome overrides the home directory (defaults to os.UserHomeDir).
|
||||
func WithHome(h string) Option { return func(a *Adapter) { a.home = h } }
|
||||
// WithHome overrides the home directory used to resolve target paths.
|
||||
func WithHome(h string) adapter.BaseOption { return func(b *adapter.Base) { b.Home = h } }
|
||||
|
||||
// New returns a new Adapter with the given options applied.
|
||||
func New(opts ...Option) *Adapter {
|
||||
a := &Adapter{home: common.DefaultHome()}
|
||||
for _, o := range opts {
|
||||
o(a)
|
||||
}
|
||||
return a
|
||||
func New(opts ...adapter.BaseOption) *Adapter {
|
||||
return &Adapter{Base: adapter.NewBase(opts...)}
|
||||
}
|
||||
|
||||
// Name returns the harness identifier.
|
||||
@@ -46,6 +41,7 @@ func (a *Adapter) Capabilities() adapter.HarnessCapabilities {
|
||||
ManagesModels: true,
|
||||
ManagesMCP: true,
|
||||
ManagesSkills: false,
|
||||
ManagesRules: true,
|
||||
ManagesInstructions: true,
|
||||
HasBuiltInSub: false,
|
||||
}
|
||||
@@ -53,19 +49,18 @@ func (a *Adapter) Capabilities() adapter.HarnessCapabilities {
|
||||
|
||||
// Detect returns true when ~/.config/cagent/ exists.
|
||||
func (a *Adapter) Detect() bool {
|
||||
_, err := os.Stat(filepath.Join(a.home, ".config", "cagent"))
|
||||
_, err := os.Stat(filepath.Join(a.Home, ".config", "cagent"))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// Render produces a starter default.yaml for cagent.
|
||||
func (a *Adapter) Render(b *canonical.Bundle) (*adapter.FileSet, error) {
|
||||
fs := adapter.NewFileSet()
|
||||
cfgPath := filepath.Join(a.home, ".config", "cagent", "default.yaml")
|
||||
cfgPath := filepath.Join(a.Home, ".config", "cagent", "default.yaml")
|
||||
|
||||
instructions := b.Instructions.Global
|
||||
if override, ok := b.Instructions.PerHarness[name]; ok && override != "" {
|
||||
instructions = override
|
||||
}
|
||||
// cagent has no rules concept; the per-agent instruction (system prompt) is
|
||||
// the only sink, so fold rules into it.
|
||||
instructions := b.InstructionTextWithRules(name)
|
||||
|
||||
mcps := map[string]any{}
|
||||
for _, s := range b.MCP.Servers {
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package cagent
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/lukaszraczylo/harness-sync/internal/adapter"
|
||||
"github.com/lukaszraczylo/harness-sync/internal/canonical"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
func TestCagentFoldsRulesIntoInstruction(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
b := &canonical.Bundle{
|
||||
Instructions: canonical.Instructions{Global: "# global"},
|
||||
Rules: []canonical.Rule{{Name: "rust", Body: "# Rust\n\nno unwrap"}},
|
||||
}
|
||||
fs, err := New(WithHome(home)).Render(b)
|
||||
require.NoError(t, err)
|
||||
seen := map[string]adapter.File{}
|
||||
fs.ForEach(func(f adapter.File) { seen[f.Dest] = f })
|
||||
|
||||
cfg := seen[filepath.Join(home, ".config", "cagent", "default.yaml")]
|
||||
require.Equal(t, adapter.RenderedFile, cfg.Kind)
|
||||
|
||||
var parsed map[string]any
|
||||
require.NoError(t, yaml.Unmarshal(cfg.Content, &parsed))
|
||||
agents := parsed["agents"].(map[string]any)
|
||||
def := agents["default"].(map[string]any)
|
||||
instr := def["instruction"].(string)
|
||||
assert.Contains(t, instr, "# global")
|
||||
assert.Contains(t, instr, "no unwrap")
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
package claudecode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
@@ -14,22 +15,15 @@ const name = "claude-code"
|
||||
|
||||
// Adapter implements adapter.Adapter for the claude-code harness.
|
||||
type Adapter struct {
|
||||
home string
|
||||
*adapter.Base
|
||||
}
|
||||
|
||||
// Option configures an Adapter.
|
||||
type Option func(*Adapter)
|
||||
|
||||
// WithHome overrides the home directory (defaults to os.UserHomeDir).
|
||||
func WithHome(h string) Option { return func(a *Adapter) { a.home = h } }
|
||||
// WithHome overrides the home directory used to resolve target paths.
|
||||
func WithHome(h string) adapter.BaseOption { return func(b *adapter.Base) { b.Home = h } }
|
||||
|
||||
// New returns a new Adapter with the given options applied.
|
||||
func New(opts ...Option) *Adapter {
|
||||
a := &Adapter{home: common.DefaultHome()}
|
||||
for _, o := range opts {
|
||||
o(a)
|
||||
}
|
||||
return a
|
||||
func New(opts ...adapter.BaseOption) *Adapter {
|
||||
return &Adapter{Base: adapter.NewBase(opts...)}
|
||||
}
|
||||
|
||||
// Name returns the harness identifier.
|
||||
@@ -43,6 +37,8 @@ func (a *Adapter) Capabilities() adapter.HarnessCapabilities {
|
||||
ManagesModels: false,
|
||||
ManagesMCP: true,
|
||||
ManagesSkills: true,
|
||||
ManagesAgents: true,
|
||||
ManagesRules: true,
|
||||
ManagesInstructions: true,
|
||||
HasBuiltInSub: true,
|
||||
}
|
||||
@@ -50,7 +46,7 @@ func (a *Adapter) Capabilities() adapter.HarnessCapabilities {
|
||||
|
||||
// Detect returns true when ~/.claude exists.
|
||||
func (a *Adapter) Detect() bool {
|
||||
_, err := os.Stat(filepath.Join(a.home, ".claude"))
|
||||
_, err := os.Stat(filepath.Join(a.Home, ".claude"))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
@@ -59,7 +55,7 @@ func (a *Adapter) Detect() bool {
|
||||
// only manages skills/agents symlinks, CLAUDE.md, and MCP servers.
|
||||
func (a *Adapter) Render(b *canonical.Bundle) (*adapter.FileSet, error) {
|
||||
fs := adapter.NewFileSet()
|
||||
base := filepath.Join(a.home, ".claude")
|
||||
base := filepath.Join(a.Home, ".claude")
|
||||
|
||||
fs.Add(adapter.File{
|
||||
Dest: filepath.Join(base, "skills"),
|
||||
@@ -71,15 +67,19 @@ func (a *Adapter) Render(b *canonical.Bundle) (*adapter.FileSet, error) {
|
||||
Kind: adapter.SymlinkDir,
|
||||
SymlinkTarget: filepath.Join(b.Root, "agents"),
|
||||
})
|
||||
// Claude Code natively auto-loads ~/.claude/rules/*.md (memory feature), so
|
||||
// rules are delivered as their own directory symlink — NOT folded into
|
||||
// CLAUDE.md — preserving each rule's optional path-scoping frontmatter.
|
||||
fs.Add(adapter.File{
|
||||
Dest: filepath.Join(base, "rules"),
|
||||
Kind: adapter.SymlinkDir,
|
||||
SymlinkTarget: filepath.Join(b.Root, "rules"),
|
||||
})
|
||||
|
||||
instructions := b.Instructions.Global
|
||||
if override, ok := b.Instructions.PerHarness[name]; ok && override != "" {
|
||||
instructions = override
|
||||
}
|
||||
fs.Add(adapter.File{
|
||||
Dest: filepath.Join(base, "CLAUDE.md"),
|
||||
Kind: adapter.RenderedFile,
|
||||
Content: []byte(instructions),
|
||||
Content: []byte(b.InstructionText(name)),
|
||||
})
|
||||
|
||||
// Claude Code reads MCP servers from two files on disk:
|
||||
@@ -92,7 +92,10 @@ func (a *Adapter) Render(b *canonical.Bundle) (*adapter.FileSet, error) {
|
||||
overlay := map[string]any{"mcpServers": mcpMap}
|
||||
|
||||
dedicatedPath := filepath.Join(base, "mcp_servers.json")
|
||||
dedicatedExisting, _ := os.ReadFile(dedicatedPath)
|
||||
dedicatedExisting, err := common.ReadExistingFile(dedicatedPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %s: %w", dedicatedPath, err)
|
||||
}
|
||||
dedicatedMerged, err := common.MergeJSONKeys(dedicatedExisting, overlay)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -103,9 +106,12 @@ func (a *Adapter) Render(b *canonical.Bundle) (*adapter.FileSet, error) {
|
||||
Content: dedicatedMerged,
|
||||
})
|
||||
|
||||
livePath := filepath.Join(a.home, ".claude.json")
|
||||
livePath := filepath.Join(a.Home, ".claude.json")
|
||||
if _, err := os.Stat(livePath); err == nil {
|
||||
liveExisting, _ := os.ReadFile(livePath)
|
||||
liveExisting, err := common.ReadExistingFile(livePath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %s: %w", livePath, err)
|
||||
}
|
||||
liveMerged, err := common.MergeJSONKeys(liveExisting, overlay)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -32,6 +32,16 @@ func importFrom(home string) (*adapter.ImportResult, error) {
|
||||
})
|
||||
}
|
||||
|
||||
rules, err := common.ImportMarkdownTree(filepath.Join(base, "rules"), "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, r := range rules {
|
||||
res.Rules = append(res.Rules, canonical.Rule{
|
||||
Name: r.Name, Description: r.Description, Body: r.Body, Path: r.Path,
|
||||
})
|
||||
}
|
||||
|
||||
body, err := common.ReadIfExists(filepath.Join(base, "CLAUDE.md"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package claudecode
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/lukaszraczylo/harness-sync/internal/adapter"
|
||||
"github.com/lukaszraczylo/harness-sync/internal/canonical"
|
||||
)
|
||||
|
||||
func TestClaudeCodeRendersRulesSymlink(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
ad := New(WithHome(home))
|
||||
b := &canonical.Bundle{Root: "/canon"}
|
||||
fs, err := ad.Render(b)
|
||||
require.NoError(t, err)
|
||||
|
||||
seen := map[string]adapter.File{}
|
||||
fs.ForEach(func(f adapter.File) { seen[f.Dest] = f })
|
||||
|
||||
rulesDest := filepath.Join(home, ".claude", "rules")
|
||||
assert.Equal(t, adapter.SymlinkDir, seen[rulesDest].Kind)
|
||||
assert.Equal(t, "/canon/rules", seen[rulesDest].SymlinkTarget)
|
||||
|
||||
// Rules are delivered natively as a directory — never folded into CLAUDE.md.
|
||||
claudemd := string(seen[filepath.Join(home, ".claude", "CLAUDE.md")].Content)
|
||||
assert.NotContains(t, claudemd, "/canon/rules")
|
||||
}
|
||||
|
||||
func TestClaudeCodeImportsRules(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
rulesDir := filepath.Join(home, ".claude", "rules")
|
||||
require.NoError(t, os.MkdirAll(rulesDir, 0o750))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(rulesDir, "go.md"),
|
||||
[]byte("# Go Rules\n\ngofmt always"), 0o600))
|
||||
|
||||
ad := New(WithHome(home))
|
||||
res, err := ad.Import(home)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, res.Rules, 1)
|
||||
assert.Equal(t, "go", res.Rules[0].Name)
|
||||
assert.Contains(t, res.Rules[0].Body, "gofmt always")
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
package crush
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
@@ -13,21 +15,16 @@ import (
|
||||
const name = "crush"
|
||||
|
||||
// Adapter implements adapter.Adapter for the crush harness.
|
||||
type Adapter struct{ home string }
|
||||
type Adapter struct {
|
||||
*adapter.Base
|
||||
}
|
||||
|
||||
// Option configures an Adapter.
|
||||
type Option func(*Adapter)
|
||||
|
||||
// WithHome overrides the home directory (defaults to os.UserHomeDir).
|
||||
func WithHome(h string) Option { return func(a *Adapter) { a.home = h } }
|
||||
// WithHome overrides the home directory used to resolve target paths.
|
||||
func WithHome(h string) adapter.BaseOption { return func(b *adapter.Base) { b.Home = h } }
|
||||
|
||||
// New returns a new Adapter with the given options applied.
|
||||
func New(opts ...Option) *Adapter {
|
||||
a := &Adapter{home: common.DefaultHome()}
|
||||
for _, o := range opts {
|
||||
o(a)
|
||||
}
|
||||
return a
|
||||
func New(opts ...adapter.BaseOption) *Adapter {
|
||||
return &Adapter{Base: adapter.NewBase(opts...)}
|
||||
}
|
||||
|
||||
// Name returns the harness identifier.
|
||||
@@ -40,14 +37,15 @@ func (a *Adapter) Capabilities() adapter.HarnessCapabilities {
|
||||
ManagesModels: true,
|
||||
ManagesMCP: true,
|
||||
ManagesSkills: true,
|
||||
ManagesInstructions: false,
|
||||
ManagesRules: true,
|
||||
ManagesInstructions: true,
|
||||
HasBuiltInSub: false,
|
||||
}
|
||||
}
|
||||
|
||||
// Detect returns true when ~/.config/crush exists.
|
||||
func (a *Adapter) Detect() bool {
|
||||
_, err := os.Stat(filepath.Join(a.home, ".config", "crush"))
|
||||
_, err := os.Stat(filepath.Join(a.Home, ".config", "crush"))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
@@ -56,7 +54,7 @@ func (a *Adapter) Detect() bool {
|
||||
// MCP key is "mcp" (not "mcpServers"); entries include a "type" field.
|
||||
func (a *Adapter) Render(b *canonical.Bundle) (*adapter.FileSet, error) {
|
||||
fs := adapter.NewFileSet()
|
||||
base := filepath.Join(a.home, ".config", "crush")
|
||||
base := filepath.Join(a.Home, ".config", "crush")
|
||||
|
||||
fs.Add(adapter.File{
|
||||
Dest: filepath.Join(base, "skills"),
|
||||
@@ -64,9 +62,25 @@ func (a *Adapter) Render(b *canonical.Bundle) (*adapter.FileSet, error) {
|
||||
SymlinkTarget: filepath.Join(b.Root, "skills"),
|
||||
})
|
||||
|
||||
// crush has no global instructions file and no rules directory: it loads
|
||||
// context from the files listed in options.context_paths (defaults are always
|
||||
// prepended; absolute paths load verbatim; the global config applies to every
|
||||
// project). Write a global AGENTS.md with rules folded in, and register its
|
||||
// absolute path so crush loads it in every session.
|
||||
agentsMD := filepath.Join(base, "AGENTS.md")
|
||||
fs.Add(adapter.File{
|
||||
Dest: agentsMD,
|
||||
Kind: adapter.RenderedFile,
|
||||
Content: []byte(b.InstructionTextWithRules(name)),
|
||||
})
|
||||
|
||||
cfgPath := filepath.Join(base, "crush.json")
|
||||
existing, _ := os.ReadFile(cfgPath)
|
||||
existing, err := common.ReadExistingFile(cfgPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %s: %w", cfgPath, err)
|
||||
}
|
||||
overlay := map[string]any{}
|
||||
overlay["options"] = crushOptionsWithContextPath(existing, agentsMD)
|
||||
if providers := common.ProvidersAsCrushMap(&b.Profile); len(providers) > 0 {
|
||||
overlay["providers"] = providers
|
||||
}
|
||||
@@ -90,6 +104,34 @@ func (a *Adapter) Render(b *canonical.Bundle) (*adapter.FileSet, error) {
|
||||
return fs, nil
|
||||
}
|
||||
|
||||
// crushOptionsWithContextPath returns the crush "options" object with contextFile
|
||||
// added to options.context_paths, preserving every other existing option key
|
||||
// (lsp, permissions, …). crush always prepends its built-in default context
|
||||
// paths at load time, so only the extra path is set here. Idempotent.
|
||||
func crushOptionsWithContextPath(existing []byte, contextFile string) map[string]any {
|
||||
opts := map[string]any{}
|
||||
if len(existing) > 0 {
|
||||
var raw map[string]any
|
||||
clean := common.StripJSONComments(string(existing))
|
||||
if json.Unmarshal([]byte(clean), &raw) == nil {
|
||||
if o, ok := raw["options"].(map[string]any); ok {
|
||||
opts = o
|
||||
}
|
||||
}
|
||||
}
|
||||
var paths []any
|
||||
if existingPaths, ok := opts["context_paths"].([]any); ok {
|
||||
paths = existingPaths
|
||||
}
|
||||
for _, p := range paths {
|
||||
if s, ok := p.(string); ok && s == contextFile {
|
||||
return opts // already registered
|
||||
}
|
||||
}
|
||||
opts["context_paths"] = append(paths, contextFile)
|
||||
return opts
|
||||
}
|
||||
|
||||
// Import reads crush config from home and returns a canonical ImportResult.
|
||||
func (a *Adapter) Import(home string) (*adapter.ImportResult, error) {
|
||||
return importFrom(home)
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package crush
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/lukaszraczylo/harness-sync/internal/adapter"
|
||||
"github.com/lukaszraczylo/harness-sync/internal/canonical"
|
||||
)
|
||||
|
||||
func renderCrush(t *testing.T, home string, b *canonical.Bundle) map[string]adapter.File {
|
||||
t.Helper()
|
||||
fs, err := New(WithHome(home)).Render(b)
|
||||
require.NoError(t, err)
|
||||
seen := map[string]adapter.File{}
|
||||
fs.ForEach(func(f adapter.File) { seen[f.Dest] = f })
|
||||
return seen
|
||||
}
|
||||
|
||||
func TestCrushWritesAGENTSAndRegistersContextPath(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
b := &canonical.Bundle{
|
||||
Root: "/canon",
|
||||
Instructions: canonical.Instructions{Global: "# global"},
|
||||
Rules: []canonical.Rule{{Name: "sec", Body: "# Security\n\nno secrets in code"}},
|
||||
}
|
||||
seen := renderCrush(t, home, b)
|
||||
|
||||
base := filepath.Join(home, ".config", "crush")
|
||||
agentsMD := filepath.Join(base, "AGENTS.md")
|
||||
assert.Equal(t, adapter.RenderedFile, seen[agentsMD].Kind)
|
||||
body := string(seen[agentsMD].Content)
|
||||
assert.Contains(t, body, "# global")
|
||||
assert.Contains(t, body, "no secrets in code")
|
||||
|
||||
var cfg map[string]any
|
||||
require.NoError(t, json.Unmarshal(seen[filepath.Join(base, "crush.json")].Content, &cfg))
|
||||
opts := cfg["options"].(map[string]any)
|
||||
paths := opts["context_paths"].([]any)
|
||||
assert.Contains(t, paths, agentsMD, "absolute AGENTS.md path must be registered for global load")
|
||||
}
|
||||
|
||||
func TestCrushPreservesExistingOptionsAndIsIdempotent(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
base := filepath.Join(home, ".config", "crush")
|
||||
require.NoError(t, os.MkdirAll(base, 0o750))
|
||||
agentsMD := filepath.Join(base, "AGENTS.md")
|
||||
|
||||
// Existing crush.json with other options keys and a pre-existing context path
|
||||
// (including our own — second apply must not duplicate it).
|
||||
existing := map[string]any{
|
||||
"options": map[string]any{
|
||||
"context_paths": []any{"PROJECT.md", agentsMD},
|
||||
"lsp": map[string]any{"go": true},
|
||||
},
|
||||
}
|
||||
body, _ := json.Marshal(existing)
|
||||
require.NoError(t, os.WriteFile(filepath.Join(base, "crush.json"), body, 0o600))
|
||||
|
||||
seen := renderCrush(t, home, &canonical.Bundle{Root: "/canon"})
|
||||
|
||||
var cfg map[string]any
|
||||
require.NoError(t, json.Unmarshal(seen[filepath.Join(base, "crush.json")].Content, &cfg))
|
||||
opts := cfg["options"].(map[string]any)
|
||||
|
||||
// Other option keys survive.
|
||||
assert.Contains(t, opts, "lsp")
|
||||
// Pre-existing user path survives; ours is present exactly once (idempotent).
|
||||
paths := opts["context_paths"].([]any)
|
||||
count := 0
|
||||
for _, p := range paths {
|
||||
if p == agentsMD {
|
||||
count++
|
||||
}
|
||||
}
|
||||
assert.Equal(t, 1, count, "our context path must not be duplicated on re-apply")
|
||||
assert.Contains(t, paths, "PROJECT.md")
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
package goose
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -22,21 +23,16 @@ import (
|
||||
const name = "goose"
|
||||
|
||||
// Adapter implements adapter.Adapter for the Goose harness.
|
||||
type Adapter struct{ home string }
|
||||
type Adapter struct {
|
||||
*adapter.Base
|
||||
}
|
||||
|
||||
// Option configures an Adapter.
|
||||
type Option func(*Adapter)
|
||||
|
||||
// WithHome overrides the home directory (defaults to os.UserHomeDir).
|
||||
func WithHome(h string) Option { return func(a *Adapter) { a.home = h } }
|
||||
// WithHome overrides the home directory used to resolve target paths.
|
||||
func WithHome(h string) adapter.BaseOption { return func(b *adapter.Base) { b.Home = h } }
|
||||
|
||||
// New returns a new Adapter with the given options applied.
|
||||
func New(opts ...Option) *Adapter {
|
||||
a := &Adapter{home: common.DefaultHome()}
|
||||
for _, o := range opts {
|
||||
o(a)
|
||||
}
|
||||
return a
|
||||
func New(opts ...adapter.BaseOption) *Adapter {
|
||||
return &Adapter{Base: adapter.NewBase(opts...)}
|
||||
}
|
||||
|
||||
// Name returns the harness identifier.
|
||||
@@ -49,14 +45,15 @@ func (a *Adapter) Capabilities() adapter.HarnessCapabilities {
|
||||
ManagesModels: true,
|
||||
ManagesMCP: true,
|
||||
ManagesSkills: true,
|
||||
ManagesInstructions: false,
|
||||
ManagesRules: true,
|
||||
ManagesInstructions: true,
|
||||
HasBuiltInSub: false,
|
||||
}
|
||||
}
|
||||
|
||||
// Detect returns true when ~/.config/goose/ exists.
|
||||
func (a *Adapter) Detect() bool {
|
||||
_, err := os.Stat(filepath.Join(a.home, ".config", "goose"))
|
||||
_, err := os.Stat(filepath.Join(a.Home, ".config", "goose"))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
@@ -67,23 +64,26 @@ func (a *Adapter) Detect() bool {
|
||||
// also added to the FileSet so goose can load the provider on first run.
|
||||
func (a *Adapter) Render(b *canonical.Bundle) (*adapter.FileSet, error) {
|
||||
fs := adapter.NewFileSet()
|
||||
cfgPath := filepath.Join(a.home, ".config", "goose", "config.yaml")
|
||||
cfgPath := filepath.Join(a.Home, ".config", "goose", "config.yaml")
|
||||
|
||||
// goose reads skills from ~/.agents/skills/<name>/SKILL.md (open Agent Skills spec)
|
||||
fs.Add(adapter.File{
|
||||
Dest: filepath.Join(a.home, ".agents", "skills"),
|
||||
Dest: filepath.Join(a.Home, ".agents", "skills"),
|
||||
Kind: adapter.SymlinkDir,
|
||||
SymlinkTarget: filepath.Join(b.Root, "skills"),
|
||||
})
|
||||
|
||||
existing, _ := os.ReadFile(cfgPath)
|
||||
existing, err := common.ReadExistingFile(cfgPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %s: %w", cfgPath, err)
|
||||
}
|
||||
|
||||
provider, model := splitProviderModel(b.Profile.Gateway.DefaultModel)
|
||||
if b.Profile.Gateway.URL != "" {
|
||||
// Emit the custom provider JSON file.
|
||||
body, providerName := common.GooseCustomProviderFile(&b.Profile)
|
||||
if body != nil {
|
||||
cpDir := filepath.Join(a.home, ".config", "goose", "custom_providers")
|
||||
cpDir := filepath.Join(a.Home, ".config", "goose", "custom_providers")
|
||||
fs.Add(adapter.File{
|
||||
Dest: filepath.Join(cpDir, providerName+".json"),
|
||||
Kind: adapter.RenderedFile,
|
||||
@@ -114,6 +114,16 @@ func (a *Adapter) Render(b *canonical.Bundle) (*adapter.FileSet, error) {
|
||||
Content: merged,
|
||||
})
|
||||
|
||||
// goose has no native rules directory; ~/.config/goose/.goosehints is the
|
||||
// global hints file applied to every session, so fold rules into it.
|
||||
if hints := b.InstructionTextWithRules(name); hints != "" {
|
||||
fs.Add(adapter.File{
|
||||
Dest: filepath.Join(a.Home, ".config", "goose", ".goosehints"),
|
||||
Kind: adapter.RenderedFile,
|
||||
Content: []byte(hints),
|
||||
})
|
||||
}
|
||||
|
||||
return fs, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package goose
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/lukaszraczylo/harness-sync/internal/adapter"
|
||||
"github.com/lukaszraczylo/harness-sync/internal/canonical"
|
||||
)
|
||||
|
||||
func TestGooseFoldsRulesIntoGoosehints(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
b := &canonical.Bundle{
|
||||
Instructions: canonical.Instructions{Global: "# global"},
|
||||
Rules: []canonical.Rule{{Name: "k8s", Body: "# Kube\n\nlabel everything"}},
|
||||
}
|
||||
fs, err := New(WithHome(home)).Render(b)
|
||||
require.NoError(t, err)
|
||||
seen := map[string]adapter.File{}
|
||||
fs.ForEach(func(f adapter.File) { seen[f.Dest] = f })
|
||||
|
||||
hints := filepath.Join(home, ".config", "goose", ".goosehints")
|
||||
require.Contains(t, seen, hints)
|
||||
assert.Equal(t, adapter.RenderedFile, seen[hints].Kind)
|
||||
body := string(seen[hints].Content)
|
||||
assert.Contains(t, body, "# global")
|
||||
assert.Contains(t, body, "label everything")
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package kilo
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -16,22 +17,15 @@ const name = "kilo"
|
||||
|
||||
// Adapter implements adapter.Adapter for the kilo harness.
|
||||
type Adapter struct {
|
||||
home string
|
||||
*adapter.Base
|
||||
}
|
||||
|
||||
// Option configures an Adapter.
|
||||
type Option func(*Adapter)
|
||||
|
||||
// WithHome overrides the home directory (defaults to os.UserHomeDir).
|
||||
func WithHome(h string) Option { return func(a *Adapter) { a.home = h } }
|
||||
// WithHome overrides the home directory used to resolve target paths.
|
||||
func WithHome(h string) adapter.BaseOption { return func(b *adapter.Base) { b.Home = h } }
|
||||
|
||||
// New returns a new Adapter with the given options applied.
|
||||
func New(opts ...Option) *Adapter {
|
||||
a := &Adapter{home: common.DefaultHome()}
|
||||
for _, o := range opts {
|
||||
o(a)
|
||||
}
|
||||
return a
|
||||
func New(opts ...adapter.BaseOption) *Adapter {
|
||||
return &Adapter{Base: adapter.NewBase(opts...)}
|
||||
}
|
||||
|
||||
// Name returns the harness identifier.
|
||||
@@ -44,14 +38,16 @@ func (a *Adapter) Capabilities() adapter.HarnessCapabilities {
|
||||
ManagesModels: true,
|
||||
ManagesMCP: true,
|
||||
ManagesSkills: true,
|
||||
ManagesInstructions: false,
|
||||
ManagesAgents: true,
|
||||
ManagesRules: true,
|
||||
ManagesInstructions: true,
|
||||
HasBuiltInSub: false,
|
||||
}
|
||||
}
|
||||
|
||||
// Detect returns true when ~/.config/kilo exists.
|
||||
func (a *Adapter) Detect() bool {
|
||||
_, err := os.Stat(filepath.Join(a.home, ".config", "kilo"))
|
||||
_, err := os.Stat(filepath.Join(a.Home, ".config", "kilo"))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
@@ -62,22 +58,35 @@ func (a *Adapter) Detect() bool {
|
||||
// No "providers" key — kilo has no such concept.
|
||||
func (a *Adapter) Render(b *canonical.Bundle) (*adapter.FileSet, error) {
|
||||
fs := adapter.NewFileSet()
|
||||
base := filepath.Join(a.home, ".config", "kilo")
|
||||
base := filepath.Join(a.Home, ".config", "kilo")
|
||||
|
||||
// Kilo CLI reads global markdown subagents from ~/.config/kilo/agents/<name>.md
|
||||
// (PLURAL — the singular "agent/" used by older OpenCode-fork builds is a
|
||||
// silent no-op on current Kilo).
|
||||
fs.Add(adapter.File{
|
||||
Dest: filepath.Join(base, "agent"),
|
||||
Dest: filepath.Join(base, "agents"),
|
||||
Kind: adapter.SymlinkDir,
|
||||
SymlinkTarget: filepath.Join(b.Root, "agents"),
|
||||
})
|
||||
// kilo reads skills from ~/.kilo/skills/<name>/SKILL.md
|
||||
fs.Add(adapter.File{
|
||||
Dest: filepath.Join(a.home, ".kilo", "skills"),
|
||||
Dest: filepath.Join(a.Home, ".kilo", "skills"),
|
||||
Kind: adapter.SymlinkDir,
|
||||
SymlinkTarget: filepath.Join(b.Root, "skills"),
|
||||
})
|
||||
// kilo has no global rules directory; ~/.config/kilo/AGENTS.md is the
|
||||
// always-on global instructions file, so fold rules into it.
|
||||
fs.Add(adapter.File{
|
||||
Dest: filepath.Join(base, "AGENTS.md"),
|
||||
Kind: adapter.RenderedFile,
|
||||
Content: []byte(b.InstructionTextWithRules(name)),
|
||||
})
|
||||
|
||||
cfgPath := filepath.Join(base, "kilo.json")
|
||||
existing, _ := os.ReadFile(cfgPath)
|
||||
existing, err := common.ReadExistingFile(cfgPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %s: %w", cfgPath, err)
|
||||
}
|
||||
modelStr := common.KiloModelString(&b.Profile)
|
||||
overlay := map[string]any{}
|
||||
if providers := common.ProvidersAsMap(&b.Profile); len(providers) > 0 {
|
||||
|
||||
@@ -33,7 +33,8 @@ func TestKiloRender(t *testing.T) {
|
||||
seen := map[string]adapter.File{}
|
||||
fs.ForEach(func(f adapter.File) { seen[f.Dest] = f })
|
||||
|
||||
agentDest := filepath.Join(home, ".config", "kilo", "agent")
|
||||
// Global markdown subagents dir is PLURAL "agents" on current Kilo CLI.
|
||||
agentDest := filepath.Join(home, ".config", "kilo", "agents")
|
||||
assert.Equal(t, adapter.SymlinkDir, seen[agentDest].Kind)
|
||||
assert.Equal(t, "/canon/agents", seen[agentDest].SymlinkTarget)
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package kilo
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/lukaszraczylo/harness-sync/internal/adapter"
|
||||
"github.com/lukaszraczylo/harness-sync/internal/canonical"
|
||||
)
|
||||
|
||||
func TestKiloFoldsRulesIntoAGENTS(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
b := &canonical.Bundle{
|
||||
Root: "/canon",
|
||||
Instructions: canonical.Instructions{Global: "# global"},
|
||||
Rules: []canonical.Rule{{Name: "py", Body: "# Py\n\ntype hints"}},
|
||||
}
|
||||
fs, err := New(WithHome(home)).Render(b)
|
||||
require.NoError(t, err)
|
||||
seen := map[string]adapter.File{}
|
||||
fs.ForEach(func(f adapter.File) { seen[f.Dest] = f })
|
||||
|
||||
agentsMD := filepath.Join(home, ".config", "kilo", "AGENTS.md")
|
||||
require.Contains(t, seen, agentsMD)
|
||||
assert.Equal(t, adapter.RenderedFile, seen[agentsMD].Kind)
|
||||
body := string(seen[agentsMD].Content)
|
||||
assert.Contains(t, body, "# global")
|
||||
assert.Contains(t, body, "type hints")
|
||||
}
|
||||
@@ -5,12 +5,23 @@ import (
|
||||
|
||||
"github.com/lukaszraczylo/harness-sync/internal/adapter"
|
||||
"github.com/lukaszraczylo/harness-sync/internal/adapter/common"
|
||||
"github.com/lukaszraczylo/harness-sync/internal/canonical"
|
||||
)
|
||||
|
||||
func importFrom(home string) (*adapter.ImportResult, error) {
|
||||
base := filepath.Join(home, ".config", "opencode")
|
||||
res := &adapter.ImportResult{}
|
||||
|
||||
agents, err := common.ImportMarkdownTree(filepath.Join(base, "agents"), "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, a := range agents {
|
||||
res.Agents = append(res.Agents, canonical.Agent{
|
||||
Name: a.Name, Description: a.Description, Body: a.Body, Path: a.Path,
|
||||
})
|
||||
}
|
||||
|
||||
cfgBody, err := common.ReadIfExists(filepath.Join(base, "opencode.jsonc"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -3,6 +3,7 @@ package opencode
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
@@ -14,21 +15,16 @@ import (
|
||||
const name = "opencode"
|
||||
|
||||
// Adapter implements adapter.Adapter for the opencode harness.
|
||||
type Adapter struct{ home string }
|
||||
type Adapter struct {
|
||||
*adapter.Base
|
||||
}
|
||||
|
||||
// Option configures an Adapter.
|
||||
type Option func(*Adapter)
|
||||
|
||||
// WithHome overrides the home directory (defaults to os.UserHomeDir).
|
||||
func WithHome(h string) Option { return func(a *Adapter) { a.home = h } }
|
||||
// WithHome overrides the home directory used to resolve target paths.
|
||||
func WithHome(h string) adapter.BaseOption { return func(b *adapter.Base) { b.Home = h } }
|
||||
|
||||
// New returns a new Adapter with the given options applied.
|
||||
func New(opts ...Option) *Adapter {
|
||||
a := &Adapter{home: common.DefaultHome()}
|
||||
for _, o := range opts {
|
||||
o(a)
|
||||
}
|
||||
return a
|
||||
func New(opts ...adapter.BaseOption) *Adapter {
|
||||
return &Adapter{Base: adapter.NewBase(opts...)}
|
||||
}
|
||||
|
||||
// Name returns the harness identifier.
|
||||
@@ -41,6 +37,8 @@ func (a *Adapter) Capabilities() adapter.HarnessCapabilities {
|
||||
ManagesModels: true,
|
||||
ManagesMCP: true,
|
||||
ManagesSkills: true,
|
||||
ManagesAgents: true,
|
||||
ManagesRules: true,
|
||||
ManagesInstructions: true,
|
||||
HasBuiltInSub: false,
|
||||
}
|
||||
@@ -48,7 +46,7 @@ func (a *Adapter) Capabilities() adapter.HarnessCapabilities {
|
||||
|
||||
// Detect returns true when ~/.config/opencode exists.
|
||||
func (a *Adapter) Detect() bool {
|
||||
_, err := os.Stat(filepath.Join(a.home, ".config", "opencode"))
|
||||
_, err := os.Stat(filepath.Join(a.Home, ".config", "opencode"))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
@@ -58,7 +56,7 @@ func (a *Adapter) Detect() bool {
|
||||
// "mcp" (map with type: local|remote entries).
|
||||
func (a *Adapter) Render(b *canonical.Bundle) (*adapter.FileSet, error) {
|
||||
fs := adapter.NewFileSet()
|
||||
base := filepath.Join(a.home, ".config", "opencode")
|
||||
base := filepath.Join(a.Home, ".config", "opencode")
|
||||
|
||||
// opencode reads skills from ~/.config/opencode/skills/<name>/SKILL.md
|
||||
fs.Add(adapter.File{
|
||||
@@ -66,9 +64,18 @@ func (a *Adapter) Render(b *canonical.Bundle) (*adapter.FileSet, error) {
|
||||
Kind: adapter.SymlinkDir,
|
||||
SymlinkTarget: filepath.Join(b.Root, "skills"),
|
||||
})
|
||||
// opencode reads markdown subagents from ~/.config/opencode/agents/<name>.md
|
||||
fs.Add(adapter.File{
|
||||
Dest: filepath.Join(base, "agents"),
|
||||
Kind: adapter.SymlinkDir,
|
||||
SymlinkTarget: filepath.Join(b.Root, "agents"),
|
||||
})
|
||||
|
||||
cfgPath := filepath.Join(base, "opencode.jsonc")
|
||||
existing, _ := os.ReadFile(cfgPath)
|
||||
existing, err := common.ReadExistingFile(cfgPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %s: %w", cfgPath, err)
|
||||
}
|
||||
|
||||
// Build the provider map, then absorb any existing providers at the same
|
||||
// gateway URL so duplicates don't accumulate across apply runs.
|
||||
@@ -105,14 +112,12 @@ func (a *Adapter) Render(b *canonical.Bundle) (*adapter.FileSet, error) {
|
||||
Content: merged,
|
||||
})
|
||||
|
||||
instructions := b.Instructions.Global
|
||||
if override, ok := b.Instructions.PerHarness[name]; ok && override != "" {
|
||||
instructions = override
|
||||
}
|
||||
// opencode has no native rules directory; rule content reaches it only via
|
||||
// the global AGENTS.md instructions file, so fold the rules in here.
|
||||
fs.Add(adapter.File{
|
||||
Dest: filepath.Join(base, "AGENTS.md"),
|
||||
Kind: adapter.RenderedFile,
|
||||
Content: []byte(instructions),
|
||||
Content: []byte(b.InstructionTextWithRules(name)),
|
||||
})
|
||||
|
||||
return fs, nil
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package opencode
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/lukaszraczylo/harness-sync/internal/adapter"
|
||||
"github.com/lukaszraczylo/harness-sync/internal/canonical"
|
||||
)
|
||||
|
||||
func TestOpencodeRendersAgentsSymlinkAndFoldsRules(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
ad := New(WithHome(home))
|
||||
b := &canonical.Bundle{
|
||||
Root: "/canon",
|
||||
Instructions: canonical.Instructions{Global: "# global"},
|
||||
Rules: []canonical.Rule{{Name: "go", Body: "# Go\n\ngofmt always"}},
|
||||
}
|
||||
fs, err := ad.Render(b)
|
||||
require.NoError(t, err)
|
||||
|
||||
seen := map[string]adapter.File{}
|
||||
fs.ForEach(func(f adapter.File) { seen[f.Dest] = f })
|
||||
|
||||
agentsDest := filepath.Join(home, ".config", "opencode", "agents")
|
||||
assert.Equal(t, adapter.SymlinkDir, seen[agentsDest].Kind)
|
||||
assert.Equal(t, "/canon/agents", seen[agentsDest].SymlinkTarget)
|
||||
|
||||
agentsMD := filepath.Join(home, ".config", "opencode", "AGENTS.md")
|
||||
assert.Equal(t, adapter.RenderedFile, seen[agentsMD].Kind)
|
||||
body := string(seen[agentsMD].Content)
|
||||
assert.Contains(t, body, "# global")
|
||||
assert.Contains(t, body, "gofmt always")
|
||||
}
|
||||
|
||||
func TestOpencodeImportsAgents(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
agentsDir := filepath.Join(home, ".config", "opencode", "agents")
|
||||
require.NoError(t, os.MkdirAll(agentsDir, 0o750))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(agentsDir, "review.md"),
|
||||
[]byte("---\nname: review\ndescription: d\n---\nbody"), 0o600))
|
||||
|
||||
ad := New(WithHome(home))
|
||||
res, err := ad.Import(home)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, res.Agents, 1)
|
||||
assert.Equal(t, "review", res.Agents[0].Name)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package pi
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/lukaszraczylo/harness-sync/internal/adapter"
|
||||
)
|
||||
|
||||
func importFrom(home string) (*adapter.ImportResult, error) {
|
||||
base := filepath.Join(home, ".pi", "agent")
|
||||
res := &adapter.ImportResult{}
|
||||
|
||||
if body, err := os.ReadFile(filepath.Join(base, "AGENTS.md")); err == nil {
|
||||
res.Instructions = string(body)
|
||||
} else if !os.IsNotExist(err) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
// Package pi is the Pi coding agent harness adapter.
|
||||
package pi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/lukaszraczylo/harness-sync/internal/adapter"
|
||||
"github.com/lukaszraczylo/harness-sync/internal/adapter/common"
|
||||
"github.com/lukaszraczylo/harness-sync/internal/canonical"
|
||||
)
|
||||
|
||||
const name = "pi"
|
||||
|
||||
// Adapter implements adapter.Adapter for the Pi coding agent harness.
|
||||
type Adapter struct {
|
||||
*adapter.Base
|
||||
}
|
||||
|
||||
// WithHome overrides the home directory used to resolve target paths.
|
||||
func WithHome(h string) adapter.BaseOption { return func(b *adapter.Base) { b.Home = h } }
|
||||
|
||||
// New returns a new Adapter with the given options applied.
|
||||
func New(opts ...adapter.BaseOption) *Adapter {
|
||||
return &Adapter{Base: adapter.NewBase(opts...)}
|
||||
}
|
||||
|
||||
// Name returns the harness identifier.
|
||||
func (a *Adapter) Name() string { return name }
|
||||
|
||||
// Capabilities declares what pi harness-sync manages.
|
||||
func (a *Adapter) Capabilities() adapter.HarnessCapabilities {
|
||||
return adapter.HarnessCapabilities{
|
||||
ManagesProviders: true,
|
||||
ManagesModels: true,
|
||||
ManagesMCP: false,
|
||||
ManagesSkills: true,
|
||||
ManagesAgents: false,
|
||||
ManagesRules: true,
|
||||
ManagesInstructions: true,
|
||||
HasBuiltInSub: false,
|
||||
}
|
||||
}
|
||||
|
||||
// Detect returns true when ~/.pi/agent exists.
|
||||
func (a *Adapter) Detect() bool {
|
||||
_, err := os.Stat(filepath.Join(a.Home, ".pi", "agent"))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// Render produces the FileSet that applies the canonical bundle to Pi.
|
||||
func (a *Adapter) Render(b *canonical.Bundle) (*adapter.FileSet, error) {
|
||||
fs := adapter.NewFileSet()
|
||||
base := filepath.Join(a.Home, ".pi", "agent")
|
||||
|
||||
fs.Add(adapter.File{
|
||||
Dest: filepath.Join(base, "skills"),
|
||||
Kind: adapter.SymlinkDir,
|
||||
SymlinkTarget: filepath.Join(b.Root, "skills"),
|
||||
})
|
||||
|
||||
if instr := b.InstructionTextWithRules(name); instr != "" {
|
||||
fs.Add(adapter.File{
|
||||
Dest: filepath.Join(base, "AGENTS.md"),
|
||||
Kind: adapter.RenderedFile,
|
||||
Content: []byte(instr),
|
||||
})
|
||||
}
|
||||
|
||||
cfgPath := filepath.Join(base, "settings.json")
|
||||
existing, err := common.ReadExistingFile(cfgPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %s: %w", cfgPath, err)
|
||||
}
|
||||
|
||||
overlay := map[string]any{}
|
||||
if b.Profile.Gateway.DefaultModel != "" {
|
||||
overlay["defaultProvider"] = common.GatewayProviderKey(b.Profile.Gateway.URL)
|
||||
overlay["defaultModel"] = b.Profile.Gateway.DefaultModel
|
||||
}
|
||||
if len(overlay) > 0 {
|
||||
merged, err := common.MergeJSONKeys(existing, overlay)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fs.Add(adapter.File{
|
||||
Dest: cfgPath,
|
||||
Kind: adapter.RenderedFile,
|
||||
Content: merged,
|
||||
})
|
||||
}
|
||||
|
||||
if modelsContent, err := piModelsJSON(b); err != nil {
|
||||
return nil, err
|
||||
} else if len(modelsContent) > 0 {
|
||||
fs.Add(adapter.File{
|
||||
Dest: filepath.Join(base, "models.json"),
|
||||
Kind: adapter.RenderedFile,
|
||||
Content: modelsContent,
|
||||
})
|
||||
}
|
||||
|
||||
return fs, nil
|
||||
}
|
||||
|
||||
func piModelsJSON(b *canonical.Bundle) ([]byte, error) {
|
||||
if b.Profile.Gateway.URL == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
modelEntries := make([]map[string]any, 0, len(b.Profile.Models))
|
||||
for _, m := range b.Profile.Models {
|
||||
entry := map[string]any{"id": m.ID}
|
||||
if m.Alias != "" {
|
||||
entry["name"] = m.Alias
|
||||
}
|
||||
modelEntries = append(modelEntries, entry)
|
||||
}
|
||||
if len(modelEntries) == 0 && b.Profile.Gateway.DefaultModel != "" {
|
||||
modelEntries = append(modelEntries, map[string]any{"id": b.Profile.Gateway.DefaultModel})
|
||||
}
|
||||
|
||||
provider := map[string]any{
|
||||
"baseUrl": b.Profile.Gateway.URL,
|
||||
"api": "openai-completions",
|
||||
"apiKey": b.Profile.Gateway.Token,
|
||||
}
|
||||
if len(modelEntries) > 0 {
|
||||
provider["models"] = modelEntries
|
||||
}
|
||||
|
||||
body, err := json.MarshalIndent(map[string]any{
|
||||
"providers": map[string]any{
|
||||
common.GatewayProviderKey(b.Profile.Gateway.URL): provider,
|
||||
},
|
||||
}, "", " ")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return append(body, '\n'), nil
|
||||
}
|
||||
|
||||
// Import reads Pi config from home and returns a canonical ImportResult.
|
||||
func (a *Adapter) Import(home string) (*adapter.ImportResult, error) {
|
||||
return importFrom(home)
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package pi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/lukaszraczylo/harness-sync/internal/adapter"
|
||||
"github.com/lukaszraczylo/harness-sync/internal/canonical"
|
||||
)
|
||||
|
||||
func TestPiRender(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
ad := New(WithHome(home))
|
||||
b := &canonical.Bundle{
|
||||
Root: "/canon",
|
||||
Profile: canonical.Profile{
|
||||
Gateway: canonical.Gateway{URL: "https://gw", Token: "dummy", DefaultModel: "sonnet"},
|
||||
Models: []canonical.Model{{ID: "claude-sonnet-4-6", Alias: "Sonnet"}},
|
||||
},
|
||||
Instructions: canonical.Instructions{Global: "# global"},
|
||||
}
|
||||
fs, err := ad.Render(b)
|
||||
require.NoError(t, err)
|
||||
|
||||
seen := map[string]adapter.File{}
|
||||
fs.ForEach(func(f adapter.File) { seen[f.Dest] = f })
|
||||
|
||||
skillsDest := filepath.Join(home, ".pi", "agent", "skills")
|
||||
assert.Equal(t, adapter.SymlinkDir, seen[skillsDest].Kind)
|
||||
assert.Equal(t, "/canon/skills", seen[skillsDest].SymlinkTarget)
|
||||
|
||||
agentsDest := filepath.Join(home, ".pi", "agent", "AGENTS.md")
|
||||
assert.Equal(t, adapter.RenderedFile, seen[agentsDest].Kind)
|
||||
assert.Contains(t, string(seen[agentsDest].Content), "# global")
|
||||
|
||||
settingsDest := filepath.Join(home, ".pi", "agent", "settings.json")
|
||||
var settings map[string]any
|
||||
require.NoError(t, json.Unmarshal(seen[settingsDest].Content, &settings))
|
||||
assert.Equal(t, "hs-gw", settings["defaultProvider"])
|
||||
assert.Equal(t, "sonnet", settings["defaultModel"])
|
||||
|
||||
modelsDest := filepath.Join(home, ".pi", "agent", "models.json")
|
||||
var models map[string]any
|
||||
require.NoError(t, json.Unmarshal(seen[modelsDest].Content, &models))
|
||||
providers := models["providers"].(map[string]any)
|
||||
gw := providers["hs-gw"].(map[string]any)
|
||||
assert.Equal(t, "https://gw", gw["baseUrl"])
|
||||
assert.Equal(t, "openai-completions", gw["api"])
|
||||
assert.Equal(t, "dummy", gw["apiKey"])
|
||||
modelList := gw["models"].([]any)
|
||||
first := modelList[0].(map[string]any)
|
||||
assert.Equal(t, "claude-sonnet-4-6", first["id"])
|
||||
assert.Equal(t, "Sonnet", first["name"])
|
||||
}
|
||||
|
||||
func TestPiRenderMergesExistingSettings(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
base := filepath.Join(home, ".pi", "agent")
|
||||
require.NoError(t, os.MkdirAll(base, 0o750))
|
||||
|
||||
existing := map[string]any{
|
||||
"theme": "light",
|
||||
"defaultThinkingLevel": "high",
|
||||
}
|
||||
body, _ := json.Marshal(existing)
|
||||
require.NoError(t, os.WriteFile(filepath.Join(base, "settings.json"), body, 0o600))
|
||||
|
||||
ad := New(WithHome(home))
|
||||
b := &canonical.Bundle{Profile: canonical.Profile{Gateway: canonical.Gateway{URL: "https://gw", DefaultModel: "sonnet"}}}
|
||||
fs, err := ad.Render(b)
|
||||
require.NoError(t, err)
|
||||
|
||||
seen := map[string]adapter.File{}
|
||||
fs.ForEach(func(f adapter.File) { seen[f.Dest] = f })
|
||||
|
||||
var parsed map[string]any
|
||||
require.NoError(t, json.Unmarshal(seen[filepath.Join(base, "settings.json")].Content, &parsed))
|
||||
assert.Equal(t, "light", parsed["theme"])
|
||||
assert.Equal(t, "high", parsed["defaultThinkingLevel"])
|
||||
assert.Equal(t, "hs-gw", parsed["defaultProvider"])
|
||||
assert.Equal(t, "sonnet", parsed["defaultModel"])
|
||||
}
|
||||
|
||||
func TestPiRenderWithoutGatewaySkipsProviderFiles(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
ad := New(WithHome(home))
|
||||
b := &canonical.Bundle{Root: "/canon"}
|
||||
fs, err := ad.Render(b)
|
||||
require.NoError(t, err)
|
||||
|
||||
seen := map[string]adapter.File{}
|
||||
fs.ForEach(func(f adapter.File) { seen[f.Dest] = f })
|
||||
|
||||
assert.Contains(t, seen, filepath.Join(home, ".pi", "agent", "skills"))
|
||||
assert.NotContains(t, seen, filepath.Join(home, ".pi", "agent", "settings.json"))
|
||||
assert.NotContains(t, seen, filepath.Join(home, ".pi", "agent", "models.json"))
|
||||
}
|
||||
|
||||
func TestPiImport(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
base := filepath.Join(home, ".pi", "agent")
|
||||
require.NoError(t, os.MkdirAll(base, 0o750))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(base, "AGENTS.md"), []byte("# global"), 0o600))
|
||||
|
||||
ad := New(WithHome(home))
|
||||
res, err := ad.Import(home)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "# global", res.Instructions)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package zed
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/lukaszraczylo/harness-sync/internal/adapter"
|
||||
"github.com/lukaszraczylo/harness-sync/internal/canonical"
|
||||
)
|
||||
|
||||
func TestZedFoldsRulesIntoAGENTS(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
b := &canonical.Bundle{
|
||||
Instructions: canonical.Instructions{Global: "# global"},
|
||||
Rules: []canonical.Rule{{Name: "ts", Body: "# TS\n\nstrict mode"}},
|
||||
}
|
||||
fs, err := New(WithHome(home)).Render(b)
|
||||
require.NoError(t, err)
|
||||
seen := map[string]adapter.File{}
|
||||
fs.ForEach(func(f adapter.File) { seen[f.Dest] = f })
|
||||
|
||||
agentsMD := filepath.Join(home, ".config", "zed", "AGENTS.md")
|
||||
require.Contains(t, seen, agentsMD)
|
||||
assert.Equal(t, adapter.RenderedFile, seen[agentsMD].Kind)
|
||||
body := string(seen[agentsMD].Content)
|
||||
assert.Contains(t, body, "# global")
|
||||
assert.Contains(t, body, "strict mode")
|
||||
}
|
||||
@@ -7,6 +7,7 @@ package zed
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
@@ -18,21 +19,16 @@ import (
|
||||
const name = "zed"
|
||||
|
||||
// Adapter implements adapter.Adapter for the Zed harness.
|
||||
type Adapter struct{ home string }
|
||||
type Adapter struct {
|
||||
*adapter.Base
|
||||
}
|
||||
|
||||
// Option configures an Adapter.
|
||||
type Option func(*Adapter)
|
||||
|
||||
// WithHome overrides the home directory (defaults to os.UserHomeDir).
|
||||
func WithHome(h string) Option { return func(a *Adapter) { a.home = h } }
|
||||
// WithHome overrides the home directory used to resolve target paths.
|
||||
func WithHome(h string) adapter.BaseOption { return func(b *adapter.Base) { b.Home = h } }
|
||||
|
||||
// New returns a new Adapter with the given options applied.
|
||||
func New(opts ...Option) *Adapter {
|
||||
a := &Adapter{home: common.DefaultHome()}
|
||||
for _, o := range opts {
|
||||
o(a)
|
||||
}
|
||||
return a
|
||||
func New(opts ...adapter.BaseOption) *Adapter {
|
||||
return &Adapter{Base: adapter.NewBase(opts...)}
|
||||
}
|
||||
|
||||
// Name returns the harness identifier.
|
||||
@@ -46,14 +42,15 @@ func (a *Adapter) Capabilities() adapter.HarnessCapabilities {
|
||||
ManagesModels: true,
|
||||
ManagesMCP: false, // Agent panel uses Extensions; context_servers key causes serde parse errors
|
||||
ManagesSkills: false,
|
||||
ManagesInstructions: false,
|
||||
ManagesRules: true,
|
||||
ManagesInstructions: true,
|
||||
HasBuiltInSub: false,
|
||||
}
|
||||
}
|
||||
|
||||
// Detect returns true when ~/.config/zed/ exists.
|
||||
func (a *Adapter) Detect() bool {
|
||||
_, err := os.Stat(filepath.Join(a.home, ".config", "zed"))
|
||||
_, err := os.Stat(filepath.Join(a.Home, ".config", "zed"))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
@@ -68,8 +65,11 @@ func (a *Adapter) Detect() bool {
|
||||
// pre-existing parse errors from user-configured entries.
|
||||
func (a *Adapter) Render(b *canonical.Bundle) (*adapter.FileSet, error) {
|
||||
fs := adapter.NewFileSet()
|
||||
cfgPath := filepath.Join(a.home, ".config", "zed", "settings.json")
|
||||
existing, _ := os.ReadFile(cfgPath)
|
||||
cfgPath := filepath.Join(a.Home, ".config", "zed", "settings.json")
|
||||
existing, err := common.ReadExistingFile(cfgPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %s: %w", cfgPath, err)
|
||||
}
|
||||
|
||||
// Set context_servers to nil so MergeJSONKeys removes the key entirely,
|
||||
// clearing any entries that trigger the serde ContextServerSettingsContent bug.
|
||||
@@ -98,6 +98,17 @@ func (a *Adapter) Render(b *canonical.Bundle) (*adapter.FileSet, error) {
|
||||
NoMerge: true,
|
||||
})
|
||||
|
||||
// Zed reads personal/global instructions from ~/.config/zed/AGENTS.md
|
||||
// (always-on for the Agent across all projects). Zed has no rules directory,
|
||||
// so fold rules into it.
|
||||
if instr := b.InstructionTextWithRules(name); instr != "" {
|
||||
fs.Add(adapter.File{
|
||||
Dest: filepath.Join(a.Home, ".config", "zed", "AGENTS.md"),
|
||||
Kind: adapter.RenderedFile,
|
||||
Content: []byte(instr),
|
||||
})
|
||||
}
|
||||
|
||||
return fs, nil
|
||||
}
|
||||
|
||||
|
||||
+38
-9
@@ -9,6 +9,7 @@ import (
|
||||
"path/filepath"
|
||||
|
||||
"github.com/lukaszraczylo/harness-sync/internal/adapter"
|
||||
"github.com/lukaszraczylo/harness-sync/internal/adapter/common"
|
||||
"github.com/lukaszraczylo/harness-sync/internal/canonical"
|
||||
"github.com/lukaszraczylo/harness-sync/internal/gitx"
|
||||
"github.com/lukaszraczylo/harness-sync/internal/merge"
|
||||
@@ -42,6 +43,11 @@ type Action struct {
|
||||
// Run renders all adapters and writes their FileSets to disk.
|
||||
// Conflicts are recorded as <dest>.rej files; processing continues past conflicts.
|
||||
//
|
||||
// When Options.Repo is nil the canonical repo is auto-opened from Bundle.Root.
|
||||
// If that directory is not a git repository the commit step is silently
|
||||
// skipped — useful for one-off renders (CI smoke tests, dry-runs) where
|
||||
// initialising a repo would be more surprising than useful.
|
||||
//
|
||||
// IMPORTANT: harness-sync intentionally does NOT resolve ${VAR} references in
|
||||
// canonical configs. Every supported harness performs its own env-var
|
||||
// expansion at MCP launch / config-load time, so resolving here would only
|
||||
@@ -66,13 +72,30 @@ func Run(opt Options) (*Report, error) {
|
||||
return rep, renderErr
|
||||
}
|
||||
}
|
||||
if !opt.DryRun && rep.Written > 0 && opt.Repo != nil {
|
||||
if err := opt.Repo.AddAll(); err != nil {
|
||||
return rep, err
|
||||
}
|
||||
if err := opt.Repo.Commit(fmt.Sprintf("apply: %d files, %d conflicts", rep.Written, rep.Conflicts)); err != nil {
|
||||
return rep, err
|
||||
}
|
||||
if opt.DryRun || rep.Written == 0 {
|
||||
return rep, nil
|
||||
}
|
||||
repo := opt.Repo
|
||||
if repo == nil {
|
||||
repo = gitx.New(opt.Bundle.Root)
|
||||
}
|
||||
if !repo.IsRepo() {
|
||||
return rep, nil
|
||||
}
|
||||
if err := repo.AddAll(); err != nil {
|
||||
return rep, err
|
||||
}
|
||||
dirty, err := repo.HasStagedChanges()
|
||||
if err != nil {
|
||||
return rep, err
|
||||
}
|
||||
if !dirty {
|
||||
// Nothing changed inside the canonical repo (writes were outside it,
|
||||
// e.g. symlinks to temp dirs in tests). Skip the no-op commit.
|
||||
return rep, nil
|
||||
}
|
||||
if err := repo.Commit(fmt.Sprintf("apply: %d files, %d conflicts", rep.Written, rep.Conflicts)); err != nil {
|
||||
return rep, err
|
||||
}
|
||||
return rep, nil
|
||||
}
|
||||
@@ -93,8 +116,14 @@ func statePath(root, adapterName, dest string) string {
|
||||
|
||||
func handleRendered(opt Options, adapterName string, f adapter.File, rep *Report) error {
|
||||
sp := statePath(opt.Bundle.Root, adapterName, f.Dest)
|
||||
base, _ := os.ReadFile(sp)
|
||||
current, _ := os.ReadFile(f.Dest)
|
||||
base, readErr := common.ReadExistingFile(sp)
|
||||
if readErr != nil {
|
||||
return fmt.Errorf("read state %s: %w", sp, readErr)
|
||||
}
|
||||
current, readErr := common.ReadExistingFile(f.Dest)
|
||||
if readErr != nil {
|
||||
return fmt.Errorf("read target %s: %w", f.Dest, readErr)
|
||||
}
|
||||
|
||||
if string(current) == string(f.Content) {
|
||||
rep.Skipped++
|
||||
|
||||
@@ -584,6 +584,160 @@ func TestApplyUnknownFileKind(t *testing.T) {
|
||||
assert.Contains(t, err.Error(), "unknown file kind")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TestApplyPropagatesReadErrors — regression for the silent-read footgun.
|
||||
// A target file in a directory we can no longer read must surface as an
|
||||
// error from Run, not as a fast-forward overwrite.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestApplyPropagatesReadErrors(t *testing.T) {
|
||||
if os.Geteuid() == 0 {
|
||||
t.Skip("running as root; cannot test permission denial")
|
||||
}
|
||||
root := t.TempDir()
|
||||
targetDir := t.TempDir()
|
||||
target := filepath.Join(targetDir, "out.txt")
|
||||
require.NoError(t, os.WriteFile(target, []byte("user-content\n"), 0o600))
|
||||
require.NoError(t, initCanonical(root))
|
||||
|
||||
// Strip read perms on the target's parent so os.ReadFile fails.
|
||||
require.NoError(t, os.Chmod(targetDir, 0o000))
|
||||
t.Cleanup(func() { _ = os.Chmod(targetDir, 0o755) })
|
||||
|
||||
ad := &stubAdapter{name: "stub", files: []adapter.File{
|
||||
{Dest: target, Kind: adapter.RenderedFile, Content: []byte("new-render\n")},
|
||||
}}
|
||||
_, err := Run(Options{
|
||||
Bundle: &canonical.Bundle{Root: root},
|
||||
Adapters: []adapter.Adapter{ad},
|
||||
Repo: gitx.New(root),
|
||||
})
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "read target")
|
||||
|
||||
// User's on-disk file must be untouched.
|
||||
_ = os.Chmod(targetDir, 0o755)
|
||||
body, rerr := os.ReadFile(target)
|
||||
require.NoError(t, rerr)
|
||||
assert.Equal(t, "user-content\n", string(body),
|
||||
"target must not be overwritten when read fails")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TestApplyAutoOpensRepoFromBundleRoot — regression: callers no longer need
|
||||
// to pre-construct a *gitx.Repo. Run opens one from Bundle.Root, skips
|
||||
// commit gracefully when the root is not a git repo, and commits when it is.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestApplyAutoOpensRepoFromBundleRoot(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
target := filepath.Join(t.TempDir(), "out.txt")
|
||||
require.NoError(t, initCanonical(root))
|
||||
|
||||
ad := &stubAdapter{name: "stub", files: []adapter.File{
|
||||
{Dest: target, Kind: adapter.RenderedFile, Content: []byte("auto\n")},
|
||||
}}
|
||||
// Intentionally pass Repo: nil — the new behaviour should open one itself.
|
||||
rep, err := Run(Options{
|
||||
Bundle: &canonical.Bundle{Root: root},
|
||||
Adapters: []adapter.Adapter{ad},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1, rep.Written)
|
||||
|
||||
// git log should have a new commit from apply, on top of the init one.
|
||||
out, gitErr := runGit(root, "log", "--oneline")
|
||||
require.NoError(t, gitErr)
|
||||
assert.GreaterOrEqual(t, countLines(out), 2)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TestApplyNoRepoSkipsCommit — when Bundle.Root isn't a git repo, Run must
|
||||
// still succeed (no error, no commit attempt). One-off renders / dry-runs.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestApplyNoRepoSkipsCommit(t *testing.T) {
|
||||
root := t.TempDir() // NOT initCanonical — no .git
|
||||
target := filepath.Join(t.TempDir(), "out.txt")
|
||||
|
||||
ad := &stubAdapter{name: "stub", files: []adapter.File{
|
||||
{Dest: target, Kind: adapter.RenderedFile, Content: []byte("x\n")},
|
||||
}}
|
||||
rep, err := Run(Options{
|
||||
Bundle: &canonical.Bundle{Root: root},
|
||||
Adapters: []adapter.Adapter{ad},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1, rep.Written)
|
||||
body, rerr := os.ReadFile(target)
|
||||
require.NoError(t, rerr)
|
||||
assert.Equal(t, "x\n", string(body))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TestApplySkipsNoOpCommit — symlinks at a path outside the canonical repo
|
||||
// do not write a state snapshot inside the repo (handleSymlink has no
|
||||
// state-tracking), so git has nothing to commit. apply.Run must detect
|
||||
// "no staged changes" and skip the commit instead of failing with
|
||||
// "nothing to commit" from git itself.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestApplySkipsNoOpCommit(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
require.NoError(t, initCanonical(root))
|
||||
targetDir := t.TempDir()
|
||||
target := filepath.Join(targetDir, "outside-link")
|
||||
real := filepath.Join(targetDir, "real.txt")
|
||||
require.NoError(t, os.WriteFile(real, []byte("real\n"), 0o600))
|
||||
|
||||
ad := &stubAdapter{name: "stub", files: []adapter.File{
|
||||
{Dest: target, Kind: adapter.SymlinkFile, SymlinkTarget: real},
|
||||
}}
|
||||
rep, err := Run(Options{
|
||||
Bundle: &canonical.Bundle{Root: root},
|
||||
Adapters: []adapter.Adapter{ad},
|
||||
// Repo: nil — auto-open from Bundle.Root (which IS a git repo).
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1, rep.Written)
|
||||
|
||||
// Symlink exists on disk.
|
||||
got, lerr := os.Readlink(target)
|
||||
require.NoError(t, lerr)
|
||||
assert.Equal(t, real, got)
|
||||
|
||||
// No extra commit — still just the init commit. A failed "nothing to
|
||||
// commit" would surface here as an error from Run.
|
||||
out, gitErr := runGit(root, "log", "--oneline")
|
||||
require.NoError(t, gitErr)
|
||||
assert.Equal(t, 1, countLines(out),
|
||||
"expected only the init commit; symlink outside canonical root should not create one")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TestApplyCommitMessageHasCounts — commit message includes the file and
|
||||
// conflict counts so the rollback story is auditable from git log alone.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestApplyCommitMessageHasCounts(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
target := filepath.Join(t.TempDir(), "msg.txt")
|
||||
require.NoError(t, initCanonical(root))
|
||||
|
||||
ad := &stubAdapter{name: "stub", files: []adapter.File{
|
||||
{Dest: target, Kind: adapter.RenderedFile, Content: []byte("m\n")},
|
||||
}}
|
||||
_, err := Run(Options{
|
||||
Bundle: &canonical.Bundle{Root: root},
|
||||
Adapters: []adapter.Adapter{ad},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
out, gitErr := runGit(root, "log", "-1", "--pretty=%s")
|
||||
require.NoError(t, gitErr)
|
||||
assert.Contains(t, out, "apply: 1 files, 0 conflicts")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package canonical
|
||||
|
||||
import "strings"
|
||||
|
||||
// InstructionText returns the instruction body a harness should receive: the
|
||||
// per-harness override when one is set, otherwise the global instructions.
|
||||
func (b *Bundle) InstructionText(harness string) string {
|
||||
if override, ok := b.Instructions.PerHarness[harness]; ok && override != "" {
|
||||
return override
|
||||
}
|
||||
return b.Instructions.Global
|
||||
}
|
||||
|
||||
// InstructionTextWithRules returns InstructionText for the harness with every
|
||||
// canonical rule body folded in. Harnesses without a native rules directory
|
||||
// (everything except claude-code/kilo) only receive rule content this way —
|
||||
// via their global instructions file. Rule frontmatter is stripped so the
|
||||
// folded output stays clean; bodies are joined in load order (deterministic).
|
||||
func (b *Bundle) InstructionTextWithRules(harness string) string {
|
||||
base := b.InstructionText(harness)
|
||||
var sb strings.Builder
|
||||
sb.WriteString(base)
|
||||
for _, r := range b.Rules {
|
||||
body := strings.TrimSpace(stripFrontmatter(r.Body))
|
||||
if body == "" {
|
||||
continue
|
||||
}
|
||||
if sb.Len() > 0 {
|
||||
sb.WriteString("\n\n")
|
||||
}
|
||||
sb.WriteString(body)
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// stripFrontmatter removes a leading YAML frontmatter block ("---\n…\n---") so
|
||||
// folding a rule into a plain instructions file does not leak its metadata.
|
||||
func stripFrontmatter(s string) string {
|
||||
if !strings.HasPrefix(s, "---\n") {
|
||||
return s
|
||||
}
|
||||
end := strings.Index(s[4:], "\n---")
|
||||
if end == -1 {
|
||||
return s
|
||||
}
|
||||
return strings.TrimPrefix(s[4+end+len("\n---"):], "\n")
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package canonical
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestInstructionText(t *testing.T) {
|
||||
t.Run("global when no override", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
b := Bundle{Instructions: Instructions{Global: "G"}}
|
||||
assert.Equal(t, "G", b.InstructionText("zed"))
|
||||
})
|
||||
t.Run("per-harness override wins", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
b := Bundle{Instructions: Instructions{Global: "G", PerHarness: map[string]string{"zed": "Z"}}}
|
||||
assert.Equal(t, "Z", b.InstructionText("zed"))
|
||||
})
|
||||
t.Run("empty override falls back to global", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
b := Bundle{Instructions: Instructions{Global: "G", PerHarness: map[string]string{"zed": ""}}}
|
||||
assert.Equal(t, "G", b.InstructionText("zed"))
|
||||
})
|
||||
t.Run("empty everything", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
b := Bundle{}
|
||||
assert.Equal(t, "", b.InstructionText("zed"))
|
||||
})
|
||||
}
|
||||
|
||||
func TestInstructionTextWithRules(t *testing.T) {
|
||||
t.Run("folds rules after global", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
b := Bundle{
|
||||
Instructions: Instructions{Global: "# Global"},
|
||||
Rules: []Rule{
|
||||
{Name: "a", Body: "# Rule A\n\nbe concise"},
|
||||
{Name: "b", Body: "# Rule B\n\nbe safe"},
|
||||
},
|
||||
}
|
||||
got := b.InstructionTextWithRules("opencode")
|
||||
assert.Equal(t, "# Global\n\n# Rule A\n\nbe concise\n\n# Rule B\n\nbe safe", got)
|
||||
})
|
||||
|
||||
t.Run("strips rule frontmatter", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
b := Bundle{
|
||||
Instructions: Instructions{Global: "G"},
|
||||
Rules: []Rule{
|
||||
{Name: "scoped", Body: "---\nname: scoped\npaths: \"**/*.go\"\n---\n# Go\n\ngofmt"},
|
||||
},
|
||||
}
|
||||
got := b.InstructionTextWithRules("opencode")
|
||||
assert.Equal(t, "G\n\n# Go\n\ngofmt", got)
|
||||
assert.NotContains(t, got, "paths:")
|
||||
assert.NotContains(t, got, "---")
|
||||
})
|
||||
|
||||
t.Run("no rules returns plain instruction text", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
b := Bundle{Instructions: Instructions{Global: "G"}}
|
||||
assert.Equal(t, "G", b.InstructionTextWithRules("opencode"))
|
||||
})
|
||||
|
||||
t.Run("empty global still emits rules", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
b := Bundle{Rules: []Rule{{Name: "a", Body: "rule body"}}}
|
||||
assert.Equal(t, "rule body", b.InstructionTextWithRules("opencode"))
|
||||
})
|
||||
|
||||
t.Run("blank rule bodies are skipped", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
b := Bundle{
|
||||
Instructions: Instructions{Global: "G"},
|
||||
Rules: []Rule{
|
||||
{Name: "empty", Body: " \n "},
|
||||
{Name: "real", Body: "keep"},
|
||||
},
|
||||
}
|
||||
assert.Equal(t, "G\n\nkeep", b.InstructionTextWithRules("opencode"))
|
||||
})
|
||||
}
|
||||
|
||||
func TestStripFrontmatter(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in string
|
||||
want string
|
||||
}{
|
||||
{"no frontmatter", "# Title\nbody", "# Title\nbody"},
|
||||
{"with frontmatter", "---\nname: x\n---\n# Title", "# Title"},
|
||||
{"unterminated frontmatter left intact", "---\nname: x\nbody", "---\nname: x\nbody"},
|
||||
{"empty", "", ""},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
assert.Equal(t, tt.want, stripFrontmatter(tt.in))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -72,6 +72,14 @@ func LoadFS(fs fsx.FS, root string) (*Bundle, error) {
|
||||
b.Agents = append(b.Agents, Agent(m))
|
||||
}
|
||||
|
||||
rules, err := loadMarkdownDirFS(fs, filepath.Join(root, "rules"), "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, m := range rules {
|
||||
b.Rules = append(b.Rules, Rule(m))
|
||||
}
|
||||
|
||||
b.Instructions.PerHarness = map[string]string{}
|
||||
body, err := readFileIfExistsFS(fs, filepath.Join(root, "instructions", "global.md"))
|
||||
if err != nil {
|
||||
|
||||
@@ -28,6 +28,10 @@ func TestLoad(t *testing.T) {
|
||||
require.Len(t, b.Agents, 1)
|
||||
assert.Equal(t, "sample", b.Agents[0].Name)
|
||||
|
||||
require.Len(t, b.Rules, 1)
|
||||
assert.Equal(t, "sample-rule", b.Rules[0].Name)
|
||||
assert.Contains(t, b.Rules[0].Body, "Always be concise.")
|
||||
|
||||
assert.Contains(t, b.Instructions.Global, "Be helpful.")
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
# Sample Rule
|
||||
|
||||
Always be concise.
|
||||
@@ -43,6 +43,7 @@ type MCPRegistry struct {
|
||||
|
||||
type MCPServer struct {
|
||||
Env map[string]string `yaml:"env,omitempty"`
|
||||
Headers map[string]string `yaml:"headers,omitempty"`
|
||||
Name string `yaml:"name"`
|
||||
Command string `yaml:"command,omitempty"`
|
||||
URL string `yaml:"url,omitempty"`
|
||||
@@ -64,6 +65,16 @@ type Agent struct {
|
||||
Path string
|
||||
}
|
||||
|
||||
// Rule is a topic-scoped instruction fragment (e.g. ~/.claude/rules/go.md).
|
||||
// Claude Code auto-loads a directory of these; harnesses without a native rules
|
||||
// directory receive the bodies folded into their global instructions file.
|
||||
type Rule struct {
|
||||
Name string
|
||||
Description string
|
||||
Body string
|
||||
Path string
|
||||
}
|
||||
|
||||
type Instructions struct {
|
||||
PerHarness map[string]string
|
||||
Global string
|
||||
@@ -76,6 +87,7 @@ type Bundle struct {
|
||||
Profile Profile
|
||||
Skills []Skill
|
||||
Agents []Agent
|
||||
Rules []Rule
|
||||
MCP MCPRegistry
|
||||
}
|
||||
|
||||
|
||||
+25
-3
@@ -93,6 +93,7 @@ func runImport(cmd *cobra.Command, reg *adapter.Registry, root, home string, pic
|
||||
}
|
||||
seenSkills := map[string]bool{}
|
||||
seenAgents := map[string]bool{}
|
||||
seenRules := map[string]bool{}
|
||||
seenMCP := map[string]bool{}
|
||||
var instructions []string
|
||||
|
||||
@@ -121,6 +122,14 @@ func runImport(cmd *cobra.Command, reg *adapter.Registry, root, home string, pic
|
||||
seenAgents[key] = true
|
||||
bundle.Agents = append(bundle.Agents, a)
|
||||
}
|
||||
for _, r := range res.Rules {
|
||||
key := r.Name + "|" + r.Body
|
||||
if seenRules[key] {
|
||||
continue
|
||||
}
|
||||
seenRules[key] = true
|
||||
bundle.Rules = append(bundle.Rules, r)
|
||||
}
|
||||
for _, m := range res.MCP {
|
||||
if seenMCP[m.Name] {
|
||||
continue
|
||||
@@ -153,8 +162,8 @@ func runImport(cmd *cobra.Command, reg *adapter.Registry, root, home string, pic
|
||||
return err
|
||||
}
|
||||
_, _ = fmt.Fprintf(cmd.OutOrStdout(),
|
||||
"imported from %v into %s\n skills: %d\n agents: %d\n mcp servers: %d\n instructions: %d source(s)\n",
|
||||
picked, root, len(bundle.Skills), len(bundle.Agents), len(bundle.MCP.Servers), len(instructions),
|
||||
"imported from %v into %s\n skills: %d\n agents: %d\n rules: %d\n mcp servers: %d\n instructions: %d source(s)\n",
|
||||
picked, root, len(bundle.Skills), len(bundle.Agents), len(bundle.Rules), len(bundle.MCP.Servers), len(instructions),
|
||||
)
|
||||
return nil
|
||||
}
|
||||
@@ -172,7 +181,7 @@ const importedProfileBody = "# harness-sync profile \xe2\x80\x94 generated by in
|
||||
"models: []\n"
|
||||
|
||||
func writeCanonical(root string, b *canonical.Bundle, picked []string) error {
|
||||
for _, sub := range []string{"profiles", "skills", "agents", "instructions"} {
|
||||
for _, sub := range []string{"profiles", "skills", "agents", "rules", "instructions"} {
|
||||
if err := os.MkdirAll(filepath.Join(root, sub), 0o750); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -233,6 +242,19 @@ func writeCanonical(root string, b *canonical.Bundle, picked []string) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, r := range b.Rules {
|
||||
rel := r.Path
|
||||
if rel == "" {
|
||||
rel = safeFilename(r.Name) + ".md"
|
||||
}
|
||||
path := filepath.Join(root, "rules", rel)
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(r.Body), 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if b.Instructions.Global != "" {
|
||||
if err := os.WriteFile(filepath.Join(root, "instructions", "global.md"),
|
||||
[]byte(b.Instructions.Global), 0o600); err != nil {
|
||||
|
||||
@@ -53,6 +53,34 @@ func TestInitImportWritesCanonical(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestInitImportsRules(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
home := t.TempDir()
|
||||
|
||||
reg := adapter.NewRegistry()
|
||||
reg.Register(&importableAdapter{
|
||||
name: "stub",
|
||||
res: &adapter.ImportResult{
|
||||
Rules: []canonical.Rule{
|
||||
{Name: "go", Body: "# Go\n\ngofmt", Path: "go.md"},
|
||||
{Name: "py", Body: "# Py\n\ntypes", Path: "py.md"},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
cmd := NewInit(reg)
|
||||
cmd.SetArgs([]string{"--root", root, "--home", home, "--from", "stub", "--no-prompt"})
|
||||
require.NoError(t, cmd.Execute())
|
||||
|
||||
assert.FileExists(t, filepath.Join(root, "rules", "go.md"))
|
||||
assert.FileExists(t, filepath.Join(root, "rules", "py.md"))
|
||||
|
||||
// Round-trips back through the loader.
|
||||
b, err := canonical.Load(root)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, b.Rules, 2)
|
||||
}
|
||||
|
||||
func makeStubReg() *adapter.Registry {
|
||||
reg := adapter.NewRegistry()
|
||||
reg.Register(&importableAdapter{
|
||||
|
||||
@@ -71,6 +71,17 @@ func (r *Repo) IsRepo() bool {
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// HasStagedChanges reports whether the index currently differs from HEAD.
|
||||
// Used by callers that want to skip a no-op `git commit` (commit exits 1
|
||||
// when there is nothing to commit, which is the wrong signal to propagate).
|
||||
func (r *Repo) HasStagedChanges() (bool, error) {
|
||||
b, err := r.run("status", "--porcelain")
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return len(bytes.TrimSpace(b)) > 0, nil
|
||||
}
|
||||
|
||||
// Revert undoes the last N commits with `git revert --no-edit HEAD~N..HEAD`.
|
||||
// n must be >= 1.
|
||||
func (r *Repo) Revert(n int) error {
|
||||
|
||||
@@ -41,3 +41,33 @@ func TestShowFileAtHead(t *testing.T) {
|
||||
_, err = r.ShowFileAtHead("nope.txt")
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func TestHasStagedChangesEmptyAfterInit(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
r := New(dir)
|
||||
require.NoError(t, r.Init())
|
||||
require.NoError(t, r.Configure("nobody", "[email protected]"))
|
||||
// No commits yet, working tree clean.
|
||||
dirty, err := r.HasStagedChanges()
|
||||
require.NoError(t, err)
|
||||
assert.False(t, dirty)
|
||||
}
|
||||
|
||||
func TestHasStagedChangesAfterAdd(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
r := New(dir)
|
||||
require.NoError(t, r.Init())
|
||||
require.NoError(t, r.Configure("nobody", "[email protected]"))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, "a.txt"), []byte("x"), 0o600))
|
||||
require.NoError(t, r.AddAll())
|
||||
|
||||
dirty, err := r.HasStagedChanges()
|
||||
require.NoError(t, err)
|
||||
assert.True(t, dirty)
|
||||
|
||||
// After commit, index matches HEAD again → no staged changes.
|
||||
require.NoError(t, r.Commit("c"))
|
||||
dirty, err = r.HasStagedChanges()
|
||||
require.NoError(t, err)
|
||||
assert.False(t, dirty)
|
||||
}
|
||||
|
||||
@@ -17,11 +17,15 @@ func TestInitApplyDiffCycle(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
root := filepath.Join(home, ".config", "harness-sync")
|
||||
|
||||
// Fake a claude-code install with one skill
|
||||
// Fake a claude-code install with one skill and one rule
|
||||
require.NoError(t, os.MkdirAll(filepath.Join(home, ".claude", "skills", "hi"), 0o750))
|
||||
require.NoError(t, os.WriteFile(
|
||||
filepath.Join(home, ".claude", "skills", "hi", "SKILL.md"),
|
||||
[]byte("---\nname: hi\n---\nbody"), 0o600))
|
||||
require.NoError(t, os.MkdirAll(filepath.Join(home, ".claude", "rules"), 0o750))
|
||||
require.NoError(t, os.WriteFile(
|
||||
filepath.Join(home, ".claude", "rules", "go.md"),
|
||||
[]byte("# Go Rules\n\ngofmt always"), 0o600))
|
||||
|
||||
run := func(args ...string) ([]byte, error) {
|
||||
cmd := exec.Command(bin, args...)
|
||||
@@ -33,6 +37,7 @@ func TestInitApplyDiffCycle(t *testing.T) {
|
||||
require.NoError(t, err, string(out))
|
||||
assert.FileExists(t, filepath.Join(root, "config.yaml"))
|
||||
assert.FileExists(t, filepath.Join(root, "skills", "hi", "SKILL.md"))
|
||||
assert.FileExists(t, filepath.Join(root, "rules", "go.md"))
|
||||
|
||||
// apply may produce conflicts on a freshly imported tree (because the
|
||||
// claude-code adapter merges into existing settings.json which differs
|
||||
@@ -85,7 +90,7 @@ func TestDetectListsAllAdapters(t *testing.T) {
|
||||
|
||||
// None should be detected in an empty HOME
|
||||
s := string(out)
|
||||
for _, name := range []string{"claude-code", "crush", "kilo", "opencode", "goose", "cagent", "zed"} {
|
||||
for _, name := range []string{"claude-code", "crush", "kilo", "opencode", "pi", "goose", "cagent", "zed"} {
|
||||
assert.Contains(t, s, name)
|
||||
}
|
||||
assert.Contains(t, s, "not detected")
|
||||
|
||||
Reference in New Issue
Block a user