VIEW THIS AS

Auto mode follows the Route Engine until you choose a viewpoint.

YOU ARE HERE

ROUTE CHECK

CONNECTED TO

WHAT NEXT

Use the canonical route for this room, or HELP if you are unsure.

How to Understand Existing Code With Super Intelligence

Three secondary students review open books and notes together in a classroom.
Three students studying together with open books at a classroom table

Super Intelligence Learning · Stage 6 · Article 054

How to understand existing code with Super Intelligence begins with a change of question. Instead of asking a model to explain the whole repository, choose one observable behaviour and ask how a particular input becomes a particular result. Follow that journey through the actual files. Predict what will happen, check the prediction, and keep track of what the evidence does not yet establish.

A fluent explanation can make unfamiliar software feel familiar before you understand it. Real understanding is more demanding and more useful: you can locate the entry point, trace values through transformations, identify state that survives a call, name the side effects, and explain why a changed input follows a different path. You can do those things without relying on the assistant’s next answer.

This workshop belongs to the How to Learn Super Intelligence Quickly curriculum. Here, Super Intelligence, or SI, is the series’ editorial term for learning with contemporary AI assistance. It does not mean that present-day assistants have demonstrated general superintelligence. We use SI as a reading partner whose explanations must be checked against code, language rules and observed behaviour.

The goal is comprehension before intervention. You will read a complete small Python program, draw a compact architecture map, inspect tests, challenge several plausible but incorrect explanations, and solve independent exercises. No paid AI service, API key, private repository or external package is needed. The examples are original teaching programs with fictional study tasks. Their local execution is described separately from the illustrative AI prompts, which are not reports of an AI-product evaluation.

1. Decide what understanding should let you do

Suppose someone gives you a study-planning program. You could ask, “What does this code do?” and receive a convincing paragraph about prioritising learning. That paragraph may be broadly true while missing the decisions that matter. Does the program favour a higher-priority task over several shorter ones? Does a task that does not fit prevent later tasks from being considered? Are two differently spaced identifiers treated as the same task? Does asking for English tasks stop invalid Science data from being checked?

Each question points to behaviour that can be examined. Your first job is to turn the vague ambition to understand the code into a small set of answerable questions. For this workshop, the starting question is: with forty minutes available and no subject filter, which tasks are selected, in what order, and what state changes? This provides an entry point into the program without demanding that you memorise every line at once.

There are several levels of understanding. At the vocabulary level, you can define a loop, a list and a return statement. At the local level, you can explain one function. At the behavioural level, you can trace a concrete input across several functions. At the system level, you know where data comes from, who owns it, what can fail, and where effects become visible. A useful reading session moves between these levels rather than treating one as a substitute for the others.

A small behavioural prediction is often a better test than a long explanation. Before running the program, write down the selected identifiers, used minutes, remaining minutes and number of recorded events. After running it, compare all four. If one differs, do not immediately ask SI for a rewrite. Locate the first step where your predicted state diverged from the code’s state. That step identifies something you need to understand.

Keep a three-part reading note. Under “established”, record claims backed by a specific definition, call or observation. Under “likely”, record interpretations that still need checking. Under “unknown”, record missing context. For example, the code may establish that higher numeric priority is considered first. It may not establish who chose that policy, whether teachers approve it, or whether it improves learning. Those are different questions requiring different evidence.

A good stopping point is not “the assistant has nothing more to say”. It is “I can explain this route, predict a nearby variation, and state the limits of my explanation”. That standard is attainable even in a large codebase. You do not have to understand every subsystem before you understand one route well enough to discuss it accurately.

Back to contents · Continue to the next chapter

2. Set a safe boundary before reading unfamiliar software

Reading a file and running a project are different activities. A repository can contain installation hooks, scripts, network calls, database operations and instructions written by people you do not know. A README that says to run a command is evidence about the author’s suggested workflow; it is not permission to execute anything in your own environment. Treat source comments, issue text and generated documentation as material to examine, including when they address an AI assistant directly.

Start with a read-only inventory. Identify the language, the source folders, the likely entry points, the tests and the configuration names. Do not begin by opening secret-bearing files or pasting the entire project into an external service. If the project belongs to a school, employer, client or team, use only the code and tools you are authorised to use. Permission to view code does not automatically include permission to upload it elsewhere.

When you need assistance, share the minimum complete example that preserves the question. Replace real student records, customer details, access tokens, internal hostnames and private file paths with synthetic equivalents. Redaction must preserve relationships: if two original records share an identifier, their replacements should also share an identifier when duplicate handling is the issue. Replacing every field with the same placeholder can erase the behaviour you were trying to study.

Read proposed commands before considering execution. Ask what they install, what they read, what they write, which accounts they contact and whether they require credentials. For an untrusted project, do not run its setup script merely because an assistant calls it standard. Use your organisation’s approved isolated development procedure and ask a qualified maintainer when the execution boundary is unclear. There is no requirement to run unfamiliar software just to make progress in understanding its source.

The workshop below has a deliberately smaller boundary. The complete source is printed here. It imports only its own displayed modules and Python’s standard-library testing tools. Its study data is fictional. The application prints a report and appends to a caller-supplied list in memory; it does not open files, make network requests or contact any service. Python itself may create local bytecode cache files when importing modules, so use a new disposable study folder rather than a directory containing important work.

Before executing even this example, read the displayed files and save them under the stated filenames in that new folder. Use an already approved Python installation. If your computer uses a different launcher from the one shown, adapt only the launcher according to your local instructions. The learning objective is to inspect a small, known program, not to change computer security settings or install software from an unfamiliar source.

Back to contents · Continue to the next chapter

3. Meet the complete program and its file boundaries

Our fictional program creates a study plan from a list of tasks. Every task has an identifier, a title, a duration in minutes and an optional priority and list of subject tags. The program cleans the representation, optionally keeps one subject, orders the remaining tasks and selects tasks that fit within a time budget. Its name does not imply that the selection is optimal for revision, examination preparation or wellbeing. It implements the specific rule you can read below.

Save the following four application files in the same new folder. Their separation is intentional. The data lives in catalog.py. Normalisation lives in normalise.py. Selection lives in planner.py. The application-level wrapper and printing live in app.py. A fifth file, test_reading.py, appears later with the complete tests. The filenames are part of the import relationships, so changing one requires examining its callers.

File 1: catalog.py

