File size: 42,861 Bytes
2423c9d
9676733
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70df949
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9676733
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
074b09a
 
 
 
 
 
 
 
9676733
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2423c9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9676733
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
074b09a
 
 
 
 
 
 
 
 
 
 
 
 
9676733
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
074b09a
 
 
 
 
 
 
 
9676733
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70df949
 
 
 
 
9676733
 
 
 
 
 
 
 
2423c9d
9676733
2423c9d
9676733
 
 
 
 
2423c9d
70df949
9676733
 
70df949
9676733
074b09a
 
2423c9d
9676733
 
 
 
 
 
 
 
 
 
2423c9d
9676733
 
 
ac3a340
 
9676733
074b09a
9676733
 
70df949
9676733
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
# LingoLOGOS thinking-python - Specification of the bundle

Status: draft 1, normative. This file is the contract a programmer implements. Where this
file 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 the
reason the host repository moves.

---

## 1. What this bundle is

An N-agent topology plus a dataset that turns **free natural-language text about Python
code** into a **verified change in a Python workspace**.

Unlike `datasets/codex-python`, which carries ten closed shape rules and refuses anything
else, this bundle claims the **open** case: any change expressible in Python, produced by
the common design patterns and the standard development methodologies. The catalog is
therefore 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 arbitrary
Python, or any benchmark over real repositories. Coverage statements name their
denominator, which is a fixture of this folder.

### 1.1 Mission: maintain an existing project on simple requests

The mission this bundle commits to, stated narrowly on purpose:

> A person who cannot name the transformation takes an **existing** Python project with a
> working test suite, says in plain words what bothers them, and the bundle carries that
> change through verification.

This is a maintenance mission, not an authoring mission. The user does not need to know what
a strategy pattern is; the gate protects them from damage they could not foresee.

The mission excludes, and the specification does not pretend otherwise:

- **Greenfield work.** The unit of output is an edit pair on a file that exists (section 5). A
  project that does not exist has no prior behaviour, and without a prior behaviour there is
  no oracle: equivalence cannot be checked, so no verdict is meaningful. A bundle that
  "implements a project from a sentence" is a different system, and this one does not become
  it by adding features.
- **Design decisions.** Where the boundaries are, which data, which interface: those are
  choices, not transformations, and no simple request carries them.
- **Unbounded sessions.** The bundle verifies each step, not the direction of a hundred
  steps. Coherence across a session belongs to the person asking.

Admission of a workspace is therefore checked **before** any node runs, and each failed
condition is a named reason code, not a crash or a silent degradation:

| Condition | Reason code |
|---|---|
| no runnable test suite for the touched files | `NO_TEST_FILE` |
| mixed or non-space indentation in the target | `TAB_INDENTED_TARGET` |
| CRLF in the target | `CRLF_TARGET` |
| non-ASCII in the target path or content handling | `NOT_ASCII_TARGET` |
| symbol reached only through dynamic import or `getattr` | `DYNAMIC_REACH` |
| target is generated code (by a build step, protobuf, Cython stub) | `GENERATED_TARGET` |

A refusal on these codes is **correct behaviour** and is counted as a success in the
evaluation, never as a failure to fix. What the bundle must do honestly is report the codes
in the coverage statement, so the size of the unmaintainable part of a workspace is visible
rather than hidden behind a green number.

For this mission there is one deliverable beyond the gates, and it is the one that shows the
mission works or does not: **the maintenance demo** (see `D8` in section 11).

---

## 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 not
validate 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 the
routing 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.
6. **The plan is language-free.** The intermediate representation passed from `intent` to
   `locator`, `planner` and `executor` carries no word of any human variety: catalog ids,
   symbol names, paths, and the `--lang` code as a tag only. Surface forms of a variety are
   *views* consumed at the `intent` boundary and never reach a downstream node. Consequence,
   and it is a rule, not a style preference: adding a seventh variety adds a lexicon file and
   a corpus slice, and **changes no rule, no frame matching downstream, and no gate**. A test
   (`tests/test_language_free_plan.py`) asserts that the same plan hash is produced for the
   six paraphrases of one entry, one per variety.

---

### 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 every
sibling 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 implements
that 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 and
outside 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 system
temporary paths while still failing on any path inside the repository. The workspace a caller
names with `--workspace` is a second, separate case: it is outside this folder, the caller
chose 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 and
an 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.

### 4.1 Growth: the catalog is meant to grow, and growth has a gate

The catalog grows by entries, not by ambition. A new entry is admissible only when it is
**verifiable**: a shape the locator can match, a transformation that produces text, a lock
test, and named refusals. Growth without that is not growth, it is noise in the candidate set.

