Northstar Operations Control Room.
Build one complete Python operations decision engine: validate a fleet inventory, track service health across cycles, prepare incident drafts and strictly gate a simulated change proposal. Prove the system across eight independent scenarios.
One program. Complete evidence. No unsupported fixes.
The Northstar Ops NOC needs a decision engine that turns a validated service inventory and a finite series of recorded health checks into a reliable site report. When monitoring identifies a sustained failure, the program prepares deduplicated incident drafts. In simulate mode it may also propose one approved, revision-matched change for review. The entire workflow is offline: no real probes, API tickets, mail, service restarts or infrastructure modifications.
Implement run_control_room(csv_text, cycles, settings, approval, previous, seen) as a pure function. Do not perform network calls, file writes, shell commands, actual ticket updates, scheduling or printing within the function.
Validate settings as exactly site, mode, fail_after and recover_after. Site is a nonempty string (normalized uppercase); mode is plan or simulate. Thresholds are actual integers (not bools): fail_after 2–4, recover_after 1–3. seen must be a set of lowercase nonempty incident-key strings. On invalid settings or seen, block with reason config before processing any data.
Parse csv_text with csv.DictReader; require exactly the unique headers host, site, service, revision in any order. All row values must be nonempty strings. Normalize host/site uppercase and service lowercase; service is web or backup. Reject malformed headers/rows as csv; duplicates of (site,host), ignoring case and whitespace, as duplicate.
Select inventory rows from settings.site. cycles must be a list of 1–8 dictionaries (even for a zero-device site). Each cycle must contain exactly one state for every selected-site host, matched case-insensitively after trimming; allowed states are healthy, failed and unknown. Reject wrong containers, repeated normalized host keys and invalid state values as observations; missing or extra host coverage as coverage. When a selected site has zero devices, one or more empty dictionaries are valid cycles; an empty cycles list is invalid.
Track each selected host across all cycles. Open an alert after fail_after consecutive failed states; while open, close it after recover_after consecutive healthy states. An unknown resets streak counters but never automatically closes an open alert. At the final cycle, classify each host into exactly one sorted list: alerts, recovered, watch, unknown, healthy. An open alert takes priority; otherwise final unknown is unknown, final failed below threshold is watch, a host that recovered from an earlier alert is recovered, and remaining hosts are healthy.
For every final open alert not already present in seen, return one sorted ticket draft containing key=site:host:service (lowercase), target=normalized hostname and summary='SERVICE check requires review' with uppercase service. This is only a draft: no real ticket is created. Do not mutate seen or earlier reports.
In simulate mode, approval must be a dictionary with exactly id, site, target, action, expected_revision, approved, window_open. Require nonblank strings, actual True booleans, a matching normalized site, a known selected-site target, and the exact approved action 'review-service-restart'; otherwise return approval. If the approved target is currently alerting, compare its captured inventory revision with expected_revision; a mismatch returns stale. On a match, propose {change_id:ID,target:HOST,action:'review-service-restart',state:'ready-for-review'}. In plan mode approval is ignored and change_plans is empty. A proposal never means execution or verified recovery.
On every failure return exactly {'ok':False,'reason':CODE,'previous':previous}, with CODE one of config, csv, duplicate, observations, coverage, approval, stale. On success return exactly {'ok':True,'mode':MODE,'report':{'site':SITE,'total':N,'alerts':[...],'recovered':[...],'watch':[...],'unknown':[...],'healthy':[...]},'ticket_drafts':[...],'change_plans':[...],'previous':previous}. All lists are deterministically sorted, and all input objects remain unchanged.
Demonstrate the difficult cases, not just the happy path.
Each case changes the input data or a safety gate. A sample output alone is not enough: the implementation must generalize across all eight groups.
01 · Complete fleet and sustained incident
All hosts observed across multiple cycles; one service alerts and a healthy service remains correctly classified.
02 · Watch vs. unknown evidence
An insufficient failure streak remains a watch finding, while the last unknown reading is not treated as healthy.
03 · Hysteresis, recovery and open alerts
Consecutive healthy samples recover an incident; unknown breaks a streak but does not silently close an open alert.
04 · CSV schema, duplicate, empty site
Malformed CSV and duplicate identities fail; a well-formed zero-device site remains a valid empty result.
05 · Incomplete or ambiguous cycles
Missing, extra or repeated case-insensitive cycle targets block rather than publish partial evidence.
06 · Approval and site boundaries
Simulated change proposals need an exact operation, matching site/target and an open authorized window; plan mode always remains read-only.
07 · Stale change request
An approved change with an unexpected revision blocks without issuing a speculative proposal.
08 · Stable incident keys and immutable evidence
Repeated incidents do not create new drafts; all inputs and previous verified output survive failures.
Write the integrated engine and check all eight scenarios.
Work from the acceptance contract, not the displayed example's output. Build validation helpers, state transitions and deterministic report assembly. Use Run to inspect your code and Check to execute extra fictional cases.
First implement blocked-result and input-validation paths. Then classify monitoring cycles, build ticket drafts and finally add the approval/revision gate. The 16,000-character limit includes the scenario verifier, so keep your own implementation focused. No live connectors or credentials are involved.
Write it. Run it. Understand it.
Independently build a full offline operations control room: inventory coverage, monitoring state, stable incident drafts, exact approval and safe remediation planning across eight scenarios.
Northstar Operations Control Room — Integrated Final Capstone
Build one integrated run_control_room(csv_text, cycles, settings, approval, previous, seen) that safely processes the entire fictional Northstar Ops site. Follow the eight-part acceptance contract in the Lesson 06 capstone brief. Validate the full CSV and each cycle, apply consecutive failure/recovery thresholds, create only unseen stable incident drafts, and propose at most one explicitly approved, revision-matched simulated change. Return a complete deterministic report or an exact blocked reason preserving previous. No network access or actual ticket/configuration changes. Eight independent scenario groups test the same implementation against modified input and failure cases.
CONTROL ROOM READY
8 scenario groups checkedTry solving it before asking for help. Hints never show a completed program.
Your printed output and errors will appear here.
Run the code, then step through the executed lines to watch variable values change.
Turn the control room into a multi-file offline NOC simulator
The browser checks the core decision engine. The optional local project expands it into a realistic maintainable application with mock adapters and documentation, while keeping every action fictional and offline. Below you can copy nine ready-to-organize offline starter files, including a deliberately unfinished engine and 16 unit-test examples. The tests are designed to fail until you write your own implementation.
inventory.csv — fictional branch devices and captured revisions
cycles.json — finite health snapshots, including a sustained failure and recovery
settings.json — site, plan/simulate mode and alert thresholds
approval.json — fake change control data for the one authorized target
control_room.py — your own implementation of the capstone function
adapters.py — fake ticket/recovery adapters that return canned API and verification results
run_control_room.py — CLI entry point that loads fixtures and prints a deterministic report
test_control_room.py — 16 independent unittest scenarios, initially failing until you implement the engine
README.md — usage, failure modes, approval boundaries and limitations
Copyable starter files: Expand each filename and copy its exact contents into your own local folder. The implementation is intentionally incomplete; its tests should fail until you finish the capstone. This mirrors the existing Applied Python final project handoff.
01inventory.csvFictional device inventory
host,site,service,revision
APP-01,HQ,web,r7
DB-01,HQ,backup,b3
EDGE-01,REMOTE,web,v1
02cycles.jsonRecorded monitoring observations
[
{
"APP-01": "failed",
"DB-01": "healthy"
},
{
"APP-01": "failed",
"DB-01": "healthy"
}
]
03settings.jsonSafe plan-mode policy
{
"site": "HQ",
"mode": "plan",
"fail_after": 2,
"recover_after": 2
}
04approval.jsonFictional operation-scoped approval
{
"id": "CHG-004",
"site": "HQ",
"target": "APP-01",
"action": "review-service-restart",
"expected_revision": "r7",
"approved": true,
"window_open": true
}
05control_room.pyYour independent engine — not implemented yet
"""Northstar Ops: independent offline capstone engine (Python 3.10+)."""
import csv
from io import StringIO
def run_control_room(csv_text, cycles, settings, approval, previous, seen):
"""Implement the complete contract from JoeLearns Lesson 06.
Return exactly {'ok': False, 'reason': CODE, 'previous': previous}
on blocked work. On success return the exact report, ticket_drafts,
change_plans, mode and previous fields. Never mutate inputs.
No network calls, production access, filesystem writes or mail.
"""
# 1. Validate settings/seen before CSV.
# 2. Validate unique inventory hosts and complete per-cycle coverage.
# 3. Apply consecutive failure and healthy recovery thresholds.
# 4. Build incident drafts only for unseen stable keys.
# 5. In simulate mode require an approved, revision-matched,
# action-scoped 'review-service-restart' proposal.
# 6. Report all hosts or block without replacing previous.
raise NotImplementedError("Implement run_control_room from Lesson 06")
06adapters.pyOffline ticket, change and verification fixtures
"""Offline-only fake response adapters; these never contact a service."""
def fake_ticket_response(outcome):
"""Return a canned response; no HTTP request or ticket write occurs."""
if outcome == "created":
return {"status": 201, "json": {"id": "SIM-INC-001", "state": "open"}}
if outcome == "queued":
return {"status": 202, "json": {"job_id": "SIM-JOB-002"}}
if outcome == "forbidden":
return {"status": 403, "json": {"error": "not-authorized"}}
if outcome == "timeout":
raise TimeoutError("fictional ticket write outcome is unknown")
return {"status": 400, "json": {"error": "bad-fixture"}}
def fake_change_response(outcome):
"""Return a simulated decision, never execute a change."""
if outcome == "accepted":
return {"state": "accepted", "operation_id": "SIM-CHG-003"}
if outcome == "conflict":
return {"state": "rejected", "reason": "revision-conflict"}
if outcome == "unknown":
return {"state": "unknown", "reason": "response-timeout"}
return {"state": "not-started"}
def fake_verification(config="pass", process="pass", application="unknown"):
"""Independent fictional checks; unknown is never auto-resolved."""
return {"config": config, "process": process, "application": application}
07run_control_room.pyOffline command-line entry point
"""Read fictional local fixtures and print a deterministic capstone result."""
import argparse
import json
import sys
from pathlib import Path
from copy import deepcopy
from control_room import run_control_room
ROOT = Path(__file__).resolve().parent
def run(argv=None):
parser = argparse.ArgumentParser(description="Offline Northstar Ops decision engine")
parser.add_argument("--scenario", choices=("alert","missing-evidence","stale-approval","approved-change"), default="alert")
parser.add_argument("--simulate", action="store_true", help="Use only the fictional scoped approval; never execute a change")
args = parser.parse_args(argv)
if args.scenario in ("stale-approval", "approved-change") and not args.simulate:
parser.error("This scenario requires --simulate")
csv_text = (ROOT / "inventory.csv").read_text(encoding="utf-8")
cycles = json.loads((ROOT / "cycles.json").read_text(encoding="utf-8"))
settings = json.loads((ROOT / "settings.json").read_text(encoding="utf-8"))
approval = json.loads((ROOT / "approval.json").read_text(encoding="utf-8"))
previous = {"report_id": "last-verified-009"}
seen = set()
settings["mode"] = "simulate" if args.simulate else "plan"
if args.scenario == "missing-evidence":
cycles[-1].pop("DB-01") # Deliberately incomplete fictional sample
if args.scenario == "stale-approval":
approval["expected_revision"] = "r6" # Does not match inventory r7
try:
result = run_control_room(csv_text, cycles, settings,
deepcopy(approval) if args.simulate else None,
previous, seen)
except NotImplementedError:
print("Implement run_control_room() before running the CLI.", file=sys.stderr)
return 2
print(json.dumps(result, indent=2, sort_keys=True))
return 0 if isinstance(result, dict) and result.get("ok") is True else 1
if __name__ == "__main__":
sys.exit(run())
08test_control_room.py16 independent unittest examples (fail until implemented)
"""Independent offline tests. They are EXPECTED to fail until you implement the engine."""
import unittest
from copy import deepcopy
from control_room import run_control_room
CSV = "host,site,service,revision\nAPP-01,HQ,web,r7\nDB-01,HQ,backup,b3\n"
BASE = {"site": "HQ", "mode": "plan", "fail_after": 2, "recover_after": 2}
APPROVAL = {
"id":"CHG-004", "site":"HQ", "target":"APP-01",
"action":"review-service-restart", "expected_revision":"r7",
"approved":True, "window_open":True
}
def cycles(*states):
return [{"APP-01": a, "DB-01": b} for a, b in states]
class ControlRoomTests(unittest.TestCase):
def run_case(self, csv_text=CSV, snapshots=None, settings=None, approval=None, seen=None):
if snapshots is None:
snapshots = cycles(("failed","healthy"),("failed","healthy"))
return run_control_room(csv_text, deepcopy(snapshots),
deepcopy(settings if settings is not None else BASE),
deepcopy(approval), {"report_id":"old-good"},
set(seen or set()))
def test_sustained_alert(self):
r=self.run_case()
self.assertTrue(r["ok"])
self.assertEqual(r["report"]["alerts"],["APP-01"])
self.assertEqual(len(r["ticket_drafts"]),1)
def test_healthy_fleet(self):
r=self.run_case(snapshots=cycles(("healthy","healthy")))
self.assertEqual(r["report"]["healthy"],["APP-01","DB-01"])
def test_watch_before_threshold(self):
r=self.run_case(settings={**BASE,"fail_after":3})
self.assertEqual(r["report"]["watch"],["APP-01"])
def test_unknown_not_healthy(self):
r=self.run_case(snapshots=cycles(("unknown","healthy")))
self.assertEqual(r["report"]["unknown"],["APP-01"])
def test_verified_recovery(self):
r=self.run_case(snapshots=cycles(("failed","healthy"),("failed","healthy"),
("healthy","healthy"),("healthy","healthy")))
self.assertEqual(r["report"]["recovered"],["APP-01"])
def test_unknown_preserves_open_alert(self):
r=self.run_case(snapshots=cycles(("failed","healthy"),("failed","healthy"),
("unknown","healthy"),("healthy","healthy")))
self.assertEqual(r["report"]["alerts"],["APP-01"])
def test_missing_csv_column(self):
r=self.run_case(csv_text="host,site,service\nAPP-01,HQ,web\n")
self.assertEqual((r["ok"],r["reason"]),(False,"csv"))
def test_duplicate_inventory(self):
r=self.run_case(csv_text=CSV+"app-01,HQ,web,r8\n")
self.assertEqual((r["ok"],r["reason"]),(False,"duplicate"))
def test_incomplete_observation_cycle(self):
r=self.run_case(snapshots=[{"APP-01":"failed"}])
self.assertEqual((r["ok"],r["reason"]),(False,"coverage"))
def test_duplicate_case_insensitive_cycle_key(self):
r=self.run_case(snapshots=[{"APP-01":"failed"," app-01 ":"healthy","DB-01":"healthy"}])
self.assertEqual((r["ok"],r["reason"]),(False,"observations"))
def test_approval_denied(self):
r=self.run_case(settings={**BASE,"mode":"simulate"},approval={**APPROVAL,"approved":False})
self.assertEqual((r["ok"],r["reason"]),(False,"approval"))
def test_action_is_scoped(self):
r=self.run_case(settings={**BASE,"mode":"simulate"},approval={**APPROVAL,"action":"force-restart"})
self.assertEqual((r["ok"],r["reason"]),(False,"approval"))
def test_stale_revision(self):
r=self.run_case(settings={**BASE,"mode":"simulate"},approval={**APPROVAL,"expected_revision":"r6"})
self.assertEqual((r["ok"],r["reason"]),(False,"stale"))
def test_valid_approval_is_only_a_proposal(self):
r=self.run_case(settings={**BASE,"mode":"simulate"},approval=APPROVAL)
self.assertEqual(r["change_plans"],[{"change_id":"CHG-004","target":"APP-01",
"action":"review-service-restart","state":"ready-for-review"}])
def test_deduplicate_seen_keys(self):
r=self.run_case(seen={"hq:app-01:web"})
self.assertEqual(r["ticket_drafts"],[])
def test_empty_site_with_empty_snapshot(self):
r=self.run_case(csv_text="host,site,service,revision\n",
snapshots=[{}])
self.assertEqual(r["report"]["total"],0)
if __name__ == "__main__":
unittest.main()
09README.mdRunbook and change-control boundaries
# Northstar Operations Control Room — Offline Python Capstone
Build the complete six-phase JoeLearns final project independently. The supplied `control_room.py` intentionally raises `NotImplementedError`. Implement the function from the Lesson 06 acceptance contract. **No solutions or customer infrastructure access are included.**
## Requirements and boundaries
Python 3.10+ with standard library only. All hosts, incidents, approvals and results are fictional. No real network probes, credentials, API calls, email, service restarts or production changes are allowed.
The default CLI mode is `plan`, which creates read-only report and ticket **drafts**. `--simulate` enables evaluation of an injected, fictional change approval. Neither mode executes remediation.
## Run locally
```bash
python -m unittest discover -v
python run_control_room.py --scenario alert
python run_control_room.py --scenario missing-evidence
python run_control_room.py --simulate --scenario stale-approval
python run_control_room.py --simulate --scenario approved-change
```
The 16 example unit tests should fail until `run_control_room()` is implemented. After implementation, tests should validate both success and blocked cases. The CLI reports a nonzero exit code for blocked outcomes.
## Data flow
`inventory.csv` + `cycles.json` + `settings.json` (and an optional `approval.json` in simulated mode) → validation → monitoring thresholds → incident drafts → scoped change proposal → deterministic JSON handoff.
Function output is **not** proof that a remote ticket was created or that any application was restored. The fake adapters in `adapters.py` illustrate response handling only. Preserve `previous` on all blocked paths; never publish partial evidence as healthy.
## Failure codes
- `config`: invalid policy or replay key configuration
- `csv`: malformed inventory schema or rows
- `duplicate`: normalized inventory identity repeated
- `observations`: invalid cycles, repeated host keys or unsupported states
- `coverage`: missing/extra host records in a cycle
- `approval`: out-of-scope, missing or unauthorized simulated operation
- `stale`: captured target revision differs from approved expectation
## Professional handoff
Create a feature branch and meaningful commits. Include a concise summary of passing/blocked tests, assumptions, retry ambiguity, why a draft is not a ticket and which recovery checks require real-world verification. Keep logs and secrets out of the repository. This project is an instructional simulator, not a production monitoring service.
- Create a local Git feature branch. Copy the nine fictional starter files below into one folder, keeping their supplied names. Use Python 3.10+ with standard-library modules only.
- Complete the control_room.py logic from the browser contract without copying test fixtures into your implementation.
- Create fake ticket adapters that produce confirmed creation (201), accepted job (202), rejected authorization (403) and ambiguous timeout fixtures. Document why an accepted or timed-out write is not automatically a finished ticket.
- Add a fake change adapter that checks the approved action 'review-service-restart', target and expected revision before returning attempted, accepted or rejected; do not perform a real change.
- Add a post-change verification fixture with configuration, service and application pass/fail/unknown results. Keep the simulated ticket open unless recovery and ticket-update confirmation are both independently verified.
- Run the 16 supplied unittest cases and add your own tests for unknown interruptions, sustained alerts, replayed incidents, denied operations, stale revisions and fake adapter uncertainty.
- Make the CLI default to plan-only. Use a clearly named --simulate flag for mock adapters, and refuse real endpoints, credentials or network inventory files.
- Produce a short operations report with both successful and blocked examples, a reason-code table, timestamps and a safe remediation runbook. Document the maximum authorized scope and unsupported real-world behaviors.
- Commit the implementation, tests and README in reviewable steps, run the full test suite, and write a final handoff explaining which checks prove algorithm behavior versus which real-world outcomes remain untested.
python -m unittest discover -vpython run_control_room.py --scenario alertpython run_control_room.py --scenario missing-evidencepython run_control_room.py --simulate --scenario stale-approvalpython run_control_room.py --simulate --scenario approved-changeThe browser verifies only the integrated function. The multi-file CLI, mock adapters and local unit tests are independent self-guided work; they are not uploaded or automatically assessed by JoeLearns.
Can another technician trust this result?
Data and coverage integrity
Validate the entire inventory, policy and finite observation set before reporting; reject malformed or duplicated identities and missing host evidence.
Stateful monitoring decisions
Use correct failure/recovery thresholds and preserve unknown states without hiding open incidents or generating duplicate alerts.
Service-desk integration design
Construct deterministic minimal ticket drafts from open incidents, filter seen keys and never claim a remote ticket was created.
Authorization and remediation safety
Check exact approval scope, expected revision and change intent; simulate only, never apply to live infrastructure.
Recovery and trustworthy output
Preserve previous reports on all blocked paths, test repeatability, and describe why change proposals do not equal verified restoration.
Professional Git handoff
Create an independent multi-file local project, meaningful commits, test fixtures and a documented runbook with explicit limitations.
Explain what your algorithm has actually verified, why ambiguous observations block or remain unknown, how incident drafts avoid duplicates, and why even a valid simulated change plan does not mean the service was restored. Review the error codes and test coverage before treating the project as ready to hand off.
Completion: When you've finished the integrated coding assessment and reviewed your engineering handoff, use the shared Continue Your Learning Path panel below to mark the final Capstone milestone complete. The saved progress tracker will then reflect completion of the six-phase learning path. This is self-guided learning, not a proctored or accredited certification.