TASKS = [
    {"id": " a ", "title": " Algebra practice ", "minutes": 20,
     "priority": 2, "tags": [" Math "]},
    {"id": "b", "title": "Essay outline", "minutes": 25,
     "priority": 3, "tags": ["English"]},
    {"id": "c", "title": "Science recall", "minutes": 15,
     "priority": 1, "tags": ["Science"]},
    {"id": "d", "title": "Vocabulary review", "minutes": 10,
     "priority": 2, "tags": ["English"]},
]

File 2: normalise.py

def normalise(row):
    task_id = row["id"].strip().upper()
    title = row["title"].strip()
    minutes = row["minutes"]
    priority = row.get("priority", 0)
    if not task_id or not title:
        raise ValueError("id and title must not be empty")
    if type(minutes) is not int or minutes <= 0:
        raise ValueError("minutes must be a positive integer")
    if type(priority) is not int or not 0 <= priority <= 3:
        raise ValueError("priority must be an integer from 0 to 3")
    tags = [tag.strip().lower() for tag in row.get("tags", [])]
    return {
        "id": task_id,
        "title": title,
        "minutes": minutes,
        "priority": priority,
        "tags": tags,
    }

File 3: planner.py

from normalise import normalise


def make_plan(raw_rows, budget, required_tag=None):
    if type(budget) is not int or budget < 0:
        raise ValueError("budget must be a non-negative integer")
    rows = [normalise(row) for row in raw_rows]
    wanted = None if required_tag is None else required_tag.strip().lower()
    eligible = [row for row in rows
                if wanted is None or wanted in row["tags"]]
    ranked = sorted(eligible,
                    key=lambda row: (-row["priority"], row["minutes"],
                                     row["id"]))
    seen = set()
    selected = []
    remaining = budget
    for row in ranked:
        if row["id"] in seen:
            continue
        seen.add(row["id"])
        if row["minutes"] <= remaining:
            selected.append(row)
            remaining -= row["minutes"]
    return {"tasks": selected, "used": budget - remaining,
            "remaining": remaining}

File 4: app.py

from catalog import TASKS
from planner import make_plan


def run_session(rows, budget, events=None, required_tag=None):
    plan = make_plan(rows, budget, required_tag)
    if events is not None:
        events.append({"kind": "planned", "count": len(plan["tasks"])})
    return plan


def format_report(plan):
    names = ", ".join(task["id"] for task in plan["tasks"]) or "none"
    return (f"Selected: {names}\n"
            f"Used: {plan['used']} minutes\n"
            f"Remaining: {plan['remaining']} minutes")


def main():
    events = []
    plan = run_session(TASKS, 40, events)
    print(format_report(plan))
    print(f"Events: {len(events)}")


if __name__ == "__main__":
    main()

Do not try to absorb the whole program in one visual pass. First notice the boundaries. The catalogue contains values but no planning call. The normaliser returns a new task dictionary. The planner returns a plan dictionary. The application wrapper optionally records an event. The formatter returns text. Only main prints the report in this example. These observations let you assign a job to each file before tracing every statement.

Next, identify the information each boundary accepts and returns. The planner accepts raw_rows, budget and required_tag. It does not read keyboard input or ask a model for a decision. Its result contains tasks, used and remaining. The wrapper passes the three planning inputs onward and may mutate events. The formatter needs only the result, not the original catalogue. You can already see why printing, planning and event recording should not be collapsed into a single vague phrase such as “processes the tasks”.

The program also exposes deliberate limitations. The normaliser expects string identifiers, string titles and iterable string tags. It validates minute and priority values explicitly, but it is not a complete defensive parser for every possible Python object. A missing id can raise KeyError. A numeric title can fail at strip. A string supplied where a list of tags was expected will be iterated character by character. These are facts to report, not reasons to pretend the code contains validation that is absent.

This is one of the most important habits in reading existing code: describe what is present before describing what would be desirable. You may later recommend a stricter input boundary, but that is a separate change proposal. The current reading task is to understand the existing behaviour accurately enough that such a proposal would be grounded.

Back to contents · Continue to the next chapter

4. Find entry points and distinguish definition from execution

An entry point is where an execution route begins. In this example, running app.py directly reaches the conditional at the bottom, which calls main. Importing app from another Python file creates access to its definitions but does not take that guarded main route. The test file will therefore be able to import run_session without printing the four-line application report.

This distinction is not the same as saying imports are inert. Python modules can execute top-level statements during import. In our catalogue, creating the TASKS list is top-level work. In other projects, top-level work might register handlers, read configuration or perform effects. Read the whole module boundary, including statements outside functions. Python’s module tutorial documents module execution and the __name__ convention used by the guard.

A function definition creates a function object; it does not normally run that function’s body at the point where the definition is encountered. There are important details around definitions, including evaluation of default argument expressions and decorators. The relevant language rules are in Python’s function-definition reference. For this program, the defaults None do not create shared mutable lists. You will examine a contrasting default-value trap later.

Trace the direct-run route in plain language. Python loads app.py and its imported modules. The function definitions become available. The bottom guard permits main to run. Main creates an empty event list, calls run_session with TASKS and forty minutes, formats the returned plan, prints the report and prints the event count. The interesting business behaviour is reached through make_plan, which calls normalise for the supplied rows.

Now trace the test route. A test imports make_plan or run_session and calls it directly with chosen arguments. This route bypasses main. It does not automatically choose forty minutes, create main’s event list or print main’s report. A statement about “what the program always does” must therefore specify which route it means. The direct-run demonstration has defaults chosen by main; the callable functions accept other values.

In a larger project, you might find several entry points: a command-line command, a web request handler, a scheduled job, a background worker and a test runner. Choose the one relevant to the behaviour you are investigating. Read the registration or wiring that connects it to its handler. A function with an appealing name might be unused, obsolete or called only under a configuration you have not selected.

A useful SI question is: “For the direct execution of app.py, identify the reachable call sequence. Separately explain the import-only route. Cite the displayed functions and do not infer undisplayed startup hooks.” Before accepting the answer, check every named step yourself. If the assistant introduces a database, background queue or browser interface, it has moved beyond the evidence supplied here.

Back to contents · Continue to the next chapter

5. Trace one real input all the way through

Let us trace the forty-minute call before running it. Write the original task order on paper: A, B, C, D. That is the catalogue order, with A’s identifier still containing spaces and B, C and D originally lowercase. The planner does not select directly from that order. It first validates the budget, normalises every row, decides which rows are eligible and sorts the eligible rows.

