intern-agent 0.1.0__py3-none-any.whl

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 (49) hide show
  1. intern_agent/__init__.py +2 -0
  2. intern_agent/__main__.py +5 -0
  3. intern_agent/adapters/__init__.py +41 -0
  4. intern_agent/adapters/claude_code.py +22 -0
  5. intern_agent/adapters/codex.py +235 -0
  6. intern_agent/adapters/generic.py +57 -0
  7. intern_agent/agentenv.py +60 -0
  8. intern_agent/capture.py +165 -0
  9. intern_agent/cli.py +823 -0
  10. intern_agent/config.py +100 -0
  11. intern_agent/counters.py +136 -0
  12. intern_agent/detect.py +125 -0
  13. intern_agent/distill.py +540 -0
  14. intern_agent/doctor.py +180 -0
  15. intern_agent/entry.py +137 -0
  16. intern_agent/evaluate.py +283 -0
  17. intern_agent/events.py +88 -0
  18. intern_agent/export.py +119 -0
  19. intern_agent/frontmatter.py +53 -0
  20. intern_agent/fsutil.py +80 -0
  21. intern_agent/guard.py +609 -0
  22. intern_agent/hooks.py +218 -0
  23. intern_agent/implicit.py +433 -0
  24. intern_agent/integrity.py +122 -0
  25. intern_agent/lesson.py +159 -0
  26. intern_agent/lifecycle.py +226 -0
  27. intern_agent/llm.py +112 -0
  28. intern_agent/lock.py +42 -0
  29. intern_agent/migrate.py +165 -0
  30. intern_agent/prompts/distill.md +33 -0
  31. intern_agent/prompts/eval_arm.md +9 -0
  32. intern_agent/prompts/eval_judge.md +24 -0
  33. intern_agent/redact.py +98 -0
  34. intern_agent/report.py +178 -0
  35. intern_agent/retrieve.py +267 -0
  36. intern_agent/review.py +78 -0
  37. intern_agent/rules.py +468 -0
  38. intern_agent/store.py +110 -0
  39. intern_agent/textsim.py +60 -0
  40. intern_agent/toml_lite.py +186 -0
  41. intern_agent/toolcache.py +43 -0
  42. intern_agent/transcript.py +648 -0
  43. intern_agent/trust.py +50 -0
  44. intern_agent-0.1.0.dist-info/METADATA +242 -0
  45. intern_agent-0.1.0.dist-info/RECORD +49 -0
  46. intern_agent-0.1.0.dist-info/WHEEL +5 -0
  47. intern_agent-0.1.0.dist-info/entry_points.txt +2 -0
  48. intern_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
  49. intern_agent-0.1.0.dist-info/top_level.txt +1 -0
