copperhead 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +72 -9
  3. package/dist/agent/ledger.js +7 -0
  4. package/dist/agent/ledger.js.map +1 -1
  5. package/dist/agent/loop.js +303 -34
  6. package/dist/agent/loop.js.map +1 -1
  7. package/dist/agent/prompts.js +3 -1
  8. package/dist/agent/prompts.js.map +1 -1
  9. package/dist/agent/providers/anthropic.js +28 -13
  10. package/dist/agent/providers/anthropic.js.map +1 -1
  11. package/dist/agent/providers/codex.js +292 -0
  12. package/dist/agent/providers/codex.js.map +1 -0
  13. package/dist/agent/render.js +170 -0
  14. package/dist/agent/render.js.map +1 -0
  15. package/dist/agent/runmeta.js +124 -0
  16. package/dist/agent/runmeta.js.map +1 -0
  17. package/dist/agent/tools.js +117 -16
  18. package/dist/agent/tools.js.map +1 -1
  19. package/dist/agent/transcript.js +23 -0
  20. package/dist/agent/transcript.js.map +1 -1
  21. package/dist/cli.js +47 -11
  22. package/dist/cli.js.map +1 -1
  23. package/dist/commands/check.js +9 -2
  24. package/dist/commands/check.js.map +1 -1
  25. package/dist/commands/create.js +57 -3
  26. package/dist/commands/create.js.map +1 -1
  27. package/dist/commands/sync.js +3 -1
  28. package/dist/commands/sync.js.map +1 -1
  29. package/dist/config.js +16 -8
  30. package/dist/config.js.map +1 -1
  31. package/dist/kicad/cli.js +58 -8
  32. package/dist/kicad/cli.js.map +1 -1
  33. package/dist/memory/constraints.js +63 -3
  34. package/dist/memory/constraints.js.map +1 -1
  35. package/dist/memory/drift.js +31 -0
  36. package/dist/memory/drift.js.map +1 -1
  37. package/dist/memory/scaffold.js +2 -1
  38. package/dist/memory/scaffold.js.map +1 -1
  39. package/dist/memory/synap.js +152 -0
  40. package/dist/memory/synap.js.map +1 -0
  41. package/dist/util/git.js +125 -4
  42. package/dist/util/git.js.map +1 -1
  43. package/dist/util/preflight.js +24 -0
  44. package/dist/util/preflight.js.map +1 -0
  45. package/package.json +21 -6
  46. package/src/agent/ledger.ts +9 -1
  47. package/src/agent/loop.ts +333 -35
  48. package/src/agent/prompts.ts +3 -1
  49. package/src/agent/providers/anthropic.ts +40 -16
  50. package/src/agent/providers/codex.ts +339 -0
  51. package/src/agent/render.ts +194 -0
  52. package/src/agent/runmeta.ts +198 -0
  53. package/src/agent/tools.ts +119 -15
  54. package/src/agent/transcript.ts +49 -0
  55. package/src/agent/types.ts +1 -0
  56. package/src/cli.ts +51 -12
  57. package/src/commands/check.ts +9 -3
  58. package/src/commands/create.ts +61 -4
  59. package/src/commands/sync.ts +5 -0
  60. package/src/config.ts +29 -9
  61. package/src/kicad/cli.ts +60 -9
  62. package/src/memory/constraints.ts +90 -3
  63. package/src/memory/drift.ts +32 -0
  64. package/src/memory/scaffold.ts +2 -1
  65. package/src/memory/synap.ts +217 -0
  66. package/src/util/git.ts +134 -4
  67. package/src/util/preflight.ts +22 -0
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Cross-run memory via Synap (https://docs.maximem.ai).
3
+ *
4
+ * copperhead's own memory is per-repo and file-based: docs/DECISIONS.md, the
5
+ * constraint registry, the drift checker. Synap is the layer above that — what
6
+ * this user tends to want across every board they've ever asked about. It
7
+ * complements the docs; it does not replace them, and nothing here is a source
8
+ * of truth. Recalled text is advisory context in the system prompt, while
9
+ * as-built facts still come from the KiCad files.
10
+ *
11
+ * Three properties are load-bearing:
12
+ *
13
+ * 1. Opt-in. Inactive unless SYNAP_API_KEY is set, so the default install is
14
+ * unchanged and `check` stays network-free (it never constructs this).
15
+ * 2. Optional at runtime. @maximem/synap-js-sdk is an optionalDependency and is
16
+ * imported lazily through a non-literal specifier, so a missing package (or
17
+ * a host without the Python 3.11+ runtime its bridge needs) degrades to
18
+ * "no memory" instead of breaking the CLI.
19
+ * 3. Fail-soft on read, loud on write. A recall failure must never cost someone
20
+ * a design run; a record failure is reported, because silently losing writes
21
+ * lets memory drift away from what actually happened.
22
+ */
23
+ import { randomUUID } from 'node:crypto';
24
+ import { execa } from 'execa';
25
+ import { redactSecrets } from '../util/redact.js';
26
+
27
+ /** Wall-clock ceiling on any single Synap call. The bridge is a Python subprocess. */
28
+ const RECALL_TIMEOUT_MS = 10_000;
29
+ const RECORD_TIMEOUT_MS = 15_000;
30
+ const MAX_RECALLED = 8;
31
+
32
+ /**
33
+ * Structural subset of @maximem/synap-js-sdk's surface. Declared locally rather
34
+ * than imported so `tsc` succeeds when the optional dependency is absent.
35
+ */
36
+ interface SynapSearchItem {
37
+ memory: string;
38
+ score?: number;
39
+ contextType?: string;
40
+ }
41
+ interface SynapClientLike {
42
+ init(): Promise<void>;
43
+ searchMemory(input: {
44
+ userId: string;
45
+ customerId?: string;
46
+ query: string;
47
+ maxResults?: number;
48
+ }): Promise<{ results: SynapSearchItem[] }>;
49
+ addMemory(input: {
50
+ userId: string;
51
+ customerId: string;
52
+ conversationId?: string;
53
+ messages: Array<{ role?: 'user' | 'assistant'; content: string }>;
54
+ metadata?: Record<string, unknown>;
55
+ }): Promise<{ success: boolean }>;
56
+ shutdown(): Promise<void>;
57
+ }
58
+
59
+ export interface RunRecord {
60
+ request: string;
61
+ outcome: 'success' | 'refused';
62
+ summary: string;
63
+ changeId: string | null;
64
+ filesTouched: string[];
65
+ decisions: string[];
66
+ verification: string;
67
+ }
68
+
69
+ export interface SynapMemory {
70
+ /** Prior context relevant to this request, as a prompt-ready markdown block. */
71
+ recall(request: string): Promise<string | null>;
72
+ /** Persist a finished run. Rejects if the write fails. */
73
+ record(run: RunRecord): Promise<void>;
74
+ /** Stop the bridge subprocess. Always call this, or the CLI will not exit. */
75
+ close(): Promise<void>;
76
+ }
77
+
78
+ export function synapEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
79
+ return Boolean(env.SYNAP_API_KEY);
80
+ }
81
+
82
+ /**
83
+ * Identity for memory scoping. The git committer email is the natural stable
84
+ * user id here: it is already the identity every run is attributed to.
85
+ */
86
+ async function resolveUserId(repoRoot: string, env: NodeJS.ProcessEnv): Promise<string> {
87
+ if (env.SYNAP_USER_ID) return env.SYNAP_USER_ID;
88
+ try {
89
+ const { stdout } = await execa('git', ['config', 'user.email'], { cwd: repoRoot });
90
+ if (stdout.trim()) return stdout.trim();
91
+ } catch {
92
+ // not configured; fall through
93
+ }
94
+ return 'copperhead-local';
95
+ }
96
+
97
+ function withTimeout<T>(p: Promise<T>, ms: number, label: string): Promise<T> {
98
+ return new Promise<T>((resolve, reject) => {
99
+ const timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
100
+ p.then(
101
+ (v) => {
102
+ clearTimeout(timer);
103
+ resolve(v);
104
+ },
105
+ (e) => {
106
+ clearTimeout(timer);
107
+ reject(e);
108
+ },
109
+ );
110
+ });
111
+ }
112
+
113
+ /**
114
+ * Returns null when memory is disabled or unavailable — every caller treats
115
+ * null as "run without cross-run memory".
116
+ */
117
+ export async function openSynapMemory(opts: {
118
+ repoRoot: string;
119
+ log?: (line: string) => void;
120
+ env?: NodeJS.ProcessEnv;
121
+ }): Promise<SynapMemory | null> {
122
+ const env = opts.env ?? process.env;
123
+ const log = opts.log ?? (() => {});
124
+ if (!synapEnabled(env)) return null;
125
+
126
+ let client: SynapClientLike;
127
+ try {
128
+ // Non-literal specifier: keeps tsc from resolving an optional dependency at
129
+ // build time, so the package may legitimately be absent.
130
+ const specifier = '@maximem/synap-js-sdk';
131
+ const mod = (await import(specifier)) as {
132
+ createClient?: (o?: Record<string, unknown>) => SynapClientLike;
133
+ default?: { createClient?: (o?: Record<string, unknown>) => SynapClientLike };
134
+ };
135
+ const createClient = mod.createClient ?? mod.default?.createClient;
136
+ if (!createClient) throw new Error('createClient not exported');
137
+ client = createClient({ apiKey: env.SYNAP_API_KEY, requestTimeoutMs: RECORD_TIMEOUT_MS });
138
+ await withTimeout(client.init(), RECORD_TIMEOUT_MS, 'synap init');
139
+ } catch (err) {
140
+ // Missing package, missing Python runtime, bad key: all non-fatal.
141
+ log(`synap memory unavailable (${(err as Error).message}); continuing without it`);
142
+ return null;
143
+ }
144
+
145
+ const userId = await resolveUserId(opts.repoRoot, env);
146
+ const customerId = env.SYNAP_CUSTOMER_ID ?? 'copperhead';
147
+ const conversationId = randomUUID();
148
+
149
+ return {
150
+ async recall(request) {
151
+ try {
152
+ const res = await withTimeout(
153
+ client.searchMemory({
154
+ userId,
155
+ customerId,
156
+ query: redactSecrets(request),
157
+ maxResults: MAX_RECALLED,
158
+ }),
159
+ RECALL_TIMEOUT_MS,
160
+ 'synap recall',
161
+ );
162
+ const items = (res.results ?? []).filter((r) => r.memory?.trim());
163
+ if (!items.length) return null;
164
+ const lines = items.map((r) => `- ${r.memory.trim()}${r.contextType ? ` _(${r.contextType})_` : ''}`);
165
+ return [
166
+ '## Recalled from prior runs (Synap)',
167
+ '',
168
+ 'Context from earlier work by this user, possibly on other boards. Advisory only:',
169
+ 'the KiCad files and this repo’s docs remain the source of truth. If any of this',
170
+ 'conflicts with what you read in the repo, the repo wins — say so rather than',
171
+ 'acting on a stale memory.',
172
+ '',
173
+ ...lines,
174
+ ].join('\n');
175
+ } catch (err) {
176
+ log(`synap recall failed (${(err as Error).message}); continuing without it`);
177
+ return null;
178
+ }
179
+ },
180
+
181
+ async record(run) {
182
+ const assistant = [
183
+ `Outcome: ${run.outcome}`,
184
+ `Summary: ${run.summary}`,
185
+ `OpenSpec change: ${run.changeId ?? 'n/a'}`,
186
+ `Verification: ${run.verification}`,
187
+ run.filesTouched.length ? `Files: ${run.filesTouched.join(', ')}` : null,
188
+ run.decisions.length ? `Decisions:\n${run.decisions.map((d) => `- ${d}`).join('\n')}` : null,
189
+ ]
190
+ .filter(Boolean)
191
+ .join('\n');
192
+
193
+ await withTimeout(
194
+ client.addMemory({
195
+ userId,
196
+ customerId,
197
+ conversationId,
198
+ messages: [
199
+ { role: 'user', content: redactSecrets(run.request) },
200
+ { role: 'assistant', content: redactSecrets(assistant) },
201
+ ],
202
+ metadata: { source: 'copperhead', outcome: run.outcome, changeId: run.changeId },
203
+ }),
204
+ RECORD_TIMEOUT_MS,
205
+ 'synap record',
206
+ );
207
+ },
208
+
209
+ async close() {
210
+ try {
211
+ await withTimeout(client.shutdown(), RECORD_TIMEOUT_MS, 'synap shutdown');
212
+ } catch {
213
+ // Best effort: a failed shutdown must not change the run's outcome.
214
+ }
215
+ },
216
+ };
217
+ }
package/src/util/git.ts CHANGED
@@ -1,4 +1,9 @@
1
1
  import { execa } from 'execa';