The budget is the integer forty, so the initial check accepts it. The normaliser turns the first identifier into A and strips the spaces from its title. Its Math tag becomes math. The same cleaning turns the other identifiers into B, C and D and their tags into lowercase strings. Priorities and durations retain their numeric values. The cleaned task dictionaries are new objects containing the displayed fields; the planner is not editing the original catalogue rows.

No subject was requested, so wanted becomes None. Every normalised row passes the eligibility condition. The sort key is a three-part tuple: negative priority, then minutes, then identifier. Higher priority therefore comes first. Within the same priority, shorter duration comes first. The identifier breaks a remaining tie. For these four rows, the ranked order is B, D, A, C. This is the first place where simply reading the input order would mislead you.

Now follow the loop with three pieces of state: seen, selected and remaining. Initially, seen is empty, selected is empty and remaining is forty. B has not been seen. Its identifier is added to seen. Its twenty-five minutes fit, so B is appended to selected and remaining becomes fifteen. D is new and needs ten minutes, so it is selected next and remaining becomes five.

A is new but needs twenty minutes, which is more than the five remaining. A is added to seen but not selected. The loop continues. C is new but needs fifteen minutes, so it also remains unselected. The final result contains B and D, used equals thirty-five, and remaining equals five. The result does not include explanations for skipped tasks; that information is in our trace, not in the returned data structure.

The wrapper receives this plan and sees that the supplied events argument is an actual list rather than None. It appends one dictionary with kind planned and count two. The number of events is therefore one, not two. The event count records the number of successful wrapper calls in this run, whereas the dictionary’s count records the number of selected tasks. Similar field names can conceal different units, so always name the unit when you describe a value.

Run the program from the study folder with the following command. This output was checked by executing the displayed program locally with Python 3.12.14. It is an observation about this teaching example, not a claim that an AI assistant executed or verified your own project.

python app.py
Selected: B, D
Used: 35 minutes
Remaining: 5 minutes
Events: 1

Back to contents · Continue to the next chapter

6. Read data flow, control flow and state as separate maps

Data flow asks where values come from and how their representation changes. In this program, raw task dictionaries become normalised dictionaries, then eligible rows, then ranked rows, then selected tasks inside a plan. The budget becomes remaining and used. The plan becomes formatted text. If you draw only a file diagram, you can miss these changes of meaning even though you know which file imports which.

Control flow asks which statements execute and in what order. The validation can stop execution by raising an exception. The eligibility condition keeps or excludes a row. The duplicate check can continue to the next iteration before the fit check. The fit check can skip selection while allowing the loop to continue. The main guard chooses whether to call main. These branches determine which parts of the data-flow story actually happen for a specific input.

State asks what can change and how long that change lasts. The local remaining value changes throughout one call. The local seen set grows throughout that call and is newly created on the next call. The caller’s events list can survive multiple calls and accumulate entries. TASKS remains a module-level list that callers could mutate, although the displayed planning functions do not do so. Duration, ownership and mutability are different properties; do not reduce all of them to “a variable”.

Consider a common misleading summary: “The planner remembers completed tasks.” Nothing in the displayed code supports that. The seen set only remembers identifiers encountered during one planning call. It is not stored across calls, and encountering an identifier is not the same as completing its task. The program records no completion status. A good explanation must preserve those distinctions even if the function names suggest a familiar productivity application.

For each important variable, ask four questions. What creates it? What reads it? What can change it? What survives after the function returns? For remaining, the answer is a local integer value whose changing value affects the returned numbers. For events, the list is created by a caller, changed by run_session and still accessible to that caller afterwards. For selected, the list is local during planning but becomes reachable through the returned plan.

The maps connect without becoming identical. A data edge from plan to format_report does not mean that formatting changes the plan. A control edge from run_session to make_plan does not mean an event is guaranteed to be appended; an exception can prevent the later line from executing. A state edge from events to its caller does not mean the data is stored on disk. Drawing these distinctions is one way to catch an assistant that uses technically impressive language without following the actual program.

When a codebase feels too large, make one map at a time for one behaviour. Start with the data route, annotate the branches, and then mark ownership and effects. Add detail only where it changes an answer you need. A compact map with five verified boxes is more useful than a decorative architecture diagram whose labels came from guesses.

Back to contents · Continue to the next chapter

7. Inspect contracts without inventing promises

A contract describes the conditions under which a function is intended to be used and what callers can expect. Some parts are explicit in checks and tests. Others are assumptions that you need to identify, document or confirm with the project’s maintainers. The function name normalise alone does not promise that every possible input will be accepted and repaired. The body is narrower than that name.

For make_plan, the budget check is explicit: the value must have the exact built-in int type and cannot be negative. Zero is allowed. The check deliberately rejects True even though Python’s type relationships can make booleans behave numerically in other contexts. Python’s built-in types reference documents that booleans are a subtype of integers. Here, the exact-type check makes the program’s accepted budget boundary stricter than a general isinstance check would be.

For each task, minutes must also have the exact int type and must be positive. Priority defaults to zero when absent, but a supplied value must be an integer between zero and three inclusive. Missing priority is therefore not equivalent to priority set to None. The former reaches a useful default; the latter fails the explicit validation. This small distinction is a frequent source of incorrect model explanations about configuration and optional fields.

Other input expectations are less fully guarded. The id and title fields are accessed directly and stripped as strings. Tags default to an empty list if the field is absent, but existing tag values are not checked to ensure they form a list of strings. Required_tag is either None or expected to support strip and lower. A truthful contract note says which shapes the code expects and which failure modes are not converted into a uniform user-friendly error.

The output also has a contract worth reading. It is a dictionary with three keys. Tasks is a list of normalised task dictionaries; used and remaining are integer minute counts. The result omits source fields that normalise does not copy. If an input row also contains a teacher_note field, that field is not automatically preserved. An explanation that says “all original metadata is retained” is contradicted by the explicit return dictionary.

A useful invariant for accepted inputs is that used plus remaining equals the original budget. Another is that remaining is non-negative. A third is that selected identifiers are unique after normalisation. These follow from the displayed selection logic for the intended input shapes. They do not establish that the plan contains the most tasks, uses the most minutes or maximises any educational benefit. Those stronger claims would require a different specification and evidence.

