Python lesson

Build an app that selects a working list of notes

Build a Python product that selects important notes and keeps the rest in an archive list, without deleting any original record.

1. Start a note-selection product

You will build a product that selects a limited working list from your notes. You assign each note its importance score. The tool selects the highest-ranked notes and keeps the rest in the output’s archive section. It is not AI that judges whether a note is true.

Python 3 and a text editor are enough. Check with python3 --version; if unavailable, install Python 3 and reopen the terminal. The actual tests used Python 3.14.4. No extra package, account or network connection is required.

Create qeyd-secimi-v1 and save the three files in the tree as UTF-8. Avoid hidden .txt extensions and do not save the tree itself. selection.json is generated output; do not create it in advance.

Text
qeyd-secimi-v1/
  app.py
  demo.json
  test_app.py

2. Implement selection in app.py

Save the complete code as app.py. select validates every note first. It sorts by descending priority, then descending updated for ties, then ascending ASCII id. The first capacity records are selected.

updated is an ordering number you supply, not a clock or an automatic date. Every remaining note retains all its fields in archived. This transparent rule is not the agentmemory algorithm and does not demonstrate improved recall.

JSON is a text format with named fields. Only after validating input does the program open new output in x mode. This mode does not overwrite an existing result. The original input file is left unchanged.

Pythonapp.py
"""Select working notes and archive the rest; delete nothing."""
import argparse
import json
from pathlib import Path
import re
import sys

LIMIT = 1024 * 1024


def reject(message):
    raise ValueError(message)


def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            reject("duplicate field")
        result[key] = value
    return result


def integer(value, low, high):
    return type(value) is int and low <= value <= high


def select(catalog):
    if type(catalog) is not dict or set(catalog) != {"capacity", "notes"}:
        reject("expected capacity and notes only")
    capacity, notes = catalog["capacity"], catalog["notes"]
    if not integer(capacity, 1, 100):
        reject("capacity: integer 1..100")
    if type(notes) is not list or len(notes) > 500:
        reject("notes: list, at most 500")
    seen = set()
    for note in notes:
        if type(note) is not dict or set(note) != {"id", "text", "priority", "updated"}:
            reject("note fields: id, text, priority, updated")
        identifier, body = note["id"], note["text"]
        if (type(identifier) is not str
                or not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", identifier)
                or identifier in seen):
            reject("id: unique ASCII [A-Za-z0-9_-], 1..64")
        seen.add(identifier)
        if type(body) is not str or not body.strip() or len(body) > 500:
            reject("text: nonblank, at most 500 characters")
        if not integer(note["priority"], 0, 100):
            reject("priority: integer 0..100")
        if not integer(note["updated"], 0, 1000000):
            reject("updated: integer 0..1000000")
    ordered = sorted(notes, key=lambda n: (-n["priority"], -n["updated"], n["id"]))
    return {"capacity": capacity, "selected": ordered[:capacity],
            "archived": ordered[capacity:]}


def run(source, destination):
    source, destination = Path(source), Path(destination)
    if source.resolve() == destination.resolve():
        reject("input and output must be different files")
    with source.open("rb") as stream:
        raw = stream.read(LIMIT + 1)
    if len(raw) > LIMIT:
        reject("input exceeds 1 MiB")
    catalog = json.loads(raw.decode("utf-8"), object_pairs_hook=unique_object,
                         parse_constant=lambda _: reject("nonfinite JSON number"))
    result = select(catalog)
    payload = json.dumps(result, indent=2, ensure_ascii=True) + "\n"
    with destination.open("x", encoding="utf-8") as stream:
        stream.write(payload)
    return result


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("input")
    parser.add_argument("output")
    args = parser.parse_args()
    try:
        result = run(args.input, args.output)
    except (OSError, ValueError, RecursionError) as error:
        print(f"error: {error}", file=sys.stderr)
        return 1
    print(f"selected={len(result['selected'])} archived={len(result['archived'])}")
    return 0


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

3. Prepare three records in demo.json

Save the complete data below as demo.json. The notes and text are invented; do not add personal information. capacity is the maximum selection size. id uniquely identifies a note, text contains its content, priority is its score and updated is its update-order number.

With capacity 2, c and b will be selected and a archived. The later correction c has score 9, putting it ahead of b with score 5. We assigned these sample scores; they are not automatic measurements of meaning or correctness.

JSONdemo.json
{
  "capacity": 2,
  "notes": [
    {"id": "a", "text": "Synthetic draft", "priority": 1, "updated": 1},
    {"id": "b", "text": "Synthetic plan", "priority": 5, "updated": 2},
    {"id": "c", "text": "Synthetic late correction", "priority": 9, "updated": 3}
  ]
}

4. Run and correct invalid input