2
+ import { cp, mkdir, mkdtemp, rm } from 'node:fs/promises';
3
+ import { existsSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import path from 'node:path';
6
+ import { PreflightError } from './preflight.js';
2
7
 
3
8
  export interface GitSnapshot {
4
9
  head: string;
@@ -19,11 +24,54 @@ export async function isGitRepo(repo: string): Promise<boolean> {
19
24
  }
20
25
  }
21
26
 
27
+ /** False on an unborn HEAD (fresh `git init` with no commits yet). */
28
+ export async function hasCommits(repo: string): Promise<boolean> {
29
+ try {
30
+ await git(repo, ['rev-parse', '--quiet', '--verify', 'HEAD']);
31
+ return true;
32
+ } catch {
33
+ return false;
34
+ }
35
+ }
36
+
22
37
  export async function isDirty(repo: string): Promise<boolean> {
23
38
  const status = await git(repo, ['status', '--porcelain']);
24
39
  return status.length > 0;
25
40
  }
26
41
 
42
+ /**
43
+ * The run-blocking git gates, in order: repo -> commits -> dirty (AC-3.8).
44
+ * Throws a PreflightError whose message explains why the run is refused and
45
+ * how to fix it; a caller that catches only needs err.message.
46
+ */
47
+ export async function gitPreflight(repo: string, opts: { allowDirty?: boolean } = {}): Promise<void> {
48
+ if (!(await isGitRepo(repo))) {
49
+ throw new PreflightError(
50
+ 'not a git repository; copperhead requires git for snapshots and rollback',
51
+ 'every run snapshots HEAD before editing so a failed run can be rolled back losslessly; without git there is no snapshot and no undo',
52
+ ['git init', 'git add -A && git commit -m "initial commit"', 'rerun the same copperhead command'],
53
+ );
54
+ }
55
+ if (!(await hasCommits(repo))) {
56
+ throw new PreflightError(
57
+ 'repository has no commits; copperhead requires at least one commit for snapshots and rollback',
58
+ 'the pre-run snapshot is the current HEAD commit; with an unborn HEAD there is nothing to roll back to if verification fails',
59
+ ['git add -A && git commit -m "initial commit"', 'rerun the same copperhead command'],
60
+ );
61
+ }
62
+ if ((await isDirty(repo)) && !opts.allowDirty) {
63
+ throw new PreflightError(
64
+ 'working tree is dirty; copperhead refuses to run on uncommitted changes by default',
65
+ 'a rollback hard-resets to the pre-run snapshot, which would silently destroy your uncommitted work',
66
+ [
67
+ 'git add -A && git commit — to keep your changes (recommended)',
68
+ 'git stash — to set them aside for now',
69
+ 'or rerun with --allow-dirty to let copperhead preserve them via "git stash create"',
70
+ ],
71
+ );
72
+ }
73
+ }
74
+
27
75
  /**
28
76
  * Snapshot the working tree before a run. On a clean tree HEAD is enough;
29
77
  * with --allow-dirty we keep a `git stash create` object so uncommitted work
@@ -43,13 +91,95 @@ export async function snapshot(repo: string): Promise<GitSnapshot> {
43
91
  * (.copperhead/runs/) survives rollback: it is the evidence of what failed.
44
92
  */
45
93
  export async function restore(repo: string, snap: GitSnapshot): Promise<void> {
46
- await git(repo, ['reset', '--hard', snap.head]);
47
- await git(repo, ['clean', '-fd', '-e', '.copperhead/runs']);
48
- if (snap.stash) {
49
- await git(repo, ['stash', 'apply', snap.stash]);
94
+ // `git clean -e` only protects untracked paths. A run directory can become
95
+ // staged (for example while preserving failed work), and `reset --hard`
96
+ // deletes such paths before clean runs. Copy it outside the repository so
97
+ // the audit trail survives regardless of its index state.
98
+ const runs = path.join(repo, '.copperhead', 'runs');
99
+ let backupRoot: string | null = null;
100
+ let backup: string | null = null;
101
+ try {
102
+ try {
103
+ backupRoot = await mkdtemp(path.join(tmpdir(), 'copperhead-runs-'));
104
+ backup = path.join(backupRoot, 'runs');
105
+ if (existsSync(runs)) await cp(runs, backup, { recursive: true });
106
+ } catch (err) {
107
+ backup = null;
108
+ console.warn(`warning: could not preserve failed-run audit trail before rollback: ${(err as Error).message}`);
109
+ }
110
+
111
+ try {
112
+ await git(repo, ['reset', '--hard', snap.head]);
113
+ await git(repo, ['clean', '-fd', '-e', '.copperhead/runs']);
114
+ if (snap.stash) {
115
+ await git(repo, ['stash', 'apply', snap.stash]);
116
+ }
117
+ } finally {
118
+ if (backup && existsSync(backup)) {
119
+ try {
120
+ await mkdir(path.dirname(runs), { recursive: true });
121
+ // Restored runs are intentionally untracked; their audit contents
122
+ // are ignored by the target-repository convention.
123
+ await cp(backup, runs, { recursive: true, force: true });
124
+ } catch (err) {
125
+ console.warn(`warning: could not restore failed-run audit trail: ${(err as Error).message}`);
126
+ }
127
+ }
128
+ }
129
+ } finally {
130
+ if (backupRoot) {
131
+ try {
132
+ await rm(backupRoot, { recursive: true, force: true });
133
+ } catch (err) {
134
+ console.warn(`warning: could not clean failed-run audit backup: ${(err as Error).message}`);
135
+ }
136
+ }
50
137
  }
51
138
  }
52
139
 
140
+ /**
141
+ * Preserve a failed run's work as a stash entry before rollback, so a failure
142
+ * is recoverable instead of destroyed. `git stash create` alone ignores
143
+ * untracked files (most of what a docs-stage run produces), so everything is
144
+ * staged first; restore() resets the index anyway. Never throws: preservation
145
+ * must not be able to block the rollback itself.
146
+ */
147
+ export async function preserveFailedRun(repo: string, runId: string): Promise<string | null> {
148
+ try {
149
+ if (!(await isDirty(repo))) return null;
150
+ // Never leave the audit trail staged: a staged-but-not-in-HEAD path is
151
+ // deleted by restore()'s `reset --hard`, which silently defeats its
152
+ // `clean -e .copperhead/runs` protection (that flag only spares untracked
153
+ // files) — the in-flight run's transcript dir vanishes mid-run. Staging
154
+ // then unstaging (rather than an exclude pathspec) because `git add`
155
+ // errors outright when a pathspec touches gitignored paths, and runs/ is
156
+ // gitignored in some target repos but tracked in others.
157
+ await git(repo, ['add', '-A']);
158
+ await git(repo, ['reset', '-q', '--', '.copperhead/runs']);
159
+ const sha = await git(repo, ['stash', 'create']);
160
+ if (!sha) return null;
161
+ await git(repo, ['stash', 'store', '-m', `copperhead failed run ${runId}`, sha]);
162
+ return sha;
163
+ } catch {
164
+ return null;
165
+ }
166
+ }
167
+
168
+ /** Current branch name, or "HEAD" when detached. Read-only metadata probe. */
169
+ export async function branchName(repo: string): Promise<string> {
170
+ return git(repo, ['rev-parse', '--abbrev-ref', 'HEAD']);
171
+ }
172
+
173
+ export async function headCommit(repo: string): Promise<string> {
174
+ return git(repo, ['rev-parse', 'HEAD']);
175
+ }
176
+
177
+ /** Count of uncommitted paths (staged, unstaged, and untracked). */
178
+ export async function uncommittedCount(repo: string): Promise<number> {
179
+ const status = await git(repo, ['status', '--porcelain']);
180
+ return status ? status.split('\n').length : 0;
181
+ }
182
+
53
183
  export async function commitAll(repo: string, message: string): Promise<string> {
54
184
  await git(repo, ['add', '-A']);
55
185
  await git(repo, ['commit', '-m', message]);
@@ -0,0 +1,22 @@
1
+ /**
2
+ * A run-blocking environment failure. Distinct from a mid-run error: nothing
3
+ * has been written yet, so the message alone is the whole user experience.
4
+ * The formatted message carries the reason, why copperhead refuses to run,
5
+ * and concrete remedy steps — every CLI catch path prints err.message, so
6
+ * embedding the explanation here means no call site needs special rendering.
7
+ */
8
+ export class PreflightError extends Error {
9
+ constructor(
10
+ readonly reason: string,
11
+ readonly why: string,
12
+ readonly remedy: string[],
13
+ ) {
14
+ super(formatPreflightFailure(reason, why, remedy));
15
+ this.name = 'PreflightError';
16
+ }
17
+ }
18
+
19
+ export function formatPreflightFailure(reason: string, why: string, remedy: string[]): string {
20
+ const steps = remedy.map((step, i) => ` ${i + 1}. ${step}`);
21
+ return [reason, '', `why it failed: ${why}`, 'to fix:', ...steps].join('\n');
22
+ }