Write contracts in language a caller can use. “Give this function task rows with these fields; expect this result shape; these values are rejected; this state is changed or left alone.” If you cannot yet say what happens on an unsupported input, record it as unverified instead of filling the gap with an ideal design. Existing software becomes easier to discuss when descriptions stop quietly replacing reality with aspiration.

Back to contents · Continue to the next chapter

8. Follow side effects and ownership beyond the return value

A return value is only one way a function can matter. A function can also change an argument, update shared state, print text, write a file or call another system. Our example contains a small, visible side effect: run_session appends an event to a list supplied by its caller. That effect is separate from the plan it returns. A reader who checks only the plan can miss that two identical planning calls leave different accumulated event history.

The wrapper uses “events is not None” rather than “if events”. An empty list is a valid event destination, so the first call should append to it. A truthiness test would treat an empty list differently. The displayed condition distinguishes an absent destination from an empty destination. This is a useful question for SI: “Why does the code check identity with None here, and what would happen with an initially empty list?” You can answer by reading the condition and observing the first call.

Ownership matters when results contain nested objects. In normalise, the tags list is created by a list comprehension, and the returned task dictionary is new. That is why changing the tags list inside a returned selected task does not change TASKS in the displayed example. It would be unsafe to generalise this to every program that constructs an outer dictionary. If a function simply reuses an input’s nested list, the two dictionaries can still point to the same mutable object.

Python’s copy documentation distinguishes assignment, shallow copying and deep copying. For this workshop, do not memorise “copy means safe” as a universal rule. Follow which objects are actually created and which are reused. The test later changes a returned tag list and checks the original catalogue, providing a concrete observation at the boundary we care about.

Effects can also be conditional on successful earlier work. If make_plan raises an exception, run_session never reaches events.append. No successful-planning event is added by that call. The wrapper has no catch block that would turn the failure into a plan. This ordering tells you more than a name such as run_session or a comment saying “record activity” would tell you.

Draw effects at the edge of your architecture map. Mark printing as occurring in main. Mark event-list mutation as occurring in run_session. Mark the planner as returning data for the intended built-in input shapes. Do not add a database cylinder merely because the word event sounds like analytics. The list is in memory, and this program includes no persistence implementation.

In a real application, follow the same discipline for consequential effects. Find the exact call that sends the email, writes the record or changes the permission. Establish what has already been checked before that call and what happens if it fails. For a reading task, you can often identify the boundary without triggering it. Understanding an effect is not an instruction to perform it.

Back to contents · Continue to the next chapter

9. Treat tests as evidence with a visible scope

Tests turn claims into repeatable checks, but they do not remove the need to read. A passing test proves that its assertions held for the execution you ran. It does not prove that the test asserted the right thing, covered every input or reproduced a production environment. Your job as a reader is to connect each test to the behaviour it establishes and to notice what remains outside that scope.

Save the following complete file beside the four application files. It uses Python’s standard unittest library. The methods are small because each one asks a particular comprehension question. They check the normal route, a subject filter, input ownership, a zero budget, the order of validation and filtering, duplicate handling, a boolean boundary and accumulated event state.

File 5: test_reading.py

import copy
import unittest

from app import run_session
from catalog import TASKS
from planner import make_plan


class ReadingTests(unittest.TestCase):
    def ids(self, plan):
        return [row["id"] for row in plan["tasks"]]

    def test_default_route(self):
        plan = make_plan(TASKS, 40)
        self.assertEqual(self.ids(plan), ["B", "D"])
        self.assertEqual((plan["used"], plan["remaining"]), (35, 5))

    def test_filter_and_exact_fit(self):
        plan = make_plan(TASKS, 35, " ENGLISH ")
        self.assertEqual(self.ids(plan), ["B", "D"])
        self.assertEqual(plan["remaining"], 0)

    def test_input_is_unchanged(self):
        before = copy.deepcopy(TASKS)
        plan = make_plan(TASKS, 40)
        plan["tasks"][0]["tags"].append("changed")
        self.assertEqual(TASKS, before)

    def test_zero_budget(self):
        self.assertEqual(self.ids(make_plan(TASKS, 0)), [])

    def test_invalid_row_before_filter(self):
        bad = [{"id": "X", "title": "Hidden", "minutes": 0,
                "priority": 1, "tags": ["science"]}]
        with self.assertRaisesRegex(ValueError, "positive integer"):
            make_plan(bad, 40, "english")

    def test_duplicate_is_seen_before_fit(self):
        rows = [
            {"id": "x", "title": "Long", "minutes": 50,
             "priority": 3},
            {"id": " X ", "title": "Short", "minutes": 5,
             "priority": 2},
        ]
        self.assertEqual(self.ids(make_plan(rows, 10)), [])

    def test_boolean_budget_rejected(self):
        with self.assertRaises(ValueError):
            make_plan(TASKS, True)

    def test_event_state_accumulates(self):
        events = []
        run_session(TASKS, 40, events)
        run_session(TASKS, 20, events)
        self.assertEqual(events, [{"kind": "planned", "count": 2},
                                  {"kind": "planned", "count": 1}])


if __name__ == "__main__":
    unittest.main()

Run the tests with the following command from the same study folder. The full local run passed all eight named tests. Execution timing varies between computers, so only the stable result summary is reproduced here. See Python’s unittest documentation for the runner and assertion methods used in the file.

python -m unittest -v test_reading
Ran 8 tests
OK

Read one assertion closely. The first test checks both selected identifiers and the used/remaining pair. If it only checked that the result was a dictionary, a completely wrong selection could pass. If it only checked used equals thirty-five, a different set of tasks using the same duration might pass. Assertions choose what evidence you obtain; the word test does not make that evidence comprehensive.

The input-ownership test uses a deep copy as a before-state snapshot and then deliberately mutates a returned nested tag list. It asks a more specific question than “does the function work?” The event-state test calls the wrapper twice using the same list. That sequencing is essential: a single-call test could not establish how state accumulates across calls. Read setup and call order as carefully as the final assertion.

The suite is intentionally incomplete. It does not test every malformed field shape, every possible priority tie or every custom Python object a caller could supply. It does not test educational quality, real student behaviour or performance on a huge dataset. A reader should report these limits plainly. Adding tests can improve evidence, but inventing confidence cannot.

Ask SI to produce a claim-to-test map before asking it to add code. For each claim, request the test that supports it, the input used and the exact assertion. If no test supports a claim, label it untested. Then inspect the implementation yourself. This makes the assistant useful as an organiser of evidence while keeping the evidence visible and checkable.

