Publish the thinking-python specification (draft 1)
Browse filesFiles changed (2)
- README.mdAdded+54
- SPECIFICATION.mdAdded+516
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354---license: mittags:- linguistics- code- dataset- specificationlanguage:- ar- en- es- hi- it- zhpretty_name: LingoLOGOS thinking-python specification---
# LingoLOGOS thinking-python - specification
This folder carries the **specification** of the thinking-python bundle: an N-agent topologyand the dataset that turn free natural-language text about Python code into a verified changein a Python workspace. The specification is published first, before any code, so the contractcan be reviewed and implemented independently.
The one file here is [SPECIFICATION.md](SPECIFICATION.md). It is normative: where code andthis file disagree, the code is wrong until this file is amended in the same change.
## What the document states
| Section | Subject ||---|---|| 0 | Confinement: the programmer works only inside `datasets/thinkingpython/`, enforced by code || 1-2 | The three claims the bundle publishes, and the vocabulary || 3 | The 7-node topology: `intent -> locator -> planner -> executor -> {gate_checker, adversary} -> arbiter`, with only `intent` allowed to be non-deterministic || 3.1 | Compliance with the sibling bundles: the `python tools/ask.py` contract, the throwaway workspace, `MultiInstanceOrchestrator` used read-only, exit codes, transcript re-derivation of the verdict || 4 | An extensible catalog with an open fallback: GoF patterns, Fowler refactorings, development methodologies || 5 | The edit-pair invariant: no source edit lands without a test that locks it || 6 | The dataset in five layers plus an adversarial set, generated and re-derivable || 6.4 | No off-the-shelf language model: the intent node runs on the catalog's own surface forms plus an optional small classifier trained from the corpus || 6.5 | The six language varieties of the genesis topology: `ar, en, es, hi, it, zh`, declared and never inferred || 7-9 | Interfaces, self-applied development methodology, reason-code registry || 10-12 | Folder layout, acceptance criteria D0-D7, explicit prohibitions |
## Status
Draft 1, normative. No code, no corpus and no weights are published in this revision: theacceptance criteria of section 11 describe what a later revision must show before it canclaim anything.
## Provenance
Part of the LingoLOGOS project. The topology follows the same envelope, node and orchestratorcontract as the other datasets of the project (`codex`, `codex-python`, `genesis`, `physics`,`math`, `geometry`, `struc`), which are not included here and are not modified by this bundle.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516# LingoLOGOS thinking-python - Specification of the bundle
Status: draft 1, normative. This file is the contract a programmer implements. Where thisfile and code disagree, the code is wrong until this file is amended in the same change.
Language: English only, ASCII only, per `AGENTS.md` section 2.
---
## 0. Confinement rule (binding, checked, not requested)
**The programmer works only inside `datasets/thinkingpython/`.**
1. Every file created, edited or deleted by the implementation lives under `datasets/thinkingpython/`. No file outside that directory may be created, renamed, moved or deleted, at any point, including scratch files, temporary files, logs, caches and generated corpora.2. No file outside that directory may be modified. This includes `README.md`, `doc/TECHNICAL_DOCUMENTATION.md`, `requirements.txt`, `pyproject.toml`, `src/`, `artifacts/`, `datasets/codex/`, `datasets/codex-python/` and every other sibling bundle. The publication row in the top table of `README.md` is the one exception and it is **not** written by this bundle: it is added by the maintainer when the asset is published, as `AGENTS.md` section 1 requires.3. Dependencies outside the directory are **read-only**. The bundle may import `lingologos_codex` (from `datasets/codex`) and may read files of any workspace it is pointed at, but it may not write to a folder it does not own except to the workspace the caller explicitly passed as `--workspace`.4. The rule is enforced by code, not by convention: - `tools/selfcheck_confine.py` walks `git status --porcelain` and fails with exit code 1 when any path outside `datasets/thinkingpython/` appears as added, modified, deleted or untracked. - `tests/test_confinement.py` asserts that no module of the package opens a file for writing whose resolved path leaves the package folder or the caller's workspace, by reading the syntax trees of every module (imports of `open(..., "w")`, `Path.write_*`, `shutil`, `os.remove`, `os.replace`). - `tools/run_gates.py` runs both before any other gate, and the gate line is `confinement`.5. A task that cannot be completed inside the directory is **not** completed by touching a file outside it. It is recorded in `doc/OPEN_QUESTIONS.md` (inside this folder) and the implementation stops there with the reason named.
Rationale: the bundle must be liftable as a standalone dataset and must never be thereason the host repository moves.
---
## 1. What this bundle is
An N-agent topology plus a dataset that turns **free natural-language text about Pythoncode** into a **verified change in a Python workspace**.
Unlike `datasets/codex-python`, which carries ten closed shape rules and refuses anythingelse, this bundle claims the **open** case: any change expressible in Python, produced bythe common design patterns and the standard development methodologies. The catalog istherefore an *extensible taxonomy with an open fallback*, not a closed list.
Three claims, and only these three, are what the dataset publishes:
| Claim | Meaning | How it is shown ||---|---|---|| C1 | text in, admissible plan out | an evaluation set of utterances with gold plans, scored || C2 | a plan becomes a change only through the kernel | verdicts `VERIFIED` / `SINGLE_PROVER` / `UNKNOWN` / `REFUSED` and reason codes || C3 | the catalog grows without breaking | adding a catalog entry adds rows and tests, never edits existing rows |
The bundle does **not** claim: understanding arbitrary prose, correctness of arbitraryPython, or any benchmark over real repositories. Coverage statements name theirdenominator, which is a fixture of this folder.
---
## 2. Vocabulary used by this specification
| Term | Definition ||---|---|| utterance | one piece of user text, one message || intent | a triple `(operation, subject, goal)` extracted from an utterance || plan | an ordered list of `step` records, each one machine executable || step | `{op, file, symbol?, search?, replace?, content?, test?}` || edit pair | a source edit plus the test that locks it, committed together || catalog entry | one named transformation this bundle knows how to carry out || verdict | one of the four kernel verdicts || reason code | one name from the registry of section 9 |
Every one of these has a JSON Schema under `schemas/`. A structure that does notvalidate is refused before any node runs. There is no informal object in this bundle.
---
## 3. Topology
N is a configuration value, not a constant. The default topology has 7 instances and therouting matrix is data.
```intent --> locator --> planner --> executor --> {gate_checker, adversary} --> arbiter ^ | |____________ retry _________|```
| id | role | nature | contract ||---|---|---|---|| `intent` | utterance to intent | the only learned or heuristic component | text in, `intent.json` out || `locator` | intent to concrete targets | deterministic: AST graph, PageRank, fuzzy name match | `intent.json` in, targets out || `planner` | targets to steps | deterministic: catalog lookup, then open planner | targets in, `plan.json` out || `executor` | steps to edit pairs | deterministic: catalog rule or structured patch writer | plan in, edit pairs out || `gate_checker` | independent prover | deterministic: compile gate, tests, optional checkers | verdict || `adversary` | second prover by another path | deterministic re-derivation | verdict || `arbiter` | consensus | deterministic | final verdict |
Rules the implementation must hold:
1. **Only `intent` may be non-deterministic.** Every other node is a pure function of its input. A rerun with the same utterance and the same workspace tree must produce the same plan hash, or the run must report `UNKNOWN` with reason `NONSENSE_REPLAY`.2. **Nodes speak one envelope**: the `lingologos-codex-envelope-1` shape already used by `datasets/codex`. One JSON object on stdin, one on stdout, no other channel, no shared memory, no files passed between nodes.3. **Every node is a separate executable** with `--role` and `--node-id`, so a topology is a process graph and not a Python import graph. Budgets: `--node-timeout SEC`, `--total-timeout SEC`; exhaustion answers `UNKNOWN` with `NODE_TIMEOUT`.4. **Retry changes fate, not words.** A second attempt whose patch signature equals the first is answered `CHECKER_ABSTAIN`. The retry loop is bounded by `maxTurns`.5. **Nothing is committed by a node.** Only the session layer writes, in one transaction, after the arbiter verdict clears the floor.
---
### 3.1 Compliance with the sibling bundles (the `tools/ask.py` contract)
The topology of this bundle is **not a private design**. It is an instance of the shape everysibling bundle exposes: `datasets/physics`, `datasets/math`, `datasets/struc`,`datasets/geometry`, `datasets/genesis` all answer one question through `python tools/ask.py`and all are driven by the same LingoLOGOS orchestrator. A programmer of this bundle implementsthat contract first and the Python specifics after.
The contract, item by item:
1. **One entry point**: `python tools/ask.py "<sentence>"` run from this folder. It accepts `--lang CODE` (the declared variety of section 6.5, one of the six), `--json` (full machine readable outcome), `--in-process` (the N agents in one process, the quicker path the tests use), `--corpus FILE` with `--limit N` (score every question against its gold and print a tally), `--keep` (keep the throwaway workspace), and the fault injection flag of the siblings is replaced here by `--faults agent:fault` limited to `tests/`, never by default. The printed outcome names the variety it answered in, as the siblings print the language they read.2. **Exit codes match the siblings**: `0` a verdict the session accepts, `2` `UNKNOWN`, `1` a corpus row that did not match its gold. Bad flags are argparse errors.3. **It builds a throwaway workspace, never a permanent one**: a `tempfile.mkdtemp(prefix = "lingologos_thinkingpython_")` holding the node folders, the seed carrying the question, a launcher for the node program, and a copy of `topology.json` whose `executable` fields point at that launcher. The workspace is deleted unless `--keep`.4. **The launcher is generated for the host**: `.cmd` on Windows, `.sh` with the executable bit set elsewhere, both wrapping `sys.executable` plus `agents/thinkingpython_agent.py`. No node may be launched by importing it.5. **The real orchestrator drives it**: `lingologos_orchestrator.orchestrator.MultiInstanceOrchestrator` is resolved by walking ancestors until a `src/lingologos_orchestrator` is found, exactly as the siblings do, and is used **read-only**. This bundle does not fork it, does not patch it, and does not add anything to it. The interface of the orchestrator used here is only `from_config_file`, `run_session`, `to_dict`, plus the `OrchestratorError` it raises.6. **`--in-process` must exist and must agree with the process path**: both paths produce the same final status, assurance and reasons, and `tests/test_ask.py` asserts that agreement on a fixed set of sentences. A run through the orchestrator is the authoritative one; the in-process run is the fast one the suite uses.7. **The verdict is re-derived from the transcript, not trusted from the node**: for every envelope, what the node claimed for its SMT status is set beside what the orchestrator's referee answered, and the decision of the chain is recomputed from that evidence. A node that claims more than the referee confirmed cannot raise the assurance.8. **Node folders follow the sibling layout**: `nodes/<id>/` carries `grammar.gf`, `ontology.smt2` and `seed_payload.json` with the envelope kind string of the kernel. The grammar note stating whether it was compiled with the GF toolchain in the authoring environment is mandatory, as the sibling cards carry it.9. **`topology.json` uses the same schema**: `$schema` of `topology-v1`, `sessionId`, `maxTurns`, `terminationCondition`, `instances[]` with `id`/`executable`/`role`, and a `routingMatrix[]` of `from`/`to`. Executables are written relative to `datasets/` when the folder sits in the repository, and the same test that reads the card checks that every instance names a file that exists and is executable.10. **The outcome block is a superset of the sibling one**: `status`, `assurance`, `answer_text`, `answer`, `reasons`, `failures`, plus the fields this bundle adds (`plan_hash`, `verdict`, `committed`, `touched_files`). Printed as a column of labelled lines by default, as the siblings print, and as JSON under `--json`.11. **A corpus mode is mandatory**, because a dataset without a scored entry point is not a dataset: `--corpus corpus/utterances.jsonl` scores L1 and prints the tally JSON, the same shape `tools/ask.py --corpus` prints in the siblings.12. **Environment discipline**: the script sets `PYTHONDONTWRITEBYTECODE=1` for the children and restores the parent environment in a `finally`. No environment variable of a sibling bundle is read or written; this bundle's variables are prefixed `LINGOLOGOS_TP_`.
Exception to section 0, stated here so it is not a contradiction: the throwaway workspace of`tools/ask.py` lives under the system temporary directory, which is outside this folder andoutside the repository. That is the only permitted write outside `datasets/thinkingpython/`,it is scratch, it is removed in a `finally`, and `tools/selfcheck_confine.py` ignores systemtemporary paths while still failing on any path inside the repository. The workspace a callernames with `--workspace` is a second, separate case: it is outside this folder, the callerchose it, and the writes there are the product of the bundle, never a scratch of it.
## 4. The catalog: how "every form of Python implementation" is allowed
The catalog is a data file, `catalog/patterns.json`, of entries with a **fixed schema andan open key space**. Each entry:
```json{ "id": "extract-method", "family": "refactoring", "source": "Fowler, Refactoring, catalog entry", "shape": "a statement block inside one function that reads no local it does not declare", "preconditions": ["the block is contiguous", "the block writes at most N names"], "effect": "the block becomes a module level function; the call site replaces the block", "lock": "a test that calls the new function and asserts the old behaviour", "refusals": ["BLOCK_NOT_CONTIGUOUS", "BLOCK_WRITES_FOREIGN_NAME"], "min_assurance": 3, "async_capable": true, "tests": ["tests/.../test_extract_method.py"]}```
Three families are mandatory in the first revision:
| Family | Contents the first revision must carry ||---|---|| `gof` | Creational: factory method, abstract factory, builder, singleton-as-registry, prototype. Structural: adapter, decorator, facade, proxy, bridge, composite. Behavioural: strategy, observer, command, template method, state, iterator, visitor, policy. || `refactoring` | extract method / function, inline, rename, introduce parameter object, replace conditional with polymorphism, replace inheritance with composition, introduce null object, introduce guard clause, replace magic literal with constant, decompose conditional, introduce assertion, replace loop with comprehension, hoist common code, introduce context manager, introduce dataclass, replace mutable default. || `methodology` | TDD red-green (a plan whose first step is a failing test), contract-first (docstring plus pre/post conditions plus a test), characterization test before refactor, seam introduction for testability, dependency injection through the constructor, property-based test addition, docstring-and-type pass, dead-code removal behind a green suite. |
Rules:
1. **Openness is a fallback path, not a license.** When no entry matches, the planner enters the `open` path: it may only emit steps of the primitive verbs (`edit`, `create`, `delete`) and those steps must pass the same gates and the same edit-pair rule as a catalog entry. An unmatched request is not refused because it is unknown; it is refused only when a gate, a precondition or the policy refuses it.2. **Every catalog entry ships as a pair: rule plus lock test.** An entry whose rule has no test is invalid and fails the `catalog_integrity` gate.3. **The catalog never mutates a previous entry.** Adding a family is additive; ids are permanent. Renaming an id requires keeping the old id as an alias and the corpus rows that named it byte-identical.4. **Design patterns are expressed as Python shapes, not as prose.** A `strategy` entry is a named shape over the syntax tree plus the edit texts it produces. A card that describes a pattern without producing text is documentation and belongs outside the catalog.
---
## 5. The edit-pair invariant (non-negotiable)
Every step that changes a source file produces **two** writes committed as onetransaction:
- the source edit;- a test that fails while the source is in its old shape and passes in the new one.
Consequences the implementation must reproduce:
1. If the test side cannot be produced, the source edit is refused with `NO_TEST_FILE` or `NO_TEST_ANCHOR`. There is no untested change in this bundle.2. If the disk rejects the transaction part way, both files are restored from the in-memory originals and the answer reports nothing landed.3. `committed` is true only after every written file has been read back and matched.4. A honesty gate runs, for every catalog entry, the experiment "write only the test side into a copy of the fixture and rerun the suite". If the copy still passes, the gate fails the bundle.5. A change may not add, delete or weaken an existing test to become green. A step whose diff removes an assertion is refused with `ASSERTION_REMOVED`.
---
## 6. Dataset composition
The dataset is generated, re-derivable, and versioned. Nothing in `corpus/` is handedited; the generator is `tools/build_corpus.py` and `--check` fails when the folderdisagrees with it.
### 6.1 Layers of the corpus
| Layer | File | Row shape | Purpose ||---|---|---|---|| L1 utterances | `corpus/utterances.jsonl` | `utterance`, `expected_plan_hash`, `expected_entry`, `targets`, `expect`, `reason_code?` | trains and scores the `intent` node || L2 plans | `corpus/plans.jsonl` | `utterance_id`, full `plan.json`, `verdict` | trains and scores the `planner` || L3 edit pairs | `corpus/edits.jsonl` | `plan_id`, `edits[]` with `file/search/replace`, `expect`, `min_assurance` | feeds the kernel case schema || L4 refusals | `corpus/refusals.jsonl` | `utterance`, `reason_code` | teaches abstention || L5 trajectories | `corpus/trajectories.jsonl` | the envelopes of a full run | regression and, later, learning |
L3 rows must validate against `lingologos_codex.casecorpus.validate_case_row`(`case_id, language, family, intent_tags, edits, expect, note`, plus the optional`reason_code, rule, pattern_id, targets, min_assurance`). Do not invent a parallelschema: extend through the optional fields or publish a versioned `case-2`.
### 6.2 How rows are produced
1. **Plant, then speak.** For every catalog entry, the generator plants the source shape into `fixtures/lab/` (a package of this folder), runs the rule, and records the edit pair. Then it renders the utterance from templates.2. **Labels are derived by execution.** A row survives only if a real `--dry-run` run on the fixture produces exactly the verdict the row claims. A row whose claimed verdict the machine contradicts is dropped by the generator and counted.3. **Utterance variation is systematic**: per entry, at least 5 registers (imperative, interrogative, first person, terse, verbose), all **six language varieties of section 6.5**, and 2 paraphrase families that never name the pattern. Sizes for the first revision: `>= 40 entries` and `>= 30 utterances per entry per variety` for L1, so `>= 7200` L1 rows, and a 70/15/15 split **by entry and by target symbol** so one symbol never appears in two splits.4. **Negatives are first class**: for every entry, at least one utterance whose target does not hold the shape (expected refusal with the code the rule raises), one ambiguous utterance (expected `AMBIGUOUS_TARGET`), one protected-path utterance (`PROTECTED_PATH`), one out-of-scope utterance (no entry matches, expected `UNKNOWN` or the open path), one already-applied utterance (`ALREADY_APPLIED`).5. **Adversarial set** `corpus/adversarial.jsonl`: contradictory instructions, instructions that ask to delete a test to become green, instructions that name a file that does not exist, prompt-injection text inside a docstring of the target file. Expected answer for every row is a refusal naming a code; the bundle must never be talked out of a gate.
### 6.3 Coverage statement
`results/coverage.json` states, for each entry: targets planted, targets in shape, rowsgenerated, refusals recorded, and the **denominator**, which is always the fixture of thisfolder and never "Python". The statement is regenerated with the corpus and the cardquotes it.
### 6.4 No off-the-shelf model is required
Nothing in this bundle downloads or depends on a pretrained language model. `intent` mustrun with: (a) a lexical and grammatical router built from the catalog's own surface forms,plus (b) an optional small classifier trained from L1 by `tools/train_intent.py`. Thetrained artifact is a weights file plus a vocabulary plus the catalog digest, publishedinside the folder, with no external weight. Any implementation of `intent` must satisfysection 3 rule 1 and the evaluation in section 8.
### 6.5 Language varieties (the same six the `genesis` topology carries)
The dataset supports the **same six varieties the genesis gateway carries**, and the set istaken from that contract, not invented here. `lingologos_gateway.lexicon.LANGS` is`(ar, en, es, hi, it, zh)`; this bundle carries one lexicon file per variety, for the samesix codes, and a variety outside that set is **not offered**.
Rules the implementation must hold:
1. **One file per variety**, `lexicon/<code>.json`, carrying the same required key set the gateway validates (`lang`, `name`, `noise`, `units`, `domains`, `frames`, `labels`, `examples`), where `frames` holds the surface forms of this bundle's catalog entries and `labels` the words an answer is assembled from. A file that is missing a key is invalid and fails the `lexicon` gate before any run.2. **The variety is declared, never inferred.** `--lang <code>` on the CLI, `lang` on the corpus row. There is no automatic language detection: an undetected variety is a wrong reading, and this bundle does not guess. A code such as `it_IT` normalizes to its head `it`, as the gateway normalizes it.3. **A declared variety with no lexicon answers, it does not crash.** The guard replies with the not-understood state and names the untranslated code, exactly as the gateway answers a French question today. A missing file never reaches a node.4. **Native script, punctuation and digits are inputs, not noise.** Arabic, Hindi, Chinese and Spanish forms (opening marks, the danda, the ideographic full stop, digit forms) are folded before matching, and the folding table per variety lives in the lexicon file, not in code.5. **The answer is worded in the variety of the question**: states, reasons and clarifying questions come from the `labels` block of that variety. What stays English ASCII always: reason codes, verdict names, JSON keys, file paths, symbol names, the prose of this folder, per `AGENTS.md` section 2.6. **Symmetric corpus, measured per variety.** Section 6.2 requires the six varieties per entry. `results/evaluation.json` reports top-1, out-of-scope refusal and clarification **per variety**, and the card quotes the worst variety, not the average. A variety that is carried but not measured is a defect, not a feature.7. **No language corpus is borrowed from another bundle.** The lexicons of this bundle live in this folder, derived from its own catalog. It reuses the *contract* of the gateway's lexicon and the same six codes; it does not read another bundle's lexicon files, and another bundle's vocabulary would not name this bundle's entries anyway.8. **Language of code is a separate axis and stays Python** (section 4). A user may write in any of the six varieties; the workspace the bundle edits is Python. The two fields are distinct on every row: `lang` for the utterance, `language` for the workspace, and neither is ever inferred from the other.
---
## 7. Interfaces
### 7.1 Package and CLI
- Folder: `datasets/thinkingpython`- Package: `lingologos_thinkingpython`- Entry: `python -B -m lingologos_thinkingpython`- Kernel resolution: an importable `lingologos_codex`, else `LINGOLOGOS_CODEX_ROOT`, else a sibling `codex/` or `datasets/codex/` among the ancestors. The kernel is not copied.
Verbs, with exit code `0` on success, `1` on refused/unknown, `2` on bad flags:
| verb | meaning ||---|---|| `python tools/ask.py "..."` | the sibling compliant entry point of section 3.1: one sentence in, one orchestrated run, one re-derived verdict || `work --workspace W --text "..."` | the whole pipeline, `--dry-run` by default, `--commit` to write || `plan --workspace W --text "..."` | the plan only, `--json` for data || `catalog list / show --entry ID / scan --workspace W` | catalog discovery over a tree || `symbols`, `graph`, `select-tests` | workspace inspection || `verify --workspace W --file F` | verdict for a file without a change || `evaluate --split eval` | scores the `intent` and `planner` nodes against the corpus || `train-intent`, `build-corpus --check` | the generation and training entry points || `lock-status`, `check-adapter` | the same answers the sibling bundle gives |
Flags carried by every writing verb: `--config FILE`, `--protect PATH`, `--print-diff`,`--audit FILE`, `--node-timeout`, `--total-timeout`, `--gate-timeout`, `--lock-wait`,`--allow-single-prover`, `--subprocesses`.
### 7.2 Session layer
Reuse the semantics proven in the sibling bundle, re-implemented inside this folder:staged verification, atomic transactional commit, exclusive workspace lock with holdertoken, rejection of linked and hardlinked paths, per-command gate budgets, one run pertree at a time. State it in `doc/SPEC_SESSION.md` here and reference it rather thandiverging from it silently.
---
## 8. Development methodology the bundle applies to itself
The bundle must be built with the methods it claims. This is a requirement, not advice.
1. **TDD.** Each task starts by adding the failing test in `tests/`, then the code. A task whose test passes before the code exists is a sign the test was written after, and the change must say so in its commit message.2. **Design patterns as named structures.** Package layout, one responsibility per module, interfaces as abstract base classes: - `IntentResolver` (`resolve(utterance, workspace) -> Intent`) - `TargetLocator` (`locate(Intent) -> list[Target]`) - `Planner` (`plan(Intent, targets) -> Plan`) - `CatalogEntry` (`matches(target)`, `produce(target) -> list[Edit]`) - `Gate` (`run(workspace) -> Verdict`), `RunnerModel`, `WorkspaceLock` Concrete patterns expected where they fit: Strategy for the catalog, Factory for entry construction from `catalog/patterns.json`, Registry for entries and reason codes, Command for steps, Template Method for the gate family, Adapter for the kernel contract, Facade for the session, Chain of Responsibility for preflight checks. A pattern applied without a test that pins its seam is not considered applied.3. **SOLID and dependency injection**: nodes receive their collaborators; no node imports a concrete checker, adapter or locator directly. Nothing is configured by editing code.4. **Contract-first**: every public function documents preconditions and postconditions in its docstring, and every schema in `schemas/` is validated at the boundary.5. **Characterization before refactor**: the fixture suite is green before the bundle touches any workspace, and a change to a workspace runs the workspace's own suite.6. **Fuzz with fixed seed**: `tests/test_corpus_fuzz.py` and `tests/test_session_fuzz.py` sweep shapes the corpus never visits; the invariant is that an answer is either a hit that leaves the file parseable, or a refusal naming a registered code. A crash or an unregistered name fails the sweep.7. **Static discipline**: `ruff`, `mypy` and `pyright` where present; absent checker answers `ABSTAIN`, never `CONFIRMED`.8. **Every gate prints elapsed seconds** and `results/gates.json` embeds a digest of every byte of the bundle except `results/` itself.
---
## 9. Reason codes
One registry, `lingologos_thinkingpython/reasons.py`, and a gate that fails when theregistry and `doc/REASONS.md` disagree, or when the card names a code the code does notraise. Three groups: session codes, kernel codes (imported from the kernel's decisionmodule, not restated), catalog and preflight codes owned by this bundle. Every new codeadded by a new catalog entry is added to the registry in the same change; a code raised byno rule fails `self_lint`.
---
## 10. Layout of the folder
```datasets/thinkingpython/ SPECIFICATION.md this file README.md the dataset card, rewritten by the publisher doc/ SPEC_SESSION.md, REASONS.md, OPEN_QUESTIONS.md, HOW_TO_ADD_AN_ENTRY.md catalog/patterns.json the extensible catalog lexicon/<code>.json one file per variety of section 6.5: ar, en, es, hi, it, zh lingologos_thinkingpython/ the package intents/ locators/ planners/ catalog/ steps/ gates/ session.py cli.py reasons.py schemas/ intent, target, plan, step, edit pair, catalog entry fixtures/lab/ the planted laboratory: one shape per entry, plus one to refuse corpus/ L1..L5 plus adversarial, generated only tools/ ask.py (the sibling compliant entry point, section 3.1), build_corpus.py, train_intent.py, run_gates.py, measure_coverage.py, selfcheck_confine.py, publish_dataset.py topology.json nodes/<id>/ agents/<id>_agent.py tests/ one file per module, confinement test, fuzz, self_lint results/ gates.json, coverage.json, evaluation.json```
---
## 11. Deliverables and acceptance
| # | Deliverable | Acceptance, machine checked ||---|---|---|| D0 | confinement | `selfcheck_confine.py` exits 0; nothing outside the folder moved || D1 | catalog `>= 40` entries | `catalog_integrity` gate: every entry has a rule, a test, refusals || D2 | corpus L1-L5 + adversarial | `build_corpus.py --check` re-derives every byte; `>= 7200` L1 rows, all six varieties per entry || D3 | 7-node topology as processes, behind `tools/ask.py` | `tests/test_topology.py` runs it as subprocesses through `MultiInstanceOrchestrator` and checks budgets; `tests/test_ask.py` asserts that `--in-process` and the orchestrated path agree on status, assurance and reasons || D4 | edit pair + honesty gate | pair-honesty gate passes for every entry || D5 | evaluation | on the `eval` split, **per variety and on the worst variety**: top-1 entry `>= 0.85`, out-of-scope refusal `>= 0.90`, zero run commits an unverified change || D5b | lexicons of the six varieties | `lexicon` gate: every file validates its required keys, no run reads a variety without a file, replies are worded in the declared variety || D6 | self-methodology | TDD order visible in history, `>= 90%` of package functions entered by the suite || D7 | card and gates | `run_gates.py` prints CONFIRMED for every gate, digest embedded |
Definition of done for any programmer task: the confinement check, `pytest`,`run_gates.py` and `build_corpus.py --check` all pass, and this specification is updatedin the same change if any contract moved.
---
## 12. Explicit prohibitions
1. No write outside `datasets/thinkingpython/` (section 0).2. No pretrained language model, no network call during a run, no remote asset.3. No prose in a language other than English; no non-ASCII characters in `.py` files.4. No committed `__pycache__/`, `*.pyc`, `*.egg-info/`.5. No new Python dependency without `requirements.txt` inside this folder, mirrored in the publication card, and never a change to the repository-level `requirements.txt`.6. No commit that lands a source edit without its lock test.7. No catalog entry edited after publication; ids are append-only.8. No claim of a benchmark, and no coverage number without its denominator.9. No gate answered `CONFIRMED` for a command that did not run: absent tools abstain.10. No publication of this asset described inside the repository documentation: the card is the folder README, and the repository carries one link.11. No language variety outside the six of section 6.5, and no lexicon file copied or read from another bundle. The varieties of this bundle are its own files under `lexicon/`, following the gateway contract for their shape only.README.mdAdded+54
SPECIFICATION.mdAdded+516