**The conflict gate.** From the first revision, `results/conflicts.json` is generated by
`measure_coverage.py`: for every symbol of `fixtures/lab/` and `fixtures/seed_project/`, the
set of entries whose shape matches it. The gate `catalog_conflicts` fails when:

- a symbol is claimed by more entries than `max_candidates` (default `4`) with no declared
  policy;
- two entries produce the **same edit pair** on the same symbol (duplicate, not conflict);
- two entries produce edit pairs that **overlap on the same lines** (the arbiter must never
  choose between two writes to the same text without a rule).

The policy is declared per pair in `catalog/conflict_policy.json` and is one of: `specificity`
(the entry whose shape is a strict subset wins), `family_order` (the family order declared in
`patterns.json`), or `clarify` (the session asks, and the ask is the correct answer). A
conflict with no policy is a `Clarify` at runtime, never a silent pick. A catalog that grows
past 150 entries with no conflict data is a catalog whose top-1 falls, and the gate is what
prevents that from arriving unnoticed.

**How to add an entry, in order.** `doc/HOW_TO_ADD_AN_ENTRY.py` is a script, not prose, and it
enforces the order:

1. **Start from evidence, not from a book.** Name at least one concrete symbol in
   `fixtures/lab/` or `fixtures/seed_project/` that holds the shape. No witness, no entry.
2. **Write the shape as a matcher first.** A function over the syntax tree returning
   candidates and non-candidates. Run it over the whole fixture set and read the candidate
   list: if it matches symbols you did not expect, the shape is wrong, not the fixture.
3. **Write the refusals before the transformation.** For each precondition, name the code and
   plant a fixture that triggers it. An entry with fewer than two refusals is rejected.
4. **Write the lock test.** It must fail on the old shape and pass on the new one; the
   pair-honesty gate checks exactly that, and a test that passes in both shapes invalidates
   the entry.
5. **Then the transformation text.** Only now: the edit pairs the entry produces.
6. **Regress the existing catalog.** `run_gates.py --catalog-regress` reruns the `eval` split
   for the entries that existed before the addition. If top-1 on any pre-existing entry drops
   by more than `0.02`, the new entry is not merged, or its shape is narrowed until the
   regression clears. Growth that costs an old entry is not growth.
7. **Declare the conflicts.** Every pair the new entry forms appears in `conflicts.json`, and
   each pair needs a policy line from the previous subsection.
8. **Render the utterances.** Templates plus at least one human-sourced phrasing in each of
   the six varieties, and at least one `contrastive` row (section 6.2). The entry is not done
   when the code works; it is done when a person's words find it.

**Where growth pays, in order.** The `refactoring` family scales almost mechanically: local
shape, local edit, near-equivalence, so entries there are cheap and the lock is strong. A
fourth family, **`python_idiom`**, is the cheapest high-yield addition: `dataclass` for
boilerplate constructors, context managers for paired acquire and release, `pathlib` for
`os.path` strings, removal of mutable default arguments, `@property` for getter and setter
pairs, comprehension for explicit accumulator loops. These forms are common, the matcher is
strong, the edit is local. Patterns that **introduce** structure rather than recognise it
(visitor, mediator) cost several times more per entry and come last. Entries that cross files
or change a public signature cost five times a local entry and produce more refusals than
successes: they belong after the maintenance demo (D8) has shown the local ones land.

---

## 5. The edit-pair invariant (non-negotiable)

Every step that changes a source file produces **two** writes committed as one
transaction:

- 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 hand
edited; the generator is `tools/build_corpus.py` and `--check` fails when the folder
disagrees 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 parallel
schema: 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. **Contrastive rows are a mandatory class**, `intent_tags` carrying `contrastive`, and they
   are the rows that grow the system. For each variety, at least one row per entry where a
   word that marks the entry in that variety also has another function in the same sentence
   (a preposition, a noun, an operator word): the Spanish `entre` and the Italian `per` of the
   genesis solve frames are the existing precedent. The expected answer for such a row is
   either the correct entry or a `Clarify` that names the two candidates, never a silent wrong
   pick. They are scored separately in `results/evaluation.json` under `contrastive`.
7. **Text taken from people carries provenance and is split by source.** Where an utterance
   is harvested from human writing rather than rendered from a template, the row records the
   source (origin, licence, whether the text was adapted) in `source`, and the 70/15/15 split
   is applied **by source and by author before it is applied by row**: fifty sentences from one
   person on one pattern are one observation, and one person's sentences never straddle two
   splits. A source without a licence line is not admitted to the corpus.

