diff --git a/docs/reference/README.md b/docs/reference/README.md
index df6f92ccfe59..b2553fe3ccda 100644
--- a/docs/reference/README.md
+++ b/docs/reference/README.md
@@ -15,7 +15,7 @@ writing both marks, not editing the page and leaving the rule to look broken.
|---|---|
| [kiro-cli/](kiro-cli/README.md) | The `kiro-cli` documentation, taken from the 2.x line. kiro-cli is Kiro Crew's required agent backend, so its ACP surface, agent-spec schema, and MCP config shape are load-bearing here. |
| [ledger-conductor-sequence.md](ledger-conductor-sequence.md) | **Named exception — local page, no upstream.** Kiro Crew's own end-to-end sequence for the work-ledger dispatch lifecycle. Preserve it across a re-fetch. |
-| [ledger/](ledger/README.md) | **Named exception — local pages, no upstream.** API-style reference for the append-only ledger: envelope, session entry types, crew entry types, the reader and writer surface, and the error codes. Preserve it across a re-fetch. |
+| [crew-log/](crew-log/README.md) | **Named exception — local pages, no upstream.** API-style reference for the append-only crew log: envelope, session entry types, crew entry types, the reader and writer surface, and the error codes. Preserve it across a re-fetch. |
Where Kiro Crew's own behavior differs from a mirrored page, Kiro Crew's docs win:
this fork is KiroACP-only and does not use every capability the upstream CLI
diff --git a/docs/reference/ledger/README.md b/docs/reference/crew-log/README.md
similarity index 77%
rename from docs/reference/ledger/README.md
rename to docs/reference/crew-log/README.md
index 872f6b10fb4a..6be9f2838629 100644
--- a/docs/reference/ledger/README.md
+++ b/docs/reference/crew-log/README.md
@@ -1,10 +1,10 @@
-# Ledger reference
+# Crew log reference
**Local page, not a mirror.** This directory is Kiro Crew's own documentation and
has no upstream source, so a re-fetch of the `kiro-cli/` mirror must leave it
alone. It is marked as a named exception in [the Reference index](../README.md).
-A ledger is one append-only JSONL file per unit. A writer adds lines to the end
+A crew log is one append-only JSONL file per unit. A writer adds lines to the end
and never rewrites a line already there, so the file — not a context window, not
a summary — is the authority for what happened to that unit. Every line after the
first carries a writer-assigned `seq` that is contiguous from 1 within the file,
@@ -12,56 +12,56 @@ so a reader folds the lines in `seq` order and gets exactly one reading of the
unit's history.
These pages say WHAT the format is. For WHY it is shaped this way, read
-[`ledger-core.md`](../../system-specs/modules/ledger-core.md) and
-[`session-ledger-emitter.md`](../../system-specs/modules/session-ledger-emitter.md).
+[`crew-log-core.md`](../../system-specs/modules/crew-log-core.md) and
+[`crew-log-emitter.md`](../../system-specs/modules/crew-log-emitter.md).
## Contents
| Page | What it covers |
|---|---|
| [envelope.md](envelope.md) | File layout, header fields, the eight common entry fields, `ref` and `thread`. Kind-independent. |
-| [session-types.md](session-types.md) | Every session ledger entry type, one subsection each, with fields and an example. |
-| [crew-types.md](crew-types.md) | The crew ledger's type families and the two dispatch contracts. |
+| [session-types.md](session-types.md) | Every session log entry type, one subsection each, with fields and an example. |
+| [crew-types.md](crew-types.md) | The crew's log's type families and the two dispatch contracts. |
| [reading-and-writing.md](reading-and-writing.md) | Reader API, writer rules, ownership, and the fail-soft emitter. |
| [errors.md](errors.md) | Every `LedgerError` code, its trigger, and what a caller does about it. |
## Glossary
-**ledger** — the storage layer (`kiro_crew.ledger`): a file format, the rules for
+**crew log** — the storage layer (`kiro_crew.crew_log`): a file format, the rules for
who may write what, and the read-back paths. "Append-only log" names the same
-thing; these pages say *ledger* throughout.
+thing; these pages say *crew log* throughout.
-**unit** — the thing a ledger belongs to. One unit, one ledger.
+**unit** — the thing a crew log belongs to. One unit, one crew log.
-**kind** — which of the two unit types a ledger is: `crew` or `session`. A kind
+**kind** — which of the two unit types a crew log is: `crew` or `session`. A kind
decides which `type` domains may be written to the file and which `src` values may
write them.
-**session ledger** — a `session`-kind ledger, keyed by an ACP session id,
+**the session's log** — a `session`-kind crew log, keyed by an ACP session id,
recording one session's turn lifecycle. [session-types.md](session-types.md)
covers it.
-**crew ledger** — a `crew`-kind ledger. Same envelope, different type domains, and
+**the crew's log** — a `crew`-kind crew log. Same envelope, different type domains, and
the place `thread` and guest-namespaced types are used.
[crew-types.md](crew-types.md) covers it.
**entry** — one line after the header: an envelope plus a type-specific `data`
object.
-**segment** — one physical file in a unit's ledger. A unit's history may span
+**segment** — one physical file in a unit's crew log. A unit's history may span
several, read oldest first. Every segment repeats the header.
**opener / closer** — a pair of types where one records that something started and
the other that it ended. A closer is what makes an interrupted opener detectable.
-## What a ledger is not
+## What a crew log is not
It is not the **SEL security audit log**, which records security-relevant
decisions for an auditor and answers a different question.
It is not a **session transcript**. Transcripts are message-grain, are rewritten
by rotation and compaction, and are a best-effort shadow of what a session slot
-held. A ledger is operation-grain and append-only.
+held. A crew log is operation-grain and append-only.
It is not the **per-turn usage row store**, which measures token and credit cost
per turn for reporting.
@@ -73,17 +73,17 @@ fact to both.
## The pointer model
-An entry cites another ledger with `ref`. A session's header points back at the
+An entry cites another crew log with `ref`. A session's header points back at the
crew row that dispatched it with `thread`. Neither copies bytes: both name a
location, and a reader that wants the content goes and reads it.
```mermaid
flowchart LR
- subgraph crew["crew ledger — crews/<store name>/ledger.jsonl"]
+ subgraph crew["the crew's log — crews/<store name>/log.jsonl"]
D["seq 41 · crew/dispatch
data.target → a session"]
R["seq 58 · crew/report
thread: 41
ref: {unit: session, id: s-7f3a, from: 12, to: 40}"]
end
- subgraph sess["session ledger — sessions/<store name>/ledger.jsonl"]
+ subgraph sess["the session's log — sessions/<store name>/log.jsonl"]
H["line 1 · header
thread: {crew: qa, seq: 41}"]
S["seq 12 … seq 40
the cited segment"]
end
@@ -95,7 +95,7 @@ flowchart LR
Two things are worth reading off that diagram. The `ref` is the one deliberate
cross-kind pointer: a crew entry cites a span of a session's file. The `thread` is
always within-file — `crew/report` threads onto `crew/dispatch` because both are
-lines in the crew ledger — except on the session *header*, where `thread` is a
+lines in the crew's log — except on the session *header*, where `thread` is a
back-pointer naming a row in another unit and is spelled `{crew, seq}` rather than
a bare int.
@@ -113,7 +113,7 @@ from a cached counter. A second process that tries to append gets
segments mid-chain is damage, not a pruned log:
[`segment_gap`](errors.md#segment_gap).
-**Crash closers are deterministic.** Opening a session ledger with repair on
+**Crash closers are deterministic.** Opening a session's log with repair on
truncates a torn tail, drops a trailing orphan chunk run, and writes one closer
per still-open opener with a fixed value per type. The same file always repairs to
the same bytes. See [reading-and-writing.md](reading-and-writing.md#crash-repair).
@@ -139,13 +139,13 @@ does not read, is refused: [`bad_header`](errors.md#bad_header),
[`bad_segment`](errors.md#bad_segment),
[`unsupported_version`](errors.md#unsupported_version).
-**Agent file tools cannot reach `ledgers/`.** The whole root is a fenced leaf in
+**Agent file tools cannot reach `crew-log/`.** The whole root is a fenced leaf in
the shared sensitive-path floor, so a prompt-injected agent cannot read another
-unit's history or forge a line into its own. The ledger's own code opens the files
+unit's history or forge a line into its own. The crew log's own code opens the files
directly and is unaffected.
**Session emission is off by default.** The session emitter is inert unless
-`KIROCREW_SESSION_LEDGER` is truthy. With the flag unset no ledger directory is
+`KIROCREW_CREW_LOG` is truthy. With the flag unset no crew log directory is
created and no emit path reaches storage.
**The format is PRE-RELEASE.** Shapes may change while the flag is off by default.
diff --git a/docs/reference/ledger/crew-types.md b/docs/reference/crew-log/crew-types.md
similarity index 88%
rename from docs/reference/ledger/crew-types.md
rename to docs/reference/crew-log/crew-types.md
index 62eb072b0817..1ed1f8669af2 100644
--- a/docs/reference/ledger/crew-types.md
+++ b/docs/reference/crew-log/crew-types.md
@@ -1,25 +1,25 @@
-# Crew ledger entry types
+# The crew's log entry types
-**Local page, not a mirror.** Part of the [ledger reference](README.md), which is
+**Local page, not a mirror.** Part of the [crew log reference](README.md), which is
marked as a named exception in [the Reference index](../README.md).
> **No crew emitter exists.** The families and the two contracts on this page are
> the specified shape a crew writer must produce. The `crew/dispatch` and
> `crew/report` contracts are defined here and in
-> [`ledger-core.md`](../../system-specs/modules/ledger-core.md); a validator that
+> [`crew-log-core.md`](../../system-specs/modules/crew-log-core.md); a validator that
> refuses a malformed one is pending. Treat every field rule below as the
> agreement, not as something the code enforces today.
-A crew ledger uses the same file layout, the same header rules and the same eight
-envelope fields as a session ledger — [envelope.md](envelope.md) covers all of
+A crew's log uses the same file layout, the same header rules and the same eight
+envelope fields as a session's log — [envelope.md](envelope.md) covers all of
that. Three things differ: which `type` domains may be written, which `src` values
may write them, and the fact that `thread` and `ref` are actually used.
## The layering rule
There is one base envelope, then two disjoint sets of types on top of it. A type
-belongs to exactly one kind, and the kind of the ledger decides whether a type may
-be written to it at all. Writing a crew-owned type into a session ledger is refused
+belongs to exactly one kind, and the kind of the crew log decides whether a type may
+be written to it at all. Writing a crew-owned type into a session's log is refused
with [`event_type_not_owned`](errors.md#event_type_not_owned), and the reverse is
refused the same way.
@@ -46,14 +46,14 @@ A crew entry is written by one of:
| `dashboard` | The dashboard, acting for the person using it. |
| `patrol` | A patrol pass. |
| `gateway` | The gateway itself. |
-| `crew:` | A named crew, writing into its own crew ledger. |
-| `app:` | A named app, writing only its own `app:/…` types, and only into a crew ledger. |
+| `crew:` | A named crew, writing into its own crew log. |
+| `app:` | A named app, writing only its own `app:/…` types, and only into a crew log. |
`dashboard` and `patrol` are crew-side values: a session entry is written with
`gateway` or `acp` and nothing else.
A guest's own name is its write permission. A `crew:` writer may write
-crew-owned types into that crew's ledger; an `app:` writer is confined to its
+crew-owned types into that crew's crew log; an `app:` writer is confined to its
own namespace. Writing outside it is
[`namespace_violation`](errors.md#namespace_violation), and an unparseable `src` is
[`bad_src`](errors.md#bad_src).
@@ -67,7 +67,7 @@ registry change.
| Family | Types | What it points at |
|---|---|---|
| shipped | `member/*`, `activity/record`, `slot/*`, `patrol/*` | `slot/*` cites the session it shipped. |
-| messages | `message/received`, `message/sent` | The redacted body is in the ledger; a permalink reply cites its anchor with `ref`. |
+| messages | `message/received`, `message/sent` | The redacted body is in the crew log; a permalink reply cites its anchor with `ref`. |
| tree | `crew/child-attached`, `crew/parent-attached`, and their `-detached` counterparts | — |
| dispatch | `crew/dispatch`, `crew/report` | A report cites the child's segment. |
| topics | `crew/topic-*`, `crew/forwarded`, `crew/run-state` | A topic cites its work session. |
@@ -130,7 +130,7 @@ A dispatched party reported back on one work item.
**Envelope requirements** — Unlike every other type documented here, `crew/report`
constrains the envelope as well as `data`:
-- **`ref` is required.** It cites the segment of the child's ledger holding the
+- **`ref` is required.** It cites the segment of the child's crew log holding the
work, so a report is never a claim without evidence. The span cap of 500 lines
(`MAX_REF_SPAN`) applies, so a long run is cited by its relevant span rather than
in full.
@@ -144,6 +144,6 @@ appear several times for one dispatch; a terminal status appears once.
```
**Reader hint** — Resolve the `ref` to read the work itself, and handle all four
-statuses the resolution can answer with — the cited ledger may be gone or pruned
+statuses the resolution can answer with — the cited crew log may be gone or pruned
long after the report was written. See
[reading-and-writing.md](reading-and-writing.md#resolving-a-ref).
diff --git a/docs/reference/ledger/envelope.md b/docs/reference/crew-log/envelope.md
similarity index 85%
rename from docs/reference/ledger/envelope.md
rename to docs/reference/crew-log/envelope.md
index 41b047955e50..05a20db654e1 100644
--- a/docs/reference/ledger/envelope.md
+++ b/docs/reference/crew-log/envelope.md
@@ -1,21 +1,21 @@
# Envelope
-**Local page, not a mirror.** Part of the [ledger reference](README.md), which is
+**Local page, not a mirror.** Part of the [crew log reference](README.md), which is
marked as a named exception in [the Reference index](../README.md).
-Everything here is kind-independent: it holds for a session ledger and a crew
-ledger alike. What differs between the two kinds is which `type` domains and which
+Everything here is kind-independent: it holds for a session's log and a crew's
+log alike. What differs between the two kinds is which `type` domains and which
`src` values are allowed, which [session-types.md](session-types.md) and
[crew-types.md](crew-types.md) cover.
## File layout
```
-/ledgers/crews//ledger.jsonl
-/ledgers/sessions//ledger.jsonl
+/crew-log/crews//log.jsonl
+/crew-log/sessions//log.jsonl
```
-`ledgers` is one shared root for both kinds, which is what lets a single fence
+`crew-log` is one shared root for both kinds, which is what lets a single fence
entry cover every unit kind at once. Under it, `crews/` holds crew units and
`sessions/` holds session units.
@@ -29,14 +29,14 @@ Each unit directory holds:
| Path | What it is |
|---|---|
-| `ledger.jsonl` | The segment whose first entry is `seq` 1. The only segment a writer creates. |
-| `ledger..jsonl` | A later segment. The filename's middle is its first entry's `seq`, all digits and greater than 1. |
+| `log.jsonl` | The segment whose first entry is `seq` 1. The only segment a writer creates. |
+| `log..jsonl` | A later segment. The filename's middle is its first entry's `seq`, all digits and greater than 1. |
| `.lock` | The append lock. Held only for the duration of one append, and it is what makes `seq` assignment serial. |
| `.lease` | The write-ownership lease. Held for as long as a handle can still append. See [reading-and-writing.md](reading-and-writing.md#ownership). |
Line 1 of a segment is a header object. Every later line is an entry. **Every
segment repeats the header**, not just the first one, so a unit whose oldest
-segment is gone is still a readable ledger. A reader validates each segment's
+segment is gone is still a readable crew log. A reader validates each segment's
header against the unit it opened and checks that the filename's declared first
`seq` matches the segment's first readable entry.
@@ -56,7 +56,7 @@ Common to both kinds:
| `type` | string | required | The unit kind this file belongs to. | `crew`, `session` |
| `version` | int | required | Header schema version. A file declaring a version this build does not read is refused with [`unsupported_version`](errors.md#unsupported_version). | `1` |
| `id` | string | required | The raw unit id. Must match the id the reader opened. | |
-| `createdAt` | int | required | Epoch milliseconds the unit's ledger was created. | |
+| `createdAt` | int | required | Epoch milliseconds the unit's crew log was created. | |
A **crew** header carries nothing beyond those four: a crew's identity is its id,
and every fact about it is an entry rather than a header field.
@@ -98,12 +98,12 @@ present, then `data` last.
| Field | Type | Required | Meaning | Enum |
|---|---|---|---|---|
-| `type` | string | required | `domain/action`, partitioned on the first slash. The action may not itself contain a slash, so a namespace is exactly one level deep. A guest form `app:/` exists for crew ledgers. | |
+| `type` | string | required | `domain/action`, partitioned on the first slash. The action may not itself contain a slash, so a namespace is exactly one level deep. A guest form `app:/` exists for crew logs. | |
| `seq` | int ≥ 1 | required | Writer-assigned under the unit's lock, contiguous from 1 after the header. | |
| `time` | int | required | Writer-assigned epoch milliseconds. | |
| `src` | string | required | Which emitter wrote the line. | `gateway`, `acp`, `dashboard`, `patrol`, or `session:` / `crew:` / `app:` |
| `thread` | int ≥ 1 | optional | The `seq` of an earlier entry in this same file, used as a grouping key. Refused if it names no earlier readable entry ([`bad_thread`](errors.md#bad_thread)). Session emitters never set it. | |
-| `ref` | object | optional | A citation into another or the same ledger. | |
+| `ref` | object | optional | A citation into another or the same crew log. | |
| `ignorable` | `true` | optional | The writer's promise that a reader may skip this line when it does not know the type. Only a literal `true` is written; the key is absent otherwise. | `true` |
| `data` | object | required | The type-specific payload. Must be a JSON object holding JSON-serializable values ([`bad_data`](errors.md#bad_data)). | |
@@ -130,7 +130,7 @@ written.
## `ref`
-A `ref` is a citation, not a copy: the bytes stay in the ledger they were written
+A `ref` is a citation, not a copy: the bytes stay in the crew log they were written
to, and a reader resolves the pointer when it wants them.
```json
@@ -139,7 +139,7 @@ to, and a reader resolves the pointer when it wants them.
| Field | Type | Required | Meaning | Enum |
|---|---|---|---|---|
-| `unit` | string | required | The kind of ledger being cited. | `crew`, `session` |
+| `unit` | string | required | The kind of crew log being cited. | `crew`, `session` |
| `id` | string | required | The cited unit's raw id. | |
| `from` | int ≥ 1 | required | First cited `seq`. | |
| `to` | int ≥ `from` | optional | Last cited `seq`. Absent cites the single line at `from`. | |
@@ -150,15 +150,15 @@ over-wide span — is [`bad_ref`](errors.md#bad_ref), raised when the ref is
constructed rather than when it is resolved.
Resolving a ref answers with a status rather than an exception, because a cited
-ledger may legitimately be gone or pruned. The four statuses are on
+crew log may legitimately be gone or pruned. The four statuses are on
[reading-and-writing.md](reading-and-writing.md#resolving-a-ref).
## `thread`
`thread` groups entries inside one file: it holds the `seq` of an earlier entry in
-the same ledger, and a reader pages a group by that anchor. It is validated
+the same crew log, and a reader pages a group by that anchor. It is validated
against the file at append time, so it can never name a line that does not exist
or one that comes later.
-Session entries never carry it. It is the crew ledger's shape, where a report
+Session entries never carry it. It is the crew's log's shape, where a report
threads onto the dispatch it answers.
diff --git a/docs/reference/ledger/errors.md b/docs/reference/crew-log/errors.md
similarity index 88%
rename from docs/reference/ledger/errors.md
rename to docs/reference/crew-log/errors.md
index ecb6581900ce..36685a760d6b 100644
--- a/docs/reference/ledger/errors.md
+++ b/docs/reference/crew-log/errors.md
@@ -1,9 +1,9 @@
# Errors
-**Local page, not a mirror.** Part of the [ledger reference](README.md), which is
+**Local page, not a mirror.** Part of the [crew log reference](README.md), which is
marked as a named exception in [the Reference index](../README.md).
-Every refused ledger operation raises `LedgerError` carrying a stable `code`, and
+Every refused crew log operation raises `LedgerError` carrying a stable `code`, and
`field` naming the offending input when one field is to blame. A caller branches on
`code`; the human-readable message is free to change without breaking it.
@@ -20,8 +20,8 @@ the one case where a write may have left residue, see
|---|---|---|
| [`bad_kind`](#bad_kind) | both | Requested kind is neither `crew` nor `session`. |
| [`invalid_id`](#invalid_id) | both | Unit id is empty, holds a separator or NUL, or escapes its root. |
-| [`bad_root`](#bad_root) | both | A kind's root under `ledgers` is a link or resolves outside the data home. |
-| [`already_exists`](#already_exists) | create | `create` was asked for a ledger whose file is already there. |
+| [`bad_root`](#bad_root) | both | A kind's root under `crew-log` is a link or resolves outside the data home. |
+| [`already_exists`](#already_exists) | create | `create` was asked for a crew log whose file is already there. |
| [`no_ledger`](#no_ledger) | open, append | No content-bearing segment exists. |
| [`already_owned`](#already_owned) | write | Another process owns writes to this unit. |
| [`bad_header`](#bad_header) | read | Line 1 is missing, unparseable, or names a different unit. |
@@ -52,17 +52,17 @@ The requested kind is neither `crew` nor `session`.
The unit id is empty, carries a path separator or a NUL, or resolves outside its own
root.
-A unit id names a directory, so a separator in it would let the ledger escape its
+A unit id names a directory, so a separator in it would let the crew log escape its
root. The raw id is refused loudly rather than folded to something safe: a fold would
-silently merge two units into one file, and two units sharing a ledger is worse than
+silently merge two units into one file, and two units sharing a crew log is worse than
a refused write.
**Caller action** — Refuse the operation upstream. Do not sanitize and retry.
### `bad_root`
-A kind's root directory under `ledgers` is a link, or resolves outside the data
-home's own ledger tree. The message names the directory.
+A kind's root directory under `crew-log` is a link, or resolves outside the data
+home's own crew log tree. The message names the directory.
Containment resolves its base first, so a linked kind root would make the link's
target the containment root and every path under it would pass — private history
@@ -75,14 +75,14 @@ inspect what the directory points at. Do not create or replace it automatically.
### `already_exists`
-`create` was asked for a ledger whose file is already there. Field: `id`.
+`create` was asked for a crew log whose file is already there. Field: `id`.
**Caller action** — Call `open` instead. The check runs twice, the second time under
the lock, so this code also means a racing create won.
### `no_ledger`
-`open` was asked for a ledger with no content-bearing segment. Field: `id`.
+`open` was asked for a crew log with no content-bearing segment. Field: `id`.
**Caller action** — Call `create`, or treat the unit as having no history. When it
comes from resolving a `ref`, it surfaces as the `gone` status rather than as this
@@ -90,7 +90,7 @@ error.
### `already_owned`
-Another process owns writes to this unit's ledger, so this one appended nothing.
+Another process owns writes to this unit's crew log, so this one appended nothing.
Distinct from every shape code: the entry was well formed and the file is healthy,
this process is simply not the writer.
@@ -105,7 +105,7 @@ wait. In the session emitter this is one of the paths that ends in a
### `bad_header`
Line 1 is missing, unparseable, or describes a different unit than the one asked
-for. A ledger without a readable header is not a ledger. Also raised for a non-integer
+for. A crew log without a readable header is not a crew log. Also raised for a non-integer
`createdAt` or `version`.
**Caller action** — Treat the file as damaged. Quarantine it rather than appending
@@ -163,26 +163,26 @@ match its type's contract.
### `event_type_not_owned`
-This ledger kind does not own that `type` domain. The message names the domains the
+This crew log kind does not own that `type` domain. The message names the domains the
kind does own.
-**Caller action** — Write to the right kind of ledger, or use the right type. See
+**Caller action** — Write to the right kind of crew log, or use the right type. See
[crew-types.md](crew-types.md#the-layering-rule).
### `namespace_violation`
A guest emitter wrote outside its own namespace, or wrote a guest type into a session
-ledger.
+log.
**Caller action** — A guest's own name is its permission. Write `app:/…` types
-as `app:`, into a crew ledger.
+as `app:`, into a crew log.
### `bad_thread`
-`thread` does not name an existing, earlier `seq` in this same ledger — it is past
+`thread` does not name an existing, earlier `seq` in this same crew log — it is past
the newest entry, or names nothing readable. Field: `thread`.
-**Caller action** — Anchor on a `seq` this ledger returned. `thread` is never a
+**Caller action** — Anchor on a `seq` this crew log returned. `thread` is never a
pointer into another unit; that is `ref`.
### `bad_ref`
@@ -221,7 +221,7 @@ state you build past it is not trustworthy.
### `bad_segment`
-A segment's header does not belong to the ledger being read, its schema version
+A segment's header does not belong to the crew log being read, its schema version
disagrees, or its filename's declared first `seq` disagrees with its readable physical
first entry. The message names the offending segment.
diff --git a/docs/reference/ledger/reading-and-writing.md b/docs/reference/crew-log/reading-and-writing.md
similarity index 92%
rename from docs/reference/ledger/reading-and-writing.md
rename to docs/reference/crew-log/reading-and-writing.md
index 85f4f8c8359c..827258960080 100644
--- a/docs/reference/ledger/reading-and-writing.md
+++ b/docs/reference/crew-log/reading-and-writing.md
@@ -1,9 +1,9 @@
# Reading and writing
-**Local page, not a mirror.** Part of the [ledger reference](README.md), which is
+**Local page, not a mirror.** Part of the [crew log reference](README.md), which is
marked as a named exception in [the Reference index](../README.md).
-Every name here is from `kiro_crew.ledger`. Each refusal names a code from
+Every name here is from `kiro_crew.crew_log`. Each refusal names a code from
[errors.md](errors.md).
## Opening and creating
@@ -98,15 +98,15 @@ first with the anchor last.
the open handle; anything else opens the cited unit. The result is a `Resolution`
carrying a `status` and a tuple of `entries`, with `.ok` true only for `ok`.
-It answers with a status rather than raising, because a cited ledger being gone is
+It answers with a status rather than raising, because a cited crew log being gone is
a normal outcome of a long-lived pointer, not a bug in the reader:
| Status | Meaning |
|---|---|
| `ok` | Every cited `seq` was read back: the covered seqs are distinct and their count matches the span. |
-| `gone` | The cited ledger does not exist at all. |
+| `gone` | The cited crew log does not exist at all. |
| `pruned` | The span reaches below the oldest surviving segment's first `seq`, and what survives is intact. |
-| `corrupt` | The ledger exists but will not open, or the read was short, or a seq repeated, or the span reaches past the newest entry. A damaged segment chain is reported here rather than raised. |
+| `corrupt` | The crew log exists but will not open, or the read was short, or a seq repeated, or the span reaches past the newest entry. A damaged segment chain is reported here rather than raised. |
Two things `resolve` does **not** do. It makes no authorization decision and takes
no access callback, so there is no `forbidden` status: a caller that needs a
@@ -128,14 +128,14 @@ domains are on [session-types.md](session-types.md); the crew kind's are on
A guest writer is one whose `src` carries its own name — `crew:` or
`app:`. That name is its permission: an `app:` writer may write only
-`app:/…` types, and only into a crew ledger. Writing outside its own
+`app:/…` types, and only into a crew log. Writing outside its own
namespace is [`namespace_violation`](errors.md#namespace_violation). An `src` that
is neither a known fixed emitter nor a well-formed namespaced one is
[`bad_src`](errors.md#bad_src).
### Ownership
-One writer owns a unit's ledger at a time, held as an advisory lock on the unit's
+One writer owns a unit's crew log at a time, held as an advisory lock on the unit's
`.lease` file.
It is taken **non-blocking**: a writer either owns the file or is told it does not,
@@ -152,7 +152,7 @@ writer keeps ownership until its process exits. That is the intended trade: a
timeout would let a second writer start appending to a file the first one may still
be writing.
-When another **process** owns the ledger, an append raises
+When another **process** owns the crew log, an append raises
[`already_owned`](errors.md#already_owned) and writes nothing. This is a hard
refusal, not a retry hint: ownership is held for the life of the owning process, so
every later entry for that unit would queue behind the same wait. A caller reports
@@ -215,7 +215,7 @@ write means.
That policy lives in the session emitter above it, which is where the write-behind,
the loss accounting and the [`write/dropped`](session-types.md#writedropped) marker
belong. The emitter's contract is that a session is never slowed or failed by its
-own ledger: a write it cannot land is dropped and accounted for, and the count and
+own crew log: a write it cannot land is dropped and accounted for, and the count and
byte total surface as one `write/dropped` entry at the head of the next batch.
Further loss merges into the same pending marker rather than adding entries. Because
a lost job never took a `seq`, the loss leaves `seq` contiguous — which is why
@@ -231,7 +231,7 @@ the next append re-supplies the missing newline. An interior line that is
newline-terminated but unparseable is left on disk and skipped on read, because
truncating at it would discard everything after it.
-**Interrupted-turn closers — session ledgers only, and only with `repair=True`.**
+**Interrupted-turn closers — the sessions' logs only, and only with `repair=True`.**
One closer per still-open opener, written in this order with a fixed value per type:
| Open opener | Closer written | Fixed value |
@@ -263,8 +263,8 @@ is checked across every boundary. A pruned front — an oldest segment starting
1 — is a supported state that `iter_from` reads and that `resolve` reports as
`pruned`.
-The write side creates one segment. No code in `kiro_crew.ledger` rolls a new
-segment or prunes an old one, so `ledger.jsonl` is the only segment a writer
+The write side creates one segment. No code in `kiro_crew.crew_log` rolls a new
+segment or prunes an old one, so `log.jsonl` is the only segment a writer
produces. Retention removes whole segments off the **front**, which is why a front
gap is legal and a mid-chain gap is
[`segment_gap`](errors.md#segment_gap).
diff --git a/docs/reference/ledger/session-types.md b/docs/reference/crew-log/session-types.md
similarity index 98%
rename from docs/reference/ledger/session-types.md
rename to docs/reference/crew-log/session-types.md
index 669f1247ccde..e22569e4f597 100644
--- a/docs/reference/ledger/session-types.md
+++ b/docs/reference/crew-log/session-types.md
@@ -1,6 +1,6 @@
-# Session ledger entry types
+# The session's log entry types
-**Local page, not a mirror.** Part of the [ledger reference](README.md), which is
+**Local page, not a mirror.** Part of the [crew log reference](README.md), which is
marked as a named exception in [the Reference index](../README.md).
Twenty-six types. Read [envelope.md](envelope.md) first for the fields every entry
@@ -25,7 +25,7 @@ its **Since** line. A type this kind owns with no emitter anywhere is under
| Type | One line | Emitter | `src` | Pairing |
|---|---|---|---|---|
-| [`session/opened`](#sessionopened) | The ledger was created, or a claim re-attached to it. | live | `gateway` | — |
+| [`session/opened`](#sessionopened) | The crew log was created, or a claim re-attached to it. | live | `gateway` | — |
| [`session/closed`](#sessionclosed) | The gateway stopped serving this session. | live | `gateway` | — |
| [`turn/started`](#turnstarted) | A turn was authorized and is about to run. | live | `gateway` | opener of `turn/completed` |
| [`turn/refused`](#turnrefused) | A gate refused to run a dispatched turn. | live | `gateway` | terminal on its own |
@@ -56,7 +56,7 @@ its **Since** line. A type this kind owns with no emitter anywhere is under
### `session/opened`
-The ledger was created, or this claim re-attached to a conversation already on
+The crew log was created, or this claim re-attached to a conversation already on
disk.
**Kind and `src`** — `session`; `src` is `gateway`.
@@ -76,7 +76,7 @@ entry's write is the point the interrupted-turn repair runs.
| `model` | string | required | Configured model. Empty when the backend serves its own default. | |
| `cwd` | string | required | Working directory. May be empty. | |
| `owner` | string | required | Owner, defaulted to `default`. | |
-| `resumed` | bool | required | `true` when this claim re-attached to an existing ledger. | |
+| `resumed` | bool | required | `true` when this claim re-attached to an existing crew log. | |
**Invariants** — At most one per create and one per re-attach. The session's
*starting* model rides here rather than in a `model/selected` entry.
@@ -372,7 +372,7 @@ A message arrived while a turn was already running.
|---|---|---|---|---|
| `source` | string | required | Surface it arrived on. | |
| `bytes` | int | required | Size of the queued message. | |
-| `queued_seq` | string | required | The queue entry's own id. A string, not a ledger `seq`. | |
+| `queued_seq` | string | required | The queue entry's own id. A string, not a crew log `seq`. | |
**Invariants** — Carries **no `turn`**: it belongs to no turn yet. The body is not
recorded here; it lands in [`message/received`](#messagereceived) when the queue
@@ -383,7 +383,7 @@ drains.
```
**Reader hint** — `queued_seq` names a queue slot and must not be resolved as a
-ledger `seq` or fed to a `ref`.
+crew log `seq` or fed to a `ref`.
**Since** — #10091.
@@ -535,7 +535,7 @@ A tool call, identified by id. Arguments are digested, never recorded.
| `args_hash` | string | optional | sha256 of the serialized arguments, when there are any. | |
| `args_bytes` | int | optional | Byte length of the serialized arguments, present with `args_hash`. | |
-**Invariants** — Argument *content* never reaches the ledger. `args_hash` lets two
+**Invariants** — Argument *content* never reaches the crew log. `args_hash` lets two
calls be compared for equality without recording what was passed.
```json
@@ -793,7 +793,7 @@ A child this session dispatched.
| `model` | string | optional | The child's model. | |
| `scope` | object | optional | Context-scope flags `{memory, lessons, project}`, all bools. | |
-**Invariants** — Carries **no `ref`**. No subagent path opens a child ledger, so a
+**Invariants** — Carries **no `ref`**. No subagent path opens a child crew log, so a
citation would name a file that does not exist.
```json
@@ -813,7 +813,7 @@ A correction sent into a running child.
**When written** — When the steer is sent.
-**Pairing** — None. It is written into the parent's ledger, because the child has
+**Pairing** — None. It is written into the parent's crew log, because the child has
none of its own.
| Field | Type | Required | Meaning | Enum |
@@ -847,7 +847,7 @@ A child finished its work.
| `ms` | int | optional | Elapsed time. Omitted at 0. | |
**Invariants** — Carries no `tokens` and no `credits`: the subagent runtime
-measures neither, so a child's cost is not recoverable from the parent's ledger.
+measures neither, so a child's cost is not recoverable from the parent's log.
```json
{"type":"subagent/completed","seq":70,"time":1789000002500,"src":"gateway","data":{"agent_id":"sub-1","ms":40000}}
@@ -907,6 +907,6 @@ no handling for anything in this table.
| `tool/loaded` | Its token-cost field has no source anywhere in the repository. |
| `skill/searched` | A skill search is an MCP tool call, already recorded. |
| `skill/loaded` | Reading a skill file is already a tool call, and its token field has no source: the loader counts characters. |
-| `summary/written` | Its coverage field names ledger `seq`s, and the summary path holds nothing that can name one, so the field would have to be fabricated. |
+| `summary/written` | Its coverage field names crew log `seq`s, and the summary path holds nothing that can name one, so the field would have to be fabricated. |
| `remote/placed` | Its provider and id fields have no source at the placement site. |
| `remote/lost` | Its reason field has no source at the relay site. |
diff --git a/docs/request-for-change/README.md b/docs/request-for-change/README.md
index a3e771c9b647..3f1e43a73af8 100644
--- a/docs/request-for-change/README.md
+++ b/docs/request-for-change/README.md
@@ -35,14 +35,14 @@ was added 2026-08-27. The `rfc-crew-agent-sdk-boundary` row was added 2026-08-28
|---|---|---|
| [rfc-webhook-subscriptions.md](rfc-webhook-subscriptions.md) | `draft` | Nothing. Verified at `6163d9a9ca`: the inbound webhook is `POST /api/hooks/agent` alone (`dashboard/handlers/hooks.py` `api_hooks_agent`), which runs one turn in a `hook:*`-keyed session from a caller-shaped `{message, sessionKey}` body and refuses a second call on a busy key (`_hook_inflight_sessions`); `webhooks.py` token entries carry no scheme, slug or payload mapping; no subscription store or event buffer exists; `dashboard/state.py` carries no `[Webhook wake]` prefix; `dashboard/tailnet_serve.py` runs `tailscale serve` (tailnet-only, no Funnel); and `irq.py` and `monitoring/` wake only from cron-tick probes |
| [rfc-overload-resilience.md](rfc-overload-resilience.md) | `accepted` | Nothing of the design on main. Verified at `6f056722b`: `src/kiro_crew/taskq/` does not exist, `SpawnGate` / `HostBudget` / `SessionStartGate` have zero hits, `REGISTERED_CAPABILITIES` in `mcp_gateway/gatewayd.py` still carries exactly `ensure_backend`, `bridge_ping`, `poolable_ack`, and `BackendPool.acquire_exclusive` still bypasses `_max_backends`. Owner decided 2026-09-12 that the whole design ships as ONE PR on branch `fix/gatewayd-overload-liveness`, whose first slice (supervisor liveness ping, 600s stub reconnect budget) is already on that branch; §13 records the six decisions and the flag that reverses each |
-| [rfc-append-only-ledger.md](rfc-append-only-ledger.md) | `in-progress` | Nothing on main; PR 1 is [#10091](https://github.com/kirodotdev/KiroCrew/pull/10091). That PR is `kiro_crew.ledger` (the per-unit files for both kinds under a masked `ledgers/` root, an envelope carrying `seq`/`thread`/`ref`, the headers, type ownership, guest namespaces, paging, `ok`/`gone` resolution, torn-tail repair with deterministic closers) with the flag-gated session emitter as its first writer; that PR carries its own module specs. Verified at `2f1e2f54a`, before it: `members.py` appends `{ts, member, session}` entries carrying neither `type` nor `seq`, and `work_ledger.py` (`items/.json`) and `session_ledger.py` (`state.json`) each keep a separate head. See the RFC's `Amendment 2026-09-16`: the vocabulary is nine types shorter, the parallel lifecycle-event package is retired, and the format is pre-release rather than frozen. PR 2 — projections, routes, UI, the crew writer and migration — is unstarted |
+| [rfc-append-only-ledger.md](rfc-append-only-ledger.md) | `in-progress` | Nothing on main; PR 1 is [#10091](https://github.com/kirodotdev/KiroCrew/pull/10091). That PR is `kiro_crew.crew_log` (the per-unit files for both kinds under a masked `crew-log/` root, an envelope carrying `seq`/`thread`/`ref`, the headers, type ownership, guest namespaces, paging, `ok`/`gone` resolution, torn-tail repair with deterministic closers) with the flag-gated session emitter as its first writer; that PR carries its own module specs. Verified at `2f1e2f54a`, before it: `members.py` appends `{ts, member, session}` entries carrying neither `type` nor `seq`, and `work_ledger.py` (`items/.json`) and `session_ledger.py` (`state.json`) each keep a separate head. See the RFC's `Amendment 2026-09-16`: the vocabulary is nine types shorter, the parallel lifecycle-event package is retired, and the format is pre-release rather than frozen. PR 2 — projections, routes, UI, the crew writer and migration — is unstarted |
| [rfc-central-governance-ceiling.md](rfc-central-governance-ceiling.md) | `draft` | Partial. On this branch (#7362): the tighten-only ladder in `load_security_policy` (`platform/governance.py`) and central-above-env precedence, with no local rollback lever. Not on any branch, and design-of-record only: the withdrawn `break_glass` override and its four defect classes (#9106), the whole platform managed tier, and the Windows `HKLM\SOFTWARE\Policies\\` rung (Windows stays advisory) |
| [rfc-remote-instance-on-fargate.md](rfc-remote-instance-on-fargate.md) | `draft` | Nothing. Verified at `8fd5193e6`: the only `LaunchEngine` implementation is `RealLaunchEngine` in `cloud/launch_engine.py`, which calls `ec2.deploy`; `cloud_launch_engine` in `dashboard/state.py` is injectable but set only by tests; `sizes.py` fixes the three shapes to instance types; nothing in `src/kiro_crew/cloud/` references Fargate, ECS or `RunTask`. |
| [rfc-conductor-work-ledger.md](rfc-conductor-work-ledger.md) | `partial` | Phases 1, 2, 2.5 and the 2.6 swap are on main; verified at `dd0dce2643`. `src/kiro_crew/work_ledger.py` is the store ([#8855](https://github.com/kirodotdev/KiroCrew/pull/8855)); `src/kiro_crew/mcp_work.py` plus `dashboard/handlers/work_ledger.py` are the four tools and their `/api/work-ledger` routes, and `_MANAGED_MCP_SERVERS` carries the `opt_in` `kirocrew-work` entry ([#9152](https://github.com/kirodotdev/KiroCrew/pull/9152)); `agent.py` installs `kirocrew-worker` and, through the shared `_conductor_spec`, both `kirocrew-conductor` and its deprecated `kirocrew-ledger-conductor` alias — the swap that made `kirocrew-conductor` itself the ledger conductor, with the old name kept for one release (§Rollout note — swap done); `kirocrew-pipeline-conductor` and `kirocrew-security-conductor` still carry no work-ledger grant ([#9277](https://github.com/kirodotdev/KiroCrew/pull/9277) retracted the mount there and it stayed retracted). `goal-conductor/SKILL.md` is the ledger procedure and `goal-ledger-conductor/SKILL.md` is a pointer to it. Not started: the wake gate (`probes/__init__.py` `build` still maps exactly one kind, `gh-pr`), the sibling digest, worker-to-worker channels, the Crew page surfaces, and the deletion of `goal-conductor/scripts/ledger_entry.py`, which is still shipped though nothing documents it |
| [rfc-session-tag-change-event.md](rfc-session-tag-change-event.md) | `draft` | Nothing. Verified at `6581a04ee`: `SessionTagsChanged` has zero hits in the tree, and `HOOK_EVENTS` (`hooks.py:93-99`) and `ALLOWED_HOOK_EVENTS` (`validation.py:92-94`) still carry exactly the five turn-lifecycle events. Tag writes still only `push_slots_update()` to the browser with no server-side consumer |
| [rfc-agent-self-tagging.md](rfc-agent-self-tagging.md) | `partial` | v1 is on main via [#7779](https://github.com/kirodotdev/KiroCrew/pull/7779) (`780e75e2d`): the `chat_tag` session directive (`mcp_tools/control.py`, applied in `dashboard/session_directive_apply.py`), the protected grants store `dashboard/chat_tag_grants.py` under the masked and fenced `tag-grants` leaf with its HMAC provenance chain and boot seed, the `[BOARD]` context line in `context.py`, the per-tag `agent` policy on the tag PATCH, and the strict-boolean `status` validation. Open: the tag-manager control for the per-tag policy (the PATCH `agent` field has no dashboard sender), provenance-required minting (open question 3, v2), and the v2 scope (folder moves, conductor-over-children, propose-confirm, move budgets), all tracked on [#7774](https://github.com/kirodotdev/KiroCrew/issues/7774) |
| [rfc-agent-config-mirror.md](rfc-agent-config-mirror.md) | `partial` | The `providers/mirrors/` package it proposes is on main — `base.py`, `claude_code.py`, `registry.py` and the package's own `README.md` — so the seam and the Claude Code mirror exist. The three pre-existing unnamed mirrors it consolidates are all still real: `providers/acp.py`'s `_write_cli_overlay` + `_write_tool_search_overlay` (kiro-cli's `cli.json`), `acp/kas_agents.py` + `acp/kas_permissions.py` (KAS `customAgents` over the wire), and `client.py`'s `_write_claude_local_settings`. Unstarted: the interface on `LLMProvider`, the disposition vocabulary, the parity test, `acp/session_mcp.py`. Both hooks gaps it names are live: `hooks` sits in `kas_agents.UNSUPPORTED_SPEC_KEYS` and is never written for Claude Code. The mirror contract is documented in two places — `providers/mirrors/README.md` and [`../system-specs/modules/providers.md`](../system-specs/modules/providers.md) — and which one owns it is unresolved |
-| [rfc-mcp-lifecycle-event-log.md](rfc-mcp-lifecycle-event-log.md) | `draft` | **Blocked on a base.** The lifecycle-event package this RFC builds on (landed by [#3808](https://github.com/kirodotdev/KiroCrew/pull/3808)) is deleted: it had no emitter, no reader and no on-disk directory, and every one of its kinds names a fact the per-unit ledger owns as a `type`. So this RFC's three precedents — the ordering model, the writer, the failure posture — have no package to be precedents for; adopting them means restating them against `kiro_crew.ledger`, where ordering is already answered per unit. The #7366 capture points it names as emit sites are on an open PR, not on main |
+| [rfc-mcp-lifecycle-event-log.md](rfc-mcp-lifecycle-event-log.md) | `draft` | **Blocked on a base.** The lifecycle-event package this RFC builds on (landed by [#3808](https://github.com/kirodotdev/KiroCrew/pull/3808)) is deleted: it had no emitter, no reader and no on-disk directory, and every one of its kinds names a fact the per-unit crew log owns as a `type`. So this RFC's three precedents — the ordering model, the writer, the failure posture — have no package to be precedents for; adopting them means restating them against `kiro_crew.crew_log`, where ordering is already answered per unit. The #7366 capture points it names as emit sites are on an open PR, not on main |
| [rfc-app-session-controls.md](rfc-app-session-controls.md) | `accepted` | Ships with its implementation in #7573. Verified at `1d705a03f`, before that PR: `UIConfig` declares `entry`/`pages`/`overlays`/`sidebar` and no session-scoped surface, and the app SDK's public files carry zero `sessionKey`/`session_key`/`activeSession`/`currentSession` hits — so no app can discover the chat it is rendered beside. Implementation (manifest field + composer host + status polling) lands in the same PR; S1 and S2 are deliberately not separable |
| [rfc-transcript-section-markers.md](rfc-transcript-section-markers.md) | `draft` | Nothing. No `section_marker` role exists; every collapse affordance is intra-turn (`CollapsibleToolGroup`, `TurnBlock`, `ToolCallLine`) and nothing collapses rows above a point |
| [rfc-crew-agent-sdk-boundary.md](rfc-crew-agent-sdk-boundary.md) | `partial` | Both named deliverables are on main: the `agent_sdk` package (`drivers/acp.py`, `backend_identity.py`, `provider_identity.py`, `backend_install.py`, `native_commands.py`) and the shrink-only import ratchet `scripts/check_agent_sdk_boundary.py`. What remains is the cleanup the boundary was declared to enable: `providers/base.py` still aliases `AcpEvent` as the "provider-agnostic" event type, direct `kiro_crew.acp` import edges remain outside `acp/` and `providers/`, and `acp/worker_pool.py` still imports back from `session_pid.py` behind a cycle guard |
diff --git a/docs/request-for-change/rfc-append-only-ledger.md b/docs/request-for-change/rfc-append-only-ledger.md
index 90bbb013e323..b5def4f20170 100644
--- a/docs/request-for-change/rfc-append-only-ledger.md
+++ b/docs/request-for-change/rfc-append-only-ledger.md
@@ -15,6 +15,11 @@ superseded-by: []
# RFC: Append-only ledger — one record per unit, every view a fold
+> **Naming:** the mechanism this RFC specifies is called the **crew log** (agreed
+> with Joe Guo, 2026-09-17). Where the text below says "ledger" for the per-unit
+> append-only file, read "crew log". The RFC's file name and title are left as they
+> were so external links keep resolving; only the name of the thing changed.
+
Status: in-progress. The storage below, and the first emitter that writes to it, land
together in [#10091](https://github.com/kirodotdev/KiroCrew/pull/10091). Nothing is on
main yet: there `members.py` writes pointer entries with no `type` and no `seq`, and
@@ -53,7 +58,7 @@ the code (`session_ledger.py`, `work_ledger.py`): a **ledger** is the append-onl
instead. Message BODIES are in scope and are written, because they are redacted before
they reach the file -- exfiltration URLs then credentials, in the writer rather than at
the call sites, so a new call site cannot forget -- and a redaction that fails yields the
- empty string, never the input. Bodies on disk are GATED: `KIROCREW_SESSION_LEDGER` may
+ empty string, never the input. Bodies on disk are GATED: `KIROCREW_CREW_LOG` may
not default to on until session trash and permanent delete reach a session's ledger
directory and `StorageReport` counts its bytes. Until both land, "delete this
conversation" would not delete it and the disk-use surface would understate it, which are
@@ -190,7 +195,7 @@ answers, because a reader told the lines were pruned stops looking -- torn-tail
deterministic closer — an interrupted turn gets `turn/completed {stop_reason: interrupted}`
stamped at the last real entry's time, so two readers of the same bytes agree — and the
OS-masked `ledgers/` leaf. Its first writer ships with it: the session emitter behind
-`KIROCREW_SESSION_LEDGER=1`, default off, INCLUDING message bodies. The `ref` back-pointer
+`KIROCREW_CREW_LOG=1`, default off, INCLUDING message bodies. The `ref` back-pointer
to a transcript position and the `session/seeded` import are migration steps and follow;
until then the transcript file is still written and still the read path. There is no
streaming-delta emitter: redacting one delta at a time cannot see a credential split across
@@ -214,7 +219,7 @@ of the crew store's JSON files and of the work ledger, and the secretaries.
Three corrections to the sections above, from implementing them. The model is one base
envelope plus session-only and crew-only halves, and the sections were written with the two
-halves mixed. `docs/system-specs/modules/ledger-core.md` sections 4, 4a, 4b and 6 are the
+halves mixed. `docs/system-specs/modules/crew-log-core.md` sections 4, 4a, 4b and 6 are the
current specification of all three.
**The signed family is two plain crew-owned types.** §4's `crew:/dispatch` and
diff --git a/docs/request-for-change/rfc-mcp-lifecycle-event-log.md b/docs/request-for-change/rfc-mcp-lifecycle-event-log.md
index 6fd3c1a892a8..fe74167ac980 100644
--- a/docs/request-for-change/rfc-mcp-lifecycle-event-log.md
+++ b/docs/request-for-change/rfc-mcp-lifecycle-event-log.md
@@ -16,8 +16,8 @@ superseded-by: []
**Status note: this RFC has no base.** The lifecycle-event package every section below
builds on is deleted -- it had no emitter, no reader and no on-disk directory, and each of
-its kinds names a fact the per-unit append-only ledger
-(`docs/system-specs/modules/ledger-core.md`) owns as a `type`. The three precedents this
+its kinds names a fact the per-unit append-only crew log
+(`docs/system-specs/modules/crew-log-core.md`) owns as a `type`. The three precedents this
RFC settles therefore have no package to settle them for, and the ordering one is already
answered there: `seq` is per unit, assigned by that unit's single writer. Taking this RFC
forward means either restating it against that ledger -- where a per-session MCP trace has a
diff --git a/docs/request-for-change/rfc-session-tag-change-event.md b/docs/request-for-change/rfc-session-tag-change-event.md
index ff29a7ab17bd..fc8817273c9f 100644
--- a/docs/request-for-change/rfc-session-tag-change-event.md
+++ b/docs/request-for-change/rfc-session-tag-change-event.md
@@ -237,7 +237,7 @@ settling its first-emitter precedents (per-`key` monotonic `seq`, one gateway ap
writer, fail-open because "the log is observability, not audit"). A
`session/tags-changed` kind would have fit its envelope (`{v, kind, src, key, ts_ms,
data}`, additive-only, opaque `key`, unknown-kind tolerance). The surviving
-append-only stream is the per-unit ledger, whose scope is one crew or one session --
+append-only stream is the per-unit crew log, whose scope is one crew or one session --
a cross-session tag transition has no unit to belong to, so this option would need
the `gateway` kind that stream does not yet define.
diff --git a/docs/system-specs/common/testing-conventions.md b/docs/system-specs/common/testing-conventions.md
index 6904bf048454..52c137928ab5 100644
--- a/docs/system-specs/common/testing-conventions.md
+++ b/docs/system-specs/common/testing-conventions.md
@@ -2318,7 +2318,7 @@ More shapes this class hides, all Windows-only and all green on every Linux run:
of magnitude below (which still fails a seconds-for-milliseconds bug) and, as the
ceiling, a span the test measures itself.
- **A fixed drain ceiling over a batch of fsync-priced writes is a rate assertion.**
- Every test in `test_ledger_edge_concurrency` hands the session ledger's single writer
+ Every test in `test_crew_log_edge_concurrency` hands the session log's single writer
thread 30 to 160 appends, and `assert emit.flush(timeout=10.0)` across that batch
bounds a write RATE rather than the emitter. One append is an `fsync` behind a
cross-process lock:
diff --git a/docs/system-specs/modules/README.md b/docs/system-specs/modules/README.md
index 476b708eadac..653b75b4350e 100644
--- a/docs/system-specs/modules/README.md
+++ b/docs/system-specs/modules/README.md
@@ -23,8 +23,8 @@ agent loads only the one it needs.
| [history.md](history.md) | Conversation persistence, JSONL rotation, and transcript search. |
| [session-summary.md](session-summary.md) | Intent-level session summaries: the sidecar cache, extraction, and the turn-end pass. |
| [session-work-ledger.md](session-work-ledger.md) | Per-session durable work state (goal, phase, tried, artifacts) on disk, its MCP tools, and monitor-loop snapshot injection. |
-| [ledger-core.md](ledger-core.md) | Append-only per-crew and per-session ledgers: the wire format, type ownership and guest namespacing, the torn-tail rule, and the pre-release status of the session vocabulary. |
-| [session-ledger-emitter.md](session-ledger-emitter.md) | The flag-gated writer that turns the ACP turn lifecycle into an append-only per-session `ledger.jsonl`: which facts are recorded, from which call site, and which are deliberately not. |
+| [crew-log-core.md](crew-log-core.md) | Append-only per-crew and per-session crew logs: the wire format, type ownership and guest namespacing, the torn-tail rule, and the pre-release status of the session vocabulary. |
+| [crew-log-emitter.md](crew-log-emitter.md) | The flag-gated writer that turns the ACP turn lifecycle into an append-only per-session `log.jsonl`: which facts are recorded, from which call site, and which are deliberately not. |
| [file-search.md](file-search.md) | The `@`-mention file/folder search: index, ranking, `kinds` filter, and the sensitive-path symmetry. |
| [session-storage.md](session-storage.md) | What sessions cost on disk, and the user-initiated trash that reclaims it. |
| [session-control.md](session-control.md) | One chat session opening, stopping, and reading another. |
diff --git a/docs/system-specs/modules/ledger-core.md b/docs/system-specs/modules/crew-log-core.md
similarity index 83%
rename from docs/system-specs/modules/ledger-core.md
rename to docs/system-specs/modules/crew-log-core.md
index 96eb0e10d942..83e3d0e5aeea 100644
--- a/docs/system-specs/modules/ledger-core.md
+++ b/docs/system-specs/modules/crew-log-core.md
@@ -1,10 +1,10 @@
-# Ledger Core
+# Crew log Core
-Owners: `kiro_crew.ledger` (`schema.py`, `store.py`, `errors.py`)
+Owners: `kiro_crew.crew_log` (`schema.py`, `store.py`, `errors.py`)
## 1. Purpose
-`kiro_crew.ledger` gives a crew or a session one durable, ordered, citable record of what happened. It is the storage layer only: it defines a file format, enforces who may write what into it, and reads it back. It carries no routes, no MCP tools, no dashboard surface and no migration.
+`kiro_crew.crew_log` gives a crew or a session one durable, ordered, citable record of what happened. It is the storage layer only: it defines a file format, enforces who may write what into it, and reads it back. It carries no routes, no MCP tools, no dashboard surface and no migration.
The problem it answers is that long-horizon work keeps its state in a context window, which harness-owned compaction summarizes lossily. Transcripts are not a substitute: rotation, compaction and consolidation rewrite the whole file, the grain is a message rather than an operation, and no field defines an order a consumer can fold on. An append-only file with a writer-assigned sequence inverts that -- the record is the authority, the context is a cache -- and lets one unit cite a segment of another's history instead of copying it.
@@ -12,28 +12,28 @@ The problem it answers is that long-horizon work keeps its state in a context wi
There is one structured record of what happened, and it is this one. A parallel global lifecycle stream (`kiro_crew.events`, day-sharded under `events/`, joined by a correlation `key`) was retired unwritten: it had no emitter and no reader, no `events/` directory existed on any host, and each of its kinds names a fact this format already owns as a `type`. Two vocabularies for one fact is a choice every future emitter would have had to make, and the answer would have been "this one" every time.
-`seq`, `thread` (a grouping key naming an earlier seq in the SAME file) and `ref` (a pointer into another file) are why. All three are defined relative to a single unit's ledger, so the scope question a global stream cannot answer for itself -- per writer? per key? global? -- is answered by the file. A day-sharded, multi-domain shard would need either a per-key sequencer inside a shared file or a `seq` whose meaning varies by kind.
+`seq`, `thread` (a grouping key naming an earlier seq in the SAME file) and `ref` (a pointer into another file) are why. All three are defined relative to a single unit's crew log, so the scope question a global stream cannot answer for itself -- per writer? per key? global? -- is answered by the file. A day-sharded, multi-domain shard would need either a per-key sequencer inside a shared file or a `seq` whose meaning varies by kind.
-A fact with no unit to belong to still has a home: a script cron, or gateway lifecycle, gets a `gateway`-kind ledger when something needs to record one. That kind does not exist yet, and adding it is a change to `KINDS` and `TYPE_OWNERSHIP` rather than to the wire format.
+A fact with no unit to belong to still has a home: a script cron, or gateway lifecycle, gets a `gateway`-kind crew log when something needs to record one. That kind does not exist yet, and adding it is a change to `KINDS` and `TYPE_OWNERSHIP` rather than to the wire format.
## 3. Storage and identity
```
-/ledgers/crews//ledger.jsonl
-/ledgers/sessions//ledger.jsonl
-.lock # sibling, per ledger
-.lease # sibling, per ledger
+/crew-log/crews//log.jsonl
+/crew-log/sessions//log.jsonl
+.lock # sibling, per crew log
+.lease # sibling, per crew log
```
`` is `session_ledger._store_name()` -- a readable fold plus a digest of the exact id -- and the raw id lives in the header. The id is deliberately not the directory name: a channel session key legitimately carries a colon (`slack:1712793600.123`), which POSIX accepts and Windows refuses, so the raw id as a filename turns a sanctioned id into an `OSError` on a supported platform. Identity is the digest, so `Foo` and `foo` get distinct directories on a case-insensitive filesystem. `store.ledger_dir()` refuses a separator or NUL in the raw id and requires the resolved path to stay below the root, so a folded name cannot traverse. `Ledger.open()` proves it reached the right unit by checking the id the header stores.
-Every segment repeats that header. Before `Ledger._iter_segments()` yields any entry from a segment, it requires the header's unit id, kind and schema version to match the opened ledger, and requires the filename's first sequence to match the physical first entry when that record is readable. A provenance failure refuses the segment and names it; an unreadable record retains the per-record skip behavior.
+Every segment repeats that header. Before `Ledger._iter_segments()` yields any entry from a segment, it requires the header's unit id, kind and schema version to match the opened crew log, and requires the filename's first sequence to match the physical first entry when that record is readable. A provenance failure refuses the segment and names it; an unreadable record retains the per-record skip behavior.
-Every kind lives under ONE `ledgers` leaf, and that leaf is what carries the protection. It is an entry in `security.paths._CREW_SECRET_LEAVES`, so the agent's own file tools are refused, and an entry in `sandbox._CREW_HIDDEN_LEAVES`, so the OS hides it from every sandboxed spawn. Both are needed and neither substitutes for the other: the write-side rules below bind only callers who go through the library, the file-tool floor answers only the agent's tools, and a spawned subprocess that calls `open()` is answered by neither. Without all three an agent could forge an entry attributed to `src:"gateway"` or rewrite the history a conductor is designed to trust.
+Every kind lives under ONE `crew-log` leaf, and that leaf is what carries the protection. It is an entry in `security.paths._CREW_SECRET_LEAVES`, so the agent's own file tools are refused, and an entry in `sandbox._CREW_HIDDEN_LEAVES`, so the OS hides it from every sandboxed spawn. Both are needed and neither substitutes for the other: the write-side rules below bind only callers who go through the library, the file-tool floor answers only the agent's tools, and a spawned subprocess that calls `open()` is answered by neither. Without all three an agent could forge an entry attributed to `src:"gateway"` or rewrite the history a conductor is designed to trust.
-Session ledgers do **not** live under the flat `sessions/.jsonl` transcript root, which they could otherwise share without shadowing. That root carries neither fence -- it is not in `_CREW_HIDDEN_LEAVES` (the `sessions` deny that exists is the private-member view's, which covers one narrow population) -- so a session ledger there was write-protected by the tool gate alone. Naming the shared root instead of one leaf per kind also means a third unit kind inherits both fences rather than needing a reviewer to notice it was left out.
+Session crew logs do **not** live under the flat `sessions/.jsonl` transcript root, which they could otherwise share without shadowing. That root carries neither fence -- it is not in `_CREW_HIDDEN_LEAVES` (the `sessions` deny that exists is the private-member view's, which covers one narrow population) -- so a session's log there was write-protected by the tool gate alone. Naming the shared root instead of one leaf per kind also means a third unit kind inherits both fences rather than needing a reviewer to notice it was left out.
-The `ledgers` root is established EAGERLY, and that is what makes the mask non-vacuous. Both fences are stated per PATH, and the Linux bind-mask loop skips a leaf that does not exist -- so a root created lazily on the first write is unmasked in every sandbox spawned before it, one of which can then create the directory itself and fill it with entries a reader would take as the gateway's. Two mechanisms close that: `ensure_data_home()` creates it `0700` at startup, and `chmod`s it too, since `mkdir`'s mode is umask-masked on creation and a no-op on a directory that already exists; and `sandbox._CREW_PRECREATE_HIDDEN_DIR_LEAVES` materialises it empty before every namespace spawn so the bind always has a name to cover. macOS needs neither: a Seatbelt deny is a path rule that holds for a name that does not exist yet.
+The `crew-log` root is established EAGERLY, and that is what makes the mask non-vacuous. Both fences are stated per PATH, and the Linux bind-mask loop skips a leaf that does not exist -- so a root created lazily on the first write is unmasked in every sandbox spawned before it, one of which can then create the directory itself and fill it with entries a reader would take as the gateway's. Two mechanisms close that: `ensure_data_home()` creates it `0700` at startup, and `chmod`s it too, since `mkdir`'s mode is umask-masked on creation and a no-op on a directory that already exists; and `sandbox._CREW_PRECREATE_HIDDEN_DIR_LEAVES` materialises it empty before every namespace spawn so the bind always has a name to cover. macOS needs neither: a Seatbelt deny is a path rule that holds for a name that does not exist yet.
## 4. Envelope
@@ -52,19 +52,19 @@ Line 1 is the header; every later line is an entry. This section is the part tha
| `time` | Epoch milliseconds. Writer-assigned. |
| `src` | The emitter. Which names a kind accepts is per kind: 4a and 4b. |
| `thread` | Optional. The seq of an earlier entry in this same file -- a grouping key, like a chat thread id. |
-| `ref` | Optional. `{unit, id, from, to?}`, a pointer to a segment of another (or the same) ledger. `to` absent means one line. |
+| `ref` | Optional. `{unit, id, from, to?}`, a pointer to a segment of another (or the same) crew log. `to` absent means one line. |
| `ignorable` | Optional, `true` only. The writer's promise that a reader which does not know this `type` may skip the line. Absent on every entry that does not set it. |
| `data` | A JSON object. |
A serialized entry is capped at `MAX_ENTRY_BYTES` (64 KiB) and a `ref` at `MAX_REF_SPAN` (500) lines. Both refuse rather than truncate; section 6 states why.
-`thread` and `ref` answer different questions and the difference is the file boundary. `thread` groups entries INSIDE one ledger, so it is an int -- a seq this same writer assigned, which is why the anchor can be proved to exist before the append lands. `ref` points ACROSS files, so it must name a unit as well as a seq range, and it is resolved at read time with four outcomes rather than dereferenced at write time: the cited file can be pruned or damaged between the citation and the read, and the citing entry is not rewritten when it is.
+`thread` and `ref` answer different questions and the difference is the file boundary. `thread` groups entries INSIDE one crew log, so it is an int -- a seq this same writer assigned, which is why the anchor can be proved to exist before the append lands. `ref` points ACROSS files, so it must name a unit as well as a seq range, and it is resolved at read time with four outcomes rather than dereferenced at write time: the cited file can be pruned or damaged between the citation and the read, and the citing entry is not rewritten when it is.
-`ref` is deliberately kind-independent: it is the envelope's, so a crew ledger may cite a session's segment and a session ledger may cite a crew's. Section 4b names the one bridge a writer takes today.
+`ref` is deliberately kind-independent: it is the envelope's, so a crew's log may cite a session's segment and a session's log may cite a crew's. Section 4b names the one bridge a writer takes today.
Two overlaps between the kinds are intentional and are not collisions. The `message` domain exists in BOTH kinds with different `data` -- a crew forwards messages, a session records its own bodies -- because ownership answers "does this kind have such events", and both do. And `ref` crossing kinds is the mechanism the two records are joined by, rather than one kind copying the other's bytes.
-### 4a. Session ledger
+### 4a. The session's log
One session's own history: the ACP turn lifecycle, what was put in front of the model, and what the model did.
@@ -76,20 +76,20 @@ The type tables are section 5, which lists every session type, its `data` and wh
A session header carries `owner`, `agent`, and the optional `task`, `pack`, `slot`, `thread` (`{crew, seq}`), `cwd` and `remote` -- the facts fixed for the session's whole life, which a reader needs before reading any entry. `owner` never changes. Among them, `thread {crew, seq}` is where a session's place in a crew's work lives: it points back at the crew entry that caused the session to exist, on line 1 rather than in an entry, because it is settled before the first turn.
-### 4b. Crew ledger
+### 4b. The crew's log
A crew's activity record: its members, its work items, the messages it forwarded, and the sentences a conductor reads. A crew entry is often a sentence plus a `ref` -- "I opened PR-4127" and where to read the work.
A crew header carries the unit's id and its creation time and nothing else. A crew's display name and template belong to the members store, which owns them and can change them; an append-only line cannot, so duplicating them here would make this file the system of record for values it has no way to update, and the first rename would leave a permanent lie on line 1.
-`src` is `gateway`, `dashboard`, `patrol`, or one of the two guest forms `crew:` and `app:`. A guest is an emitter that names an INSTANCE rather than a subsystem, and a crew ledger is the one kind that accepts one, because it is the record several units contribute to: a child crew reports into its parent's ledger, a conductor signs its own dispatches, and an app records a fact no built-in domain covers. Section 6 states what each guest may write.
+`src` is `gateway`, `dashboard`, `patrol`, or one of the two guest forms `crew:` and `app:`. A guest is an emitter that names an INSTANCE rather than a subsystem, and a crew's log is the one kind that accepts one, because it is the record several units contribute to: a child crew reports into its parent's crew log, a conductor signs its own dispatches, and an app records a fact no built-in domain covers. Section 6 states what each guest may write.
The families, from the RFC:
| family | types | pointer |
|---|---|---|
| shipped | `member/*`, `activity/record`, `slot/*`, `patrol/*` | `slot/*` -> the session |
-| messages | `message/received`, `message/sent` | redacted body in the ledger |
+| messages | `message/received`, `message/sent` | redacted body in the crew log |
| tree | `crew/child-attached`, `crew/parent-attached`, `*-detached` | -- |
| dispatch | `crew/dispatch`, `crew/report` | report -> the child's segment |
| topics | `crew/topic-*`, `crew/forwarded`, `crew/run-state` | topic -> its work session |
@@ -97,7 +97,7 @@ The families, from the RFC:
| knowledge | `crew/finding`, `crew/summary`, `crew/note-*`, `crew/link` | the segment covered |
| memory | `memory/bound\|copied\|forgotten\|restored` | -- |
-Two of these families carry a contract with REQUIRED fields. **Required here is a contract on the writer, and what enforces it is a declaration rather than a branch:** a per-type `data` requirement belongs to the type registry, next to that type's own `data` shape, not to `check_ownership`, which answers who may write a type rather than what the type must contain. Until that module exists these two contracts are held by review against this section. TODO: declare them in the ledger type registry module, `kiro_crew.ledger.types`, when it lands.
+Two of these families carry a contract with REQUIRED fields. **Required here is a contract on the writer, and what enforces it is a declaration rather than a branch:** a per-type `data` requirement belongs to the type registry, next to that type's own `data` shape, not to `check_ownership`, which answers who may write a type rather than what the type must contain. Until that module exists these two contracts are held by review against this section. TODO: declare them in the crew log type registry module, `kiro_crew.crew_log.types`, when it lands.
**`crew/dispatch`** -- a parent asking for an item to be worked.
@@ -128,21 +128,21 @@ Two of these families carry a contract with REQUIRED fields. **Required here is
| `data.status` | yes | One of `done`, `blocked`, `failed`, `progress`. |
| `data.credits` | no | Credits the child spent. Absent is not zero. |
| `data.summary` | no | One sentence. |
-| `ref` | yes | A segment of the child's ledger: the evidence. |
+| `ref` | yes | A segment of the child's crew log: the evidence. |
| `thread` | when replying | The dispatch's `seq`. |
-`ref` is required for the same reason `target` is. A report is a CLAIM about work that happened somewhere else, and `board` and `budget` fold status and credits straight off it without opening the child's ledger; the `ref` is what makes that fold checkable rather than trusted. A report with no `ref` is an unfalsifiable claim, permanently, since nothing later can attach the evidence to a line that is already written.
+`ref` is required for the same reason `target` is. A report is a CLAIM about work that happened somewhere else, and `board` and `budget` fold status and credits straight off it without opening the child's crew log; the `ref` is what makes that fold checkable rather than trusted. A report with no `ref` is an unfalsifiable claim, permanently, since nothing later can attach the evidence to a line that is already written.
`thread` is the dispatch's `seq` when the report answers one, which is what makes a dispatch and its replies one conversation inside the parent's file. A report volunteered with no dispatch behind it carries no `thread`.
Both of these are one type each, not one per writer. The child's identity is `src`, so two children reporting on one item write the same `type` into one file and are told apart by who signed them.
-`ref` on a report is **the one cross-kind bridge a writer takes**: from a crew ledger into a session's segment, one level down, in the direction a conductor reads. The pair is symmetric with `subagent/spawned` (section 5): the child's header `thread` points up at the entry that caused it, and that entry's `ref` points down into the child's record.
+`ref` on a report is **the one cross-kind bridge a writer takes**: from a crew's log into a session's segment, one level down, in the direction a conductor reads. The pair is symmetric with `subagent/spawned` (section 5): the child's header `thread` points up at the entry that caused it, and that entry's `ref` points down into the child's record.
## 5. The session-log format, pre-release
-**The shapes below are PRE-RELEASE and may change.** `KIROCREW_SESSION_LEDGER` defaults off, so
-no ledger directory is created on a stock install and there is no user data on disk for a shape
+**The shapes below are PRE-RELEASE and may change.** `KIROCREW_CREW_LOG` defaults off, so
+no crew log directory is created on a stock install and there is no user data on disk for a shape
change to break. While that holds, a type may be added, removed or reshaped in one commit.
**The freeze point is the release that turns the flag on by default.** From then on there are
@@ -216,7 +216,7 @@ every block put in front of the model — `system`, `memory`, `lessons`, `skills
Arguments and results are DIGESTED, never recorded: `args_hash` / `result_hash` are the sha256 of
the serialized payload and `args_bytes` / `result_bytes` its length. That answers "same arguments as
-last time" and "how large was this" without the ledger becoming where a shell command's secrets and
+last time" and "how large was this" without the crew log becoming where a shell command's secrets and
a file's contents accumulate. Bodies, if they ever land, arrive as their own change. Each pair is
absent rather than zeroed when there is nothing to digest, since 0 is a real size. `is_error` is
tri-state and absent when the caller did not say, because "nobody asserted this worked" is not the
@@ -245,7 +245,7 @@ a slot key, not a session id, so there is nothing to key an entry by.
These are the families a single-agent runtime never needs and a gateway does: every token spent on a
session's behalf, whether a person asked for it or not, is a fact in that session's log attributed to
-what caused it. A subagent is itself a session with its own ledger, whose header `thread` points at
+what caused it. A subagent is itself a session with its own crew log, whose header `thread` points at
the parent's `subagent/spawned` entry while that entry carries a `ref` into the child's log — the
same pair as a crew dispatch, one level down.
@@ -262,7 +262,7 @@ Every refusal is a `LedgerError` carrying a stable `code`; the codes are API sur
A type never carries the writer's identity. `crew:/` is not a type at all but a malformed one (`bad_type`): identity belongs in `src`, where authorization reads it, and a type that repeats it would make the same fact a different type per writer -- so a fold would need to parse the type to group two children's reports on one item, and the registry would grow an entry per crew.
-What this layer does NOT check is any relationship between the guest and the ledger. It has no crew tree to consult, so it cannot ask whether `crew:qa` is really a child of the crew whose file it is writing into -- and a check with nothing behind it only looks like a boundary, the same reason `resolve` has no `forbidden` status yet. Authorization here is that the emitter is a form this kind accepts and that a guest stays inside its own namespace; who is whose child arrives with the grants, at the layer that has the tree.
+What this layer does NOT check is any relationship between the guest and the crew log. It has no crew tree to consult, so it cannot ask whether `crew:qa` is really a child of the crew whose file it is writing into -- and a check with nothing behind it only looks like a boundary, the same reason `resolve` has no `forbidden` status yet. Authorization here is that the emitter is a form this kind accepts and that a guest stays inside its own namespace; who is whose child arrives with the grants, at the layer that has the tree.
The remaining bounds: `thread` must name an existing, parseable, earlier seq (`bad_thread`); `ref` must be well-formed and span at most `MAX_REF_SPAN` lines (`bad_ref`); a serialized entry must be at most `MAX_ENTRY_BYTES` (`entry_too_large`). Caps refuse rather than truncate, leaving the file byte-identical -- a clipped record the caller believes landed intact is a loss the caller cannot detect.
@@ -292,7 +292,7 @@ Both reads are FRAMED by `jsonl_util`, so one planted line cannot cost more memo
A header naming a format version this build does not read is refused BEFORE the rest of the header is checked and before any row is decoded, with its own code (`unsupported_version`) and a message telling the reader to upgrade and stating the file is not damaged. The ordering is the point: a newer format need not satisfy any of this build's structural checks, so its new required type would surface as `unknown_entry_type` and its header shape as `bad_header` -- both of which accuse the file of corruption when the truth is that the reader is old, and someone acting on that diagnosis deletes a healthy log. Refusing NEWER only; an older version opens as it stands, which is what a future migration is for. Nothing else in this module reads `version`, so without this check carrying it buys nothing.
-A session ledger's newest turn can be left open by a crash, a `SIGKILL` or a pod eviction. `Ledger.open(kind, id, repair=True)` -- or `ledger.repair_interrupted_turn()` on a handle already held -- closes it, appending deterministic closers: a `tool/completed` with `status: "unknown"` for each unmatched `tool/called` inside that turn, in first-seen order, then `turn/completed` with `stop_reason: "interrupted"`. Calls first, because a turn cannot close while a call inside it is open, and closing them the other way would produce a record no live writer could have produced.
+A session's log's newest turn can be left open by a crash, a `SIGKILL` or a pod eviction. `Ledger.open(kind, id, repair=True)` -- or `ledger.repair_interrupted_turn()` on a handle already held -- closes it, appending deterministic closers: a `tool/completed` with `status: "unknown"` for each unmatched `tool/called` inside that turn, in first-seen order, then `turn/completed` with `stop_reason: "interrupted"`. Calls first, because a turn cannot close while a call inside it is open, and closing them the other way would produce a record no live writer could have produced.
A group whose members are meaningless apart is written by `append_many`, which takes the file lock once, allocates a contiguous seq run from one read of the tail, and writes every line with one `write()` and one `fsync`. The one caller today is a body too large for a single line: the `message/chunk` entries plus the entry that CITES their seqs. The citation is built INSIDE the lock, by a `cite(seqs)` callable the caller passes alongside the chunks and which receives the run the call has just allocated, so a citation cannot disagree with the allocation it names. Allocating outside the lock and citing the result cannot be made correct, because the lock is a cross-process one: between that read and the write another handle can append and shift the run, after which `chunks` name the intruder's entries -- seqs that exist and parse, so no later read can tell the body apart from the right one. Appending the members separately leaves a different window, in which a hard kill puts the body on disk with nothing pointing at it -- stored and unreachable, with no record of the message at all. Every refusal still happens before any byte is written, including validation of what `cite` returns, so a rejected group leaves the file identical, and `thread` is not accepted because a group is self-contained and an anchor check would have to re-read the tail it is being allocated from.
@@ -300,7 +300,7 @@ One write can still tear, so the repair handles what a torn group leaves. A TRAI
That scan reads with the ABORT posture, because the offset it produces feeds a truncation. A bounded read drops an over-cap record in full, terminator included, without yielding it, so a byte walk over what such a read yields stops matching the file at the first oversized record and every offset after it is short by that record's length -- and truncating at a short offset cuts valid entries. So a record that cannot be delivered intact aborts the scan and nothing is truncated, with a warning naming why. The cost of failing closed is one unreachable body left in the file, against losing history that was never in question.
-**Repair is opt-in, and only a RESUME may ask for it.** A plain `open` never mutates the record. The two callers of `open` want opposite things: a resume -- the gateway finding a session ledger whose writer is gone -- wants the open turn closed, while a live writer RECONNECTING to its own ledger must not have it closed, because its turn is still running and a `turn/completed {interrupted}` landing mid-turn would claim an outcome the turn never had and then be followed by more of that turn's entries. Nothing in the file distinguishes an open turn from a dead one, so only the caller's situation can: repair cannot be inferred from the fact that an `open` is happening. A reconnect happens for reasons unrelated to the writer's health -- a handle dropped from a bounded cache is enough -- which is precisely how an unconditional repair corrupts a live turn. The caller's situation is a belief about a writer it cannot see, which is why it is not the only check: see "Write ownership" below.
+**Repair is opt-in, and only a RESUME may ask for it.** A plain `open` never mutates the record. The two callers of `open` want opposite things: a resume -- the gateway finding a session's log whose writer is gone -- wants the open turn closed, while a live writer RECONNECTING to its own crew log must not have it closed, because its turn is still running and a `turn/completed {interrupted}` landing mid-turn would claim an outcome the turn never had and then be followed by more of that turn's entries. Nothing in the file distinguishes an open turn from a dead one, so only the caller's situation can: repair cannot be inferred from the fact that an `open` is happening. A reconnect happens for reasons unrelated to the writer's health -- a handle dropped from a bounded cache is enough -- which is precisely how an unconditional repair corrupts a live turn. The caller's situation is a belief about a writer it cannot see, which is why it is not the only check: see "Write ownership" below.
Every closer reuses the LAST REAL entry's `time`. A closer describes what happened when the writer stopped, not when some later process opened the file, so the current clock would put a gap of arbitrary length inside a turn and make any duration computed off these entries a measure of downtime. Reusing the time also makes the repair deterministic: the same bytes in produce the same bytes out, whenever it runs, and a second repair adds nothing because the tail is balanced.
@@ -308,9 +308,9 @@ This is still append-only -- nothing is rewritten and `seq` continues -- so a re
**A content-aware repair reads with the abort posture, because its result decides whether history is added.** The ordinary reader skips a malformed interior line so one damaged line cannot hide the history in front of it, and that is the wrong tolerance here: a turn whose real `turn/completed` is byte-damaged reads as still open once the line is skipped, and a closer appended from that fold states an outcome no writer observed -- permanently, since later folds skip the damaged real completion too and see only the fabrication. So the fold reports every record it could not read, and a skip refuses the repair outright: the file is left exactly as it is with one warning naming the record. This is the same rule the truncation-offset scan already follows, and both share one classification of what counts as a record, because their results feed the same mutation -- one chooses where the file is cut, the other whether lines are added to it.
-`seq` is read back from a bounded window at the file's end inside the per-ledger lock rather than trusted from an in-process cache, so two writers cannot both claim one number and the read costs the same on a ten-line ledger or a million-line one. `store._anchor_exists()` reuses that same window, so proving a `thread` anchor is parseable is free for a recent anchor and falls back to a scan only for one older than the window.
+`seq` is read back from a bounded window at the file's end inside the per-file lock rather than trusted from an in-process cache, so two writers cannot both claim one number and the read costs the same on a ten-line crew log or a million-line one. `store._anchor_exists()` reuses that same window, so proving a `thread` anchor is parseable is free for a recent anchor and falls back to a scan only for one older than the window.
-`resolve` has four outcomes and takes NO access callback. `ok` is a complete answer; `gone` means the cited unit has no ledger at all; `pruned` means the span reaches BELOW the oldest surviving segment's first seq, so retention removed it; `corrupt` means the span lies inside a segment that still exists yet read short, which is damage.
+`resolve` has four outcomes and takes NO access callback. `ok` is a complete answer; `gone` means the cited unit has no crew log at all; `pruned` means the span reaches BELOW the oldest surviving segment's first seq, so retention removed it; `corrupt` means the span lies inside a segment that still exists yet read short, which is damage.
**Retention and damage are never reported as each other.** Both look identical from the caller's side -- a short answer -- so the classification is made from the segment names rather than the result: a span starting below `segment_first_seqs()[0]` is `pruned` when the part of it at or above that seq reads back whole, and anything else that reads short is `corrupt`. The surviving part is checked separately because a partly pruned span is short for a legitimate reason -- so the count that would catch damage in it is already satisfied -- and a citation whose head retention removed can still hold a damaged line further up, in a segment that is still on disk. Reporting that as retention hides the damage behind a normal answer. Getting this backwards is worse than either error alone. A reader told `pruned` stops looking, because retention removing old lines is a normal answer; told `corrupt`, it knows the file it still has is not intact. Reporting damage as retention therefore converts a recoverable alarm into silence. Citing PAST the newest entry is `corrupt` too, and deliberately not `ok`: a `Ref` always names a definite span -- absent `to_seq` means the single line at `from_seq`, so there is no open-ended spelling -- which makes a span reaching beyond the newest entry a claim about lines that are not in the file. `ok` means every cited seq was read back, so a short answer is the citation failing whatever shortened the file. That also covers the case with no torn bytes to give it away: whole lines cleanly truncated lower both the walked entries and a reopened handle's tail together, and an expected count taken from the file rather than from the citation would shrink to match what survived and answer `ok` with the cited lines gone.
@@ -332,8 +332,8 @@ After locking, the held inode is compared with the file now at the lease path, a
## 8. Retention: segment files
-A ledger is one or more SEGMENT files. `ledger.jsonl` is the segment beginning at seq 1; a later
-segment is `ledger..jsonl`, with its first seq in the name so ordering needs no file read.
+A crew log is one or more SEGMENT files. `log.jsonl` is the segment beginning at seq 1; a later
+segment is `log..jsonl`, with its first seq in the name so ordering needs no file read.
A reader walks segments in ascending first-seq order and requires seq to stay contiguous ACROSS each
boundary (`segment_gap`), because two files are independent objects: a half-finished copy or a
deleted middle segment is invisible unless it is checked. Inside one file a missing seq is a damaged
@@ -355,18 +355,18 @@ fold and a citation take, and a fold that silently stopped at a segment boundary
rather than incomplete. `get` and `page` span them too: reading the newest alone made a point read of a rotated
entry answer `None`, which a caller cannot tell from "no such entry", and made paging stop at the
boundary while reporting no cursor -- claiming the whole history had been seen when one segment had.
-**No writer rotates yet** -- a writer appends to the newest segment, which is `ledger.jsonl` in every
-ledger today. What creates the second segment, and on what trigger, is a later change that needs no
+**No writer rotates yet** -- a writer appends to the newest segment, which is `log.jsonl` in every
+crew log today. What creates the second segment, and on what trigger, is a later change that needs no
format change to land.
### Retention: whole units
-A unit's whole ledger is removed by `store.remove_unit(kind, id)`, and that is the ONE spelling of
+A unit's whole crew log is removed by `store.remove_unit(kind, id)`, and that is the ONE spelling of
deletion in this module: the retention sweep and the session permanent-delete funnel both call it,
because two callers deleting one tree two ways is two chances to get the order wrong and the order is
the entire correctness argument. It is not rotation and not a format change, and NOTHING is written
-to a ledger that is about to go -- no tombstone, no `pruned` entry. A reader holding a citation into
-it already has its answer: `resolve` reports `gone` for a pointer into a unit with no ledger at all.
+to a crew log that is about to go -- no tombstone, no `pruned` entry. A reader holding a citation into
+it already has its answer: `resolve` reports `gone` for a pointer into a unit with no crew log at all.
**Removal goes through the lease, and the lease it takes is SOLE.** Ownership is what stands between
a removal and unlinking the segments a live writer is appending to, so the removal claims it
@@ -374,7 +374,7 @@ non-blocking and is refused with `already_owned` when it cannot -- the unit is l
nothing, and a later one collects it once its writer is gone. `sole` is load bearing rather than
decorative: the lock is refcounted per process, so a plain claim against a unit THIS process is
already writing succeeds by joining that count and proves nothing, which would let a sweep running
-inside the gateway delete the ledger of a session the emitter's cached handle is mid-append to. A
+inside the gateway delete the crew log of a session the emitter's cached handle is mid-append to. A
sole holder also blocks every later claim, shared or not, until it is released; without that the
refusal is one-directional -- a writer arriving second would join the remover's own lock and append
into a unit whose files are being unlinked.
@@ -411,19 +411,19 @@ containment, and hands the removal its target -- which is not itself a link, so
path would prove nothing and one unit's id would delete another unit's history.
**What the sweep selects.** `store.sweep_expired(days)` is called by
-`history._cleanup_old_archives`, so `session.archive_retention_days` governs ledgers too: one switch,
+`history._cleanup_old_archives`, so `session.archive_retention_days` governs crew logs too: one switch,
one hourly throttle, no new config key, and a negative value disables both halves. It walks
-`ledgers/sessions` alone -- crew ledgers are never in scope, since they have no writer and no
+`crew-log/sessions` alone -- the crews' logs are never in scope, since they have no writer and no
`session/closed` to age from, and a rule invented for them now would be a guess applied to files
nothing produces. A missing root costs one directory listing, which is also what makes the sweep de
-facto gated by `KIROCREW_SESSION_LEDGER` without reading it: only the emitter creates session units.
+facto gated by `KIROCREW_CREW_LOG` without reading it: only the emitter creates session units.
Reading the flag here would be worse than not reading it, because turning it off would then strand
-every ledger already written, permanently.
+every crew log already written, permanently.
A unit is EXPIRED when its newest LIFECYCLE entry is a `session/closed` older than the cutoff.
`session/opened` and `session/closed` are the pair that moves a unit between open and closed, and the
newest of the PAIR is what decides -- not the newest close on its own. A resumed session appends to
-the ledger it already had, so `... closed ... opened ...` is a legitimate file whose session is
+the crew log it already had, so `... closed ... opened ...` is a legitimate file whose session is
running right now, and a rule that read the newest close would call it expired and delete a live
conversation's log. Entries that are neither -- a turn, a tool, an in-flight closer the emitter writes
after a teardown by design -- say nothing about the state and are skipped.
@@ -435,7 +435,7 @@ Four things are skipped regardless of age, and each is a refusal rather than an
newest segment's end, and only entries written after it can push it out; once a unit is closed the
emitter writes nothing but a handful of in-flight closers unless the session is revived, which
appends its own `session/opened`. So a lifecycle entry outside the window means a live session --
- exactly the unit that must be kept -- and the bound fails closed instead of scanning every ledger on
+ exactly the unit that must be kept -- and the bound fails closed instead of scanning every crew log on
every pass.
- **A torn tail.** Unterminated trailing bytes are what `open(repair=True)` truncates, and the sweep
cannot tell a dead writer's crash artifact from an append that has not reached its fsync -- the
@@ -451,14 +451,14 @@ Four things are skipped regardless of age, and each is a refusal rather than an
holder is NOT revoked to make the record tidy, and its shared log is not collected while it can resume.
An unreadable map withholds the claim for the same reason. Reading the map to WITHHOLD a claim is safe
in the way reading it to grant one is not: a forged or emptied map can only make the gateway assert
- less than the truth, and the sweep itself still reads nothing but the ledger. The permanent-delete
+ less than the truth, and the sweep itself still reads nothing but the crew log. The permanent-delete
funnel applies the same veto, because it deletes without consulting the reason.
`reset` is deliberately excluded even though it cold-starts its successor on a new id, because its own
`clear_sid` is guarded by `if clear_conversation and session is not None` -- so a reset that keeps the
conversation writes `session/closed {reset}` while LEAVING the old id mapped, still resumable and its
log still needed. `discarded` clears the sid unconditionally and would qualify on that test, but no
- path writes that reason into a ledger today, so admitting it would be a rule about a file nothing
+ path writes that reason into a crew log today, so admitting it would be a rule about a file nothing
produces. Every other reason -- a shutdown, a crash, an eviction, or a spelling this build does not
know -- ends the gateway's SERVICE of the session without ending the id's life. An absent, empty or
non-string reason is read as absent, never matched.
@@ -467,7 +467,7 @@ Four things are skipped regardless of age, and each is a refusal rather than an
unit back out of reach. So planting a mapping and resuming causes the log to be KEPT, never deleted:
every way of making the id reachable again also makes the unit uncollectable.
- This reason is the WHOLE authorization for deleting a unit, and it is read from the ledger rather than
+ This reason is the WHOLE authorization for deleting a unit, and it is read from the crew log rather than
from anything outside it. Asking `session_map.json` which sessions are still mapped, and keeping those,
was implemented and then removed: that file is agent-WRITABLE while this tree is bind-masked, and a
VALID empty map is not a failed read -- it reads as "nothing is revivable" and hands the trusted sweep
@@ -482,7 +482,7 @@ whose header names another unit or another schema version, or whose filename dec
its own first entry does not carry, refuses the whole read with `bad_segment`. The sweep never goes
through that path -- it reads the header line and a bounded tail directly -- so a unit the reader
refuses is still collected on age. That is deliberate. Gating removal on readability would make a
-damaged ledger IMMORTAL: the one unit nothing can use would be the one unit retention could never
+damaged crew log IMMORTAL: the one unit nothing can use would be the one unit retention could never
reclaim, and the corruption would be preserved forever by the rule meant to protect history. None of
the three refusals above needs the entries to be readable end to end, so what is dropped is a closed,
aged, unowned unit either way.
@@ -494,9 +494,9 @@ resets -- a restored tree would read as freshly closed and never expire. The fal
than skipping the unit because a damaged `time` still proves the session ended, and mtime is then the
best available bound on when writing stopped; it can only be at or after the real close, so it errs
toward keeping the file. The LAST close in the file is the one read, because a resumed session
-appends to the ledger it already had and only the newest close describes the life that ended.
+appends to the crew log it already had and only the newest close describes the life that ended.
-**Permanently deleting a session removes its ledger; closing a tab does not.** The dashboard's
+**Permanently deleting a session removes its crew log; closing a tab does not.** The dashboard's
history-delete funnel calls `remove_unit` with the ACP session id it captured BEFORE the teardown,
and only once that teardown SUCCEEDED. The gate is on success rather than on the attempt because
`destroy_if` refuses when the session was replaced by a successor generation, is busy, or still has a
@@ -505,7 +505,7 @@ now. The write lease is not a substitute for that check: ownership ends between
idle-but-live session holds nothing for the removal to be refused by. Only an id the delete claim
PROVED is used -- it is dropped on every path that disowns the slot, and a value that is not a
non-empty string reads as absent -- so an unresolvable one removes nothing and the sweep collects that
-ledger on age instead. The removal is best-effort: the transcript row is already gone by then, so
+crew log on age instead. The removal is best-effort: the transcript row is already gone by then, so
raising would ask a person to retry a delete against a row that is absent.
**Every destroy records its teardown, and without that entry neither half collects the unit.**
@@ -515,7 +515,7 @@ handle, and the write lease that handle carries, so a removal claiming the lease
`owned`; the sweep is blocked from the other side, because a unit whose newest lifecycle entry is not
a close reads as OPEN whatever its age. One missing entry defeated both paths, which is why the entry
is written where every destroy passes rather than only in the delete funnel. Writing it cannot start a
-file either -- the emitter never creates a ledger for a session that has none -- and the entry itself
+file either -- the emitter never creates a crew log for a session that has none -- and the entry itself
is what RELEASES the handle, since `on_session_closed` drops it once no turn of that session is
pinned. The delete funnel therefore FLUSHES before it claims the lease, waiting for that release; a
flush that times out is not a failure, because the entry stays owed and the sweep collects the unit
@@ -523,8 +523,8 @@ once it lands.
**The unit's own HEADER has to name the slot being deleted.** The id above arrives from
`session_map.json`, which lives inside the agent-visible tree, so a mapping that named another
-conversation's session would aim this removal at that conversation's ledger. `store.unit_header_slot`
-is the independent answer: the header is written once at creation inside the FENCED ledger tree and is
+conversation's session would aim this removal at that conversation's log. `store.unit_header_slot`
+is the independent answer: the header is written once at creation inside the FENCED crew log tree and is
never rewritten, so it does not move when a mapping does, and a unit belonging to another slot fails the
check. Slot recycling does not weaken it, because the id is what selects the unit and the slot only has
to prove that unit belonged to the slot being deleted -- a successor in the same slot is selected by its
@@ -537,7 +537,7 @@ That is the opposite of the rule for the WORK ledger, which the same funnel deli
(`session-work-ledger.md`), and the difference is mechanical rather than a re-reading of that ruling.
A work ledger is keyed by the SLOT KEY, which is recycled: a successor tab in the same slot
legitimately inherits and resumes that record, and no in-process check can prove one is not about to
-appear, so deleting it can destroy a successor's resumable state. A session ledger is keyed by the ACP
+appear, so deleting it can destroy a successor's resumable state. The session's log is keyed by the ACP
SESSION ID, which never names a different conversation, so the removal cannot reach a successor at
all; and it holds a kernel-arbitrated lease, so a writer that IS still there refuses the removal
rather than racing it. Neither property is available to the work ledger, which is why one is collected
@@ -545,6 +545,6 @@ here and the other is not.
## 9. Scope
-The first consumer is the session-ledger emitter (`docs/system-specs/modules/session-ledger-emitter.md`), which writes the ACP turn lifecycle behind the `KIROCREW_SESSION_LEDGER` flag. No crew writer exists yet, so the crew half of the ownership registry has no emitter. That is safe to leave open because the crew half is a registry of the kind's own domains rather than a list of writers: a guest crew writes those domains under its own `src`, and an app needs no entry at all, since its `app:/` prefix is its permission.
+The first consumer is the session-log emitter (`docs/system-specs/modules/crew-log-emitter.md`), which writes the ACP turn lifecycle behind the `KIROCREW_CREW_LOG` flag. No crew writer exists yet, so the crew half of the ownership registry has no emitter. That is safe to leave open because the crew half is a registry of the kind's own domains rather than a list of writers: a guest crew writes those domains under its own `src`, and an app needs no entry at all, since its `app:/` prefix is its permission.
-Read and write paths ship together deliberately: the guarantees this format makes -- contiguous seq under a lock, torn-tail repair, refusal before any byte is written -- are each a claim about what a reader sees after a writer acted, so neither half demonstrates them alone. `test/test_ledger_core.py` exercises them against real files rather than against a mock.
+Read and write paths ship together deliberately: the guarantees this format makes -- contiguous seq under a lock, torn-tail repair, refusal before any byte is written -- are each a claim about what a reader sees after a writer acted, so neither half demonstrates them alone. `test/test_crew_log_core.py` exercises them against real files rather than against a mock.
diff --git a/docs/system-specs/modules/session-ledger-emitter.md b/docs/system-specs/modules/crew-log-emitter.md
similarity index 97%
rename from docs/system-specs/modules/session-ledger-emitter.md
rename to docs/system-specs/modules/crew-log-emitter.md
index f07fc5f69e98..e600a1dc599f 100644
--- a/docs/system-specs/modules/session-ledger-emitter.md
+++ b/docs/system-specs/modules/crew-log-emitter.md
@@ -1,12 +1,12 @@
-# Session Ledger Emitter
+# Session Crew log Emitter
-`session_ledger_emit.py` turns the gateway's ACP turn lifecycle into the append-only
-per-session ledger `kiro_crew.ledger` keeps for each ACP session id. It is a **writer
+`crew_log/emit.py` turns the gateway's ACP turn lifecycle into the append-only
+per-session crew log `kiro_crew.crew_log` keeps for each ACP session id. It is a **writer
only**: it owns which facts matter and where they are known, not storage or its layout.
-The emitter is gated behind `KIROCREW_SESSION_LEDGER=1` (`constants.env_flag_enabled`,
+The emitter is gated behind `KIROCREW_CREW_LOG=1` (`constants.env_flag_enabled`,
read per call, truthy set `{1, true, yes, on}`) and defaults **OFF**, so this module is
-inert until a later change turns it on. With the flag off no ledger directory is created
+inert until a later change turns it on. With the flag off no crew log directory is created
and no call reaches the storage library.
There is ONE flag. An earlier design gated streamed deltas behind a second one; that
@@ -22,11 +22,11 @@ to the writer would charge every user for a feature that is off by default.
## Identity
-The ledger key is the **ACP session id**, not the slot key. A slot outlives its ACP
+The crew log key is the **ACP session id**, not the slot key. A slot outlives its ACP
session: an agent switch, a model switch, or a project change calls
`SessionLifecycle.reset`, which pops the live session and lets the next turn cold-start a
fresh one. When that reset cleared the conversation the successor has a new id and a new
-ledger; when it did not, the next cold start resumes the same id via `session/load`, so
+crew log; when it did not, the next cold start resumes the same id via `session/load`, so
`Ledger.exists` decides between create and open and a resumed session never truncates it.
`owner` and `agent` are header fields, written once at create time. There is no turn id in
@@ -290,7 +290,7 @@ last step's completion, then the turn's own. The `finally` rather than the norma
because several recovery paths return before the terminal event is reached, and a
stash that never runs leaves a turn open in the file forever.
-The map is SEEDED from the file when a claim re-attaches to an existing ledger,
+The map is SEEDED from the file when a claim re-attaches to an existing crew log,
because the in-memory map cannot survive the restart that makes a collision
possible: without seeding, a rerun after a restart writes attempt 1 at an ordinal
whose file already has an attempt 1. Seeding reads that session's `turn/started`
@@ -456,7 +456,7 @@ four characters per token, the same figure `dashboard/handlers/usage.py` uses. T
entry says so in `tokens_estimated`. The only exact tokenizer available is the
wrong one for the served model, and a fabricated exact count would be worse than
an admitted estimate. Three blocks the design names -- steering, tool specs and
-injected ledger context -- have no opening marker for `split_blocks` to classify, so
+injected crew log context -- have no opening marker for `split_blocks` to classify, so
their characters land in its unclassified bucket, which this entry reports as a
single `other` source. Three zeroed sources would claim a measurement nobody took.
@@ -489,11 +489,11 @@ vocabulary a statement about what the log contains rather than a wish list, whic
makes a reader's `known=` set worth declaring.
Any of them may come back when a real source exists: while the format is pre-release
-(`ledger-core.md` section 5) that is an ordinary change, and after the freeze point it is
+(`crew-log-core.md` section 5) that is an ordinary change, and after the freeze point it is
an additive one, since re-adding a type is exactly the case the `ignorable` marker and the
unknown-type refusal already handle.
-Every compaction reaches the ledger on exactly one of those two paths. A reading kiro-cli
+Every compaction reaches the crew log on exactly one of those two paths. A reading kiro-cli
reset to unknown mid-turn defers its verdict to the next confirmed reading, and that
settlement is the first measurement the compaction has; recording it there is what keeps
the hardest-to-measure compactions from being the ones missing from the log. On that path
@@ -563,8 +563,8 @@ not a session id, so there is nothing to key an entry by. They land with that pl
Tool arguments and tool results are recorded as a DIGEST and a byte count, never as
bytes; message bodies ARE recorded, redacted, and split when they exceed the line cap.
A tool call is identified by
-its `tool_call_id` inside `data`, not by `ref`: a `Ref` cites lines of another ledger, and
-an ACP frame is not a ledger unit. That id is the join key the transcript already uses.
+its `tool_call_id` inside `data`, not by `ref`: a `Ref` cites lines of another crew log, and
+an ACP frame is not a crew log unit. That id is the join key the transcript already uses.
A tool's `name` and `server` carry ONLY the trusted `_meta.kiro` identity, so both are
empty when the backend supplies none, and the call id still joins the entry to the
@@ -617,7 +617,7 @@ Tombstones, projections, a reader, and any UI are out of scope.
## Failure policy
Every entry point is fail-soft and returns `None`. A storage error is caught, reported
-once per process at warning level, and demoted to debug afterwards so a broken ledger
+once per process at warning level, and demoted to debug afterwards so a broken crew log
cannot flood the log. This matters at three sites: the approval decision resolves on the
websocket handler task, so an exception there would break the click handler and hang the
waiting turn; `_default_session_model` runs inside `asyncio.to_thread` behind a
@@ -640,7 +640,7 @@ it in the file: writing them while it waits would put that log on disk in an ord
happened, which a fold reads as fact and cannot detect. Producers append to the same bucket,
so a later write queues behind the retained batch by construction, and the inline fast path
is off for a session that owes anything -- a synchronous caller queues too rather than
-overtaking its own earlier entry. The backoff is per session, so one wedged ledger paces only
+overtaking its own earlier entry. The backoff is per session, so one wedged crew log paces only
itself.
It is BOUNDED, and that bound is the honest half. Entries live in memory until they are
@@ -663,7 +663,7 @@ anything.
`already_owned` is a refusal on the same terms, and it is the one that is not about the
entry. Another PROCESS holds that unit's write ownership, so this gateway appends nothing --
-see "Write ownership" in the ledger-core spec. Ownership lasts as long as the owning process,
+see "Write ownership" in the crew-log core spec. Ownership lasts as long as the owning process,
which no attempt budget outlasts, so retrying is the same waste with a worse consequence:
every later entry for that session would queue behind one waiting for a process to exit. The
degradation is therefore that a second gateway claiming a live session LOSES ITS OWN ENTRIES,
@@ -706,12 +706,12 @@ ordinal stamped on it would name a turn that did not cause it.
The envelope's `thread` field is left UNSET on every session entry. `thread` points at
another LINE's `seq`, which is only knowable for a unit whose anchor line is written
-before the entries that cite it; that is the crew ledger's shape, not this one's.
+before the entries that cite it; that is the crew's log's shape, not this one's.
## Reconnect is not resume
Open handles are cached with a bound, so a handle can go missing and the next emit
-reopens the ledger. That reopen is a RECONNECT and it never asks for the interrupted-turn
+reopens the crew log. That reopen is a RECONNECT and it never asks for the interrupted-turn
repair: a handle absent from the cache says nothing about the writer's health, and the
turn is typically still running, so closing it would append a `turn/completed
{interrupted}` mid-turn and then keep writing past it.
@@ -752,7 +752,7 @@ The writer holds two rules at once, and neither may be traded for the other.
A lifecycle record is never dropped while the process is healthy, at any depth of
backlog. A hole in an append-only log is permanent and silent: a reader cannot tell a turn that
never completed from one whose completion was discarded, which is precisely the distinction this
-ledger exists to record, and several subsystems read it to decide what happened. A crash-shaped
+crew log exists to record, and several subsystems read it to decide what happened. A crash-shaped
loss is different in kind -- the repair names and closes what a kill left behind -- but a discard
chosen while nothing is wrong has nothing that can recover it and no reader that can detect it.
So there is no cap past which an entry is thrown away, and an entry is given up on only when the
@@ -775,7 +775,7 @@ keeping up costs memory rather than turn latency. An earlier design let a satura
wait for queue room and, past a deadline, append for itself; both of those put a turn behind
the disk, which is the thing this path exists to prevent.
-The buffer is keyed per session, because each session is a separate file and one slow ledger
+The buffer is keyed per session, because each session is a separate file and one slow crew log
must not reorder another's entries.
What bucketing does NOT buy is latency isolation, and the distinction matters enough to state:
@@ -842,6 +842,6 @@ the registration happens immediately before the writer pool is first asked for w
pool's own handler still runs ahead of this one.
There is no second stream to reconcile with. The parallel lifecycle-event package this
-module was designed alongside is retired, so `kiro_crew.ledger` is the only structured
+module was designed alongside is retired, so `kiro_crew.crew_log` is the only structured
record of a session's history and this module is its only writer;
`docs/request-for-change/rfc-append-only-ledger.md` is the decision of record.
diff --git a/docs/system-specs/modules/session-work-ledger.md b/docs/system-specs/modules/session-work-ledger.md
index 362923c078ad..3324ca9dd705 100644
--- a/docs/system-specs/modules/session-work-ledger.md
+++ b/docs/system-specs/modules/session-work-ledger.md
@@ -29,7 +29,7 @@ maintenance primitive, not part of the history-delete request path, and its one
caller is the operator sweep in [Cleanup](#cleanup).
That reasoning is specific to THIS store's identity and does not carry to the
-append-only session ledger (`ledger-core.md`), which the same funnel does remove.
+append-only session ledger (`crew-log-core.md`), which the same funnel does remove.
The hazard here is key REUSE: this store is keyed by the slot key, so a successor
tab in the same slot legitimately inherits and resumes the record. A session
ledger is keyed by the ACP session id, which never names a different
diff --git a/src/kiro_crew/acp/_dispatch.py b/src/kiro_crew/acp/_dispatch.py
index daeb54064258..fcda941f9b3e 100644
--- a/src/kiro_crew/acp/_dispatch.py
+++ b/src/kiro_crew/acp/_dispatch.py
@@ -1897,7 +1897,7 @@ def _measure_tool_output(redacted: str) -> tuple[str, int]:
two outputs sharing their first bounded characters would hash the same, and
the byte count would under-report every output past the bound.
- Computed only while the ledger is on. The pair has one consumer, the emitter,
+ Computed only while the crew log is on. The pair has one consumer, the emitter,
which is gated on the same flag -- so with the flag off this is work nothing
reads, over text as large as a file the model just printed. ``("", -1)`` is
the emitter's own spelling for a field it must not record, distinct from a
@@ -1906,10 +1906,10 @@ def _measure_tool_output(redacted: str) -> tuple[str, int]:
One function for both parser sites (this module's terminal-frame builder and
the streaming update parser in ``client``) so the digest they produce cannot
- drift apart: a ledger reader comparing two entries has no way to tell which
+ drift apart: a crew log reader comparing two entries has no way to tell which
parser produced either one.
"""
- from kiro_crew.session_ledger_emit import enabled as _ledger_enabled
+ from kiro_crew.crew_log.emit import enabled as _ledger_enabled
if not _ledger_enabled():
return "", -1
@@ -2011,7 +2011,7 @@ def _build_tool_result_event(update: dict[str, Any], cache_scope: str = "") -> A
)
joined = "\n".join(output_parts)
_redacted = _redact(joined)
- # Measured only when the ledger is on. These two fields have exactly one
+ # Measured only when the crew log is on. These two fields have exactly one
# consumer -- the flag-gated emitter -- so hashing every tool result while it
# is off is work nothing reads, and a tool result is as large as a file the
# model just printed. The defaults carry "not recorded" rather than a
diff --git a/src/kiro_crew/config/paths.py b/src/kiro_crew/config/paths.py
index 0bbeed521c71..48407e8e6327 100644
--- a/src/kiro_crew/config/paths.py
+++ b/src/kiro_crew/config/paths.py
@@ -467,8 +467,8 @@ def ensure_data_home() -> Path:
exc_info=True,
)
# UNCONDITIONAL, not in an `else`. The home failing to tighten is the case
- # where the ledger root's own mode matters MOST: it is the only remaining
- # boundary, and skipping it there leaves every lazily created ledger
+ # where the crew log root's own mode matters MOST: it is the only remaining
+ # boundary, and skipping it there leaves every lazily created crew log
# directory at the process umask. The helper reports its own failure, so a
# filesystem that refuses both still boots.
_ensure_ledger_root(home, restrict_dir_to_owner)
@@ -476,7 +476,7 @@ def ensure_data_home() -> Path:
def _ensure_ledger_root(home: Path, restrict: Callable[[Path], None]) -> None:
- """Establish ``/ledgers`` owner-only, before anything writes a ledger.
+ """Establish ``/crew-log`` owner-only, before anything writes a crew log.
Eager rather than lazy because two other mechanisms are stated per PATH and
both are weaker while the name does not exist: the Linux sandbox bind-mask
@@ -495,12 +495,12 @@ def _ensure_ledger_root(home: Path, restrict: Callable[[Path], None]) -> None:
exotic filesystem must not make the gateway unbootable, and the sandbox mask
plus the file-tool fence still stand if this one assertion cannot be made.
"""
- root = home / "ledgers"
+ root = home / "crew-log"
try:
canonical_home = home.resolve()
- if root.is_symlink() or root.resolve() != canonical_home / "ledgers":
+ if root.is_symlink() or root.resolve() != canonical_home / "crew-log":
logger.warning(
- "Refusing ledger root %s: it is a link or resolves outside %s",
+ "Refusing crew log root %s: it is a link or resolves outside %s",
root,
canonical_home,
)
@@ -509,20 +509,20 @@ def _ensure_ledger_root(home: Path, restrict: Callable[[Path], None]) -> None:
restrict(root)
# The kind directories under it need the same two properties, and for the
# same reason: containment resolves its base first, so a linked
- # ``ledgers/`` would make the link's target the containment root and
- # every ledger path beneath it would pass while living outside this tree.
+ # ``crew-log/`` would make the link's target the containment root and
+ # every crew log path beneath it would pass while living outside this tree.
# Establishing them here is what the argument above makes for the root --
# a name that does not exist has no mode to inherit and is skipped by the
- # sandbox mask. The names are the spellings ``ledger/store.py::_ROOT_DIR``
+ # sandbox mask. The names are the spellings ``crew_log/store.py::_ROOT_DIR``
# maps its kinds to; this module imports no ``kiro_crew`` package at module
# scope, so they are stated rather than read.
for leaf in ("crews", "sessions"):
kind_root = root / leaf
if kind_root.is_symlink() or (
- kind_root.exists() and kind_root.resolve() != canonical_home / "ledgers" / leaf
+ kind_root.exists() and kind_root.resolve() != canonical_home / "crew-log" / leaf
):
logger.warning(
- "Refusing ledger kind directory %s: it is a link or resolves outside %s",
+ "Refusing crew log kind directory %s: it is a link or resolves outside %s",
kind_root,
canonical_home,
)
@@ -531,7 +531,7 @@ def _ensure_ledger_root(home: Path, restrict: Callable[[Path], None]) -> None:
restrict(kind_root)
except (OSError, RuntimeError):
logger.warning(
- "Cannot restrict %s to owner-only; ledgers may be readable by other users",
+ "Cannot restrict %s to owner-only; crew logs may be readable by other users",
root,
exc_info=True,
)
diff --git a/src/kiro_crew/crew_log/__init__.py b/src/kiro_crew/crew_log/__init__.py
new file mode 100644
index 000000000000..9719dde52982
--- /dev/null
+++ b/src/kiro_crew/crew_log/__init__.py
@@ -0,0 +1,191 @@
+"""Append-only crew logs for crews and sessions -- the storage layer, nothing else.
+
+The format, the rules and how this stream relates to the lifecycle event track are
+specified in ``docs/system-specs/modules/crew-log-core.md``. Two units, one file
+each, the gateway the only writer::
+
+ from kiro_crew.crew_log import Ledger
+
+ crew = Ledger.create("crew", "qa")
+ crew.append("member/joined", {"who": "s-7f3a"}, src="gateway")
+
+A crew header carries nothing but the unit's id and its creation time, which is
+why the example passes neither: a display name belongs to the members store, which
+owns it and can change it, and ``create`` refuses an unknown header field with
+``bad_header_field`` rather than dropping it.
+
+This package holds no dashboard, route, tool or migration code. It reads and
+writes its own files and imports only path, lock and containment primitives, so
+a consumer can be added without this layer learning about it.
+
+The public names are re-exported LAZILY (:pep:`562`): importing the package, or
+one of its submodules such as ``emit``, does not pull in ``store``, ``schema`` or
+``lease``. Those load on first attribute access -- when a call actually reaches
+storage -- so the flag-off gateway boot path pays for none of it.
+"""
+
+from __future__ import annotations
+
+import importlib
+from typing import TYPE_CHECKING, Any
+
+#: Public name -> submodule that defines it. Attribute access loads the submodule
+#: on demand, so the storage layer stays unloaded until a caller reaches it.
+_EXPORTS: dict[str, str] = {
+ # entry_types
+ "ENTRY_TYPES": "entry_types",
+ "SESSION_ENTRY_TYPES": "entry_types",
+ "EntryType": "entry_types",
+ "Field": "entry_types",
+ "declaration_for": "entry_types",
+ "render_markdown": "entry_types",
+ "validate_data": "entry_types",
+ # errors
+ "CODE_ALREADY_EXISTS": "errors",
+ "CODE_ALREADY_OWNED": "errors",
+ "CODE_BAD_DATA": "errors",
+ "CODE_BAD_DATA_FIELD": "errors",
+ "CODE_BAD_HEADER": "errors",
+ "CODE_BAD_HEADER_FIELD": "errors",
+ "CODE_BAD_KIND": "errors",
+ "CODE_BAD_REF": "errors",
+ "CODE_BAD_ROOT": "errors",
+ "CODE_BAD_SEGMENT": "errors",
+ "CODE_BAD_SRC": "errors",
+ "CODE_BAD_THREAD": "errors",
+ "CODE_BAD_TYPE": "errors",
+ "CODE_ENTRY_TOO_LARGE": "errors",
+ "CODE_EVENT_TYPE_NOT_OWNED": "errors",
+ "CODE_INVALID_ID": "errors",
+ "CODE_NAMESPACE_VIOLATION": "errors",
+ "CODE_NO_LEDGER": "errors",
+ "CODE_SEGMENT_GAP": "errors",
+ "CODE_UNKNOWN_ENTRY_TYPE": "errors",
+ "CODE_UNSUPPORTED_VERSION": "errors",
+ "IndeterminateAppend": "errors",
+ "LedgerError": "errors",
+ # schema
+ "FIXED_SOURCES": "schema",
+ "KIND_CREW": "schema",
+ "KIND_FIXED_SOURCES": "schema",
+ "KIND_SESSION": "schema",
+ "KIND_SOURCE_PREFIXES": "schema",
+ "KINDS": "schema",
+ "MAX_ENTRY_BYTES": "schema",
+ "MAX_REF_SPAN": "schema",
+ "SCHEMA_VERSION": "schema",
+ "TYPE_OWNERSHIP": "schema",
+ "CrewHeader": "schema",
+ "Entry": "schema",
+ "Header": "schema",
+ "Ref": "schema",
+ "SessionHeader": "schema",
+ "SessionThread": "schema",
+ # store
+ "DEFAULT_PAGE_LIMIT": "store",
+ "LOG_FILE": "store",
+ "MAX_PAGE_LIMIT": "store",
+ "STATUS_CORRUPT": "store",
+ "STATUS_GONE": "store",
+ "STATUS_OK": "store",
+ "STATUS_PRUNED": "store",
+ "Ledger": "store",
+ "Page": "store",
+ "Resolution": "store",
+ "ledger_dir": "store",
+ "ledger_path": "store",
+ "ledger_root": "store",
+ "now_ms": "store",
+ "segment_first_seqs": "store",
+ "segment_paths": "store",
+}
+
+__all__ = sorted(_EXPORTS)
+
+
+def __getattr__(name: str) -> Any:
+ """Resolve a public name by importing its submodule on first access (:pep:`562`)."""
+ module = _EXPORTS.get(name)
+ if module is None:
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+ submodule = importlib.import_module(f"{__name__}.{module}")
+ value = getattr(submodule, name)
+ globals()[name] = value # cache so the next access skips the lookup
+ return value
+
+
+def __dir__() -> list[str]:
+ return sorted(set(globals()) | set(_EXPORTS))
+
+
+if TYPE_CHECKING: # keep the names visible to type checkers and IDEs
+ from kiro_crew.crew_log.entry_types import ( # noqa: F401
+ ENTRY_TYPES,
+ SESSION_ENTRY_TYPES,
+ EntryType,
+ Field,
+ declaration_for,
+ render_markdown,
+ validate_data,
+ )
+ from kiro_crew.crew_log.errors import ( # noqa: F401
+ CODE_ALREADY_EXISTS,
+ CODE_ALREADY_OWNED,
+ CODE_BAD_DATA,
+ CODE_BAD_DATA_FIELD,
+ CODE_BAD_HEADER,
+ CODE_BAD_HEADER_FIELD,
+ CODE_BAD_KIND,
+ CODE_BAD_REF,
+ CODE_BAD_ROOT,
+ CODE_BAD_SEGMENT,
+ CODE_BAD_SRC,
+ CODE_BAD_THREAD,
+ CODE_BAD_TYPE,
+ CODE_ENTRY_TOO_LARGE,
+ CODE_EVENT_TYPE_NOT_OWNED,
+ CODE_INVALID_ID,
+ CODE_NAMESPACE_VIOLATION,
+ CODE_NO_LEDGER,
+ CODE_SEGMENT_GAP,
+ CODE_UNKNOWN_ENTRY_TYPE,
+ CODE_UNSUPPORTED_VERSION,
+ IndeterminateAppend,
+ LedgerError,
+ )
+ from kiro_crew.crew_log.schema import ( # noqa: F401
+ FIXED_SOURCES,
+ KIND_CREW,
+ KIND_FIXED_SOURCES,
+ KIND_SESSION,
+ KIND_SOURCE_PREFIXES,
+ KINDS,
+ MAX_ENTRY_BYTES,
+ MAX_REF_SPAN,
+ SCHEMA_VERSION,
+ TYPE_OWNERSHIP,
+ CrewHeader,
+ Entry,
+ Header,
+ Ref,
+ SessionHeader,
+ SessionThread,
+ )
+ from kiro_crew.crew_log.store import ( # noqa: F401
+ DEFAULT_PAGE_LIMIT,
+ LOG_FILE,
+ MAX_PAGE_LIMIT,
+ STATUS_CORRUPT,
+ STATUS_GONE,
+ STATUS_OK,
+ STATUS_PRUNED,
+ Ledger,
+ Page,
+ Resolution,
+ ledger_dir,
+ ledger_path,
+ ledger_root,
+ now_ms,
+ segment_first_seqs,
+ segment_paths,
+ )
diff --git a/src/kiro_crew/session_ledger_emit.py b/src/kiro_crew/crew_log/emit.py
similarity index 96%
rename from src/kiro_crew/session_ledger_emit.py
rename to src/kiro_crew/crew_log/emit.py
index 0a71a23d48d5..a060e1deaf0d 100644
--- a/src/kiro_crew/session_ledger_emit.py
+++ b/src/kiro_crew/crew_log/emit.py
@@ -1,12 +1,12 @@
-"""Write the ACP turn lifecycle to an append-only per-session ledger.
+"""Write the ACP turn lifecycle to an append-only per-session crew log.
-See ``docs/system-specs/modules/session-ledger-emitter.md`` for the contract this
+See ``docs/system-specs/modules/crew-log-emitter.md`` for the contract this
module implements. In short: each entry point is a one-line call at a site in the
dashboard chat path where a lifecycle fact is already known, and every one of
-them is **fail-soft** -- a ledger error is reported once and then swallowed, so a
-broken ledger can never break a turn.
+them is **fail-soft** -- a crew log error is reported once and then swallowed, so a
+broken crew log can never break a turn.
-The whole module is inert unless ``KIROCREW_SESSION_LEDGER`` is truthy. With the
+The whole module is inert unless ``KIROCREW_CREW_LOG`` is truthy. With the
flag off nothing is created and every call returns immediately.
The grouping identity of a session entry is ``data.turn`` -- the runner's own turn
@@ -19,7 +19,7 @@
The envelope's ``thread`` field is left unset here. ``thread`` points at another
LINE's ``seq``, which only a unit whose anchor line is written before the entries
-citing it can supply; that is the crew ledger's shape, not this one's.
+citing it can supply; that is the crew's log shape, not this one's.
Three things are recorded differently from a naive reading of the lifecycle, all
deliberate and all explained in the spec:
@@ -27,8 +27,8 @@
* ``compaction/applied`` carries context-usage **percentages**, because the
compaction boundary never learns a raw token count.
* A tool call and an approval are identified by an id inside ``data``, not by
- ``ref``. A ``Ref`` is a citation of another ledger's lines, and a tool call id
- names a frame on the ACP stream, which is not a ledger unit.
+ ``ref``. A ``Ref`` is a citation of another crew log's lines, and a tool call id
+ names a frame on the ACP stream, which is not a crew log unit.
* A turn that ends without its terminal event is still CLOSED, by the turn's own
``finally``: ``stop_reason: "failed"``, an ``error`` naming the exception class
when one was caught, and no ``tokens`` or ``credits``, because none were
@@ -58,7 +58,7 @@
The envelope's ``thread`` field stays unset on a session entry. ``thread`` points
at another LINE's seq, which is only knowable for a unit whose anchor line is
-written before the entries that cite it; that is the crew ledger's shape, not
+written before the entries that cite it; that is the crew's log shape, not
this one's.
Two rules govern the writer, and neither gives way to the other: a lifecycle
@@ -109,7 +109,7 @@
logger = logging.getLogger(__name__)
#: Turning this on is a separate change from landing the emitter.
-SESSION_LEDGER_ENV = "KIROCREW_SESSION_LEDGER"
+CREW_LOG_ENV = "KIROCREW_CREW_LOG"
_KIND = "session"
@@ -143,7 +143,7 @@
#: The label a block with no marker of its own is reported under. ``split_blocks``
#: classifies by opening marker, and three blocks the design names -- steering,
-#: tool specs, injected ledger context -- have none, so their characters land in
+#: tool specs, injected crew log context -- have none, so their characters land in
#: its unclassified bucket. Renaming that bucket here keeps the entry honest
#: about being a remainder rather than inventing three zeroed sources.
_OTHER_SOURCE = "other"
@@ -218,7 +218,7 @@ class _RetryState:
that wrote something is not wedged, however much is still owed.
``not_before`` is the monotonic instant the next pass may claim the bucket. It
- is per session, so a wedged ledger's backoff paces only its own entries.
+ is per session, so a wedged crew log's backoff paces only its own entries.
"""
attempts: int = 0
@@ -261,7 +261,7 @@ class _PendingJob:
counted: bool = False
#: Never refused at the memory ceiling. The ceiling bounds the memory held by
#: PAYLOAD entries; two jobs are O(1) per session and must not be refusable by
- #: it. The file-CREATING record: refusing it means the ledger never exists, so
+ #: it. The file-CREATING record: refusing it means the crew log never exists, so
#: every later entry for that session -- including the ``write/dropped`` marker
#: that would report the damage -- is silently discarded and not counted. The
#: loss MARKER: a record whose job is to report that the ceiling fired must not
@@ -270,7 +270,7 @@ class _PendingJob:
exempt_ceiling: bool = False
#: Run once when this job is given up on permanently -- a refusal, or its
#: attempt budget spent. The file-creating record uses it to flag a session
- #: whose ledger never came into being, so later entries for it count as loss
+ #: whose crew log never came into being, so later entries for it count as loss
#: instead of returning a silent no-op. Never raises into the writer.
on_permanent_drop: Callable[[], None] | None = None
@@ -326,7 +326,7 @@ class _PendingJob:
#: How long the writer waits before retrying a batch whose append raised, and the
#: ceiling that wait doubles to. The errors worth retrying are the transient ones
#: -- an ENOSPC a rotation clears, an EIO on a network mount -- which resolve on a
-#: timescale a short backoff covers. The wait is per SESSION, so one wedged ledger
+#: timescale a short backoff covers. The wait is per SESSION, so one wedged crew log
#: paces only itself and another session's entries keep flowing.
_RETRY_BACKOFF_SECONDS = 0.05
_RETRY_BACKOFF_MAX_SECONDS = 2.0
@@ -374,7 +374,7 @@ class _PendingJob:
#: session -> the appends waiting to be written, in the order they were made.
#: Producers only ever append here; the writer prepends a batch it could not
#: write. Keyed per session because each session is a separate file, so one slow
-#: ledger cannot reorder another's entries -- and because a retained batch has to
+#: crew log cannot reorder another's entries -- and because a retained batch has to
#: hold back exactly the entries that belong AFTER it, which is that session's
#: bucket and nothing else. A bucket is popped whole and is never left empty.
#: ``nbytes`` is an O(1) size hint the producer already had -- the body length
@@ -404,8 +404,8 @@ class _PendingJob:
_inline: "set[str]" = set()
#: How many appends were dropped after their attempt budget was spent.
_dropped_count = 0
-#: Sessions whose ledger CREATION failed permanently -- the file-creating record
-#: was refused or spent its attempt budget, so no ledger file exists and no later
+#: Sessions whose crew log CREATION failed permanently -- the file-creating record
+#: was refused or spent its attempt budget, so no crew log file exists and no later
#: append for the session can ever land. Distinct from a session that legitimately
#: has none (feature off, never opened): that stays a silent policy no-op, this
#: makes later discards COUNT as loss instead of returning a silent None. Cleared
@@ -502,20 +502,20 @@ def _ledger() -> Any:
gate -- pure glue, no import-time work, no shutdown hook registered until a
write happens -- and the package it fronts (the store, the schema and the
lease) stays unloaded until one of the entry points below reaches storage. A
- launch with ``KIROCREW_SESSION_LEDGER`` unset never imports it, because
+ launch with ``KIROCREW_CREW_LOG`` unset never imports it, because
``enabled()`` refuses before any of those paths is taken.
"""
global _subsystem
if _subsystem is None:
- from kiro_crew import ledger
+ from kiro_crew import crew_log
- _subsystem = ledger
+ _subsystem = crew_log
return _subsystem
def enabled() -> bool:
"""True when the emitter should write. Read per call, never cached."""
- return env_flag_enabled(SESSION_LEDGER_ENV)
+ return env_flag_enabled(CREW_LOG_ENV)
def _notify() -> None:
@@ -638,7 +638,7 @@ def reset_caches() -> None:
across, and so is the retry state behind it, and so is the claim on the writer.
Reaching that point means the writer is wedged, and the handles those jobs
would have written through are being dropped in this same call -- so keeping
- them would leave the writer retrying entries against a ledger this process has
+ them would leave the writer retrying entries against a crew log this process has
stopped believing in. Clearing the claim matters as much as clearing the
buffer: a claim nothing will ever release makes every later barrier report a
batch in flight, so one wedged pass would otherwise fail every ``flush`` for
@@ -710,21 +710,21 @@ def session_id_of(client: Any) -> str:
def _report(what: str, exc: BaseException) -> None:
- """Report a ledger failure once at warning level, then stay quiet."""
+ """Report a crew log failure once at warning level, then stay quiet."""
global _warned
with _lock:
first = not _warned
_warned = True
if first:
logger.warning(
- "session ledger writes are failing (%s: %s%s); further failures "
+ "session log writes are failing (%s: %s%s); further failures "
"are logged at debug only",
what,
exc,
f", code={getattr(exc, 'code', '')}" if getattr(exc, "code", "") else "",
)
else:
- logger.debug("session ledger %s failed", what, exc_info=True)
+ logger.debug("session log %s failed", what, exc_info=True)
def _on_event_loop() -> bool:
@@ -739,7 +739,7 @@ def _on_event_loop() -> bool:
def _permanent(exc: BaseException) -> bool:
"""Whether retrying *exc* is pointless because it will be refused again.
- A :class:`~kiro_crew.ledger.LedgerError` is a REFUSAL, not a failure: the
+ A :class:`~kiro_crew.crew_log.LedgerError` is a REFUSAL, not a failure: the
storage layer declines the entry before any byte is written, so the file is
byte-identical and nothing about this process's next attempt is different.
Either the entry does not fit the format, in which case the same verdict comes
@@ -807,7 +807,7 @@ def _note_stall_if_any() -> None:
_stall_reported = True
held = _pending_count
logger.error(
- "session ledger writer stalled: %s has been in progress for over %.0fs and "
+ "session log writer stalled: %s has been in progress for over %.0fs and "
"has neither returned nor failed; %d append(s) are waiting behind it",
what,
_WRITE_STALL_SECS,
@@ -986,7 +986,7 @@ def _buffer(session_id: str, pending: _PendingJob) -> None:
own cleanup still runs so nothing waits on a record that will never land.
Two jobs are EXEMPT from the ceiling (``_PendingJob.exempt_ceiling``) and can
- never be refused here: the record that CREATES a session's ledger file, and a
+ never be refused here: the record that CREATES a session's crew log file, and a
loss marker. Both are O(1) per session, so neither is the memory the ceiling
bounds -- and refusing the creating record destroys that session's whole log
plus every loss marker that would have reported the damage, while refusing a
@@ -1103,7 +1103,7 @@ def _drop(session_id: str, jobs: "list[_PendingJob]", *, mark: bool = False) ->
_dropped_reported.add(session_id)
if first:
logger.warning(
- "session ledger gave up on %d append(s) for session %s after %d failed "
+ "session log gave up on %d append(s) for session %s after %d failed "
"attempts; %d dropped in total. That log's tail is short by them. "
"Further losses for this session are logged at debug until one lands",
len(jobs),
@@ -1113,7 +1113,7 @@ def _drop(session_id: str, jobs: "list[_PendingJob]", *, mark: bool = False) ->
)
else:
logger.debug(
- "session ledger dropped %d more append(s) for session %s",
+ "session log dropped %d more append(s) for session %s",
len(jobs),
session_id,
)
@@ -1206,7 +1206,7 @@ def _note_progress(session_id: str) -> None:
_overflow_reported.discard(session_id)
if recovered:
logger.warning(
- "session ledger writes for session %s are landing again; the "
+ "session log writes for session %s are landing again; the "
"write/dropped marker was appended before later entries",
session_id,
)
@@ -1256,7 +1256,7 @@ def _start_drain() -> None:
_draining = False
_drain_future = None
_notify()
- _report("scheduling the ledger writer", exc)
+ _report("scheduling the crew log writer", exc)
return
with _lock:
# Published so the barriers can tell a pass that is still coming from one
@@ -1315,7 +1315,7 @@ def _next_pass_delay_locked(deferred_loss: "set[str] | None" = None) -> float:
has asked for quiescence, which is the only thing that pause gives up. Nothing
claimable means every owed bucket is inside a backoff or held by an inline
write, so the wait is exactly what the soonest of those has left: the writer
- sleeps instead of spinning, and one wedged ledger paces only its own entries.
+ sleeps instead of spinning, and one wedged crew log paces only its own entries.
A shutdown does not COLLAPSE the backoff -- burning six attempts in no time at
all against a filesystem that needed a moment converts a delay into a guaranteed
@@ -1526,7 +1526,7 @@ def _report_high_water() -> None:
held = _pending_count
if first:
logger.warning(
- "session ledger has %d appends buffered, past the %d mark: the writer "
+ "session log has %d appends buffered, past the %d mark: the writer "
"is not keeping up and the backlog is held in memory rather than "
"dropped; further growth is not reported",
held,
@@ -1544,7 +1544,7 @@ def _report_overflow(session_id: str, total: int) -> None:
high-water mark reports.
"""
logger.error(
- "session ledger buffer full for session %s: the writer is too far behind "
+ "session log buffer full for session %s: the writer is too far behind "
"to hold more, so its newest appends are being rejected and counted; %d "
"rejected in total. That log's tail is short by them until writes catch "
"up. Further overflow for this session is not reported until one lands",
@@ -1662,7 +1662,7 @@ def drain_for_shutdown(timeout: float = _SHUTDOWN_DRAIN_SECONDS) -> bool:
with _drained:
drained = _drained.wait_for(_quiet, timeout=timeout)
except Exception as exc:
- _report("draining the session ledger for shutdown", exc)
+ _report("draining the session log for shutdown", exc)
drained = False
if not drained:
with _lock:
@@ -1677,7 +1677,7 @@ def drain_for_shutdown(timeout: float = _SHUTDOWN_DRAIN_SECONDS) -> bool:
try:
drained = _drain_inline_until(time.monotonic() + _SECOND_CHANCE_DRAIN_SECONDS)
except Exception as exc:
- _report("draining the session ledger for shutdown", exc)
+ _report("draining the session log for shutdown", exc)
drained = False
if not drained:
with _lock:
@@ -1685,7 +1685,7 @@ def drain_for_shutdown(timeout: float = _SHUTDOWN_DRAIN_SECONDS) -> bool:
loss_markers = len(_pending_loss)
running = _writer_busy_locked()
logger.warning(
- "session ledger did not finish writing within %.1fs of shutdown; "
+ "session log did not finish writing within %.1fs of shutdown; "
"%d append(s) buffered, %d loss marker(s) owed, batch in flight=%s",
timeout,
held,
@@ -1788,7 +1788,7 @@ def _drop_oldest_live() -> None:
shed += 1
if shed:
logger.error(
- "session ledger is tracking more than %d turns in flight and shed %d "
+ "session log is tracking more than %d turns in flight and shed %d "
"closed-but-undrained record(s): turns are ending without their "
"terminal event landing",
_MAX_LIVE_TURNS,
@@ -1798,7 +1798,7 @@ def _drop_oldest_live() -> None:
if not _live_overage_reported:
_live_overage_reported = True
logger.error(
- "session ledger is tracking %d turns in flight, over the %d "
+ "session log is tracking %d turns in flight, over the %d "
"ceiling, and every record is a turn still running -- accepting "
"the overage rather than evicting a live turn and restarting its "
"numbering",
@@ -1855,11 +1855,11 @@ def _remember(session_id: str, ledger: Any) -> None:
def _handle(session_id: str) -> Any:
- """An open ledger for *session_id*, or None when it has none. Never creates one.
+ """An open crew log for *session_id*, or None when it has none. Never creates one.
- None means exactly one thing: this session has no ledger file AND its creation
+ None means exactly one thing: this session has no crew log file AND its creation
was never attempted (feature off, never opened), so an event for it is
- deliberately not written rather than starting a ledger with no header. That is
+ deliberately not written rather than starting a crew log with no header. That is
a policy no-op, not a loss, and it is not counted as one.
A session whose creation FAILED permanently is different: it was opened, so its
@@ -1873,7 +1873,7 @@ def _handle(session_id: str) -> Any:
make the job succeed with nothing written, and the entry would vanish with no
retry and no entry in :func:`dropped_writes`. That is the same silent hole the
retention exists to close, one layer up. The ``exists`` stat is inside that
- rule too: a stat that raises has not answered whether the ledger is there, and
+ rule too: a stat that raises has not answered whether the crew log is there, and
reading it as absent would discard the entry on a guess.
Runs on the writer, so the stat and the open read are off the loop like the
@@ -1889,7 +1889,7 @@ def _handle(session_id: str) -> Any:
creation_failed = session_id in _creation_failed
if not _ledger().Ledger.exists(_KIND, session_id):
if creation_failed:
- # The file-creating record died permanently, so this session's ledger
+ # The file-creating record died permanently, so this session's crew log
# will never exist -- but it was OPENED, so its later entries are a real
# loss, not the silent no-op an unopened session gets. Raise a refusal
# rather than return None: the exception reaches _run_job, _permanent is
@@ -1897,7 +1897,7 @@ def _handle(session_id: str) -> Any:
# counted in dropped_writes, with a write/dropped marker owed, instead
# of vanishing uncounted.
raise _ledger().LedgerError(
- "session ledger creation failed permanently; entry cannot be recorded",
+ "session log creation failed permanently; entry cannot be recorded",
code=_ledger().CODE_NO_LEDGER,
)
return None
@@ -1940,7 +1940,7 @@ def _bound_unpinned(
store.pop(key, None)
if len(store) > limit:
logger.debug(
- "session ledger %s holds %d entries, over the %d cap: every one "
+ "session log %s holds %d entries, over the %d cap: every one "
"belongs to a turn in flight",
what,
len(store),
@@ -2180,7 +2180,7 @@ def _safe_text(text: Any) -> str:
def _text_slices(text: str) -> list[str]:
- """*text* cut into pieces that each MEASURE small enough for one ledger line.
+ """*text* cut into pieces that each MEASURE small enough for one crew log line.
Measured, not assumed. A character-count budget cannot be derived from the
byte cap, because ``ensure_ascii`` escapes by code UNIT: a BMP character costs
@@ -2207,7 +2207,7 @@ def _fits_one_line(text: str, extra: "dict[str, Any] | None" = None) -> bool:
"""Whether *text* can ride on a single entry, envelope included.
Measured on the ESCAPED form, because that is what goes on the line: the
- ledger serializes with ``ensure_ascii``, so a non-ASCII character costs six
+ crew log serializes with ``ensure_ascii``, so a non-ASCII character costs six
bytes and a check against the raw length would pass a body the append then
refuses. :data:`_ENVELOPE_HEADROOM` is left for the rest of the entry.
@@ -2240,7 +2240,7 @@ def _write(
up, cached, or read back from a line written earlier. The envelope's
``thread`` field points at another LINE's seq, which is only knowable for a
unit whose anchor line is written before the entries that cite it; that is
- the crew ledger's shape, not this one's.
+ the crew's log shape, not this one's.
``ignorable`` marks an entry a reader may skip when it does not know the
type. It is the writer's promise that nothing later in the file depends on
@@ -2274,16 +2274,16 @@ def on_session_opened(
owner: str = "default",
resumed: bool = False,
) -> None:
- """Create the ledger if this session has none, then echo its header.
+ """Create the crew log if this session has none, then echo its header.
Called once per turn, because the per-turn session claim is where the ACP
id becomes known -- but an entry is written only when there is something new
- to say: the ledger was just created, or this claim RE-ATTACHED to an existing
+ to say: the crew log was just created, or this claim RE-ATTACHED to an existing
conversation (a new gateway process taking over the same session id). A warm
- reuse of a session already carrying a ledger adds nothing, so it is silent.
+ reuse of a session already carrying a crew log adds nothing, so it is silent.
``owner`` and ``agent`` are header fields, written once at create time and
- never rewritten. A resumed session id reuses its existing ledger and
+ never rewritten. A resumed session id reuses its existing crew log and
appends, so an agent or model switch that kept the conversation continues
one log rather than starting a second one. ``model`` is not a header field
in the storage schema, so it is carried on this entry instead.
@@ -2334,7 +2334,7 @@ def _job() -> None:
may_repair = bool(resumed) and not live_at_claim
if resumed and live_at_claim:
logger.warning(
- "session ledger %s: opened as a resume while turn %d is still "
+ "session log %s: opened as a resume while turn %d is still "
"running in this process, so the open turn is NOT repaired -- "
"closing it would record an outcome the turn never had and then "
"be followed by the rest of that turn",
@@ -2380,7 +2380,7 @@ def _job() -> None:
)
def _flag_creation_failed() -> None:
- # The creating record died with no ledger file behind it: no later append
+ # The creating record died with no crew log file behind it: no later append
# for this session can land, so _handle stops treating its absence as a
# policy no-op and later discards are COUNTED instead of silently dropped.
with _lock:
@@ -2388,7 +2388,7 @@ def _flag_creation_failed() -> None:
_submit(
_job,
- "opening a ledger",
+ "opening a crew log",
session_id,
exempt_ceiling=True,
on_permanent_drop=_flag_creation_failed,
@@ -2614,7 +2614,7 @@ def _turn_closer(
def _entry_line_fits(entry_type: str, data: dict[str, Any], *, src: str) -> bool:
- """Whether *data* fits its complete serialized ledger entry.
+ """Whether *data* fits its complete serialized crew log entry.
Measured through the STORE's own serializer rather than a local ``json.dumps``
with the same options: this decides whether an entry is written whole or split,
@@ -2712,7 +2712,7 @@ def _append_body_entry(
both records exist and have to be reconcilable; the body itself stays either
way.
- Runs on the writer thread with the ledger handle in hand, because the chunks
+ Runs on the writer thread with the crew log handle in hand, because the chunks
must be on disk before the entry citing them can name their seqs.
"""
data: dict[str, Any] = {"turn": int(turn)}
@@ -2781,13 +2781,13 @@ def on_message_received(
body of exactly the turns a reader most wants to explain.
Not emitted where the message is actually appended to the slot
- (``_ChatSlot.enqueue_or_run_prompt``): the ledger is keyed by the ACP session
+ (``_ChatSlot.enqueue_or_run_prompt``): the crew log is keyed by the ACP session
id and that site runs before the session is claimed, so there is no id to key
- by and no ledger to write to yet.
+ by and no crew log to write to yet.
``source`` is the surface the message arrived on, a fact the dispatch layer
supplies. ``attachments`` are identifiers, not ``Ref``s -- a ``Ref`` cites
- lines of another ledger and an attachment is not a ledger unit, the same
+ lines of another crew log and an attachment is not a crew log unit, the same
reason a tool call id lives in ``data``.
Gated on the flag before redaction runs: redaction walks the whole body with
@@ -2961,7 +2961,7 @@ def on_context_composed(
Every label ``split_blocks`` does not classify is folded into a single
``other`` source. Three blocks the design names -- steering, tool specs and
- injected ledger context -- have no opening marker, so their characters are
+ injected crew log context -- have no opening marker, so their characters are
genuinely in that remainder; reporting them as three zeroed sources would
claim a measurement that was never taken.
"""
@@ -3325,7 +3325,7 @@ def _forget() -> None:
# The creation-failure flag is per SESSION, so it dies with the
# session rather than living until the next ``reset_caches``: the
# flag makes every later entry for this id a counted loss, and a
- # successor reusing the id creates its own ledger and must not
+ # successor reusing the id creates its own crew log and must not
# inherit that verdict. Cleared here rather than on the write path
# because this runs as terminal cleanup, so it also runs when the
# closing entry itself was dropped -- which is the case for exactly
@@ -3353,7 +3353,7 @@ def _forget() -> None:
__all__ = [
"ACTORS",
- "SESSION_LEDGER_ENV",
+ "CREW_LOG_ENV",
"buffered_writes",
"drain_for_shutdown",
"dropped_writes",
diff --git a/src/kiro_crew/ledger/entry_types.py b/src/kiro_crew/crew_log/entry_types.py
similarity index 96%
rename from src/kiro_crew/ledger/entry_types.py
rename to src/kiro_crew/crew_log/entry_types.py
index 91c176990057..b29409e56573 100644
--- a/src/kiro_crew/ledger/entry_types.py
+++ b/src/kiro_crew/crew_log/entry_types.py
@@ -1,4 +1,4 @@
-"""Per-type ``data`` shapes for the session-ledger entry types, checked on append.
+"""Per-type ``data`` shapes for the session crew log entry types, checked on append.
:data:`TYPE_OWNERSHIP` answers whether a KIND of unit has such events at all, by
domain prefix. This module answers the next question -- what does one entry of
@@ -7,7 +7,7 @@
in a spec table describing it, and two statements of one fact drift.
**What a declaration is derived from.** The WRITER, not the table: every field
-below is read off the site that produces it (:mod:`kiro_crew.session_ledger_emit`
+below is read off the site that produces it (:mod:`kiro_crew.crew_log.emit`
for the ordinary entries, ``store._closer_entries`` for the crash-repair closers).
A type earns a declaration by having a writer, so the 20 declared here are exactly
the session types something writes today; a type nothing writes is left undeclared
@@ -18,7 +18,7 @@
would refuse the one write that closes an interrupted turn.
**Undeclared keys are refused**, the same posture and for the same reason as
-:func:`~kiro_crew.ledger.schema.build_header`: a caller that misspells a field
+:func:`~kiro_crew.crew_log.schema.build_header`: a caller that misspells a field
would otherwise be told the entry landed as asked while the value it meant to
record silently vanished. So a new field arrives with its declaration, in one
commit, or not at all.
@@ -26,7 +26,7 @@
**Values come in two strengths, and only one of them refuses.** ``enum_closed``
marks a vocabulary the WRITER itself clamps -- ``turn/started.actor`` and
``turn/refused.actor`` are coerced to
-:data:`~kiro_crew.session_ledger_emit.ACTORS` at the emitter -- so no caller can
+:data:`~kiro_crew.crew_log.emit.ACTORS` at the emitter -- so no caller can
produce a value outside it and enforcing costs nothing. Every other vocabulary is
PASSED THROUGH from
somewhere this module does not own: a provider's ``stop_reason``, the gateway's
@@ -37,7 +37,7 @@
instead of catching mistakes.
Types with no declaration pass through untouched. That is what keeps the crew
-ledger, whose own type families have no emitter, and every guest namespace
+crew log, whose own type families have no emitter, and every guest namespace
(``crew:/…``, ``app:/…``) writable while this covers the session
families that are written today.
"""
@@ -49,8 +49,8 @@
from dataclasses import dataclass
from typing import Any
-from kiro_crew.ledger.errors import CODE_BAD_DATA_FIELD, LedgerError
-from kiro_crew.ledger.schema import KIND_SESSION
+from kiro_crew.crew_log.errors import CODE_BAD_DATA_FIELD, LedgerError
+from kiro_crew.crew_log.schema import KIND_SESSION
#: JSON types a declared field may hold. ``int`` and ``float`` are separate
#: because the wire format's numbers are separate to a reader: a count is not a
@@ -154,7 +154,7 @@ def _turn(note: str = "Turn ordinal.") -> Field:
# -- session, turn ------------------------------------------------------ #
EntryType(
"session/opened",
- "The ledger was created, or this claim re-attached to an existing conversation.",
+ "The crew log was created, or this claim re-attached to an existing conversation.",
(
Field("agent", JSON_STRING, required=True, note="Agent name."),
Field("slot", JSON_STRING, required=True, note="Slot key; may be empty."),
@@ -170,7 +170,7 @@ def _turn(note: str = "Turn ordinal.") -> Field:
"resumed",
JSON_BOOL,
required=True,
- note="True when this claim re-attached to an existing ledger.",
+ note="True when this claim re-attached to an existing crew log.",
),
),
),
@@ -547,7 +547,7 @@ def _turn(note: str = "Turn ordinal.") -> Field:
#: Per kind, because the question "what does this type carry" is asked of a unit.
#: A crew registry drops in beside this one when a crew emitter lands; until then
-#: a crew ledger's types are simply undeclared and pass through.
+#: a crew's log's types are simply undeclared and pass through.
ENTRY_TYPES: dict[str, dict[str, EntryType]] = {KIND_SESSION: SESSION_ENTRY_TYPES}
@@ -626,7 +626,7 @@ def validate_data(kind: str, entry_type: str, data: Any) -> None:
falls outside a CLOSED enum. Returns silently for a type with no declaration,
which is every crew type and every guest namespace.
- A refusal is a :class:`~kiro_crew.ledger.errors.LedgerError`, so the
+ A refusal is a :class:`~kiro_crew.crew_log.errors.LedgerError`, so the
write-behind emitter already treats it the way it treats an oversize entry: a
permanent refusal, reported and counted in ``dropped_writes()``, never raised
into the gateway and never retried against a verdict that cannot change.
@@ -678,7 +678,7 @@ def render_markdown(kind: str = KIND_SESSION) -> str:
So the reference tables in the spec can be GENERATED from the registry the
append path enforces, instead of being a second description of it that drifts.
"""
- out: list[str] = [f"# Declared `{kind}` ledger entry types", ""]
+ out: list[str] = [f"# Declared `{kind}` crew log entry types", ""]
for spec in ENTRY_TYPES.get(kind, {}).values():
out.append(f"## `{spec.type}`")
out.append("")
@@ -703,7 +703,7 @@ def main(argv: "list[str] | None" = None) -> int:
if args == ["--markdown"]:
print(render_markdown())
return 0
- print("usage: python -m kiro_crew.ledger.entry_types --markdown", file=sys.stderr)
+ print("usage: python -m kiro_crew.crew_log.entry_types --markdown", file=sys.stderr)
return 2
diff --git a/src/kiro_crew/ledger/errors.py b/src/kiro_crew/crew_log/errors.py
similarity index 87%
rename from src/kiro_crew/ledger/errors.py
rename to src/kiro_crew/crew_log/errors.py
index 442c948cfdd2..6da8feca814a 100644
--- a/src/kiro_crew/ledger/errors.py
+++ b/src/kiro_crew/crew_log/errors.py
@@ -1,4 +1,4 @@
-"""Refusals the append-only ledger raises, each carrying a stable ``code``.
+"""Refusals the append-only crew log raises, each carrying a stable ``code``.
Every refusal is a :class:`LedgerError` with a machine-readable ``code``, the
same contract :mod:`kiro_crew.work_ledger` uses: a caller (a route handler, a
@@ -11,24 +11,24 @@
from __future__ import annotations
-#: The requested ledger kind is neither ``crew`` nor ``session``.
+#: The requested crew log kind is neither ``crew`` nor ``session``.
CODE_BAD_KIND = "bad_kind"
#: The unit id is empty, carries a path separator or a NUL, or resolves outside
#: its own root.
CODE_INVALID_ID = "invalid_id"
-#: ``create`` was asked for a ledger whose file is already there.
+#: ``create`` was asked for a crew log whose file is already there.
CODE_ALREADY_EXISTS = "already_exists"
-#: Another process owns writes to this unit's ledger, so this one appended
+#: Another process owns writes to this unit's crew log, so this one appended
#: nothing. Distinct from every code above: the entry was well formed and the
#: file is healthy -- this process is simply not the writer. A caller reports the
#: loss rather than retrying, because ownership is held for the life of the
#: owning process and every later entry for that unit would queue behind the one
#: waiting for it.
CODE_ALREADY_OWNED = "already_owned"
-#: ``open`` was asked for a ledger whose file is not there.
+#: ``open`` was asked for a crew log whose file is not there.
CODE_NO_LEDGER = "no_ledger"
#: Line 1 is missing, unparseable, or describes a different unit than the one
-#: asked for. A ledger without a readable header is not a ledger.
+#: asked for. A crew log without a readable header is not one.
CODE_BAD_HEADER = "bad_header"
#: A header field is missing, of the wrong python type, or unknown.
CODE_BAD_HEADER_FIELD = "bad_header_field"
@@ -45,14 +45,14 @@
#: type carries. Distinct from ``bad_data``, which is about the payload as a
#: whole; ``field`` names the offending path (``data.tokens.input``) so a caller
#: can point at it without parsing prose. See
-#: :mod:`kiro_crew.ledger.entry_types` for the declarations.
+#: :mod:`kiro_crew.crew_log.entry_types` for the declarations.
CODE_BAD_DATA_FIELD = "bad_data_field"
-#: This ledger kind does not own that ``type`` prefix (rule 1).
+#: This crew log kind does not own that ``type`` prefix (rule 1).
CODE_EVENT_TYPE_NOT_OWNED = "event_type_not_owned"
#: A guest emitter wrote outside its own namespace, or wrote a guest type into
-#: a session ledger (rule 2).
+#: a session's log (rule 2).
CODE_NAMESPACE_VIOLATION = "namespace_violation"
-#: ``thread`` does not name an existing, earlier seq in this same ledger.
+#: ``thread`` does not name an existing, earlier seq in this same crew log.
CODE_BAD_THREAD = "bad_thread"
#: ``ref`` is malformed: bad unit, bad id, non-positive bounds, inverted
#: bounds, or a span wider than the read cap.
@@ -70,7 +70,7 @@
#: entry a reader cannot interpret may change the meaning of every entry after
#: it, so reconstruction stops rather than silently skipping it.
CODE_UNKNOWN_ENTRY_TYPE = "unknown_entry_type"
-#: A segment's header does not belong to the ledger being read, or its filename's
+#: A segment's header does not belong to the crew log being read, or its filename's
#: declared first seq disagrees with its readable physical first entry. The message
#: names the offending segment so an operator can quarantine the damaged object.
CODE_BAD_SEGMENT = "bad_segment"
@@ -79,8 +79,8 @@
#: segments off the FRONT, which leaves no gap between the ones that remain, so
#: a gap here is damage or a partial copy rather than a pruned log.
CODE_SEGMENT_GAP = "segment_gap"
-#: A kind's root directory under ``ledgers`` is a link, or resolves outside the
-#: data home's own ledger tree. Containment resolves its base first, so a linked
+#: A kind's root directory under ``crew-log`` is a link, or resolves outside the
+#: data home's own crew log tree. Containment resolves its base first, so a linked
#: kind root would make the link's TARGET the containment root and every path
#: under it would pass -- private history readable and forgeable at a location
#: the protections established for the data home do not cover. The message names
@@ -89,7 +89,7 @@
class LedgerError(Exception):
- """A refused ledger operation.
+ """A refused crew log operation.
``code`` is the stable identifier; ``field`` names the offending input when
one field is to blame, so a caller can point at it without parsing prose.
diff --git a/src/kiro_crew/ledger/lease.py b/src/kiro_crew/crew_log/lease.py
similarity index 94%
rename from src/kiro_crew/ledger/lease.py
rename to src/kiro_crew/crew_log/lease.py
index f067c66393ea..1b926a043aa9 100644
--- a/src/kiro_crew/ledger/lease.py
+++ b/src/kiro_crew/crew_log/lease.py
@@ -1,4 +1,4 @@
-"""Write ownership of one unit's ledger, arbitrated by the kernel.
+"""Write ownership of one unit's crew log, arbitrated by the kernel.
The arbiter is an advisory lock on a ``.lease`` file beside the log, taken
NON-BLOCKING, so contention is an answer rather than a wait: a process that
@@ -52,10 +52,10 @@
from dataclasses import dataclass
from pathlib import Path
-from kiro_crew.ledger.errors import CODE_ALREADY_OWNED, LedgerError
+from kiro_crew.crew_log.errors import CODE_ALREADY_OWNED, LedgerError
from kiro_crew.platform_compat import file_lock
-#: The lease file's name inside a unit's ledger directory. Distinct from the
+#: The lease file's name inside a unit's crew log directory. Distinct from the
#: per-append lock: that one is taken and released around every write, so a
#: lease on the same path would either deadlock against it or be released by it.
LEASE_FILE = ".lease"
@@ -134,7 +134,7 @@ def acquire(path: Path, *, kind: str, unit_id: str, sole: bool = False) -> str:
counting sense: every call that returns has added a reference, and each one
has to be released.
- Raises a :class:`~kiro_crew.ledger.LedgerError` with code ``already_owned``
+ Raises a :class:`~kiro_crew.crew_log.LedgerError` with code ``already_owned``
when another process holds the log. That is a REFUSAL, not a failure: this
process has written nothing, and it will not own the log by asking again in a
moment, so a caller reports the loss rather than retrying it.
@@ -163,21 +163,21 @@ def acquire(path: Path, *, kind: str, unit_id: str, sole: bool = False) -> str:
held = _held.get(key)
if held is not None:
if held.removing:
- raise _refused(f"the {kind} ledger {unit_id!r} is being removed by this process")
+ raise _refused(f"the {kind} crew log {unit_id!r} is being removed by this process")
if sole:
- raise _refused(f"this process already owns writes to {kind} ledger {unit_id!r}")
+ raise _refused(f"this process already owns writes to {kind} crew log {unit_id!r}")
held.refs += 1
return key
try:
stack = _take(path)
except BlockingIOError as exc:
- raise _refused(f"another process owns writes to {kind} ledger {unit_id!r}") from exc
+ raise _refused(f"another process owns writes to {kind} crew log {unit_id!r}") from exc
if stack is None:
# A lock was taken every time and the file moved out from under it
# every time. Same answer as contention -- ownership could not be
# established, so nothing is written -- and the message says which.
raise _refused(
- f"the lease file of {kind} ledger {unit_id!r} keeps being replaced, so no "
+ f"the lease file of {kind} crew log {unit_id!r} keeps being replaced, so no "
"lock on it can be verified"
)
_held[key] = _Held(stack=stack, refs=1, removing=sole)
diff --git a/src/kiro_crew/ledger/schema.py b/src/kiro_crew/crew_log/schema.py
similarity index 89%
rename from src/kiro_crew/ledger/schema.py
rename to src/kiro_crew/crew_log/schema.py
index 0299edd54a33..28ced25231d9 100644
--- a/src/kiro_crew/ledger/schema.py
+++ b/src/kiro_crew/crew_log/schema.py
@@ -1,12 +1,12 @@
-"""Wire format for the append-only ledger: the header, the entry, the rules.
+"""Wire format for the append-only crew log: the header, the entry, the rules.
-One ledger is one file. Line 1 is a **header** describing the unit the file
+One crew log is one file. Line 1 is a **header** describing the unit the file
belongs to; every later line is an **entry**. Nothing is ever rewritten, so the
format has to be readable by a consumer newer *or* older than the writer:
- Unknown envelope keys are ignored rather than rejected, and an unparseable
interior line is skipped rather than failing the read (see
- :mod:`kiro_crew.ledger.store`). ``version`` is the escape hatch for a future
+ :mod:`kiro_crew.crew_log.store`). ``version`` is the escape hatch for a future
incompatible break, not a per-change workflow.
- An unknown TYPE is a different question from an unknown key, and the writer
answers it per entry. ``ignorable: true`` says a reader may skip this line
@@ -32,7 +32,7 @@
**Namespacing** (rule 2) answers *may this emitter write this*, and it is a rule
about ``src`` rather than about the spelling of the type. Each kind accepts its
own emitters (:data:`KIND_FIXED_SOURCES`, :data:`KIND_SOURCE_PREFIXES`): a
-session ledger takes ``gateway`` and ``acp``, a crew ledger takes ``gateway``,
+session's log takes ``gateway`` and ``acp``, a crew's log takes ``gateway``,
``dashboard``, ``patrol`` and the two guest forms ``crew:`` and
``app:``. A ``crew:`` guest writes the crew kind's own built-in
domains, and its name in ``src`` is the signature -- a type carries the fact,
@@ -56,7 +56,7 @@
from dataclasses import dataclass
from typing import Any
-from kiro_crew.ledger.errors import (
+from kiro_crew.crew_log.errors import (
CODE_BAD_DATA,
CODE_BAD_HEADER,
CODE_BAD_HEADER_FIELD,
@@ -78,7 +78,7 @@
KIND_CREW = "crew"
KIND_SESSION = "session"
-#: The two units that own a ledger. A kind is also the ``unit`` a ref names.
+#: The two units that own a crew log. A kind is also the ``unit`` a ref names.
KINDS: frozenset[str] = frozenset({KIND_CREW, KIND_SESSION})
#: Serialized-line ceiling. A line past this is refused, not clipped.
@@ -141,8 +141,8 @@
}
#: The guest emitter prefixes each kind accepts. A guest names an instance, so
-#: it is spelled ``:`` and only a crew ledger takes one: a session
-#: ledger is one session's own turn history, which no other unit writes into.
+#: it is spelled ``:`` and only a crew's log takes one: a session's
+#: log is one session's own turn history, which no other unit writes into.
KIND_SOURCE_PREFIXES: dict[str, tuple[str, ...]] = {
KIND_CREW: (CREW_SOURCE_PREFIX, APP_SOURCE_PREFIX),
KIND_SESSION: (),
@@ -173,23 +173,25 @@ def require_unit_id(unit_id: str, *, field: str = "id") -> str:
"""*unit_id* unchanged, or raise ``invalid_id``.
A unit id names a DIRECTORY, so a separator or a NUL in it would let the
- ledger escape its own root. The raw id is refused loudly rather than folded
+ crew log escape its own root. The raw id is refused loudly rather than folded
to something safe: a fold would silently merge two units into one file, and
- two units sharing a ledger is worse than a refused write. Containment is
+ two units sharing a crew log is worse than a refused write. Containment is
re-checked symlink-safely when the path is built (``resolved_within``); this
is the cheap shape gate in front of it.
"""
if not isinstance(unit_id, str) or not unit_id:
- raise LedgerError("ledger id must be a non-empty string", code=CODE_INVALID_ID, field=field)
+ raise LedgerError(
+ "crew log id must be a non-empty string", code=CODE_INVALID_ID, field=field
+ )
if "\0" in unit_id or "/" in unit_id or "\\" in unit_id:
raise LedgerError(
- f"ledger id must not contain a path separator or NUL: {unit_id!r}",
+ f"crew log id must not contain a path separator or NUL: {unit_id!r}",
code=CODE_INVALID_ID,
field=field,
)
if unit_id in {".", ".."}:
raise LedgerError(
- f"ledger id must not be a relative path element: {unit_id!r}",
+ f"crew log id must not be a relative path element: {unit_id!r}",
code=CODE_INVALID_ID,
field=field,
)
@@ -200,7 +202,7 @@ def require_kind(kind: str, *, field: str = "kind") -> str:
"""*kind* unchanged, or raise ``bad_kind``."""
if kind not in KINDS:
raise LedgerError(
- f"unknown ledger kind {kind!r}; expected one of {sorted(KINDS)}",
+ f"unknown crew log kind {kind!r}; expected one of {sorted(KINDS)}",
code=CODE_BAD_KIND,
field=field,
)
@@ -254,9 +256,9 @@ def is_guest_type_domain(domain: str) -> bool:
def guest_source_prefix_of(src: str, kind: str) -> str | None:
"""The guest prefix *src* carries for *kind*, or ``None``.
- Keyed by kind, so the answer is the one this ledger accepts rather than the
- union: ``crew:qa`` is a guest of a crew ledger and nothing at all to a
- session ledger.
+ Keyed by kind, so the answer is the one this log accepts rather than the
+ union: ``crew:qa`` is a guest of a crew's log and nothing at all to a
+ session's log.
"""
for prefix in KIND_SOURCE_PREFIXES.get(kind, ()):
if src.startswith(prefix):
@@ -267,7 +269,7 @@ def guest_source_prefix_of(src: str, kind: str) -> str | None:
def require_src(src: str, *, kind: str) -> str:
"""*src* unchanged, or raise ``bad_src``.
- Checked against what this KIND of ledger accepts. ``kind`` is keyword-only
+ Checked against what this KIND of crew log accepts. ``kind`` is keyword-only
and required: it selects the rule, so a caller that omits it must fail
loudly rather than have its ``src`` measured against some default kind's
list.
@@ -284,7 +286,7 @@ def require_src(src: str, *, kind: str) -> str:
f"{prefix}" for prefix in KIND_SOURCE_PREFIXES[kind]
]
raise LedgerError(
- f"a {kind} ledger accepts src {accepted}: {src!r}",
+ f"a {kind} crew log accepts src {accepted}: {src!r}",
code=CODE_BAD_SRC,
field="src",
)
@@ -295,7 +297,7 @@ def check_ownership(kind: str, entry_type: str, src: str) -> None:
``src`` is where authorization lives, so it is settled first: an emitter a
kind does not accept is refused whatever it writes, and everything below can
- then reason about an emitter this ledger already takes. A guest TYPE
+ then reason about an emitter this crew log already takes. A guest TYPE
(``app:/``) is judged by its namespace alone and never against
the ownership registry, which is why the registry needs no app entries.
"""
@@ -306,8 +308,8 @@ def check_ownership(kind: str, entry_type: str, src: str) -> None:
if is_guest_type_domain(domain):
if kind != KIND_CREW:
raise LedgerError(
- f"a {kind} ledger does not accept the guest type {entry_type!r}; "
- f"the {GUEST_TYPE_PREFIX} namespace is crew-ledger only",
+ f"a {kind} crew log does not accept the guest type {entry_type!r}; "
+ f"the {GUEST_TYPE_PREFIX} namespace is crew-log only",
code=CODE_NAMESPACE_VIOLATION,
field="type",
)
@@ -327,7 +329,7 @@ def check_ownership(kind: str, entry_type: str, src: str) -> None:
)
if domain not in TYPE_OWNERSHIP[kind]:
raise LedgerError(
- f"a {kind} ledger does not own the type {entry_type!r}; "
+ f"a {kind} crew log does not own the type {entry_type!r}; "
f"owned domains are {sorted(TYPE_OWNERSHIP[kind])}",
code=CODE_EVENT_TYPE_NOT_OWNED,
field="type",
@@ -341,9 +343,9 @@ def check_ownership(kind: str, entry_type: str, src: str) -> None:
@dataclass(frozen=True)
class Ref:
- """A pointer to a segment of another (or the same) ledger.
+ """A pointer to a segment of another (or the same) crew log.
- A ref is a CITATION, not a copy: the bytes stay in the ledger they were
+ A ref is a CITATION, not a copy: the bytes stay in the crew log they were
written to, and a reader that may not read that unit gets ``forbidden``
rather than the contents. ``to_seq`` absent means the single line at
``from_seq``.
@@ -425,14 +427,14 @@ def _is_seq(value: Any) -> bool:
@dataclass(frozen=True)
class Entry:
- """One ledger line after the header. ``seq`` and ``time`` are writer-assigned.
+ """One crew log line after the header. ``seq`` and ``time`` are writer-assigned.
``ignorable`` marks an entry a reader may SKIP when it does not know the
type. It is the writer's promise that nothing later in the file depends on
this entry having been interpreted -- a sampled stream body, a hint -- and it
is the only thing that lets an older reader keep folding a file a newer
writer extended. Without it an unknown type stops reconstruction
- (:meth:`~kiro_crew.ledger.store.Ledger.iter_from` with ``known=``), because a
+ (:meth:`~kiro_crew.crew_log.store.Ledger.iter_from` with ``known=``), because a
required entry a reader cannot interpret may change the meaning of every
entry after it.
"""
@@ -520,14 +522,14 @@ def serialize(payload: dict[str, Any]) -> str:
``ensure_ascii`` stays on so the file is byte-stable regardless of the
reader's locale, and the separators drop the whitespace ``json`` adds by
- default -- a ledger line is machine-read, and the bytes are the budget the
+ default -- a crew log line is machine-read, and the bytes are the budget the
size cap is spent from.
"""
try:
return json.dumps(payload, ensure_ascii=True, separators=(",", ":"), sort_keys=False)
except (TypeError, ValueError) as exc:
raise LedgerError(
- f"ledger payload is not JSON-serializable: {exc}", code=CODE_BAD_DATA, field="data"
+ f"crew log payload is not JSON-serializable: {exc}", code=CODE_BAD_DATA, field="data"
) from exc
@@ -561,7 +563,7 @@ def require_data(data: Any) -> dict[str, Any]:
@dataclass(frozen=True)
class SessionThread:
- """Where a session hangs off its owning crew's ledger."""
+ """Where a session hangs off its owning crew's log."""
crew: str
seq: int
@@ -585,7 +587,7 @@ def coerce(cls, raw: Any) -> SessionThread | None:
@dataclass(frozen=True)
class CrewHeader:
- """Line 1 of a crew ledger: which unit this file belongs to, and since when.
+ """Line 1 of a crew's log: which unit this file belongs to, and since when.
Deliberately minimal. A crew's display name and template belong to the
members store, which owns them and can change them; duplicating them here
@@ -610,7 +612,7 @@ def to_dict(self) -> dict[str, Any]:
@dataclass(frozen=True)
class SessionHeader:
- """Line 1 of a session ledger."""
+ """Line 1 of a session's log."""
id: str
owner: str
@@ -659,7 +661,7 @@ def to_dict(self) -> dict[str, Any]:
def build_header(kind: str, unit_id: str, created_at: int, fields: dict[str, Any]) -> Header:
- """The header for a new ledger, or raise ``bad_header_field``.
+ """The header for a new crew log, or raise ``bad_header_field``.
Unknown keys are refused rather than dropped. On the READ path an unknown
key is ignored (an older reader must tolerate a newer writer), but on the
@@ -672,14 +674,14 @@ def build_header(kind: str, unit_id: str, created_at: int, fields: dict[str, Any
unknown = sorted(set(fields) - allowed)
if unknown:
raise LedgerError(
- f"unknown header field(s) for a {kind} ledger: {unknown}; allowed: {sorted(allowed)}",
+ f"unknown header field(s) for a {kind} crew log: {unknown}; allowed: {sorted(allowed)}",
code=CODE_BAD_HEADER_FIELD,
field=unknown[0],
)
missing = [name for name in _REQUIRED_HEADER_FIELDS[kind] if fields.get(name) is None]
if missing:
raise LedgerError(
- f"missing required header field(s) for a {kind} ledger: {missing}",
+ f"missing required header field(s) for a {kind} crew log: {missing}",
code=CODE_BAD_HEADER_FIELD,
field=missing[0],
)
@@ -718,35 +720,35 @@ def parse_header(raw: Any, *, kind: str, unit_id: str) -> Header:
"""A header from its wire form, or raise ``bad_header``.
The stored ``type`` and ``id`` must match what the caller asked to open. A
- ledger whose header names a different unit is not this unit's ledger, and
+ crew log whose header names a different unit is not this unit's crew log, and
reading it as if it were would attribute one unit's history to another.
"""
if not isinstance(raw, dict):
- raise LedgerError("ledger header is not an object", code=CODE_BAD_HEADER, field="type")
+ raise LedgerError("crew log header is not an object", code=CODE_BAD_HEADER, field="type")
stored_kind = raw.get("type")
if stored_kind != kind:
raise LedgerError(
- f"ledger header says type {stored_kind!r}, opened as {kind!r}",
+ f"crew log header says type {stored_kind!r}, opened as {kind!r}",
code=CODE_BAD_HEADER,
field="type",
)
if raw.get("id") != unit_id:
raise LedgerError(
- f"ledger header says id {raw.get('id')!r}, opened as {unit_id!r}",
+ f"crew log header says id {raw.get('id')!r}, opened as {unit_id!r}",
code=CODE_BAD_HEADER,
field="id",
)
created_at = raw.get("createdAt")
if not isinstance(created_at, int) or isinstance(created_at, bool):
raise LedgerError(
- f"ledger header createdAt must be epoch ms: {created_at!r}",
+ f"crew log header createdAt must be epoch ms: {created_at!r}",
code=CODE_BAD_HEADER,
field="createdAt",
)
version = raw.get("version")
if not isinstance(version, int) or isinstance(version, bool):
raise LedgerError(
- f"ledger header version must be an int: {version!r}",
+ f"crew log header version must be an int: {version!r}",
code=CODE_BAD_HEADER,
field="version",
)
@@ -759,7 +761,7 @@ def parse_header(raw: Any, *, kind: str, unit_id: str) -> Header:
# truth is that this process is old. The distinction is the whole point of
# carrying a version, and nothing else in this module reads it.
raise LedgerError(
- f"{kind} ledger {unit_id!r} was written by a newer build "
+ f"{kind} crew log {unit_id!r} was written by a newer build "
f"(format version {version}, this build reads {SCHEMA_VERSION}); "
"upgrade to read it. The file is not damaged.",
code=CODE_UNSUPPORTED_VERSION,
@@ -771,7 +773,7 @@ def parse_header(raw: Any, *, kind: str, unit_id: str) -> Header:
owner = raw.get("owner")
if not isinstance(agent, str) or not isinstance(owner, str):
raise LedgerError(
- f"session ledger header needs string owner and agent: {owner!r}, {agent!r}",
+ f"session log header needs string owner and agent: {owner!r}, {agent!r}",
code=CODE_BAD_HEADER,
field="agent",
)
diff --git a/src/kiro_crew/ledger/store.py b/src/kiro_crew/crew_log/store.py
similarity index 93%
rename from src/kiro_crew/ledger/store.py
rename to src/kiro_crew/crew_log/store.py
index 75411539e853..364615d2fbe1 100644
--- a/src/kiro_crew/ledger/store.py
+++ b/src/kiro_crew/crew_log/store.py
@@ -1,17 +1,17 @@
-"""The append-only ledger store: one file per unit, the gateway the only writer.
+"""The append-only crew log store: one file per unit, the gateway the only writer.
Layout, resolved against the live data home on every call (never captured at
import, so pod isolation and test isolation both keep working)::
- /ledgers/crews//ledger.jsonl
- /ledgers/sessions//ledger.jsonl
+ /crew-log/crews//log.jsonl
+ /crew-log/sessions//log.jsonl
```` is the readable-plus-digest fold of the unit id that
``session_ledger`` and ``work_ledger`` already use, and the raw id lives in the
header (see :func:`ledger_dir` for why the id is not the directory name). Both
files carry a ``.lock`` sibling in the same directory.
-One dedicated ``ledgers`` root, holding every kind, is what carries the
+One dedicated ``crew-log`` root, holding every kind, is what carries the
protection: the leaf is hidden from a sandboxed process by the OS and fenced from
the agent's own file tools, and both fences are stated per leaf, so every kind
under this root inherits them and a new kind cannot be left out by omission. A
@@ -42,7 +42,7 @@
inside the critical section on every append rather than trusted from the
in-process cache, so two writers cannot both believe they own the same number.
The read is a bounded window at the end of the file (``_TAIL_WINDOW``), not a
-scan, so it costs the same on a ledger with ten lines and one with a million.
+scan, so it costs the same on a crew log with ten lines and one with a million.
``.last_seq`` serves the cached value for callers that only want to look.
"""
@@ -64,13 +64,8 @@
from kiro_crew.atomic_write import atomic_write
from kiro_crew.config.paths import data_home
-from kiro_crew.jsonl_util import (
- UnreadableRecord,
- bounded_raw_records,
- strict_raw_records,
-)
-from kiro_crew.ledger.entry_types import validate_data
-from kiro_crew.ledger.errors import (
+from kiro_crew.crew_log.entry_types import validate_data
+from kiro_crew.crew_log.errors import (
CODE_ALREADY_EXISTS,
CODE_ALREADY_OWNED,
CODE_BAD_DATA,
@@ -85,10 +80,10 @@
IndeterminateAppend,
LedgerError,
)
-from kiro_crew.ledger.lease import LEASE_FILE
-from kiro_crew.ledger.lease import acquire as acquire_lease
-from kiro_crew.ledger.lease import release as release_lease
-from kiro_crew.ledger.schema import (
+from kiro_crew.crew_log.lease import LEASE_FILE
+from kiro_crew.crew_log.lease import acquire as acquire_lease
+from kiro_crew.crew_log.lease import release as release_lease
+from kiro_crew.crew_log.schema import (
KIND_CREW,
KIND_SESSION,
MAX_ENTRY_BYTES,
@@ -104,33 +99,38 @@
require_unit_id,
serialize,
)
+from kiro_crew.jsonl_util import (
+ UnreadableRecord,
+ bounded_raw_records,
+ strict_raw_records,
+)
from kiro_crew.platform_compat import file_lock, restrict_dir_to_owner
from kiro_crew.session_ledger import _store_name, is_link, resolved_within, unlink_lock_in_hold
logger = logging.getLogger(__name__)
-LEDGER_FILE = "ledger.jsonl"
+LOG_FILE = "log.jsonl"
-#: How a segment past the first is named and found. ``ledger.jsonl`` holds seq 1
-#: onward; ``ledger..jsonl`` is a later segment.
-_SEGMENT_STEM = "ledger"
+#: How a segment past the first is named and found. ``log.jsonl`` holds seq 1
+#: onward; ``log..jsonl`` is a later segment.
+_SEGMENT_STEM = "log"
_SEGMENT_SUFFIX = ".jsonl"
_SEGMENT_GLOB = f"{_SEGMENT_STEM}.*{_SEGMENT_SUFFIX}"
_LOCK_FILE = ".lock"
-#: The one data-home leaf that holds every ledger, of every kind.
+#: The one data-home leaf that holds every crew log, of every kind.
#:
#: A dedicated root rather than a subdirectory of each unit's existing home,
#: because the protection is what makes the record an authority: this leaf is
#: hidden from a sandboxed process by the OS (``sandbox._CREW_HIDDEN_LEAVES``)
#: and fenced from the agent's own file tools (``security.paths``), and both are
#: stated per LEAF. The ``sessions`` transcript root carries NEITHER entry, so a
-#: session ledger placed there is protected by the tool gate alone and a
+#: session log placed there is protected by the tool gate alone and a
#: sandboxed subprocess can open it directly and forge the history a conductor
#: reads as fact. One root also means one entry per fence instead of one per
#: kind, so a third unit kind inherits the protection rather than needing a
#: reviewer to notice it was left out.
-_ROOT_LEAF = "ledgers"
+_ROOT_LEAF = "crew-log"
#: Directory under :data:`_ROOT_LEAF` that holds each kind's units.
_ROOT_DIR: dict[str, str] = {KIND_CREW: "crews", KIND_SESSION: "sessions"}
@@ -169,7 +169,7 @@ def now_ms() -> int:
def ledger_root(kind: str) -> Path:
- """Root directory holding every ledger of *kind*."""
+ """Root directory holding every crew log of *kind*."""
return data_home() / _ROOT_LEAF / _ROOT_DIR[require_kind(kind)]
@@ -191,7 +191,7 @@ def _checked_ledger_root(kind: str) -> Path:
* the kind directory is not itself a link -- ``lstat`` rather than ``stat``,
so the answer is about the name and not about what it points at;
* it resolves to exactly the canonical spelling under the data home's own
- ``ledgers`` tree, with both sides resolved so one symlinked ancestor cannot
+ ``crew-log`` tree, with both sides resolved so one symlinked ancestor cannot
make two spellings of the same directory disagree.
An absent directory is fine and is not an error: the callers that write
@@ -203,37 +203,37 @@ def _checked_ledger_root(kind: str) -> Path:
is_link = root.is_symlink()
except OSError as exc: # pragma: no cover -- a stat fault on the parent
raise LedgerError(
- f"cannot establish the ledger root {root}: {exc}",
+ f"cannot establish the crew log root {root}: {exc}",
code=CODE_BAD_ROOT,
) from exc
if is_link:
raise LedgerError(
- f"refusing a linked ledger root: {root} is a symbolic link",
+ f"refusing a linked crew log root: {root} is a symbolic link",
code=CODE_BAD_ROOT,
)
if not root.exists():
return root
try:
resolved = root.resolve()
- # Anchored at the data home, NOT at ``/ledgers`` resolved: resolving
- # the parent would accept a linked ``ledgers`` -- both sides would then
+ # Anchored at the data home, NOT at ``/crew-log`` resolved: resolving
+ # the parent would accept a linked ``crew-log`` -- both sides would then
# spell the link's target and agree, which is the same escape one level up.
canonical = data_home().resolve() / _ROOT_LEAF / _ROOT_DIR[require_kind(kind)]
except (OSError, RuntimeError) as exc:
raise LedgerError(
- f"cannot resolve the ledger root {root}: {exc}",
+ f"cannot resolve the crew log root {root}: {exc}",
code=CODE_BAD_ROOT,
) from exc
if resolved != canonical:
raise LedgerError(
- f"refusing a ledger root outside the data home: {root} resolves to {resolved}",
+ f"refusing a crew log root outside the data home: {root} resolves to {resolved}",
code=CODE_BAD_ROOT,
)
return root
def ledger_dir(kind: str, unit_id: str) -> Path:
- """The validated directory for one unit's ledger. Does not create it.
+ """The validated directory for one unit's crew log. Does not create it.
The directory is named with the readable-plus-digest fold
(``session_ledger._store_name``) rather than the raw id, and the raw id is
@@ -260,7 +260,7 @@ def ledger_dir(kind: str, unit_id: str) -> Path:
resolved = resolved_within(_checked_ledger_root(kind), _store_name(unit_id))
if resolved is None:
raise LedgerError(
- f"path traversal blocked for ledger id: {unit_id!r}",
+ f"path traversal blocked for crew log id: {unit_id!r}",
code=CODE_INVALID_ID,
field="id",
)
@@ -268,13 +268,13 @@ def ledger_dir(kind: str, unit_id: str) -> Path:
def ledger_path(kind: str, unit_id: str) -> Path:
- """The ledger file for one unit."""
- return ledger_dir(kind, unit_id) / LEDGER_FILE
+ """The crew log file for one unit."""
+ return ledger_dir(kind, unit_id) / LOG_FILE
def _segment_first_seq(path: Path) -> int | None:
"""The first seq declared by a canonical segment filename, or ``None``."""
- if path.name == LEDGER_FILE:
+ if path.name == LOG_FILE:
return 1
prefix = f"{_SEGMENT_STEM}."
if not path.name.startswith(prefix) or not path.name.endswith(_SEGMENT_SUFFIX):
@@ -286,7 +286,7 @@ def _segment_first_seq(path: Path) -> int | None:
def segment_paths(kind: str, unit_id: str) -> list[Path]:
- """Every segment of one unit's ledger, in ascending first-seq order.
+ """Every segment of one unit's crew log, in ascending first-seq order.
Retention is deleting whole segments off the FRONT, which is why the format
is segments rather than one growing file: dropping the oldest lines out of a
@@ -295,14 +295,14 @@ def segment_paths(kind: str, unit_id: str) -> list[Path]:
line byte-identical, so retention costs a reader the old entries and costs
the format nothing.
- ``ledger.jsonl`` is the segment that starts at seq 1 and is the only one a
- writer creates today; a later segment is ``ledger..jsonl``. The
+ ``log.jsonl`` is the segment that starts at seq 1 and is the only one a
+ writer creates today; a later segment is ``log..jsonl``. The
first-seq is IN the name so ordering needs no file read, and so a reader can
tell a gap at the front (retention) from a gap in the middle (damage).
"""
directory = ledger_dir(kind, unit_id)
found: list[tuple[int, Path]] = []
- head = directory / LEDGER_FILE
+ head = directory / LOG_FILE
if head.is_file():
found.append((1, head))
for candidate in directory.glob(_SEGMENT_GLOB):
@@ -310,7 +310,7 @@ def segment_paths(kind: str, unit_id: str) -> list[Path]:
if first is None:
# Not a segment: a neighbour that merely shares the prefix. Ignored
# rather than refused, so an editor's backup file cannot make a
- # readable ledger unreadable.
+ # readable crew log unreadable.
continue
found.append((first, candidate))
found.sort(key=lambda pair: pair[0])
@@ -323,7 +323,7 @@ def segment_first_seqs(kind: str, unit_id: str) -> list[int]:
The companion to :func:`segment_paths`, and the reason the first-seq is in the
file NAME: telling a gap at the front from a gap in the middle needs only the
directory listing, so the decision costs no file read and stays correct on a
- ledger too large to scan.
+ crew log too large to scan.
"""
return [
first
@@ -355,10 +355,10 @@ def _lock_path(kind: str, unit_id: str) -> Path:
def remove_unit(kind: str, unit_id: str, *, guard: "Callable[[Path], bool]") -> str:
- """Remove one unit's ledger entirely. Returns one of the ``REMOVE_*`` statuses.
+ """Remove one unit's crew log entirely. Returns one of the ``REMOVE_*`` statuses.
The ONE spelling of deletion in this package, called by the retention sweep
- and by the permanent-delete funnel alike, for the reason the work ledger's
+ and by the permanent-delete funnel alike, for the reason the work crew log's
``purge_matching`` docstring gives: two callers deleting the same tree two
ways is two chances to get the order wrong, and the order is the whole
correctness argument.
@@ -397,11 +397,11 @@ def remove_unit(kind: str, unit_id: str, *, guard: "Callable[[Path], bool]") ->
open -- the same asymmetry :func:`session_ledger.unlink_lock_in_hold`
documents, so that function is reused rather than copied.
- **Nothing is written to a ledger that is about to go.** No "pruned" entry, no
+ **Nothing is written to a crew log that is about to go.** No "pruned" entry, no
tombstone: removal is not rotation and not a format change, and a reader
holding a citation into the unit already has its answer from
``Ref.resolve``, which reports ``gone`` for a pointer into a unit that has no
- ledger at all.
+ crew log at all.
Failures are COUNTED, not ignored, and reported for what they are. A unit
that could not be fully removed answers ``failed`` rather than being reported
@@ -425,7 +425,7 @@ def remove_unit(kind: str, unit_id: str, *, guard: "Callable[[Path], bool]") ->
named = _checked_ledger_root(kind) / _store_name(unit_id)
if is_link(named):
logger.warning(
- "ledger retention: %s ledger %r is a link; refusing to remove what it names",
+ "crew log retention: %s log %r is a link; refusing to remove what it names",
kind,
unit_id,
)
@@ -443,7 +443,7 @@ def remove_unit(kind: str, unit_id: str, *, guard: "Callable[[Path], bool]") ->
except OSError:
# Failing to open the lease file is not evidence that someone owns the
# unit, and it is not a removal either.
- logger.warning("ledger retention: cannot lease %s ledger %r", kind, unit_id, exc_info=True)
+ logger.warning("crew log retention: cannot lease %s log %r", kind, unit_id, exc_info=True)
return REMOVE_FAILED
lease_gone = False
try:
@@ -460,7 +460,7 @@ def remove_unit(kind: str, unit_id: str, *, guard: "Callable[[Path], bool]") ->
# reader looking for a record this pass destroyed.
if history_gone:
logger.warning(
- "ledger retention: %s ledger %r only PARTLY removed; %d history file(s) "
+ "crew log retention: %s log %r only PARTLY removed; %d history file(s) "
"already gone and %d entr(ies) would not go",
kind,
unit_id,
@@ -469,7 +469,7 @@ def remove_unit(kind: str, unit_id: str, *, guard: "Callable[[Path], bool]") ->
)
else:
logger.warning(
- "ledger retention: %s ledger %r not removed; its history is intact",
+ "crew log retention: %s log %r not removed; its history is intact",
kind,
unit_id,
)
@@ -483,24 +483,24 @@ def remove_unit(kind: str, unit_id: str, *, guard: "Callable[[Path], bool]") ->
try:
lease_path.unlink(missing_ok=True)
except OSError:
- logger.debug("ledger retention: lease file still held; leaving it")
+ logger.debug("crew log retention: lease file still held; leaving it")
return REMOVE_FAILED
try:
directory.rmdir()
except OSError:
# Every file this owns is gone. A directory that will not go is residue,
# not retained history, so the removal still counts -- but say so.
- logger.debug("ledger retention: %s ledger %r directory not removed", kind, unit_id)
+ logger.debug("crew log retention: %s log %r directory not removed", kind, unit_id)
return REMOVE_REMOVED
def unit_header_slot(kind: str, unit_id: str) -> "str | None":
"""The slot recorded in *unit_id*'s HEADER, or None when it cannot be proved.
- An independent second answer to "whose ledger is this", for a caller that
+ An independent second answer to "whose crew log is this", for a caller that
reached the unit id through a channel it does not fully trust. The header is
written once by the emitter at creation and never rewritten, and it is inside
- the fenced ledger tree, so it does not move when a mapping does.
+ the fenced crew log tree, so it does not move when a mapping does.
None for every reason a caller must not proceed on: no directory, no segment,
an unreadable or unparseable header, a header whose own id does not fold back
@@ -602,14 +602,14 @@ def _is_segment_name(name: str) -> bool:
Deliberately broader than :func:`_segment_first_seq`, which answers the
different question of whether a file is a canonical segment a reader may
- trust: that one rejects ``ledger.1.jsonl`` and ``ledger.0.jsonl``, because no
+ trust: that one rejects ``log.1.jsonl`` and ``log.0.jsonl``, because no
real segment starts below seq 2. Removal must not inherit that rule. It
deletes every file in the unit's directory whatever its name, and this
predicate only decides what goes FIRST, so a stray numbered file is better
grouped with the segments than left to the tail of the pass -- it is history
by shape, and the ordering exists so the identity files outlive the history.
"""
- if name == LEDGER_FILE:
+ if name == LOG_FILE:
return True
if not (name.startswith(f"{_SEGMENT_STEM}.") and name.endswith(_SEGMENT_SUFFIX)):
return False
@@ -642,13 +642,13 @@ def _is_segment_name(name: str) -> bool:
#: is not None``, so a reset that keeps the conversation emits
#: ``session/closed {reset}`` while LEAVING the old id mapped -- still resumable,
#: and its log still needed. ``discarded`` clears the sid unconditionally and would
-#: qualify on that test, but no path writes that reason into a ledger today, so
+#: qualify on that test, but no path writes that reason into a crew log today, so
#: admitting it would be a rule about a file nothing produces. Every other reason --
#: a shutdown, a crash, an eviction, or a spelling this build does not know -- ends
#: the gateway's SERVICE of the session without ending the id's life.
#:
#: This reason is the whole authorization for deleting a unit, and it is read from
-#: the ledger rather than from anything outside it. The obvious alternative -- ask
+#: the crew log rather than from anything outside it. The obvious alternative -- ask
#: which sessions are still mapped in ``session_map.json`` and keep those -- was
#: implemented and then removed, because that file is agent-WRITABLE while this tree
#: is bind-masked, and a VALID EMPTY map is not a failed read: it reads as "nothing
@@ -666,7 +666,7 @@ def _is_terminal_close(entry: "Entry") -> bool:
def sweep_expired(retention_days: int, *, now: float | None = None) -> "tuple[int, int]":
- """Remove CLOSED session ledgers older than *retention_days*. ``(removed, failed)``.
+ """Remove CLOSED session logs older than *retention_days*. ``(removed, failed)``.
The same switch and the same sweep that already expire transcript archives:
``history._cleanup_old_archives`` calls this with the retention it resolved
@@ -674,26 +674,26 @@ def sweep_expired(retention_days: int, *, now: float | None = None) -> "tuple[in
already has. A negative value disables both halves, so a user who turned
archive expiry off has turned this off too and there is no second setting to
find. Bodies live in these files now, which is why one switch has to govern
- both: expiring the transcript while its ledger grew forever is the gap this
+ both: expiring the transcript while its crew log grew forever is the gap this
closes.
A missing root, or one holding no unit directories, costs a directory listing
and answers ``(0, 0)``. That is also what makes this de facto gated by
- ``KIROCREW_SESSION_LEDGER`` without reading it: only the emitter creates
+ ``KIROCREW_CREW_LOG`` without reading it: only the emitter creates
session units, and the emitter is inert without the flag. Reading the flag
HERE would be worse than not reading it -- turning it off would strand every
- ledger already written, permanently, since nothing else collects them.
+ crew log already written, permanently, since nothing else collects them.
- Crew ledgers are out of scope and are never scanned: this walks
- ``ledgers/sessions`` alone. They have no writer yet, and no ``session/closed``
+ Crew logs are out of scope and are never scanned: this walks
+ ``crew-log/sessions`` alone. They have no writer yet, and no ``session/closed``
to age from, so a rule invented for them now would be a guess applied to
files nothing produces.
- A unit is collectable only when its own ledger PROVES the session is finished:
+ A unit is collectable only when its own log PROVES the session is finished:
the newest lifecycle entry is a ``session/closed`` whose reason is one of
:data:`_TERMINAL_CLOSE_REASONS`, meaning the gateway cleared that ACP id's
mapping during the teardown so it can never be resumed. Nothing outside the
- ledger tree takes part in that decision -- see that constant for why the
+ crew log tree takes part in that decision -- see that constant for why the
session map was tried for it and removed.
"""
if retention_days < 0:
@@ -709,7 +709,7 @@ def sweep_expired(retention_days: int, *, now: float | None = None) -> "tuple[in
# A root that EXISTS and is wrong. Not a unit failure -- there is no
# legitimate unit here to have failed -- so it is reported and the pass
# ends rather than being counted as work.
- logger.warning("ledger retention: refusing to sweep the session ledger root", exc_info=True)
+ logger.warning("crew log retention: refusing to sweep the session log root", exc_info=True)
return (0, 0)
except OSError:
# Includes the ordinary case of a root that was never created.
@@ -737,7 +737,7 @@ def sweep_expired(retention_days: int, *, now: float | None = None) -> "tuple[in
# One unreadable unit must not stop the pass over the others, and it
# is not a removal: the unit keeps its history and the next pass sees
# it again.
- logger.debug("ledger retention: skipped %s", child.name, exc_info=True)
+ logger.debug("crew log retention: skipped %s", child.name, exc_info=True)
failed += 1
continue
if status == REMOVE_REMOVED:
@@ -746,7 +746,7 @@ def sweep_expired(retention_days: int, *, now: float | None = None) -> "tuple[in
failed += 1
if removed or failed:
logger.info(
- "ledger retention: removed %d expired session ledger(s) (>%dd), %d could not be removed",
+ "crew log retention: removed %d expired session log(s) (>%dd), %d could not be removed",
removed,
retention_days,
failed,
@@ -784,7 +784,7 @@ def _expired_unit_id(directory: Path, cutoff_ms: int) -> "str | None":
is never touched, whatever its age, and this is the check that decides it.
The pair ``session/opened`` / ``session/closed`` is what moves a unit
between the two states, so the newest of the PAIR is the answer -- not the
- newest close on its own. A resumed session appends to the ledger it already
+ newest close on its own. A resumed session appends to the crew log it already
had, so ``... closed ... opened ...`` is a legitimate file whose session is
running right now. The read is bounded, so the deciding entry could in
principle sit further back than the window -- but only entries written after
@@ -792,7 +792,7 @@ def _expired_unit_id(directory: Path, cutoff_ms: int) -> "str | None":
a handful of in-flight closers unless the session was revived, which appends
its own ``session/opened``. So a lifecycle entry outside the window means a
live session, which is exactly the unit that must be kept: the bound fails
- closed rather than needing a full scan of every ledger on every pass.
+ closed rather than needing a full scan of every crew log on every pass.
* **A segment that vanished mid-read.** Another remover -- the delete funnel,
or a second pass -- got there first, which is the outcome this sweep wanted.
It reads as "nothing to do" rather than as a failure, because the caller's
@@ -864,7 +864,7 @@ def _last_lifecycle_entry(tail: _Tail) -> "Entry | None":
"""The newest ``session/opened`` or ``session/closed`` in *tail*'s window.
Whether a unit is closed is decided by the newest of the PAIR, not by the
- newest close on its own. A resumed session appends to the ledger it already
+ newest close on its own. A resumed session appends to the crew log it already
had, so a file legitimately reads ``... closed ... opened ...`` -- one close
followed by the revival that outlived it -- and a scan that stopped at the
close would call a session that is running right now expired and delete a
@@ -1058,7 +1058,7 @@ def _full_scan_last_seq(path: Path) -> int:
def _has_content(path: Path) -> bool:
"""Whether *path* holds any bytes. A zero-byte file reads as absent.
- ``create`` and ``open`` need the same answer: an empty file is not a ledger
+ ``create`` and ``open`` need the same answer: an empty file is not a crew log
and never was one, so treating it as existing would strand a unit on a file
that carries nothing to protect.
"""
@@ -1073,7 +1073,7 @@ def _iter_entries(path: Path) -> Iterator[Entry]:
A malformed interior line is SKIPPED, not raised on: the log is append-only
and one damaged line must not hide the history in front of it. The file is
- streamed line by line, so a large ledger costs one line of memory, not its
+ streamed line by line, so a large crew log costs one line of memory, not its
size.
Decoding is STRICT and per line. Replacement-decoding would be the wrong
@@ -1094,7 +1094,7 @@ def _iter_entries(path: Path) -> Iterator[Entry]:
try:
with open(path, "rb") as source:
for index, raw in enumerate(
- bounded_raw_records(source, path, cap=MAX_ENTRY_BYTES, label="ledger")
+ bounded_raw_records(source, path, cap=MAX_ENTRY_BYTES, label="crew log")
):
if index == 0:
continue # the header
@@ -1176,7 +1176,7 @@ class Page:
@dataclass(frozen=True)
class Resolution:
- """The outcome of following a :class:`~kiro_crew.ledger.schema.Ref`."""
+ """The outcome of following a :class:`~kiro_crew.crew_log.schema.Ref`."""
status: str
entries: tuple[Entry, ...]
@@ -1217,12 +1217,12 @@ def _covers_span(found: tuple[Entry, ...], from_seq: int, last_seq: int) -> bool
# --------------------------------------------------------------------------- #
-# The ledger
+# The crew log
# --------------------------------------------------------------------------- #
class Ledger:
- """One unit's append-only ledger.
+ """One unit's append-only crew log.
Construct through :meth:`create` or :meth:`open`, never directly: both do
the file-level work (existence, header, torn-tail repair, seq recovery) that
@@ -1297,7 +1297,7 @@ def __repr__(self) -> str: # pragma: no cover - diagnostics only
@classmethod
def exists(cls, kind: str, unit_id: str) -> bool:
- """Whether *unit_id* has a ledger with content. Raises on an invalid id.
+ """Whether *unit_id* has a crew log with content. Raises on an invalid id.
Empty means absent, the same answer ``create`` and ``open`` give, so all
three agree about a file that carries nothing.
@@ -1306,7 +1306,7 @@ def exists(cls, kind: str, unit_id: str) -> bool:
@classmethod
def create(cls, kind: str, unit_id: str, **header_fields: Any) -> Ledger:
- """Write a new ledger's header. Refuses if the file already exists.
+ """Write a new crew log's header. Refuses if the file already exists.
The header is PUBLISHED atomically -- temp file, fsync, rename -- while
every later line is a plain append. Creation is the one moment the file
@@ -1324,20 +1324,20 @@ def create(cls, kind: str, unit_id: str, **header_fields: Any) -> Ledger:
Existence is checked twice, the second time under the lock: the first
check is the cheap answer for the ordinary caller, the second is what
- makes "create refuses an existing ledger" true when two processes race.
+ makes "create refuses an existing crew log" true when two processes race.
"""
kind = require_kind(kind)
path = ledger_path(kind, unit_id)
if _has_content(path):
raise LedgerError(
- f"{kind} ledger {unit_id!r} already exists", code=CODE_ALREADY_EXISTS, field="id"
+ f"{kind} crew log {unit_id!r} already exists", code=CODE_ALREADY_EXISTS, field="id"
)
header = build_header(kind, unit_id, now_ms(), header_fields)
line = require_entry_line(serialize(header.to_dict()))
with _open_lock(_lock_path(kind, unit_id)):
if _has_content(path):
raise LedgerError(
- f"{kind} ledger {unit_id!r} already exists",
+ f"{kind} crew log {unit_id!r} already exists",
code=CODE_ALREADY_EXISTS,
field="id",
)
@@ -1354,7 +1354,7 @@ def create(cls, kind: str, unit_id: str, **header_fields: Any) -> Ledger:
@classmethod
def open(cls, kind: str, unit_id: str, *, repair: bool = False) -> Ledger:
- """Open an existing ledger, repairing a torn tail if there is one.
+ """Open an existing crew log, repairing a torn tail if there is one.
A zero-byte file answers ``no_ledger``, the same answer ``create`` gives
it. One meaning for an empty file across both paths is what keeps them
@@ -1363,9 +1363,9 @@ def open(cls, kind: str, unit_id: str, *, repair: bool = False) -> Ledger:
``repair`` is what closes an INTERRUPTED TURN, and it is opt-in because
the two callers of ``open`` want opposite things. A RESUME -- the gateway
- finding a session ledger whose writer is gone -- wants the open turn
+ finding a session log whose writer is gone -- wants the open turn
closed, and passes ``repair=True``. A live writer RECONNECTING to its own
- ledger must not: its turn is still running, and closing it would append a
+ crew log must not: its turn is still running, and closing it would append a
``turn/completed {interrupted}`` in the middle of a turn that then keeps
writing, so the record would claim an outcome the turn never had. A
reconnect happens for reasons that have nothing to do with the writer's
@@ -1377,7 +1377,7 @@ def open(cls, kind: str, unit_id: str, *, repair: bool = False) -> Ledger:
"""
kind = require_kind(kind)
# The NEWEST segment is the one a writer appends to, and with nothing
- # rotating yet that is ``ledger.jsonl`` in every ledger that exists. Taking
+ # rotating yet that is ``log.jsonl`` in every crew log that exists. Taking
# it from the segment list rather than the fixed name is what lets a log
# whose oldest segment was pruned still open: retention removes files off
# the front, and the header travels on each segment so the survivor carries
@@ -1386,7 +1386,9 @@ def open(cls, kind: str, unit_id: str, *, repair: bool = False) -> Ledger:
candidate for candidate in segment_paths(kind, unit_id) if _has_content(candidate)
]
if not segments:
- raise LedgerError(f"no {kind} ledger for {unit_id!r}", code=CODE_NO_LEDGER, field="id")
+ raise LedgerError(
+ f"no {kind} crew log for {unit_id!r}", code=CODE_NO_LEDGER, field="id"
+ )
path = segments[-1]
header_path = segments[0]
with _open_lock(_lock_path(kind, unit_id)):
@@ -1395,7 +1397,7 @@ def open(cls, kind: str, unit_id: str, *, repair: bool = False) -> Ledger:
dropped = path.stat().st_size - tail.torn_offset
_truncate(path, tail.torn_offset)
logger.warning(
- "dropped %d torn trailing byte(s) from %s ledger %r",
+ "dropped %d torn trailing byte(s) from %s crew log %r",
dropped,
kind,
unit_id,
@@ -1404,7 +1406,7 @@ def open(cls, kind: str, unit_id: str, *, repair: bool = False) -> Ledger:
parsed = None if not raw else _parses_to_object(raw)
if parsed is None:
raise LedgerError(
- f"{kind} ledger {unit_id!r} has no readable header line",
+ f"{kind} crew log {unit_id!r} has no readable header line",
code=CODE_BAD_HEADER,
field="type",
)
@@ -1438,7 +1440,7 @@ def open(cls, kind: str, unit_id: str, *, repair: bool = False) -> Ledger:
)
def repair_interrupted_turn(self) -> int:
- """Close an open turn on this ledger. Returns how many closers landed.
+ """Close an open turn on this crew log. Returns how many closers landed.
The method form of ``open(repair=True)``, for a caller that already holds
a handle. Same rule: only a resume calls it, never a live writer.
@@ -1534,7 +1536,7 @@ def append(
not isinstance(thread, int) or isinstance(thread, bool) or thread < 1
):
raise LedgerError(
- f"thread must be a positive seq in this ledger: {thread!r}",
+ f"thread must be a positive seq in this crew log: {thread!r}",
code=CODE_BAD_THREAD,
field="thread",
)
@@ -1546,7 +1548,7 @@ def append(
tail = _scan_tail(self._path)
if tail.empty:
raise LedgerError(
- f"no {self._kind} ledger for {self._id!r}",
+ f"no {self._kind} crew log for {self._id!r}",
code=CODE_NO_LEDGER,
field="id",
)
@@ -1556,7 +1558,7 @@ def append(
thread > tail.last_seq or not _anchor_exists(self._path, thread, tail)
):
raise LedgerError(
- f"thread {thread} names no parseable entry in this ledger "
+ f"thread {thread} names no parseable entry in this crew log "
f"(newest seq is {tail.last_seq})",
code=CODE_BAD_THREAD,
field="thread",
@@ -1629,7 +1631,7 @@ def append_many(
tail = _scan_tail(self._path)
if tail.empty:
raise LedgerError(
- f"no {self._kind} ledger for {self._id!r}",
+ f"no {self._kind} crew log for {self._id!r}",
code=CODE_NO_LEDGER,
field="id",
)
@@ -1729,7 +1731,7 @@ def _iter_segments(self) -> Iterator[Entry]:
"""Every entry of every segment, oldest first, refusing bad provenance.
Every segment repeats the header because retention may remove the first one.
- Each header must therefore identify this same ledger and schema before any
+ Each header must therefore identify this same crew log and schema before any
entry from that independent file becomes authoritative. The filename's first
seq is a second provenance claim and must agree with the physical first entry
when that record is readable.
@@ -1759,7 +1761,7 @@ def _iter_segments(self) -> Iterator[Entry]:
if segment_header.version != self._header.version:
raise LedgerError(
f"segment {path.name} has schema version {segment_header.version}, "
- f"but this ledger uses {self._header.version}",
+ f"but this crew log uses {self._header.version}",
code=CODE_BAD_SEGMENT,
field="version",
)
@@ -1853,9 +1855,9 @@ def _page(self, before: int | None, limit: int, *, keep: Callable[[Entry], bool]
def resolve(self, ref: Ref | dict[str, Any]) -> Resolution:
"""Follow *ref* and return the segment it cites.
- Four outcomes. ``ok`` carries the entries. ``gone`` means the cited ledger
+ Four outcomes. ``ok`` carries the entries. ``gone`` means the cited crew log
does not exist at all -- a normal answer, not an error, since the cited
- ledger may legitimately have been deleted and the citing entry stays honest
+ crew log may legitimately have been deleted and the citing entry stays honest
about having pointed at it. ``pruned`` means the span reaches below the
oldest surviving segment's first seq, so retention removed those lines.
``corrupt`` means the span lies inside a segment that still exists yet read
@@ -1888,7 +1890,7 @@ def resolve(self, ref: Ref | dict[str, Any]) -> Resolution:
try:
target = Ledger.open(pointer.unit, pointer.id)
except LedgerError as exc:
- # Only "there is no such ledger" is `gone`. A ledger that EXISTS
+ # Only "there is no such crew log" is `gone`. A crew log that EXISTS
# but will not open -- a damaged header, an unreadable segment --
# is damage, and answering `gone` for it tells the reader to stop
# looking for a file that is right there and broken.
@@ -1967,7 +1969,7 @@ def _mkdir_private(directory: Path) -> None:
A bare ``mkdir`` takes the process umask, which is commonly world-readable, and
these directories hold conversation bodies. The eager tightening at
- ``/ledgers`` normally makes a leaf's own mode moot -- an unreadable parent
+ ``/crew-log`` normally makes a leaf's own mode moot -- an unreadable parent
is enough -- but it is best-effort, and this runs on the path taken when it did
not succeed. So the guarantee is asserted per directory as well as once at the
root, rather than resting on a parent that may not have been tightened.
@@ -1977,7 +1979,7 @@ def _mkdir_private(directory: Path) -> None:
directory is already owner-only.
Best-effort for the same reason the root's is: a filesystem that refuses the mode
- change must not make a ledger unwritable, and the sandbox mask and the file-tool
+ change must not make a crew log unwritable, and the sandbox mask and the file-tool
fence still stand.
"""
directory.mkdir(parents=True, exist_ok=True)
@@ -2108,7 +2110,7 @@ def _refuse_content_repair(unit_id: str, skipped: str) -> None:
observed, permanently, to a log nothing rewrites.
"""
logger.warning(
- "session ledger %r: not repairing an interrupted turn -- the fold skipped a "
+ "session log %r: not repairing an interrupted turn -- the fold skipped a "
"record (%s), so its result cannot be trusted and appending a closer could "
"fabricate an outcome",
unit_id,
@@ -2188,7 +2190,7 @@ def _orphan_chunk_offset(path: Path) -> "tuple[int, int, int] | None":
# Fail closed. Every byte has to be accounted for before an offset into this
# file can be trusted, and this read could not account for one.
logger.warning(
- "ledger %r: not scanning for an orphan chunk group -- a record could not "
+ "crew log %r: not scanning for an orphan chunk group -- a record could not "
"be read intact (%s), so a byte offset into this file cannot be trusted "
"and truncating on one could cut valid entries",
path,
@@ -2225,7 +2227,7 @@ def _truncate(path: Path, offset: int) -> None:
@dataclass(frozen=True)
class _OpenTail:
- """What a session ledger's last turn left open, in first-seen order."""
+ """What a session log's last turn left open, in first-seen order."""
turn: Any
calls: tuple[dict[str, Any], ...]
@@ -2339,17 +2341,17 @@ def _closer_entries(tail: _OpenTail, first_seq: int) -> list[Entry]:
def _close_interrupted_tail(kind: str, unit_id: str, path: Path) -> int:
"""Append closers for an interrupted turn. Returns how many were written.
- Session ledgers only, and RESUME ONLY. A crash, a SIGKILL or a pod eviction
+ Session logs only, and RESUME ONLY. A crash, a SIGKILL or a pod eviction
leaves the newest turn open, and every later reader then has to carry the same
special case: is this turn still running, or did its writer die? Closing the
- tail when the ledger is LOADED after an interruption answers that once, in the
+ tail when the crew log is LOADED after an interruption answers that once, in the
record, instead of in each reader.
"Loaded after an interruption" is the whole precondition, which is why this is
never reached from a plain ``open``. An open turn is indistinguishable from a
dead one by looking at the file, so the CALLER's situation is the only thing
that can tell them apart: a resume knows the previous writer is gone, and a
- live writer reconnecting to its own ledger knows it is not. Closing a turn
+ live writer reconnecting to its own log knows it is not. Closing a turn
that is still running would append an outcome it never had and then let the
turn keep writing past its own completion.
@@ -2384,7 +2386,7 @@ def _close_interrupted_tail(kind: str, unit_id: str, path: Path) -> int:
_truncate(path, offset)
tail = _scan_tail(path)
logger.warning(
- "dropped an unreachable chunk group from session ledger %r: seq %d-%d "
+ "dropped an unreachable chunk group from session log %r: seq %d-%d "
"were written for a message whose citing entry never landed, so that "
"one message is missing from this log",
unit_id,
@@ -2405,7 +2407,7 @@ def _close_interrupted_tail(kind: str, unit_id: str, path: Path) -> int:
needs_newline = False
written += 1
logger.info(
- "closed an interrupted turn in session ledger %r: %d closer(s) appended",
+ "closed an interrupted turn in session log %r: %d closer(s) appended",
unit_id,
written,
)
diff --git a/src/kiro_crew/dashboard/chat_delivery.py b/src/kiro_crew/dashboard/chat_delivery.py
index d6eb76ec6f8d..d1f8dbda67a0 100644
--- a/src/kiro_crew/dashboard/chat_delivery.py
+++ b/src/kiro_crew/dashboard/chat_delivery.py
@@ -148,7 +148,7 @@ def _queued_entry_id(slot: Any, delivery_id: str) -> str:
window -- and reading that as "mine was requeued" drops the transcript row for
a steer the turn actually consumed.
- The entry's OWN id is returned rather than a bool because the ledger records
+ The entry's OWN id is returned rather than a bool because the crew log records
which queue entry the text became, and the only id this coroutine could
otherwise reach is the client's `sendId` -- a different namespace, minted by a
different party, which no reader could join against the queue.
@@ -357,12 +357,12 @@ def _record_steer_requeued(queue_id: str) -> None:
# Deferred, not module-scope: this module is reached from the gateway boot
# path, and AUTOSDE's no-new-work-on-gateway-boot-path rule asks for a
# flag-gated subsystem's IMPORT to be gated, not just its use.
- from kiro_crew import session_ledger_emit
+ from kiro_crew.crew_log import emit as crew_log_emit
- sid = session_ledger_emit.session_id_of(client)
+ sid = crew_log_emit.session_id_of(client)
if not sid:
return
- session_ledger_emit.on_message_queued(
+ crew_log_emit.on_message_queued(
sid,
source="steer",
size_bytes=len(message.encode("utf-8", "surrogatepass")),
@@ -389,7 +389,7 @@ def _record_steer_requeued(queue_id: str) -> None:
"steer for slot %s was requeued and drained during the RPC; row already " "persisted",
slot.key,
)
- # No ledger entry: the drain already STARTED a turn with this text, and
+ # No entry: the drain already STARTED a turn with this text, and
# that turn recorded its own `message/received`. Writing `message/queued`
# now would place the queued fact AFTER the received fact that supersedes
# it, which reads as a message queued after it had already run.
@@ -397,7 +397,7 @@ def _record_steer_requeued(queue_id: str) -> None:
still_registered = bool(slot._pending_steers.count(message))
# The requeued entry's own id when the teardown moved our steer, else "". Held
- # rather than discarded to a bool, because the entry the ledger names has to be
+ # rather than discarded to a bool, because the entry the crew log names has to be
# the entry this path actually found.
queued_id = _queued_entry_id(slot, delivery_id)
queued = bool(queued_id)
@@ -417,7 +417,7 @@ def _record_steer_requeued(queue_id: str) -> None:
# Still registered means the teardown has not run yet and will
# requeue it, so the text still runs — the caller must NOT resend.
#
- # No ledger entry, because "will requeue" is a PREDICTION and this log
+ # No entry, because "will requeue" is a PREDICTION and this log
# records only what is observed: a second stop can hard-kill and
# discard the pending steers before the teardown runs, and then a
# `message/queued` would permanently claim a queue entry that was
@@ -500,7 +500,7 @@ def _record_steer_requeued(queue_id: str) -> None:
# No ledger entry from here either. Reaching this point rules out every requeue
# and discard KNOWN SO FAR, which is what entitles this path to persist a
# transcript row -- but that row is mutable and starts as `written`, promoted to
- # `consumed` only when the echo confirms the injection. A ledger line has no
+ # `consumed` only when the echo confirms the injection. A crew log line has no
# such state: it would assert consumption this coroutine cannot prove, and a
# turn that ends without the echo still requeues the text.
@@ -649,10 +649,10 @@ def queue_for_next_turn(
# running, so it is there. No turn ordinal: this message belongs to no turn
# yet, and it names the one it eventually runs as when that turn starts.
# Deferred for the boot-path rule; see the note at the other call site.
- from kiro_crew import session_ledger_emit
+ from kiro_crew.crew_log import emit as crew_log_emit
- session_ledger_emit.on_message_queued(
- session_ledger_emit.session_id_of(getattr(slot, "_acp_client", None)),
+ crew_log_emit.on_message_queued(
+ crew_log_emit.session_id_of(getattr(slot, "_acp_client", None)),
source=slot.key,
# "replace", not strict: a JSON body may carry a lone surrogate, which
# strict UTF-8 refuses to encode. The message is ALREADY queued at this
diff --git a/src/kiro_crew/dashboard/chat_runner.py b/src/kiro_crew/dashboard/chat_runner.py
index 463da3b5737d..f4bf1d33ae5e 100644
--- a/src/kiro_crew/dashboard/chat_runner.py
+++ b/src/kiro_crew/dashboard/chat_runner.py
@@ -19,7 +19,6 @@
model_registry,
resource_status,
session_directive,
- session_ledger_emit,
)
from kiro_crew.acp.client import (
AcpAuthRequired,
@@ -84,6 +83,7 @@
strip_plan_markers,
validate_plan_format,
)
+from kiro_crew.crew_log import emit as crew_log_emit
from kiro_crew.dashboard import directive_queue
from kiro_crew.dashboard.chat_delivery import (
STEER_STATE_CONSUMED,
@@ -1252,7 +1252,7 @@ def _ledger_model(slot: Any, fallback: str = "") -> str:
entry therefore states a model that was not used, in a file nothing rewrites.
``served_model`` is the session fact, and it is empty when the backend serves
- its own default. The ledger records that emptiness rather than naming a model,
+ its own default. The crew log records that emptiness rather than naming a model,
for the same reason it omits an unmeasured token count: absent beats false.
*fallback* covers only a slot shape that cannot report the fact at all -- the
@@ -3972,10 +3972,10 @@ def _is_stop_event(m: dict) -> bool:
# is read from the slot's client and the emitter's live record, so there is one
# source for it rather than a copy threaded through every caller; the step is
# derived inside the emitter from the same record.
- _ledger_sid_here = session_ledger_emit.session_id_of(getattr(slot, "_acp_client", None))
- session_ledger_emit.on_message_sent(
+ _ledger_sid_here = crew_log_emit.session_id_of(getattr(slot, "_acp_client", None))
+ crew_log_emit.on_message_sent(
_ledger_sid_here,
- session_ledger_emit.live_turn(_ledger_sid_here),
+ crew_log_emit.live_turn(_ledger_sid_here),
text=redacted,
interrupted=interrupted,
)
@@ -6192,7 +6192,7 @@ def _queue_entry_is_orchestration(item: dict) -> bool:
#: the producer at ``queue_append`` and is not derivable from the entry's text,
#: which is the point: the banners these two injections wrap their text in
#: (``CRON_NOTIFY_PREFIX``, ``SUBAGENT_COMPLETION_PREFIXES``) are strings a user
-#: can type, and attributing a turn in the session ledger is a claim a reader
+#: can type, and attributing a turn in the session's log is a claim a reader
#: takes as fact. Same source, same reason as ``is_system_injection_item``.
#:
#: ``SYNTHETIC_RECOVERY_KIND`` is deliberately absent: a recovery's actor is
@@ -6218,7 +6218,7 @@ def _actor_for_queue_items(items: "list[dict]") -> str:
for item in items:
meta = item.get("meta")
stamped = meta.get(TURN_ACTOR_META_KEY, "") if isinstance(meta, dict) else ""
- if isinstance(stamped, str) and stamped in session_ledger_emit.ACTORS:
+ if isinstance(stamped, str) and stamped in crew_log_emit.ACTORS:
return stamped
return ""
@@ -6839,11 +6839,11 @@ async def _note_irreversibly_consumed() -> None:
"_directive_user_origin": directive_user_origin,
"_directive_channel_origin": directive_channel_origin,
}
- # Provenance for the session ledger, from the enqueue-time ``kind`` tag — the
+ # Provenance for the session's log, from the enqueue-time ``kind`` tag — the
# same unforgeable source ``is_system_injection_item`` classifies on, and for
# the same reason: the banner these injections wrap their text in is something
# a user can type. Left unset when no consumed entry carries a mapped kind,
- # which the ledger records as a user turn.
+ # which the crew log records as a user turn.
_queue_actor = _actor_for_queue_items(consumed)
if _queue_actor:
_run_kwargs["_turn_actor"] = _queue_actor
@@ -6852,7 +6852,7 @@ async def _note_irreversibly_consumed() -> None:
if _irreversible_delivery_callbacks:
_run_kwargs["_on_irreversibly_consumed"] = _note_irreversibly_consumed
# The row this turn runs carried its attachment lists through the queue, and this
- # is the site that has the item, so the ledger's ids come from here. Collected
+ # is the site that has the item, so the crew log's ids come from here. Collected
# across `consumed` because a row that carries attachments drains ALONE
# (`carries_attachments`), so there is exactly one such row to read.
_drained_attachment_meta: dict[str, list[str]] = {}
@@ -7163,10 +7163,10 @@ async def _run_chat(
_directive_channel_origin: bool = False,
# Who caused this turn, from the dispatch that knows -- a consumed queue
# entry's enqueue-time ``kind`` tag, or an injector calling this runner
- # directly. Recorded in the session ledger, so it must not be derivable from
+ # directly. Recorded in the session's log, so it must not be derivable from
# the message TEXT: a user can type the cron or sub-agent banner, and the
- # ledger's whole premise is that a reader takes it as fact. Empty means no
- # dispatch claimed it, which the ledger records as ``user``.
+ # crew log's whole premise is that a reader takes it as fact. Empty means no
+ # dispatch claimed it, which the crew log records as ``user``.
_turn_actor: str = "",
regenerate_hint: str = "",
_on_consumed: "Callable[[bool], None] | None" = None,
@@ -7275,7 +7275,7 @@ def _stop_pressed() -> bool:
# message, which the user writes.
_ledger_actor = _turn_actor or ("autonudge" if _directive_self_wake else "user")
- # Append-only session ledger identity, declared HERE rather than only where
+ # Append-only the session's log identity, declared HERE rather than only where
# it is filled in below: the mid-turn steer cut flushes a segment from a
# nested closure, and a closure reading one of these before the turn path
# assigns it would raise instead of simply recording nothing. Each is
@@ -7283,16 +7283,16 @@ def _stop_pressed() -> bool:
# makes every emitter call a no-op.
_ledger_sid = ""
_turn_msg_boundary = 0
- # The turn's ORDINAL for the ledger, kept separate from the message-slice
+ # The turn's ORDINAL for the crew log, kept separate from the message-slice
# index above even though both start at the same value. The slice index is
# reset when a mid-turn clear empties the message list, because the turn-stats
# scan is relative to that list -- and a shared local would silently move the
- # ledger's ordinal to 0 at the same moment, so the turn's own closers would
+ # crew log's ordinal to 0 at the same moment, so the turn's own closers would
# name a turn that never started.
_ledger_turn_no = 0
_ledger_step = 0
_ledger_step_t0 = time.monotonic()
- # The turn's terminal ledger payload, captured at the terminal event and
+ # The turn's terminal crew log payload, captured at the terminal event and
# emitted in the finally: the closers must follow the turn's last flushed
# assistant message, which happens after the stream loop breaks.
_ledger_terminal: "dict | None" = None
@@ -7483,7 +7483,7 @@ def _persist_partial_reply() -> None:
ONE helper for every recovery path, so the log copy cannot be forgotten by
the next path added -- the same reason redaction lives at the emitter's
boundary rather than at its call sites. Four handlers had this block
- inline and none of them reached the ledger, so a turn that streamed text
+ inline and none of them reached the crew log, so a turn that streamed text
the user watched got a closer saying it ended and nothing saying what it
had produced.
@@ -7499,7 +7499,7 @@ def _persist_partial_reply() -> None:
_redacted = redact_credentials(redact_exfiltration_urls(assistant_text)[0])[0]
slot.append("assistant", _redacted, "msg msg-a")
_append_redaction_notice(slot, _redacted)
- session_ledger_emit.on_message_sent(
+ crew_log_emit.on_message_sent(
_ledger_sid,
_ledger_turn_no,
step=_ledger_step,
@@ -8659,11 +8659,11 @@ def _require_current_binding() -> None:
# (the dashboard steer handler) can reach the running session's client
# to inject a mid-turn steer. Cleared in the finally below.
slot._acp_client = getattr(client, "client", None)
- # Append-only session ledger (flag-gated, fail-soft). The id is read
+ # Append-only the session's log (flag-gated, fail-soft). The id is read
# once here and reused at every emit site below, so a turn that never
# got a session id emits nothing rather than guessing one. ``owner`` is
# "default" because a crew-bound slot never reaches this local runner.
- _ledger_sid = session_ledger_emit.session_id_of(client)
+ _ledger_sid = crew_log_emit.session_id_of(client)
# This consumer implements the low-fidelity child downgrade (the
# interactive card) — opt in so the handle-level fail-close gate
# yields those events here instead of rejecting them itself.
@@ -8793,14 +8793,14 @@ def _require_current_binding() -> None:
f"will be used automatically once it's offered again.",
"msg msg-info",
)
- # Append-only session ledger (flag-gated, fail-soft). Written HERE rather
+ # Append-only the session's log (flag-gated, fail-soft). Written HERE rather
# than at session acquisition, because `model` has to name what the session
# RUNS on and that is not settled until the verdict above: a withheld pin is
# kept on the slot, and an unpinned slot's pin is backfilled, both after the
# handle exists. This is still ahead of every turn entry, and the announce
# decision itself is latched inside the emitter, so a retry after the header
# landed cannot skip it.
- session_ledger_emit.on_session_opened(
+ crew_log_emit.on_session_opened(
_ledger_sid,
agent=slot.agent or "",
slot=slot.key,
@@ -9595,7 +9595,7 @@ async def _refusal_fallback_retry() -> bool:
_turn_cost_usd = 0.0
_turn_model = ""
_turn_msg_boundary = len(slot.messages)
- # The ledger ordinal is the ABSOLUTE durable position, not the window
+ # The crew log ordinal is the ABSOLUTE durable position, not the window
# length. `slot.messages` is front-trimmed at `_MAX_SLOT_MESSAGES`, so past
# that cap its length stops growing and every later turn drew the SAME
# ordinal -- the emitter then read distinct turns as retries of one and
@@ -9621,7 +9621,7 @@ async def _refusal_fallback_retry() -> bool:
getattr(slot, "_disk_older_durable_count", 0) or 0
) + durable_row_count(slot.messages)
- # Append-only session ledger: what the request was configured as, what
+ # Append-only the session's log: what the request was configured as, what
# the gateway put in front of the model, and the body it accepted. All
# three name ``_ledger_turn_no``, the one ordinal every entry of this
# turn uses, and all three are written BEFORE the dispatch gates below --
@@ -9630,7 +9630,7 @@ async def _refusal_fallback_retry() -> bool:
# The accepted input first, then the two facts DERIVED from it. Context is
# composed from this message, so a fold that read the composition first
# would see a derived fact before its cause.
- session_ledger_emit.on_message_received(
+ crew_log_emit.on_message_received(
_ledger_sid,
_ledger_turn_no,
role="user",
@@ -9638,14 +9638,14 @@ async def _refusal_fallback_retry() -> bool:
source=telemetry_channel_of(session_key),
attachments=_attachments,
)
- session_ledger_emit.on_request_configured(
+ crew_log_emit.on_request_configured(
_ledger_sid,
_ledger_turn_no,
model=_ledger_model(slot, slot.model or agent_model),
provider=provider_name,
context_window=read_context_tokens(client)[1],
)
- session_ledger_emit.on_context_composed(
+ crew_log_emit.on_context_composed(
_ledger_sid,
_ledger_turn_no,
blocks=slot_ctx_blocks,
@@ -9665,7 +9665,7 @@ async def _refusal_fallback_retry() -> bool:
try:
if monitor_completion is not None:
if not await monitor_completion.authorize():
- session_ledger_emit.on_turn_refused(
+ crew_log_emit.on_turn_refused(
_ledger_sid,
_ledger_turn_no,
"not_authorized",
@@ -9676,7 +9676,7 @@ async def _refusal_fallback_retry() -> bool:
state.sessions.begin_turn(session_key)
except SessionClosingError:
logger.info("Aborting dispatch for %s — gateway is shutting down", session_key)
- session_ledger_emit.on_turn_refused(
+ crew_log_emit.on_turn_refused(
_ledger_sid,
_ledger_turn_no,
"gateway_closing",
@@ -9702,7 +9702,7 @@ async def _refusal_fallback_retry() -> bool:
"was still being prepared (no session existed to cancel yet)",
session_key,
)
- session_ledger_emit.on_turn_refused(
+ crew_log_emit.on_turn_refused(
_ledger_sid,
_ledger_turn_no,
"stopped_before_dispatch",
@@ -9732,7 +9732,7 @@ async def _refusal_fallback_retry() -> bool:
"the turn was being prepared",
session_key,
)
- session_ledger_emit.on_turn_refused(
+ crew_log_emit.on_turn_refused(
_ledger_sid,
_ledger_turn_no,
"replay_superseded_before_dispatch",
@@ -9746,7 +9746,7 @@ async def _refusal_fallback_retry() -> bool:
return
if monitor_completion is not None:
monitor_completion.mark_accepted()
- # Append-only session ledger (flag-gated, fail-soft). Emitted HERE, after
+ # Append-only the session's log (flag-gated, fail-soft). Emitted HERE, after
# every gate above has passed, because ``turn/started`` asserts that the
# turn RAN: a start written before authorization leaves an orphan for each
# refusal, and the interrupted-turn repair would later close it as though
@@ -9756,7 +9756,7 @@ async def _refusal_fallback_retry() -> bool:
# stop-generation read above and the stream's turn registration below --
# the emitter hands the write to its own thread and returns -- so the
# atomic span those two gates rely on is unchanged.
- session_ledger_emit.on_turn_started(
+ crew_log_emit.on_turn_started(
_ledger_sid,
_ledger_turn_no,
_ledger_actor,
@@ -9771,7 +9771,7 @@ async def _refusal_fallback_retry() -> bool:
# dispatch would leave a step/started for a model call that never ran and
# never completes -- the same reason turn/started waits for the gates -- and
# the step's duration would include the time the gates took.
- _ledger_step = session_ledger_emit.on_step_started(_ledger_sid, _ledger_turn_no)
+ _ledger_step = crew_log_emit.on_step_started(_ledger_sid, _ledger_turn_no)
_ledger_step_t0 = time.monotonic()
event_stream = client.stream_command(message) if is_slash else client.stream(full_message)
async for event in event_stream:
@@ -9853,7 +9853,7 @@ async def _refusal_fallback_retry() -> bool:
# went on to produce this text, so the tools it was waiting on
# did finish. The turn-end closers cannot say that and take the
# emitter's `unknown` default instead.
- session_ledger_emit.close_open_tool_calls(
+ crew_log_emit.close_open_tool_calls(
_ledger_sid, _ledger_turn_no, status="completed"
)
# Text after a tool group means the model was called AGAIN:
@@ -9861,13 +9861,13 @@ async def _refusal_fallback_retry() -> bool:
# This transition is the only per-model-call boundary the
# stream exposes -- its terminal event is the turn's, not a
# call's -- so the step is derived here rather than reported.
- session_ledger_emit.on_step_completed(
+ crew_log_emit.on_step_completed(
_ledger_sid,
_ledger_turn_no,
_ledger_step,
ms=int((time.monotonic() - _ledger_step_t0) * 1000),
)
- _ledger_step = session_ledger_emit.on_step_started(_ledger_sid, _ledger_turn_no)
+ _ledger_step = crew_log_emit.on_step_started(_ledger_sid, _ledger_turn_no)
_ledger_step_t0 = time.monotonic()
in_tool_group = False
# The streamed delta is NOT written to the ledger. Redacting each
@@ -9973,7 +9973,7 @@ async def _refusal_fallback_retry() -> bool:
# emitting the call first put the tool ahead of the text that
# preceded it and a fold would read the narration as the call's
# result.
- session_ledger_emit.on_tool_called(
+ crew_log_emit.on_tool_called(
_ledger_sid,
_ledger_turn_no,
name=event.tool_name or "",
@@ -9982,7 +9982,7 @@ async def _refusal_fallback_retry() -> bool:
call_id=event.tool_call_id or "",
# Digested to a hash and a size, never recorded: that answers
# "same arguments as last time" and "how big was it" without
- # the ledger becoming where a shell command's secrets land.
+ # the crew log becoming where a shell command's secrets land.
# This is the already-redacted display string, so a value the
# user could not see is not hashed into a durable file either.
args=event.tool_input or "",
@@ -10322,7 +10322,7 @@ async def _refusal_fallback_retry() -> bool:
if event.refusal
else (event.tool_status or ("completed" if event.tool_final else "unknown"))
)
- session_ledger_emit.on_tool_completed(
+ crew_log_emit.on_tool_completed(
_ledger_sid,
_ledger_turn_no,
name=event.tool_name or "",
@@ -12100,7 +12100,7 @@ async def _refusal_fallback_retry() -> bool:
# Advance the durable POSITION base by the rows this clear
# evicts, exactly as the trim path does (`_ChatSlot.append`)
# and as every restore path recomputes it. The base plus the
- # window's durable rows is the ledger turn ordinal and the
+ # window's durable rows is the crew log turn ordinal and the
# session_control `since` cursor space; emptying the window
# without crediting the base made the next turn draw an
# ordinal an earlier turn already wrote (two unrelated turns
@@ -12594,7 +12594,7 @@ async def _refusal_fallback_retry() -> bool:
# joins. Attributing the sample to the slot would file every
# linked Slack or Telegram turn under ``dashboard`` — the
# same blind spot in a new place.
- # The turn's ledger closers are STASHED, not emitted here. This
+ # The turn's crew log closers are STASHED, not emitted here. This
# point is inside the stream loop, and the turn's LAST assistant
# message is flushed after the loop breaks -- so emitting now puts
# `turn/completed` in the file ahead of a `message/sent` belonging
@@ -14682,12 +14682,12 @@ def _emit_error(msg: str, *, will_retry: bool = False) -> None:
and not _should_suppress_requeue(slot)
and (_fb_candidate := await _fallback_swap_for_turn(slot, client)) is not None
):
- # Append-only session ledger (flag-gated, fail-soft). Emitted HERE,
+ # Append-only the session's log (flag-gated, fail-soft). Emitted HERE,
# in the branch body, so it runs after _fallback_swap_for_turn has
# released slot._model_pick_lock rather than while it is held. This
# is the one model decision a transcript cannot answer afterwards:
# the user picked the primary and the turn ran somewhere else.
- session_ledger_emit.on_model_selected(
+ crew_log_emit.on_model_selected(
_ledger_sid, _fb_candidate, "fallback", turn=_ledger_turn_no
)
# ── Throttle-exhaustion model fallback (agent.fallback_model) ──
@@ -15202,7 +15202,7 @@ def _emit_error(msg: str, *, will_retry: bool = False) -> None:
if not (isinstance(exc, MemoryStartupUnavailable) and not _memory_preparation_admitted):
await state.sessions.record_failure(session_key)
finally:
- # The turn's ledger closers, in the one order a reader can trust: every
+ # The turn's crew log closers, in the one order a reader can trust: every
# `message/sent` for this turn has now been flushed, so the tool closer,
# the last step's completion and the turn's own completion land after the
# text they close over. Emitted HERE rather than at the terminal event
@@ -15213,16 +15213,16 @@ def _emit_error(msg: str, *, will_retry: bool = False) -> None:
# before the turn completes so a turn never completes with an open
# call inside it -- the shape the interrupted-turn repair exists to
# fix, which a live turn must not produce in the first place.
- session_ledger_emit.close_open_tool_calls(_ledger_sid, _ledger_turn_no)
+ crew_log_emit.close_open_tool_calls(_ledger_sid, _ledger_turn_no)
# The turn's LAST model call has no tool group after it to close it,
# so the turn's end does.
- session_ledger_emit.on_step_completed(
+ crew_log_emit.on_step_completed(
_ledger_sid,
_ledger_turn_no,
_ledger_step,
ms=int((time.monotonic() - _ledger_step_t0) * 1000),
)
- session_ledger_emit.on_turn_completed(_ledger_sid, _ledger_turn_no, **_ledger_terminal)
+ crew_log_emit.on_turn_completed(_ledger_sid, _ledger_turn_no, **_ledger_terminal)
_ledger_terminal = None
_ledger_turn_open = False
elif _ledger_turn_open:
@@ -15240,14 +15240,14 @@ def _emit_error(msg: str, *, will_retry: bool = False) -> None:
# `_record_model` are assigned inside the terminal-event arm, so
# naming them here would raise inside a `finally` and mask the very
# exception that brought us here.
- session_ledger_emit.close_open_tool_calls(_ledger_sid, _ledger_turn_no)
- session_ledger_emit.on_step_completed(
+ crew_log_emit.close_open_tool_calls(_ledger_sid, _ledger_turn_no)
+ crew_log_emit.on_step_completed(
_ledger_sid,
_ledger_turn_no,
_ledger_step,
ms=int((time.monotonic() - _ledger_step_t0) * 1000),
)
- session_ledger_emit.on_turn_failed(
+ crew_log_emit.on_turn_failed(
_ledger_sid,
_ledger_turn_no,
error=_ledger_error,
diff --git a/src/kiro_crew/dashboard/handlers/sessions.py b/src/kiro_crew/dashboard/handlers/sessions.py
index 87052cf0e261..25708259cf9d 100644
--- a/src/kiro_crew/dashboard/handlers/sessions.py
+++ b/src/kiro_crew/dashboard/handlers/sessions.py
@@ -1761,7 +1761,7 @@ def _capture_history_delete_claim(state: DashboardState, key: str) -> _HistoryDe
)
# Best-effort and read LAST: an unreadable ACP id must not downgrade a
# claim the checks above already completed, because every other cleanup
- # this claim authorizes is more important than collecting one ledger --
+ # this claim authorizes is more important than collecting one crew log --
# which the retention sweep collects anyway once the session is closed.
# Type-checked rather than merely truthy: this value goes on to ADDRESS a
# directory, so anything that is not a real id must read as absent.
@@ -1769,7 +1769,7 @@ def _capture_history_delete_claim(state: DashboardState, key: str) -> _HistoryDe
resumable = state.sessions.resumable_sid(session_key)
except Exception:
logger.debug(
- "History delete: ACP session id unreadable for %s; leaving its ledger "
+ "History delete: ACP session id unreadable for %s; leaving its crew log "
"to the retention sweep",
session_key,
exc_info=True,
@@ -2287,7 +2287,7 @@ def live_runtime_owns_session(session_key: str) -> bool:
# makes a work ledger unsafe to delete here is that its identity is the SLOT
# KEY, which is recycled -- a successor tab in the same slot legitimately
# inherits and resumes that record, and no check here can prove one is not
- # about to. A session ledger is keyed by the ACP SESSION ID, which never
+ # about to. A session's log is keyed by the ACP SESSION ID, which never
# names a different conversation, so removing it cannot reach a successor's
# state.
#
@@ -2295,10 +2295,10 @@ def live_runtime_owns_session(session_key: str) -> bool:
# attempted. ``destroy_if`` refuses when the session was replaced by a
# successor generation, is busy, or still has a live slot owner -- and in each
# of those cases the session it names is preserved and may be writing right
- # now, so removing its ledger would take a live conversation's log. The write
+ # now, so removing its crew log would take a live conversation's log. The write
# lease is not a substitute for this check: ownership ends BETWEEN turns by
# design, so an idle-but-live session holds nothing for the removal to be
- # refused by. A refused teardown therefore leaves the ledger alone and the
+ # refused by. A refused teardown therefore leaves the crew log alone and the
# retention sweep collects it once the session is genuinely closed.
#
# Only an id this claim PROVED is used -- captured pre-unlink, dropped on every
@@ -2306,7 +2306,7 @@ def live_runtime_owns_session(session_key: str) -> bool:
if session_destroyed and claim.acp_session_id:
# A key still mapping to this session id VETOES the removal. The unit is
# keyed by the ACP id, so a second key pointing at that id shares this very
- # ledger, and the teardown above removed only ONE mapping -- the other holder
+ # crew log, and the teardown above removed only ONE mapping -- the other holder
# can still resume, and its log is still needed. Two keys on one sid is a
# state the system itself produces: importing a transferred session twice
# allocates a new slot key each time and deliberately leaves the source
@@ -2320,7 +2320,7 @@ def live_runtime_owns_session(session_key: str) -> bool:
retained_key = ""
if retained_key is not None:
logger.info(
- "History delete: session id for %s is still mapped; leaving its ledger "
+ "History delete: session id for %s is still mapped; leaving its crew log "
"to retention",
key,
)
@@ -2328,9 +2328,9 @@ def live_runtime_owns_session(session_key: str) -> bool:
# Every slot spelling this delete established for itself. The removal
# requires the unit's own header to name one of them, because the id
# above came from ``session_map.json`` -- inside the agent-visible tree --
- # while the header is written once inside the fenced ledger tree and
+ # while the header is written once inside the fenced crew log tree and
# never rewritten. A mapping that named another conversation's session
- # would aim this removal at that conversation's ledger; its header would
+ # would aim this removal at that conversation's crew log; its header would
# not name this slot. The candidate spellings are included beside the
# live slot key so a legacy spelling of the same slot is not read as a
# different one.
@@ -2390,10 +2390,10 @@ def live_runtime_owns_session(session_key: str) -> bool:
def _remove_session_ledger(
session_id: str, history_key: str, proven_slots: "frozenset[str]"
) -> None:
- """Remove the append-only ledger of *session_id*. Never raises.
+ """Remove the append-only crew log of *session_id*. Never raises.
Imported lazily: this handler module is loaded on every startup while the
- ledger store is only reachable behind ``KIROCREW_SESSION_LEDGER``, so a
+ crew log store is only reachable behind ``KIROCREW_CREW_LOG``, so a
launch without the flag should not pay for the import.
*proven_slots* is every slot spelling this delete established for itself, and
@@ -2401,7 +2401,7 @@ def _remove_session_ledger(
because it arrives from ``session_map.json`` -- a file inside the agent-visible
tree -- so a mapping that named another conversation's session would aim this
removal at that conversation's ledger. The header is the independent answer: it
- is written once at creation inside the fenced ledger tree and never rewritten,
+ is written once at creation inside the fenced crew log tree and never rewritten,
so it does not move when a mapping does, and a unit belonging to another slot
fails the check. Slot recycling does not weaken it, because the id is what
selects the unit and the slot only has to prove the unit belonged to the slot
@@ -2413,16 +2413,16 @@ def _remove_session_ledger(
has landed.
Best-effort, like every other step of this teardown. The transcript row is
- already gone by the time this runs, so raising would turn a ledger that could
+ already gone by the time this runs, so raising would turn a crew log that could
not be collected into a failed delete the user has to retry against a row that
is absent -- and the retention sweep collects it on age regardless.
``owned`` is the ordinary answer when a queued write still holds the lease,
and it is not an error: that pass simply does nothing.
"""
try:
- from kiro_crew import session_ledger_emit
- from kiro_crew.ledger.schema import KIND_SESSION
- from kiro_crew.ledger.store import REMOVE_REMOVED, remove_unit, unit_header_slot
+ from kiro_crew.crew_log import emit as crew_log_emit
+ from kiro_crew.crew_log.schema import KIND_SESSION
+ from kiro_crew.crew_log.store import REMOVE_REMOVED, remove_unit, unit_header_slot
# LET THE TEARDOWN ENTRY LAND FIRST, and not as a courtesy: until it does,
# this removal cannot succeed at all. ``destroy`` -- the teardown checked
@@ -2431,45 +2431,47 @@ def _remove_session_ledger(
# that handle carries, only once that entry lands. A removal claiming the
# lease ``sole`` is refused while the handle is held, so without this
# barrier the funnel answers ``owned`` for every session the gateway
- # actually emitted for. Measured directly: a ledger opened through the
+ # actually emitted for. Measured directly: a crew log opened through the
# emitter answers ``owned``, and ``removed`` only after its close lands.
#
# A timeout is not a failure and is not treated as one. The entry stays
# owed, so the unit becomes collectable by the retention sweep -- which
# needs that same close, since a unit whose newest lifecycle entry is not
# a close reads as OPEN whatever its age. This pass simply does nothing.
- session_ledger_emit.flush(timeout=_LEDGER_TEARDOWN_FLUSH_SECONDS)
+ crew_log_emit.flush(timeout=_LEDGER_TEARDOWN_FLUSH_SECONDS)
header_slot = unit_header_slot(KIND_SESSION, session_id)
if header_slot is None or header_slot not in proven_slots:
logger.info(
- "History delete: the session ledger for %s names slot %r, which this "
+ "History delete: the session's log for %s names slot %r, which this "
"delete did not prove; leaving it to retention",
history_key,
header_slot,
)
return
- # Accept-all guard, deliberately. The sweep's guard re-reads the ledger
+ # Accept-all guard, deliberately. The sweep's guard re-reads the crew log
# because ITS reason is a property of the file -- an age it sampled outside
# the lease. This caller's reason is not in the file at all: the session
- # this ledger belongs to was destroyed by the teardown above, which is
+ # this crew log belongs to was destroyed by the teardown above, which is
# checked before this runs, and the header check above already proved the
# unit is this slot's. Re-reading the age here would answer a question
# nobody asked, and a close entry still queued behind the teardown would
- # make the honest answer "not closed" and skip a ledger whose session is
+ # make the honest answer "not closed" and skip a crew log whose session is
# gone.
status = remove_unit(KIND_SESSION, session_id, guard=lambda _dir: True)
except Exception:
logger.warning(
- "History delete: could not remove the session ledger for %s", history_key, exc_info=True
+ "History delete: could not remove the session's log for %s",
+ history_key,
+ exc_info=True,
)
return
if status == REMOVE_REMOVED:
- logger.info("History delete: removed the session ledger for %s", history_key)
+ logger.info("History delete: removed the session's log for %s", history_key)
else:
logger.info(
- "History delete: session ledger for %s not removed (%s); leaving it to retention",
+ "History delete: the session's log for %s not removed (%s); leaving it to retention",
history_key,
status,
)
diff --git a/src/kiro_crew/dashboard/server.py b/src/kiro_crew/dashboard/server.py
index 77367d84ba99..abb2ddf0ff5e 100644
--- a/src/kiro_crew/dashboard/server.py
+++ b/src/kiro_crew/dashboard/server.py
@@ -3171,7 +3171,7 @@ async def _instances_shutdown(app_: web.Application) -> None:
await manager.shutdown()
async def _session_ledger_drain(app_: web.Application) -> None:
- """Write out the session ledger's buffered appends before the process goes.
+ """Write out the session's log buffered appends before the process goes.
The emitter hands appends to a writer thread so a turn never waits on the
filesystem, which means a record can be in memory when shutdown starts.
@@ -3182,15 +3182,15 @@ async def _session_ledger_drain(app_: web.Application) -> None:
"""
try:
# Imported here, not at module scope: this file is on the gateway boot
- # path, and the emitter is flag-gated behind KIROCREW_SESSION_LEDGER.
+ # path, and the emitter is flag-gated behind KIROCREW_CREW_LOG.
# AUTOSDE's no-new-work-on-gateway-boot-path rule asks for the IMPORT to
# be gated, not just the handler, so a launch with the flag unset pays
# nothing for a subsystem it will never call.
- from kiro_crew import session_ledger_emit
+ from kiro_crew.crew_log import emit as crew_log_emit
- await asyncio.to_thread(session_ledger_emit.drain_for_shutdown)
+ await asyncio.to_thread(crew_log_emit.drain_for_shutdown)
except Exception: # noqa: BLE001 - shutdown must not raise
- logger.debug("session ledger drain failed during shutdown", exc_info=True)
+ logger.debug("crew log drain failed during shutdown", exc_info=True)
app.on_startup.append(_instances_startup)
app.on_cleanup.append(_instances_shutdown)
diff --git a/src/kiro_crew/executors.py b/src/kiro_crew/executors.py
index 466566257937..29160fc7e4a1 100644
--- a/src/kiro_crew/executors.py
+++ b/src/kiro_crew/executors.py
@@ -287,7 +287,7 @@
_MAX_PATH_PROBE_WORKERS = 8
_MAX_PATH_TRANSFER_WORKERS = 8
# ONE worker, and the count is the contract rather than a capacity guess. An
-# append-only ledger assigns ``seq`` by reading the file's own tail under its
+# append-only crew log assigns ``seq`` by reading the file's own tail under its
# lock, and a turn's entries thread under the ``seq`` its ``turn/started``
# returned -- so the entries of one unit must reach the file in the order their
# call sites produced them. A single worker draining a FIFO queue is what
@@ -531,13 +531,13 @@ def path_transfer_executor() -> ThreadPoolExecutor:
def ledger_executor() -> ThreadPoolExecutor:
- """Return the process-wide append-only ledger writer pool, creating it on first use.
+ """Return the process-wide append-only crew log writer pool, creating it on first use.
Threads are named ``mc-ledger``, and there is exactly ONE of them
(:data:`_MAX_LEDGER_WORKERS`) because the order entries reach a unit's file
is part of the format, not an optimization -- see that constant.
- Serves :mod:`kiro_crew.session_ledger_emit`, whose storage call takes the
+ Serves :mod:`kiro_crew.crew_log.emit`, whose storage call takes the
per-ledger lock, reads a bounded tail to assign ``seq`` and ``fsync``s the
appended line. Those otherwise run on the gateway's own event loop: a
``flock`` that waits and an ``fsync`` that enters the kernel, once per tool
@@ -548,7 +548,7 @@ def ledger_executor() -> ThreadPoolExecutor:
:func:`path_resolve_executor` has one: an ``fsync`` on a wedged or full
filesystem holds its worker until the kernel returns, and a started
``run_in_executor`` future cannot be cancelled. Here that can only delay
- other ledger writes -- which are fail-soft and never block a turn -- while on
+ other crew log writes -- which are fail-soft and never block a turn -- while on
the maintenance pool it would occupy a worker the orphan-reaping sweeps need
to recover from an event-loop wedge.
"""
diff --git a/src/kiro_crew/history.py b/src/kiro_crew/history.py
index 16907b4d9302..f42cf88fab86 100644
--- a/src/kiro_crew/history.py
+++ b/src/kiro_crew/history.py
@@ -931,9 +931,9 @@ def _cleanup_old_archives(retention_days: int | None = None, base: Path | None =
entirely — the user manages archive deletion manually.
The same pass expires closed SESSION LEDGERS, on the same setting and inside
- the same throttle (:func:`kiro_crew.ledger.store.sweep_expired`). One switch
- governs both because a session's message bodies live in its ledger now: a
- build that expired the transcript archive while the ledger it points into grew
+ the same throttle (:func:`kiro_crew.crew_log.store.sweep_expired`). One switch
+ governs both because a session's message bodies live in its crew log now: a
+ build that expired the transcript archive while the crew log it points into grew
forever would keep the larger half of the same history indefinitely, and a
second setting for it would be a second thing to find and turn off.
"""
@@ -962,8 +962,8 @@ def _cleanup_old_archives(retention_days: int | None = None, base: Path | None =
adir = _archive_dir(base)
cutoff = now - retention_days * 86400
removed = 0
- # An absent archive directory is not a reason to skip the ledger half: a
- # session can hold a ledger long before anything of its transcript is
+ # An absent archive directory is not a reason to skip the crew log half: a
+ # session can hold a crew log long before anything of its transcript is
# archived, so returning here would leave that half uncollected until the
# first archive ever written.
if adir.exists():
@@ -981,7 +981,7 @@ def _cleanup_old_archives(retention_days: int | None = None, base: Path | None =
def _cleanup_expired_ledgers(retention_days: int, now: float) -> None:
- """Expire closed session ledgers, best-effort, never at the transcript's cost.
+ """Expire closed the sessions' logs, best-effort, never at the transcript's cost.
Off the event loop, which is what makes the added filesystem work safe rather
than merely cheap: the only caller is ``_cleanup_old_archives``, reached from
@@ -993,20 +993,20 @@ def _cleanup_expired_ledgers(retention_days: int, now: float) -> None:
than per delete on the loop.
Imported lazily and swallowed on failure for one reason each. Lazily because
- this module is imported on every startup while the ledger store is only
- reachable behind ``KIROCREW_SESSION_LEDGER``, and a launch without the flag
+ this module is imported on every startup while the crew log store is only
+ reachable behind ``KIROCREW_CREW_LOG``, and a launch without the flag
should not pay for the import. Swallowed because the caller is on the
- transcript ARCHIVE path: a ledger tree that cannot be swept is a disk-space
+ transcript ARCHIVE path: a crew log tree that cannot be swept is a disk-space
problem, and letting it raise here would turn that into a failure to archive
the transcript, which loses history rather than retaining too much of it. The
sweep logs its own counts.
"""
try:
- from kiro_crew.ledger.store import sweep_expired
+ from kiro_crew.crew_log.store import sweep_expired
sweep_expired(retention_days, now=now)
except Exception:
- logger.debug("Session ledger retention sweep failed", exc_info=True)
+ logger.debug("The session's log retention sweep failed", exc_info=True)
def transcript_sort_key(ts: str) -> tuple[int, float]:
diff --git a/src/kiro_crew/ledger/__init__.py b/src/kiro_crew/ledger/__init__.py
deleted file mode 100644
index 1adba5e38250..000000000000
--- a/src/kiro_crew/ledger/__init__.py
+++ /dev/null
@@ -1,158 +0,0 @@
-"""Append-only ledgers for crews and sessions -- the storage layer, nothing else.
-
-The format, the rules and how this stream relates to the lifecycle event track are
-specified in ``docs/system-specs/modules/ledger-core.md``. Two units, one file
-each, the gateway the only writer::
-
- from kiro_crew.ledger import Ledger
-
- crew = Ledger.create("crew", "qa")
- crew.append("member/joined", {"who": "s-7f3a"}, src="gateway")
-
-A crew header carries nothing but the unit's id and its creation time, which is
-why the example passes neither: a display name belongs to the members store, which
-owns it and can change it, and ``create`` refuses an unknown header field with
-``bad_header_field`` rather than dropping it.
-
-This package holds no dashboard, route, tool or migration code. It reads and
-writes its own files and imports only path, lock and containment primitives, so
-a consumer can be added without this layer learning about it.
-"""
-
-from __future__ import annotations
-
-from kiro_crew.ledger.entry_types import (
- ENTRY_TYPES,
- SESSION_ENTRY_TYPES,
- EntryType,
- Field,
- declaration_for,
- render_markdown,
- validate_data,
-)
-from kiro_crew.ledger.errors import (
- CODE_ALREADY_EXISTS,
- CODE_ALREADY_OWNED,
- CODE_BAD_DATA,
- CODE_BAD_DATA_FIELD,
- CODE_BAD_HEADER,
- CODE_BAD_HEADER_FIELD,
- CODE_BAD_KIND,
- CODE_BAD_REF,
- CODE_BAD_ROOT,
- CODE_BAD_SEGMENT,
- CODE_BAD_SRC,
- CODE_BAD_THREAD,
- CODE_BAD_TYPE,
- CODE_ENTRY_TOO_LARGE,
- CODE_EVENT_TYPE_NOT_OWNED,
- CODE_INVALID_ID,
- CODE_NAMESPACE_VIOLATION,
- CODE_NO_LEDGER,
- CODE_SEGMENT_GAP,
- CODE_UNKNOWN_ENTRY_TYPE,
- CODE_UNSUPPORTED_VERSION,
- IndeterminateAppend,
- LedgerError,
-)
-from kiro_crew.ledger.schema import (
- FIXED_SOURCES,
- KIND_CREW,
- KIND_FIXED_SOURCES,
- KIND_SESSION,
- KIND_SOURCE_PREFIXES,
- KINDS,
- MAX_ENTRY_BYTES,
- MAX_REF_SPAN,
- SCHEMA_VERSION,
- TYPE_OWNERSHIP,
- CrewHeader,
- Entry,
- Header,
- Ref,
- SessionHeader,
- SessionThread,
-)
-from kiro_crew.ledger.store import (
- DEFAULT_PAGE_LIMIT,
- LEDGER_FILE,
- MAX_PAGE_LIMIT,
- STATUS_CORRUPT,
- STATUS_GONE,
- STATUS_OK,
- STATUS_PRUNED,
- Ledger,
- Page,
- Resolution,
- ledger_dir,
- ledger_path,
- ledger_root,
- now_ms,
- segment_first_seqs,
- segment_paths,
-)
-
-__all__ = [
- "CODE_ALREADY_EXISTS",
- "CODE_ALREADY_OWNED",
- "CODE_BAD_DATA",
- "CODE_BAD_DATA_FIELD",
- "CODE_BAD_HEADER",
- "CODE_BAD_HEADER_FIELD",
- "CODE_BAD_KIND",
- "CODE_BAD_REF",
- "CODE_BAD_ROOT",
- "CODE_BAD_SEGMENT",
- "CODE_BAD_SRC",
- "CODE_BAD_THREAD",
- "CODE_BAD_TYPE",
- "CODE_ENTRY_TOO_LARGE",
- "CODE_UNSUPPORTED_VERSION",
- "CODE_EVENT_TYPE_NOT_OWNED",
- "CODE_INVALID_ID",
- "CODE_NAMESPACE_VIOLATION",
- "CODE_NO_LEDGER",
- "CODE_UNKNOWN_ENTRY_TYPE",
- "CODE_SEGMENT_GAP",
- "DEFAULT_PAGE_LIMIT",
- "ENTRY_TYPES",
- "FIXED_SOURCES",
- "KINDS",
- "KIND_CREW",
- "KIND_FIXED_SOURCES",
- "KIND_SESSION",
- "KIND_SOURCE_PREFIXES",
- "LEDGER_FILE",
- "MAX_ENTRY_BYTES",
- "MAX_PAGE_LIMIT",
- "MAX_REF_SPAN",
- "SCHEMA_VERSION",
- "SESSION_ENTRY_TYPES",
- "STATUS_CORRUPT",
- "STATUS_GONE",
- "STATUS_OK",
- "STATUS_PRUNED",
- "TYPE_OWNERSHIP",
- "CrewHeader",
- "Entry",
- "EntryType",
- "Field",
- "Header",
- "Ledger",
- "IndeterminateAppend",
- "LedgerError",
- "Page",
- "Ref",
- "Resolution",
- "SessionHeader",
- "SessionThread",
- "declaration_for",
- "ledger_dir",
- "ledger_path",
- "render_markdown",
- "segment_first_seqs",
- "segment_paths",
- "ledger_root",
- "now_ms",
- "validate_data",
-]
diff --git a/src/kiro_crew/sandbox.py b/src/kiro_crew/sandbox.py
index a07ec813b7c1..68488ee08652 100644
--- a/src/kiro_crew/sandbox.py
+++ b/src/kiro_crew/sandbox.py
@@ -335,16 +335,23 @@ def _overflow_uid() -> int | None:
# The conductor work ledger: a worker's full file toolset must not reach any
# conductor's records except through the routes that check its binding.
"work-ledger",
- # Every append-only per-unit ledger, crew and session alike (ledger/store.py).
- # The design treats the ledger as the authority a conductor reads instead of
+ # Every append-only per-unit crew log, crew and session alike (crew_log/store.py).
+ # The design treats the crew log as the authority a conductor reads instead of
# re-deriving, so an in-sandbox process able to write here could forge an
# entry attributed to the gateway or rewrite the history it is reporting
# into. The library's write rules bind only callers who go through it, and the
# file-tool fence answers only the agent's own tools -- neither answers a
# sandboxed subprocess calling ``open()``, which is what this entry is for.
# Nothing in-sandbox reads one: the store runs in the GATEWAY process, so
- # HIDDEN rather than READONLY. Named at the shared ``ledgers`` root, so a
+ # HIDDEN rather than READONLY. Named at the shared ``crew-log`` root, so a
# future unit kind is covered without a new entry.
+ "crew-log",
+ # The RETIRED root, for the reason its file-tool fence is kept: this rename
+ # ships no migration, so entries an older build wrote under ``/ledgers``
+ # are still on disk and would lose their OS mask on upgrade. Deliberately NOT in
+ # ``_CREW_PRECREATE_HIDDEN_DIR_LEAVES``: that set exists for a root the store
+ # creates LAZILY, and nothing creates this one any more, so there is no writer to
+ # race. Precreating it would re-materialise the retired name on every machine.
"ledgers",
"cron-history",
# The cron in-flight markers, masked rather than sealed read-only because
@@ -1017,7 +1024,7 @@ def carveout_shadowed_by_foreign_mask(path: str, mode: str = "standard") -> bool
# Private memory has the same late-creation hazard: an agent spawned before
# the first member must never gain access when that member's database appears.
"memory_stores",
- # Append-only per-unit ledgers, and the hazard is the sharpest here: the
+ # Append-only per-unit crew logs, and the hazard is the sharpest here: the
# record is the AUTHORITY a reader trusts instead of re-deriving, and the
# store creates this root on its first write. A sandbox spawned before that
# write finds the name absent, the ``SENSITIVE_DIRS`` loop skips what does not
@@ -1026,7 +1033,7 @@ def carveout_shadowed_by_foreign_mask(path: str, mode: str = "standard") -> bool
# read as the gateway's. Materialising it empty at 0700 gives the bind a name
# to cover before anything can write one. macOS needs no entry here: a
# Seatbelt deny is a path rule that holds for a name that does not exist yet.
- "ledgers",
+ "crew-log",
# The chat_tag grants store writes by atomic rename of a sibling temp, so
# the whole directory must exist before the isdir-guarded mask loop runs —
# otherwise the first sandbox spawned before the first grant write sees an
diff --git a/src/kiro_crew/security/paths.py b/src/kiro_crew/security/paths.py
index 4684987d1501..e5ea41d89336 100644
--- a/src/kiro_crew/security/paths.py
+++ b/src/kiro_crew/security/paths.py
@@ -348,8 +348,8 @@ def _leaf_segments(spec: str) -> list[str]:
# straight off disk, and a corrupted record reads as ABSENT to the store —
# silent loss the conductor cannot see. No legitimate file-tool reader.
"work-ledger",
- # Every append-only per-unit ledger, crew and session alike (ledger/store.py).
- # Not credentials, but the design's whole premise is that the ledger is the
+ # Every append-only per-unit crew log, crew and session alike (crew_log/store.py).
+ # Not credentials, but the design's whole premise is that the crew log is the
# AUTHORITY and the context window only a cache: a conductor reads a unit's
# history as fact instead of re-deriving it. An agent's auto-approved file
# tools reaching this subtree would let it forge an entry attributed to the
@@ -359,10 +359,17 @@ def _leaf_segments(spec: str) -> list[str]:
# library, so they bind only callers who go through it; this entry is what
# keeps a file tool from going around it, and the sandbox mask on the same
# leaf is what keeps a spawned subprocess from going around BOTH. Named at the
- # shared ``ledgers`` root so every unit kind is fenced by one entry — session
- # ledgers included, which is why they do not live under the ``sessions``
+ # shared ``crew-log`` root so every unit kind is fenced by one entry — session
+ # crew logs included, which is why they do not live under the ``sessions``
# transcript root. The store opens these paths directly rather than through
# this gate, so nothing breaks.
+ "crew-log",
+ # The RETIRED root the same store used before it was renamed. Kept because this
+ # rename ships no migration: a machine that ran the old build with the feature
+ # flag on still has real entries under ``/ledgers``, and dropping the leaf
+ # would un-fence them from the agent's file tools on upgrade. Nothing writes here
+ # any more, so the entry costs a retired name and refuses nothing legitimate --
+ # the same reasoning the retired browser leaves above are kept under.
"ledgers",
# The optional Playwright extension token. It removes the browser-side approval
# click for an attach, so a process that could read it could attach to the
diff --git a/src/kiro_crew/security_posture.py b/src/kiro_crew/security_posture.py
index bd3839de0f93..0d51dbd88b2a 100644
--- a/src/kiro_crew/security_posture.py
+++ b/src/kiro_crew/security_posture.py
@@ -113,10 +113,10 @@ class PostureControl:
"source-content digests remain server-side.",
),
(
- "Session ledger entries",
- "session_ledger_emit.py",
- "Message bodies written to the append-only per-session ledger under "
- "`/ledgers/sessions/` -- what the user typed and what the model "
+ "Crew log entries",
+ "crew_log/emit.py",
+ "Message bodies written to the append-only per-session crew log under "
+ "`/crew-log/sessions/` -- what the user typed and what the model "
"answered. This sink is a FILE rather than "
"a response, so what it writes outlives the process and is read back "
"later by folds and the session panel; that makes it an output boundary "
diff --git a/src/kiro_crew/session_compaction.py b/src/kiro_crew/session_compaction.py
index b9b2cf61c847..d5abf7bc72bd 100644
--- a/src/kiro_crew/session_compaction.py
+++ b/src/kiro_crew/session_compaction.py
@@ -270,11 +270,11 @@ def _compaction_gate_decision(self, key: str, provider: LLMProvider, pct: float)
baseline = self.state.pending_verdict.get(key)
if baseline is not None and not self._deps.context_pct_is_unknown(provider):
del self.state.pending_verdict[key]
- # Append-only session ledger (flag-gated, fail-soft). The OTHER half
+ # Append-only the session's log (flag-gated, fail-soft). The OTHER half
# of the emit in ``_settle_compact_cooldown``: a compaction whose
# effect was not measurable at the time deferred its verdict to here,
# and without this line that compaction would never appear in the
- # ledger at all. ``pct`` is the first CONFIRMED reading after it, so
+ # crew log at all. ``pct`` is the first CONFIRMED reading after it, so
# it is the honest ``pct_after`` even when it is higher than
# ``baseline`` -- a deferred reading includes a later turn's growth,
# which makes ``freed_pct`` negative rather than absent. Recording
@@ -284,10 +284,10 @@ def _compaction_gate_decision(self, key: str, provider: LLMProvider, pct: float)
# Deferred, not module-scope: this module is reached from the gateway
# boot path, and AUTOSDE's no-new-work-on-gateway-boot-path rule asks
# for a flag-gated subsystem's IMPORT to be gated, not just its use.
- from kiro_crew import session_ledger_emit
+ from kiro_crew.crew_log import emit as crew_log_emit
- session_ledger_emit.on_compaction_applied(
- session_ledger_emit.session_id_of(provider),
+ crew_log_emit.on_compaction_applied(
+ crew_log_emit.session_id_of(provider),
pct_before=baseline,
pct_after=pct,
)
@@ -556,15 +556,15 @@ def _settle_compact_cooldown(self, key: str, provider: LLMProvider, pct_before:
)
return False
self.state.pending_verdict.pop(key, None)
- # Append-only session ledger (flag-gated, fail-soft). This is the
+ # Append-only the session's log (flag-gated, fail-soft). This is the
# immediately-confirmed half; a deferred verdict is recorded by
# ``_compaction_gate_decision`` when its reading settles, so every
- # compaction reaches the ledger on exactly one of the two paths.
+ # compaction reaches the crew log on exactly one of the two paths.
# Deferred for the boot-path rule; see the note at the other call site.
- from kiro_crew import session_ledger_emit
+ from kiro_crew.crew_log import emit as crew_log_emit
- session_ledger_emit.on_compaction_applied(
- session_ledger_emit.session_id_of(provider),
+ crew_log_emit.on_compaction_applied(
+ crew_log_emit.session_id_of(provider),
pct_before=pct_before,
pct_after=pct_after,
)
diff --git a/src/kiro_crew/session_lifecycle.py b/src/kiro_crew/session_lifecycle.py
index 42014fee45c1..79268f01ed9d 100644
--- a/src/kiro_crew/session_lifecycle.py
+++ b/src/kiro_crew/session_lifecycle.py
@@ -492,8 +492,8 @@ async def reset(
# this session's. The pop and the sample happen before this call's
# own suspension point, so that ordering still holds; only the
# crumb unlink is deferred to a worker.
- # Append-only session ledger (flag-gated, fail-soft). Reset is
- # the teardown that ends a ledger's life, since the successor
+ # Append-only the session's log (flag-gated, fail-soft). Reset is
+ # the teardown that ends a crew log's life, since the successor
# cold-starts a new ACP session id. Written BEFORE the await
# below: the emitter hands the entry to its own thread and
# returns, so this adds no suspension point, while writing it
@@ -504,10 +504,10 @@ async def reset(
# Deferred, not module-scope: this module is reached from the gateway
# boot path, and AUTOSDE's no-new-work-on-gateway-boot-path rule asks
# for a flag-gated subsystem's IMPORT to be gated, not just its use.
- from kiro_crew import session_ledger_emit
+ from kiro_crew.crew_log import emit as crew_log_emit
- session_ledger_emit.on_session_closed(
- session_ledger_emit.session_id_of(session.provider),
+ crew_log_emit.on_session_closed(
+ crew_log_emit.session_id_of(session.provider),
END_REASON_RESET,
)
await record_session_ended(key, end_reason=END_REASON_RESET)
@@ -873,7 +873,7 @@ async def destroy(
reason=constants.unbind_reason_session_destroyed,
)
if session is not None:
- # Append-only session ledger (flag-gated, fail-soft). Destroy is a
+ # Append-only the session's log (flag-gated, fail-soft). Destroy is a
# teardown and has to record itself, for the same reason the reset
# route above does -- and for one more: without this entry the
# unit is never collected by EITHER half of retention. The emitter
@@ -908,7 +908,7 @@ async def destroy(
# the teardown that already happened. Entries from turns that were
# in flight still follow it by design -- see `on_session_closed`.
#
- # It cannot start a ledger for a session that has none: `_handle`
+ # It cannot start a crew log for a session that has none: `_handle`
# never creates one, so a close for an unopened session writes
# nothing rather than leaving a header behind for a conversation
# that is being destroyed.
@@ -916,9 +916,9 @@ async def destroy(
# Deferred, not module-scope: this module is reached from the
# gateway boot path, and AUTOSDE's no-new-work-on-gateway-boot-path
# rule asks for a flag-gated subsystem's IMPORT to be gated too.
- from kiro_crew import session_ledger_emit
+ from kiro_crew.crew_log import emit as crew_log_emit
- ledger_sid = session_ledger_emit.session_id_of(session.provider)
+ ledger_sid = crew_log_emit.session_id_of(session.provider)
retained_key: str | None = None
if ledger_sid:
try:
@@ -929,11 +929,11 @@ async def destroy(
if retained_key is not None:
self._deps.logger.info(
"Session destroy: %s still maps to session id of %s; recording a "
- "non-terminal teardown so its ledger is retained",
+ "non-terminal teardown so its crew log is retained",
retained_key,
key,
)
- session_ledger_emit.on_session_closed(
+ crew_log_emit.on_session_closed(
ledger_sid,
END_REASON_DESTROYED if retained_key is None else _END_REASON_SID_RETAINED,
)
diff --git a/src/kiro_crew/slack/gateway.py b/src/kiro_crew/slack/gateway.py
index 565bf058bab6..8a6f71c6e27d 100644
--- a/src/kiro_crew/slack/gateway.py
+++ b/src/kiro_crew/slack/gateway.py
@@ -4004,7 +4004,7 @@ async def _deliver_script_result(
wrapped,
_directive_user_origin=False,
# Structural provenance for the session
- # ledger: the queued twin above carries
+ # crew log: the queued twin above carries
# CRON_NOTIFICATION_KIND, and this branch is
# the same injector dispatching directly.
_turn_actor="cron",
@@ -9023,7 +9023,7 @@ def _note_consumed(consumed: bool = True) -> None:
announce,
_directive_user_origin=False,
# Structural provenance for the session
- # ledger: the queued twin above carries
+ # crew log: the queued twin above carries
# SUBAGENT_COMPLETION_KIND, and this branch
# is the same injector dispatching directly.
_turn_actor="subagent",
@@ -13217,7 +13217,7 @@ async def _shutdown_and_exit(self, watchdog: asyncio.Future | None = None) -> No
# session by this point, so the sweep is not racing a mapping publisher --
# the same position the sweep already held here before this change.
await asyncio.to_thread(cleanup_orphaned_sessions)
- # The session ledger's buffered appends, for EVERY gateway mode. The
+ # The session's log's buffered appends, for EVERY gateway mode. The
# dashboard registers its own cleanup hook, but a mode that builds no
# dashboard app -- slack-only is the plain case -- never runs one, and
# os._exit below skips atexit, so without this the buffer dies with the
@@ -13229,12 +13229,12 @@ async def _shutdown_and_exit(self, watchdog: asyncio.Future | None = None) -> No
# Imported HERE, not at module scope: AUTOSDE's
# no-new-work-on-gateway-boot-path rule asks for an optional subsystem's
# import to be gated, and a shutdown drain is the only use in this module.
- from kiro_crew import session_ledger_emit
+ from kiro_crew.crew_log import emit as crew_log_emit
- if not await asyncio.to_thread(session_ledger_emit.drain_for_shutdown):
- logger.warning("session ledger did not fully drain before exit")
+ if not await asyncio.to_thread(crew_log_emit.drain_for_shutdown):
+ logger.warning("the session's log did not fully drain before exit")
except Exception: # noqa: BLE001 - shutdown must not raise
- logger.debug("session ledger drain failed during shutdown", exc_info=True)
+ logger.debug("the session's log drain failed during shutdown", exc_info=True)
# This is a hard exit too: os._exit skips atexit, so the log queue's
# drain hook never runs here either. Without this the whole shutdown
# tail is lost -- including the "Graceful shutdown timed out" warning
diff --git a/test/acp_frame_replay_harness.py b/test/acp_frame_replay_harness.py
index ef431d75af90..0c9d335f98b3 100644
--- a/test/acp_frame_replay_harness.py
+++ b/test/acp_frame_replay_harness.py
@@ -224,7 +224,7 @@ def replay_frames(
reads its permission frames the way the live session did. Absent, as on every
other harness, no frame is read as an envelope.
- The session-ledger flag is forced ON for the replay. The parsers measure a
+ The crew log flag is forced ON for the replay. The parsers measure a
tool result's full byte count and digest only while that flag is set, since
the emitter is its only consumer -- so replaying with it off would record a
shorter event than any session with the feature enabled produces, and the
@@ -234,15 +234,15 @@ def replay_frames(
restored afterwards: this process runs other tests, and leaving the feature on
for them would change what they exercise.
"""
- prior = os.environ.get("KIROCREW_SESSION_LEDGER")
- os.environ["KIROCREW_SESSION_LEDGER"] = "1"
+ prior = os.environ.get("KIROCREW_CREW_LOG")
+ os.environ["KIROCREW_CREW_LOG"] = "1"
try:
return _replay(frames, gate_envelope_nonce=gate_envelope_nonce)
finally:
if prior is None:
- os.environ.pop("KIROCREW_SESSION_LEDGER", None)
+ os.environ.pop("KIROCREW_CREW_LOG", None)
else:
- os.environ["KIROCREW_SESSION_LEDGER"] = prior
+ os.environ["KIROCREW_CREW_LOG"] = prior
def _replay(
diff --git a/test/ledger_type_helpers.py b/test/crew_log_type_helpers.py
similarity index 88%
rename from test/ledger_type_helpers.py
rename to test/crew_log_type_helpers.py
index c9fac8b07d3a..0f625d8b3f02 100644
--- a/test/ledger_type_helpers.py
+++ b/test/crew_log_type_helpers.py
@@ -1,8 +1,8 @@
-"""Smallest-valid-payload vehicles for the session-ledger entry types.
+"""Smallest-valid-payload vehicles for the session-log entry types.
A test that asserts on segments, ownership or the append path needs a well-formed
entry of some type without caring what it says. Building that payload from the
-declarations in :mod:`kiro_crew.ledger.entry_types` rather than writing it out
+declarations in :mod:`kiro_crew.crew_log.entry_types` rather than writing it out
keeps a caller from holding a payload the format refuses.
This lives in the test suite, not beside the declarations, because every caller is
@@ -13,7 +13,7 @@
from typing import Any
-from kiro_crew.ledger.entry_types import (
+from kiro_crew.crew_log.entry_types import (
JSON_ARRAY,
JSON_BOOL,
JSON_FLOAT,
diff --git a/test/fixtures/ledger_crash_child.py b/test/fixtures/crew_log_crash_child.py
similarity index 92%
rename from test/fixtures/ledger_crash_child.py
rename to test/fixtures/crew_log_crash_child.py
index 62d3514ca21b..960b5e00acde 100644
--- a/test/fixtures/ledger_crash_child.py
+++ b/test/fixtures/crew_log_crash_child.py
@@ -1,4 +1,4 @@
-"""A child that writes a real ledger, parks at a named failpoint, and waits to die.
+"""A child that writes a real crew log, parks at a named failpoint, and waits to die.
Every other crash test in this suite hands the repair a file IT wrote by hand, so
what those prove is "given this file state, the repair does X" -- never "a real
@@ -12,7 +12,7 @@
mid-setup, which is a race that reads as a flaky test rather than as the bug it
would hide.
-Usage: ledger_crash_child.py
+Usage: crew_log_crash_child.py
Failpoints:
open-turn a turn is started and left open -- what a crash mid-turn leaves
@@ -26,9 +26,8 @@
import time
from pathlib import Path
-from kiro_crew import ledger as lg
-from kiro_crew import session_ledger_emit as emit
-from kiro_crew.ledger import Ledger
+from kiro_crew import crew_log as lg
+from kiro_crew.crew_log import Ledger, emit
SESSION = "crash-child-session"
diff --git a/test/fixtures/ledger_lease_child.py b/test/fixtures/crew_log_lease_child.py
similarity index 90%
rename from test/fixtures/ledger_lease_child.py
rename to test/fixtures/crew_log_lease_child.py
index 63d41bf112e6..76ed57091dc0 100644
--- a/test/fixtures/ledger_lease_child.py
+++ b/test/fixtures/crew_log_lease_child.py
@@ -1,4 +1,4 @@
-"""A child that owns a session ledger's writes and parks with a turn still open.
+"""A child that owns a session log's writes and parks with a turn still open.
The cross-process half of write ownership cannot be asserted inside one process:
an advisory lock belongs to an open file description, so a second descriptor here
@@ -11,15 +11,15 @@
tells it to exit. Nothing sleeps, and the parent's read of the announcement is
what orders the two processes.
-Usage: ledger_lease_child.py
+Usage: crew_log_lease_child.py
"""
from __future__ import annotations
import sys
-from kiro_crew import ledger as lg
-from kiro_crew.ledger import Ledger
+from kiro_crew import crew_log as lg
+from kiro_crew.crew_log import Ledger
#: Written to stdout once the turn is open and this process owns the log.
OWNED = "owned"
diff --git a/test/test_acp_client.py b/test/test_acp_client.py
index c89bbd3441d5..1f5d1cc04777 100644
--- a/test/test_acp_client.py
+++ b/test/test_acp_client.py
@@ -7314,7 +7314,7 @@ def test_credential_straddling_the_bound_is_still_redacted(self):
assert len(event.tool_output) <= 8000
def test_long_output_metadata_covers_full_redacted_text(self, monkeypatch):
- monkeypatch.setenv("KIROCREW_SESSION_LEDGER", "1")
+ monkeypatch.setenv("KIROCREW_CREW_LOG", "1")
output = "A" * 8000 + "é-tail"
full_redacted = acp_client.redact_text(output)
full_bytes = full_redacted.encode("utf-8", "replace")
@@ -7348,7 +7348,7 @@ def test_no_output_metadata_is_measured_while_the_ledger_is_off(self, monkeypatc
while nothing will read it is work the default path must not do. ``-1``
distinguishes "not recorded" from a real zero-length output.
"""
- monkeypatch.delenv("KIROCREW_SESSION_LEDGER", raising=False)
+ monkeypatch.delenv("KIROCREW_CREW_LOG", raising=False)
client = self._client()
msg = self._make_msg(
{
diff --git a/test/test_config_paths.py b/test/test_config_paths.py
index 8abe7ee8eadd..26aebab11996 100644
--- a/test/test_config_paths.py
+++ b/test/test_config_paths.py
@@ -77,7 +77,7 @@ def test_link_is_refused_without_touching_its_target(
home.mkdir()
target = tmp_path / "outside"
target.mkdir()
- make_dir_link(home / "ledgers", target)
+ make_dir_link(home / "crew-log", target)
restricted: list[Path] = []
with caplog.at_level(logging.WARNING, logger=paths.__name__):
@@ -85,7 +85,7 @@ def test_link_is_refused_without_touching_its_target(
assert restricted == [], "the owner-only callback would chmod the link target"
assert list(target.iterdir()) == [], "the linked target was modified"
- assert any("Refusing ledger root" in record.message for record in caplog.records)
+ assert any("Refusing crew log root" in record.message for record in caplog.records)
class TestConfigPackageDir:
diff --git a/test/test_ledger_core.py b/test/test_crew_log_core.py
similarity index 96%
rename from test/test_ledger_core.py
rename to test/test_crew_log_core.py
index e707b87d6c37..6a471a2dea37 100644
--- a/test/test_ledger_core.py
+++ b/test/test_crew_log_core.py
@@ -1,4 +1,4 @@
-"""Append-only ledger core -- one test per rule the format promises.
+"""Append-only crew log core -- one test per rule the format promises.
Grouped the way the module is reasoned about: identity and lifecycle, the seq
contract, the two namespace rules, the caps, the read shapes (fold, page,
@@ -17,13 +17,13 @@
import threading
import pytest
-from ledger_type_helpers import minimal_data
+from crew_log_type_helpers import minimal_data
-from kiro_crew import ledger as lg
+from kiro_crew import crew_log as lg
from kiro_crew import sandbox
from kiro_crew.config import paths
from kiro_crew.config.paths import data_home, ensure_data_home
-from kiro_crew.ledger import Ledger, LedgerError, Ref, store
+from kiro_crew.crew_log import Ledger, LedgerError, Ref, store
from kiro_crew.security.paths import is_sensitive_path
from kiro_crew.session_ledger import _store_name
@@ -66,8 +66,8 @@ def _ledger_bytes(kind: str = lg.KIND_SESSION, unit_id: str = SESSION) -> bytes:
def test_each_kind_lands_in_its_own_root_one_directory_deep():
crew, session = _crew(), _session()
- assert crew.path == lg.ledger_root("crew") / _store_name(CREW) / "ledger.jsonl"
- assert session.path == lg.ledger_root("session") / _store_name(SESSION) / "ledger.jsonl"
+ assert crew.path == lg.ledger_root("crew") / _store_name(CREW) / "log.jsonl"
+ assert session.path == lg.ledger_root("session") / _store_name(SESSION) / "log.jsonl"
assert crew.path.parent.parent == lg.ledger_root("crew")
@@ -97,9 +97,9 @@ def test_the_raw_id_is_recoverable_from_the_header_not_the_directory_name():
assert Ledger.open(lg.KIND_CREW, "qa-team").header.id == "qa-team"
-def test_a_session_ledger_is_invisible_to_a_flat_transcript_glob():
+def test_a_session_log_is_invisible_to_a_flat_transcript_glob():
# The session root is shared with the existing flat ``.jsonl``
- # transcripts, whose readers glob one level deep. A ledger nested a
+ # transcripts, whose readers glob one level deep. A crew log nested a
# directory down must not appear to them, or the two stores shadow.
session = _session()
assert session.path.is_file()
@@ -430,7 +430,7 @@ def test_the_ownership_registry_is_the_documented_partition():
#: The session log's complete vocabulary. Spelled out in full rather than derived
#: from the ownership registry, so a domain that quietly loses an action is caught --
#: the registry is prefix-based and would not notice. The shapes are pre-release
-#: while ``KIROCREW_SESSION_LEDGER`` defaults off, so a type may be added, removed or
+#: while ``KIROCREW_CREW_LOG`` defaults off, so a type may be added, removed or
#: reshaped; this tuple is what makes such a change deliberate rather than silent.
SESSION_VOCABULARY: tuple[str, ...] = (
"session/opened",
@@ -563,7 +563,7 @@ def test_an_unrecognized_src_is_refused(bad):
# --- rule 2: authorization on src -----------------------------------------
#
-# The full per-kind matrix lives in test_ledger_kinds.py; these pin the codes.
+# The full per-kind matrix lives in test_crew_log_kinds.py; these pin the codes.
def test_a_crew_guest_writes_the_crew_kinds_own_domains():
@@ -582,7 +582,7 @@ def test_an_app_guest_writes_only_its_own_type_namespace():
assert exc.value.field == "src"
-def test_a_session_ledger_refuses_the_app_type_namespace_outright():
+def test_a_session_log_refuses_the_app_type_namespace_outright():
session = _session()
with _raises(lg.CODE_NAMESPACE_VIOLATION) as exc:
session.append("app:radar/scan", {}, src="gateway")
@@ -879,7 +879,7 @@ def test_a_span_below_the_oldest_surviving_segment_is_pruned():
for index in range(4):
crew.append("activity/tick", {"i": index}, src="gateway")
head = crew.path
- later = head.parent / "ledger.3.jsonl"
+ later = head.parent / "log.3.jsonl"
lines = head.read_text(encoding="utf-8").splitlines(keepends=True)
later.write_text(lines[0] + "".join(lines[3:]), encoding="utf-8")
head.unlink()
@@ -895,7 +895,7 @@ def test_damage_in_the_surviving_part_of_a_pruned_citation_is_corrupt():
for index in range(4):
crew.append("activity/tick", {"i": index}, src="gateway")
head = crew.path
- later = head.parent / "ledger.3.jsonl"
+ later = head.parent / "log.3.jsonl"
lines = head.read_text(encoding="utf-8").splitlines(keepends=True)
later.write_text(lines[0] + "{ damaged surviving entry\n" + lines[4], encoding="utf-8")
head.unlink()
@@ -1379,7 +1379,7 @@ def test_a_ledger_of_one_kind_cannot_be_opened_as_the_other():
_crew()
target = lg.ledger_dir(lg.KIND_SESSION, CREW)
target.mkdir(parents=True, exist_ok=True)
- (target / lg.LEDGER_FILE).write_bytes(lg.ledger_path(lg.KIND_CREW, CREW).read_bytes())
+ (target / lg.LOG_FILE).write_bytes(lg.ledger_path(lg.KIND_CREW, CREW).read_bytes())
with _raises(lg.CODE_BAD_HEADER) as exc:
Ledger.open(lg.KIND_SESSION, CREW)
assert _code(exc) == lg.CODE_BAD_HEADER
@@ -1418,7 +1418,7 @@ def test_seq_falls_back_to_a_full_scan_when_the_window_holds_nothing_valid():
def _interrupted_session() -> Ledger:
- """A session ledger whose newest turn was cut off mid-tool-call."""
+ """A session log whose newest turn was cut off mid-tool-call."""
led = _session()
led.append("turn/started", {"turn": 1, "actor": "user", "depth": 0}, src="gateway")
led.append(
@@ -1443,7 +1443,7 @@ def _interrupted_session() -> Ledger:
def test_a_plain_open_never_touches_an_interrupted_tail():
# The bug this split exists to prevent. A live writer reconnects to its own
- # ledger for reasons that say nothing about its health -- a handle dropped from
+ # log for reasons that say nothing about its health -- a handle dropped from
# a bounded cache is enough -- so an open that repaired would close a turn that
# is still running and then let it keep writing past its own completion.
_interrupted_session()
@@ -1492,7 +1492,7 @@ def test_repair_refuses_to_close_past_a_damaged_real_completion(caplog):
path.write_bytes(b"".join(lines))
before = path.read_bytes()
- with caplog.at_level(logging.WARNING, logger="kiro_crew.ledger.store"):
+ with caplog.at_level(logging.WARNING, logger="kiro_crew.crew_log.store"):
Ledger.open(lg.KIND_SESSION, SESSION, repair=True)
assert (
@@ -1539,12 +1539,12 @@ def test_closing_is_deterministic_and_a_balanced_tail_is_left_alone():
assert list(again.iter_from(1))[-1].data["stop_reason"] == "interrupted"
-def test_only_a_session_ledger_is_closed_this_way():
+def test_only_a_session_log_is_closed_this_way():
# The closers encode the SESSION turn lifecycle, so the repair is gated on
- # kind rather than on what the tail happens to look like: a crew ledger's
+ # kind rather than on what the tail happens to look like: a crew log's
# types are its own, and its reader must not find turn entries it never wrote.
# Asserted on the gate directly, because the ownership rule refuses to let a
- # crew ledger hold a `turn/started` in the first place.
+ # crew log hold a `turn/started` in the first place.
_interrupted_session()
path = lg.ledger_path(lg.KIND_SESSION, SESSION)
before = _ledger_bytes()
@@ -1596,8 +1596,8 @@ def test_the_root_is_established_owner_only_before_any_ledger_exists(monkeypatch
monkeypatch.setenv("KIROCREW_HOME", str(home))
paths._config_dir_memo = None
ensure_data_home()
- root = home / "ledgers"
- assert root.is_dir(), "no ledger has been written, yet the root exists"
+ root = home / "crew-log"
+ assert root.is_dir(), "no crew log has been written, yet the root exists"
if os.name == "posix":
assert stat.S_IMODE(root.stat().st_mode) == 0o700
@@ -1609,24 +1609,24 @@ def test_an_existing_root_with_a_loose_mode_is_tightened(monkeypatch, tmp_path):
if os.name != "posix":
pytest.skip("POSIX mode semantics")
home = tmp_path / "restored-home"
- (home / "ledgers").mkdir(parents=True)
+ (home / "crew-log").mkdir(parents=True)
# Deliberately group- and world-readable: that is the state a restored backup
# or an older build leaves behind, and the point is that startup re-asserts
# owner-only over it rather than accepting what it found.
- (home / "ledgers").chmod(
+ (home / "crew-log").chmod(
stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH
)
monkeypatch.setenv("KIROCREW_HOME", str(home))
paths._config_dir_memo = None
ensure_data_home()
- assert stat.S_IMODE((home / "ledgers").stat().st_mode) == 0o700
+ assert stat.S_IMODE((home / "crew-log").stat().st_mode) == 0o700
# --- sandbox disposition --------------------------------------------------
def test_every_ledger_is_refused_to_the_agents_own_file_tools():
- # The ledger is the AUTHORITY a conductor reads instead of re-deriving, so an
+ # The crew log is the AUTHORITY a conductor reads instead of re-deriving, so an
# agent able to write here could forge an entry attributed to the gateway or
# rewrite the history it is reporting into. The write-side rules bind callers
# who go through the library; this floor is what stops a file tool going
@@ -1644,18 +1644,18 @@ def test_every_ledger_is_masked_from_every_sandboxed_process():
# One entry at the shared root covers every kind: the file-tool floor above
# answers the agent's own tools, and this answers a spawned subprocess that
# calls open() directly -- which no tool gate sees.
- assert "ledgers" in sandbox._CREW_HIDDEN_LEAVES
+ assert "crew-log" in sandbox._CREW_HIDDEN_LEAVES
-def test_a_session_ledger_lives_under_the_masked_leaf_not_the_transcript_root():
- # Why the session half needs its own root. Under `sessions/` a ledger has
+def test_a_session_log_lives_under_the_masked_leaf_not_the_transcript_root():
+ # Why the session half needs its own root. Under `sessions/` a log has
# NEITHER fence: that root is the flat transcript store and carries no mask
# entry, so a sandboxed subprocess can forge a session's history whatever the
# tool gate says. Asserted on the real created path rather than a root's
# name -- a name check passes just as happily one directory above the masked
# leaf.
path = _session().path
- assert (data_home() / "ledgers") in path.parents
+ assert (data_home() / "crew-log") in path.parents
assert (data_home() / "sessions") not in path.parents
@@ -1663,7 +1663,7 @@ def test_a_session_ledger_lives_under_the_masked_leaf_not_the_transcript_root():
def _split_into_segments(kind: str, unit_id: str, at_seq: int) -> None:
- """Move every entry from *at_seq* onward into ``ledger..jsonl``.
+ """Move every entry from *at_seq* onward into ``log..jsonl``.
Stands in for a writer that rotates, which nothing does yet: the reader side
is what this commit freezes, so the fixture produces the on-disk shape a
@@ -1676,7 +1676,7 @@ def _split_into_segments(kind: str, unit_id: str, at_seq: int) -> None:
for raw in entries:
(moved if json.loads(raw)["seq"] >= at_seq else kept).append(raw)
head.write_bytes(header + b"".join(kept))
- (head.parent / f"ledger.{at_seq}.jsonl").write_bytes(header + b"".join(moved))
+ (head.parent / f"log.{at_seq}.jsonl").write_bytes(header + b"".join(moved))
def test_segments_are_found_and_ordered_by_their_first_seq(tmp_path):
@@ -1687,9 +1687,8 @@ def test_segments_are_found_and_ordered_by_their_first_seq(tmp_path):
_split_into_segments(lg.KIND_SESSION, "seg-order", 5)
names = [p.name for p in lg.segment_paths(lg.KIND_SESSION, "seg-order")]
- assert names == ["ledger.jsonl", "ledger.5.jsonl", "ledger.9.jsonl"], (
- "segments must order by first seq, not by name -- ledger.9 sorts before "
- "ledger.5 as a string"
+ assert names == ["log.jsonl", "log.5.jsonl", "log.9.jsonl"], (
+ "segments must order by first seq, not by name -- log.9 sorts before " "log.5 as a string"
)
@@ -1707,11 +1706,11 @@ def test_a_valid_multi_segment_layout_reads_end_to_end(tmp_path):
def test_a_linked_kind_root_is_refused_and_named(tmp_path):
- """A symlinked ``ledgers/`` must not become the containment root.
+ """A symlinked ``crew-log/`` must not become the containment root.
Containment resolves its base first and then checks only that the child stays
under the resolved base -- so with the kind directory itself a link, the
- link's TARGET becomes the root and every ledger path under it passes while
+ link's TARGET becomes the root and every log path under it passes while
living outside the tree whose protections the data home establishes.
"""
elsewhere = tmp_path / "writable-elsewhere"
@@ -1739,8 +1738,8 @@ def test_a_linked_kind_root_is_refused_and_named(tmp_path):
def test_a_kind_root_resolving_outside_the_data_home_is_refused(tmp_path):
"""Not only a link ON the kind directory: a linked ANCESTOR is the same escape.
- The check resolves both sides, so a ``ledgers`` directory that is itself a
- link is caught even though ``ledgers/sessions`` under it is a real directory.
+ The check resolves both sides, so a ``crew-log`` directory that is itself a
+ link is caught even though ``crew-log/sessions`` under it is a real directory.
"""
outside = tmp_path / "outside-tree"
(outside / "sessions").mkdir(parents=True)
@@ -1773,8 +1772,8 @@ def test_a_foreign_segment_is_refused_and_named(tmp_path):
for n in range(1, 9):
foreign.append("turn/started", {"turn": n, "actor": "user", "depth": 0}, src="gateway")
_split_into_segments(lg.KIND_SESSION, "seg-foreign", 5)
- foreign_segment = lg.ledger_dir(lg.KIND_SESSION, "seg-foreign") / "ledger.5.jsonl"
- offending = lg.ledger_dir(lg.KIND_SESSION, "seg-target") / "ledger.5.jsonl"
+ foreign_segment = lg.ledger_dir(lg.KIND_SESSION, "seg-foreign") / "log.5.jsonl"
+ offending = lg.ledger_dir(lg.KIND_SESSION, "seg-target") / "log.5.jsonl"
offending.write_bytes(foreign_segment.read_bytes())
reader = lg.Ledger.open(lg.KIND_SESSION, "seg-target")
@@ -1790,8 +1789,8 @@ def test_a_renamed_segment_is_refused_and_named(tmp_path):
led.append("turn/started", {"turn": n, "actor": "user", "depth": 0}, src="gateway")
_split_into_segments(lg.KIND_SESSION, "seg-renamed", 5)
directory = lg.ledger_dir(lg.KIND_SESSION, "seg-renamed")
- offending = directory / "ledger.6.jsonl"
- (directory / "ledger.5.jsonl").rename(offending)
+ offending = directory / "log.6.jsonl"
+ (directory / "log.5.jsonl").rename(offending)
reader = lg.Ledger.open(lg.KIND_SESSION, "seg-renamed")
with _raises(lg.CODE_BAD_SEGMENT) as exc:
@@ -1828,7 +1827,7 @@ def test_a_gap_between_segments_is_refused_rather_than_read_across(tmp_path):
# high would leave the second segment empty.
_split_into_segments(lg.KIND_SESSION, "seg-gap", 9)
_split_into_segments(lg.KIND_SESSION, "seg-gap", 5)
- (lg.ledger_dir(lg.KIND_SESSION, "seg-gap") / "ledger.5.jsonl").unlink()
+ (lg.ledger_dir(lg.KIND_SESSION, "seg-gap") / "log.5.jsonl").unlink()
reader = lg.Ledger.open(lg.KIND_SESSION, "seg-gap")
with pytest.raises(LedgerError) as excinfo:
@@ -1837,14 +1836,14 @@ def test_a_gap_between_segments_is_refused_rather_than_read_across(tmp_path):
def test_a_neighbour_file_sharing_the_prefix_is_ignored_not_refused(tmp_path):
- # An editor backup or a stray copy must not make a readable ledger unreadable.
+ # An editor backup or a stray copy must not make a readable log unreadable.
led = _session("seg-neighbour")
for n in range(1, 5):
led.append("turn/started", {"turn": n, "actor": "user", "depth": 0}, src="gateway")
directory = lg.ledger_dir(lg.KIND_SESSION, "seg-neighbour")
- (directory / "ledger.backup.jsonl").write_text("not a segment\n")
+ (directory / "log.backup.jsonl").write_text("not a segment\n")
- assert [p.name for p in lg.segment_paths(lg.KIND_SESSION, "seg-neighbour")] == ["ledger.jsonl"]
+ assert [p.name for p in lg.segment_paths(lg.KIND_SESSION, "seg-neighbour")] == ["log.jsonl"]
reader = lg.Ledger.open(lg.KIND_SESSION, "seg-neighbour")
assert [e.seq for e in reader.iter_from(1)] == [1, 2, 3, 4]
@@ -1899,10 +1898,10 @@ def _count(directory):
def test_the_ledger_root_is_restricted_even_when_the_home_cannot_be(tmp_path, monkeypatch):
- # The two tightenings are independent claims. Skipping the ledger root when the
+ # The two tightenings are independent claims. Skipping the crew log root when the
# home's own chmod fails inverts the priority: that is the case where the root's
# mode is the ONLY boundary left, because an unreadable parent is not there to
- # do the work -- and every lazily created ledger directory below it would keep
+ # do the work -- and every lazily created crew log directory below it would keep
# the process umask.
from kiro_crew import platform_compat
@@ -1926,8 +1925,8 @@ def _refuse_the_home(directory):
assert got == home
assert refused == [home], "the test did not exercise the failing branch"
- root = home / "ledgers"
- assert root.is_dir(), "the ledger root was skipped because the home's chmod failed"
+ root = home / "crew-log"
+ assert root.is_dir(), "the crew log root was skipped because the home's chmod failed"
if os.name == "posix":
assert stat.S_IMODE(root.stat().st_mode) == 0o700
@@ -1941,12 +1940,12 @@ def test_a_lazily_created_ledger_directory_is_not_world_readable():
if os.name == "posix":
mode = stat.S_IMODE(ledger.path.parent.stat().st_mode)
- assert mode == 0o700, f"the ledger directory is {oct(mode)}, not owner-only"
+ assert mode == 0o700, f"the crew log directory is {oct(mode)}, not owner-only"
def test_a_ledger_that_exists_but_will_not_open_is_damage_not_absence():
- # `gone` means "there is no such ledger" and tells a reader to stop looking. A
- # ledger whose header is corrupt is right there and broken, so answering
+ # `gone` means "there is no such crew log" and tells a reader to stop looking. A
+ # crew log whose header is corrupt is right there and broken, so answering
# `gone` for it converts a recoverable alarm into silence.
src = _session()
victim = _session("other-session")
@@ -2051,7 +2050,7 @@ def test_repair_drops_a_chunk_group_whose_citing_entry_never_landed(caplog):
path = lg.ledger_path(lg.KIND_SESSION, SESSION)
assert "message/chunk" in path.read_text(encoding="utf-8")
- with caplog.at_level(logging.WARNING, logger="kiro_crew.ledger.store"):
+ with caplog.at_level(logging.WARNING, logger="kiro_crew.crew_log.store"):
Ledger.open(lg.KIND_SESSION, SESSION, repair=True)
body = path.read_text(encoding="utf-8")
@@ -2238,7 +2237,7 @@ def test_a_group_cites_the_seqs_it_was_actually_allocated():
``plan_group_seqs`` served) makes the citation name the intruder's seq and reddens
the equality below.
"""
- from kiro_crew.ledger import store as store_mod
+ from kiro_crew.crew_log import store as store_mod
session = _session()
session.append("turn/started", {"turn": 1, "actor": "user", "depth": 0}, src="acp")
@@ -2247,7 +2246,7 @@ def test_a_group_cites_the_seqs_it_was_actually_allocated():
fired: list[int] = []
def _intruding_lock(path):
- # Once, and only for this ledger's lock: a re-entrant fire would recurse
+ # Once, and only for this log's lock: a re-entrant fire would recurse
# through the intruder's own append.
if not fired:
fired.append(1)
@@ -2318,7 +2317,7 @@ def test_repair_leaves_the_file_alone_when_a_record_cannot_be_accounted_for(capl
)
before = path.read_bytes()
- with caplog.at_level(logging.WARNING, logger="kiro_crew.ledger.store"):
+ with caplog.at_level(logging.WARNING, logger="kiro_crew.crew_log.store"):
Ledger.open(lg.KIND_SESSION, SESSION, repair=True)
body = path.read_bytes()
diff --git a/test/test_ledger_edge_concurrency.py b/test/test_crew_log_edge_concurrency.py
similarity index 98%
rename from test/test_ledger_edge_concurrency.py
rename to test/test_crew_log_edge_concurrency.py
index 0d5214b469dd..fca76b55094d 100644
--- a/test/test_ledger_edge_concurrency.py
+++ b/test/test_crew_log_edge_concurrency.py
@@ -1,6 +1,6 @@
-"""Producer-side concurrency of the session ledger emitter.
+"""Producer-side concurrency of the session log emitter.
-The STORE layer's two-handle seq race is pinned in test_ledger_core.py. This
+The STORE layer's two-handle seq race is pinned in test_crew_log_core.py. This
file attacks the EMITTER layer above it: the _submit / _buffer / _drain_loop /
flush machinery that sits between a producer calling on_* and the Ledger.append
that lands a line on disk.
@@ -20,8 +20,7 @@
import pytest
-from kiro_crew import session_ledger_emit as emit
-from kiro_crew.ledger import Ledger, ledger_path
+from kiro_crew.crew_log import Ledger, emit, ledger_path
SESSION = "conc-edge-sess-0001"
@@ -45,7 +44,7 @@
def _isolated_home(tmp_path, monkeypatch):
"""Each test gets its own data home, zero-backoff, and a clean emitter."""
monkeypatch.setenv("KIROCREW_HOME", str(tmp_path / "home"))
- monkeypatch.setenv(emit.SESSION_LEDGER_ENV, "1")
+ monkeypatch.setenv(emit.CREW_LOG_ENV, "1")
monkeypatch.setattr(emit, "_retry_delay", lambda _attempts: 0.0)
emit.reset_caches()
yield
@@ -343,7 +342,7 @@ def _produce(sid: str) -> None:
for sid in sids:
entries = _entries(sid)
- # Header is entry 0 -- its type is the ledger kind, "session"
+ # Header is entry 0 -- its type is the crew log kind, "session"
assert entries[0]["type"] == "session", f"{sid}: first line is not a header"
# Every line parses as valid JSON (already guaranteed by _entries, but
# also check via the production reader)
diff --git a/test/test_ledger_edge_exhaustion.py b/test/test_crew_log_edge_exhaustion.py
similarity index 99%
rename from test/test_ledger_edge_exhaustion.py
rename to test/test_crew_log_edge_exhaustion.py
index e0b2682267f7..7707d26f9e1a 100644
--- a/test/test_ledger_edge_exhaustion.py
+++ b/test/test_crew_log_edge_exhaustion.py
@@ -1,4 +1,4 @@
-"""Resource-exhaustion edge cases for the session ledger emitter.
+"""Resource-exhaustion edge cases for the session log emitter.
ENOSPC, EIO, hung writes, sustained backpressure, oversize entries, and
shutdown-under-load. Every test synchronises on events and injected delays,
@@ -17,8 +17,8 @@
import pytest
-from kiro_crew import ledger as lg
-from kiro_crew import session_ledger_emit as emit
+from kiro_crew import crew_log as lg
+from kiro_crew.crew_log import emit
SESSION = "acp-exhaust-0001"
SESSION_B = "acp-exhaust-0002"
@@ -32,7 +32,7 @@ def _pending(job, what: str) -> emit._PendingJob:
@pytest.fixture(autouse=True)
def _isolated_home(tmp_path, monkeypatch):
monkeypatch.setenv("KIROCREW_HOME", str(tmp_path / "home"))
- monkeypatch.setenv(emit.SESSION_LEDGER_ENV, "1")
+ monkeypatch.setenv(emit.CREW_LOG_ENV, "1")
monkeypatch.setattr(emit, "_retry_delay", lambda _attempts: 0.0)
emit.reset_caches()
yield
diff --git a/test/test_ledger_edge_fanout.py b/test/test_crew_log_edge_fanout.py
similarity index 98%
rename from test/test_ledger_edge_fanout.py
rename to test/test_crew_log_edge_fanout.py
index 11b920e30efd..021f29cb76ae 100644
--- a/test/test_ledger_edge_fanout.py
+++ b/test/test_crew_log_edge_fanout.py
@@ -13,8 +13,7 @@
import pytest
-from kiro_crew import session_ledger_emit as emit
-from kiro_crew.ledger import Ledger, ledger_path
+from kiro_crew.crew_log import Ledger, emit, ledger_path
# ---------------------------------------------------------------------------
# Fixtures
@@ -29,7 +28,7 @@ def _pending(job, what: str) -> emit._PendingJob:
@pytest.fixture(autouse=True)
def _isolated_home(tmp_path, monkeypatch):
monkeypatch.setenv("KIROCREW_HOME", str(tmp_path / "home"))
- monkeypatch.setenv(emit.SESSION_LEDGER_ENV, "1")
+ monkeypatch.setenv(emit.CREW_LOG_ENV, "1")
monkeypatch.setattr(emit, "_retry_delay", lambda _attempts: 0.0)
emit.reset_caches()
yield
diff --git a/test/test_ledger_edge_reconnect.py b/test/test_crew_log_edge_reconnect.py
similarity index 98%
rename from test/test_ledger_edge_reconnect.py
rename to test/test_crew_log_edge_reconnect.py
index 9e6163d7bf12..4b93dd5245bb 100644
--- a/test/test_ledger_edge_reconnect.py
+++ b/test/test_crew_log_edge_reconnect.py
@@ -1,9 +1,9 @@
"""Edge-case tests: ACP disconnect, reconnect and resume racing a live writer.
-Covers the contract from ledger-core.md:
+Covers the contract from crew-log-core.md:
Repair is opt-in, and only a RESUME may ask for it. A live writer
- RECONNECTING to its own ledger must NOT have its open turn closed,
+ RECONNECTING to its own log must NOT have its open turn closed,
because its turn is still running and a `turn/completed {interrupted}`
landing mid-turn would claim an outcome the turn never had and then
be followed by more of that turn's entries.
@@ -20,8 +20,8 @@
import pytest
-from kiro_crew import ledger as lg
-from kiro_crew import session_ledger_emit as emit
+from kiro_crew import crew_log as lg
+from kiro_crew.crew_log import emit
SESSION = "reconnect-edge-001"
@@ -29,7 +29,7 @@
@pytest.fixture(autouse=True)
def _isolated_home(tmp_path, monkeypatch):
monkeypatch.setenv("KIROCREW_HOME", str(tmp_path / "home"))
- monkeypatch.setenv(emit.SESSION_LEDGER_ENV, "1")
+ monkeypatch.setenv(emit.CREW_LOG_ENV, "1")
monkeypatch.setattr(emit, "_retry_delay", lambda _attempts: 0.0)
emit.reset_caches()
yield
diff --git a/test/test_ledger_edge_throttle.py b/test/test_crew_log_edge_throttle.py
similarity index 97%
rename from test/test_ledger_edge_throttle.py
rename to test/test_crew_log_edge_throttle.py
index 49a1f1175d95..24693a1f3c59 100644
--- a/test/test_ledger_edge_throttle.py
+++ b/test/test_crew_log_edge_throttle.py
@@ -1,8 +1,8 @@
-"""Ledger edge cases: backend throttle, model fallback, and model attribution.
+"""Crew log edge cases: backend throttle, model fallback, and model attribution.
The throttle-fallback ladder in ``_run_chat`` is the one model decision a
transcript cannot answer afterwards: the user picked the primary and the turn
-ran somewhere else. These tests pin what the ledger writes and — more critically
+ran somewhere else. These tests pin what the crew log writes and — more critically
— what it does NOT write, so a reader can trust that the model named in an entry
is the model that produced the work.
"""
@@ -17,7 +17,6 @@
import pytest
from chat_test_helpers import _make_state
-from kiro_crew import session_ledger_emit as emit
from kiro_crew.acp.client import AcpError
from kiro_crew.acp.types import (
EVENT_COMPLETE,
@@ -25,8 +24,8 @@
AcpEvent,
TurnUsage,
)
+from kiro_crew.crew_log import emit, ledger_path
from kiro_crew.dashboard.chat_runner import _ledger_model, _run_chat
-from kiro_crew.ledger import ledger_path
from kiro_crew.llm_helpers import TRANSIENT_RETRIES
SESSION = "acp-throttle-0001"
@@ -36,7 +35,7 @@
def _ledger_home(tmp_path, monkeypatch):
"""Own data home, emitter on, no state carried between tests."""
monkeypatch.setenv("KIROCREW_HOME", str(tmp_path / "home"))
- monkeypatch.setenv(emit.SESSION_LEDGER_ENV, "1")
+ monkeypatch.setenv(emit.CREW_LOG_ENV, "1")
emit.reset_caches()
yield
emit.reset_caches()
@@ -153,7 +152,7 @@ def _set_fallback_attrs(slot, monkeypatch):
async def test_same_model_retry_success_no_fallback_logged(tmp_path, monkeypatch):
"""A throttle that retries on the SAME model and succeeds.
- The ledger must NOT contain ``model/selected`` with ``source=fallback``.
+ The crew log must NOT contain ``model/selected`` with ``source=fallback``.
"""
monkeypatch.setattr("kiro_crew.dashboard.chat_runner._agent_fallback_chain", lambda: ())
monkeypatch.setattr("kiro_crew.dashboard.chat_runner.transient_retry_delay", lambda _a: 0.0)
diff --git a/test/test_session_ledger_emit.py b/test/test_crew_log_emit.py
similarity index 98%
rename from test/test_session_ledger_emit.py
rename to test/test_crew_log_emit.py
index c9e9644676c9..cc7789f79a34 100644
--- a/test/test_session_ledger_emit.py
+++ b/test/test_crew_log_emit.py
@@ -1,4 +1,4 @@
-"""Unit tests for the append-only session ledger emitter."""
+"""Unit tests for the append-only session log emitter."""
from __future__ import annotations
@@ -19,12 +19,11 @@
import pytest
+from kiro_crew import crew_log as lg
from kiro_crew import executors
-from kiro_crew import ledger as lg
-from kiro_crew import session_ledger_emit as emit
+from kiro_crew.crew_log import emit, ledger_path, ledger_root
+from kiro_crew.crew_log.lease import LEASE_FILE
from kiro_crew.dashboard import server as server_module
-from kiro_crew.ledger import ledger_path, ledger_root
-from kiro_crew.ledger.lease import LEASE_FILE
from kiro_crew.platform_compat import file_lock
SESSION = "acp-sess-0001"
@@ -56,12 +55,12 @@ def _isolated_home(tmp_path, monkeypatch):
shard. Zeroed, they wait only on the writer's own barrier.
"""
monkeypatch.setenv("KIROCREW_HOME", str(tmp_path / "home"))
- monkeypatch.setenv(emit.SESSION_LEDGER_ENV, "1")
+ monkeypatch.setenv(emit.CREW_LOG_ENV, "1")
monkeypatch.setattr(emit, "_retry_delay", lambda _attempts: 0.0)
emit.reset_caches()
yield
# Stop the writer BEFORE pytest removes tmp_path. The writer runs on its own
- # thread and creates the ledger root on demand, so one still in flight here can
+ # thread and creates the crew log root on demand, so one still in flight here can
# recreate the directory tree pytest has just deleted -- leaving a stray home
# behind and, worse, making a later test's failure depend on the previous test's
# timing. `drain_for_shutdown` returns once nothing is buffered and no batch is
@@ -252,7 +251,7 @@ def test_every_entry_of_a_turn_names_that_turn_in_its_data():
def test_no_session_entry_carries_a_thread():
# `thread` points at another LINE's seq, which is only knowable for a unit
- # whose anchor is written before the entries citing it -- the crew ledger's
+ # whose anchor is written before the entries citing it -- the crew log's
# shape. A session entry names its turn in data instead.
_open_session()
emit.on_turn_started(SESSION, 1, "user")
@@ -394,7 +393,7 @@ def test_an_app_authored_send_is_not_dispatched_as_a_person():
and node.slice.value == "_turn_actor"
]
assert kwargs_writes, (
- "an app-authored send reaches the turn with no actor, so the ledger "
+ "an app-authored send reaches the turn with no actor, so the crew log "
"records a person who never typed anything"
)
@@ -407,7 +406,7 @@ def test_a_tool_call_is_identified_by_id_in_data_and_records_no_arguments():
emit.on_turn_started(SESSION, 3, "user")
emit.on_tool_called(SESSION, 3, name="execute_bash", server="", kind="execute", call_id="tc-9")
entry = _body()[-1]
- # ref is a citation of another ledger's lines, so a tool call id is data.
+ # ref is a citation of another crew log's lines, so a tool call id is data.
assert "ref" not in entry
assert entry["data"] == {
"turn": 3,
@@ -452,7 +451,7 @@ def test_a_received_message_is_recorded_even_when_the_turn_is_then_refused():
def test_attachments_are_identifiers_not_refs():
- # An attachment is not a ledger unit, so it cannot be cited by a Ref -- the
+ # An attachment is not a crew log unit, so it cannot be cited by a Ref -- the
# same reason a tool call id lives in data.
_open_session()
_typed(1, "see this", attachments=["img-1", "img-2"])
@@ -1161,7 +1160,7 @@ def _spy(session_id, ledger):
def test_a_turns_closers_name_the_turn_that_started_it():
# The runner's message-slice index is reset when a mid-turn clear empties the
- # message list. That index and the ledger's turn ordinal must not be the same
+ # message list. That index and the crew log's turn ordinal must not be the same
# value: sharing one would move the ordinal to 0 mid-turn, and the turn's own
# closers -- emitted at the end -- would then name a turn that never started,
# filing the turn's cost under a phantom ordinal 0 while the real turn shows a
@@ -1170,7 +1169,7 @@ def test_a_turns_closers_name_the_turn_that_started_it():
emit.on_turn_started(SESSION, 3, "user")
step = emit.on_step_started(SESSION, 3)
emit.on_tool_called(SESSION, 3, name="fs_read", call_id="c9", args="{}")
- # Whatever the runner does to its own slice index, the ledger's ordinal is the
+ # Whatever the runner does to its own slice index, the crew log's ordinal is the
# one the turn opened with.
emit.close_open_tool_calls(SESSION, 3)
emit.on_step_completed(SESSION, 3, step, ms=1)
@@ -1315,16 +1314,16 @@ def _calls(name: str) -> list[int]:
drains = _calls("drain_for_shutdown")
exits = _calls("_exit")
- assert drains, "the hard-exit path does not drain the session ledger at all"
+ assert drains, "the hard-exit path does not drain the session log at all"
assert exits, "this test no longer finds the hard exit it is anchored to"
assert min(drains) < min(
exits
- ), f"the ledger drain at line {min(drains)} runs after the exit at {min(exits)}"
- # And before the log-queue drain, so a ledger warning still reaches the log.
+ ), f"the crew log drain at line {min(drains)} runs after the exit at {min(exits)}"
+ # And before the log-queue drain, so a crew log warning still reaches the log.
log_drains = _calls("drain_log_queue_before_hard_exit")
if log_drains:
assert min(drains) < min(log_drains), (
- "the ledger drain runs after the log queue is flushed, so its own "
+ "the crew log drain runs after the log queue is flushed, so its own "
"warning about an incomplete drain would be lost"
)
@@ -1372,7 +1371,7 @@ def test_an_empty_body_writes_no_sent_entry_at_all():
def test_every_new_family_is_silent_with_the_flag_off(monkeypatch):
_open_session()
- monkeypatch.delenv(emit.SESSION_LEDGER_ENV, raising=False)
+ monkeypatch.delenv(emit.CREW_LOG_ENV, raising=False)
before = len(_body())
emit.on_message_received(SESSION, 1, text="x")
emit.on_message_sent(SESSION, 1, text="y")
@@ -1393,7 +1392,7 @@ def test_a_disabled_emitter_does_no_payload_work_at_all(monkeypatch):
is off by default.
"""
_open_session()
- monkeypatch.delenv(emit.SESSION_LEDGER_ENV, raising=False)
+ monkeypatch.delenv(emit.CREW_LOG_ENV, raising=False)
worked: list[str] = []
monkeypatch.setattr(
emit, "_payload_digest", lambda payload: worked.append("digest") or ("", -1)
@@ -1694,7 +1693,7 @@ def test_a_refused_oversize_write_is_dropped_and_counted_and_named_once(caplog):
assert emit.dropped_writes() == 2, "both losses are counted"
warnings = [r for r in caplog.records if r.levelno == logging.WARNING]
# One for the storage failure, one for the loss -- and the SECOND refusal adds
- # neither, because a failing ledger names itself once rather than per entry.
+ # neither, because a failing crew log names itself once rather than per entry.
assert len(warnings) == 2, f"expected the failure and the loss once each: {warnings}"
assert any("gave up on" in record.getMessage() for record in warnings)
@@ -1751,8 +1750,8 @@ def test_a_missing_session_id_is_a_no_op():
def test_cache_pressure_never_closes_a_live_turn(monkeypatch):
"""What a bounded LRU of open handles must not do to a running turn.
- With more concurrent ledgers than the cache holds, evicting a live session's
- handle makes the next emit in that same turn reopen the ledger -- and an open
+ With more concurrent crew logs than the cache holds, evicting a live session's
+ handle makes the next emit in that same turn reopen the crew log -- and an open
that repaired would append a false `turn/completed {interrupted}` into a turn
that then keeps writing. Two things prevent it: repair is opt-in and only a
resume asks for it, and a session with a turn in flight is not evicted at all.
@@ -1850,7 +1849,7 @@ def test_a_resume_does_not_close_a_turn_this_process_is_still_running(caplog):
assert emit.flush()
# NO reset_caches: this process still holds turn 1 as live, which is the whole
# point -- the claim below is contradicted by our own state.
- with caplog.at_level(logging.WARNING, logger="kiro_crew.session_ledger_emit"):
+ with caplog.at_level(logging.WARNING, logger="kiro_crew.crew_log.emit"):
emit.on_session_opened(SESSION, agent="kirocrew", resumed=True)
assert emit.flush()
@@ -1877,7 +1876,7 @@ def test_a_resume_does_not_close_a_turn_this_process_is_still_running(caplog):
@contextlib.contextmanager
def _owned_elsewhere(session_id: str = SESSION):
- """Hold one session ledger's write ownership from another descriptor.
+ """Hold one session log's write ownership from another descriptor.
An advisory lock belongs to an open file description, so a descriptor of our
own contends exactly as a second gateway's would. Non-blocking, so a lock this
@@ -1892,7 +1891,7 @@ def _owned_elsewhere(session_id: str = SESSION):
def _can_take_ownership(session_id: str = SESSION) -> bool:
- """Whether another owner could take this ledger's write lock right now.
+ """Whether another owner could take this crew log's write lock right now.
False means this process still owns the log. Non-blocking, so a held lock is
an answer here rather than a wait.
@@ -2109,7 +2108,7 @@ def test_a_stalled_write_is_named_by_a_producer_without_being_asked(caplog):
emit._inflight_what = "a write that never returns"
emit._stall_reported = False
try:
- with caplog.at_level(logging.ERROR, logger="kiro_crew.session_ledger_emit"):
+ with caplog.at_level(logging.ERROR, logger="kiro_crew.crew_log.emit"):
# An ordinary producer call, nothing stall-specific about it.
emit.on_turn_started(SESSION, 1, "user")
assert any(
@@ -2267,7 +2266,7 @@ def test_a_tool_call_records_a_digest_of_its_arguments_never_the_arguments():
"Did this call run the same command as the last one" and "how big was this
payload" are both answerable from a digest. Keeping the payload itself would
- make the ledger a place shell arguments and file contents accumulate.
+ make the crew log a place shell arguments and file contents accumulate.
"""
_open_session()
emit.on_turn_started(SESSION, 1, "user")
@@ -2365,11 +2364,11 @@ def test_a_long_result_records_the_full_redacted_output_measurement():
assert data["result_bytes"] == len(
full_output.encode("utf-8")
- ), "the ledger measured the displayed prefix instead of the full redacted output"
+ ), "the crew log measured the displayed prefix instead of the full redacted output"
assert data["result_hash"] == hashlib.sha256(full_output.encode("utf-8")).hexdigest()
assert (
data["result_hash"] != hashlib.sha256(displayed.encode("utf-8")).hexdigest()
- ), "the ledger hashed the displayed prefix instead of the full redacted output"
+ ), "the crew log hashed the displayed prefix instead of the full redacted output"
def test_equal_display_prefixes_record_different_full_result_hashes():
@@ -2466,7 +2465,7 @@ def test_a_turn_start_carries_the_message_it_answers_when_the_caller_knows_it():
def test_flag_off_writes_no_file_at_all(monkeypatch):
- monkeypatch.setenv(emit.SESSION_LEDGER_ENV, "0")
+ monkeypatch.setenv(emit.CREW_LOG_ENV, "0")
assert emit.enabled() is False
_open_session()
emit.on_turn_started(SESSION, 1, "user")
@@ -2477,7 +2476,7 @@ def test_flag_off_writes_no_file_at_all(monkeypatch):
def test_flag_unset_writes_no_file_at_all(monkeypatch):
- monkeypatch.delenv(emit.SESSION_LEDGER_ENV, raising=False)
+ monkeypatch.delenv(emit.CREW_LOG_ENV, raising=False)
assert emit.enabled() is False
_open_session()
assert not _store_root().exists()
@@ -2491,7 +2490,7 @@ def test_flag_off_allocates_no_state_either(monkeypatch):
record per turn on every gateway running with the emitter off -- invisible,
because no file appears to give it away.
"""
- monkeypatch.setenv(emit.SESSION_LEDGER_ENV, "0")
+ monkeypatch.setenv(emit.CREW_LOG_ENV, "0")
assert emit.enabled() is False
for turn in range(1, 6):
@@ -2510,12 +2509,12 @@ def test_flag_off_allocates_no_state_either(monkeypatch):
def test_a_flag_turned_off_mid_turn_still_releases_what_it_allocated(monkeypatch):
# The release paths stay unguarded for exactly this: state allocated while the
# flag was on must not be stranded by turning it off.
- monkeypatch.setenv(emit.SESSION_LEDGER_ENV, "1")
+ monkeypatch.setenv(emit.CREW_LOG_ENV, "1")
_open_session()
emit.on_turn_started(SESSION, 1, "user")
assert (SESSION, 1) in emit._live
- monkeypatch.setenv(emit.SESSION_LEDGER_ENV, "0")
+ monkeypatch.setenv(emit.CREW_LOG_ENV, "0")
emit.on_turn_completed(SESSION, 1, stop_reason="end_turn")
assert (SESSION, 1) not in emit._live
assert SESSION not in emit._pinned
@@ -2523,21 +2522,21 @@ def test_a_flag_turned_off_mid_turn_still_releases_what_it_allocated(monkeypatch
@pytest.mark.parametrize("value", ["1", "true", "TRUE", " yes ", "on"])
def test_the_flag_accepts_the_repo_truthy_spellings(monkeypatch, value):
- monkeypatch.setenv(emit.SESSION_LEDGER_ENV, value)
+ monkeypatch.setenv(emit.CREW_LOG_ENV, value)
assert emit.enabled() is True
@pytest.mark.parametrize("value", ["0", "false", "no", "off", "", "2"])
def test_the_flag_rejects_everything_else(monkeypatch, value):
- monkeypatch.setenv(emit.SESSION_LEDGER_ENV, value)
+ monkeypatch.setenv(emit.CREW_LOG_ENV, value)
assert emit.enabled() is False
def test_the_flag_is_read_per_call_not_at_import(monkeypatch):
- monkeypatch.setenv(emit.SESSION_LEDGER_ENV, "0")
+ monkeypatch.setenv(emit.CREW_LOG_ENV, "0")
_open_session()
assert not _store_root().exists()
- monkeypatch.setenv(emit.SESSION_LEDGER_ENV, "1")
+ monkeypatch.setenv(emit.CREW_LOG_ENV, "1")
_open_session()
assert _ledger_path().is_file()
@@ -2882,7 +2881,7 @@ def test_the_dashboard_cleanup_hook_actually_drains_off_the_loop():
source = inspect.getsource(server_module)
assert (
"app.on_cleanup.append(_session_ledger_drain)" in source
- ), "the server no longer registers a ledger drain on cleanup"
+ ), "the server no longer registers a crew log drain on cleanup"
drained: list[str] = []
@@ -3070,7 +3069,7 @@ def test_a_reopen_that_fails_is_retried_rather_than_discarding_the_entry():
"""The same hole one layer up from the append.
A handle can go missing from the bounded cache, and the next entry reopens the
- ledger. If that reopen error were swallowed the job would SUCCEED with nothing
+ crew log. If that reopen error were swallowed the job would SUCCEED with nothing
written -- no retry, and nothing in ``dropped_writes()`` either -- which is
exactly the silent hole the retention exists to close.
"""
@@ -3106,7 +3105,7 @@ def test_a_retried_session_open_still_writes_the_entry_it_owes():
The job decides whether to announce from filesystem state it changes itself:
when the header lands and the entry behind it does not, the retry finds the
- ledger already there and would read "nothing new to say" -- skipping
+ crew log already there and would read "nothing new to say" -- skipping
``session/opened`` for good, and not counting it either. The decision is
latched on the first attempt for exactly that reason.
"""
@@ -3706,7 +3705,7 @@ def _hangs() -> None:
release.wait(30.0)
try:
- with caplog.at_level(logging.WARNING, logger="kiro_crew.session_ledger_emit"):
+ with caplog.at_level(logging.WARNING, logger="kiro_crew.crew_log.emit"):
emit._buffer(SESSION, _pending(_hangs, "a write that never returns"))
assert took_it.wait(20.0), "the writer never picked up the hanging job"
@@ -3746,7 +3745,7 @@ def test_a_write_stuck_too_long_is_named(caplog):
emit._inflight_what = "a write that never returns"
emit._stall_reported = False
try:
- with caplog.at_level(logging.ERROR, logger="kiro_crew.session_ledger_emit"):
+ with caplog.at_level(logging.ERROR, logger="kiro_crew.crew_log.emit"):
emit._note_stall_if_any()
assert any(
"neither returned nor failed" in r.getMessage() for r in caplog.records
@@ -3852,7 +3851,7 @@ def test_a_wedged_session_neither_reorders_nor_loses_another_and_both_land():
"""The per-session bucket, asserted rather than only claimed -- and its limit.
The buffer is keyed per session because each session is a separate file, and the
- guarantee that shape buys is written in the spec: one slow ledger must not
+ guarantee that shape buys is written in the spec: one slow crew log must not
REORDER another's entries. This pins that, and it also pins the part the spec
now states explicitly because writing this test is what surfaced it: ONE worker
drains every session, so a write that hangs does DELAY every other session's
@@ -4040,8 +4039,13 @@ def _record(fn, *a, **k):
print(
json.dumps(
{
- "storage": sorted(k for k in sys.modules if k.startswith("kiro_crew.ledger")),
- "glue": "kiro_crew.session_ledger_emit" in sys.modules,
+ "storage": sorted(
+ k
+ for k in sys.modules
+ if k.startswith("kiro_crew.crew_log.")
+ and k != "kiro_crew.crew_log.emit"
+ ),
+ "glue": "kiro_crew.crew_log.emit" in sys.modules,
"hooks": [n for n in registered if "drain_for_shutdown" in n],
}
)
@@ -4099,7 +4103,7 @@ def test_a_flag_off_launch_does_not_load_the_storage_subsystem(tmp_path: Path) -
seen = _boot_probe(tmp_path)
assert seen["glue"], "the probe did not reach the emitter at all, so it proves nothing"
assert seen["storage"] == [], (
- "a launch with KIROCREW_SESSION_LEDGER unset imported the storage subsystem: "
+ "a launch with KIROCREW_CREW_LOG unset imported the storage subsystem: "
f"{seen['storage']}"
)
@@ -4113,7 +4117,7 @@ def test_a_flag_off_launch_registers_no_shutdown_hook(tmp_path: Path) -> None:
"""
seen = _boot_probe(tmp_path)
assert seen["hooks"] == [], (
- "a flag-off launch registered the ledger drain at exit: " f"{seen['hooks']}"
+ "a flag-off launch registered the crew log drain at exit: " f"{seen['hooks']}"
)
@@ -4133,13 +4137,13 @@ def test_the_shutdown_hook_is_registered_once_on_first_use(monkeypatch) -> None:
)
-# --- the ledger-creating record is exempt from the memory ceiling ----------
+# --- the log-creating record is exempt from the memory ceiling ----------
def test_overflow_while_the_creating_record_is_queued_still_creates_the_ledger(monkeypatch):
"""(a) A ceiling crossed as the file-creating record is queued must not erase it.
- The ceiling bounds PAYLOAD memory, and the record that creates the ledger is
+ The ceiling bounds PAYLOAD memory, and the record that creates the crew log is
O(1) per session -- refusing it would leave the session with no file, so every
later entry (the loss marker included) would be a silent uncounted no-op. The
creating record is exempt, so it lands even at a zero-capacity ceiling and the
@@ -4173,7 +4177,7 @@ def _occupy_writer() -> None:
emit.on_turn_completed(SESSION, 1, stop_reason="end_turn")
assert emit.flush(timeout=20.0)
- assert _ledger_path().is_file(), "the ceiling refused the ledger-creating record"
+ assert _ledger_path().is_file(), "the ceiling refused the log-creating record"
body_types = [e["type"] for e in _body()]
assert "session/opened" in body_types, "the creating session/opened entry was refused"
@@ -4184,7 +4188,7 @@ def _occupy_writer() -> None:
def _fail_creation_permanently() -> None:
"""Open a session whose creating record is REFUSED (a permanent LedgerError).
- Leaves ``SESSION`` flagged in ``_creation_failed`` with no ledger file, which
+ Leaves ``SESSION`` flagged in ``_creation_failed`` with no log file, which
is the state a later append must count as loss rather than silently no-op.
"""
real_create = lg.Ledger.create
@@ -4203,14 +4207,14 @@ def _refuse_create(kind, unit_id, *args, **kwargs):
def test_a_permanently_failed_creation_counts_later_discards_as_loss():
"""(b) After a permanent creation failure, later entries are COUNTED, not dropped silently.
- A session whose creating record died permanently has no ledger file, but it
+ A session whose creating record died permanently has no log file, but it
WAS opened, so its later entries are a real loss. ``_handle`` raises a refusal
for such a session instead of returning None, so the discarded entry is counted
in ``dropped_writes`` rather than vanishing as a silent policy no-op.
"""
_fail_creation_permanently()
assert SESSION in emit._creation_failed, "the failed creation was not flagged"
- assert not _ledger_path().is_file(), "no ledger file should exist after a failed creation"
+ assert not _ledger_path().is_file(), "no log file should exist after a failed creation"
dropped_before = emit.dropped_writes()
emit.on_turn_started(SESSION, 1, "user")
@@ -4222,7 +4226,7 @@ def test_a_permanently_failed_creation_counts_later_discards_as_loss():
def test_a_session_that_was_never_opened_stays_a_silent_no_op():
- """(b, negative half) A session that legitimately has no ledger is unchanged.
+ """(b, negative half) A session that legitimately has no crew log is unchanged.
The creation-failed count must not turn the ordinary "feature off / never
opened" no-op into a counted loss: that session is a policy no-op, uncounted.
@@ -4238,7 +4242,7 @@ def test_a_closed_session_does_not_leave_its_creation_failure_flagged():
"""The creation-failure verdict dies with the session, not at the next reset.
The flag makes every later entry for that id a counted loss, so a successor
- reusing the id would inherit a verdict about a ledger it never created. Left
+ reusing the id would inherit a verdict about a crew log it never created. Left
to ``reset_caches`` the flag would also outlive every failed session for as
long as the process runs. It is cleared in the close path's terminal cleanup,
which runs even when the closing entry itself was dropped -- and that is the
diff --git a/test/test_ledger_kinds.py b/test/test_crew_log_kinds.py
similarity index 91%
rename from test/test_ledger_kinds.py
rename to test/test_crew_log_kinds.py
index 1f4e8799fee8..0e71fb51684c 100644
--- a/test/test_ledger_kinds.py
+++ b/test/test_crew_log_kinds.py
@@ -1,6 +1,6 @@
"""The layering: what is the envelope, what belongs to one kind, who may write it.
-``test_ledger_core.py`` covers the format. This file covers the SPLIT -- the
+``test_crew_log_core.py`` covers the format. This file covers the SPLIT -- the
matrix of which ``src`` each kind accepts, the guest rules that authorization
hangs off ``src``, and the two crew contracts' envelope half. It is a matrix
rather than a set of examples because the hole it closes is a shared source list
@@ -10,7 +10,7 @@
The `data` half of the crew contracts -- ``crew/dispatch`` requiring ``target``,
``crew/report`` requiring ``ref`` -- is per-type validation, which lives in the
type registry rather than here. Until that module exists, those requirements are
-spec text (``docs/system-specs/modules/ledger-core.md`` section 4b) and this file
+spec text (``docs/system-specs/modules/crew-log-core.md`` section 4b) and this file
asserts only what the envelope itself can hold.
"""
@@ -18,9 +18,9 @@
import pytest
-from kiro_crew import ledger as lg
-from kiro_crew.ledger import Ledger, LedgerError, Ref
-from kiro_crew.ledger.schema import check_ownership, require_src
+from kiro_crew import crew_log as lg
+from kiro_crew.crew_log import Ledger, LedgerError, Ref
+from kiro_crew.crew_log.schema import check_ownership, require_src
CREW = "qa"
SESSION = "s-7f3a"
@@ -82,7 +82,7 @@ def test_the_matrix_covers_every_documented_source():
assert any(src.startswith(prefix) for src in listed), prefix
-def test_a_patrol_cannot_write_into_a_session_ledger():
+def test_a_patrol_cannot_write_into_a_session_log():
# The concrete hole a shared source list leaves open: a patrol has nothing
# to say inside one session's own turn history, and src is what a reader
# attributes an entry to.
@@ -113,7 +113,7 @@ def test_an_unknown_kind_is_refused_before_any_source_list_is_indexed():
def test_the_session_emitters_own_sources_are_all_accepted():
"""No behaviour change for the writes that exist: the emitter's own constants."""
- from kiro_crew import session_ledger_emit as emit
+ from kiro_crew.crew_log import emit
for src in (emit._SRC_ACP, emit._SRC_GATEWAY):
assert require_src(src, kind=lg.KIND_SESSION) == src
@@ -128,7 +128,7 @@ def test_a_crew_guest_writes_the_crew_kinds_built_in_domains():
assert crew.append(entry_type, {}, src="crew:qa").src == "crew:qa"
-def test_a_crew_guest_is_refused_by_a_session_ledger():
+def test_a_crew_guest_is_refused_by_a_session_log():
session = _session()
with pytest.raises(LedgerError) as exc:
session.append("turn/started", {"turn": 1}, src="crew:qa")
@@ -144,7 +144,7 @@ def test_an_app_guest_is_confined_to_its_own_type_namespace():
assert _code(exc) == lg.CODE_NAMESPACE_VIOLATION
-def test_an_app_guest_is_refused_by_a_session_ledger():
+def test_an_app_guest_is_refused_by_a_session_log():
session = _session()
with pytest.raises(LedgerError) as exc:
session.append("app:radar/scan", {}, src="app:radar")
@@ -162,7 +162,7 @@ def test_a_type_never_carries_the_writers_identity():
def test_one_report_type_serves_every_child():
# The point of moving identity into src: two children write the same type
- # into one parent ledger, and the entries are told apart by src.
+ # into one parent crew log, and the entries are told apart by src.
crew = _crew()
evidence = Ref(lg.KIND_SESSION, SESSION, 1)
first = crew.append(
@@ -196,7 +196,7 @@ def test_a_report_may_cite_a_session_segment_which_is_the_one_cross_kind_bridge(
assert report.ref is not None and report.ref.unit == lg.KIND_SESSION
-def test_a_session_ledger_may_cite_a_crew_segment_too():
+def test_a_session_log_may_cite_a_crew_segment_too():
"""``ref`` is kind-independent: it is the envelope's, not one kind's."""
_crew()
session = _session()
diff --git a/test/test_ledger_lease.py b/test/test_crew_log_lease.py
similarity index 97%
rename from test/test_ledger_lease.py
rename to test/test_crew_log_lease.py
index 31d25157bc2a..8cd02714f87c 100644
--- a/test/test_ledger_lease.py
+++ b/test/test_crew_log_lease.py
@@ -1,6 +1,6 @@
-"""Write ownership of a session ledger -- who may append, and who is refused.
+"""Write ownership of a session log -- who may append, and who is refused.
-The hazard being pinned: a resume opens a session ledger with ``repair=True``
+The hazard being pinned: a resume opens a session log with ``repair=True``
while a writer is still live, so the file states that the turn completed as
interrupted and then, further down, completed for real, with one tool call closed
both ``unknown`` and ``completed``. A fold reads two outcomes for one turn and
@@ -27,12 +27,12 @@
import pytest
-from kiro_crew import ledger as lg
-from kiro_crew.ledger import Ledger, LedgerError
-from kiro_crew.ledger.lease import LEASE_FILE
+from kiro_crew import crew_log as lg
+from kiro_crew.crew_log import Ledger, LedgerError
+from kiro_crew.crew_log.lease import LEASE_FILE
from kiro_crew.platform_compat import file_lock
-CHILD = Path(__file__).parent / "fixtures" / "ledger_lease_child.py"
+CHILD = Path(__file__).parent / "fixtures" / "crew_log_lease_child.py"
SESSION = "lease-owner-session"
#: Only an upper bound on a failure. Every wait here returns as soon as the child
#: answers on its pipe, so a passing run does not spend it.
@@ -85,7 +85,7 @@ def _types(unit_id: str = SESSION) -> "list[str]":
class _Foreign:
- """Another owner of one ledger's writes, holding its own descriptor.
+ """Another owner of one crew log's writes, holding its own descriptor.
Stands in for a second process wherever the property does not need one. The
lock is taken NON-BLOCKING, so a failure to take it is reported here rather
@@ -226,7 +226,7 @@ def test_a_release_fired_by_the_collector_inside_an_acquire_does_not_deadlock(mo
Mutation guard: making the lock a plain ``threading.Lock`` hangs the acquire
below, and the bounded wait reports it.
"""
- from kiro_crew.ledger import lease
+ from kiro_crew.crew_log import lease
class Cycle:
pass
@@ -395,7 +395,7 @@ def _child(home: Path, tmp_path: Path) -> "subprocess.Popen[str]":
"""
env = {
"KIROCREW_HOME": str(home),
- "KIROCREW_SESSION_LEDGER": "1",
+ "KIROCREW_CREW_LOG": "1",
"PYTHONPATH": str(Path(__file__).resolve().parents[1] / "src"),
"PATH": os.environ.get("PATH", ""),
"TMPDIR": str(tmp_path),
diff --git a/test/test_session_ledger_order.py b/test/test_crew_log_order.py
similarity index 97%
rename from test/test_session_ledger_order.py
rename to test/test_crew_log_order.py
index 51cc0c687280..360a2c87579f 100644
--- a/test/test_session_ledger_order.py
+++ b/test/test_crew_log_order.py
@@ -1,6 +1,6 @@
"""``seq`` must follow causality at every emit site, not merely be contiguous.
-The ledger's whole premise is that a reader folds entries in ``seq`` order, so an
+The crew log's whole premise is that a reader folds entries in ``seq`` order, so an
entry appearing before the facts that happened first is not a cosmetic problem: it
is a wrong answer the fold cannot detect, in a file that is never rewritten. These
tests drive the real ``_run_chat`` over a scripted ACP stream and assert on the
@@ -17,7 +17,6 @@
import pytest
from chat_test_helpers import _make_state
-from kiro_crew import session_ledger_emit as emit
from kiro_crew.acp.types import (
EVENT_CLEAR_STATUS,
EVENT_COMPLETE,
@@ -26,8 +25,8 @@
EVENT_TOOL_RESULT,
AcpEvent,
)
+from kiro_crew.crew_log import emit, ledger_path
from kiro_crew.dashboard.chat_runner import _run_chat
-from kiro_crew.ledger import ledger_path
SESSION = "acp-order-0001"
@@ -36,14 +35,14 @@
def _ledger_home(tmp_path, monkeypatch):
"""Own data home, emitter on, and no state carried between tests."""
monkeypatch.setenv("KIROCREW_HOME", str(tmp_path / "home"))
- monkeypatch.setenv(emit.SESSION_LEDGER_ENV, "1")
+ monkeypatch.setenv(emit.CREW_LOG_ENV, "1")
emit.reset_caches()
yield
emit.reset_caches()
def _entries() -> list[dict]:
- """Every ledger line after the header, in file order."""
+ """Every crew log line after the header, in file order."""
path = ledger_path("session", SESSION)
if not path.is_file():
return []
@@ -69,7 +68,7 @@ def _state_and_slot(tmp_path: Path, events, *, raises: BaseException | None = No
client = MagicMock()
client.session_id = SESSION
# The runner publishes the INNER client on the slot, and `_flush_segment`
- # resolves the ledger key from there rather than from the provider -- so the
+ # resolves the crew log key from there rather than from the provider -- so the
# inner one has to carry the id too, or every `message/sent` is a silent no-op
# and the ordering assertions below are vacuous.
client.client._session_id = SESSION
@@ -186,7 +185,7 @@ async def test_a_recovery_path_records_the_partial_reply_it_persists(tmp_path, e
``slot.append`` rather than ``_flush_segment``, because they purge the chunk
rows and must not broadcast a segment. They reach the log through one shared
helper, so the transcript cannot hold text the user watched stream while the
- ledger carries a turn closer and nothing else -- a closer asserting an end for
+ crew log carries a turn closer and nothing else -- a closer asserting an end for
output the record never mentions. The body is written with ``interrupted`` and
BEFORE the closers, which is the order it happened.
"""
@@ -294,7 +293,7 @@ async def test_the_input_is_recorded_before_what_was_derived_from_it(tmp_path):
@pytest.mark.asyncio
async def test_message_received_records_entry_text_before_prompt_expansion(tmp_path):
- """The ledger records the accepted text, while the model sees its expansion."""
+ """The crew log records the accepted text, while the model sees its expansion."""
from kiro_crew.dashboard import chat_runner
state, slot = _state_and_slot(tmp_path, [AcpEvent(kind=EVENT_TEXT_CHUNK, text="ok")])
@@ -322,7 +321,7 @@ def test_the_model_recorded_is_the_one_the_session_runs_on():
list -- while the session runs on the backend default. Writing that pin into an
append-only entry states a model the session did not run, in a file nothing
rewrites. `served_model` is the session fact, empty when the backend serves its
- own default, and the ledger records that emptiness rather than naming a model.
+ own default, and the crew log records that emptiness rather than naming a model.
Mutation guard: reading `slot.model` at either site reddens this.
"""
@@ -349,7 +348,7 @@ async def test_an_accepted_attachment_is_named_in_the_message_entry(tmp_path):
"""A turn's input includes what was attached to it.
`on_message_received` has always accepted the ids; the call site did not pass
- them, so a message whose whole point was a file left the ledger describing text
+ them, so a message whose whole point was a file left the crew log describing text
alone and a reader could not tell why the turn did what it did. The ids come from
the site that ACCEPTED them -- the handler, or the queue drain for a row that
waited -- rather than being read back off the slot's last user row, which would
@@ -407,7 +406,7 @@ def test_a_segment_cut_by_a_steer_is_recorded_as_interrupted():
flush_src = inspect.getsource(chat_runner._flush_segment)
assert "interrupted: bool = False" in flush_src, "the flush cannot carry the fact"
- assert "interrupted=interrupted" in flush_src, "the flush does not pass it to the ledger"
+ assert "interrupted=interrupted" in flush_src, "the flush does not pass it to the crew log"
# The steer cut is the caller that must set it. Read from the source of the
# enclosing runner because the callback is a closure built per turn.
@@ -599,7 +598,7 @@ async def test_the_turn_ordinal_keeps_rising_across_a_native_clear(tmp_path):
assert after["turn"] > cleared, (
f"the first turn after the clear reused ordinal {after['turn']} (the clear turn "
f"was {cleared}, the one before it {before}); two unrelated turns now share one "
- "ledger identity"
+ "crew log identity"
)
assert after.get("attempt", 1) == 1, (
"the first turn after the clear was recorded as a retry, which is what a "
diff --git a/test/test_ledger_real_crash.py b/test/test_crew_log_real_crash.py
similarity index 98%
rename from test/test_ledger_real_crash.py
rename to test/test_crew_log_real_crash.py
index fc69222a05d3..bda1aa784036 100644
--- a/test/test_ledger_real_crash.py
+++ b/test/test_crew_log_real_crash.py
@@ -24,10 +24,10 @@
import pytest
-from kiro_crew import ledger as lg
-from kiro_crew.ledger import Ledger
+from kiro_crew import crew_log as lg
+from kiro_crew.crew_log import Ledger
-CHILD = Path(__file__).parent / "fixtures" / "ledger_crash_child.py"
+CHILD = Path(__file__).parent / "fixtures" / "crew_log_crash_child.py"
SESSION = "crash-child-session"
#: Generous, and only an upper bound on a failure: the wait returns as soon as the
#: marker holds its terminal value, so a passing run does not spend it.
@@ -65,7 +65,7 @@ def _kill_at(tmp_path: Path, failpoint: str, marker_value: str) -> Path:
# startup can need it; nothing else is.
env = {
"KIROCREW_HOME": str(home),
- "KIROCREW_SESSION_LEDGER": "1",
+ "KIROCREW_CREW_LOG": "1",
"PYTHONPATH": str(Path(__file__).resolve().parents[1] / "src"),
"PATH": os.environ.get("PATH", ""),
# Keep the child's own temp files inside the test's directory, for the same
diff --git a/test/test_ledger_retention.py b/test/test_crew_log_retention.py
similarity index 94%
rename from test/test_ledger_retention.py
rename to test/test_crew_log_retention.py
index b3d887bef5c8..f2163c251744 100644
--- a/test/test_ledger_retention.py
+++ b/test/test_crew_log_retention.py
@@ -1,11 +1,11 @@
-"""Ledger retention -- one test per rule the sweep and the removal promise.
+"""Crew log retention -- one test per rule the sweep and the removal promise.
Two layers, in the order they depend on each other: ``remove_unit`` (ownership,
ordering, identity last, counted failures) and ``sweep_expired`` (which units it
selects, and every unit it must refuse to touch).
The refusals carry the weight here. A sweep that removes too little costs disk;
-a sweep that removes an OPEN session's log, a crew ledger, or a unit some writer
+a sweep that removes an OPEN session's log, a crew log, or a unit some writer
still owns destroys a record nothing can rebuild -- so each of those has its own
test rather than being covered incidentally by the happy path.
"""
@@ -20,11 +20,11 @@
import time
import pytest
-from ledger_type_helpers import minimal_data
+from crew_log_type_helpers import minimal_data
-from kiro_crew import ledger as lg
-from kiro_crew.ledger import Ledger, store
-from kiro_crew.ledger.lease import LEASE_FILE
+from kiro_crew import crew_log as lg
+from kiro_crew.crew_log import Ledger, store
+from kiro_crew.crew_log.lease import LEASE_FILE
from kiro_crew.session_ledger import _store_name
SESSION = "s-retain"
@@ -54,7 +54,7 @@ def _isolated_home(tmp_path, monkeypatch):
def _closed_session(
unit_id: str = SESSION, *, closed_days_ago: float = 90.0, reason: str = "destroyed"
) -> Ledger:
- """A session ledger holding one ``session/closed`` written *closed_days_ago*.
+ """A session log holding one ``session/closed`` written *closed_days_ago*.
The default *reason* is a real terminal one. It is not decoration: a unit is
collectable only when its close reason proves the gateway cleared that ACP id's
@@ -69,7 +69,7 @@ def _closed_session(
def _open_session(unit_id: str = SESSION, *, age_days: float = 90.0) -> Ledger:
- """A session ledger with a header and entries but NO ``session/closed``.
+ """A session log with a header and entries but NO ``session/closed``.
Its ``session/opened`` is aged too, not just the file: "an open session is
never touched, HOWEVER OLD it is" is a claim about every clock in the unit, so
@@ -123,7 +123,7 @@ def _age_close_entry(unit_id: str, *, days: float) -> None:
close edits the line afterwards. The entry keeps its real shape, so the sweep
reads it exactly as it reads a genuinely old one.
"""
- path = _unit_dir(lg.KIND_SESSION, unit_id) / "ledger.jsonl"
+ path = _unit_dir(lg.KIND_SESSION, unit_id) / "log.jsonl"
lines = path.read_text(encoding="utf-8").splitlines()
for index in range(len(lines) - 1, -1, -1):
entry = json.loads(lines[index])
@@ -271,16 +271,16 @@ def _record_path(self, *args, **kwargs):
finally:
Path.unlink = real_path_unlink
- assert "ledger.jsonl" in order, order
+ assert "log.jsonl" in order, order
assert order[-1] == LEASE_FILE, order
- assert order.index("ledger.jsonl") < order.index(LEASE_FILE), order
+ assert order.index("log.jsonl") < order.index(LEASE_FILE), order
def test_remove_unit_counts_a_failure_and_keeps_the_history():
"""A partial removal is reported, never counted as a removal.
``rmtree(ignore_errors=True)`` would report success over a subtree it left
- standing. The unit keeps its segments, so it still reads as a ledger and the
+ standing. The unit keeps its segments, so it still reads as a crew log and the
next pass can aim at it again.
"""
ledger = _closed_session()
@@ -291,7 +291,7 @@ def test_remove_unit_counts_a_failure_and_keeps_the_history():
real_unlink = Path.unlink
def _refuse_segment(self, *args, **kwargs):
- if self.name == "ledger.jsonl":
+ if self.name == "log.jsonl":
raise OSError("held")
return real_unlink(self, *args, **kwargs)
@@ -352,7 +352,7 @@ def test_remove_unit_never_follows_a_unit_directory_linked_to_another_unit():
pytest.skip("symlinks unavailable")
assert _remove("s-attacker") == store.REMOVE_ABSENT
- assert (victim_dir / "ledger.jsonl").exists()
+ assert (victim_dir / "log.jsonl").exists()
assert Ledger.exists(lg.KIND_SESSION, "s-victim")
@@ -399,9 +399,9 @@ def test_a_linked_unit_directory_never_causes_the_target_to_be_removed():
pytest.skip("symlinks unavailable")
assert store.sweep_expired(30) == (0, 0)
- assert (stash / "ledger.jsonl").exists()
+ assert (stash / "log.jsonl").exists()
assert _remove("s-hidden") == store.REMOVE_ABSENT
- assert (stash / "ledger.jsonl").exists()
+ assert (stash / "log.jsonl").exists()
# --- sweep_expired: what it selects ----------------------------------------
@@ -439,7 +439,7 @@ def test_sweep_never_touches_an_open_session_however_old_it_is():
def test_sweep_ages_from_the_close_entry_not_the_file_mtime():
"""The entry's own ``time`` wins, because mtime is metadata a restore resets.
- A restored or copied tree carries a fresh mtime on a months-old ledger. Aging
+ A restored or copied tree carries a fresh mtime on a months-old crew log. Aging
from mtime would make such a unit read as just-closed and survive retention
forever, so the writer's own record of when the session ended is authoritative.
"""
@@ -472,7 +472,7 @@ def test_sweep_falls_back_to_mtime_when_the_close_entry_has_no_usable_time():
def test_sweep_reads_the_newest_close_when_a_resumed_session_closed_twice():
- """A resumed session appends to the ledger it already had.
+ """A resumed session appends to the crew log it already had.
So a file can hold more than one close, and only the newest describes the
life that ended. Reading the first would expire a session that came back.
@@ -490,7 +490,7 @@ def test_sweep_reads_the_newest_close_when_a_resumed_session_closed_twice():
def test_sweep_never_expires_a_session_that_was_REOPENED_after_its_close():
"""Whether a unit is closed is decided by the newest of the lifecycle PAIR.
- A resumed session appends to the ledger it already had, so ``... closed ...
+ A resumed session appends to the crew log it already had, so ``... closed ...
opened ...`` is a legitimate file whose session is running RIGHT NOW. Reading
the newest close on its own calls it expired and deletes a live
conversation's log -- the same rule as "an open session is never touched",
@@ -641,7 +641,7 @@ def test_sweep_leaves_a_torn_tail_to_the_resume_repair():
def test_sweep_still_collects_a_unit_whose_segments_the_READER_refuses():
- """A ledger too damaged to read is still expired, and that is deliberate.
+ """A crew log too damaged to read is still expired, and that is deliberate.
Segment provenance is checked on the READ path: a filename whose declared
first seq disagrees with the file's first entry makes ``iter_from`` raise
@@ -650,7 +650,7 @@ def test_sweep_still_collects_a_unit_whose_segments_the_READER_refuses():
still collectable.
That is the wanted behaviour, not a gap the sweep should close by borrowing
- the reader's check. Gating removal on readability would make a damaged ledger
+ the reader's check. Gating removal on readability would make a damaged crew log
IMMORTAL: the one unit nothing can use would be the one unit retention could
never reclaim, and the corruption would be preserved forever by the very rule
meant to protect history. The sweep's own guards do not depend on the entries
@@ -664,7 +664,7 @@ def test_sweep_still_collects_a_unit_whose_segments_the_READER_refuses():
# A second segment whose header is genuinely this unit's -- so the header half
# of the check passes -- but whose filename claims a first seq its own first
# entry does not carry.
- (directory / "ledger.9.jsonl").write_bytes((directory / "ledger.jsonl").read_bytes())
+ (directory / "log.9.jsonl").write_bytes((directory / "log.jsonl").read_bytes())
reader = lg.Ledger.open(lg.KIND_SESSION, SESSION)
with pytest.raises(lg.LedgerError) as refused:
@@ -677,13 +677,13 @@ def test_sweep_still_collects_a_unit_whose_segments_the_READER_refuses():
def test_sweep_never_scans_crew_ledgers():
- """Crew ledgers are out of scope: no writer, and no close to age from.
+ """Crew logs are out of scope: no writer, and no close to age from.
- Pinned with a crew ledger carrying a ``session/closed`` line WRITTEN DIRECTLY
+ Pinned with a crew log carrying a ``session/closed`` line WRITTEN DIRECTLY
to the file, aged past the cutoff. It has to be planted rather than appended,
- because a crew ledger cannot own a ``session`` type through the API
+ because a crew log cannot own a ``session`` type through the API
(``event_type_not_owned``) -- and that is exactly the case scoping must answer:
- this tree is agent-writable, so "no crew ledger can contain that entry" is a
+ this tree is agent-writable, so "no crew log can contain that entry" is a
property of the writer, not of the bytes. Without the scoping such a unit
reads as an expired session and is removed.
"""
@@ -729,7 +729,7 @@ def test_sweep_skips_a_unit_whose_header_id_does_not_address_its_directory():
"src": "gateway",
"data": {"reason": "destroyed"},
}
- (plant / "ledger.jsonl").write_text(
+ (plant / "log.jsonl").write_text(
json.dumps(header, separators=(",", ":"), sort_keys=True)
+ "\n"
+ json.dumps(aged, separators=(",", ":"), sort_keys=True)
@@ -740,7 +740,7 @@ def test_sweep_skips_a_unit_whose_header_id_does_not_address_its_directory():
assert store.sweep_expired(30) == (0, 0)
assert live_path.exists()
assert Ledger.exists(lg.KIND_SESSION, "s-live")
- assert (plant / "ledger.jsonl").exists()
+ assert (plant / "log.jsonl").exists()
def test_sweep_skips_a_unit_a_writer_still_owns_and_removes_its_neighbour():
@@ -793,7 +793,7 @@ def test_sweep_refuses_a_linked_session_root_and_reads_nothing_under_it(tmp_path
kind_root = lg.ledger_root(lg.KIND_SESSION)
kind_root.rename(elsewhere)
kind_root.symlink_to(elsewhere, target_is_directory=True)
- planted = elsewhere / _store_name("s-outside") / "ledger.jsonl"
+ planted = elsewhere / _store_name("s-outside") / "log.jsonl"
assert planted.exists(), "fixture did not plant a readable unit under the link"
assert store.sweep_expired(30) == (0, 0), "the walk ran under a linked root"
@@ -804,7 +804,7 @@ def test_sweep_writes_nothing_into_a_ledger_it_keeps():
"""Removal is not rotation: no tombstone, no ``pruned`` entry, ever.
A citation into a removed unit is already answered by ``Ref.resolve``, which
- reports ``gone`` for a pointer into a unit that has no ledger at all.
+ reports ``gone`` for a pointer into a unit that has no crew log at all.
"""
ledger = _open_session(age_days=400)
path = ledger.path
@@ -842,9 +842,9 @@ def test_history_archive_cleanup_honours_the_disable_for_ledgers_too(monkeypatch
def test_history_archive_cleanup_sweeps_ledgers_with_no_archive_directory(monkeypatch):
- """An absent archive dir is not a reason to skip the ledger half.
+ """An absent archive dir is not a reason to skip the crew log half.
- A session holds a ledger long before anything of its transcript is archived,
+ A session holds a crew log long before anything of its transcript is archived,
so an early return there would leave that half uncollected until the first
archive was ever written.
"""
@@ -863,17 +863,17 @@ def test_a_failing_ledger_sweep_never_breaks_the_transcript_archive(monkeypatch)
"""The caller is on the archive path: raising here would lose history.
Retaining too much is a disk-space problem; failing to archive the transcript
- loses the record, so the ledger half is contained.
+ loses the record, so the crew log half is contained.
"""
from kiro_crew import history
monkeypatch.setattr(history, "_last_cleanup", 0.0)
def _boom(*_args, **_kwargs):
- raise RuntimeError("ledger tree unreadable")
+ raise RuntimeError("crew log tree unreadable")
monkeypatch.setattr(store, "sweep_expired", _boom)
- # Returns the archive count without propagating the ledger failure.
+ # Returns the archive count without propagating the crew log failure.
assert history._cleanup_old_archives(retention_days=30) == 0
@@ -954,7 +954,7 @@ def factory(session_key=None, agent=None, channel_id=None, **kwargs):
def _newest_lifecycle_type(unit_id: str) -> str:
"""The type of the newest ``session/opened``/``session/closed`` in the unit."""
- path = _unit_dir(lg.KIND_SESSION, unit_id) / "ledger.jsonl"
+ path = _unit_dir(lg.KIND_SESSION, unit_id) / "log.jsonl"
newest = ""
for line in path.read_text(encoding="utf-8").splitlines():
try:
@@ -979,14 +979,14 @@ async def test_destroying_a_session_records_the_teardown_in_its_ledger(monkeypat
Driven through the REAL ``destroy`` rather than a stub. A mocked teardown that
omits the emit is exactly how this defect stayed invisible: every removal test
- built its ledger with ``Ledger.create``, which leaves nothing holding the
+ built its crew log with ``Ledger.create``, which leaves nothing holding the
unit, so they were green while the gateway could not collect a real one.
"""
- from kiro_crew import session_ledger_emit as emit
from kiro_crew.config import KiroCrewConfig
+ from kiro_crew.crew_log import emit
from kiro_crew.session import SessionManager
- monkeypatch.setenv(emit.SESSION_LEDGER_ENV, "1")
+ monkeypatch.setenv(emit.CREW_LOG_ENV, "1")
emit.reset_caches()
try:
cfg = KiroCrewConfig()
@@ -1017,11 +1017,11 @@ async def test_a_destroyed_sessions_ledger_is_then_collectable_by_the_sweep(monk
refused by a lease nobody released, and the sweep skipping a unit that reads
as open. A test on the entry's presence would prove neither.
"""
- from kiro_crew import session_ledger_emit as emit
from kiro_crew.config import KiroCrewConfig
+ from kiro_crew.crew_log import emit
from kiro_crew.session import SessionManager
- monkeypatch.setenv(emit.SESSION_LEDGER_ENV, "1")
+ monkeypatch.setenv(emit.CREW_LOG_ENV, "1")
emit.reset_caches()
try:
cfg = KiroCrewConfig()
@@ -1034,7 +1034,7 @@ async def test_a_destroyed_sessions_ledger_is_then_collectable_by_the_sweep(monk
assert emit.flush(timeout=5.0)
# Age the close the sweep reads, the same way the fixtures above do.
- path = _unit_dir(lg.KIND_SESSION, "acp-aged") / "ledger.jsonl"
+ path = _unit_dir(lg.KIND_SESSION, "acp-aged") / "log.jsonl"
lines = path.read_text(encoding="utf-8").splitlines()
for index in range(len(lines) - 1, -1, -1):
entry = json.loads(lines[index])
@@ -1113,7 +1113,7 @@ def test_a_close_that_does_not_end_the_ids_life_is_never_collected(reason):
keeps the conversation writes this close while LEAVING the old id mapped --
still resumable, and its log still needed. ``discarded`` clears the sid
unconditionally and would qualify on that test, but no path writes it into a
- ledger today, so admitting it would be a rule about a file nothing produces.
+ crew log today, so admitting it would be a rule about a file nothing produces.
A shutdown, a crash, an eviction and an unknown spelling all leave the id
mapped too. Retaining costs disk; deleting one of these destroys a live
conversation's history.
@@ -1128,7 +1128,7 @@ def test_a_close_that_does_not_end_the_ids_life_is_never_collected(reason):
def test_a_valid_empty_session_map_cannot_authorize_collecting_a_reset_closed_unit():
"""The exact lever the review found, pinned shut.
- ``session_map.json`` is agent-WRITABLE while the ledger tree is bind-masked, and
+ ``session_map.json`` is agent-WRITABLE while the crew log tree is bind-masked, and
a VALID empty map is not a failed read: it reads as "no session is revivable",
which is a positive answer that would authorize a trusted sweep to delete a
fenced unit the writer cannot touch directly. So nothing outside the fence takes
@@ -1183,7 +1183,7 @@ def test_the_sweep_reads_no_file_outside_the_ledger_tree(monkeypatch):
tree is bind-masked, and a VALID empty map is not a failed read -- it reads as
"nothing is revivable" and hands the trusted sweep a positive answer that
authorizes deleting a fenced unit. This test fails if any read reaches outside
- the ledger root again, which is the only way that lever comes back.
+ the crew log root again, which is the only way that lever comes back.
"""
root = lg.ledger_root(lg.KIND_SESSION).resolve()
ledger = _closed_session(closed_days_ago=90)
@@ -1204,7 +1204,7 @@ def _record_open(file, *args, **kwargs):
assert store.sweep_expired(30) == (1, 0)
strays = [path for path in opened if not path.startswith(str(root))]
- assert strays == [], f"the sweep read outside the ledger tree: {strays}"
+ assert strays == [], f"the sweep read outside the crew log tree: {strays}"
# --- the marker asserts REVOCATION COMPLETED, not merely "a destroy ran" ---
@@ -1212,7 +1212,7 @@ def _record_open(file, *args, **kwargs):
def _newest_close_reason(unit_id: str) -> str:
"""The reason on the newest ``session/closed`` in the unit."""
- path = _unit_dir(lg.KIND_SESSION, unit_id) / "ledger.jsonl"
+ path = _unit_dir(lg.KIND_SESSION, unit_id) / "log.jsonl"
reason = ""
for line in path.read_text(encoding="utf-8").splitlines():
try:
@@ -1228,16 +1228,16 @@ def _newest_close_reason(unit_id: str) -> str:
async def test_a_destroy_that_leaves_another_mapping_writes_a_NON_terminal_reason(monkeypatch):
"""One map key is deleted, so a second key on the same sid still resolves it.
- The ledger unit is keyed by the ACP id, so that other holder shares this very
+ The crew log unit is keyed by the ACP id, so that other holder shares this very
log and can resume it. ``destroyed`` claims the id is globally revoked, so it is
withheld here and the unit stays uncollectable -- retention prefers keeping a
log it cannot prove is dead.
"""
- from kiro_crew import session_ledger_emit as emit
from kiro_crew.config import KiroCrewConfig
+ from kiro_crew.crew_log import emit
from kiro_crew.session import SessionManager
- monkeypatch.setenv(emit.SESSION_LEDGER_ENV, "1")
+ monkeypatch.setenv(emit.CREW_LOG_ENV, "1")
emit.reset_caches()
try:
cfg = KiroCrewConfig()
@@ -1266,11 +1266,11 @@ async def test_a_destroy_that_leaves_another_mapping_writes_a_NON_terminal_reaso
@pytest.mark.asyncio
async def test_an_unreadable_map_also_withholds_the_terminal_reason(monkeypatch):
"""An unreadable map is not evidence of revocation, so the claim is withheld."""
- from kiro_crew import session_ledger_emit as emit
from kiro_crew.config import KiroCrewConfig
+ from kiro_crew.crew_log import emit
from kiro_crew.session import SessionManager
- monkeypatch.setenv(emit.SESSION_LEDGER_ENV, "1")
+ monkeypatch.setenv(emit.CREW_LOG_ENV, "1")
emit.reset_caches()
try:
cfg = KiroCrewConfig()
@@ -1300,11 +1300,11 @@ async def test_a_session_opened_after_a_destroy_makes_the_unit_uncollectable_aga
as a live conversation whatever the close said. Anyone who plants a mapping and
resumes therefore causes the log to be KEPT, not deleted.
"""
- from kiro_crew import session_ledger_emit as emit
from kiro_crew.config import KiroCrewConfig
+ from kiro_crew.crew_log import emit
from kiro_crew.session import SessionManager
- monkeypatch.setenv(emit.SESSION_LEDGER_ENV, "1")
+ monkeypatch.setenv(emit.CREW_LOG_ENV, "1")
emit.reset_caches()
try:
cfg = KiroCrewConfig()
diff --git a/test/test_ledger_types.py b/test/test_crew_log_types.py
similarity index 96%
rename from test/test_ledger_types.py
rename to test/test_crew_log_types.py
index 02bed24c7939..4bc36bfb3136 100644
--- a/test/test_ledger_types.py
+++ b/test/test_crew_log_types.py
@@ -3,7 +3,7 @@
Three claims, and they are separate on purpose. The registry must accept every
entry a real WRITER produces (the emitter and the crash-repair closers), it must
refuse each way a payload can be wrong, and it must leave an undeclared type
-alone -- which is what keeps the crew ledger and every guest namespace writable
+alone -- which is what keeps the crew log and every guest namespace writable
while the session families are checked.
"""
@@ -17,24 +17,24 @@
import pytest
-from kiro_crew import session_ledger_emit as emit
-from kiro_crew.ledger import (
+from kiro_crew.crew_log import (
CODE_BAD_DATA_FIELD,
SESSION_ENTRY_TYPES,
Ledger,
LedgerError,
declaration_for,
+ emit,
)
-from kiro_crew.ledger import entry_types as reg
-from kiro_crew.ledger import (
+from kiro_crew.crew_log import entry_types as reg
+from kiro_crew.crew_log import (
ledger_path,
render_markdown,
)
-from kiro_crew.ledger import store as store_mod
-from kiro_crew.ledger import (
+from kiro_crew.crew_log import store as store_mod
+from kiro_crew.crew_log import (
validate_data,
)
-from kiro_crew.ledger.store import (
+from kiro_crew.crew_log.store import (
STOP_REASON_INTERRUPTED,
TOOL_STATUS_UNKNOWN,
_closer_entries,
@@ -139,7 +139,7 @@
@pytest.fixture(autouse=True)
def _isolated_home(tmp_path, monkeypatch):
monkeypatch.setenv("KIROCREW_HOME", str(tmp_path / "home"))
- monkeypatch.setenv(emit.SESSION_LEDGER_ENV, "1")
+ monkeypatch.setenv(emit.CREW_LOG_ENV, "1")
emit.reset_caches()
yield
emit.drain_for_shutdown(timeout=2.0)
@@ -387,7 +387,7 @@ def test_a_token_mapping_is_required_whole_but_only_once_it_is_there():
@pytest.mark.parametrize(
("kind", "entry_type"),
[
- # A crew ledger's own families: no crew emitter exists, so nothing is
+ # A crew log's own families: no crew emitter exists, so nothing is
# declared and a crew write must not be blocked by this registry.
("crew", "member/joined"),
("crew", "activity/tick"),
@@ -405,7 +405,7 @@ def test_an_undeclared_type_is_not_validated(kind, entry_type):
def test_a_session_type_is_not_declared_for_a_crew_ledger():
- # The registry is per KIND. A crew ledger cannot hold `turn/started` at all --
+ # The registry is per KIND. A crew log cannot hold `turn/started` at all --
# ownership refuses it first -- so declaring it there would be a shape for a
# write that never happens.
assert declaration_for("crew", "turn/started") is None
@@ -621,7 +621,7 @@ def test_the_markdown_dump_marks_the_sampled_types():
def test_the_markdown_dump_is_empty_for_a_kind_with_no_declarations():
- assert render_markdown("crew").strip() == "# Declared `crew` ledger entry types"
+ assert render_markdown("crew").strip() == "# Declared `crew` crew log entry types"
def test_the_cli_prints_the_tables_and_refuses_anything_else(capsys):
@@ -632,7 +632,7 @@ def test_the_cli_prints_the_tables_and_refuses_anything_else(capsys):
def test_the_module_runs_as_a_command():
- # `python -m kiro_crew.ledger.entry_types --markdown` is the documented form,
+ # `python -m kiro_crew.crew_log.entry_types --markdown` is the documented form,
# so the module has to be importable AS a script and not only as a library.
root = Path(__file__).resolve().parents[1]
# The venv this suite runs under may have ``kiro_crew`` installed from a
@@ -641,7 +641,7 @@ def test_the_module_runs_as_a_command():
env = dict(os.environ)
env["PYTHONPATH"] = str(root / "src")
result = subprocess.run(
- [sys.executable, "-m", "kiro_crew.ledger.entry_types", "--markdown"],
+ [sys.executable, "-m", "kiro_crew.crew_log.entry_types", "--markdown"],
cwd=root,
env=env,
capture_output=True,
@@ -651,7 +651,7 @@ def test_the_module_runs_as_a_command():
check=False,
)
assert result.returncode == 0, result.stderr
- assert "# Declared `session` ledger entry types" in result.stdout
+ assert "# Declared `session` crew log entry types" in result.stdout
# --- the declarations are well formed ------------------------------------
diff --git a/test/test_docs_ledger_reference.py b/test/test_docs_crew_log_reference.py
similarity index 95%
rename from test/test_docs_ledger_reference.py
rename to test/test_docs_crew_log_reference.py
index 9b05af79ac74..cc80161e2ec3 100644
--- a/test/test_docs_ledger_reference.py
+++ b/test/test_docs_crew_log_reference.py
@@ -1,4 +1,4 @@
-"""The ledger reference documents types the code actually owns, with valid examples.
+"""The crew log reference documents types the code actually owns, with valid examples.
An API reference drifts silently: a type is renamed in ``schema.TYPE_OWNERSHIP`` and
the page that documents it keeps its old spelling, or an example is hand-edited into
@@ -35,7 +35,7 @@
import pytest
-from kiro_crew.ledger.schema import (
+from kiro_crew.crew_log.schema import (
KIND_SESSION,
MAX_ENTRY_BYTES,
MAX_REF_SPAN,
@@ -47,9 +47,9 @@
serialize,
split_type,
)
-from kiro_crew.ledger.store import DEFAULT_PAGE_LIMIT, MAX_PAGE_LIMIT
+from kiro_crew.crew_log.store import DEFAULT_PAGE_LIMIT, MAX_PAGE_LIMIT
-_DOCS = Path(__file__).parent.parent / "docs" / "reference" / "ledger"
+_DOCS = Path(__file__).parent.parent / "docs" / "reference" / "crew-log"
SESSION_TYPES_DOC = _DOCS / "session-types.md"
#: A live type's subsection heading: ``### `domain/action` ``.
@@ -144,7 +144,7 @@ def test_example_type_is_documented_on_this_page(block: str) -> None:
def test_session_examples_carry_no_crew_only_envelope_fields(block: str) -> None:
"""Session entries never thread, and no session emitter cites a ref."""
raw = json.loads(block)
- assert "thread" not in raw, "thread is the crew ledger's shape"
+ assert "thread" not in raw, "thread is the crew's log shape"
assert "ref" not in raw, "no session emitter sets ref"
@@ -154,7 +154,7 @@ def test_session_examples_name_only_a_session_emitter(block: str) -> None:
``check_ownership`` accepts any fixed source for any kind, so ``dashboard`` or
``patrol`` on a session entry passes the writer's gates while naming an emitter
- that writes to crew ledgers. That makes it precisely the mistake a reference
+ that writes to crew logs. That makes it precisely the mistake a reference
page can carry without anything catching it, so the page is pinned here.
"""
assert json.loads(block)["src"] in SESSION_SOURCES
@@ -228,14 +228,14 @@ def _emit_functions_called_in_the_tree() -> frozenset[str]:
root = Path(__file__).parent.parent / "src" / "kiro_crew"
called: set[str] = set()
for path in root.rglob("*.py"):
- if path.name == "session_ledger_emit.py":
+ if path.parent.name == "crew_log" and path.name == "emit.py":
continue
try:
text = path.read_text(encoding="utf-8", errors="replace")
except OSError: # pragma: no cover - unreadable file is not this test's subject
continue
# Cheap guard first: almost no file mentions the emitter at all.
- if "session_ledger_emit" not in text:
+ if "crew_log_emit" not in text:
continue
called.update(re.findall(r"\b(on_[a-z_]+)\s*\(", text))
return frozenset(called)
diff --git a/test/test_remove_slot_for_history_key.py b/test/test_remove_slot_for_history_key.py
index 2060c35636ae..0c56b704873e 100644
--- a/test/test_remove_slot_for_history_key.py
+++ b/test/test_remove_slot_for_history_key.py
@@ -3201,7 +3201,7 @@ def _ledger(session_id: str, slot: str = "dashboard_chat-1-100"):
ledger tree. A fixture with no slot is a unit the funnel must refuse, which
is what the two tests below use it for.
"""
- from kiro_crew import ledger as lg
+ from kiro_crew import crew_log as lg
return lg.Ledger.create(
lg.KIND_SESSION, session_id, owner="default", agent="kirocrew", slot=slot
@@ -3209,7 +3209,7 @@ def _ledger(session_id: str, slot: str = "dashboard_chat-1-100"):
@staticmethod
def _exists(session_id: str) -> bool:
- from kiro_crew import ledger as lg
+ from kiro_crew import crew_log as lg
return lg.Ledger.exists(lg.KIND_SESSION, session_id)
@@ -3263,20 +3263,20 @@ async def test_a_ledger_the_emitter_itself_opened_is_still_removed(self, monkeyp
``destroy`` does, and a stub that omitted it would be testing a gateway
that does not exist -- which is precisely how this defect stayed
invisible. ``destroy``'s own emit is pinned separately, driven through the
- real method, in ``test_ledger_retention.py``.
+ real method, in ``test_crew_log_retention.py``.
The pre-assertion is the point of the test. Asserting only that the ledger
is gone would pass against a fixture that never held the lease, which is
exactly how the rest of this class was green while the funnel could not
remove a real one.
"""
- from kiro_crew import ledger as lg
- from kiro_crew import session_ledger_emit as emit
- from kiro_crew.ledger.store import REMOVE_OWNED, remove_unit
+ from kiro_crew import crew_log as lg
+ from kiro_crew.crew_log import emit
+ from kiro_crew.crew_log.store import REMOVE_OWNED, remove_unit
from kiro_crew.metrics.sessions import END_REASON_DESTROYED
_guard_work_ledger_cleanup(monkeypatch)
- monkeypatch.setenv(emit.SESSION_LEDGER_ENV, "1")
+ monkeypatch.setenv(emit.CREW_LOG_ENV, "1")
emit.reset_caches()
try:
emit.on_session_opened(
@@ -3321,11 +3321,11 @@ async def test_the_teardown_entry_never_starts_a_ledger_for_a_session_without_on
assertion would pass either way. Refusing the removal is the one reading
where the two diverge.
"""
- from kiro_crew import session_ledger_emit as emit
- from kiro_crew.ledger import store as ledger_store
+ from kiro_crew.crew_log import emit
+ from kiro_crew.crew_log import store as ledger_store
_guard_work_ledger_cleanup(monkeypatch)
- monkeypatch.setenv(emit.SESSION_LEDGER_ENV, "1")
+ monkeypatch.setenv(emit.CREW_LOG_ENV, "1")
monkeypatch.setattr(
ledger_store, "remove_unit", lambda *_a, **_k: ledger_store.REMOVE_OWNED
)
@@ -3377,7 +3377,7 @@ async def test_a_ledger_with_no_slot_in_its_header_is_left_to_retention(self, mo
landed.
"""
_guard_work_ledger_cleanup(monkeypatch)
- from kiro_crew import ledger as lg
+ from kiro_crew import crew_log as lg
lg.Ledger.create(lg.KIND_SESSION, "acp-slotless", owner="default", agent="kirocrew")
slot = _make_slot("dashboard_chat-1-100")
@@ -3563,7 +3563,7 @@ async def test_a_failing_ledger_removal_never_fails_the_delete(self, monkeypatch
state = _make_state({"dashboard_chat-1-100": slot})
state.sessions.resumable_sid = MagicMock(return_value="acp-explodes")
- from kiro_crew.ledger import store as ledger_store
+ from kiro_crew.crew_log import store as ledger_store
def _boom(*_args, **_kwargs):
raise RuntimeError("ledger tree unreadable")
diff --git a/test/test_sandbox_absent_ceiling_seal.py b/test/test_sandbox_absent_ceiling_seal.py
index fd5f5e8a8a8b..84ab765e95db 100644
--- a/test/test_sandbox_absent_ceiling_seal.py
+++ b/test/test_sandbox_absent_ceiling_seal.py
@@ -687,13 +687,13 @@ def test_an_existing_directory_is_left_alone_and_not_reported(self, crew_home):
def test_an_absent_ledgers_root_is_materialized_before_the_mask_binds(self, crew_home, mode):
"""The sharpest case of this whole class, named on its own.
- A ledger is the authority a reader trusts instead of re-deriving, and the
+ A crew log is the authority a reader trusts instead of re-deriving, and the
store creates this root on its first write. Absent, the ``isdir`` guard
skips it and the mask is vacuous for the life of every sandbox spawned
first -- one of which can then create the directory itself and fill it with
entries attributed to the gateway.
"""
- root = crew_home / "ledgers"
+ root = crew_home / "crew-log"
assert not root.exists(), "the point of the test is that it starts absent"
created = sandbox._materialize_maskable_dirs()
diff --git a/test/test_session.py b/test/test_session.py
index 0ed196ec1ba0..ffa09527efcf 100644
--- a/test/test_session.py
+++ b/test/test_session.py
@@ -5704,11 +5704,11 @@ async def test_a_deferred_verdict_records_the_compaction_when_it_settles(
unknown mid-turn -- would settle here and be recorded nowhere, so the
ledger would be missing exactly the compactions that were hardest to
measure."""
- from kiro_crew import session_ledger_emit
+ from kiro_crew.crew_log import emit as crew_log_emit
seen: list[tuple[float, float]] = []
monkeypatch.setattr(
- session_ledger_emit,
+ crew_log_emit,
"on_compaction_applied",
lambda sid, *, pct_before, pct_after: seen.append((pct_before, pct_after)),
)
diff --git a/test/test_session_control.py b/test/test_session_control.py
index b1fdde320a9d..c9b0a3715320 100644
--- a/test/test_session_control.py
+++ b/test/test_session_control.py
@@ -484,17 +484,17 @@ async def test_a_requeued_steer_records_queued_and_never_steered(tmp_path, monke
message, so this is the only place that can record it at all.
"""
monkeypatch.setenv("KIROCREW_HOME", str(tmp_path / "home"))
- monkeypatch.setenv("KIROCREW_SESSION_LEDGER", "1")
+ monkeypatch.setenv("KIROCREW_CREW_LOG", "1")
import json
- from kiro_crew import ledger as lg
- from kiro_crew import session_ledger_emit
+ from kiro_crew import crew_log as lg
+ from kiro_crew.crew_log import emit as crew_log_emit
- session_ledger_emit.reset_caches()
+ crew_log_emit.reset_caches()
sid = "sess-steer-requeue"
- session_ledger_emit.on_session_opened(sid, agent="kirocrew", slot="chat-1")
- session_ledger_emit.on_turn_started(sid, 1, "user")
- assert session_ledger_emit.flush()
+ crew_log_emit.on_session_opened(sid, agent="kirocrew", slot="chat-1")
+ crew_log_emit.on_turn_started(sid, 1, "user")
+ assert crew_log_emit.flush()
state = _make_state(tmp_path)
slot = _busy(_slot(state, "chat-1"))
@@ -515,7 +515,7 @@ async def _steer(msg):
outcome = await cd.steer_into_running_turn(state, slot, "run this instead")
assert outcome == cd.STEER_REQUEUED
- assert session_ledger_emit.flush()
+ assert crew_log_emit.flush()
body = [
json.loads(line)
for line in lg.ledger_path("session", sid).read_text(encoding="utf-8").splitlines()[1:]
@@ -526,7 +526,7 @@ async def _steer(msg):
assert len(mine) == 1, f"expected one entry for one message, got {[e['type'] for e in mine]}"
assert mine[0]["type"] == "message/queued"
assert mine[0]["data"]["source"] == "steer"
- session_ledger_emit.reset_caches()
+ crew_log_emit.reset_caches()
@pytest.mark.asyncio
@@ -3928,7 +3928,7 @@ def test_the_delivery_path_never_claims_a_turn_consumed_a_steer(tmp_path, monkey
Mutation guard: recording the delivered case here -- from a live ordinal or any
other guess -- reddens this.
"""
- from kiro_crew import session_ledger_emit
+ from kiro_crew.crew_log import emit as crew_log_emit
from kiro_crew.dashboard import chat_delivery
state = _make_state(tmp_path)
@@ -3938,19 +3938,19 @@ def test_the_delivery_path_never_claims_a_turn_consumed_a_steer(tmp_path, monkey
appended: list[str] = []
queued_for: list[str] = []
- monkeypatch.setattr(session_ledger_emit, "session_id_of", lambda _client: "acp-1")
+ monkeypatch.setattr(crew_log_emit, "session_id_of", lambda _client: "acp-1")
# Spied on the shared write seam rather than on one entry point, so an entry
# written under ANY type is caught rather than only a steer-shaped one.
monkeypatch.setattr(
- session_ledger_emit,
+ crew_log_emit,
"_write",
lambda _sid, entry_type, *a, **kw: appended.append(entry_type),
)
monkeypatch.setattr(
- session_ledger_emit, "on_message_queued", lambda sid, **_kw: queued_for.append(sid)
+ crew_log_emit, "on_message_queued", lambda sid, **_kw: queued_for.append(sid)
)
# A turn IS running, so a guess would have had something plausible to record.
- monkeypatch.setattr(session_ledger_emit, "live_turn", lambda _sid: 13)
+ monkeypatch.setattr(crew_log_emit, "live_turn", lambda _sid: 13)
def _consume_inside_the_rpc(*_a, **_kw):
# The running turn takes the registration, which is what makes the
@@ -3979,7 +3979,7 @@ def test_a_stop_race_that_only_expects_a_requeue_records_nothing(tmp_path, monke
Mutation guard: recording the queued outcome here reddens this.
"""
- from kiro_crew import session_ledger_emit
+ from kiro_crew.crew_log import emit as crew_log_emit
from kiro_crew.dashboard import chat_delivery
state = _make_state(tmp_path)
@@ -3988,10 +3988,8 @@ def test_a_stop_race_that_only_expects_a_requeue_records_nothing(tmp_path, monke
slot._acp_client = _steerable(accepted=True)
queued: list[str] = []
- monkeypatch.setattr(session_ledger_emit, "session_id_of", lambda _client: "acp-1")
- monkeypatch.setattr(
- session_ledger_emit, "on_message_queued", lambda sid, **_kw: queued.append(sid)
- )
+ monkeypatch.setattr(crew_log_emit, "session_id_of", lambda _client: "acp-1")
+ monkeypatch.setattr(crew_log_emit, "on_message_queued", lambda sid, **_kw: queued.append(sid))
def _stop_without_requeueing(*_a, **_kw):
# A stop lands while the steer is still registered, and nothing has moved
@@ -4020,7 +4018,7 @@ def test_a_requeued_steer_is_recorded_as_a_queued_message(tmp_path, monkeypatch)
Mutation guard: recording `send_id` reddens this, because the two differ here.
"""
- from kiro_crew import session_ledger_emit
+ from kiro_crew.crew_log import emit as crew_log_emit
from kiro_crew.dashboard import chat_delivery
state = _make_state(tmp_path)
@@ -4029,9 +4027,9 @@ def test_a_requeued_steer_is_recorded_as_a_queued_message(tmp_path, monkeypatch)
slot._acp_client = _steerable(accepted=True)
queued: list[dict] = []
- monkeypatch.setattr(session_ledger_emit, "session_id_of", lambda _client: "acp-1")
+ monkeypatch.setattr(crew_log_emit, "session_id_of", lambda _client: "acp-1")
monkeypatch.setattr(
- session_ledger_emit, "on_message_queued", lambda sid, **kw: queued.append(dict(kw))
+ crew_log_emit, "on_message_queued", lambda sid, **kw: queued.append(dict(kw))
)
seen: dict[str, str] = {}
diff --git a/test/test_steer_requeue.py b/test/test_steer_requeue.py
index a343b41285b8..deeb87d8a696 100644
--- a/test/test_steer_requeue.py
+++ b/test/test_steer_requeue.py
@@ -241,11 +241,11 @@ def test_no_site_writes_a_steer_entry(self, tmp_path, monkeypatch):
without one. Adding an emitter back at either site, without a resolver that
owns both facts, reddens this test.
"""
- from kiro_crew import session_ledger_emit
+ from kiro_crew.crew_log import emit as crew_log_emit
from kiro_crew.dashboard.chat_runner import _settle_consumed_steers
assert not [
- name for name in dir(session_ledger_emit) if "steer" in name.lower()
+ name for name in dir(crew_log_emit) if "steer" in name.lower()
], "the emitter exposes a steer entry point, which no site can order correctly"
monkeypatch.setattr("kiro_crew.dashboard.state.config_dir", lambda: tmp_path)
@@ -256,15 +256,13 @@ def test_no_site_writes_a_steer_entry(self, tmp_path, monkeypatch):
slot._acp_client = MagicMock()
appended: list[tuple] = []
- monkeypatch.setattr(session_ledger_emit, "session_id_of", lambda _c: "acp-1")
- monkeypatch.setattr(
- session_ledger_emit, "_write", lambda *a, **kw: appended.append((a, kw))
- )
+ monkeypatch.setattr(crew_log_emit, "session_id_of", lambda _c: "acp-1")
+ monkeypatch.setattr(crew_log_emit, "_write", lambda *a, **kw: appended.append((a, kw)))
_settle_consumed_steers(slot, "\nfix the bug\n", state)
assert slot._pending_steers == ["late arrival"], "settling itself still works"
- assert appended == [], "the echo wrote a ledger entry it cannot order"
+ assert appended == [], "the echo wrote a crew log entry it cannot order"
def test_snapshot_settles_only_contained_steers(self, tmp_path, monkeypatch):
from kiro_crew.dashboard.chat_runner import _settle_consumed_steers