Files

150 lines
5.4 KiB
Python

"""A Customer case on disk: its intent and the history of that intent.
deliverables/cases/<customer_case>/
intent/
001.md, 002.md, ... each statement of what the customer wants, as given
history.json every statement in order, the Execution it started
and how that Execution ended
executions/<execution_id>/ what was generated for one statement
The intent is recorded when an Execution starts, so a request is on record even if
nothing was delivered for it. history.json is the index of the case.
"""
from __future__ import annotations
import hashlib
import json
from collections.abc import Mapping
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
import yaml
from execution_engine.states.execution_state import case_dir
INTENT_DIR = "intent"
HISTORY_FILENAME = "history.json"
IN_PROGRESS = "in_progress"
SCOPE_SUPPLIED = ".scope.yaml"
SCOPE_COMPLETED = ".scope.completed.yaml"
SOURCES_DIR = ".sources" # a folder: what a spec was digested from
def intent_dir(output_root: Path, customer_case: str) -> Path:
return case_dir(output_root, customer_case) / INTENT_DIR
def read_history(output_root: Path, customer_case: str) -> dict[str, Any]:
"""The case's intent history; empty when the case has none yet."""
path = intent_dir(output_root, customer_case) / HISTORY_FILENAME
if path.is_file():
try:
history = json.loads(path.read_text(encoding="utf-8"))
if isinstance(history, dict) and isinstance(history.get("intents"), list):
return history
except ValueError:
pass
return {"customer_case": customer_case, "intents": []}
def record_intent(
output_root: Path,
customer_case: str,
*,
execution_id: str,
session_id: str,
workflow_request: str,
baseline: str | None = None,
scope_supplied: str | None = None,
scope_completed: Mapping[str, Any] | None = None,
sources: Mapping[str, str] | None = None,
) -> int:
"""Record a new statement of the customer's intent and return its version.
`baseline` is the Execution a Change request starts from; with it the history
shows the case's line of versions.
"""
folder = intent_dir(output_root, customer_case)
folder.mkdir(parents=True, exist_ok=True)
history = read_history(output_root, customer_case)
version = max((item["version"] for item in history["intents"]), default=0) + 1
recorded_at = datetime.now(UTC).isoformat(timespec="seconds")
statement = f"{version:03d}.md"
(folder / statement).write_text(
f"# Intent {version}: {customer_case}\n\n"
f"- Recorded: {recorded_at}\n"
f"- Execution: `{execution_id}`\n"
+ (f"- Changes: `{baseline}`\n" if baseline else "")
+ "\n"
f"## What the customer wants\n\n{workflow_request.strip()}\n",
encoding="utf-8",
)
scope_files = None
if scope_completed is not None:
# The spec as supplied, unaltered, and the completed copy beside it.
scope_files = {"completed": f"{INTENT_DIR}/{version:03d}{SCOPE_COMPLETED}"}
(folder / f"{version:03d}{SCOPE_COMPLETED}").write_text(
yaml.safe_dump(dict(scope_completed), sort_keys=False, allow_unicode=True),
encoding="utf-8",
)
if scope_supplied:
scope_files["supplied"] = f"{INTENT_DIR}/{version:03d}{SCOPE_SUPPLIED}"
(folder / f"{version:03d}{SCOPE_SUPPLIED}").write_text(
scope_supplied, encoding="utf-8"
)
source_files = None
if sources:
# What the spec was digested from, as supplied: never altered.
kept = folder / f"{version:03d}{SOURCES_DIR}"
source_files = {}
for name, content in sources.items():
path = kept / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8")
source_files[name] = hashlib.sha256(content.encode("utf-8")).hexdigest()
history["intents"].append(
{
"version": version,
"recorded_at": recorded_at,
"statement": f"{INTENT_DIR}/{statement}",
"workflow_request": workflow_request,
"execution_id": execution_id,
"session_id": session_id,
"status": IN_PROGRESS,
"execution": None,
"baseline": baseline,
"scope": scope_files,
# The sources the spec was digested from, each with its hash.
"sources": source_files,
}
)
_write_history(folder, history)
return version
def close_intent(
output_root: Path,
customer_case: str,
*,
execution_id: str,
status: str,
has_files: bool,
) -> None:
"""Record how the Execution started by an intent ended, and where its files are."""
history = read_history(output_root, customer_case)
for item in history["intents"]:
if item.get("execution_id") == execution_id:
item["status"] = status
item["execution"] = f"executions/{execution_id}" if has_files else None
_write_history(intent_dir(output_root, customer_case), history)
return
def _write_history(folder: Path, history: dict[str, Any]) -> None:
folder.mkdir(parents=True, exist_ok=True)
(folder / HISTORY_FILENAME).write_text(
json.dumps(history, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
)