Playbook drafting: auto-classify and auto-draft an ingested source document
PlaybookDrafter in engine/playbook_drafting.py builds a Playbook: a per-site, AI-generated knowledge framework. Ingested source documents (SOPs, work instructions, deviation reports) are auto-classified and drafted into structured entries end to end, with a single sign-off rather than a curation UI.
PlaybookDrafter is glue over things already built elsewhere:
ChunkingRegistry(engine/chunking.py) supplies the declared document-type category set that classification branches over.SignoffStore(engine/mandatory_human_signoff.py) is where every draft lands. This module never resolves a draft itself. It only ever submits one Pending.
1. Load and version-check the prompt assets
from pathlib import Path
from engine.prompt_assets import assert_version, load_prompt_asset
classification_asset = load_prompt_asset(Path("path/to/the/classification/prompt/asset.md"))
assert_version(classification_asset, "0.1.0")
drafting_asset = load_prompt_asset(Path("path/to/the/drafting/prompt/asset.md"))
assert_version(drafting_asset, "0.1.0")
PlaybookDrafter doesn't load or version-check either asset itself. This is the same "loading is the caller's concern" split that PlaybookAnswerer in engine/playbook_answer.py uses for its own prompt asset. Do it once at startup, not per document.
2. Build the drafter over already-constructed collaborators
from engine.chunking import ChunkingRegistry, paragraph_chunking
from engine.mandatory_human_signoff import SignoffStore
from engine.playbook_drafting import PlaybookDrafter
registry = ChunkingRegistry()
registry.register("sop", paragraph_chunking) # whatever document types this Node Type knows
signoff_store = SignoffStore()
signoff_store.ensure_schema()
drafter = PlaybookDrafter(
registry,
inference_client, # engine.inference.InferenceClient
classification_asset,
drafting_asset,
signoff_store,
activity_log, # engine.activity_log.ActivityLog
"MES", # this Node's own node_type
node_instance_id, # this Node's own instance id
)
registry isn't chunking anything here. PlaybookDrafter only reads its registered_document_types, to build the classifier's declared branch set (below).
Hand in the same registry that a real caller also chunks and embeds documents through (docs/operations/retrieval-embedding-infra.md). Classification and chunking-strategy dispatch can then never disagree about which document types exist.
3. Ingest a document
record = drafter.ingest("torque-wrench-sop", sop_text)
record.status # PendingStatus.PENDING, always
record.content["document_type"] # the classifier's own branch, e.g. "sop"
record.content["title"] # the drafted entry's title
record.content["body"] # the drafted entry's body - a rewrite, never the raw text back
ingest always returns a fresh PendingRecord. No branch discards or auto-approves a document: every ingested document becomes a draft awaiting a human's sign-off.
PlaybookDrafter takes inference_enabled: bool = True. With it false (see inference-operating-mode.md), no model call is made. Classification falls back to GENERIC_STRATEGY, and the draft body is the raw ingested text, still submitted Pending.
engine/node_main.py and engine/erp_main.py do not construct a PlaybookDrafter. The runtime ingestion path for documents is engine/document_ingestion.py (retrieval-ingestion-pipeline.md).
Auto-classification is a Gate instance, not a separate taxonomy
The document-type classifier that feeds chunking-strategy selection is a Gate instance. PlaybookDrafter._classify is that Gate, built with EvaluationMode.LLM, branches=chunking_registry.registered_document_types and fallback=GENERIC_STRATEGY (the reserved fallback name in engine/chunking.py).
A model response that doesn't match any registered document type routes to "generic" instead of raising. This is the same fail-safe dispatch that ChunkingRegistry.chunk already uses for an unregistered document type, so the two mechanisms can never disagree about what counts as unrecognized.
Drafting is a second, separate inference call
Classification decides what kind of document this is. Drafting decides what the entry says. These are two independent model calls, not one call asked to do both jobs.
The drafting call's response is validated against a fixed Title:/Body: structure (_validate_draft_format and _find_draft_lines) before it is parsed (_parse_draft). InferenceClient.call's retry loop re-prompts on a malformed response, as it does for any other validator rejection. This module does not try to salvage free-form text after the fact.
The format rules are strict on purpose:
_find_draft_linesis a plain linear scan over the response's lines, not a regex.- A regex combining adjacent
\s*/.+?/\s*quantifiers overDOTALLtext is a textbook catastrophic-backtracking shape. - A degenerate response would hang the whole classification or drafting call. A local model's own repetition-collapse failure mode is one such response: long runs of near-blank lines with no genuine
"Body:"line to terminate the search. - The line scan is O(number of lines), and no backtracking is possible.
- A regex combining adjacent
"Title:"must open the very first line of the stripped response. It is not enough for the response to contain a line that starts with it somewhere.- Tolerating a conversational preamble, by scanning forward for the first
"Title:"-prefixed line, is vulnerable to a decoy. A model that echoes the expected format as an example before its real answer ("entries use this format: Title: <field> Body: <field> ... Here is the actual entry: Title: ... Body: ...") would have the example parsed as the real draft. The genuine entry would be silently swallowed into an oversized, garbled body. - The licensed drafting prompt asset already instructs "respond in exactly this format, with no other text", so a compliant model never needs preamble tolerance. A model that doesn't comply is retried, and eventually raises
PlaybookDraftingError. That is better than risking a plausible-looking but wrong parse.
- Tolerating a conversational preamble, by scanning forward for the first
- The title is confined to that one first line. A regex
.+?capture underDOTALLcould span into following lines and silently produce a multi-line title, which the line scan can't do. "Body:"must open its own line. A"...Body:"glued onto another word doesn't count.- An empty body is rejected. That means nothing but whitespace after
"Body:"and no further lines. A complete entry needs both a title and a body. A response truncated right after the"Body:"marker (for example by hitting an output-token budget) is retried instead of being accepted as a thin, empty-bodied draft.
A genuine call failure raises, it never becomes a silent bad outcome
InferenceClient.call never raises on a model or transport failure. As its own docstring puts it, retries are exhausted and reported through CallOutcome.success instead.
Both _classify_call and _draft therefore route their outcome through engine.inference.raise_if_failed. This is a small shared helper, also used by the synthesis call in engine/playbook_answer.py. It raises a caller-supplied exception type when every retry attempt failed, instead of consuming outcome.text regardless. Here that type is PlaybookDraftingError (engine.exceptions.PlaybookDraftingError).
- Classification: an exhausted retry budget (for example, the endpoint unreachable throughout) is never routed through the Gate's unrecognized-category fallback. That fallback is for a real, accepted response that doesn't name a known document type, not for a call that never produced one. Without this check, an infrastructure outage would silently record as an ordinary
"generic"classification, indistinguishable afterwards from a real one. - Drafting: an exhausted retry budget (the model never producing a validator-accepted
Title:/Body:response) is never parsed anyway._parse_draftis only ever called on a response that_validate_draft_formatalready accepted.
PlaybookDraftingError propagates out of ingest() through the Task Execution logging mechanism below. That mechanism logs it as a terminal error:-prefixed outcome before re-raising, the same "a genuine bug still gets one terminal, logged entry" guarantee that every other Task-shaped consumer in this codebase gets. A caller needs no try/except of its own around ingest() to keep the Activity Log complete.
Activity Log wiring
Every ingest() call writes exactly one ActivityLogEntry, through the shared Activity Log wiring (docs/operations/wiring-task-execution-to-activity-log.md). PlaybookDrafter doesn't write it directly. It wraps its classify, draft and submit logic as a trivial one-step Prompt Chaining Task, the same composition that engine/playbook_answer.py and engine/identity_resolution.py use.
triggeris always"sop_document_ingested"andtask_typeis always"ingestion-time classification"(engine.playbook_drafting.TRIGGERandTASK_TYPE). The trigger means "a new document arrives".outcomeis the classifieddocument_type: what actually happened during this run, the same way theoutcomeinengine/identity_resolution.pyreports which branch an observation took.reference_idscarriespending_signoff_id(the submittedPendingRecord's own id) andsource_document_id. Query which documents drafted a given Pending record withactivity_log.query(reference_id=...).- A model-written draft adds
prompt_nameandprompt_version(the drafting prompt), which are also stored in the record's content. The fallback draft carries neither.
Pitfalls
PlaybookDrafternever resolves a draft. That is entirelySignoffStore's job (docs/operations/mandatory-human-sign-off-mechanism.md).record_typeis always"playbook_entry". Approving, rejecting, or editing and resubmitting a draft happens throughSignoffStoredirectly, not through this module.- A document type the classifier invents that isn't in
chunking_registry's registered set always falls back to"generic"and never raises, but only when the call itself succeeded.- If a caller expects every document to classify precisely, that is a prompt-tuning problem (the licensed
playbook_document_classification.mdasset). It is not something to catch by checkingrecord.content["document_type"] == "generic"afterwards as an error case."generic"is a legitimate, intended outcome for a document that doesn't match anything more specific. - A call that never succeeded at all (the endpoint unreachable, every retry rejected) is a different case. It raises
PlaybookDraftingErrorand never reaches the fallback.
- If a caller expects every document to classify precisely, that is a prompt-tuning problem (the licensed
ingest()can raisePlaybookDraftingError. A caller processing a batch of documents should catch it per document if one bad or unreachable call shouldn't abort the rest. This module makes no batching decision of its own, the same "one batch failing doesn't stop the rest" policy split thatInferenceClient.run_planleaves to its caller.chunking_registryis a caller-supplied, already-constructed collaborator, and this module registers no strategies of its own. A Node Type's document types are its own concern (the chunking registration indocs/operations/retrieval-embedding-infra.md), not somethingPlaybookDrafterdecides.activity_log,node_typeandnode_instance_idare required, not optional. There is no logging-disabled mode, the same requirementPlaybookAnswerercarries.
Release: v0.11.0