Company OAsAll ProblemsOA CalendarInterview ExperiencesPremium
OAHelper

Built by students, for students - practice company-specific OAs, DSA sheets, and real interview experiences to land your dream role.

© 2026 OAHelper.in·Terms·Privacy·Refunds·Trust & Safety·Contact·
Ready to crack your next OA?

Practice company-specific questions trusted by thousands of students across India.

Start PracticingGo Premium
OA Practice·DSA·Placements

Disclaimer: OAHelper is an independent educational platform. We (oahelper.in) do not own the images or questions shown. Content is uploaded by users.

Module 06

Initialization Scripts

  • Why Models Fail
  • A Minimal Workbench
  • Executable Constraints
  • Repo Memory and State
  • Initialization Scripts
  • Scope Contracts
On this page

This week

  • Why Models Fail
  • A Minimal Workbench
  • Executable Constraints
  • Repo Memory and State
  • Initialization Scripts
  • Scope Contracts

In plain words

Every time an agent starts fresh, it wastes effort finding out the same things: which Python, which test command, where the files are. That is like checking the lab PC from zero every single class. An init script does all those checks once, writes them into a small report file, and stops the agent completely if anything is broken.

How it flows

  1. 1Session starts→
  2. 2Run probes→
  3. 3Collect statuses→
  4. 4Write report→
  5. 5Halt or start agent

A tiny example

Python
def probe_python():
    return ("python", "ok", "3.11")

probes = [probe_python(), probe_deps(), probe_tests()]
write_report(probes)
if any(s == "fail" for _, s, _ in probes):
    halt("workbench broken")
start_agent()

Notice that each probe returns the same three-part shape, so the report and the halt check stay simple.


What you will learn

  • Why every fresh agent session wastes time rediscovering the same boring facts.
  • How to write one small init script that checks the workbench before the agent starts.
  • How to save those checks into a report file the agent simply reads.
  • Why init must fail loudly instead of quietly guessing.

The problem, simply

Think of the first day of a new semester lab. Nobody has checked anything. Is the PC on? Is Python installed? Where is the dataset? Which command runs the experiment? You lose the first forty minutes just finding out.

Now imagine that happening every single lab session. That is exactly what happens to an AI agent.

Every new session, the agent starts cold. It guesses the Python version and the test command. It lists the repo folder four or five times looking for the entry point. It imports a package that was never installed. By the time it makes one real code change, thousands of tokens are gone on setup.

We call this the setup tax. You are paying it again and again for answers that never change. The fix is simple: pay it once, in a script, and write the answers down.

The idea

One script that runs before the agent

An initialization script, or init script, is a small program that runs first, before the agent loop starts. It does not write code and it does not talk to any model. It only checks things and writes a report.

  1. 1Session starts→
  2. 2Init script runs→
  3. 3Probes check workbench→
  4. 4Report written→
  5. 5Agent reads report

Each check is called a probe. A probe is just a small function that answers one question and returns three things: its name, a status, and a short detail line. Nothing clever.

What the probes check

  • Runtime versions. Wrong Python or Node version gives you silent wrong-version bugs later.
  • Dependencies. A missing package caught now costs far less than a missing package caught at step forty.
  • Test command. If the agent cannot run tests, it cannot verify its own work. That is a broken workbench.
  • Repo paths. Hard-coded paths drift over time. Resolve them once and pin them.
  • Environment variables. A missing API key should be a clear failure line, not a mystery crash.
  • State freshness. Leftover state from a crashed session is a trap.
  • Last-known-good commit. Something to compare against when the session ends.

Fail loud, fail fast, fail in one place

If a probe fails, stop. Do not let the agent "figure it out somehow". The entire purpose of init is to refuse to start when the workbench is broken. Silent fallback defeats the point.

Warning

Warning: An init script that quietly continues on failure is worse than no init script, because now you trust a broken setup.

It must be idempotent

Idempotent means running it twice changes nothing. The second run should produce the same report, only with a fresh timestamp.

Why does this matter? Because then you can call it from anywhere without fear: a pre-task hook, a CI job, a Docker entrypoint, a slash command.

A worked example

Suppose Priya is building an agent that fixes bugs in her college project repo. She writes init_agent.py with five probes.

She runs it on Monday. Python 3.11 is fine, pytest is found, API_KEY is set. All green, report written, agent starts.

On Wednesday a teammate removes pytest. The test-command probe fails, the script exits non-zero, the agent never starts. Priya sees one clear line: test command not found. Two minutes to fix, instead of an agent flailing and then reporting "all tests pass" when it never ran any.

IMPRemember: The agent should read facts, not rediscover them.

Three patterns from real setups

Last-known-good anchoring. Store the commit from the last successful merge in a file. At init, compare the current commit against it. If more than, say, fifty files changed, refuse to start until a human approves the new baseline. This stops drift from piling up across sessions.

Lock file with a time limit. After one successful probe pass, write a prereqs.lock file. On later runs, if the lock is still fresh (say under 24 hours) and the dependency list hash has not changed, skip the expensive probes. Same idea as Docker layer caching.

No network, no model calls in init. Probes are plain deterministic plumbing. A probe that calls a language model to classify a failure is not a probe, it is a whole workflow. Keep the whole init under about three seconds. If one probe is slower than three seconds, either cache its result or move it out of init.

  1. 1Probe runs→
  2. 2Status recorded→
  3. 3Any blocker?→
  4. 4Halt or continue