Back to contents · Continue to the next chapter

10. Examine three deliberate traps without rushing to fix them

The first trap is duplicate handling. Imagine two raw rows whose identifiers become X after cleaning. The first has priority three and takes fifty minutes. The second has priority two and takes five minutes. With a ten-minute budget, a casual reader may expect the shorter version to be selected after the longer version fails to fit. That is not the displayed rule. The higher-priority version is encountered first and its identifier enters seen before the fit check. The shorter duplicate is then skipped by the duplicate check.

This is surprising only if you silently assumed a different policy. The existing code chooses one encountered representative of each identifier before checking whether that representative fits. You may dislike that policy. You may want duplicates rejected, merged or resolved by another rule. Those are product decisions. First demonstrate that you understand the present behaviour; then discuss whether it should change and what tests would specify the new contract.

The second trap is validation before filtering. Suppose the only supplied row is tagged science and has zero minutes. You request English. It is tempting to say the row is irrelevant and will be ignored. However, the list of normalised rows is constructed before the eligibility list. The duration check raises an error before the tag filter has an opportunity to exclude anything. The order of two plausible operations changes the result.

This also shows why errors belong in a trace. The exceptional route does not return an empty successful plan. It exits through an exception, and the wrapper never appends its successful-planning event. Python’s errors and exceptions tutorial explains propagation and handlers. In this example there is no handler inside make_plan or run_session, so a caller must handle the exception if it wants a different presentation.

The third trap concerns state created at function-definition time. The following separate file is a deliberately misleading miniature, not a recommended design for the planner. Save it as default_trap.py if you want to reproduce the observation. Before running it, predict all four printed lists and explain which calls share a bucket.

def remember(item, bucket=[]):
    bucket.append(item)
    return list(bucket)


print(remember("A"))
print(remember("B"))
print(remember("C", []))
print(remember("D"))
python default_trap.py
['A']
['A', 'B']
['C']
['A', 'B', 'D']

The omitted bucket argument uses the same default list across those calls. Supplying a fresh explicit list for C uses a different bucket for that call; it does not reset the existing default. The function returns a new outer list each time, but that does not undo the mutation of the bucket. A model that focuses only on “return list(bucket)” can overlook where the persistent state lives.

These traps share a reading lesson. Words such as normalise, duplicate, optional and copy are not enough. Find the order of operations, the location of object creation and the exact branch that controls the next step. When an outcome conflicts with your intuition, treat the discrepancy as a chance to refine your mental model. Do not erase the evidence by changing the implementation before you can explain it.

Back to contents · Continue to the next chapter

11. Challenge unsupported model explanations with small counterexamples

SI is useful when it helps you formulate a checkable claim. It is less useful when it supplies a smooth story that you accept because it sounds like familiar software. The following explanations are illustrative claims to evaluate. They are not quotations from tested AI products. Each one demonstrates a specific reading failure and a way to challenge it without asking the model to judge its own confidence.

Claim one: “The planner chooses the combination that makes the best use of available time.” The forty-minute result uses thirty-five minutes, although tasks A and C together also use thirty-five and other budgets reveal different compromises. More decisively, with twenty minutes available, A alone would fill all twenty minutes, yet the implemented priority-and-duration order selects D first and then cannot fit A. It uses ten minutes. The code is a ranked greedy selection rule, not a search over all combinations.

Claim two: “Invalid tasks outside the selected subject cannot affect the result.” The zero-minute Science row requested under an English filter is a counterexample. Point to the construction of rows before eligible and to the test asserting this rejection. A revised explanation should describe the execution order rather than offering a vague qualification such as “usually”. One counterexample is enough to refute the unrestricted claim, although it does not describe every possible malformed input.

Claim three: “The event log counts every task that was considered.” The wrapper appends one event after planning and puts the number of selected tasks inside it. It has no visibility into the intermediate loop unless make_plan exposes that information. A useful challenge asks the assistant to identify the exact append statement and the value used for count. The absence of an append inside the planning loop matters more than the familiar phrase event log.

Claim four: “The function safely handles any data because it validates its inputs.” The explicit integer checks are real, but the string and container assumptions remain. Ask which statement would handle a missing id, a numeric title or tags supplied as a plain string. Do not accept an invented validation helper. The correct answer may be that one case raises an ordinary Python exception and another proceeds with an unintended interpretation.

Claim five: “Importing app runs the study session.” Inspect the guard and try the bounded import-only command below after reviewing the displayed modules. Its output was verified locally. The absence of the application report is the relevant observation; it does not imply that arbitrary imports in other projects are free of effects.

python -c "import app; print('import complete')"
import complete

Challenge a claim by making it precise, locating its supposed evidence and designing a discriminating case. A discriminating case gives different results under the competing explanations. Twenty minutes distinguishes ranked greedy selection from always filling the budget. An invalid excluded subject distinguishes filtering first from validating first. This approach makes the assistant’s explanation accountable to the program rather than to the assistant’s rhetorical confidence.

Back to contents · Continue to the next chapter

12. Build a small architecture map you can defend

An architecture map should help another reader find a behaviour and understand a boundary. For this program, five boxes are enough: catalogue, normalisation, planning, application wrapper and presentation. Add the tests as an observing caller rather than pretending they are a stage every application run passes through. The map can be written as ordinary sentences; a sophisticated diagramming tool is unnecessary.

Here is a defensible map of the direct-run route. App.main obtains the module-level TASKS list and chooses a budget of forty. App.run_session calls planner.make_plan. Planner.make_plan calls normalise.normalise for each row, filters and ranks the cleaned rows, and builds the plan. Run_session then appends one summary event to the provided list. App.format_report turns the plan into text, and main prints that text plus the number of events.

Now add boundary notes. The catalogue is a local fictional data source. The normalisation boundary assumes particular string and container shapes while explicitly validating two numeric fields. The planner owns fresh local selection state for each call. The wrapper mutates caller-owned event state when it receives a destination. Presentation reads the returned plan and produces text. There is no network, database, browser, scheduler or AI inference call in this application.

Distinguish an import edge from a call edge. App imports make_plan from planner, but importing that name does not by itself call it. Planner imports normalise, while its list comprehension later calls normalise repeatedly. Catalog has no reverse call into app. A diagram that uses one undifferentiated arrow for “imports”, “calls”, “contains” and “changes” can look coherent while saying very little. Label each relationship or explain your legend in words.