Open a terminal in the folder: python3 app.py demo.json selection.json. Expect selected=2 archived=1. In selection.json, selected ids are c,b and archived is a. All four fields remain in each record. Reusing the output name causes an error; choose selection-2.json for a new result.

Create empty.json with {"capacity":2,"notes":[]}. Run python3 app.py empty.json empty-selection.json. Expect selected=0 archived=0. An empty note list is valid; a completely blank text file is not valid JSON.

Put {"capacity":true,"notes":[]} in bad.json. Run python3 app.py bad.json bad-selection.json. Expect error: capacity: integer 1..100 and no output file. Replace true with 2 and try again. In JSON, true is a Boolean value, not a whole count.

5. Verify results with test_app.py

Save the complete tests as test_app.py. Run python3 -m unittest -v test_app.py. The finished product passed 5 tests; expect Ran 5 tests and OK. Checks cover preservation of every record as well as selection.

Tests check tied scores, an empty list, invalid fields and types, strict JSON validation and the actual CLI. They also verify preservation of input and existing output. If you do not get OK, first check that all three files are together and their code is complete.

Pythontest_app.py
import copy
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
import app

HERE = Path(__file__).resolve().parent
DEMO = json.loads((HERE / "demo.json").read_text())


def ids(result):
    return [n["id"] for n in result["selected"]]


class Tests(unittest.TestCase):
    def test_normal(self):
        before = copy.deepcopy(DEMO)
        result = app.select(DEMO)
        self.assertEqual(ids(result), ["c", "b"])
        self.assertEqual(result["archived"], [DEMO["notes"][0]])
        self.assertEqual(DEMO, before)

    def test_ties_empty(self):
        data = copy.deepcopy(DEMO)
        for n in data["notes"]:
            n.update(priority=5, updated=2)
        self.assertEqual(ids(app.select(data)), ["a", "b"])
        self.assertEqual(app.select({"capacity": 1, "notes": []})["selected"], [])

    def test_invalid(self):
        for key, value in [("id", "../a"), ("id", "a"*65), ("text", " "),
                           ("text", "a"*501), ("priority", True), ("priority", 101),
                           ("updated", False), ("updated", -1), ("extra", 1)]:
            data = copy.deepcopy(DEMO)
            data["notes"][0][key] = value
            self.assertRaises(ValueError, app.select, data)

    def test_files(self):
        with tempfile.TemporaryDirectory() as folder:
            source, target = Path(folder)/"in", Path(folder)/"out"
            raw = json.dumps(DEMO).encode()
            source.write_bytes(raw)
            app.run(source, target)
            saved = target.read_bytes()
            self.assertRaises(FileExistsError, app.run, source, target)
            self.assertRaises(ValueError, app.run, source, source)
            self.assertEqual((source.read_bytes(), target.read_bytes()), (raw, saved))
            target.unlink()
            for raw in [b'{"capacity":1,"capacity":2,"notes":[]}', b'NaN', b'\xff',
                        b'[]', b'{', b' '* (app.LIMIT+1),
                        b'{"capacity":true,"notes":[]}',
                        json.dumps({"capacity":1,"notes":DEMO["notes"]*167}).encode()]:
                source.write_bytes(raw)
                self.assertRaises(ValueError, app.run, source, target)
                self.assertFalse(target.exists())

    def test_cli_late_note(self):
        with tempfile.TemporaryDirectory() as folder:
            source, target = Path(folder)/"in", Path(folder)/"out"
            command = [sys.executable, str(HERE/"app.py"), str(source), str(target)]
            for notes, expected in [(DEMO["notes"][:2], ["b", "a"]),
                                    (DEMO["notes"], ["c", "b"])]:
                source.write_text(json.dumps({"capacity":2,"notes":notes}))
                result = subprocess.run(command, capture_output=True, text=True)
                self.assertEqual(result.returncode, 0, result.stderr)
                self.assertEqual(ids(json.loads(target.read_text())), expected)
                target.unlink()


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

6. Add an important late note

Exercise: in a copy of demo.json, append {"id":"d","text":"Synthetic urgent fix","priority":100,"updated":4} to notes. Add a comma after the previous element and save as exercise.json. Run python3 app.py exercise.json exercise-selection.json. Expect selected=2 archived=2: selected is d,c and archived is b,a.

Limits are 1 MiB input, 500 notes, capacity 1–100, priority 0–100 and updated 0–1000000. id uses 1–64 ASCII letters, digits, underscores or hyphens. text must be nonblank and at most 500 characters. Extra fields, duplicate ids and duplicate JSON fields are rejected.

The November 28 source release changes behavior at the memory cap. We explore selection without connecting to that service. The archive is part of the same JSON file, not a separate server or backup. Keep the original input and practice only with invented notes.

Author

IT Innovations Editorial

Published:

Original source: agentmemory v0.9.34

Recommended reading

All articles