Repository navigation
API Reference parrot.tools.working_memory.task_memory.store.postgres
PostgreSQL backing for durable task memory (FEAT-538, Delivery B).
This module owns three things, and deliberately not a fourth:
-
The migration — reading, parsing and explicitly applying
migrations/001_task_memory.sql, plus verifying that a database has the shape the code expects before anything touches it. -
The connection pool lifecycle — created lazily, so importing this module (or running the in-memory backend) never pays for
asyncpg. -
The shared transaction coordinator — one connection that the task store and the artifact store both enlist in, because durable artifact publication must commit the alias/version index, the evidence rows and the
artifact_registeredjournal event together. Two unrelated pool transactions would let a crash between them publish a storage reference whose bytes or whose journal entry never existed. -
The durable journal and reducer projections — the append protocol below, which must be behaviourally identical to :class:
~.memory.InMemoryTaskMemoryStore(AC2). Where the two could differ, this module follows the in-memory store's decisions rather than inventing its own, and the shared conformance suite is run against both. -
The durable artifact store — :class:
PostgresArtifactStore, which owns aliases, versions and evidence pins. It lives here rather than in its own module precisely because it must share this module's pool and transaction coordinator: an artifact's index rows, its evidence rows and itsartifact_registeredjournal event have to commit on ONE connection or not at all.
The append protocol (spec §2 Persistence and Recovery) is one transaction, in this order:
-
INSERT ... ON CONFLICT DO NOTHING/SELECT ... FOR UPDATEthe task row. The row lock is what serializes appends to the same task while letting different tasks proceed concurrently — PostgreSQL does the serialization the in-memory store gets from a per-taskasyncio.Lock. - Verify scope.
- Classify by
event_id— before the revision check, so a caller retrying a batch that in fact committed gets a no-op rather than a conflict it cannot resolve. - Check
expected_revision. - Check capacity.
- Reduce into a local variable, allocating contiguous sequences.
- Insert the journal rows, update the projection, and commit.
Steps 2–6 write nothing, so "a rejected command changes nothing" holds both by construction and, for anything that escapes it, by the transaction rolling back.
.. warning::
asyncpg is imported lazily, inside the functions that need a
connection. Importing it at module load would mean a deployment
without the PostgreSQL extra could not even import the task-memory
package, and the in-memory backend would pay for a driver it never
uses. There is a test asserting this.
Type: str
Type: int
Durable aliases, versions and evidence pins on PostgreSQL (Delivery B).
The catalog backend of decision D1, made durable. It satisfies
:class:~parrot.interfaces.artifact_store.ArtifactStore and must be
behaviourally identical to
:class:~..artifacts.InMemoryArtifactStore (AC2) — where the two
could differ, this class follows the in-memory store's decisions
rather than inventing its own, and the shared conformance suite runs
against both.
The publish order is the guarantee (spec §2 Persistence and Recovery)::
write the immutable blob
-> verify readability and checksum
-> ATOMICALLY commit the alias/version index, the evidence
rows and the `artifact_registered` journal event, on ONE
connection
A crash between the blob write and the commit leaves an orphan blob, which is expected and sweepable. The order exists to make the opposite impossible: an index row pointing at bytes that were never written is a phantom reference, and nothing downstream can recover from one.
Version allocation serializes on the alias row. A writer takes
SELECT ... FOR UPDATE on artifact_aliases before computing
latest_version + 1, so two concurrent overwrites of the same
alias cannot both allocate the same number. PostgreSQL does here what
the in-memory store gets from its asyncio.Lock.
Pinning is derived, never stored. A version is pinned while any
nonterminal task references it in artifact_evidence — including
a task other than the one that produced it. A single mutable flag
could not express "two tasks reference this, one has finished", and
consulting only the producing task would let a cross-task reference
be swept out from under its holder.
| Parameter | Type | Default | Description |
|---|---|---|---|
tasks |
'PostgresTaskMemoryStore' |
The task store whose pool, schema and transaction coordinator this store shares. | |
blobs |
Optional[Any] |
None |
Durable byte storage (:class:~..blob.ArtifactBlobStore). Without it, versions are registered as metadata only and reported honestly as missing — durable metadata with no durable bytes is not evidence, and is never presented as such. |
config |
Optional[TaskMemoryConfig] |
None |
Capacity configuration. Defaults to the task store's. |
Open a transaction this store and the task store can share.
transaction() -> Any
Returns: Any — An async context manager yielding a class:PostgresTransaction.
Release resources. The pool belongs to the task store.
close() -> None
Register a value durably, allocating or incrementing its version.
Snapshotting and fingerprinting run on a worker thread before the transaction opens, so no database lock is held across CPU work. Only allocation, the blob write and publication happen inside it.
pin_for registers and pins in one act. As in the in-memory
store this matters for more than convenience: an unpinned version
is an ordinary retention candidate, so a value pinned only
afterwards can be swept before its pin ever applies.
put(scope: TaskScope, key: str, value: Any, *, task_id: Optional[str] = None, kind: Optional[ArtifactKind] = None, description: str = '', producer_call_id: Optional[str] = None, attribution: Attribution = Attribution.NONE, turn_id: Optional[str] = None, metadata: Optional[dict] = None, transaction: Optional[Any] = None, pin_for: Optional[str] = None) -> ArtifactDescriptor
| Parameter | Type | Default | Description |
|---|---|---|---|
scope |
TaskScope |
Trusted runtime scope. | |
key |
str |
Working-memory alias to publish under. | |
value |
Any |
The value to register. | |
task_id |
Optional[str] |
None |
Owning task, when one is selected. |
kind |
Optional[ArtifactKind] |
None |
Explicit evidence type; inferred when None. |
description |
str |
'' |
Human-readable description, retained by the caller's catalog rather than stored here. |
producer_call_id |
Optional[str] |
None |
The physical attempt that produced it. |
attribution |
Attribution |
Attribution.NONE |
How that attempt was attributed. |
turn_id |
Optional[str] |
None |
Conversation turn, stamped on the journal event. |
metadata |
Optional[dict] |
None |
Caller metadata. Unused here; the catalog owns it. |
transaction |
Optional[Any] |
None |
Shared transaction to enlist in, so the index rows and the journal event commit together. |
pin_for |
Optional[str] |
None |
Task id to pin this version for, atomically with registration. |
Returns: ArtifactDescriptor — The read projection of the newly registered version.
Raises:
-
LimitExceeded— If the alias exceeds :data:Limits.MAX_IDENTIFIER. -
TaskMemoryUnavailable— If the database cannot be reached.
Pin a version for a task by recording an evidence reference.
pin_evidence(scope: TaskScope, ref: EvidenceRef, task_id: str, *, step_id: str = '__task__') -> bool
| Parameter | Type | Default | Description |
|---|---|---|---|
scope |
TaskScope |
Trusted runtime scope. | |
ref |
EvidenceRef |
The version to pin. | |
task_id |
str |
The referencing task. | |
step_id |
str |
'__task__' |
The referencing step. |
Returns: bool — True when the version exists in this scope and was pinned.
Drop every reference a task holds on a version.
unpin_evidence(scope: TaskScope, ref: EvidenceRef, task_id: str) -> bool
| Parameter | Type | Default | Description |
|---|---|---|---|
scope |
TaskScope |
Trusted runtime scope. | |
ref |
EvidenceRef |
The version. | |
task_id |
str |
The task releasing it. |
Returns: bool — True when a reference was removed.
Return the NONTERMINAL tasks still referencing a version.
This is the pin query, and its shape is the point: a version is pinned while any nonterminal task references it, including one other than its producer. A terminal task's reference stops pinning, which is what lets retention proceed once every holder has finished — and what stops a cross-task reference being swept out from under a task that is still working.
pins_for(scope: TaskScope, ref: EvidenceRef) -> Tuple[str, ...]
| Parameter | Type | Default | Description |
|---|---|---|---|
scope |
TaskScope |
Trusted runtime scope. | |
ref |
EvidenceRef |
The version. |
Returns: Tuple[str, ...] — The pinning task ids, sorted.
Resolve an alias to the version it currently points at.
A plain key never searches another task's namespace, and a tombstoned alias resolves to nothing.
get_current(scope: TaskScope, key: str, *, task_id: Optional[str] = None) -> Optional[ArtifactDescriptor]
| Parameter | Type | Default | Description |
|---|---|---|---|
scope |
TaskScope |
Trusted runtime scope. | |
key |
str |
The alias. | |
task_id |
Optional[str] |
None |
Owning task namespace. |
Returns: Optional[ArtifactDescriptor] — The current descriptor, or None.
Resolve one exact version, checking scope.
A globally unique artifact id is an identifier, not a capability:
the scope check is not optional. A same-scope cross-task
reference must be explicit, so a task_id mismatch reports the
version as absent rather than resolving it implicitly.
get_version(scope: TaskScope, ref: EvidenceRef, *, task_id: Optional[str] = None) -> Optional[ArtifactDescriptor]
| Parameter | Type | Default | Description |
|---|---|---|---|
scope |
TaskScope |
Trusted runtime scope. | |
ref |
EvidenceRef |
The exact version. | |
task_id |
Optional[str] |
None |
Owning task, when validating a cross-task reference. |
Returns: Optional[ArtifactDescriptor] — The descriptor, or None.
Materialize a version's payload under a hard byte ceiling.
The bounds are delegated to the blob store, which checks the stored object's size before downloading it and verifies the checksum of what it transferred. A refusal never carries a payload.
load_payload(scope: TaskScope, ref: EvidenceRef, *, max_bytes: int, offset: Optional[int] = None, limit: Optional[int] = None) -> PayloadResult
| Parameter | Type | Default | Description |
|---|---|---|---|
scope |
TaskScope |
Trusted runtime scope. | |
ref |
EvidenceRef |
The exact version. | |
max_bytes |
int |
Ceiling on the decoded payload. 0 never materializes. |
|
offset |
Optional[int] |
None |
First row, for a tabular page. |
limit |
Optional[int] |
None |
Row count, for a tabular page. |
Returns: PayloadResult — A result carrying either the payload or a refusal.
Page artifact descriptors in a scope.
Descriptors are metadata only: building a page reads no blob,
calls no repr() and computes no summary.
list(scope: TaskScope, *, task_id: Optional[str] = None, kinds: Optional[Sequence[ArtifactKind]] = None, limit: int = 50, cursor: Optional[str] = None, as_of_seq: Optional[int] = None) -> ArtifactPage
| Parameter | Type | Default | Description |
|---|---|---|---|
scope |
TaskScope |
Trusted runtime scope. | |
task_id |
Optional[str] |
None |
Restrict to one task's namespace. |
kinds |
Optional[Sequence[ArtifactKind]] |
None |
Restrict to these evidence types. |
limit |
int |
50 |
Bounded page size. |
cursor |
Optional[str] |
None |
Opaque cursor from a previous page. |
as_of_seq |
Optional[int] |
None |
Recorded in the cursor query, for symmetry with the in-memory store. |
Returns: ArtifactPage — A bounded page of descriptors.
Raises:
-
CursorError— If the cursor is malformed, out of bounds, or issued for a different scope or query.
Mark one version's content as no longer valid evidence.
Bytes are left alone: invalidation is a statement about
evidence, not about storage, and a persisted payload remains on
disk. evidence_verifiable is cleared, because a fingerprint
that no longer describes the content proves nothing.
invalidate(scope: TaskScope, ref: EvidenceRef, *, reason: str, transaction: Optional[Any] = None) -> ArtifactDescriptor
| Parameter | Type | Default | Description |
|---|---|---|---|
scope |
TaskScope |
Trusted runtime scope. | |
ref |
EvidenceRef |
The exact version. | |
reason |
str |
Why. | |
transaction |
Optional[Any] |
None |
Shared transaction to enlist in. |
Returns: ArtifactDescriptor — The updated descriptor.
Raises:
-
ScopeViolation— If the version does not exist in this scope.
Release a version's stored bytes, keeping its metadata.
Explicit eviction does not invalidate: the caller asked for the bytes back, and the fingerprint still describes what the version contained. A metadata tombstone always remains, so no step is left labelled valid against evidence that silently vanished.
The index row is updated first and the object deleted afterwards. A crash between them leaves an orphan blob, which retention sweeps — the opposite order would leave the index pointing at bytes that are already gone.
evict(scope: TaskScope, ref: EvidenceRef) -> bool
| Parameter | Type | Default | Description |
|---|---|---|---|
scope |
TaskScope |
Trusted runtime scope. | |
ref |
EvidenceRef |
The exact version. |
Returns: bool — True when bytes were released.
Remove a live alias without deleting the versions behind it.
The identity and its version counter survive as a tombstone,
so a later re-put under the same key continues at
latest + 1. Restarting at 1 would let a fresh, unrelated
version shadow still-pinned evidence at the same coordinates.
drop_alias(scope: TaskScope, key: str, *, task_id: Optional[str] = None) -> bool
| Parameter | Type | Default | Description |
|---|---|---|---|
scope |
TaskScope |
Trusted runtime scope. | |
key |
str |
The alias to remove. | |
task_id |
Optional[str] |
None |
Owning task namespace. |
Returns: bool — True when the alias existed and was live.
Durable task-memory storage on PostgreSQL (Delivery B).
The schema lifecycle, the pool, the transaction coordinator and the journal/projection command and read paths are implemented here.
Durable aliases, versions and evidence pins belong to
:class:PostgresArtifactStore, which shares this store's pool and
transaction coordinator.
| Parameter | Type | Default | Description |
|---|---|---|---|
dsn |
Optional[str] |
None |
PostgreSQL connection string. None defers to pool. |
pool |
Optional[Any] |
None |
An already-built asyncpg pool to borrow. When given, this store does not own it and will not close it. |
schema |
str |
SCHEMA_NAME |
Schema to operate in. Overridable only for test isolation; production always uses :data:SCHEMA_NAME. |
min_size |
int |
1 |
Minimum pool size when this store builds the pool. |
max_size |
int |
10 |
Maximum pool size when this store builds the pool. |
config |
Optional[TaskMemoryConfig] |
None |
Close the pool, if this store owns it.
close() -> None
Return the coordinator that hands out shareable transactions.
coordinator() -> PostgresTransactionCoordinator
Returns: PostgresTransactionCoordinator
Open a transaction this store and an artifact store can share.
transaction() -> Any
Returns: Any — An async context manager yielding a class:PostgresTransaction.
Apply the packaged migration explicitly.
Safe to repeat: every statement is IF NOT EXISTS-guarded and
the version row uses ON CONFLICT DO NOTHING, so re-running is
a no-op that also completes a migration interrupted part-way.
This is never called from a tool path. Automatic DDL on a hot path would mean any agent turn could attempt a schema change.
apply_migrations() -> int
Returns: int — The migration version now recorded in the database.
Raises:
-
TaskMemoryUnavailable— If the database already records a NEWER migration than this build implements. Running old code against a new schema is refused rather than attempted.
Run the DOWN migration.
.. danger::
Destructive and irreversible: it drops the whole schema, and every journal, projection and artifact index row with it. It also orphans every blob in external storage, which this migration does not touch. Read the rollback guidance at the top of the migration file before calling this.
revert_migrations() -> None
Check the database has the shape this build expects.
Called at enabled-backend startup, not per operation. A missing table is reported by name, so an operator sees "you did not run the migration" rather than a confusing error inside the first append.
verify_schema() -> None
Raises:
-
TaskMemoryUnavailable— If the schema is absent, incomplete, or records a newer migration than this build implements.
Create a task and append its first batch of events atomically.
There is no window in which a task exists with an empty journal: the row and its whole creation batch commit together.
Creation is idempotent and safe to race. Two pods creating the
same task id concurrently produce one row and one journal — the
loser of the INSERT ... ON CONFLICT DO NOTHING falls through
to the ordinary append path, which recognises the identical batch
as a redelivery.
create_task(scope: TaskScope, *, goal: str, events: Sequence[JournalEvent], transaction: Optional[PostgresTransaction] = None) -> AppendResult
| Parameter | Type | Default | Description |
|---|---|---|---|
scope |
TaskScope |
Trusted runtime scope the task belongs to. | |
goal |
str |
The task's goal, stamped onto task_started when the event does not already carry it. |
|
events |
Sequence[JournalEvent] |
Initial events, beginning with task_started. |
|
transaction |
Optional[PostgresTransaction] |
None |
A transaction to enlist in, or None. |
Returns: AppendResult — The append result, including the reduced projection.
Raises:
-
LimitExceeded— If the scope already holds the maximum number of open tasks. -
ScopeViolation— If the task id already exists in a different scope. -
ReducerError— If the batch is malformed. -
PlanValidationError— If the initial plan is invalid.
Append a batch of events under an optimistic revision check.
append_events(scope: TaskScope, task_id: str, events: Sequence[JournalEvent], *, expected_revision: Optional[int] = None, transaction: Optional[PostgresTransaction] = None) -> AppendResult
| Parameter | Type | Default | Description |
|---|---|---|---|
scope |
TaskScope |
Trusted runtime scope. | |
task_id |
str |
The task to append to. | |
events |
Sequence[JournalEvent] |
The batch, in order. | |
expected_revision |
Optional[int] |
None |
Revision the caller believes is current. None skips the check. |
transaction |
Optional[PostgresTransaction] |
None |
A transaction to enlist in, or None. |
Returns: AppendResult — The append result.
Raises:
-
ScopeViolation— If the task does not exist in this scope. -
RevisionConflict— If the revision is stale and the batch is not a pure redelivery. Nothing is written. -
ReducerError— If an id is reused with a different payload, or an event is malformed. -
LimitExceeded— If the journal's capacity is exhausted.
Load one task's projection consistently.
The projection, its sequence fence and the event count are read in ONE transaction, so a concurrent append cannot make them describe different instants.
load_snapshot(scope: TaskScope, task_id: str) -> Optional[TaskSnapshot]
| Parameter | Type | Default | Description |
|---|---|---|---|
scope |
TaskScope |
Trusted runtime scope. | |
task_id |
str |
The task to load. |
Returns: Optional[TaskSnapshot] — The snapshot, or None when no such task exists in this scope. A task owned by another scope reads as absent rather than forbidden — an existence oracle is a leak.
List tasks in a scope, newest activity first.
Ordering is (updated_at desc, task_id asc), matching the
in-memory store. The task-id tiebreak makes the order total, so
keyset pagination cannot skip or repeat a row when two tasks
share a timestamp.
list_tasks(scope: TaskScope, *, statuses: Optional[Sequence[TaskStatus]] = None, limit: int = 20, cursor: Optional[str] = None) -> TaskPage
| Parameter | Type | Default | Description |
|---|---|---|---|
scope |
TaskScope |
Trusted runtime scope. | |
statuses |
Optional[Sequence[TaskStatus]] |
None |
Restrict to these statuses; None means open (non-terminal) tasks only. |
limit |
int |
20 |
Bounded page size. |
cursor |
Optional[str] |
None |
Opaque cursor from a previous page. |
Returns: TaskPage — A bounded page of summaries.
Raises:
-
CursorError— If the cursor is malformed, out of bounds, or was issued for a different scope or query.
Page a task's journal in ascending sequence order.
Reads never append: no statement here writes, so repeated reads cannot change a task's sequence or fill its journal.
list_events(scope: TaskScope, task_id: str, *, after_seq: int = 0, limit: int = 50, as_of_seq: Optional[int] = None) -> EventPage
| Parameter | Type | Default | Description |
|---|---|---|---|
scope |
TaskScope |
Trusted runtime scope. | |
task_id |
str |
The task to read. | |
after_seq |
int |
0 |
Return events strictly after this sequence. |
limit |
int |
50 |
Bounded page size. |
as_of_seq |
Optional[int] |
None |
Fence the read at this sequence. |
Returns: EventPage — A bounded page of events.
Raises:
-
ScopeViolation— If the task does not exist in this scope.
List calls this task started but never settled.
Read-only and appends nothing. An unresolved call is a question, not a verdict: a ten-minute tool call is unresolved for ten minutes and is perfectly healthy throughout.
unresolved_calls(scope: TaskScope, task_id: str) -> Tuple[UnresolvedCall, ...]
| Parameter | Type | Default | Description |
|---|---|---|---|
scope |
TaskScope |
Trusted runtime scope. | |
task_id |
str |
The task to scan. |
Returns: Tuple[UnresolvedCall, ...] — The unresolved calls, in start order.
Raises:
-
ScopeViolation— If the task does not exist in this scope.
Whether a call already has a settled outcome.
This is the durable half of fencing. A late result from an old owner is rejected on the strength of this, not on Redis: the journal is the record, and a decision already written there cannot be overwritten by a slower owner that has just woken up.
has_terminal_event(scope: TaskScope, task_id: str, call_id: str) -> bool
| Parameter | Type | Default | Description |
|---|---|---|---|
scope |
TaskScope |
Trusted runtime scope. | |
task_id |
str |
The owning task. | |
call_id |
str |
The attempt. |
Returns: bool — True when a terminal event exists for the call.
Raises:
-
ScopeViolation— If the task does not exist in this scope.
Settle provably-dead calls as tool_outcome_unknown, once.
Three properties this method exists to guarantee:
-
A live call is never touched.
is_livemust returnFalse— provably gone — before anything is appended.TrueandNoneare both left alone, so neither a slow call nor an unreachable cache can be mistaken for a crash. An expired append lease is not consulted at all: it says nothing about whether a call is running. -
At most one unknown per call, ever. The whole pass runs
under the task row's
SELECT ... FOR UPDATE, and the unresolved set is read inside that lock. A second reconciler blocks, then re-reads and finds the call already settled. Two concurrent reconcilers therefore append one event between them, not two — and a repeated scan appends none. - Nothing is retried. This records that an outcome is unknown. It never re-dispatches: the effect may already have happened, and repeating it is the one unrecoverable mistake.
reconcile_calls(scope: TaskScope, task_id: str, *, is_live: Optional[LivenessProbe] = None, min_age_seconds: float = 0.0, now: Optional[datetime] = None, reason: str = 'the owner of this call is no longer live and its outcome was never recorded; the tool may or may not have run, so this is UNKNOWN and must not be retried automatically') -> ReconcileReport
| Parameter | Type | Default | Description |
|---|---|---|---|
scope |
TaskScope |
Trusted runtime scope. | |
task_id |
str |
The task to reconcile. | |
is_live |
Optional[LivenessProbe] |
None |
Tri-state liveness probe. None means no probe is available, in which case nothing is reconciled — refusing to guess is the point. |
min_age_seconds |
float |
0.0 |
Grace period. A call younger than this is left alone even if it looks dead, so a claim that has not yet been written cannot be raced. |
now |
Optional[datetime] |
None |
Injected clock, for deterministic tests. |
reason |
str |
'the owner of this call is no longer live and its outcome was never recorded; the tool may or may not have run, so this is UNKNOWN and must not be retried automatically' |
Text recorded on the event. |
Returns: ReconcileReport — class:ReconcileReport distinguishing every skip reason.
Raises:
-
ScopeViolation— If the task does not exist in this scope.
Return how many events a task's journal holds.
count_events(scope: TaskScope, task_id: str) -> int
| Parameter | Type | Default | Description |
|---|---|---|---|
scope |
TaskScope |
Trusted runtime scope. | |
task_id |
str |
The task to measure. |
Returns: int — The event count, or 0 when the task does not exist in this scope.
Delete one terminal task's journal and projection.
Implements :class:~..retention.JournalPurge. Two guards make
this safe to call from a sweeper that may be racing anything
else in the system:
Only a terminal task is ever purged. Retention only selects terminal tasks, but the check is repeated here because this is the last point before the rows are gone. A task that was resumed between selection and purge is left alone — the sweeper's view is a snapshot, and acting on a stale one is exactly how live work gets deleted.
Pins held by other tasks survive. Deleting the row cascades
to this task's task_journal and artifact_evidence rows
only. A version another, still-live task references keeps that
task's evidence row, so it stays pinned and is not swept
afterwards. The artifact rows themselves are never touched here.
.. warning::
This destroys the local audit trail, including the
retention_scheduled event recording the intent to destroy
it. With archive_uri configured the archive carries that
final event; without one the deletion is deliberately
irreversible. Nothing in this method preserves in-journal
audit, and it does not pretend to.
purge_task(scope: TaskScope, task_id: str) -> bool
| Parameter | Type | Default | Description |
|---|---|---|---|
scope |
TaskScope |
Trusted runtime scope. | |
task_id |
str |
The task to remove. |
Returns: bool — True when rows were removed. Idempotent: purging an already-purged task returns False rather than failing, so a retry after a crash converges instead of erroring.
Return every storage key an index row still points at.
This is the "live index" half of the orphan rule. A blob absent from this set is not automatically an orphan — a publish may be in flight, or an archive may reference it — but a blob present in it is definitively not one.
live_storage_refs(scope: TaskScope) -> FrozenSet[str]
| Parameter | Type | Default | Description |
|---|---|---|---|
scope |
TaskScope |
Trusted runtime scope. |
Returns: FrozenSet[str] — The referenced storage keys.
One unit of work, bound to exactly one pooled connection.
Satisfies the :class:~parrot.interfaces.task_memory.Transaction
protocol. The connection is exposed so that the task store and the
artifact store write through the same one — that shared connection
is the whole point of the coordinator, and the reason an artifact's
index row, its evidence rows and its journal event become visible
together or not at all.
| Parameter | Type | Default | Description |
|---|---|---|---|
connection |
'asyncpg.Connection' |
The pooled connection this unit of work runs on. | |
transaction |
Any |
The driver-level transaction object. |
Attributes:
| Attribute | Type | Description |
|---|---|---|
connection |
'asyncpg.Connection' |
The connection every enlisted store must use. |
is_active |
bool |
Whether this transaction is still open. |
Abandon the unit of work, discarding every change made in it.
Idempotent: rolling back an already-finished transaction is a no-op, so a cleanup path never has to guess whether it ran.
rollback() -> None
Hands out transactions the task and artifact stores share.
Satisfies
:class:~parrot.interfaces.task_memory.TransactionCoordinator.
| Parameter | Type | Default | Description |
|---|---|---|---|
store |
'PostgresTaskMemoryStore' |
The store whose pool supplies connections. |
Open a transaction, committing on clean exit, rolling back on error.
begin() -> AsyncIterator[PostgresTransaction]
Returns: AsyncIterator[PostgresTransaction]
Raises:
-
TaskMemoryUnavailable— If no pool is configured.
Type: Tuple[str, ...]
What one reconciliation pass actually did.
Every bucket is reported separately, because "did nothing" has three very different meanings and collapsing them would hide the case this task exists to protect.
There is deliberately no already_resolved bucket. The unresolved
set is read inside the task lock, so a call another reconciler has
already settled is simply not in it — scanned drops instead. A
field that could never be populated would imply a distinction this
design does not make.
| Parameter | Type | Default | Description |
|---|---|---|---|
scanned |
int |
0 |
|
reconciled |
Tuple[str, ...] |
() |
|
alive |
Tuple[str, ...] |
() |
|
unknown_liveness |
Tuple[str, ...] |
() |
|
too_young |
Tuple[str, ...] |
() |
Fields:
| Field | Type | Default | Description |
|---|---|---|---|
scanned |
int |
0 |
Unresolved calls considered. |
reconciled |
Tuple[str, ...] |
() |
Calls newly recorded as tool_outcome_unknown. |
alive |
Tuple[str, ...] |
() |
Calls skipped because their owner still holds them. |
unknown_liveness |
Tuple[str, ...] |
() |
Calls skipped because liveness could not be determined. Not reconciled — an unreachable cache is not evidence of death. |
too_young |
Tuple[str, ...] |
() |
Calls skipped as inside the grace period. |
Attributes:
| Attribute | Type | Description |
|---|---|---|
changed |
bool |
Whether this pass appended anything. |
Type: str
Type: Tuple[str, ...]
A call the journal shows starting but never finishing.
Being unresolved says nothing about whether the call is alive. It is the question recovery asks, not the answer.
| Parameter | Type | Default | Description |
|---|---|---|---|
call_id |
str |
||
tool_name |
str |
||
started_at |
datetime |
||
started_seq |
int |
||
step_id |
Optional[str] |
None |
|
turn_id |
Optional[str] |
None |
|
parent_call_id |
Optional[str] |
None |
|
attempt |
int |
1 |
|
is_aggregate |
bool |
False |
Fields:
| Field | Type | Default | Description |
|---|---|---|---|
call_id |
str |
The physical attempt. | |
tool_name |
str |
The tool it dispatched, as recorded at start. | |
started_at |
datetime |
When tool_started was persisted. |
|
started_seq |
int |
Its journal sequence. | |
step_id |
Optional[str] |
None |
The step it was attributed to, if any. |
turn_id |
Optional[str] |
None |
The turn it belonged to. |
parent_call_id |
Optional[str] |
None |
Its parent aggregate, if any. |
attempt |
int |
1 |
The attempt number recorded at start. |
is_aggregate |
bool |
False |
Whether other calls name it as their parent. An aggregate is not a physical attempt and must not be counted as one. |
Return the path of the packaged migration file.
migration_path() -> Path
Returns: Path — Absolute path to migrations/001_task_memory.sql.
Read the packaged migration file.
read_migration() -> str
Returns: str — The file's full text.
Raises:
-
TaskMemoryUnavailable— If the migration is missing from the installed package. A durable deployment without its schema definition cannot be made durable, so this fails loudly at startup rather than at the first append.
Split the migration into its UP and DOWN halves.
split_migration(sql: Optional[str] = None) -> Tuple[str, str]
| Parameter | Type | Default | Description |
|---|---|---|---|
sql |
Optional[str] |
None |
Migration text; read from the package when None. |
Returns: Tuple[str, str] — A (up_sql, down_sql) pair, each stripped.
Raises:
-
TaskMemoryUnavailable— If either fence is missing or malformed. A migration whose DOWN half cannot be located is, for operational purposes, an irreversible one — better to refuse it than to discover that during a rollback.
- 1. MCP Server — exposing tools as a service
- 2. A2A — exposing agents and orchestrators as services
- 3. Toolkits for third party services and Cloud Security composition
- 4. Interaction surface — WebSockets, audio, integrations
- 5. Hardening — anti prompt injection, PBAC and tool gating
- 6. Cross cutting concerns and reference deployment
- 7. AgentCrew — Sequential, Parallel, Flow and Loop execution
- 8. AgentsFlow — DAG first orchestration with per node FSM
- 9. Ontologic RAG — graph first retrieval, intent routing & multi tenant knowledge
- 10. Observability — OpenLIT + OpenTelemetry
- Class Catalog by Module
- Module level Functions Catalog
- AI Parrot — Exposure, Interoperability & Hardening Architecture
- Agent Mesh
- AgentService — Standalone Runtime for Autonomous Agents
- AbstractClient: The Provider Client Family
- Anthropic client
- Bedrock Mantle Client
- TypeSafe System One Client (
JevClient) - Meta Model API Client (Muse Spark)
- OpenAI Compatible Client Base (
OpenAIBaseClient) - Per Loop LLM Client Cache
- Question Token Budgets (Bedrock Converse, Nova text, Bedrock Mantle)
- Agent Configure Lifecycle
- AgentTalk Integration Guide
- Agent Configuration via
agents.yaml - AgentFactory HTTP API
- Agent Studio — API Reference
- Agent CLI Daemon (agentd)
- FirefliesInsightsAgent
- Follow up Suggestion Chips (FEAT 752)
- Agents and Chatbots: The Bot Class Hierarchy
- Agent Studio — database storage (host guide)
- Ephemeral User Agents — Frontend Integration Handoff
parrot agent— Agent Terminal Workspace- Crew Handler
- Database Agent
- Running the CVE Experts
- Domain Experts (FEAT 778)
- FEAT 437
- Technical Voice Guide (AgentTalk Voice) for Frontend
- AgentDashboard — A2UI v1.0 Technical Reference for
navigator frontend next - Semantic UI Model → Adaptive Cards (FEAT 303)
- Exposing an AI Parrot Agent as an MCP Server
- AgentCrew User Guide
- AgentsFlow User Guide
- Crew Definition Storage
- A2UI Agent Functions Runtime — the v1.0 RPC leg (FEAT 469)
- Capabilities of an AI Parrot Analytical Agent (PandasAgent)
- Agent Security Guardrails (FEAT 761)
- SpawnSubAgentTool
- Testagent
- Agentic End to End Testing (FEAT 581)
- Uiagent
- WebAgent — Browser Interaction via Chrome DevTools
- WebNavigatorAgent — Catalogued Web Navigation on Your Chrome Profile
- ExecutionMemory Integration Guide
- Agent Brain
- Agent Memory
- Conversation History Ownership
- Conversation Memory Subsystem Overview
- Dream Cycle — episodic → wiki brain consolidation
- Durable Conversation Memory
- Memory Dynamics
- Per Turn Conversation Compaction
- Recoverable Task Memory (FEAT 538)
- Task Memory — Phase 0 Integration Map (FEAT 538 / TASK 2970)
- User Memory
- Bookstore Agentic Retrieval
- Bookstore in Codex
- Bookstore Conceptual Relations — the book graph (FEAT 533)
- Bookstore notebooks
- Contracts catalog performance (FEAT 539, AC14)
- Contracts pilot acceptance — Bob's twelve cases (FEAT 539, AC15)
- Contracts Card & Ontology (FEAT 539)
- Luau parser resource policy (FEAT 532 TASK 2896)
- Glossary of Terms (FEAT 917)
- GraphIndex core seams (FEAT 540)
- GraphIndex — Structured Knowledge Graph Indexing
- Local Knowledge Base
- Procedure Graph — Assembly Manuals (FEAT 601)
- Ontology backend programme
- Ontology vocabulary store
- PageIndex Agentic Retrieval and Citations
- PageIndex Generation Publication
- PageIndex Layout Structure Builder
- PageIndex Local MCP Toolkit
- PageIndex Segment Store
- PageIndex Tree Optimizer
- PageIndex — Tree Based RAG for Document Retrieval
- ArxivTool for AI Parrot
- Accounting metrics layer
- Tool Result Compression Pipeline (FEAT 380)
- DatasetManager Implementation Walkthrough
- FredAPITool Documentation
- EmployeesTool Employee Hierarchy Tool for AI Parrot
- HoobaToolkit
- Jira text templates (JiraToolkit)
- Expose Toolkits as Local MCP (
parrot mcp local) - MultiStoreSearch Toolkit — Multi Origin Retrieval for Agents
- Supervised Obscura Browser Integration
- OdooHelpdeskToolkit — Softhealer helpdesk on Odoo 19
- OdooToolkit Capabilities
- QuerysourceToolkit
- ReadOnlyRepoToolkit (FEAT 484)
- PythonREPLTool Sandbox: Worker Process Execution Model
- Research Tools for Agents
- gVisor Installation Guide for AI Parrot Secure Sandbox
- SDD Sandbox — OS Setup
- Governed semantic layer
- Tool optimizations for Claude Code and Codex (FEAT 543)
- AbstractTool Clone Method
- Toolbar API Documentation
- AudioNoteCaptureToolkit
- ExecutionPlanToolkit — Reference
- Host toolkits for Agent Studio
- Infographic Authoring for Data Agents (FEAT 326)
- InfographicToolkit — Reference
- Tool System Internals: Tools, Toolkits and ToolManager
- AI Parrot Tools Documentation
- What If Scenario Analysis
- Workday worker history
- DecisionFlowNode Usage Guide
- Multi Agent Orchestration: AgentCrew and AgentsFlow
- Docker Tool Executor & Execution Policy
- Generic Gate Host
- HeartbeatManager — Per Agent Autonomous Heartbeat Loop
- JobManager
- Node Types Reference
- OrchestratorAgent — Multi Party Conferencing (
confer) - Planogram compliance cycle (perceive → identify → compare)
- Planogram compliance — migrating configurations to the new cycle (FEAT 574, FEAT 612)
- Planogram perception spike — FEAT 574
- Scheduler backends in multi worker deployments
- Thales User Guide
- Per tenant skills (FEAT 707)
- Skill routing and trigger caching
- Skills system: discovery, toolkits and mixin
- Contextual Embedding Headers
- DocumentDB Usage Patterns
- DocumentDB Interface Guide
- DynamoDB Local (docker compose)
- Fully offline local agent with LanceDB (FEAT 542)
- LanceDB vector, full text and hybrid store (FEAT 542)
- Loader Metadata Standard
- Document Loaders for RAG
- Matryoshka Embedding Truncation
- Parent Child Retrieval (Small to Big)
- Storage Backends Guide
- User stores (Redis by default)
- Vector Stores and Embeddings Reference
- Vector Store Handler — API Reference
- A2A Secure Communication Demo
- Agent as a Local MCP Server (parrot toolkits install agent)
- add repository:
- GitHub MCP Installation and Usage
- MCP integration: client, server and agent tools
- Create and configure agent
- Roost — local inter agent sub protocol
- Roost carriers
- Roost performatives, protocols and obligations
- Simple Mcp Server
- SimpleMCPServer Configuration
- API Endpoints Reference
- Admin UI (FEAT 468)
- Infographic Render Endpoint — Reference
- EventBus v2 Configuration Reference (
[bus]/[bus.alerts]) - EventBus v2 Migration Notes (FEAT 310)
- EventBus v2 — Unified Event Fabric (FEAT 310)
- Session file store
- A2UI Dashboard + Widget Renderer — Frontend Build Guide
- Avatar Technical Guide (LiveAvatar Phase A) for Frontend
- Frontend Guide for SvelteKit: LiveAvatar FULL Mode and VoiceBot (FEAT 248)
- DEPRECATED: Native Voice Avatar (LiveAvatar Phase C) Technical Guide for Frontend
- Technical Guide to Structured Artifacts for Frontend
- VoiceBot · VoiceChatHandler · FEAT 245 — Frontend Guide for Realtime Conversation with Agents
- Server Layer: BotManager and HTTP Handlers
- Infographic Handler — Frontend API Contract
- Interactive Artifacts — Frontend API Contract
- Google Drive file manager
- SharePoint & OneDrive file managers
- WhatsApp Integration Implementation Summary
- WhatsApp Integration for AI Parrot
- P3 — parrot admin ui inventory (canvases / A2UI / infographic / builders)
- WhatsApp + AutonomousOrchestrator Integration
- Audio Form Voice Modes — Developer Guide
- Who owns an OAuth2 (3LO) credential
- CommCenter — Bulk Notification Sender (FEAT 417)
- FormDesigner → MS Teams: Adaptive Card renderer and bot submit path (FEAT 551)
- GitHub reviewer
- Google OAuth 2.0 — AI Parrot Integration
- Fireflies Agent Examples
- HITL Tool Call Confirmation (FEAT 235)
- Teams HITL Channel Setup Guide (FEAT 205)
- JiraSpecialist Prompt Layer Stack
- JiraSpecialist — Daily Standup Lanes
- Jira Transition Actions — Activating
TRIGGER_AGENTDispatch - Jupyter Output Mode Documentation
- Knowledge upload from chat (FEAT 647)
- LiveAvatar over your own LiveKit (Cloud or self hosted)
- Matrix Bridges for the AI Parrot Swarm (FEAT 463)
- Matrix Clients for the AI Parrot Swarm (FEAT 463)
- Migration Guide: FEAT 202 — ai parrot integrations
- Connections on Microsoft Teams
- MS Teams Toolkit for AI Parrot
- Nova Sonic Voice Protocol Reference
- Office 365 OAuth 2.0 (Delegated) — AI Parrot Integration
- PR Review Command — Setup Guide
- Queued chat commands
- Runbook — the
issuesnamespace (Jira ticket corpus) - Dev loop kick off from Slack (FEAT 555)
- Telegram Auth Open Mode (webview | browser)
- Telegram connections
- Telegram Bot Integration Guide
- FEAT 536 — VoiceBot Nova Dual Output + LiveAvatar: Real Live Operational Acceptance
- FEAT 537 — Nova VoiceBot avatar broadcast: operational acceptance
- FEAT 537 — Nova PCM → LiveAvatar LITE → LiveKit multi subscriber live gate
- speech_report TTS backends
- Nova VoiceBot avatar broadcast for multiple browsers (FEAT 537)
- 🦜 AI Parrot Voice Chat
- WhisperX Setup Guide for AI Parrot
- A2UI Linked Surfaces (FEAT 598)
- A2UI v1.0 Wire (FEAT 470)
- === D3.js ===
- Backend HTML Design System (FEAT 493)
- FEAT 488
- FormDesigner Audio Renderer
- Form Designer — Autonomous FormSchema Persistence (Standalone Forms)
- Form Designer — Conditional Sections: Pre/Post Dependencies
- FormBuilder — LLM answer plausibility enforcement
- FormDesigner — orphan upload cleanup (FEAT 731)
- FormDesigner — public response controls
- Form Designer — Relational Fields
- Serving FormDesigner forms from a Teams agent
- Form Designer — Unknown Field Capture Policy for Form Submissions
- FormDesigner — validation audit trail
- Infographic Recipes (FEAT 324)
- Inline A2UI Component Routing (FEAT 755)
- Metric Definition Registry (FEAT 756)
- Smart OutputFormatter Documentation
- N4 — navigator api backend inventory (dashboards / widgets / templates / modules / programs)
- P1 — ai parrot HTTP/WS endpoint inventory (report builder lens)
- P2 — ai parrot (Python) UI components, models, renderers, persistence — inventory for a REPORT BUILDER
- P4 — ai parrot prior art for a Report Builder (SDD inventory)
- ai parrot server — Admin / Bots / Studio / misc endpoint inventory
- P1 — ai parrot HTTP/WS endpoint inventory (report builder lens) ( core)
- parrot formdesigner — HTTP/WS endpoint inventory
- Report Builder — ai parrot inventory and analysis
- WeasyPrint 69.0 CSS Support — Empirical Findings
- Identity Capability User Guide
- Layers Reference
- Output Language (FEAT 638)
- PromptBuilder — User Modifiable Variables
- PromptBuilder User Guide
- Delegated OAuth2 connections
- Delegated OAuth2 connections on the web channel — deployment recipe and live harness
- Deterministic Groundedness Scoring
- ONNX Backend for the Prompt Injection Guardrail (FEAT 439)
- PBAC Guardrails — Policy Driven Tool Call Denial (FEAT 406)
- SecurityAdvisor — SOC2 Oriented Read Only Advisory Agent
- User Profile Management
- AI Parrot MCP Server AWS Deployment Guide
- Bot Cleanup Lifecycle
- Business Automation — Operator Runbook
parrot loginand connections- CompanyInfoToolkit
- Per component and per agent LLM defaults (FEAT 796, FEAT 882)
- Answer Accuracy Metrics for the Evaluation Harness (FEAT 652)
- Infographic CSP and Signed URLs — Operations Guide
- Global install: the parrot managed runtime (reference)
- Runbook — the Fireflies Meeting Registry
- Wiki standup briefs — runbook
parrot.finance— the finance satellite- Migration — FEAT 201: ai parrot embeddings
- Migration — FEAT 203: ai parrot server
- FEAT 223 — Structured Artifact Contract: Migration Guide
- FEAT 273 — Legacy output mode deprecations → A2UI
- Migration — FEAT 315: Unified NovaClient for all Amazon Nova models
- Migration — FEAT 421: Client declared tenant in the forms URL
- Migration — FEAT 446: SaaS Auth Hardening (S0 of Parrot Research Cloud)
- Migration — FEAT 473: A2UI v1.0 for STRUCTURED_CHART / STRUCTURED_TABLE / STRUCTURED_MAP
- Migration — FEAT 523: PEP 420 LLM Client Extraction
- Gemini 2.5 retirement (FEAT 798)
- Migration — FEAT 564: Reliable video reels with Gemini Omni and Veo 3.1
- Native Claude sandbox for SDD sessions (FEAT 768)
- Complementary (collaborative) research partner (FEAT 482)
- Dev flow per seat LLM configuration (
DevFlowModelPlan) - Dev loop
novabackend (AWS Bedrock) - sdd worker as orchestrator of parallel sdd coder seats (FEAT 549)
- SDD compaction capability record
- SDD execution optimization — operation and rollout
- Proposals to Reduce SDD Execution Time
- Dev flow / dev loop telemetry accounting
- Language Agnostic Validation Runners (FEAT 709)
- Spec Driven Development in Google Gemini / Antigravity CLI
- Guide to using the SDD slash commands
- AI Parrot Spec Driven Development (SDD) Platform
- SDD on Google Antigravity (agy)
/sdd donecloseout hooks- Decision Audit (FEAT 784)
- SDD experience memory
- SDD Expert Consult
- Ledger outbox (FEAT 758)
- FEAT 580 LSP Pilot — Live Evaluation Results
- SDD LSP research pilot (FEAT 580)
- Necessity Ladder (FEAT 908)
- Procedure Graph
- Test selection in the SDD flow — the Validation Contract (FEAT 699)
- wikitoolkit Cheatsheet
- wikitoolkit inbox
- wikitoolkit lint
- LLM Wiki — an agent maintained knowledge repository
- Schema Plane — Operator Guide (FEAT 600)
- SQLite concurrency for wiki and ledger
- wikitoolkit standup
- WikiToolkit as Claude Code infrastructure
- Authentication uses Navigator Auth
- AbstractClient base changes require a decision
- Clients are memory less
- Configuration uses NavConfig
- Graph backends — retire ArangoDB for PostgreSQL + SurrealDB
- Conversation history has one writer
- HTTP stack uses aiohttp
- LangChain is not part of the stack
- Async code remains non blocking
- Concrete tools live in ai parrot tools