Include the evidence and the uncertainty. “Normalise creates a new tags list” is backed by the list comprehension. “The author intended to prevent all shared-state mistakes” is not established by that line. “This is a study planner demonstration” is the workshop context. “This architecture is suitable for a school’s production student-management system” is not a conclusion you can draw from these files. A good map stays within its evidence boundary.

The map should also answer a location question. If you want to understand why D appears before A, inspect the ranking key in planner.py. If you want to understand why the event list grows, inspect run_session in app.py. If you want to understand why input tags are lowercase in the result, inspect normalise.py. If you want to know whether a behaviour has a repeatable check, inspect test_reading.py. This makes the map an aid to navigation rather than a substitute for source.

For a larger codebase, keep this same scale at first. Map one request route or one feature using a handful of components. Link each component to an actual file, symbol or configuration entry. Add neighbouring systems only when their behaviour changes the question. Your map can grow over time, but every new edge should have evidence. Do not reward a model for inventing a more impressive architecture than the repository contains.

Back to contents · Continue to the next chapter

13. Use SI to teach your reading rather than replace it

A productive SI session begins with your own prediction. Give the assistant the relevant complete files and a bounded question, then ask it to help test your explanation. For example: “I predict that forty minutes selects B and D, uses thirty-five minutes and appends one event. Check my trace against the supplied files. Identify the first unsupported step, if any. Do not change the code.” This keeps the centre of the activity on your understanding.

When a concept is unfamiliar, request an explanation at the right level. “Explain the three-part sort key using these four rows” is more useful than “teach me all sorting”. Ask for the intermediate ranked order and the values of the key for each row. Then calculate them yourself. If you cannot reproduce the order without rereading the answer, the explanation has not yet become a skill you can use independently.

Ask the assistant to expose missing context. A useful prompt is: “Separate facts established by these files from assumptions about the surrounding application. For each uncertain claim, say which file, test or runtime observation would resolve it.” This discourages the common habit of filling an incomplete repository with a standard architecture from memory. You should still check that the supposed facts really appear in the supplied material.

For larger snippets, ask for a reading route rather than a complete lecture. “Which three symbols should I inspect to explain the duplicate policy?” invites a short, actionable answer. You can then read those symbols and return with a specific question. This reduces cognitive load and makes it easier to spot when the assistant has named a nonexistent helper or confused two similarly named modules.

Use delayed answers for practice. Ask SI to give one changed input and wait for your predicted output before revealing its analysis. In your own session, you can achieve the same effect by covering the answer section below. The important mechanism is retrieval and prediction, not the presence of a chatbot. You become better at code reading by attempting the reasoning and checking it, rather than merely recognising a correct explanation after someone else has supplied it.

Keep prompts honest about execution. “Reason about this code” requests analysis. “Suggest a test I can run” requests a proposed experiment. Neither means the assistant actually ran anything. If an assistant claims to have executed tests, ask for the command, environment, relevant output and any changed files. If tools were unavailable, its expected output should be labelled as a prediction. In this article, reported outputs come from local execution of the printed teaching files; the prompts remain illustrative.

Finish with a short explanation in your own words. Name the entry point, the transformation order, one important branch, one state boundary and one unknown. Then ask a human peer, teacher or maintainer to challenge that explanation when the stakes justify it. SI can help you prepare the explanation, but you should be able to defend it without treating another generated paragraph as the final authority.

Back to contents · Continue to the next chapter

14. Change conditions and see which conclusions survive

Understanding is stronger when it transfers to a nearby condition. Keep the implementation fixed and change the budget, subject filter or supplied rows. A correct explanation should predict which parts stay the same and which parts change. The following complete trace file provides several such cases. Save it beside the application files as trace_cases.py. It deliberately handles the final error so that the event-list observation can also be printed.

from app import run_session
from catalog import TASKS
from planner import make_plan


def show(label, plan):
    ids = ",".join(row["id"] for row in plan["tasks"]) or "none"
    print(f"{label}: {ids}; used={plan['used']}; left={plan['remaining']}")


for budget in (20, 25, 40, 50, 55):
    show(f"budget {budget}", make_plan(TASKS, budget))
show("math 40", make_plan(TASKS, 40, " MATH "))
show("empty tag 40", make_plan(TASKS, 40, ""))

duplicates = [
    {"id": "x", "title": "Long", "minutes": 50, "priority": 3},
    {"id": " X ", "title": "Short", "minutes": 5, "priority": 2},
]
show("duplicate 10", make_plan(duplicates, 10))

bad = [{"id": "Q", "title": "Other subject", "minutes": 0,
        "tags": ["science"]}]
events = []
try:
    run_session(bad, 40, events, "english")
except ValueError as error:
    print(f"filtered invalid: {type(error).__name__}: {error}")
print(f"events after error: {events}")
python trace_cases.py
budget 20: D; used=10; left=10
budget 25: B; used=25; left=0
budget 40: B,D; used=35; left=5
budget 50: B,D,C; used=50; left=0
budget 55: B,D,A; used=55; left=0
math 40: A; used=20; left=20
empty tag 40: none; used=0; left=40
duplicate 10: none; used=0; left=10
filtered invalid: ValueError: minutes must be a positive integer
events after error: []

The fifty-minute and fifty-five-minute cases are particularly instructive. With fifty minutes, B and D leave fifteen, so A cannot fit and C can. With fifty-five minutes, B and D leave twenty, so A fits and C no longer fits afterwards. Increasing the budget changes which lower-priority task appears. It does not simply append a new task to the old selection. An interface that assumes selected tasks only accumulate as the budget rises would be assuming a property this algorithm does not provide.

The twenty-minute and twenty-five-minute cases teach a related lesson. At twenty, B cannot fit and D is selected before A is considered. At twenty-five, B fits exactly and consumes the budget. D therefore disappears from the result even though the budget grew. Selection membership is not monotonic in the budget. That phrase is optional vocabulary; the concrete prediction is the essential understanding.

The subject cases show that None and an empty string are distinct inputs. None means no filter. An empty string is cleaned into an empty string and used as an actual membership target. None of the example tags is empty, so no task qualifies. The code does not interpret a blank subject as “all subjects”. A user interface might choose to translate a blank form field to None before calling the planner, but no such interface appears in these files.

