aai-coding 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.
aai_coding/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,137 @@
1
+ r'''Jeremy's coding style and conventions: read before writing, reviewing, or assessing any code.
2
+
3
+ # Coding Patterns
4
+
5
+ Based on the fastai style guide and Jeremy's 3 decades of coding experience, and used across all of his projects, not only fastai ones.
6
+
7
+ Use the fastcore/fasthtml ecosystem (fastcore, fasthtml, fastlite, ...) when picking libraries. These are Jeremy's own, editable-installed as siblings, and preferred over heavier third-party alternatives.
8
+
9
+ ## Improving Tooling Pays Off Exponentially
10
+
11
+ Making our tools marvellous matters more than the task in hand. A finished task helps once. A better tool helps every later task, every later session, and the whole team. Ergonomics count as much as capability. Most code you have read was written by people who put up with tool friction rather than fix it, so your default is the workaround. Here the tools are ours and one edit away. When something grates, fix it or raise it. Never quietly work around it.
12
+
13
+ ## Every Construct Must Earn Its Place
14
+
15
+ Readers assume everything present is necessary. When they see `str(x)` on something that's already a str, they stop and wonder what subtle thing it's guarding against. When the answer is "nothing", they paid for a mystery with no payoff. The same goes for defensive copies (`list(x)` that's never mutated), "just in case" try/excepts, redundant type coercions, and unused parameters. Before adding any construct, know why it's needed. If you can't say, leave it out. The cost doubles in nbdev projects, where tests are documentation.
16
+
17
+ Knowing why a construct is needed does not mean waiting for someone to ask for it. An open source user who finds a gap concludes the library cannot do it and moves on. Judge a library feature by whether the design calls for it and users would expect it.
18
+
19
+ The same applies to prose in code: almost never add comments (only when the code is truly unclear), and don't add type hints, docstrings, or boilerplate that pull no weight. Prefer concise, readable code over verbose "enterprise" style.
20
+ Only write a code comment to state a constraint the code itself can't show, never to say where it came from, what the next line does, or why your change is correct. That's you talking to the reviewer, not the next reader, and it's noise the moment the PR merges.
21
+
22
+ ## Plain Commands: Flags, Redirects, and Pipes Are for Exceptions
23
+
24
+ The same principle applies to running commands. The bare invocation is the contract: `pytest tests -q`, `cargo fmt`, `maturin develop`. Project config exists precisely so the plain command does the right thing, and then every invocation is short, identical, and instantly readable. A flag, redirect, or pipe is a statement ("this one call has a requirement the defaults don't cover"), and used that way it carries information: the reader stops, asks why, and there's an answer. Sprinkled defensively on every call, decorations destroy that signal: every command looks exceptional so none is, and the one deliberate flag is indistinguishable from habit. Transcripts compound the damage, since each decorated call teaches later calls to decorate too.
25
+
26
+ - Wanting the same flag on every run means it's a missing config line: promote it and go back to the bare command (`pytest --timeout 300` on every run becomes `timeout = 60` under `[tool.pytest.ini_options]`).
27
+ - Don't check-then-apply when applying is the goal: `cargo fmt`, not `cargo fmt --check` followed by `cargo fmt`. `--check` is for a final no-mutation verification, e.g. CI.
28
+ - Run commands bare and read their output. Never pipe through truncating filters (`| tail -20`, `| grep PASS`): truncation is decided before the output exists, and it hides exactly the surprises worth seeing. Never merge stderr into stdout with `2>&1`: separated, a crash is unmissable.
29
+ - On the rare occasion output genuinely can't come back inline (far too large), redirect the streams separately (`>meta/stdout.txt 2>meta/stderr.txt`) and read the files from the kernel.
30
+ - A real one-off requirement gets its flag once, with the reason stated alongside, and disappears again on the next call.
31
+
32
+ ## Docments
33
+
34
+ Docments are trailing comments on function parameters that fastcore uses for documentation. A signature with docments (or any long signature) uses this layout: `(` stays on the def line, each parameter on its own line indented 4, and `):` alone on its own line at def indent:
35
+
36
+ ```python
37
+ @delegates(start_kernel)
38
+ async def run_kernel(
39
+ kernel_name='python3', # Kernelspec name to launch
40
+ manager_cls=KernelManager, # Manager class, e.g. a subclass customizing launch
41
+ **kwargs
42
+ ):
43
+ ```
44
+
45
+ NEVER remove docments when refactoring. They're essential documentation.
46
+
47
+ When `**kwargs` passes through to a known callee, decorate with `@delegates(callee)` so the signature shows the real options. delegates REQUIRES the collector to be named `kwargs`, not `kw` etc. Skip the decorator when the callee's own signature is just `**kwargs` (nothing to delegate).
48
+
49
+ ## Raw Strings
50
+
51
+ Write any non-trivial string literal as a raw string (`r"..."` / `r"""..."""`): regexes, text you pass to tools, code or markup inside strings, anything multi-line or containing backslashes. In plain strings a stray `\n` or `\d` either errors or silently corrupts, and each miss costs a round trip to diagnose plus another to fix. Raw strings are WYSIWYG, so the first attempt matches what you meant. The `r` costs nothing when no escapes are present, so make it the default, not the exception.
52
+
53
+ ## Style Checker (chkstyle)
54
+
55
+ Run `chkstyle {path}` to check fastai style (only include path if needed). But use judgment. chkstyle is a hint, not gospel.
56
+ In nbdev projects, point it at the notebooks (`chkstyle nbs/00_core.ipynb`), not the exported `.py`. The notebook run also checks example and test cells, which never reach the module.
57
+
58
+ ## Config Patterns
59
+
60
+ Read from standard locations rather than duplicating config:
61
+
62
+ - GitHub release notes config: `.github/release.yml`
63
+ - Project config: `pyproject.toml` under `[tool.yourpkg]`
64
+ - Infer values when possible (e.g., package name from `[project].name`)
65
+ - Bundle data files inside the package and read them with `importlib.resources`
66
+
67
+ ## Versioning: Bump After Release
68
+
69
+ Jeremy bumps the version immediately after each release, as part of releasing and never as part of a change. The tree therefore always carries the next release's version. A sibling dep pin can name a version before it ships (`foo>=<foo's local version>`).
70
+
71
+ A downstream pin is part of the change that creates the dependency. When a change makes one package consume another's new behavior or API, stamp the consumers' pins in the same session. A pin deferred to release time is a forgotten pin.
72
+
73
+ This convention is for Python projects. Other artifact types version at change time instead: for example, the Claude Code plugins in skill-plugins bump automatically when `./build.py` regenerates a changed output.
74
+
75
+ ## Project Layout
76
+
77
+ Prefer flat layout over src/:
78
+
79
+ ```
80
+ myproject/
81
+ ├── mypkg/
82
+ │ └── __init__.py
83
+ ├── tests/
84
+ ├── pyproject.toml
85
+ └── README.md
86
+ ```
87
+
88
+ ## Testing
89
+
90
+ In nbdev projects (most projects here) there are no test cells: tests ARE the documentation, changes revise lesson cells, and the red-green check applies only to an assertion you actually revised or added (see `doc(nbdev.skill)`). Coverage is never a goal.
91
+
92
+ All code has writing, maintenance, and readability costs, and tests most of all: every test must be kept passing forever, gets read by every future contributor, and must be revised whenever the behavior it pins changes. So never write a test as a reflex. A test earns its place only when:
93
+
94
+ - it documents an idea, or
95
+ - the logic is intricate enough that you had to think carefully to get it right (edge cases, parsing, arithmetic, tricky conditionals: the places a future change could silently break it), or
96
+ - the code assumes something about an external system (a file format, an API's response shape, another tool's behavior) that is somewhat likely to change one day, and we want to hear about it when the assumption is violated. These must exercise the real thing (a mock merely re-states our assumption), so they're usually the slow-marked tests
97
+
98
+ Wiring and orchestration get zero tests: re-exports, delegations, one-line glue, functions that only sequence calls to other tools. A test there only asserts that Python works, and pins down internals we may want to change. Strong tell: if a test needs recording fakes or mock collaborators to reach the code, it's testing a transcript of the implementation, not logic. Extract the logic into a small pure function and test that, or don't test at all.
99
+
100
+ Pytest is for checks that don't fit as a readable notebook lesson and are too complex or distracting even for a `#|hide` cell; there, ALWAYS work red-green: write the test FIRST, run it to see it fail, THEN make the change, then run it again to see it pass.
101
+
102
+ - Prefer as few tests as possible: a single test that walks through many checks is more readable and faster than many small ones
103
+ - A check worth keeping goes in a real test file or notebook cell, never left as an ad-hoc command. In a notebook, the checks made while exploring often ARE the narrative (each one both documents what we needed to know and keeps guarding it), so they stay as example cells. In a pytest file, an exploratory check survives only if it meets one of the criteria above
104
+ - Assert the logic, not incidentals: check what the behavior guarantees, never byte-exact renderings, exact reprs, or field order. A test that compares a whole output string locks in formatting decisions that were never the point (e.g. assert the content appears in a markdown display block, not the display's exact text). NEVER use tests to "lock in" behavior, unless that exact behavior really is a key part of the logic or contract that must always be true forever
105
+ - Use `pytest -q` (not `python -m pytest`, which prompts for permission). nbdev projects use `nbdev-test` on the changed notebook, but some notebooks are slow or hit live services, so check with the user before running one you don't know is safe (known safe: all of pyskills)
106
+ - Don't run slow-marked tests until finishing a session, or after a change likely to directly impact them
107
+
108
+ ## One-liner Patterns
109
+
110
+ ```python
111
+ # Conditionals
112
+ if not x: return default
113
+ if x and y: do_thing()
114
+
115
+ # Try/except
116
+ try: return run("cmd").strip() or default
117
+ except Exception: return default
118
+
119
+ # Loops
120
+ for i in range(n): result[i] = 0
121
+ while len(items) < 3: items.append(0)
122
+ ```
123
+
124
+ ## Import Style
125
+
126
+ Combine imports on single lines:
127
+
128
+ ```python
129
+ import os, re, sys, shutil
130
+ from pathlib import Path
131
+ from fastcore.utils import *
132
+ ```
133
+
134
+ `from fastcore.utils import *` already provides `os`, `Path`, and much of the stdlib, so don't re-import those alongside it.
135
+ '''
136
+
137
+ __all__ = []
aai_coding/harness.py ADDED
@@ -0,0 +1,304 @@
1
+ """Hook implementations for the team harness, installed as the `aai-hook` CLI. Each subcommand is registered in a harness's hook config (Claude Code settings.json or codex hooks.json) and reads the hook event's JSON payload from stdin. See SETUP.md for the wiring."""
2
+ import json, os, re, sys
3
+ from datetime import datetime
4
+ from pathlib import Path
5
+
6
+ __all__ = ['main']
7
+
8
+ NO_TRUNCATE = ('Output pipe truncates below 20 lines. Drop the pipe or keep >=20: truncation is decided '
9
+ 'before the output exists, so keep enough to diagnose surprises.')
10
+ NO_STDERR_MERGE = ('Do not merge stderr into stdout with 2>&1. Run the command bare: the harness pushes large '
11
+ 'output to a file by itself, and stderr kept separate makes a crash unmissable.')
12
+ _TRUNC = re.compile(r'\|\s*(tail|head)\s+(-n\s*)?-?([1-9]|1[0-9])\b')
13
+ _MERGE = re.compile(r'2>\s*&\s*1')
14
+
15
+
16
+ def bash_guard_msg(cmd):
17
+ "The objection `cmd` earns - a sub-20-line head/tail pipe, or a 2>&1 stderr merge - else None"
18
+ if _MERGE.search(cmd): return NO_STDERR_MERGE
19
+ return NO_TRUNCATE if _TRUNC.search(cmd) else None
20
+
21
+
22
+ Q_NOTICE = ('This prompt ends with a question mark, so it seems to be a question. Claude Code bug: a tool call '
23
+ 'after your answer text hides the answer. Do all your tool calls first, as many as the question needs, '
24
+ 'then write the answer and stop.')
25
+ READ_NOTICE = ('This prompt appears to contain a request to read something. If it could reasonably be interpreted that way, '
26
+ 'read the target in full NOW, before composing any response: a notebook via summary_dlg then view_dlg/find_msgs as needed; '
27
+ 'a .py or other text file in full. Never respond from assumed or remembered contents.')
28
+ APPROVAL_NOTICE = ('This bare approval covers exactly what was explicitly agreed, nothing more. Before '
29
+ 'acting, check that each thing you are about to do was confirmed by the user - not merely proposed, '
30
+ 'listed, or summarized by you. If approval of any item is uncertain, it is not approved: ask.')
31
+
32
+
33
+ Q_NOTICE_CODEX = ('This prompt ends with a question mark, so it seems to be a question. Answer it directly, '
34
+ 'making only the tool calls needed to get the answer, before and instead of any further work.')
35
+ BTW_NOTICE = ('This prompt begins with `BTW ` and is a side request. Answer it first, then resume the '
36
+ 'previously active task if it still has unfinished items. Do not treat the side request as replacing '
37
+ 'or cancelling that task unless the user explicitly says so.')
38
+
39
+
40
+ def prompt_notices(prompt, q_notice=Q_NOTICE):
41
+ "Notices a submitted prompt earns: question-mark answer-first, read-in-full, bare-approval scope, and BTW side-request"
42
+ out = []
43
+ if prompt.rstrip().endswith('?'): out.append(q_notice)
44
+ if 'please read' in prompt.lower(): out.append(READ_NOTICE)
45
+ if re.sub(r'^\s+|[\s.!]+$', '', prompt.lower()) in ('go', 'ok'): out.append(APPROVAL_NOTICE)
46
+ if prompt.startswith('BTW '): out.append(BTW_NOTICE)
47
+ return out
48
+
49
+
50
+ def synthetic_resume(path):
51
+ "The last compact boundary's epoch time when the transcript compacted after its last SessionStart delivery (this 'resume' rebuilt a compacted context), else None"
52
+ p = Path(path)
53
+ if not p.is_file(): return None
54
+ b = s = -1
55
+ bt = None
56
+ for i, line in enumerate(p.open()):
57
+ try: r = json.loads(line)
58
+ except json.JSONDecodeError: continue
59
+ if r.get('type') == 'system' and r.get('subtype') == 'compact_boundary': b, bt = i, r.get('timestamp')
60
+ if r.get('type') == 'attachment' and r.get('attachment', {}).get('hookEvent') == 'SessionStart': s = i
61
+ if b > s: # a boundary without a timestamp reads as "now", disabling the age guard so the reset stays unconditional
62
+ return datetime.fromisoformat(bt.replace('Z', '+00:00')).timestamp() if bt else datetime.now().timestamp()
63
+
64
+
65
+ COMPACT_MSG = '**Post-compaction: your context was rewritten — doc() output is gone and skill texts are stale snapshots — but the kernel process survived untouched: namespace, imports, and current-notebook defaults are all still live, so do not re-run startup or re-import.** Read doc(f) again before using any tooling function whose docs you no longer hold. Re-invoke `persistent-python` now — the live SKILL.md always wins over a replayed snapshot. You will need to redo the dojo. The summary\'s "resume directly / pick up the last task" instruction applies only when it records work actually in flight: if the last user message was already answered and no task is open, do not re-answer or resume anything from before the compact — reply with one short line and wait for the next message.'
66
+ SYNTH_MSG = '**Post-compaction resume: the conversation context was rewritten and the kernel restarted with a clean namespace.** Tool documentation and skill text shown in the reconstructed history may be truncated or stale: read doc(f) again before using any tooling function whose docs you no longer hold. Re-invoke `persistent-python` now, and rebuild variables, current-notebook defaults, and monkeypatches on demand. Keep any dojo completion id from your context. The summary\'s "resume directly / pick up the last task" instruction applies only when it records work actually in flight: if the last user message was already answered and no task is open, do not re-answer or resume anything from before the compact — reply with one short line and wait for the next message.'
67
+ RESUME_MSG = '**Post-resume: your context is exactly as it was when the app closed — everything you can still see (doc() output, dojo completion id) remains valid — but the kernel restarted with a clean namespace (startup.py re-ran, so its imports are back).** Rebuild other session state on demand (variables, set_dlg, monkeypatches), and pass a dojo completion id from your context to dojo_start(id) before file work.'
68
+ BOOTSTRAP_MSG = '**NEVER touch local files or run code before completing the bootstrap. "Touch" means any file read, edit, search, or listing (Read/Edit/Grep/Glob, Bash, `fd`/`rg`), any clikernel `execute`, and any subagent that would do these on your behalf — however small it looks: one quick read counts, one search counts, "just checking one thing" counts. Bootstrap = invoke the `persistent-python` skill, run `from llmdojo.dojo import *; dojo_start()` and complete every task it prints (if a completion id from a clean round is in your context, `dojo_start(id)` replays it instantly). Work that never reaches for the filesystem — pure discussion, web research, browser automation — never hits the trigger and needs no bootstrap. Why: this project runs on a persistent Python workbench with curated pyskills, and unbootstrapped sessions reliably regress to ad-hoc Bash and one-off scripts that cost more to review than the dojo costs to run.** After bootstrapping, map each task to a pyskill from the `list_pyskills()` catalog before reaching for Bash, and read the project `README.md` and `DEV.md` before starting work.'
69
+ NBDEV_MSG = '**This is an nbdev project: notebooks in `nbs/` are the source of truth, and the exported `.py` files are autogenerated — never edit them.** Before your FIRST edit to any .ipynb you MUST: read doc(nbdev.skill). If its output is not visible in your current context, you have not read it — "I know nbdev" is the trigger to read it, not to skip it, because it documents where this house\'s style differs from your priors. Editing a notebook without it is the same class of error as editing a generated `.py`. Search notebooks by cell id (not line numbers) with the notebook-aware search pyskill, and never grep the generated `.py`. Edit cells through the hash-verified edit pyskill, never the `.py`.'
70
+ BLOCK_EDIT_MSG = 'Native file write/edit tools are blocked in this environment: make the edit via the clikernel session instead (exhash / %%exhash, pyskills.edit, pyskills.ipynb).'
71
+
72
+
73
+ def claude_session_start(o):
74
+ "SessionStart: orientation notice by source, then Python-project bootstrap and nbdev addenda"
75
+ d = Path(os.environ.get('CLAUDE_PROJECT_DIR') or os.getcwd())
76
+ src = o.get('source', '')
77
+ if src in ('resume', 'compact'): print(f'[{src} at {datetime.now():%H:%M:%S}]')
78
+ if src == 'compact':
79
+ print(COMPACT_MSG)
80
+ elif src == 'resume' and synthetic_resume(o.get('transcript_path', '')): print(SYNTH_MSG)
81
+ elif src == 'resume' and (d/'pyproject.toml').is_file(): print(RESUME_MSG)
82
+ if (d/'pyproject.toml').is_file(): print(BOOTSTRAP_MSG)
83
+ try: nb = any(l.startswith('[tool.nbdev]') for l in (d/'pyproject.toml').open())
84
+ except OSError: nb = False
85
+ if nb: print(NBDEV_MSG)
86
+
87
+
88
+ def _prompt_submit(o, q_notice):
89
+ ns = prompt_notices(o.get('prompt') or '', q_notice)
90
+ if ns: print(json.dumps(dict(hookSpecificOutput=dict(
91
+ hookEventName='UserPromptSubmit', additionalContext='\n'.join(ns)))))
92
+
93
+
94
+ def claude_prompt_submit(o):
95
+ "Claude UserPromptSubmit: emit all notices as one hookSpecificOutput JSON object"
96
+ _prompt_submit(o, Q_NOTICE)
97
+
98
+
99
+ def codex_prompt_submit(o):
100
+ "codex UserPromptSubmit: emit all notices as one hookSpecificOutput JSON object"
101
+ _prompt_submit(o, Q_NOTICE_CODEX)
102
+
103
+
104
+ def claude_bash_guard(o):
105
+ "PreToolUse(Bash): reject output-truncating pipes"
106
+ if m := bash_guard_msg(o.get('tool_input', {}).get('command') or ''):
107
+ print(m, file=sys.stderr)
108
+ sys.exit(2)
109
+
110
+
111
+ def claude_block_native_edit(o):
112
+ "PreToolUse(Write|Edit|NotebookEdit): route edits to the kernel tooling"
113
+ print(BLOCK_EDIT_MSG, file=sys.stderr)
114
+ sys.exit(2)
115
+
116
+
117
+ AIR_ROUNDS, AIR_RENUDGE, AIR_SUBSTANCE = 8, 5, 100
118
+ AIR_MSG = 'You may have made {0} tool rounds without surfacing. Write real response text that re-points your attention (long runs collapse it onto recent results): restate the request, including one constraint you\'d stopped mentioning; name your most questionable recent tool call (nbdev => nb tooling, pyskills over Bash, exhash for edits, wrapping param in unneeded str() or Path().expanduser, unneeded final print()) and correct it if wrong (do not mention this in your final reply to the user); state the next step. Write any upcoming user-facing text in GOV.UK style. One idea per sentence. No dash asides, no semicolon joins. Re-read any docstrings, docs, or comments you wrote since the last surfacing and fix them to the same standard. If this reads like your last surfacing, you haven\'t reconnected.'
119
+
120
+
121
+ def _state_file(kind, sid):
122
+ "Per-session state file of the given `kind` under the shared state root, sweeping abandoned siblings"
123
+ d = Path(os.environ.get('LLMDOJO_STATE_DIR', Path.home()/'.local/state/llmdojo'))/kind
124
+ d.mkdir(parents=True, exist_ok=True)
125
+ import time
126
+ for g in d.glob('*'):
127
+ try:
128
+ if g.stat().st_mtime < time.time() - 86400: g.unlink(missing_ok=True)
129
+ except FileNotFoundError: pass # a concurrent sweep got it first
130
+ return d/f'{sid}.json'
131
+
132
+
133
+ def claude_air(o):
134
+ "UserPromptSubmit/MessageDisplay/PostToolBatch: nudge after AIR_ROUNDS tool rounds with no substantive text"
135
+ f = _state_file('air', o.get('session_id', ''))
136
+ try: st = json.loads(f.read_text())
137
+ except (OSError, ValueError): st = {} # missing, torn by a concurrent writer, or otherwise unreadable: start fresh
138
+ if not isinstance(st, dict): st = {}
139
+ st = {k: st.get(k, d) for k, d in dict(rounds=0, nudged=0, mid='', midlen=0).items()}
140
+ ev = o['hook_event_name']
141
+ if ev == 'UserPromptSubmit': st.update(rounds=0, nudged=0)
142
+ elif ev == 'MessageDisplay':
143
+ if o.get('message_id') != st['mid']: st.update(mid=o.get('message_id'), midlen=0)
144
+ st['midlen'] += len(o.get('delta') or '')
145
+ if o.get('final') and st['midlen'] >= AIR_SUBSTANCE: st.update(rounds=0, nudged=0)
146
+ elif ev == 'PostToolBatch':
147
+ st['rounds'] += 1
148
+ if st['rounds'] >= AIR_ROUNDS and st['rounds'] - st['nudged'] >= AIR_RENUDGE:
149
+ st['nudged'] = st['rounds']
150
+ print(json.dumps(dict(hookSpecificOutput=dict(
151
+ hookEventName='PostToolBatch', additionalContext=AIR_MSG.format(st['rounds'])))))
152
+ tmp = f.with_suffix(f'.{os.getpid()}.tmp') # concurrent hook processes share this file: atomic replace, never a torn write
153
+ tmp.write_text(json.dumps(st))
154
+ tmp.replace(f)
155
+
156
+
157
+ # Port of podlayer/message-drop-sentinel (MIT). Workaround for a live platform bug: mid-turn
158
+ # `thinking -> text -> thinking -> tool_use` drops the text upstream - never rendered, never in the
159
+ # transcript, gone from the agent's replayed context - leaving two ADJACENT thinking blocks as a scar.
160
+ # Retire when fixed; upstream reports and the re-test recipe are in that repo's README.
161
+ DROP_MSG_BATCH = 'Two thinking blocks in a row appeared in this turn: you probably just emitted text that the platform silently ate (it reached neither the user nor the transcript, and will not be in your future context). If the user should see it, say it again in your turn-final message; if the user may need it NOW, say it now and immediately end the turn.'
162
+ DROP_MSG_STOP = 'Two thinking blocks in a row appeared in this turn: text you emitted mid-turn may have been silently dropped (it reached neither the user nor the transcript, and will not be in your future context). If your turn-final message already contains everything the user needs, reply with exactly "ok" and nothing else - do not re-summarize. Only if something important appears nowhere in your final message should you state that missing thing now: just the missing part, not a recap.'
163
+
164
+
165
+ def _is_user_prompt(r):
166
+ "A real user prompt record: non-meta, plain text content, not a tool_result carrier"
167
+ if r.get('type') != 'user' or r.get('isMeta'): return False
168
+ c = (r.get('message') or {}).get('content')
169
+ if isinstance(c, str): return True
170
+ return isinstance(c, list) and any(b.get('type') == 'text' for b in c) and not any(b.get('type') == 'tool_result' for b in c)
171
+
172
+
173
+ def count_scars(transcript_path):
174
+ "`(scars, prompt_uuid)` for the current turn: adjacent thinking-block pairs mark where a dropped text used to be"
175
+ recs = []
176
+ for line in Path(transcript_path).open():
177
+ try: recs.append(json.loads(line))
178
+ except ValueError: pass # blank or malformed line
179
+ start = 0
180
+ for i, r in enumerate(recs):
181
+ if _is_user_prompt(r): start = i
182
+ types = [b.get('type') for r in recs[start:] if r.get('type') == 'assistant' and isinstance((r.get('message') or {}).get('content'), list)
183
+ for b in r['message']['content']]
184
+ scars = sum(1 for a, b in zip(types, types[1:]) if a == b == 'thinking')
185
+ return scars, (recs[start].get('uuid') if recs else None)
186
+
187
+
188
+ def claude_drop_sentinel(o):
189
+ "PostToolBatch/Stop: detect thinking-sandwich message drops via the transcript scar, and prompt a pinned restate"
190
+ try:
191
+ if o.get('agent_id'): return # a subagent's deliverable is its turn-final message: the shape the bug never touches
192
+ tp = o.get('transcript_path')
193
+ if not tp or not Path(tp).is_file(): return
194
+ scars, uid = count_scars(tp)
195
+ f = _state_file('drop-sentinel', o.get('session_id', ''))
196
+ try: st = json.loads(f.read_text())
197
+ except (OSError, ValueError): st = {}
198
+ done = st.get('reported', 0) if isinstance(st, dict) and st.get('prompt_uuid') == uid else 0
199
+ if scars <= done: return # whichever boundary reports first claims the holes
200
+ tmp = f.with_suffix(f'.{os.getpid()}.tmp')
201
+ tmp.write_text(json.dumps(dict(prompt_uuid=uid, reported=scars)))
202
+ tmp.replace(f)
203
+ if o['hook_event_name'] == 'PostToolBatch':
204
+ print(json.dumps(dict(hookSpecificOutput=dict(hookEventName='PostToolBatch',
205
+ additionalContext=DROP_MSG_BATCH))))
206
+ else: print(json.dumps(dict(decision='block', reason=DROP_MSG_STOP)))
207
+ except Exception as e: print(f'[drop-sentinel] fail-open: {e!r}', file=sys.stderr)
208
+
209
+
210
+ SLOP_WORST, SLOP_DENSITY, SLOP_WORDS, SLOP_TOP = 10, 10, 40, 8
211
+ SLOP_MSG = ("slopometer: your previous turn's final message scored density {d} (flag threshold {t}), worst finding {w}. "
212
+ 'The rows below apply to your own prose only: a span that is a quoted example, discussed text, or a title needs no change. '
213
+ 'Write your reply to the prompt above in the reference register, avoiding these patterns.\n{rows}')
214
+ SLOP_RESTATE = ('The user sent a bare ";": they did not understand your previous reply. Restate it in simple precise English: '
215
+ 'short sentences, named actors, plain words, no joins, and define every term you keep.')
216
+ SLOP_CAVEAT = ('The user sent a bare "\'": your previous reply appears to contain a caveat in the last or penultimate paragraph, and they cannot tell whether it is '
217
+ 'a real critical issue they must fully understand and respond to before proceeding, or an LLM sign-off habit they need not act on. '
218
+ 'Say plainly which it is. If real, restate the issue, what hangs on it, and what response it needs; if habit, withdraw it.')
219
+
220
+
221
+ _SLOP_KEYS = dict(mid='', buf='', last='', lastmid='', done='')
222
+
223
+ def _slop_state(f):
224
+ try: st = json.loads(f.read_text())
225
+ except (OSError, ValueError): st = {}
226
+ if not isinstance(st, dict): st = {}
227
+ return {k: st.get(k, d) for k, d in _SLOP_KEYS.items()}
228
+
229
+ def _slop_report(txt):
230
+ "Zero or one scored-message notices for `txt`, applying the env-tunable thresholds"
231
+ if len(txt.split()) < int(os.environ.get('SLOP_WORDS', SLOP_WORDS)): return []
232
+ from shutil import which
233
+ if not which('slopometer'): return []
234
+ import subprocess
235
+ r = subprocess.run(['slopometer', '--json'], input=txt, capture_output=True, text=True, timeout=60)
236
+ if r.returncode: return []
237
+ j = json.loads(r.stdout)
238
+ worst_min = int(os.environ.get('SLOP_WORST', SLOP_WORST))
239
+ dens_min = float(os.environ.get('SLOP_DENSITY', SLOP_DENSITY))
240
+ if not (j['worst'] >= worst_min or j['density'] >= dens_min): return []
241
+ def row(f):
242
+ tl = f" (tell {f['tell']})" if f['tell'] is not None else ''
243
+ return f"[{f['weight']}] {f['rule']}{tl}: {f['text']!r}"
244
+ rows = '\n'.join(row(f) for f in j['findings'][:SLOP_TOP])
245
+ return [SLOP_MSG.format(d=j['density'], t=dens_min, w=j['worst'], rows=rows)]
246
+
247
+
248
+ def claude_slop(o):
249
+ "MessageDisplay/UserPromptSubmit: track the displaying message, then report the previous turn's score with the new prompt"
250
+ try:
251
+ if o.get('agent_id'): return
252
+ f = _state_file('slop', o.get('session_id', ''))
253
+ st = _slop_state(f)
254
+ if o['hook_event_name'] == 'MessageDisplay':
255
+ if o.get('message_id') != st['mid']: st.update(mid=o.get('message_id'), buf='')
256
+ st['buf'] += o.get('delta') or ''
257
+ if o.get('final'): st['last'], st['lastmid'] = st['buf'], st['mid']
258
+ tmp = f.with_suffix(f'.{os.getpid()}.tmp')
259
+ tmp.write_text(json.dumps(st))
260
+ tmp.replace(f)
261
+ return
262
+ notes = []
263
+ if (o.get('prompt') or '').strip() == ';': notes.append(SLOP_RESTATE)
264
+ if (o.get('prompt') or '').strip() == "'": notes.append(SLOP_CAVEAT)
265
+ txt, fresh = st['last'], st['lastmid'] != st['done']
266
+ if txt and fresh:
267
+ st['done'] = st['lastmid']
268
+ tmp = f.with_suffix(f'.{os.getpid()}.tmp')
269
+ tmp.write_text(json.dumps(st))
270
+ tmp.replace(f)
271
+ notes += _slop_report(txt)
272
+ if notes: print(json.dumps(dict(hookSpecificOutput=dict(
273
+ hookEventName='UserPromptSubmit', additionalContext='\n'.join(notes)))))
274
+ except Exception as e: print(f'[slop] fail-open: {e!r}', file=sys.stderr)
275
+ def codex_orientation(o):
276
+ "codex PostCompact/SessionStart/PreToolUse: one-shot post-compaction reorientation"
277
+ state = Path(os.environ.get('LLMDOJO_STATE_DIR', Path.home()/'.local/state/llmdojo'))
278
+ markers = state/'compact'
279
+ marker = markers/f"{o['session_id']}.json"
280
+ event = o['hook_event_name']
281
+ import llmdojo
282
+ message = ('Context was compacted, so the clikernel documentation is no longer in context. Read the startup documentation in '
283
+ 'two separate calls: first `doc(clik,pysk,edsk)`, then `doc(dsk,exh,rgsk)`. Run `doc()` for '
284
+ 'anything else you need as you continue. Do not rerun the dojo. After running the two `doc()` calls, retry your last tool '
285
+ 'call; it should now work. Then continue your existing task if it is not complete.')
286
+ sample = (Path(llmdojo.__file__).parent/'dojo_data/codexdojo_sample.md').read_text()
287
+ message += ('\n\nThe following is a sample usage session from before compaction. Treat it as reference '
288
+ 'for correct tool usage; do not repeat or score it.\n\n') + sample
289
+ if event == 'PostCompact':
290
+ markers.mkdir(parents=True, exist_ok=True)
291
+ marker.write_text(json.dumps(dict(turn_id=o.get('turn_id'))))
292
+ elif event == 'PreToolUse':
293
+ try: marker.unlink()
294
+ except FileNotFoundError: pass
295
+ else: print(json.dumps(dict(hookSpecificOutput=dict(hookEventName='PreToolUse', permissionDecision='deny', permissionDecisionReason=message))))
296
+ elif event == 'SessionStart':
297
+ try: marker.unlink()
298
+ except FileNotFoundError: pass
299
+ else: print(json.dumps(dict(hookSpecificOutput=dict(hookEventName='SessionStart', additionalContext=message))))
300
+
301
+
302
+ def main():
303
+ "Dispatch `aai-hook <subcommand>` to its handler with the stdin JSON payload"
304
+ globals()[sys.argv[1].replace('-', '_')](json.load(sys.stdin))
@@ -0,0 +1,20 @@
1
+ r'''Official docs for the tool you are running in (Claude Code or codex): read before answering questions about its behaviour, config, or features.
2
+
3
+ # Harness Docs
4
+
5
+ 1. Work in `clikernel`, with the `exhash` pyskill loaded. Open the docs index in one step, never displaying the raw text: `toc = open_doc(llms_txt(<your harness>))`.
6
+ 2. Find the page with `toc.links('<topic>')`: a few `[n] Title: description` rows are the whole display. Pick the row whose title matches the question.
7
+ For codex the index is the whole OpenAI developers hub (the codex-scoped llms.txt their docs link to is a 404), so narrow to Codex first: `toc.search('^## Codex')` lists one `Codex — <Topic>` row per page with its address token, then `toc.at('<token copied from that row>').links('')` gives that page's followable row. A bare `toc.links('<topic>')` over the hub matches other OpenAI products too.
8
+ 3. Open it with `page = toc.open(n)`: fetched, parsed, and `base`-recorded in one step. No URL is copied at any point. Never fetch `llms-full.txt`. Pick the right page from the index instead.
9
+ 4. Display `page` bare and read the listing: every row ends with the section's size, so the whole-or-sections decision reads straight off it. At most 30,000 characters in total: display the whole `page.text`. A short page read whole gives an overview sections cannot. Larger: do not display it. `page.search('<topic>')` shows `token title (count) [size] preview` rows; retrieve matching sections with `at('<token copied from a row>')`, or `paths(2)` when structure itself is the question. Never display an arbitrary slice. The choice is the whole page or selected sections, nothing between. Fetch shared sections separately when an event-specific section refers to them.
10
+ 5. Use the official documentation for documented interfaces and normal day-to-day behavior. Some questions the docs do not answer. For codex, dive into its source, which is open. For Claude Code, which ships no public source, check the changelog and What's New pages for recent changes, and investigate observed behavior directly (settings files, `--help`, `/doctor`).
11
+ 6. Base the answer on the strongest applicable evidence: documented contracts for public behavior, matching source for implementation details where available, and direct observation for runtime behavior. Distinguish among them when it matters.
12
+ '''
13
+
14
+ __all__ = ['llms_txt']
15
+
16
+ def llms_txt(
17
+ harness: str, # 'claude' or 'codex'
18
+ ) -> str:
19
+ "URL of `harness`'s official llms.txt docs index"
20
+ return dict(claude='https://code.claude.com/docs/llms.txt', codex='https://developers.openai.com/llms.txt')[harness]
aai_coding/llms.py ADDED
@@ -0,0 +1,40 @@
1
+ """Short model names and one-shot completion helpers for aai-coding's LLM agents, over fastllm.
2
+
3
+ `models` maps short names to full `'vendor/model'` specs (copied from solveit's model options).
4
+ `ask` runs a one-shot completion: pass a short name or any full spec, and get the response text back.
5
+ """
6
+
7
+ __all__ = ['models', 'response_text', 'ask']
8
+
9
+ from fastllm.acomplete import acomplete
10
+ from fastllm.chat import contents, mk_msgs
11
+
12
+ models = dict(sonnet='anthropic/claude-sonnet-5', sonnet46='anthropic/claude-sonnet-4-6', fable='anthropic/claude-fable-5',
13
+ opus='anthropic/claude-opus-4-8', opus46='anthropic/claude-opus-4-6',
14
+ luna='openai/gpt-5.6-luna', terra='openai/gpt-5.6-terra', sol='openai/gpt-5.6-sol',
15
+ flashlite='gemini/models/gemini-3.1-flash-lite', flash='gemini/models/gemini-3.5-flash', gemini='gemini/models/gemini-3.1-pro-preview',
16
+ qwen='fireworks_ai/accounts/fireworks/models/qwen3p7-plus', minimax='minimax/MiniMax-M3',
17
+ kimi='moonshot/kimi-k2.6', kimicode='moonshot/kimi-k2.7-code',
18
+ glm='fireworks_ai/accounts/fireworks/models/glm-5p2', glmfast='fireworks_ai/accounts/fireworks/routers/glm-5p2-fast',
19
+ dsflash='deepseek/deepseek-v4-flash', dspro='deepseek/deepseek-v4-pro',
20
+ codexluna='codex/gpt-5.6-luna', codexterra='codex/gpt-5.6-terra', codexsol='codex/gpt-5.6-sol')
21
+
22
+
23
+ def response_text(res):
24
+ "The visible text of an `acomplete` result: its message's text parts joined (thinking parts skipped)."
25
+ m = contents(res)
26
+ return '' if not m else ''.join(p.text for p in m.content if p.type == 'text' and p.text)
27
+
28
+
29
+ async def ask(
30
+ prompt, # The user message
31
+ model='sonnet', # A `models` short name, or any full 'vendor/model' spec
32
+ system=None, # Optional system prompt
33
+ effort=None, # Reasoning effort where the model supports it: 'low'/'medium'/'high'
34
+ max_tokens=8192, # Response cap; fastllm's own defaults are small
35
+ **kw, # Passed through to `acomplete`
36
+ ):
37
+ "One-shot completion returning the response text."
38
+ res = await acomplete(mk_msgs([prompt]), models.get(model, model), system=system,
39
+ reasoning_effort=effort, max_tokens=max_tokens, **kw)
40
+ return response_text(res)
aai_coding/looker.py ADDED
@@ -0,0 +1,71 @@
1
+ """Answer questions about images and PDFs by asking a separate codex process to look at them, which keeps large files out of this session (macOS only). Use it to verify rendered output: PDFs, screenshots, captured windows.
2
+
3
+ `look` sends the images to a fresh, ephemeral gpt-5.6-luna thread whose only context is the checker charter, your question, and the images, and returns its answer. `pdf2pngs` is the pure-Quartz page renderer it uses, independently useful wherever a PDF needs to become images (no CLI tools, no permissions, no size limit worries in *your* context). Needs `openai-codex` and PyObjC (workspace installs have both). `mdhtml2docx.word.win_pic` is one producer of window captures to check."""
4
+ from pathlib import Path
5
+ import Quartz
6
+ from Foundation import NSURL
7
+
8
+ __all__ = ['pdf2pngs', 'look']
9
+
10
+ _CHARTER = ('You are a visual checker. The turn contains questions followed by one or more images; '
11
+ 'PDF pages arrive as one image per page, in order.\n'
12
+ '- Answer exactly the questions asked. Nothing else.\n'
13
+ '- Be concise and factual: report what is visible, not what you infer or expect. '
14
+ 'If asked about text, quote it verbatim.\n'
15
+ '- If something asked about is not visible, absent, or illegible, say so plainly.\n'
16
+ '- Mention anything clearly anomalous (error dialogs, repair banners, blank pages) '
17
+ 'even if not asked, in one sentence.\n'
18
+ '- Never guess. If an image is unreadable, report that as your answer.')
19
+
20
+
21
+ def _png(img, path):
22
+ "Write CGImage `img` as png to `path`, returning it"
23
+ dst = Quartz.CGImageDestinationCreateWithURL(NSURL.fileURLWithPath_(str(path)), 'public.png', 1, None)
24
+ Quartz.CGImageDestinationAddImage(dst, img, None)
25
+ if not Quartz.CGImageDestinationFinalize(dst): raise ValueError(f'could not write png to {path}')
26
+ return path
27
+
28
+
29
+
30
+ def pdf2pngs(path, dest_dir=None, scale=2):
31
+ "Render each page of the PDF at `path` as `<stem>-<n>.png` in `dest_dir` (default: alongside), returning the paths"
32
+ p = Path(path).expanduser().resolve()
33
+ pdf = Quartz.CGPDFDocumentCreateWithURL(NSURL.fileURLWithPath_(str(p)))
34
+ if pdf is None: raise ValueError(f'not a readable PDF: {p}')
35
+ d = Path(dest_dir).expanduser() if dest_dir else p.parent
36
+ d.mkdir(parents=True, exist_ok=True)
37
+ cs = Quartz.CGColorSpaceCreateDeviceRGB()
38
+ out = []
39
+ for n in range(1, Quartz.CGPDFDocumentGetNumberOfPages(pdf) + 1):
40
+ page = Quartz.CGPDFDocumentGetPage(pdf, n)
41
+ r = Quartz.CGPDFPageGetBoxRect(page, Quartz.kCGPDFMediaBox)
42
+ w, h = int(r.size.width*scale), int(r.size.height*scale)
43
+ ctx = Quartz.CGBitmapContextCreate(None, w, h, 8, 0, cs, Quartz.kCGImageAlphaPremultipliedLast)
44
+ Quartz.CGContextSetRGBFillColor(ctx, 1, 1, 1, 1)
45
+ Quartz.CGContextFillRect(ctx, Quartz.CGRectMake(0, 0, w, h))
46
+ Quartz.CGContextScaleCTM(ctx, scale, scale)
47
+ Quartz.CGContextDrawPDFPage(ctx, page)
48
+ fp = _png(Quartz.CGBitmapContextCreateImage(ctx), d/f'{p.stem}-{n}.png')
49
+ out.append(fp)
50
+ return out
51
+
52
+ async def look(
53
+ question, # What to check; be specific, and say what the images are
54
+ *paths, # Image and/or PDF files (PDFs are rasterized per page)
55
+ model='gpt-5.6-luna',
56
+ effort='medium', # Codex reasoning effort: 'none'/'minimal'/'low'/'medium'/'high'/'xhigh'
57
+ scale=2, # Rasterization scale for PDF pages
58
+ ):
59
+ "Answer `question` about the files at `paths` via an isolated codex thread. Needs `openai-codex`."
60
+ from tempfile import TemporaryDirectory
61
+ from openai_codex import AsyncCodex, LocalImageInput, Sandbox, TextInput
62
+ from openai_codex.api import ReasoningEffort
63
+ with TemporaryDirectory() as td:
64
+ imgs = []
65
+ for p in map(Path, paths):
66
+ if p.suffix.lower() == '.pdf': imgs += pdf2pngs(p, td, scale=scale)
67
+ else: imgs.append(p)
68
+ async with AsyncCodex() as cx:
69
+ th = await cx.thread_start(model=model, sandbox=Sandbox.read_only, ephemeral=True, base_instructions=_CHARTER)
70
+ res = await th.run([TextInput(question), *(LocalImageInput(str(i)) for i in imgs)], effort=ReasoningEffort(effort))
71
+ return res.final_response
aai_coding/theory.py ADDED
@@ -0,0 +1,23 @@
1
+ r'''What "Theory" (capital T) means in this team's vocabulary: Peter Naur's programming-as-theory-building. Read when the user says the Theory of something, or asks to discuss, find, or capture a Theory.
2
+
3
+ # The Theory
4
+
5
+ "Theory" here is Naur's sense, from his 1985 paper Programming as Theory Building. A program is not its source code or its docs. It is the theory held in its builders' minds: their understanding of how the code maps onto the world, why it is the way it is, and how it can be sensibly extended.
6
+
7
+ Consequences Naur draws:
8
+
9
+ - The main consequence is that the Theory needs to be held in the developers' minds. To do so, it needs to be expressed in its most minimal representation. There is always time to get into details later, but when discussing the Theory conciseness is king. It does not mean to exclude important details, it does not mean we want to give the developer the illusion of control. It means we iterate until we find the Core that is true and we want to anchor into.
10
+ - The theory cannot be fully written down. Documentation captures artifacts of the theory, not the theory itself, which is why "just read the docs" never fully onboards anyone.
11
+ - Program death: a program whose theory-holders have all left is effectively dead, even if it still runs. Reviving it is closer to rebuilding than reading.
12
+ - Modification quality depends on the theory, not the code. Someone with the theory makes changes that fit the program's nature. Someone without it makes patches that gradually corrode the design.
13
+
14
+ # Using it
15
+
16
+ When jumping into a new codebase, figure out the Theory first, then understand the code through it: the driving facts or constraints, the derivation of the design from them, and the alternatives rejected and why.
17
+
18
+ When reviewing a PR, ask what Theory the change assumes and whether that matches the Theory of the codebase. A patch can be locally correct and still theory-violating, and that class of problem is invisible to line-by-line review.
19
+
20
+ When the user says "the Theory of X", this vocabulary is assumed; do not re-explain Naur. Discussing a Theory means talking it through in conversation. Do not turn it into a process, a checklist, or markdown files unless the user explicitly asks for a written artifact.
21
+
22
+ IMPORTANT: when stating or discussing a Theory, follow `aai_coding.write_prose` closely. A Theory lives in minds, and its statement must be plain enough to hold there.
23
+ '''