1. Create a planner folder
You will build a product showing which package must be ready before another. A dependency means one package needs another. A batch lists names that are ready together; the app does not execute them.
You need Python 3 and an editor. Check python3 --version; if unavailable, install Python 3 and reopen the terminal. Actual checks used Python 3.14.4. Save the three files in paket-plani-v1 as UTF-8 without hidden .txt extensions. Do not save the tree itself.
paket-plani-v1/
app.py
demo.json
test_app.py
2. Implement dependency rules in app.py
Save the complete code as app.py. At the start of each round, plan selects every package with no remaining dependencies and sorts their names. It removes that batch before the next round. If work remains but nothing is ready, there is a dependency cycle.
This is graph planning: a graph represents packages and their relationships. Results are written only to a new file; existing input and output are not replaced. No network or extra library is used.
"""Dependency planner."""
import argparse
import json
import re
import sys
LIMIT = 1024 * 1024
NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,39}", re.ASCII)
class Invalid(Exception):
pass
def fail(message):
raise Invalid(message)
def object_pairs(pairs):
obj = {}
for key, value in pairs:
if key in obj:
fail("duplicate_key")
obj[key] = value
return obj
def plan(data):
if not isinstance(data, dict) or set(data) != {"packages"}:
fail("invalid_shape")
items = data["packages"]
if not isinstance(items, list) or len(items) > 100:
fail("invalid_packages")
graph = {}
for package in items:
if not isinstance(package, dict) or set(package) != {"name", "depends"}:
fail("invalid_shape")
name, depends = package["name"], package["depends"]
if not isinstance(name, str) or not NAME.fullmatch(name):
fail("invalid_name")
if name in graph:
fail("duplicate_name")
if not isinstance(depends, list) or any(
not isinstance(item, str) or not NAME.fullmatch(item) for item in depends
):
fail("invalid_dependencies")
if len(depends) != len(set(depends)):
fail("duplicate_dependency")
if name in depends:
fail("self_dependency")
graph[name] = set(depends)
if any(deps - graph.keys() for deps in graph.values()):
fail("unknown_dependency")
total, batches = len(graph), []
while graph:
ready = sorted(name for name, deps in graph.items() if not deps)
if not ready:
fail("cycle")
batches.append(ready)
for name in ready:
del graph[name]
for deps in graph.values():
deps.difference_update(ready)
return {"batches": batches, "total": total}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input")
parser.add_argument("output")
args = parser.parse_args()
try:
try:
with open(args.input, "rb") as source:
raw = source.read(LIMIT + 1)
except OSError:
fail("input_error")
if len(raw) > LIMIT:
fail("input_too_large")
try:
data = json.loads(raw.decode("utf-8"), object_pairs_hook=object_pairs,
parse_constant=lambda _: fail("invalid_constant"))
except (ValueError, RecursionError):
fail("invalid_json")
output = json.dumps(plan(data)) + "\n"
try:
with open(args.output, "x", encoding="utf-8") as target:
target.write(output)
except FileExistsError:
fail("output_exists")
except OSError:
fail("output_error")
except Invalid as error:
print("error: " + str(error), file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
3. Define three packages in demo.json
Save the complete sample as demo.json. JSON is a text format with named fields. Each item in packages has a name and depends list. core, ui and site are invented teaching names.
Although site appears first in the input, core is ready first. ui depends only on core, and site depends on ui. batches will therefore contain core, then ui, then site. Changing input order does not change the plan.
{"packages":[{"name":"site","depends":["ui"]},{"name":"ui","depends":["core"]},{"name":"core","depends":[]}]}
4. Run and correct a cycle
Open a terminal in the folder: python3 app.py demo.json plan.json. Success prints nothing. Expect total 3 and batches [["core"],["ui"],["site"]] in plan.json. Reusing the output name gives error: output_exists; choose plan-2.json for a new result.
Put {"packages":[]} in empty.json. Run python3 app.py empty.json empty-plan.json. Expect total 0 and empty batches. In a copy of demo, change core’s depends to ["site"] to create a cycle. A fresh output run must give error: cycle without creating output. Restore core’s empty [] list to fix it.
5. Verify output with test_app.py
Save the complete tests as test_app.py and run python3 -m unittest -v test_app.py. The product passed 3 test methods; expect Ran 3 tests and OK. They check the actual CLI, empty and invalid input, independent packages and preservation of existing files.
Names must be unique and dependencies must exist. A package cannot depend on itself. These checks prevent a silently incomplete plan. Tests use their own temporary files without personal information.
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
APP = Path(__file__).with_name("app.py")
DEMO = json.loads(APP.with_name("demo.json").read_text())
class Tests(unittest.TestCase):
def cli(self, raw, exists=False, same=False):
with tempfile.TemporaryDirectory() as folder:
src, dst = Path(folder) / "in.json", Path(folder) / "out.json"
src.write_bytes(raw)
if exists:
dst.write_bytes(b"keep")
if same:
dst = src
run = subprocess.run([sys.executable, str(APP), str(src), str(dst)],
capture_output=True, text=True)
self.assertEqual(src.read_bytes(), raw)
if exists:
self.assertEqual(dst.read_bytes(), b"keep")
if run.returncode and not exists and not same:
self.assertFalse(dst.exists())
return run, dst.read_text() if dst.exists() else None
def check(self, data, expected):
run, result = self.cli(json.dumps(data).encode())
self.assertEqual((run.returncode, run.stderr), (0, ""))
self.assertEqual(json.loads(result), expected)
def test_success(self):
self.check(DEMO, {"batches": [["core"], ["ui"], ["site"]], "total": 3})
self.check({"packages": []}, {"batches": [], "total": 0})
self.check({"packages": [{"name": n, "depends": []} for n in "zab"]},
{"batches": [["a", "b", "z"]], "total": 3})
extra = {"packages": DEMO["packages"] + [{"name": "docs", "depends": ["core"]}]}
self.check(extra, {"batches": [["core"], ["docs", "ui"], ["site"]], "total": 4})
def test_invalid(self):
cases = [b"{", b"\xff", b'{"packages":[],"packages":[]}',
b'{"packages":NaN}', b'{"packages":Infinity}', b" " * 1048577]
values = [[], {}, {"packages": [], "x": 1}, {"packages": {}},
{"packages": [{}]}, {"packages": [False]}]
rows = [[{"name": n, "depends": []}] for n in ["", "ü", "a" * 41, 1]]
rows += [[{"name": "a", "depends": d}]
for d in ["a", [1], ["b", "b"], ["a"], ["missing"]]]
rows += [[{"name": "a", "depends": [], "x": 1}],
[{"name": "a", "depends": []}] * 2,
[{"name": "a", "depends": ["b"]}, {"name": "b", "depends": ["a"]}],
[{"name": str(i), "depends": []} for i in range(101)]]
values += [{"packages": row} for row in rows]
cases += [json.dumps(value).encode() for value in values]
for raw in cases:
with self.subTest(raw=raw[:70]):
run, _ = self.cli(raw)
self.assertNotEqual(run.returncode, 0)
self.assertTrue(run.stderr.startswith("error: "))
def test_preserve(self):
for opts in [{"exists": True}, {"same": True}]:
run, _ = self.cli(json.dumps(DEMO).encode(), **opts)
self.assertEqual(run.stderr, "error: output_exists\n")
if __name__ == "__main__":
unittest.main()
6. Put two packages in one batch
Exercise: append {"name":"docs","depends":["core"]} to packages in a copy of demo, adding a comma after the previous element. Save exercise.json and run python3 app.py exercise.json exercise-plan.json. Expect batches [["core"],["docs","ui"],["site"]] and total 4.
Input is limited to 1 MiB and 100 packages. Names contain 1–40 ASCII characters, start with a letter or digit and may include dots, underscores and hyphens. Dependencies must be unique. These batches are our own planning rule, not npm approval or release order. Version compatibility, builds and publication are not tested.