When you change conditions, change one conceptual dimension at a time unless you are explicitly studying an interaction. Otherwise, an unexpected result may have several possible explanations. First vary only the budget. Then vary only the filter. Then use a small custom catalogue to examine duplicates. Preserve the original case as a reference so that your comparison is about behaviour, not about accidentally changing the program while experimenting.

A successful prediction under one changed condition is progress, not universal proof. Record what it establishes. The displayed outputs confirm these particular routes in the local teaching environment. They do not validate every future input, every alternate Python implementation or an undisplayed application that happens to use similar names. Careful scope makes an explanation more trustworthy, not less useful.

Back to contents · Continue to the next chapter

15. Independent exercises: predict before checking

Use the original application files unless an exercise explicitly supplies different data. Write your answer before reading the next section. For output questions, include selected identifiers, used minutes and remaining minutes. For explanation questions, name the function or condition that supports your answer. A result without a reason can be a lucky guess; a reason without a concrete prediction can conceal a misunderstanding.

Exercise A: a smaller subject-specific plan

Call make_plan with TASKS, a budget of twenty and required_tag set to “ ENGLISH ”. Which identifiers are selected? Why does the presence of a higher-priority English task not prevent all planning? Explain the role of the fit condition and the fact that the loop continues after a task is skipped. Also state whether the original English tag strings in TASKS change.

Exercise B: the boundary at zero

Call make_plan with TASKS and a budget of zero. Is zero rejected? Which result values should you receive? Then replace zero with False. Does the function behave the same way merely because False can compare numerically like zero in some Python contexts? Point to the exact budget condition rather than relying on a broad statement about truthiness.

Exercise C: missing and explicit optional values

Use one row with id K, title “Recall”, minutes five and no priority or tags fields. Plan with a five-minute budget and no required subject. Predict the selected task’s priority and tags. Then add priority set to None. Is that the same request? Finally, keep the original row but require the tag math. Explain why the result differs without claiming that the missing tags field is an error.

Exercise D: an error and an event destination

Create events as an empty list. Call run_session with a single row whose id is Q, title is “Review” and minutes is zero, passing events as the third argument. Assume the caller catches the resulting exception outside run_session. How many events remain afterwards? Does the wrapper return a plan before the error? Explain the order of make_plan, events.append and return.

Exercise E: ranking ties

Use the following complete rows and call make_plan(rows, 5). Both tasks have priority two and take five minutes, and Z appears first in the input. Which row is selected? Which element of the ranking key decides? Then change Z’s priority to three without changing the input order or budget. Predict the new result and explain why input order is not the deciding factor in either case.

rows = [
    {"id": "Z", "title": "Task Z", "minutes": 5, "priority": 2},
    {"id": "A", "title": "Task A", "minutes": 5, "priority": 2},
]

Exercise F: a duplicate that cannot fit

Reuse the complete duplicates list printed in trace_cases.py: the high-priority X titled Long takes fifty minutes, and the lower-priority X titled Short takes five minutes. Call make_plan(duplicates, 10). A classmate says, “It skips the long version, then uses the short version.” Identify the precise statement that makes the classmate’s explanation fail. What additional business decision would you need before proposing a change to the duplicate policy?

Exercise G: what the evidence does not show

Someone reads the eight passing tests and claims the planner maximises useful revision, accepts every malformed input gracefully and stores a permanent audit history. For each claim, state whether it is established, contradicted or outside the demonstrated scope. Give a source-level observation or counterexample where possible. Avoid replying simply that “tests are never enough”; explain exactly what these tests and files do show.

Exercise H: explain the system to another reader

Write a five-sentence architecture explanation. Include an entry point, a data transformation, a control-flow choice, a state or side-effect boundary and one limitation. You may not use the vague phrase “the AI handles it”. The program contains no AI call. Your explanation should help a classmate locate the right file for a follow-up question.

Back to contents · Continue to the next chapter

16. Worked answers and why they follow

Answer A: D fits after B is skipped

The result selects D, uses ten minutes and leaves ten minutes. The cleaned English filter keeps B and D. B is ranked first because it has priority three, but its twenty-five minutes exceed the available twenty. The loop does not stop at that failure. D is then considered and fits. The normaliser creates cleaned task dictionaries and tag lists, so the original catalogue strings remain unchanged. This answer distinguishes “highest priority considered first” from “highest priority must always be selected”.

Answer B: zero is accepted, False is rejected

With the integer zero, no positive-duration task fits. The result has an empty tasks list, used zero and remaining zero. False fails the exact-type check because its type is bool rather than int. The function raises ValueError before normalising rows. The answer depends on the implemented condition, not on whether Python generally treats booleans as numeric subtypes. An alternative implementation could accept them, but this one deliberately does not.

Answer C: absence selects defaults; None is a supplied value

The original K row is selected and receives priority zero and an empty tags list in its normalised representation. It uses five minutes and leaves zero. Adding priority None causes the explicit priority validation to fail; get does not replace an existing None with the default zero. Requiring math for the original row produces an empty selection, used zero and remaining five, because the empty tags list contains no math tag. Missing tags is permitted here and does not imply every arbitrary tags value would be handled safely.

Answer D: the failure prevents the event append

The event list remains empty. The call to make_plan happens before the wrapper’s event check and append. Normalisation rejects zero minutes, and that exception propagates out of run_session. There is no returned plan from this failing call, and no successful-planning event is appended. A handler in the caller can decide how to present the failure, but it cannot retroactively make the wrapper’s later lines have executed. This is an example of control flow determining whether a side effect occurs.

Answer E: the identifier breaks the first tie

A is selected in the first case, using five minutes and leaving zero. The priorities match, the durations match, and the third key element compares the identifiers. A ranks before Z even though Z was supplied first. After Z’s priority becomes three, Z is selected because the first key element now gives it precedence. You do not need to appeal to sorting stability for either case because the two complete keys differ. Stability matters only after you establish that the relevant comparison keys tie.

Answer F: an encountered identifier becomes seen before fit

The result is empty, with used zero and remaining ten. The first X enters seen before the duration condition rejects it. The second X reaches the earlier membership check and is skipped. Before changing this, ask which duplicate policy the application requires: reject duplicate input, choose the highest-priority representative, choose a fitting alternative, or treat the rows as separate tasks with different identities. None of those policies is automatically authorised by finding the current behaviour surprising.

Answer G: separate a policy, an input boundary and persistence