### 6.3 Coverage statement

`results/coverage.json` states, for each entry: targets planted, targets in shape, rows
generated, refusals recorded, and the **denominator**, which is always the fixture of this
folder and never "Python". The statement is regenerated with the corpus and the card
quotes it.

### 6.4 No off-the-shelf model is required

Nothing in this bundle downloads or depends on a pretrained language model. `intent` must
run 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`. The
trained artifact is a weights file plus a vocabulary plus the catalog digest, published
inside the folder, with no external weight. Any implementation of `intent` must satisfy
section 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 is
taken 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 same
six 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 is a gate, not a goal; the number reported is the worst variety.**
   Section 6.2 requires the six varieties per entry so that no variety is silently forgotten,
   and the requirement ends there. Uniform *shape* across varieties is not uniform
   *capability*: with a template-rendered corpus the per-variety number only measures how many
   surface forms were written by hand for that variety. So `results/evaluation.json` reports
   top-1, out-of-scope refusal, clarification and `contrastive` **per variety**, plus the
   **spread** between best and worst variety, and the card quotes the worst variety and the
   spread, never the average. A variety that is carried but not measured is a defect.
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 holder
token, rejection of linked and hardlinked paths, per-command gate budgets, one run per
tree at a time. State it in `doc/SPEC_SESSION.md` here and reference it rather than
diverging 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 the
registry and `doc/REASONS.md` disagree, or when the card names a code the code does not
raise. Three groups: session codes, kernel codes (imported from the kernel's decision
module, not restated), catalog and preflight codes owned by this bundle. Every new code
added by a new catalog entry is added to the registry in the same change; a code raised by
no rule fails `self_lint`.

The preflight group carries the admission codes of section 1.1 — `NO_TEST_FILE`,
`TAB_INDENTED_TARGET`, `CRLF_TARGET`, `NOT_ASCII_TARGET`, `DYNAMIC_REACH`,
`GENERATED_TARGET` — raised by the workspace check that runs before any node, and counted as
correct behaviour in `results/coverage.json`.

---

## 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.py
  catalog/patterns.json         the extensible catalog
  catalog/conflict_policy.json  per-pair policy: specificity, family_order, clarify
  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
  fixtures/seed_project/        the maintenance demo project of section 1.1, suite green
  corpus/                       L1..L5, adversarial, maintenance.jsonl, 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,
                               run_maintenance.py, selfcheck_confine.py, publish_dataset.py
  topology.json   nodes/<id>/   agents/<id>_agent.py
  tests/                        one file per module, confinement test, language-free-plan
                                test, fuzz, self_lint
  results/                      gates.json, coverage.json, evaluation.json, conflicts.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 |
| D1b | growth is safe | `catalog_conflicts` gate on `results/conflicts.json`: every claimed symbol has a declared policy, no duplicate edit pair, no overlapping writes; `run_gates.py --catalog-regress` shows no pre-existing entry losing more than 0.02 top-1 |
| 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 | Two splits, named and never mixed. `composed` is re-derived from the lexicon and only proves generator and router agree: `generator_consistency` gate demands top-1 `>= 0.999` on its `eval` split. `heldout` is **written, never generated from the lexicon**, and is the number the card leads with: top-1 `>= 0.60`, recall `>= 0.60`, precision `>= 0.95`, refusal `>= 0.95`, spread between best and worst variety `<= 0.20`, all **per variety and on the worst variety**. A top-1 without its recall is not a report: abstention is a failure, not a pass |
| D5a | authorship of every split | Every corpus row carries a `source` field naming who wrote it, and every published number names the authorship class beside it. A model-authored split is labelled as a proxy for free phrasing, with the direction of its bias stated; it is never merged with human data |
| 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 |
| D5c | language-free plan | `tests/test_language_free_plan.py`: one entry in six varieties yields one identical plan hash; no human word of any variety appears in a downstream node payload |
| 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 |
| D8 | maintenance demo of section 1.1 | `fixtures/seed_project/`: a package of `20-30` files with a green suite; `corpus/maintenance.jsonl` carries `>= 30` simple requests in plain words, each with an expected verdict; `tools/run_maintenance.py` replays them in order on the seed and prints the tally. Acceptance: `>= 20` land `VERIFIED`, **every** refusal names a code from section 1.1, and the suite of the seed is green after the whole run. The demo is reported as measured, including the refusals; a run with fewer than 20 verified is a documented negative result, not a reason to move the threshold |

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 updated
in 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.