intern_agent/cli.py ADDED
@@ -0,0 +1,823 @@
1
+ """intern command line: lessons (add, list, show, rm), capture, distill, recall, hook, stats, rules
2
+ (promote, rules, approve-rule, reject, disable-rule, guard), retire, restore, report, export, doctor,
3
+ import-review, eval, import.
4
+
5
+ Commands that grant trust or change what is enforced (approve, trust, approve-rule, reject, disable-rule)
6
+ ask a person on /dev/tty to type the id and refuse inside an agent session (agentenv.py); they record the
7
+ new state in integrity.json. Commands that write lessons or rules hold the store lock (lock.py)."""
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import sys
13
+ from pathlib import Path
14
+ from typing import Optional, Sequence
15
+
16
+ from . import __version__, agentenv, capture, config, events, retrieve, trust
17
+ from .adapters import AGENTS
18
+ from .entry import HOOK_EVENTS
19
+ from .lesson import KINDS, Lesson, Scope, new_id
20
+ from .redact import redact
21
+ from .store import Store, all_lessons, stores_for
22
+
23
+
24
+ UNTRUSTED_HINT = ("This repository's .intern/ was not created by intern on this machine, so its lessons are not "
25
+ "recalled. Run `intern trust` here if you trust them.")
26
+ GITIGNORE_HINT = "Project lessons are local. Add this line to .gitignore: .intern/"
27
+ AGENT_HINT = ("Written from inside an agent session, so it is stored as untrusted and not recalled. "
28
+ "Run `intern approve {id}` in your own terminal to keep it.")
29
+
30
+
31
+ def _person(what: str, question: str, token: str) -> Optional[int]:
32
+ """None when a person typed ``token`` on /dev/tty, else the exit code (2). There is no --yes: a flag
33
+ is something an agent can pass. See agentenv.py for why this is a speed bump, not a boundary."""
34
+ ok, why = agentenv.person_confirms(question, token)
35
+ if ok:
36
+ return None
37
+ print(f"intern: {what}: {why}", file=sys.stderr)
38
+ return 2
39
+
40
+
41
+ def _stores(cwd: Optional[Path] = None) -> list:
42
+ return stores_for(cwd, include_untrusted=True)
43
+
44
+
45
+ def _find(lesson_id: str, store_name: Optional[str] = None) -> tuple:
46
+ matches = [s for s in _stores() if (store_name is None or s.name == store_name) and s.has(lesson_id)]
47
+ if len(matches) > 1:
48
+ raise ValueError(f"{lesson_id} exists in both stores; pass --store global or --store project")
49
+ if not matches:
50
+ return None, None
51
+ return matches[0], matches[0].get(lesson_id)
52
+
53
+
54
+ def _unused_id() -> str:
55
+ """An id free in every store, so `show` and `rm` never have to guess."""
56
+ stores = _stores()
57
+ while True:
58
+ candidate = new_id()
59
+ if not any(store.has(candidate) for store in stores):
60
+ return candidate
61
+
62
+
63
+ def _split(values: Optional[Sequence[str]]) -> list:
64
+ out = []
65
+ for value in values or []:
66
+ out.extend(part.strip() for part in value.split(",") if part.strip())
67
+ return out
68
+
69
+
70
+ def cmd_add(args: argparse.Namespace) -> int:
71
+ if args.project:
72
+ home = config.project_home()
73
+ if home is None:
74
+ print("intern: --project needs a git repository", file=sys.stderr)
75
+ return 2
76
+ created = not home.exists()
77
+ if created:
78
+ trust.add(config.global_home(), home.parent) # intern made this store, so it may read it
79
+ store = Store(home, "project", trust.is_trusted(config.global_home(), home.parent))
80
+ else:
81
+ created, store = False, Store(config.global_home(), "global")
82
+ root = config.project_root()
83
+ scope = Scope(project=root.name if (args.project and root) else "*", tools=_split(args.tool),
84
+ paths=_split(args.path), intents=_split(args.intent))
85
+ event = events.append(store.events_path, "manual", note=args.title, correction=args.instead,
86
+ project=root.name if root else None, provenance={"agent": agentenv.in_agent()})
87
+ agent = agentenv.in_agent()
88
+ lesson = Lesson(id=_unused_id(), title=redact(args.title), scope=scope, evidence=[{"event": event["id"]}],
89
+ untrusted=agent, context=redact(args.context or ""), did=redact(args.did or ""),
90
+ instead=redact(args.instead or ""), why=redact(args.why or ""),
91
+ do=redact(args.do or ""), dont=redact(args.dont or ""))
92
+ path = store.save(lesson)
93
+ if args.json:
94
+ print(json.dumps({"id": lesson.id, "store": store.name, "path": str(path)}))
95
+ else:
96
+ print(f"{lesson.id} {store.name} {path}")
97
+ if created:
98
+ print(GITIGNORE_HINT, file=sys.stderr)
99
+ if not store.trusted:
100
+ print(UNTRUSTED_HINT, file=sys.stderr)
101
+ if agent:
102
+ print(AGENT_HINT.format(id=lesson.id), file=sys.stderr)
103
+ return 0
104
+
105
+
106
+ def cmd_list(args: argparse.Namespace) -> int:
107
+ rows, errors = [], []
108
+ for store in _stores():
109
+ for lesson, error in store.all():
110
+ if error:
111
+ errors.append(f"{store.name}: {error}")
112
+ elif args.kind is None or lesson.kind == args.kind:
113
+ rows.append((store, lesson))
114
+ if args.json:
115
+ print(json.dumps([{"id": l.id, "store": s.name, "trusted": s.trusted and not l.untrusted, "kind": l.kind,
116
+ "title": l.title, "scope": l.scope.to_dict(), "exposures": l.exposures,
117
+ "violations": l.violations} for s, l in rows], ensure_ascii=False))
118
+ else:
119
+ for store, lesson in rows:
120
+ mark = "" if store.trusted else " (untrusted project store)"
121
+ mark += " (untrusted: intern approve to recall it)" if lesson.untrusted else ""
122
+ print(f"{lesson.id} {lesson.kind:13s} {store.name:7s} {lesson.title}{mark}")
123
+ if not rows:
124
+ print("no lessons")
125
+ for error in errors:
126
+ print(f"intern: skipped {error}", file=sys.stderr)
127
+ return 1 if errors else 0
128
+
129
+
130
+ def cmd_show(args: argparse.Namespace) -> int:
131
+ store, lesson = _find(args.id, args.store)
132
+ if lesson is None:
133
+ print(f"intern: no lesson {args.id}", file=sys.stderr)
134
+ return 1
135
+ if args.json:
136
+ data = {"id": lesson.id, "store": store.name, "title": lesson.title, "kind": lesson.kind,
137
+ "source": lesson.source, "scope": lesson.scope.to_dict(), "evidence": lesson.evidence,
138
+ "created": lesson.created, "refreshed": lesson.refreshed, "exposures": lesson.exposures,
139
+ "violations": lesson.violations, "notes": lesson.notes, "context": lesson.context, "did": lesson.did,
140
+ "instead": lesson.instead, "why": lesson.why, "do": lesson.do, "dont": lesson.dont}
141
+ print(json.dumps(data, ensure_ascii=False))
142
+ else:
143
+ sys.stdout.write(lesson.to_text())
144
+ return 0
145
+
146
+
147
+ def cmd_rm(args: argparse.Namespace) -> int:
148
+ """A lesson with an open rule is removed only after a person confirms on /dev/tty (``--yes`` does
149
+ not count: removing it turns the guard rule off). Confirmation comes first, then the deletion."""
150
+ from . import lifecycle
151
+
152
+ store, lesson = _find(args.id, args.store)
153
+ if lesson is None:
154
+ print(f"intern: no lesson {args.id}", file=sys.stderr)
155
+ return 1
156
+ book = _book()
157
+ if lifecycle.open_rules(book, args.id):
158
+ try:
159
+ closed = lifecycle.close_rules_for(book, args.id)
160
+ except lifecycle.NotConfirmed as exc:
161
+ print(f"intern: rm: {exc}; nothing was removed", file=sys.stderr)
162
+ return 2
163
+ else:
164
+ closed = []
165
+ if not args.yes:
166
+ if not sys.stdin.isatty():
167
+ print("intern: refusing to delete without --yes (no terminal to confirm)", file=sys.stderr)
168
+ return 2
169
+ answer = input(f"Delete {lesson.id} ({lesson.title})? [y/N] ")
170
+ if answer.strip().lower() not in ("y", "yes"):
171
+ print("kept")
172
+ return 1
173
+ store.remove(args.id)
174
+ print(f"removed {args.id}" + (f"; turned off its rules {', '.join(r.id for r in closed)}" if closed else ""))
175
+ return 0
176
+
177
+
178
+ def _stdin_json() -> dict:
179
+ text = sys.stdin.read()
180
+ try:
181
+ data = json.loads(text) if text.strip() else {}
182
+ except ValueError as exc:
183
+ raise ValueError(f"stdin is not JSON: {exc}") from None
184
+ if not isinstance(data, dict):
185
+ raise ValueError("stdin must hold a JSON object")
186
+ return data
187
+
188
+
189
+ def cmd_capture(args: argparse.Namespace) -> int:
190
+ data = _stdin_json()
191
+ settings = config.load()
192
+ event = capture.capture(Store(config.global_home(), "global").events_path, args.gate, data,
193
+ settings["detect"]["languages"])
194
+ print(json.dumps(event, ensure_ascii=False) if args.json else event["id"])
195
+ return 0
196
+
197
+
198
+ def cmd_distill(args: argparse.Namespace) -> int:
199
+ from . import distill # not at the top: it loads the LLM runner, which no other command needs
200
+
201
+ since = distill.parse_since(args.since)
202
+ store = Store(config.global_home(), "global")
203
+ try:
204
+ report = distill.distill(store, config.load(), since=since, dry_run=args.dry_run)
205
+ except distill.Busy as exc:
206
+ print(f"intern: {exc}", file=sys.stderr)
207
+ return 0
208
+ if args.json:
209
+ print(json.dumps(report.__dict__, ensure_ascii=False))
210
+ else:
211
+ verb = "would write" if args.dry_run else "wrote"
212
+ print(f"{report.candidates} candidates: {verb} {len(report.lessons)} lessons, "
213
+ f"{len(report.duplicates)} duplicates, {report.rejected} rejected, {report.invalid} invalid, "
214
+ f"{report.pending} pending")
215
+ if args.dry_run and report.prompt_tokens:
216
+ print(f"LLM prompt size: about {report.prompt_tokens} tokens")
217
+ if report.proposed:
218
+ print(f"proposed rules: {', '.join(report.proposed)} (see `intern rules`; you approve or reject them)")
219
+ if report.retired:
220
+ print(f"retired: {', '.join(report.retired)} (`intern restore <id>` brings one back)")
221
+ if report.error:
222
+ print(f"intern: distill failed, events kept for the next run: {report.error}", file=sys.stderr)
223
+ return 1
224
+ return 0
225
+
226
+
227
+ def cmd_recall(args: argparse.Namespace) -> int:
228
+ data = _stdin_json()
229
+ cwd = str(data.get("cwd") or Path.cwd())
230
+ files = data.get("files") if isinstance(data.get("files"), list) else []
231
+ query = retrieve.Query(prompt=str(data.get("prompt") or ""), cwd=cwd, tool=data.get("tool") or None,
232
+ tool_input=data.get("tool_input"), files=[str(f) for f in files],
233
+ project=capture.project_name(cwd))
234
+ from . import integrity
235
+
236
+ held = integrity.withheld(config.global_home())
237
+ lessons = [(name, lesson) for name, lesson in all_lessons(stores_for(Path(cwd))) if lesson.id not in held]
238
+ result = retrieve.recall(lessons, query, config.load(), tool_only=args.tool_only)
239
+ if args.json:
240
+ print(json.dumps(result.to_dict(), ensure_ascii=False))
241
+ else:
242
+ if result.text:
243
+ print(result.text)
244
+ for lesson_id in result.suspect:
245
+ print(f"intern: suspect {lesson_id}: a cited file or line is gone", file=sys.stderr)
246
+ return 0
247
+
248
+
249
+ def cmd_hook(args: argparse.Namespace) -> int:
250
+ from .entry import hook
251
+
252
+ return hook(args.event, args.agent)
253
+
254
+
255
+ def cmd_stats(args: argparse.Namespace) -> int:
256
+ store = Store(config.global_home(), "global")
257
+ gates: dict = {}
258
+ for event in events.read(store.events_path):
259
+ gates[event.get("gate")] = gates.get(event.get("gate"), 0) + 1
260
+ outcomes: dict = {}
261
+ for row in events.read(store.stats_path):
262
+ if row.get("type") == "distill":
263
+ per_gate = outcomes.setdefault(row.get("gate"), {})
264
+ per_gate[row.get("outcome")] = per_gate.get(row.get("outcome"), 0) + 1
265
+ corrections = outcomes.get("user-correction", {})
266
+ decided = sum(corrections.values())
267
+ rate = round(corrections.get("rejected", 0) / decided, 3) if decided else None
268
+ lessons = all_lessons(_stores())
269
+ by_store: dict = {}
270
+ for name, lesson in lessons:
271
+ by_store[name] = by_store.get(name, 0) + 1
272
+ data = {"events": gates, "distill": outcomes, "false_positive_rate": rate,
273
+ "lessons": {"total": len(lessons), "by_store": by_store,
274
+ "untrusted": sum(1 for _, l in lessons if l.untrusted)}}
275
+ if args.json:
276
+ print(json.dumps(data, ensure_ascii=False))
277
+ return 0
278
+ print("events: " + (", ".join(f"{g} {n}" for g, n in sorted(gates.items(), key=lambda i: str(i[0]))) or "none"))
279
+ for gate, counts in sorted(outcomes.items(), key=lambda i: str(i[0])):
280
+ print(f"distill {gate}: " + ", ".join(f"{k} {v}" for k, v in sorted(counts.items())))
281
+ if rate is not None:
282
+ print(f"correction false positive rate: {rate:.0%} of {decided} candidates")
283
+ print(f"lessons: {len(lessons)} ({', '.join(f'{k} {v}' for k, v in sorted(by_store.items())) or 'none'}), "
284
+ f"untrusted {data['lessons']['untrusted']}")
285
+ return 0
286
+
287
+
288
+ def cmd_trust(args: argparse.Namespace) -> int:
289
+ root = config.find_root(Path(args.path).expanduser() if args.path else Path.cwd())
290
+ if root is None:
291
+ print("intern: trust needs a git repository", file=sys.stderr)
292
+ return 2
293
+ refused = _person("trust", f"Recall the lessons in {root}/.intern?", root.name)
294
+ if refused is not None:
295
+ return refused
296
+ added = trust.add(config.global_home(), root)
297
+ print(f"{'trusted' if added else 'already trusted'}: {root}")
298
+ return 0
299
+
300
+
301
+ def cmd_approve(args: argparse.Namespace) -> int:
302
+ store, lesson = _find(args.id, args.store)
303
+ if lesson is None:
304
+ print(f"intern: no lesson {args.id}", file=sys.stderr)
305
+ return 1
306
+ from . import integrity
307
+
308
+ if not lesson.untrusted and lesson.id not in integrity.withheld(config.global_home()):
309
+ print(f"{lesson.id} is already trusted")
310
+ return 0
311
+ refused = _person("approve", f"Recall {lesson.id} ({lesson.title})?", lesson.id)
312
+ if refused is not None:
313
+ return refused
314
+ lesson = store.get(lesson.id) or lesson
315
+ lesson.untrusted = False
316
+ store.save(lesson)
317
+ integrity.record(config.global_home(), approved=[lesson.id])
318
+ print(f"approved {lesson.id}: it will be recalled when it applies")
319
+ return 0
320
+
321
+
322
+ # ---- rules, retirement, report, export (stage 2) ----------------------------------------------------
323
+ def _book():
324
+ from .rules import RuleBook
325
+
326
+ return RuleBook(config.global_home())
327
+
328
+
329
+ def _stats_path() -> Path:
330
+ return Store(config.global_home(), "global").stats_path
331
+
332
+
333
+ def _rule(rule_id: str):
334
+ rule = _book().get(rule_id)
335
+ if rule is None:
336
+ print(f"intern: no rule {rule_id}", file=sys.stderr)
337
+ return rule
338
+
339
+
340
+ def cmd_promote(args: argparse.Namespace) -> int:
341
+ from . import lifecycle
342
+ from .rules import validate_draft
343
+
344
+ store, lesson = _find(args.id, args.store)
345
+ if lesson is None:
346
+ print(f"intern: no lesson {args.id}", file=sys.stderr)
347
+ return 1
348
+ if lesson.untrusted or not store.trusted:
349
+ print(f"intern: {lesson.id} is untrusted; run `intern approve {lesson.id}` first", file=sys.stderr)
350
+ return 2
351
+ book = _book()
352
+ open_rules = [r for r in book.for_lesson(lesson.id) if r.status in ("proposed", "active")]
353
+ if open_rules:
354
+ print(f"intern: {lesson.id} already has rule {open_rules[0].id} ({open_rules[0].status})", file=sys.stderr)
355
+ return 1
356
+ kind = args.kind or ("hook-check" if args.pattern else "instruction")
357
+ draft = validate_draft({"kind": kind, "tool": args.tool, "pattern": args.pattern, "unless": args.unless,
358
+ "decision": args.decision, "message": args.message or lesson.title,
359
+ "text": args.text or (lesson.title if kind != "hook-check" else "")})
360
+ if draft.get("warning"):
361
+ print(f"intern: warning: {draft.pop('warning')}", file=sys.stderr)
362
+ rule = lifecycle.propose(book, store, lesson, draft, "manual")
363
+ print(f"proposed {rule.id} for {lesson.id}: {rule.summary()}")
364
+ print(f"Approve it in your own terminal: intern approve-rule {rule.id}")
365
+ return 0
366
+
367
+
368
+ def cmd_rules(args: argparse.Namespace) -> int:
369
+ from . import counters
370
+
371
+ rules = [r for r in _book().all() if args.all or r.status in ("proposed", "active")]
372
+ hits = counters.rule_hits(_stats_path())
373
+ if args.json:
374
+ print(json.dumps([dict(r.__dict__, hits=hits.get(r.id, 0)) for r in rules], ensure_ascii=False))
375
+ return 0
376
+ for rule in rules:
377
+ print(f"{rule.id} {rule.status:9s} {rule.kind:11s} {rule.lesson} {rule.summary()} hits {hits.get(rule.id, 0)}")
378
+ if not rules:
379
+ print("no rules")
380
+ if any(r.status == "proposed" for r in rules):
381
+ print("Approve or reject in your own terminal: intern approve-rule <id> | intern reject <id>",
382
+ file=sys.stderr)
383
+ return 0
384
+
385
+
386
+ def _change_rule(args: argparse.Namespace, status: str, verb: str) -> int:
387
+ from . import lifecycle
388
+
389
+ rule = _rule(args.id)
390
+ if rule is None:
391
+ return 1
392
+ refused = _person(f"{verb} a rule", f"{verb.capitalize()} {rule.id}: {rule.summary()}", rule.id)
393
+ if refused is not None:
394
+ return refused
395
+ lifecycle.set_status(_book(), _stores(), rule, status)
396
+ print(f"{status} {rule.id} (lesson {rule.lesson})")
397
+ return 0
398
+
399
+
400
+ def cmd_approve_rule(args: argparse.Namespace) -> int:
401
+ return _change_rule(args, "active", "approve")
402
+
403
+
404
+ def cmd_reject(args: argparse.Namespace) -> int:
405
+ return _change_rule(args, "rejected", "reject")
406
+
407
+
408
+ def cmd_disable_rule(args: argparse.Namespace) -> int:
409
+ return _change_rule(args, "disabled", "disable")
410
+
411
+
412
+ def cmd_guard(args: argparse.Namespace) -> int:
413
+ from . import guard
414
+
415
+ rule = _rule(args.test)
416
+ if rule is None:
417
+ return 1
418
+ if rule.kind != "hook-check":
419
+ print(f"{rule.id} is a {rule.kind} rule; only hook-check rules are checked by guard")
420
+ return 1
421
+ entry = rule.cache_entry()
422
+ tool = args.tool or (rule.tool if rule.tool != "*" else "Bash")
423
+ tool_input = {"command": args.text} if guard.shell_tool(tool) else {"file_path": args.text}
424
+ if guard.matches(entry, tool, tool_input):
425
+ print(f"{rule.decision}: {guard.reason(entry)}" + ("" if rule.runs else f" (rule is {rule.status})"))
426
+ return 0
427
+ plain = guard.matches(dict(entry, unless=""), tool, tool_input)
428
+ print("unless matched" if rule.unless and plain else "no match")
429
+ return 1
430
+
431
+
432
+ def cmd_retire(args: argparse.Namespace) -> int:
433
+ from . import counters, lifecycle
434
+
435
+ days = int(config.load()["retire"]["days"])
436
+ done = lifecycle.retire(_stores(), counters.tally(_stats_path()), days, dry_run=args.dry_run)
437
+ verb = "would retire" if args.dry_run else "retired"
438
+ for store, lesson in done:
439
+ print(f"{verb} {lesson.id} {store.name} {lesson.title}")
440
+ if not done:
441
+ print(f"nothing to retire (soft lessons shown at least once and unbroken for {days} days)")
442
+ return 0
443
+
444
+
445
+ def cmd_restore(args: argparse.Namespace) -> int:
446
+ from . import lifecycle
447
+
448
+ found = lifecycle.restore(_stores(), args.id)
449
+ if found is None:
450
+ print(f"intern: no archived lesson {args.id}", file=sys.stderr)
451
+ return 1
452
+ print(f"restored {args.id} to {found[0].name}")
453
+ return 0
454
+
455
+
456
+ def cmd_report(args: argparse.Namespace) -> int:
457
+ from . import lifecycle, report
458
+ from .distill import parse_since
459
+
460
+ data = report.build(_stores(), _book(), _stats_path(), lifecycle.since_cutoff(parse_since(args.since)))
461
+ if args.json:
462
+ print(json.dumps(data, ensure_ascii=False))
463
+ else:
464
+ sys.stdout.write(report.render(data, markdown=args.markdown))
465
+ return 0
466
+
467
+
468
+ def cmd_export(args: argparse.Namespace) -> int:
469
+ from . import counters, export
470
+
471
+ if not (args.agents_md or args.format):
472
+ print("intern: export needs --agents-md or --format agents|claude|cursor", file=sys.stderr)
473
+ return 2
474
+ fmt = args.format or "agents"
475
+ project = None
476
+ if args.project:
477
+ root = config.find_root(Path.cwd())
478
+ if root is None:
479
+ raise ValueError("--project needs to run inside a repository")
480
+ project = root.name
481
+ text = export.block(stores_for(Path.cwd()), _book(), counters.tally(_stats_path()), project)
482
+ preamble = export.CURSOR_FRONTMATTER if fmt == "cursor" else ""
483
+ if not args.write:
484
+ sys.stdout.write(preamble + text)
485
+ return 0
486
+ target = Path(args.write).expanduser()
487
+ if fmt == "cursor" and target.suffix != ".mdc":
488
+ raise ValueError("Cursor reads project rules only from .mdc files, e.g. .cursor/rules/intern.mdc")
489
+ if fmt == "cursor":
490
+ target.parent.mkdir(parents=True, exist_ok=True)
491
+ changed = export.write(target, text, preamble)
492
+ print(f"{'updated' if changed else 'unchanged'}: {args.write}")
493
+ return 0
494
+
495
+
496
+ def cmd_doctor(args: argparse.Namespace) -> int:
497
+ from . import doctor
498
+
499
+ problems, notes, add = doctor.check(Path.cwd())
500
+ if args.json:
501
+ print(json.dumps({"problems": problems, "notes": notes, "add": add}, ensure_ascii=False))
502
+ else:
503
+ sys.stdout.write(doctor.render(problems, notes, add, Path.cwd()))
504
+ return 1 if problems else 0
505
+
506
+
507
+ # ---- review findings, eval, import (stage 3) --------------------------------------------------------
508
+ def cmd_import_review(args: argparse.Namespace) -> int:
509
+ from . import review
510
+
511
+ try:
512
+ text = sys.stdin.read() if args.file == "-" else Path(args.file).expanduser().read_text(encoding="utf-8")
513
+ except (OSError, UnicodeDecodeError) as exc:
514
+ raise ValueError(f"{args.file}: {exc}") from None
515
+ findings, skipped = review.parse(text)
516
+ path = Store(config.global_home(), "global").events_path
517
+ languages = config.load()["detect"]["languages"]
518
+ seen = review.recorded_keys(path)
519
+ fresh, duplicates = [], 0
520
+ for finding in findings:
521
+ key = review.key(finding)
522
+ if key in seen:
523
+ duplicates += 1
524
+ continue
525
+ seen.add(key)
526
+ fresh.append(finding)
527
+ findings = fresh
528
+ ids = []
529
+ for finding in findings:
530
+ if not args.dry_run:
531
+ ids.append(capture.capture(path, "review-finding", dict(finding, reviewer=args.reviewer), languages)["id"])
532
+ if args.json:
533
+ print(json.dumps({"findings": findings, "events": ids, "skipped": skipped, "duplicates": duplicates},
534
+ ensure_ascii=False))
535
+ else:
536
+ if duplicates:
537
+ print(f"{duplicates} findings already recorded, left out")
538
+ for finding in findings:
539
+ where = (finding.get("file") or "-") + (f":{finding['line']}" if finding.get("line") else "")
540
+ print(f"{'would record' if args.dry_run else 'recorded'} {finding['severity']:8s} {where} "
541
+ f"{finding['finding'][:80]}")
542
+ print(f"{len(findings)} findings, {skipped} lines with | skipped")
543
+ return 0 if findings or duplicates or not skipped else 1
544
+
545
+
546
+ def _confirm_spend(calls: int, budget: float) -> Optional[int]:
547
+ if not sys.stdin.isatty():
548
+ print(f"intern: eval makes up to {calls} paid model calls (budget ${budget:g}); pass --yes to run it",
549
+ file=sys.stderr)
550
+ return 2
551
+ answer = input(f"Make up to {calls} paid model calls (budget ${budget:g})? [y/N] ")
552
+ return None if answer.strip().lower() in ("y", "yes") else 1
553
+
554
+
555
+ def cmd_eval(args: argparse.Namespace) -> int:
556
+ from . import evaluate
557
+
558
+ store, lesson = _find(args.id, args.store)
559
+ if lesson is None:
560
+ print(f"intern: no lesson {args.id}", file=sys.stderr)
561
+ return 1
562
+ settings = config.load()
563
+ wanted = args.cases if args.cases is not None else int(settings["eval"]["cases"])
564
+ if wanted < 1:
565
+ raise ValueError("--cases must be at least 1")
566
+ budget = args.budget_usd if args.budget_usd is not None else float(settings["eval"]["budget_usd"])
567
+ cases = evaluate.build_cases(lesson, Store(config.global_home(), "global").events_path, wanted)
568
+ if store.home != config.global_home() and not cases:
569
+ cases = evaluate.build_cases(lesson, store.events_path, wanted)
570
+ if not cases:
571
+ print(f"intern: {lesson.id} has no evidence event to replay and no context and did to build a case from",
572
+ file=sys.stderr)
573
+ return 1
574
+ calls = len(cases) * evaluate.CALLS_PER_CASE
575
+ if args.dry_run:
576
+ payload = {"lesson": lesson.id, "cases": len(cases), "calls": calls, "budget_usd": budget}
577
+ print(json.dumps(payload) if args.json else
578
+ f"eval {lesson.id}: {len(cases)} cases, {calls} model calls (no call made), budget ${budget:g}")
579
+ return 0
580
+ if agentenv.in_agent():
581
+ # An agent must not spend the user's money on its own say-so: --yes is ignored in agent sessions.
582
+ ok, why = agentenv.person_confirms(
583
+ f"intern eval {lesson.id} makes up to {calls} paid model calls (budget ${budget:g}).", lesson.id)
584
+ if not ok:
585
+ print(f"intern: {why}; run this yourself in a separate terminal", file=sys.stderr)
586
+ return 2
587
+ elif not args.yes:
588
+ refused = _confirm_spend(calls, budget)
589
+ if refused is not None:
590
+ return refused
591
+ result = evaluate.Runner(settings, budget, str(config.global_home())).run(lesson, cases, wanted).to_dict()
592
+ evaluate.save(config.global_home(), result)
593
+ if args.json:
594
+ print(json.dumps(result, ensure_ascii=False))
595
+ else:
596
+ sys.stdout.write(evaluate.render_result(result))
597
+ return 0 if result["cases"] else 1
598
+
599
+
600
+ def cmd_import(args: argparse.Namespace) -> int:
601
+ from . import migrate
602
+
603
+ store = Store(config.global_home(), "global")
604
+ titles = {migrate._norm(l.title): l.id for _, l in all_lessons(_stores())} if args.direct else None
605
+ notes = migrate.plan(Path(args.from_markdown).expanduser(), store.events_path, titles)
606
+ agent = agentenv.in_agent()
607
+ done = []
608
+ for note in notes:
609
+ if note.skip:
610
+ continue
611
+ if args.dry_run:
612
+ done.append((note, None))
613
+ continue
614
+ event = events.append(store.events_path, "manual", provenance={"agent": agent, "imported": True},
615
+ **migrate.event_fields(note, args.source))
616
+ lesson_id = None
617
+ if args.direct:
618
+ lesson = Lesson(id=_unused_id(), title=redact(note.title), evidence=[{"event": event["id"]}],
619
+ source=["papercut" if args.source == "papercut" else "manual"], untrusted=agent,
620
+ context=redact(note.context), instead=redact(note.instead), why=redact(note.why))
621
+ store.save(lesson)
622
+ titles[migrate._norm(note.title)] = lesson.id # type: ignore[index]
623
+ lesson_id = lesson.id
624
+ done.append((note, lesson_id))
625
+ if args.json:
626
+ print(json.dumps([{"file": str(n.path), "title": n.title, "skip": n.skip,
627
+ "lesson": next((lid for d, lid in done if d is n), None)} for n in notes], ensure_ascii=False))
628
+ else:
629
+ verb = "would import" if args.dry_run else "imported"
630
+ for note, lesson_id in done:
631
+ print(f"{verb} {note.path.name}: {note.title}" + (f" -> {lesson_id}" if lesson_id else ""))
632
+ for note in notes:
633
+ if note.skip:
634
+ print(f"skipped {note.path.name}: {note.skip}")
635
+ print(f"{len(done)} {verb}, {sum(1 for n in notes if n.skip)} skipped")
636
+ if done and not args.direct and not args.dry_run:
637
+ print("Run `intern distill` to turn them into lessons (an LLM call).")
638
+ if done and agent and not args.dry_run:
639
+ print("Imported from inside an agent session: the lessons stay untrusted until you run "
640
+ "`intern approve <id>` in your own terminal.", file=sys.stderr)
641
+ return 0
642
+
643
+
644
+ def build_parser() -> argparse.ArgumentParser:
645
+ parser = argparse.ArgumentParser(prog="intern", description="Lessons a coding agent learns from its mistakes.")
646
+ parser.add_argument("--version", action="version", version=f"intern {__version__}")
647
+ sub = parser.add_subparsers(dest="command", required=True)
648
+
649
+ add = sub.add_parser("add", help="record a lesson by hand")
650
+ add.add_argument("title", help="one line: the rule in plain words")
651
+ add.add_argument("--context", help="when this applies")
652
+ add.add_argument("--did", help="what the agent did")
653
+ add.add_argument("--instead", help="what it should do")
654
+ add.add_argument("--why", help="why")
655
+ add.add_argument("--do", help="a good example")
656
+ add.add_argument("--dont", help="a bad example")
657
+ add.add_argument("--tool", action="append", help="tool scope, e.g. Bash (repeatable or comma separated)")
658
+ add.add_argument("--path", action="append", help="path glob scope, e.g. 'src/**/*.ts'")
659
+ add.add_argument("--intent", action="append", help="intent tag, e.g. deploy, ui, migration")
660
+ add.add_argument("--project", action="store_true", help="store in this repository's .intern/ (local only)")
661
+ add.add_argument("--json", action="store_true")
662
+ add.set_defaults(func=cmd_add)
663
+
664
+ lst = sub.add_parser("list", help="list lessons from the global and project stores")
665
+ lst.add_argument("--kind", choices=KINDS)
666
+ lst.add_argument("--json", action="store_true")
667
+ lst.set_defaults(func=cmd_list)
668
+
669
+ show = sub.add_parser("show", help="print one lesson")
670
+ show.add_argument("id")
671
+ show.add_argument("--store", choices=("global", "project"))
672
+ show.add_argument("--json", action="store_true")
673
+ show.set_defaults(func=cmd_show)
674
+
675
+ rm = sub.add_parser("rm", help="delete a lesson (the event log keeps a record)")
676
+ rm.add_argument("id")
677
+ rm.add_argument("--store", choices=("global", "project"))
678
+ rm.add_argument("--yes", action="store_true", help="do not ask (ignored when the lesson has a rule)")
679
+ rm.set_defaults(func=cmd_rm)
680
+
681
+ cap = sub.add_parser("capture", help="record an event from stdin JSON (hooks, the agent, scripts)")
682
+ cap.add_argument("--gate", required=True, choices=capture.CAPTURE_GATES)
683
+ cap.add_argument("--json", action="store_true", help="print the stored event")
684
+ cap.set_defaults(func=cmd_capture)
685
+
686
+ dis = sub.add_parser("distill", help="turn new events into lessons (calls the configured LLM command)")
687
+ dis.add_argument("--since", help="only events newer than this, e.g. 7d, 12h, 2w")
688
+ dis.add_argument("--dry-run", action="store_true", help="show what would happen; no LLM call, no writes")
689
+ dis.add_argument("--json", action="store_true")
690
+ dis.set_defaults(func=cmd_distill)
691
+
692
+ rec = sub.add_parser("recall", help="lessons for stdin JSON {prompt, cwd, tool, tool_input, files}")
693
+ rec.add_argument("--tool-only", action="store_true", help="only lessons scoped to the given tool")
694
+ rec.add_argument("--json", action="store_true")
695
+ rec.set_defaults(func=cmd_recall)
696
+
697
+ hk = sub.add_parser("hook", help="hook entry point for an agent (reads the hook JSON on stdin)")
698
+ hk.add_argument("event", choices=HOOK_EVENTS)
699
+ hk.add_argument("--agent", choices=AGENTS, default="claude-code",
700
+ help="whose hook format to read and write (default claude-code)")
701
+ hk.set_defaults(func=cmd_hook)
702
+
703
+ tr = sub.add_parser("trust", help="recall lessons from this repository's .intern/ (you vouch for them)")
704
+ tr.add_argument("path", nargs="?", help="a folder inside the repository (default: here)")
705
+ tr.set_defaults(func=cmd_trust)
706
+
707
+ ap = sub.add_parser("approve", help="mark an untrusted lesson as yours, so it can be recalled")
708
+ ap.add_argument("id")
709
+ ap.add_argument("--store", choices=("global", "project"))
710
+ ap.set_defaults(func=cmd_approve)
711
+
712
+ st = sub.add_parser("stats", help="event counts, distill outcomes, false positive rate, lessons")
713
+ st.add_argument("--json", action="store_true")
714
+ st.set_defaults(func=cmd_stats)
715
+
716
+ pr = sub.add_parser("promote", help="propose a binding rule for a lesson (a person approves it)")
717
+ pr.add_argument("id")
718
+ pr.add_argument("--store", choices=("global", "project"))
719
+ pr.add_argument("--kind", choices=("hook-check", "instruction", "lint", "test", "skill-patch"))
720
+ pr.add_argument("--tool", default="Bash", help="tool the hook check applies to (default Bash, * for any)")
721
+ pr.add_argument("--pattern", help="regex matched against the tool input (Bash command, file path and text)")
722
+ pr.add_argument("--unless", help="regex that lets a matching call through")
723
+ pr.add_argument("--decision", choices=("ask", "deny"), default="ask")
724
+ pr.add_argument("--message", help="what the agent is told (default: the lesson title)")
725
+ pr.add_argument("--text", help="the line for instruction, lint, test or skill-patch rules")
726
+ pr.set_defaults(func=cmd_promote)
727
+
728
+ rl = sub.add_parser("rules", help="list proposed and active rules")
729
+ rl.add_argument("--all", action="store_true", help="also disabled and rejected rules")
730
+ rl.add_argument("--json", action="store_true")
731
+ rl.set_defaults(func=cmd_rules)
732
+
733
+ for name, func, text in (("approve-rule", cmd_approve_rule, "turn a proposed rule on (you type its id)"),
734
+ ("reject", cmd_reject, "turn a rule proposal down; it is not proposed again"),
735
+ ("disable-rule", cmd_disable_rule, "turn an active rule off")):
736
+ cmd = sub.add_parser(name, help=text)
737
+ cmd.add_argument("id")
738
+ cmd.set_defaults(func=func)
739
+
740
+ gd = sub.add_parser("guard", help="try a hook-check rule against a command or text")
741
+ gd.add_argument("--test", required=True, metavar="RULE_ID")
742
+ gd.add_argument("--tool", help="tool name to test as (default: the rule's tool)")
743
+ gd.add_argument("text")
744
+ gd.set_defaults(func=cmd_guard)
745
+
746
+ rt = sub.add_parser("retire", help="archive soft lessons shown at least once and unbroken for retire.days")
747
+ rt.add_argument("--dry-run", action="store_true")
748
+ rt.set_defaults(func=cmd_retire)
749
+
750
+ rs = sub.add_parser("restore", help="bring a lesson back from archive/")
751
+ rs.add_argument("id")
752
+ rs.set_defaults(func=cmd_restore)
753
+
754
+ rp = sub.add_parser("report", help="exposures, violations, compliance and rule proposals per lesson")
755
+ rp.add_argument("--since", help="only facts newer than this, e.g. 30d")
756
+ rp.add_argument("--json", action="store_true")
757
+ rp.add_argument("--markdown", action="store_true")
758
+ rp.set_defaults(func=cmd_report)
759
+
760
+ dr = sub.add_parser("doctor", help="check the Claude Code settings that protect intern, and intern's state")
761
+ dr.add_argument("--json", action="store_true")
762
+ dr.set_defaults(func=cmd_doctor)
763
+
764
+ ir = sub.add_parser("import-review", help="record review findings from 'file:line | severity | finding | fix' lines")
765
+ ir.add_argument("file", help="the reviewer's report, or - for stdin")
766
+ ir.add_argument("--reviewer", default="review", help="who found them, e.g. code-reviewer or security")
767
+ ir.add_argument("--dry-run", action="store_true")
768
+ ir.add_argument("--json", action="store_true")
769
+ ir.set_defaults(func=cmd_import_review)
770
+
771
+ ev = sub.add_parser("eval", help="replay a lesson's mistakes with and without it; a blind judge scores them "
772
+ "(paid model calls)")
773
+ ev.add_argument("id")
774
+ ev.add_argument("--store", choices=("global", "project"))
775
+ ev.add_argument("--cases", type=int, help="how many evidence events to replay (default [eval] cases)")
776
+ ev.add_argument("--budget-usd", type=float, help="stop once this much is spent (default [eval] budget_usd)")
777
+ ev.add_argument("--dry-run", action="store_true", help="count cases and calls; call nothing")
778
+ ev.add_argument("--yes", action="store_true", help="do not ask before the paid calls")
779
+ ev.add_argument("--json", action="store_true")
780
+ ev.set_defaults(func=cmd_eval)
781
+
782
+ im = sub.add_parser("import", help="turn lessons you wrote in markdown (memory files, notes) into lessons")
783
+ im.add_argument("--from-markdown", required=True, metavar="PATH", help="a .md file or a folder of them")
784
+ im.add_argument("--source", choices=("papercut", "hatadan-ders", "memory"), default="memory")
785
+ im.add_argument("--direct", action="store_true", help="map the fields as they are; no LLM at distill")
786
+ im.add_argument("--dry-run", action="store_true", help="list what would be imported; write nothing")
787
+ im.add_argument("--json", action="store_true")
788
+ im.set_defaults(func=cmd_import)
789
+
790
+ ex = sub.add_parser("export", help="a managed block of rules and lessons for AGENTS.md, CLAUDE.md or Cursor")
791
+ ex.add_argument("--agents-md", action="store_true", help="the AGENTS.md block (same as --format agents)")
792
+ ex.add_argument("--format", choices=("agents", "claude", "cursor"),
793
+ help="agents (AGENTS.md), claude (CLAUDE.md) or cursor (.cursor/rules/intern.mdc)")
794
+ ex.add_argument("--project", action="store_true", help="only this repository's lessons and their rules")
795
+ ex.add_argument("--write", metavar="PATH", help="put the block into this file, replacing an earlier one")
796
+ ex.set_defaults(func=cmd_export)
797
+ return parser
798
+
799
+
800
+ WRITERS = {"add", "rm", "approve", "trust", "promote", "approve-rule", "reject", "disable-rule", "retire",
801
+ "restore", "import"}
802
+
803
+
804
+ def main(argv: Optional[Sequence[str]] = None) -> int:
805
+ args = build_parser().parse_args(argv)
806
+ try:
807
+ if args.command in WRITERS and not getattr(args, "dry_run", False):
808
+ from .lock import Busy, locked
809
+
810
+ try:
811
+ with locked(config.global_home(), wait=10.0):
812
+ return args.func(args)
813
+ except Busy as exc:
814
+ print(f"intern: {exc}", file=sys.stderr)
815
+ return 1
816
+ return args.func(args)
817
+ except ValueError as exc:
818
+ print(f"intern: {exc}", file=sys.stderr)
819
+ return 2
820
+
821
+
822
+ if __name__ == "__main__":
823
+ sys.exit(main())