Build it

Python
#!/usr/bin/env python3
"""A tiny init script: probe the workbench, write a report, fail loud."""

import importlib.util
import json
import os
import shutil
import sys
import time

# Each probe returns (name, status, detail). Status is "ok" or "fail".
# "block" probes stop the agent. "warn" probes only get noted.

def probe_python():
    ok = sys.version_info >= (3, 8)
    return ("python_version", "ok" if ok else "fail",
            "%d.%d found" % sys.version_info[:2])

def probe_deps(packages):
    missing = [p for p in packages if importlib.util.find_spec(p) is None]
    return ("dependencies", "fail" if missing else "ok",
            "missing: " + ", ".join(missing) if missing else "all present")

def probe_test_command(cmd):
    found = shutil.which(cmd) is not None
    return ("test_command", "ok" if found else "fail",
            cmd + (" resolvable" if found else " NOT on PATH"))

def probe_env(keys):
    missing = [k for k in keys if not os.environ.get(k)]
    return ("env_vars", "fail" if missing else "ok",
            "missing: " + ", ".join(missing) if missing else "all set")

def run_init():
    blocking = ["python_version", "dependencies"]   # these stop the agent
    probes = [
        probe_python(),
        probe_deps(["json", "os"]),        # stdlib names, so this passes
        probe_test_command("python3"),     # pretend this is your test runner
        probe_env(["PATH"]),
    ]
    report = {
        "timestamp": int(time.time()),
        "probes": [{"name": n, "status": s, "detail": d} for n, s, d in probes],
    }
    for name, status, detail in probes:
        print("%-16s %-5s %s" % (name, status, detail))
    with open("init_report.json", "w") as f:
        json.dump(report, f, indent=2)
    failed = [n for n, s, _ in probes if s == "fail" and n in blocking]
    if failed:
        print("INIT FAILED -> " + ", ".join(failed))
        return 1
    print("INIT OK -> init_report.json written, agent may start")
    return 0

if __name__ == "__main__":
    sys.exit(run_init())

Look at the printed table: every probe gives a name, a status and one detail line. Then open init_report.json and see the same facts stored, so the agent reads them instead of checking again. Run the script twice and compare the two reports; only the timestamp should change. That is idempotence in action.

Where you will see this

  • Claude Code hooks: a pre-task hook runs the init script and refuses to launch the agent if it fails.
  • GitHub Actions: a setup job runs the init script, and the agent job depends on it passing.
  • Docker entrypoints: the container runs init before starting the agent runtime, so failures show up in logs.
  • Cursor and similar editor agents: project setup files that tell the agent the build and test commands up front.
  • Any company CI pipeline: the "verify environment" step before the real build is the same idea, without the agent.

Common mistakes

  • Letting a failed probe pass silently. The agent then works on a broken setup and reports confident nonsense. Halt instead.
  • Putting model calls or network calls inside init. That makes init slow and non-deterministic, so you can no longer trust it as a baseline check.
  • Making the script non-idempotent. If a second run changes things, you cannot safely call it from hooks and CI, which is most of its value.
  • Probing everything under the sun. A thirty-second init is a tax of its own. Keep it to the checks that actually block work.
  • Writing the report but never reading it. If the agent still rediscovers paths every session, you added a script and kept the tax.

If they ask in an interview

Q: What is an initialization script for an agent, and why do you need one?

A: It is a small deterministic script that runs before the agent loop and checks the workbench: runtime version, dependencies, test command, paths, environment variables. It writes the results to a report file so the agent reads known facts instead of rediscovering them every session. This removes the per-session setup tax and catches broken environments early.

Q: Why must the init script fail loudly instead of continuing?

A: Because a broken workbench produces confident wrong output. If the test command is missing and the agent continues, it may claim tests pass when nothing ran. Halting with one clear error gives the human one place to look and one thing to fix.

Q: What should never go inside an init probe?

A: Network calls, model calls, and anything slow or non-deterministic. Probes are plain plumbing that should finish in a couple of seconds. If a check needs a model to interpret it, that is a workflow, not a probe, and it belongs outside init.

Try these

  1. Add a probe that compares the current commit with a stored last-known-good commit and refuses to start if more than fifty files changed.
  2. Make the script write a prereqs.lock file after a successful pass, and skip the slow probes if that lock is under 24 hours old.
  3. Add a --fix flag that installs missing development dependencies automatically, but never touches runtime dependencies without asking.
  4. Time each probe and print a warning for any probe that takes more than three seconds. Then decide what to cache.

Words, simply

WordMeaning in simple words
Init scriptThe small program that runs and checks everything before the agent starts
ProbeOne check that answers one question and returns a name, a status and a detail
Init reportThe JSON file holding all probe results, which the agent reads at startup
IdempotentRunning it twice changes nothing, except the timestamp
Fail loudStop and show the error to a human instead of quietly continuing
Setup taxThe tokens and time wasted every session rediscovering obvious facts
Last-known-goodThe last commit that was known to be fine, kept as a comparison point
Lock fileA small file saying "these checks passed recently, skip them for now"

Quick recap

  • Pay the setup cost once in a script, write the answers to a report, and let the agent read them.
  • Probes must be fast, deterministic, and offline; a failed blocking probe halts the session.
  • Idempotence is what makes the script safe to call from hooks, CI, and containers.

Check what you learned

1 / 7. What does an init script save you from?
1/7
PreviousRepo Memory and StateNextScope Contracts

On this page