API Reference¶
The TNGS REST API is served at port 8000. Interactive Swagger UI is available at /docs when the server is running.
Base URL: http://localhost:8000
Authentication: Bearer token (header: Authorization: Bearer <token>)
Content-Type: application/json
Health¶
GET /v1/health/live¶
Liveness probe. Always returns 200.
Response 200:
GET /v1/health/ready¶
Readiness probe. Returns 200 when Neo4j is reachable, 503 otherwise.
Response 200:
Response 503:
Ingest¶
POST /v1/notes/import¶
Ingest raw text, Markdown, or pre-structured JSON. Runs the full pipeline and persists the narrative graph.
Request body:
{
"title": "My Story",
"text": "Alice walked slowly. She stopped.\n\nBob arrived at last.",
"narrative_id": "my-id-001",
"source_ref": "notebook-2026-04.txt",
"format": "text"
}
| Field | Type | Required | Description |
|---|---|---|---|
title |
string | ✓ | Narrative title |
text |
string | Raw prose to ingest | |
narrative_id |
string | Generated if absent | |
source_ref |
string | Provenance reference | |
format |
string | text (default), markdown, json, csv |
Response 201:
{
"narrative_id": "my-id-001",
"scene_count": 2,
"atom_count": 3,
"event_count": 2,
"character_count": 2,
"pattern_count": 0,
"flagged_count": 0
}
Narratives¶
GET /v1/narratives/{id}¶
Retrieve a narrative's current state.
Path: narrative_id — the narrative's unique ID
Response 200:
{
"id": "my-id-001",
"title": "My Story",
"status": "patterned",
"source_ref": "notebook-2026-04.txt",
"scene_count": 2,
"created_at": "2026-04-26T10:00:00"
}
Response 404: Narrative not found.
DELETE /v1/narratives/{id}¶
Archive a narrative (sets status to archived).
Response 204: No content.
Response 404: Narrative not found.
Patterns¶
POST /v1/patterns¶
Register a new pattern template.
Request body:
{
"id": "pattern.pursuit",
"name": "Pursuit",
"family": "pursuit",
"description": "A chase or quest structure."
}
Response 201:
GET /v1/patterns¶
List all registered patterns, optionally filtered by family.
Query params:
- family (optional) — filter by pattern family string
Response 200: Array of pattern records.
GET /v1/patterns/{id}/instances¶
List concrete pattern instances in a narrative.
Path: pattern_id
Query: narrative_id (required)
Response 200: Array of instance records.
Response 404: Pattern template not found.
Transforms¶
POST /v1/transforms/apply¶
Apply a transformation axis to a scene.
Request body:
{
"scene_id": "scene-abc",
"axis": "pov",
"parameters": {
"focalizer": "char-alice",
"distance": "internal",
"reliability": "unreliable"
},
"operator": "matt"
}
Axis parameter reference:
| Axis | Required parameters |
|---|---|
pov |
focalizer (string) |
mood |
label (string); optional: valence [-1,1], arousal [0,1] |
genre |
name (string); optional: conventions (string list) |
chronotope |
time_mode (cyclical/linear/suspended/compressed), space_mode (bounded/open/liminal/utopian) |
reliability |
reliability (reliable/unreliable/ambiguous) |
code_overlay |
atom_id (string), code (hermeneutic/proairetic/semic/symbolic/cultural) |
Response 200:
{
"transform_id": "uuid",
"scene_id": "scene-abc",
"axis": "pov",
"produced_id": "pov-uuid",
"status": "accepted"
}
Response 400: Invalid axis parameters.
Response 422: Invalid request body schema.
GET /v1/transforms/{id}¶
Retrieve a transform audit record.
Response 200:
{
"id": "transform-uuid",
"scene_id": "scene-abc",
"produced_type": ["Perspective"],
"produced_id": "pov-uuid"
}
Render¶
POST /v1/render/{id}¶
Render the current graph state to an output format.
Path: narrative_id
Request body:
type value |
Output | Content-Type |
|---|---|---|
prose |
Markdown prose draft | text/markdown |
diff |
Transformation diff JSON | application/json |
json |
Full graph state JSON | application/json |
cypher |
Replayable MERGE script | text/x-cypher |
markdown |
Structured summary | text/markdown |
graphml |
yEd-compatible GraphML with tension-colored edges | application/xml |
GraphML / yEd
The graphml render type produces a yEd-compatible GraphML file. Edges
are colored on a six-stop gradient (grey → blue → gold → orange → crimson →
dark-red) by narrative tension score. See GraphML Export
for full details.
Response 200:
{
"narrative_id": "my-id-001",
"render_type": "prose",
"content": "# My Story\n\n## Scene 1\n...",
"content_type": "text/markdown"
}
Response 404: Narrative not found.
Response 422: Invalid render type.
Module Reference¶
tng.domain.models
¶
Domain model classes for the Transformable Narrative Graph System.
Every class in this module is a pure Pydantic BaseModel. No infrastructure imports (Neo4j driver, FastAPI, etc.) are allowed here. This keeps the domain layer independently testable and decoupled from persistence concerns.
The class hierarchy mirrors the graph schema defined in SRS §4: Narrative → Scene → Atom / Event / PatternInstance Scene → Perspective / MoodState / GenreProfile / Chronotope Atom → CodeTag Transform → (audit trail linking to any scene-level state node)
Atom
¶
Bases: BaseModel
The minimal expressive narrative unit — a single clause or sentence.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Unique identifier. |
text |
str
|
Raw text of the atom. |
kind |
AtomKind
|
Functional classification. |
surface_order |
int
|
Position within its parent Scene (0-based). |
confidence |
float
|
Segmentation / classification confidence in [0.0, 1.0]. |
code_tags |
list[CodeTag]
|
Barthesian code labels attached to this atom. |
needs_review |
bool
|
True when confidence is below the configured threshold. |
Source code in src/tng/domain/models.py
AtomRevision
¶
Bases: BaseModel
A revised version of an Atom's text, preserving the full revision chain.
The graph schema mirrors the transform audit pattern:
(Atom)-[:CURRENT_REVISION]->(AtomRevision) points to the latest;
(Atom)-[:HAS_REVISION]->(AtomRevision) retains all versions;
(AtomRevision)-[:SUPERSEDES]->(AtomRevision) links new → old.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Unique identifier. |
atom_id |
str
|
ID of the parent Atom. |
text |
str
|
Revised prose text. |
revised_at |
datetime
|
UTC timestamp of the revision. |
operator |
str
|
Identifier of the user or system that issued the revision. |
reason |
str
|
Optional human-readable reason for the change. |
Source code in src/tng/domain/models.py
Character
¶
Bases: BaseModel
A participant or focalizer in the narrative.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Unique identifier. |
name |
str
|
Character name as it appears in the source text. |
role |
str
|
Narrative role (e.g. "protagonist", "antagonist", "witness"). |
Source code in src/tng/domain/models.py
Chronotope
¶
Bases: BaseModel
Bakhtinian time-space frame for a Scene.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Unique identifier. |
time_mode |
str
|
One of: cyclical, linear, suspended, compressed. |
space_mode |
str
|
One of: bounded, open, liminal, utopian. |
Source code in src/tng/domain/models.py
CodeTag
¶
Bases: BaseModel
A Barthesian code label attached to an Atom.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Unique identifier for this tag. |
code |
BarthesCode
|
The Barthesian code category. |
label |
str
|
Human-readable annotation label. |
Source code in src/tng/domain/models.py
Event
¶
Bases: BaseModel
An action-bearing narrative unit extracted from an Atom.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Unique identifier. |
verb |
str
|
Lemmatised main verb of the event clause. |
tense |
str
|
Grammatical tense string (e.g. "past", "present"). |
aspect |
str
|
Grammatical aspect string (e.g. "simple", "progressive"). |
confidence |
float
|
Extraction confidence in [0.0, 1.0]. |
participants |
list[Character]
|
Characters who take part in this event. |
needs_review |
bool
|
True when confidence is below the configured threshold. |
Source code in src/tng/domain/models.py
EventRelation
¶
Bases: BaseModel
A directed relationship between two Event nodes.
Captures explicit causal and temporal connections that are stored as first-class relationships in the graph. These are fetched separately from the event nodes themselves because they are inter-event edges rather than containment relationships.
Attributes:
| Name | Type | Description |
|---|---|---|
source_id |
str
|
ID of the originating Event. |
target_id |
str
|
ID of the destination Event. |
relation_type |
str
|
One of |
Source code in src/tng/domain/models.py
GenreProfile
¶
Bases: BaseModel
Genre encoding for a Scene or Narrative.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Unique identifier. |
name |
str
|
Genre name (e.g. "gothic", "road novel"). |
conventions |
list[str]
|
JSON-serialisable list of constraint strings describing genre-specific narrative obligations. |
Source code in src/tng/domain/models.py
GraphState
¶
Bases: BaseModel
A complete, self-contained snapshot of one narrative's graph state.
Passed to renderer implementations so they never issue Cypher directly.
Attributes:
| Name | Type | Description |
|---|---|---|
narrative |
Narrative
|
The root Narrative with all nested scenes and atoms. |
transforms |
list[Transform]
|
Ordered transform history (oldest first). |
characters |
list[Character]
|
All Characters referenced in this narrative. |
event_relations |
list[EventRelation]
|
Explicit inter-event relationships (CAUSES, ENABLES, PREVENTS, PRECEDES) fetched from the graph. Used by the GraphML renderer to draw and score causal/temporal edges. |
Source code in src/tng/domain/models.py
MoodState
¶
Bases: BaseModel
Affective/tonal state for a Scene.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Unique identifier. |
label |
str
|
Free-text mood label (e.g. "melancholic", "tense"). |
valence |
float
|
Sentiment polarity in [-1.0, 1.0]; negative = negative affect. |
arousal |
float
|
Activation level in [0.0, 1.0]; high = energetic. |
Source code in src/tng/domain/models.py
Narrative
¶
Bases: BaseModel
Top-level work or draft — the root node of a TNGS narrative graph.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Unique identifier. |
title |
str
|
Working title of the narrative. |
status |
NarrativeStatus
|
Life-cycle state. |
source_ref |
str
|
Optional reference to the originating source document. |
scenes |
list[Scene]
|
Ordered list of Scenes. |
created_at |
datetime
|
UTC creation timestamp. |
Source code in src/tng/domain/models.py
Pattern
¶
Bases: BaseModel
A reusable narrative template stored in the graph library.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Unique identifier (e.g. "pattern.gift_exchange"). |
name |
str
|
Human-readable name. |
family |
str
|
Family tag (see PatternFamily enum). |
description |
str
|
Prose description of the pattern's narrative function. |
Source code in src/tng/domain/models.py
PatternInstance
¶
Bases: BaseModel
Concrete realisation of a Pattern in a specific Scene.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Unique identifier. |
slot |
str
|
Structural slot label (e.g. "scene-core", "opening"). |
confidence |
float
|
Match confidence in [0.0, 1.0]. |
template |
Pattern | None
|
The Pattern this instance realises. |
realized_atoms |
Atom IDs that ground this instance. |
|
realized_events |
Event IDs that ground this instance. |
|
needs_review |
bool
|
True when confidence is below the configured threshold. |
Source code in src/tng/domain/models.py
Perspective
¶
Bases: BaseModel
Focalization state for a Scene at a point in transformation history.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Unique identifier. |
focalizer |
str
|
ID of the Character through whose perspective events are filtered. |
distance |
FocalizationDistance
|
Genettean focalization distance. |
reliability |
ReliabilityLevel
|
Narrator/focalizer credibility rating. |
Source code in src/tng/domain/models.py
Scene
¶
Bases: BaseModel
A bounded narrative segment within a Narrative.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Unique identifier. |
sequence |
int
|
Ordinal position within the parent Narrative (1-based). |
summary |
str
|
Optional human-readable summary of the scene. |
atoms |
list[Atom]
|
Ordered list of Atoms in this scene. |
events |
list[Event]
|
Events extracted from this scene. |
pattern_instances |
list[PatternInstance]
|
Pattern instances detected in this scene. |
current_perspective |
Perspective | None
|
Active Perspective node (if any). |
current_mood |
MoodState | None
|
Active MoodState node (if any). |
current_genre |
GenreProfile | None
|
Active GenreProfile node (if any). |
chronotope |
Chronotope | None
|
Active Chronotope node (if any). |
Source code in src/tng/domain/models.py
Transform
¶
Bases: BaseModel
Audit record for a single transformation operation.
The Transform node is the spine of the transformation lineage graph.
It links the scene it modified (APPLIED_TO) and the new state node
it produced (PRODUCED). It is never deleted or overwritten; the
full sequence of transforms is always traversable.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Unique identifier. |
axis |
TransformAxis
|
The transformation axis that was applied. |
operator |
str
|
Identifier of the user or system that issued the transform. |
applied_at |
datetime
|
UTC timestamp of the operation. |
parameters |
dict[str, Any]
|
Axis-specific parameters as a free dict (serialised to JSON when persisted). |
scene_id |
str
|
ID of the scene this transform was applied to. |
produced_id |
str
|
ID of the new state node produced by this transform. |
Source code in src/tng/domain/models.py
tng.domain.enums
¶
Bounded enumeration types for the TNGS domain vocabulary.
All semantic axes that must stay closed (cannot be arbitrary strings) are defined here. Using enumerations rather than open strings makes every vocabulary set queryable by value, prevents typo-driven divergence, and guarantees that Pydantic validation catches unknown values at the API boundary rather than silently persisting garbage to the graph.
AtomKind
¶
Bases: str, Enum
Functional classification of a narrative atom.
Attributes:
| Name | Type | Description |
|---|---|---|
DESCRIPTIVE |
Depicts setting, appearance, or state. |
|
DIALOGIC |
Direct or indirect speech act. |
|
REFLEXIVE |
Character introspection or narratorial comment. |
|
TRANSITIONAL |
Moves the narrative between scenes or moments. |
|
EXPOSITORY |
Background information, world-building, or backstory. |
Source code in src/tng/domain/enums.py
BarthesCode
¶
Bases: str, Enum
Barthesian narrative codes (from S/Z, Roland Barthes, 1970).
Attributes:
| Name | Type | Description |
|---|---|---|
HERMENEUTIC |
Mystery or enigma that propels reader anticipation. |
|
PROAIRETIC |
Action sequence implying a consequent action. |
|
SEMIC |
Connotative detail that builds character or atmosphere. |
|
SYMBOLIC |
Binary or antithetical thematic opposition. |
|
CULTURAL |
Reference to a shared body of knowledge or convention. |
Source code in src/tng/domain/enums.py
FocalizationDistance
¶
Bases: str, Enum
Genettean focalization distance for a Perspective node.
Attributes:
| Name | Type | Description |
|---|---|---|
ZERO |
Narrator knows more than any character (omniscient). |
|
INTERNAL |
Narrative filtered through one character's consciousness. |
|
EXTERNAL |
Narrator records behaviour without access to interiority. |
Source code in src/tng/domain/enums.py
NarrativeStatus
¶
Bases: str, Enum
Life-cycle states for a Narrative node (see state machine, SRS §7.4).
Attributes:
| Name | Type | Description |
|---|---|---|
DRAFT |
Narrative created but not yet atomized. |
|
ATOMIZED |
Ingest complete; atoms and events persisted. |
|
PATTERNED |
Pattern detection run; instances linked. |
|
TRANSFORMED |
At least one transformation axis applied. |
|
RENDERED |
Render operation has been performed. |
|
EXPORTED |
Narrative exported to an external format. |
|
ARCHIVED |
Administratively archived; no further processing. |
Source code in src/tng/domain/enums.py
PatternFamily
¶
Bases: str, Enum
High-level family tags for narrative pattern templates.
Attributes:
| Name | Type | Description |
|---|---|---|
RITUAL |
Socially codified exchange or ceremony. |
|
TRANSITION |
Movement across a threshold or boundary. |
|
CONFLICT |
Antagonistic encounter between agents. |
|
REVELATION |
Disclosure of previously hidden information. |
|
PURSUIT |
Chase or quest structure. |
|
TRANSFORMATION |
Internal or external change of state. |
Source code in src/tng/domain/enums.py
ReliabilityLevel
¶
Bases: str, Enum
Credibility rating assigned to a narrative Perspective.
Attributes:
| Name | Type | Description |
|---|---|---|
RELIABLE |
Narrator or focalizer is trustworthy. |
|
UNRELIABLE |
Narrator or focalizer is demonstrably biased or wrong. |
|
AMBIGUOUS |
Reliability cannot be determined from available evidence. |
Source code in src/tng/domain/enums.py
RenderType
¶
Bases: str, Enum
Output format requested from the Render endpoint.
Attributes:
| Name | Type | Description |
|---|---|---|
PROSE |
Atoms in surface order as a prose draft. |
|
DIFF |
Side-by-side before/after for each transformed axis. |
|
JSON |
Full graph state as a JSON document. |
|
CYPHER |
Replayable Cypher MERGE script. |
|
MARKDOWN |
Structured Markdown summary with transform log. |
|
GRAPHML |
yEd-compatible GraphML with edges coloured by narrative tension. Suitable for visual graph exploration in yEd or any tool that reads the GraphML + yFiles extension schema. |
Source code in src/tng/domain/enums.py
TransformAxis
¶
Bases: str, Enum
The six supported transformation axes of TNGS.
Each axis operates on a specific domain object and produces a new state node rather than overwriting the existing one, preserving the full transformation lineage as traversable graph state.
Attributes:
| Name | Type | Description |
|---|---|---|
POV |
Point-of-view / focalization shift. |
|
MOOD |
Affective / tonal retag. |
|
GENRE |
Genre profile swap. |
|
CHRONOTOPE |
Bakhtinian time-space remap. |
|
RELIABILITY |
Narrator reliability adjustment. |
|
CODE_OVERLAY |
Barthesian code attachment to atoms. |
Source code in src/tng/domain/enums.py
tng.services.ingest_service
¶
Ingest service — orchestrates the full ingest pipeline (SRS §6.1, Diagram 7).
Responsibilities¶
- Accept a raw text payload (plain text, Markdown, or pre-structured JSON).
- Segment text into scenes and atoms via the
segmenter. - Extract entities and events via
entity_extractorandevent_detector. - Apply confidence scoring and review flags via
annotator. - Delegate pattern detection to
PatternService. - Persist the complete result via
GraphRepositoryin a single pass. - Return an
IngestResultsummary to the caller.
The service never issues Cypher directly; it only calls the repository. All pre-processing runs in memory before any graph write, ensuring the graph is never left in a partially-atomized state (SRS Diagram 7 note).
IngestPayload
dataclass
¶
Normalised input payload for the IngestService.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
title
|
str
|
Narrative title. |
required |
text
|
str
|
Raw prose or pre-structured text to ingest. |
required |
narrative_id
|
str
|
Optional; generated if absent. |
make_id()
|
source_ref
|
str
|
Optional provenance reference. |
''
|
format
|
str
|
Input format hint: |
'text'
|
annotations
|
dict
|
Optional pre-annotations dict (from JSON payloads). |
dict()
|
Source code in src/tng/services/ingest_service.py
IngestResult
dataclass
¶
Summary returned to the API after a successful ingest operation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
narrative_id
|
str
|
ID of the created or updated Narrative. |
required |
scene_count
|
int
|
Number of scenes persisted. |
0
|
atom_count
|
int
|
Total atoms written to the graph. |
0
|
event_count
|
int
|
Total events written. |
0
|
character_count
|
int
|
Total characters written. |
0
|
pattern_count
|
int
|
Number of pattern instances created. |
0
|
flagged_count
|
int
|
Number of nodes flagged for human review. |
0
|
Source code in src/tng/services/ingest_service.py
IngestService
¶
Orchestrates the ingest pipeline from raw text to persisted graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo
|
GraphRepository
|
An open |
required |
pattern_service
|
PatternService
|
A |
required |
settings
|
Settings
|
Application settings (used for |
required |
Source code in src/tng/services/ingest_service.py
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | |
ingest(payload)
¶
Run the full ingest pipeline and persist the result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
payload
|
IngestPayload
|
Normalised input payload. |
required |
Returns:
| Type | Description |
|---|---|
IngestResult
|
|
Source code in src/tng/services/ingest_service.py
tng.services.transform_service
¶
Transform service — validates and applies transformation axes (SRS §7).
The six transformation axes are each dispatched through a dedicated
validator and then routed to the GraphRepository. The service is the
only place where axis-specific parameter validation occurs; the repository
is responsible only for the Cypher mechanics.
Non-destructive contract (SRS §7.2)¶
Every transformation:
- Creates a new state node.
- Detaches the old
CURRENT_*relationship. - Attaches the new
CURRENT_*relationship. - Creates a
Transformaudit node linked to both.
The old state node is never deleted — full lineage is always traversable.
Design notes¶
- Axis validators use Pydantic for parameter schemas; an invalid parameter
dict raises
ValueErrorbefore any graph write occurs (SRS Diagram 9). - The
TransformRequestdataclass is the public input contract; it is populated from the API schema and handed toapply().
ChronotopeParams
¶
Bases: BaseModel
Parameters for a chronotope transformation.
Attributes:
| Name | Type | Description |
|---|---|---|
time_mode |
str
|
Time mode (cyclical/linear/suspended/compressed). |
space_mode |
str
|
Space mode (bounded/open/liminal/utopian). |
Source code in src/tng/services/transform_service.py
CodeOverlayParams
¶
Bases: BaseModel
Parameters for a code overlay transformation.
Attributes:
| Name | Type | Description |
|---|---|---|
atom_id |
str
|
ID of the target Atom. |
code |
BarthesCode
|
Barthesian code category. |
label |
str
|
Human-readable annotation label. |
Source code in src/tng/services/transform_service.py
GenreParams
¶
Bases: BaseModel
Parameters for a genre transformation.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Genre name. |
conventions |
list[str]
|
List of genre constraint strings. |
Source code in src/tng/services/transform_service.py
MoodParams
¶
Bases: BaseModel
Parameters for a mood transformation.
Attributes:
| Name | Type | Description |
|---|---|---|
label |
str
|
Free-text mood label. |
valence |
float
|
Sentiment polarity in [-1.0, 1.0]. |
arousal |
float
|
Activation in [0.0, 1.0]. |
Source code in src/tng/services/transform_service.py
PovParams
¶
Bases: BaseModel
Parameters for a POV transformation.
Attributes:
| Name | Type | Description |
|---|---|---|
focalizer |
str
|
ID of the Character who becomes the focalizer. |
distance |
FocalizationDistance
|
Genettean focalization distance. |
reliability |
ReliabilityLevel
|
Narrator/focalizer credibility. |
Source code in src/tng/services/transform_service.py
ReliabilityParams
¶
Bases: BaseModel
Parameters for a reliability transformation.
Attributes:
| Name | Type | Description |
|---|---|---|
reliability |
ReliabilityLevel
|
New reliability level for the existing Perspective. |
Source code in src/tng/services/transform_service.py
TransformRequest
dataclass
¶
Input contract for a transform request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scene_id
|
str
|
Target scene ID. |
required |
axis
|
TransformAxis
|
The transformation axis. |
required |
parameters
|
dict[str, Any]
|
Axis-specific parameter dict. |
required |
operator
|
str
|
Identifier of the requesting user/system. |
'system'
|
Source code in src/tng/services/transform_service.py
TransformResponse
dataclass
¶
Result returned to the API after a transform operation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transform_id
|
str
|
ID of the created Transform audit node. |
required |
scene_id
|
str
|
Target scene ID. |
required |
axis
|
str
|
The axis that was applied. |
required |
produced_id
|
str
|
ID of the new state node created. |
required |
status
|
str
|
Always |
'accepted'
|
Source code in src/tng/services/transform_service.py
TransformService
¶
Validates and applies transformation axes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo
|
GraphRepository
|
Open |
required |
Source code in src/tng/services/transform_service.py
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | |
apply(request)
¶
Validate parameters and apply a transformation to a scene.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
TransformRequest
|
The transform request. |
required |
Returns:
| Type | Description |
|---|---|
TransformResponse
|
A |
Raises:
| Type | Description |
|---|---|
ValueError
|
When axis parameters fail validation. |
Source code in src/tng/services/transform_service.py
apply_bulk(narrative_id, axis, parameters, operator='system')
¶
Apply a transformation axis to every scene in a narrative.
Validates parameters against the axis schema before issuing any write. Scenes are processed in sequence order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
narrative_id
|
str
|
Target narrative ID. |
required |
axis
|
TransformAxis
|
The transformation axis. |
required |
parameters
|
dict[str, Any]
|
Axis-specific parameter dict (validated once). |
required |
operator
|
str
|
Identifier of the requesting user/system. |
'system'
|
Returns:
| Type | Description |
|---|---|
list[TransformResponse]
|
List of |
Raises:
| Type | Description |
|---|---|
ValueError
|
When parameters fail axis validation or the narrative has no scenes. |
Source code in src/tng/services/transform_service.py
get_history(scene_id)
¶
Return the transformation history for a scene.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scene_id
|
str
|
The target scene ID. |
required |
Returns:
| Type | Description |
|---|---|
list[dict]
|
Ordered list of transform audit dicts. |
Source code in src/tng/services/transform_service.py
tng.services.pattern_service
¶
Pattern service — detects and instantiates narrative pattern templates.
Implements SRS §6.2 (Diagram 8): pattern detection is a matching operation between incoming atoms/events and a library of Pattern templates stored in the graph.
Architecture¶
- The service holds a reference to the
GraphRepositoryfor template lookups and instance persistence. - Pattern matching is a Strategy: each
PatternMatcherchecks a single template against the atom/event set and returns an optionalPatternInstancewith a confidence score. - Multiple matchers can fire on the same scene; overlapping patterns are
not collapsed — they are represented as separate
PatternInstancenodes (SRS §6.2). - Pattern templates are loaded from the graph at startup and cached in memory for the lifetime of the service.
Built-in matchers¶
The service ships four lightweight matchers that cover common patterns from the SRS seed data. Additional matchers can be registered at startup without modifying this module.
KeywordAtomMatcher
dataclass
¶
Matches a pattern by searching atom texts for keyword strings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keywords
|
frozenset[str]
|
Set of lowercase keywords to search for in atom text. |
required |
base_confidence
|
float
|
Confidence assigned on single keyword match. |
0.7
|
Source code in src/tng/services/pattern_service.py
match(template, atoms, events)
¶
Return a PatternInstance if keywords are found in atom text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
Pattern
|
The template to match. |
required |
atoms
|
list[Atom]
|
Scene atoms whose text is scanned. |
required |
events
|
list[Event]
|
Scene events (not used by this matcher). |
required |
Returns:
| Type | Description |
|---|---|
PatternInstance | None
|
A |
Source code in src/tng/services/pattern_service.py
PatternMatcher
¶
Bases: Protocol
Contract for a single-pattern matching strategy.
:method match: Test atoms and events against a template.
Return a PatternInstance if matched, else None.
Source code in src/tng/services/pattern_service.py
match(template, atoms, events)
¶
Attempt to match the template against the provided atoms/events.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
Pattern
|
The pattern template to match against. |
required |
atoms
|
list[Atom]
|
Scene atoms available for slot binding. |
required |
events
|
list[Event]
|
Scene events available for slot binding. |
required |
Returns:
| Type | Description |
|---|---|
PatternInstance | None
|
A |
Source code in src/tng/services/pattern_service.py
PatternService
¶
Detects narrative patterns in a set of atoms and events.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo
|
GraphRepository
|
|
required |
matchers
|
dict[str, PatternMatcher] | None
|
Matcher registry mapping pattern ID → matcher.
Defaults to |
None
|
Source code in src/tng/services/pattern_service.py
detect_patterns(atoms, events, narrative_id)
¶
Run all registered matchers against the given atoms and events.
Pattern templates are fetched from the graph by ID. If a template does not exist in the graph it is silently skipped (not auto-created).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atoms
|
list[Atom]
|
Scene atoms to match against. |
required |
events
|
list[Event]
|
Scene events to match against. |
required |
narrative_id
|
str
|
ID of the parent narrative (for logging). |
required |
Returns:
| Type | Description |
|---|---|
list[PatternInstance]
|
List of |
Source code in src/tng/services/pattern_service.py
register_pattern(pattern, matcher)
¶
Register a new pattern template and its matcher at runtime.
The pattern template is persisted to the graph immediately.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
Pattern
|
The |
required |
matcher
|
PatternMatcher
|
The matcher strategy for this pattern. |
required |
Source code in src/tng/services/pattern_service.py
VerbFamilyMatcher
dataclass
¶
Matches a pattern whose template name is associated with a set of verbs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
verb_hints
|
frozenset[str]
|
Set of lowercase verb strings that signal this pattern. |
required |
base_confidence
|
float
|
Confidence assigned when a hint verb is found. |
0.75
|
Source code in src/tng/services/pattern_service.py
match(template, atoms, events)
¶
Return a PatternInstance if any event verb matches a hint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
Pattern
|
The template to match. |
required |
atoms
|
list[Atom]
|
Scene atoms (not used by this matcher). |
required |
events
|
list[Event]
|
Scene events whose verbs are checked. |
required |
Returns:
| Type | Description |
|---|---|
PatternInstance | None
|
A |
Source code in src/tng/services/pattern_service.py
tng.services.render_service
¶
Render service — dispatches render requests to registered renderers.
The service maintains a registry of RendererProtocol implementations
keyed by RenderType. Renderers are registered at startup; new output
types can be added without modifying this module (open/closed principle).
No renderer is allowed to issue Cypher directly. All graph data arrives
as a GraphState snapshot fetched by this service via the repository.
RenderService
¶
Dispatches render requests to the appropriate renderer implementation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo
|
GraphRepository
|
Open |
required |
renderers
|
dict[RenderType, RendererProtocol] | None
|
Renderer registry. Defaults to the five built-in renderers; inject custom implementations for extensibility. |
None
|
Source code in src/tng/services/render_service.py
register_renderer(render_type, renderer)
¶
Register or replace a renderer at runtime.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
render_type
|
RenderType
|
The output format key. |
required |
renderer
|
RendererProtocol
|
The renderer implementation to register. |
required |
Source code in src/tng/services/render_service.py
render(narrative_id, render_type, params=None)
¶
Fetch graph state and render it to the requested format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
narrative_id
|
str
|
The narrative to render. |
required |
render_type
|
RenderType
|
The desired output format. |
required |
params
|
dict[str, Any] | None
|
Renderer-specific parameters (optional). |
None
|
Returns:
| Type | Description |
|---|---|
RenderOutput
|
A |
Raises:
| Type | Description |
|---|---|
KeyError
|
When |
ValueError
|
When the narrative does not exist. |
Source code in src/tng/services/render_service.py
tng.repository.graph_repository
¶
Graph repository — single point of contact with Neo4j.
All Cypher queries are executed here and nowhere else. Service-layer code receives domain objects; it never sees raw driver records. This enforces the boundary described in SRS §3.2 (Diagram 2).
Connection lifecycle¶
The repository accepts a neo4j.Driver instance. The driver manages
its own connection pool; one driver per process is the correct pattern.
The close() method must be called at application shutdown to release
pool resources.
Transaction discipline¶
- Writes — all multi-statement writes use managed transactions
(
session.execute_write) so that failures roll back atomically. - Small reads — bounded single-record reads use
execute_query. - Streaming reads — render queries that may return many rows use
session.runwith lazy cursor iteration.
GraphRepository
¶
Abstracts all Neo4j interactions for the TNGS application.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
driver
|
Driver
|
An authenticated |
required |
database
|
str
|
Name of the Neo4j database to target. |
'neo4j'
|
Source code in src/tng/repository/graph_repository.py
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 | |
apply_schema()
¶
Apply all constraints and indexes idempotently.
Safe to call on every startup; uses IF NOT EXISTS guards.
Source code in src/tng/repository/graph_repository.py
apply_transform(transform)
¶
Dispatch and persist a transformation on a scene.
Routes to the appropriate axis-specific Cypher query. The old state node is detached (not deleted) and the new state node is created in a single managed transaction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transform
|
Transform
|
Fully populated Transform domain object. |
required |
Returns:
| Type | Description |
|---|---|
Transform
|
The same transform (with |
Raises:
| Type | Description |
|---|---|
ValueError
|
For unknown or unsupported axis values. |
Source code in src/tng/repository/graph_repository.py
archive_narrative(narrative_id)
¶
Set a Narrative's status to archived.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
narrative_id
|
str
|
Target narrative ID. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Source code in src/tng/repository/graph_repository.py
close()
¶
get_atom_revisions(atom_id)
¶
Return all AtomRevision nodes for an atom, oldest first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atom_id
|
str
|
The target Atom's ID. |
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
List of revision dicts with |
Source code in src/tng/repository/graph_repository.py
get_atoms_with_context(narrative_id)
¶
Fetch atoms in surface order with their current scene context.
Used by the prose renderer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
narrative_id
|
str
|
The narrative to render. |
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
Row dicts with atom text, scene metadata, and perspective/mood. |
Source code in src/tng/repository/graph_repository.py
get_event_relations(narrative_id)
¶
Fetch all inter-event causal and temporal relationships.
Returns CAUSES, ENABLES, PREVENTS, and PRECEDES
edges between events within the narrative's scenes. Used by the
GraphML renderer to draw and tension-score causal graph structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
narrative_id
|
str
|
The narrative to query. |
required |
Returns:
| Type | Description |
|---|---|
list[EventRelation]
|
List of |
Source code in src/tng/repository/graph_repository.py
get_graph_state(narrative_id)
¶
Return a complete in-memory snapshot of a narrative's graph state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
narrative_id
|
str
|
The narrative to snapshot. |
required |
Returns:
| Type | Description |
|---|---|
GraphState | None
|
A |
Source code in src/tng/repository/graph_repository.py
get_narrative(narrative_id)
¶
Retrieve a Narrative by ID with all nested scenes and atoms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
narrative_id
|
str
|
The narrative's unique identifier. |
required |
Returns:
| Type | Description |
|---|---|
Narrative | None
|
A populated |
Source code in src/tng/repository/graph_repository.py
get_pattern(pattern_id)
¶
Retrieve a single Pattern template by ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern_id
|
str
|
The pattern's unique identifier. |
required |
Returns:
| Type | Description |
|---|---|
Pattern | None
|
A |
Source code in src/tng/repository/graph_repository.py
get_scene_ids(narrative_id)
¶
Return scene IDs for a narrative in sequence order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
narrative_id
|
str
|
The narrative's unique identifier. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
List of scene ID strings, ordered by sequence. |
Source code in src/tng/repository/graph_repository.py
get_transform(transform_id)
¶
Retrieve a Transform audit record by ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transform_id
|
str
|
The transform's unique identifier. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | None
|
A dict with transform details or |
Source code in src/tng/repository/graph_repository.py
get_transform_history(scene_id)
¶
Return the ordered transformation history for a scene.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scene_id
|
str
|
The scene to query. |
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
List of transform dicts ordered by applied_at ASC. |
Source code in src/tng/repository/graph_repository.py
list_pattern_instances(narrative_id)
¶
List all PatternInstances for a narrative with context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
narrative_id
|
str
|
The narrative to query. |
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
List of dicts with instance, pattern, and scene_id. |
Source code in src/tng/repository/graph_repository.py
list_patterns(family=None)
¶
List pattern templates, optionally filtered by family.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
family
|
str | None
|
If provided, only return patterns of this family. |
None
|
Returns:
| Type | Description |
|---|---|
list[Pattern]
|
List of matching patterns. |
Source code in src/tng/repository/graph_repository.py
ping()
¶
Return True when Neo4j is reachable and the database responds.
Returns:
| Type | Description |
|---|---|
bool
|
|
Raises:
| Type | Description |
|---|---|
Exception
|
On Neo4j connectivity failure — callers decide how to handle it. |
Source code in src/tng/repository/graph_repository.py
revise_atom(atom_id, revision_id, text, revised_at, operator, reason)
¶
Create an AtomRevision node and re-point CURRENT_REVISION.
The old CURRENT_REVISION edge is detached (not deleted) and a SUPERSEDES edge is added from the new revision to the old one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atom_id
|
str
|
The target Atom's ID. |
required |
revision_id
|
str
|
Pre-generated ID for the new AtomRevision node. |
required |
text
|
str
|
Revised prose text. |
required |
revised_at
|
datetime
|
UTC timestamp. |
required |
operator
|
str
|
Identifier of the requesting user/system. |
required |
reason
|
str
|
Optional reason for the change. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Source code in src/tng/repository/graph_repository.py
save_narrative(narrative)
¶
Persist or update a Narrative node.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
narrative
|
Narrative
|
The domain Narrative to persist. |
required |
Returns:
| Type | Description |
|---|---|
Narrative
|
The same narrative (unchanged — the graph write is idempotent via MERGE). |
Source code in src/tng/repository/graph_repository.py
save_pattern(pattern)
¶
Persist a Pattern template.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
Pattern
|
The pattern to save. |
required |
Returns:
| Type | Description |
|---|---|
Pattern
|
The same pattern (unchanged). |
Source code in src/tng/repository/graph_repository.py
save_scene(scene, narrative_id)
¶
Persist a Scene and link it to its parent Narrative.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scene
|
Scene
|
The domain Scene to persist. |
required |
narrative_id
|
str
|
The parent narrative's ID. |
required |
Returns:
| Type | Description |
|---|---|
Scene
|
The saved scene. |
Source code in src/tng/repository/graph_repository.py
update_narrative_status(narrative_id, status)
¶
Update the status property on a Narrative node.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
narrative_id
|
str
|
Target narrative ID. |
required |
status
|
NarrativeStatus
|
New status value. |
required |
Source code in src/tng/repository/graph_repository.py
update_narrative_status_for_scene(scene_id, status)
¶
Update the status of the Narrative that contains a given scene.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scene_id
|
str
|
ID of a scene whose parent narrative should be updated. |
required |
status
|
NarrativeStatus
|
New status value. |
required |
Source code in src/tng/repository/graph_repository.py
create_driver(settings)
¶
Create and return an authenticated Neo4j driver.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
settings
|
Settings
|
Application settings containing Neo4j URI and credentials. |
required |
Returns:
| Type | Description |
|---|---|
Driver
|
A connected |