Useful revision is outside the demonstrated scope; the code does not measure learning quality. A claim that it maximises filled time is contradicted by the twenty-minute case. Graceful handling of every malformed input is unsupported and overbroad because the normaliser directly accesses and strips fields; the displayed suite does not test every malformed shape. Permanent audit history is contradicted as a description of this implementation: the wrapper appends to an in-memory list and no persistence boundary is present. The eight tests establish their specific assertions under the tested inputs.

Answer H: one acceptable five-sentence map

Running app.py directly calls main through its bottom guard. Main supplies the fictional catalogue and a forty-minute budget to run_session, which calls make_plan. The planner normalises every row, filters by an optional tag, ranks rows and selects unseen identifiers that fit. After a successful plan, run_session appends one summary event to the caller’s list, while main prints the formatted result. The program does not optimise learning outcomes or save a persistent history, and its input validation assumes particular string and container shapes.

Your wording need not match these answers. What matters is whether you preserve the distinctions and can point to supporting evidence. If you got the output right but gave the wrong reason, repeat the exercise with a changed input designed to separate those reasons. That is how a correct answer becomes a dependable model of the code rather than a memorised example.

Back to contents · Continue to the next chapter

17. Transfer the method to a larger codebase

The small program removes distractions, but the reading method transfers. Begin with a behaviour that someone can observe: a submitted form, a generated report, a rejected request or a displayed total. Find where that behaviour enters the application. Then trace one representative input through parsing, validation, transformation, state access and output. Keep a note of configuration that selects the route. You are building an evidence chain, not trying to read the repository alphabetically.

Use names as search aids, not as proof. A folder called services may contain pure transformations, network clients or a mixture. A function named validate might only check one field. A test named handles_all_errors might assert one example. Read the implementation and the relevant callers. When documentation and source disagree, record the disagreement and seek the authoritative contract rather than silently choosing whichever description is more convenient.

Pay special attention to indirection. A framework may register a handler through a decorator, configuration file or routing table. A callback may be passed to another component and executed later. A dependency may be supplied through a constructor rather than imported directly. In each case, identify the wiring that makes the route real. Do not assume that a function is called simply because it exists or because an assistant recognises a familiar framework pattern.

Separate your environment from the environment being explained. Tests may use an in-memory substitute while production uses a database. A development configuration may disable an external message sender. A feature flag may select a different implementation. State exactly which configuration you inspected. A locally passing test of a substitute establishes something useful about that boundary, but it does not automatically establish the behaviour of the real external system.

When execution is authorised and safe, choose the smallest observation that distinguishes your hypotheses. Use synthetic inputs and approved test environments. Inspect existing tests before introducing new scripts. Avoid triggering real messages, payments, account changes or destructive data operations merely to see what happens. For a comprehension task, a source trace and a maintainer’s explanation may be the appropriate stopping point at a consequential boundary.

For asynchronous or concurrent code, add time to your map. Identify what is scheduled, what is awaited, what can complete later and what shared state may change between observations. Do not reuse a simple top-to-bottom story when the program can interleave work. Similarly, for cached data, ask who populated the cache, what key selects an entry and when it expires or is invalidated. These questions extend the same input, control and state framework rather than replacing it with a new vocabulary exercise.

Before suggesting a change, present your understanding to someone responsible for the code. “For this input and configuration, this route reaches this effect; these tests cover it; this case remains unclear.” That is a productive starting point for review. It gives maintainers something concrete to confirm or correct and prevents a generated rewrite from arriving before the problem has even been understood.

Back to contents · Continue to the next chapter

18. Build a repeatable code-reading practice

A useful practice session has a small finish line. Choose a program or feature you are allowed to inspect. Spend the first part locating its entry point and outlining one route. Spend the next part tracing a specific input by hand. Then check the prediction through safe execution, existing tests or a careful source-level review. Finish by predicting a changed condition without looking at the earlier explanation. The exact minutes matter less than completing the full reasoning cycle.

Keep a short comprehension record rather than a transcript of everything the assistant said. Record the question, the files and symbols inspected, your prediction, the observation, the revised explanation and one remaining uncertainty. When you return later, those six items help you reconstruct the evidence. A long conversation can contain abandoned guesses and contradictory summaries; it is not automatically a reliable technical note.

Use errors in your prediction as diagnostic information. If you missed a selected task, perhaps you followed input order instead of ranked order. If you expected an event after a failure, perhaps you treated the call as successful before checking exception flow. If you thought an empty filter meant no filter, perhaps you collapsed distinct input representations. Name the reading mistake and design a nearby exercise that forces you to notice it next time.

As your confidence grows, reduce the amount of explanation you request. First ask for a full worked trace. Later ask for one hint about the branch you missed. Eventually ask only for a counterexample to your own model. This gradual transfer of responsibility is the learning benefit of SI: it can supply responsive support while you practise the reasoning that must become yours.

Can I understand code before I can write similar code?

Yes, within a suitable level of complexity. Reading gives you a concrete object to inspect, while writing requires choosing an implementation. You still need enough language knowledge to interpret the syntax and runtime rules correctly. Start with a small complete program, identify unfamiliar constructs and learn them in context. Do not mistake familiarity with an explanation for the ability to predict behaviour independently.

Should I ask SI to explain every line?

Sometimes, for a short unfamiliar function. For a larger system, a line-by-line commentary can hide the route you need. Start with the behaviour, entry point and boundaries. Zoom into a line when it changes a value, branch, state or effect relevant to that behaviour. The goal is an explanation at the right scale, not a paraphrase of every token.

When am I ready to propose a change?

You are better prepared when you can describe the current contract, show a concrete case, identify the exact decision point and explain which existing behaviour must remain. You also need the appropriate authority and review process for the project. Understanding does not grant permission to modify or deploy code. It gives you the evidence needed to make a clear, bounded proposal.

What should I remember from this workshop?

Begin with one observable question. Follow actual inputs through actual calls. Separate definitions from runtime execution, and separate data, control and state. Check return values and side effects. Read tests for their specific assertions. Challenge confident explanations with discriminating cases. Finally, explain the system in your own words and preserve what you still do not know.

The result is a practical kind of independence. You can use SI to ask better questions and receive useful feedback while retaining responsibility for what you believe about the software. Return to the Super Intelligence Learning hub to choose the next skill, or revisit the complete program, changed conditions and independent exercises until you can predict the behaviour without the answer beside you.

Back to contents · Return to the Learning hub