Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions config-baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -1846,6 +1846,9 @@
"history_max_days": 365,
"backup_enabled": true,
"backup_keep": 7,
"persistence_enabled": true,
"inject_memory": true,
"inject_lessons": true,
"migrated": false
}
},
Expand Down Expand Up @@ -2204,6 +2207,48 @@
"enumValues": null,
"defaultValue": 7
},
{
"path": "memory.persistence_enabled",
"kind": "core",
"type": "boolean",
"required": false,
"deprecated": false,
"sensitive": false,
"tags": [],
"label": "Persistence Enabled",
"help": "Global switch for persistent memory. Off: no automatic memory writes (lessons, consolidation extraction, task-runner lessons) and no stored memory/lessons injected into new sessions; within-conversation context is unaffected. Explicit dashboard edits and deletions stay available. An installed app's own ingestion sweep is out of scope and still writes app-scoped rows.",
"hasChildren": false,
"enumValues": null,
"defaultValue": true
},
{
"path": "memory.inject_memory",
"kind": "core",
"type": "boolean",
"required": false,
"deprecated": false,
"sensitive": false,
"tags": [],
"label": "Inject Memory Context",
"help": "Inject the stored memory block (preferences, the memory activity index and recent-session snippets) into new-session context. On-demand memory_recall is unaffected.",
"hasChildren": false,
"enumValues": null,
"defaultValue": true
},
{
"path": "memory.inject_lessons",
"kind": "core",
"type": "boolean",
"required": false,
"deprecated": false,
"sensitive": false,
"tags": [],
"label": "Inject Lessons Context",
"help": "Inject the learned-corrections and user-profile blocks into new-session context.",
"hasChildren": false,
"enumValues": null,
"defaultValue": true
},
{
"path": "memory.migrated",
"kind": "core",
Expand Down
8 changes: 7 additions & 1 deletion docs/system-specs/modules/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -1894,6 +1894,9 @@ class MemoryConfig:
embed_model_legacy_ids: list[str] = field(default_factory=list) # managed compatibility labels retained across restarts; explicit model apply clears them and rebuilds inherited vectors
history_idle_hours: float = 3.0 # consolidate history after N hours idle
history_max_days: int = 365 # prune daily history files older than this
persistence_enabled: bool = True # global switch: off = no automatic memory writes (lessons, consolidation, task-runner) AND no stored memory/lessons injected
inject_memory: bool = True # inject the stored memory block (preferences, activity index, recent-session snippets) into new-session context
inject_lessons: bool = True # inject the [Learned corrections] + [USER PROFILE] blocks into new-session context

@dataclass
class KnowledgeConfig:
Expand Down Expand Up @@ -2662,7 +2665,10 @@ Returns the effective config for a channel:
},
"memory": {
"history_idle_hours": 3.0,
"history_max_days": 365
"history_max_days": 365,
"persistence_enabled": true,
"inject_memory": true,
"inject_lessons": true
},
"knowledge": {
"auto_add_documents": false,
Expand Down
2 changes: 2 additions & 0 deletions docs/system-specs/modules/learn-cron-dashboard.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ Named-store lessons require a middleware-verified internal request or the dashbo

The `learn_add` MCP tool (backed by `POST /api/lessons`) is subject to session-scope checks in `dashboard/handlers/cron.py:api_lessons_create`:

0. Before any write proceeds, the global persistence switch is checked: `memory.persistence_enabled: false` refuses every create with HTTP 403 and an SEL `persistence_disabled` audit record, regardless of session mode. Enforced on the route so every transport that posts here (MCP tool, dashboard, direct HTTP) is covered by the one check; `GET /api/lessons` and `DELETE /api/lessons` are unaffected — reads and the right to forget survive the switch.

1. `X-Session-Key` header is required; missing → HTTP 400 `missing X-Session-Key`.
2. `dashboard:ui` (browser UI's static key) is always allowed.
3. Otherwise the slot name (portion after the `:` prefix, or the whole key) must satisfy at least one of:
Expand Down
14 changes: 14 additions & 0 deletions docs/system-specs/modules/memory-skills-hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,20 @@ larger than 8 MiB is refused without truncating or deleting it; editable-history
GET and PUT retain the existing `store_unavailable` (503) error response.
Ordinary V2 message context does not scan learned history.

Whether a group is in scope is the intersection of the caller-passed
`context_groups` (subagent narrowing) with the operator's config toggles —
`memory.inject_memory` / `memory.inject_lessons`, with
`memory.persistence_enabled` as the global switch — computed inside
`build_session_context()` so every surface (dashboard, channels, cron,
heartbeat, task runner, eval, subagents) obeys the config without passing
anything. The member-essentials builder and the post-compaction re-injection in
`build_message()` route through the same intersection, because each restores a
block the session-start build gates: reading the caller scope alone there would
hand back withheld memory for the rest of the session. The `[CONTEXT SCOPE]`
withheld-groups block stays keyed to the caller-passed value only: "your parent
withheld" describes per-spawn narrowing, not the operator's standing config
choice.

`MemoryStore.get_context()` retains `history_cap=25_000` as its default for
programmatic readers. V1 `ContextBuilder` calls it with the scaled history cap
when building fresh session context. V2 reads preference/project anchors without
Expand Down
16 changes: 14 additions & 2 deletions src/kiro_crew/cli_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -2457,11 +2457,23 @@ def _learn(args: argparse.Namespace) -> None:

jsonl_store = LessonStore()
cfg = KiroCrewConfig.load()
action = getattr(args, "learn_action", None)
# Global persistence switch (memory.persistence_enabled): the CLI writes to
# the store directly (no HTTP), so it carries its own check mirroring the
# POST /api/lessons refusal. Refused ahead of the vector store because
# constructing and init-ing it creates or migrates memory.db, which a
# refused write must not do; list and remove still need that store, so the
# check is scoped to the add action.
if action == "add" and not cfg.memory.persistence_enabled:
print(
"Lesson NOT saved: persistent memory is disabled "
"(memory.persistence_enabled is false). Re-enable with: "
"kirocrew config set memory.persistence_enabled true"
)
return
vs = VectorMemoryStore(embedding_dim=cfg.memory.embedding_dim)
vs.init()
try:
action = getattr(args, "learn_action", None)

if action == "add":
rule = args.rule
category = args.category
Expand Down
3 changes: 3 additions & 0 deletions src/kiro_crew/config/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -2945,6 +2945,9 @@ def _build_memory_config(memory_data: dict) -> MemoryConfig:
history_max_days=_safe_nonnegative_int(memory_data.get("history_max_days", 365), 365),
backup_enabled=_safe_bool(memory_data.get("backup_enabled", True), True),
backup_keep=_safe_int(memory_data.get("backup_keep", 7), 7, 1, None),
persistence_enabled=_safe_bool(memory_data.get("persistence_enabled", True), True),
inject_memory=_safe_bool(memory_data.get("inject_memory", True), True),
inject_lessons=_safe_bool(memory_data.get("inject_lessons", True), True),
migrated=memory_data.get("migrated", False),
)

Expand Down
28 changes: 28 additions & 0 deletions src/kiro_crew/config/sections.py
Original file line number Diff line number Diff line change
Expand Up @@ -2199,6 +2199,34 @@ class MemoryConfig:
"Values below 1 are treated as 1 so retention cannot empty the directory.",
),
)
persistence_enabled: bool = field(
default=True,
metadata=_meta(
"Persistence Enabled",
"Global switch for persistent memory. Off: no automatic memory "
"writes (lessons, consolidation extraction, task-runner lessons) "
"and no stored memory/lessons injected into new sessions; "
"within-conversation context is unaffected. Explicit dashboard "
"edits and deletions stay available. An installed app's own "
"ingestion sweep is out of scope and still writes app-scoped rows.",
),
)
inject_memory: bool = field(
default=True,
metadata=_meta(
"Inject Memory Context",
"Inject the stored memory block (preferences, the memory activity "
"index and recent-session snippets) into new-session context. "
"On-demand memory_recall is unaffected.",
),
)
inject_lessons: bool = field(
default=True,
metadata=_meta(
"Inject Lessons Context",
"Inject the learned-corrections and user-profile blocks into " "new-session context.",
),
)
migrated: bool = field(
default=False,
metadata=_meta("Migrated", "Whether memory has been migrated to vector store."),
Expand Down
77 changes: 71 additions & 6 deletions src/kiro_crew/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -1450,6 +1450,37 @@ def _group_included(groups: frozenset[str] | None, group: str) -> bool:
return groups is None or group in groups


def _config_scoped_groups(
context_groups: frozenset[str] | None, cfg: "KiroCrewConfig | None" = None
) -> frozenset[str] | None:
"""The caller-passed scope intersected with the operator's config toggles.

``memory.inject_memory`` / ``memory.inject_lessons`` (with
``memory.persistence_enabled`` as the global switch) withhold a group on
EVERY surface. Intersecting here — instead of at each call site — keeps a
new context entry point from silently escaping the config;
``build_session_context``, the v2 essentials builder and the
post-compaction re-injection all route through this.
Subagent narrowing is preserved: config can only remove groups from the
caller-passed scope, never add one back. Only the memory and lessons groups
are ever subtracted, so a project-group gate reads the caller scope
directly. The ``[CONTEXT SCOPE]`` block
stays keyed to the caller-passed value, because "your parent withheld"
describes per-spawn narrowing, not the operator's standing choice.
"""
if cfg is None:
cfg = KiroCrewConfig.load()
withheld: set[str] = set()
if not (cfg.memory.persistence_enabled and cfg.memory.inject_memory):
withheld.add(CONTEXT_GROUP_MEMORY)
if not (cfg.memory.persistence_enabled and cfg.memory.inject_lessons):
withheld.add(CONTEXT_GROUP_LESSONS)
if not withheld:
return context_groups
base = SWITCHABLE_CONTEXT_GROUPS if context_groups is None else context_groups
return frozenset(base) - withheld


def _build_context_scope_section(groups: frozenset[str] | None) -> str:
"""Name the groups a parent withheld, or ``""`` when nothing was withheld.

Expand Down Expand Up @@ -3346,6 +3377,21 @@ def _build_v2_essentials(
template = member_template or template
if not owner:
return ""
# Same config intersection as build_session_context: this builder is a
# second context entry point, so a group the operator disabled must be
# withheld here too rather than only on the main path.
#
# EXCEPT when profile_overrides is supplied. That argument makes this a
# VALIDATOR (_validate_private_profile_update), not a context build: the
# candidate profile is appended only under the memory-group gate below,
# and render_essentials' combined-budget refusal is what rejects a
# profile that fits per-file but overflows the combined cap. Scoping the
# groups here would drop that gate whenever injection is disabled, so an
# oversized profile would save and then break every later member build.
# A validation pass must see the complete candidate set regardless of
# what the operator currently injects.
if profile_overrides is None:
context_groups = _config_scoped_groups(context_groups)
reads = not blocks_reads and _group_included(context_groups, CONTEXT_GROUP_MEMORY)
identity = self._build_member_section(owner, strict=True, include_briefing=reads)
documents = documents_for_member(
Expand Down Expand Up @@ -3650,6 +3696,19 @@ def _mark(label: str) -> None:
# member capability gate below — one read per context build.
_cfg = KiroCrewConfig.load()

# Config-driven injection toggles (memory.inject_memory /
# memory.inject_lessons, with memory.persistence_enabled as the global
# switch): a group the operator disabled is withheld on EVERY surface —
# dashboard, channels, cron, heartbeat, task runner, eval, subagents —
# by intersecting here, the one method all context builds pass through,
# rather than at the eleven call sites that would each have to remember
# to pass ``context_groups``. The caller-passed ``context_groups`` keeps
# driving the [CONTEXT SCOPE] block below: its "Your parent withheld"
# prose describes subagent narrowing, and a config withholding is the
# operator's standing choice, not the parent's per-spawn one, so it is
# deliberately silent there.
effective_groups = _config_scoped_groups(context_groups, _cfg)

if mode == _member_mode and _member_backend_can_dispatch(_cfg):
append_required(
f"[CREW MEMBER OPERATING MODE]\n"
Expand Down Expand Up @@ -3715,7 +3774,7 @@ def _mark(label: str) -> None:
# the sub-agent reads the scope as framing rather than discovering a gap.
append_required(_build_context_scope_section(context_groups))

if _group_included(context_groups, CONTEXT_GROUP_LESSONS):
if _group_included(effective_groups, CONTEXT_GROUP_LESSONS):
profile_ctx = _build_user_profile_section(_cfg)
if profile_ctx:
parts.append(profile_ctx)
Expand Down Expand Up @@ -3895,7 +3954,7 @@ def _mark(label: str) -> None:
memory = None
member_vectors = None
if not blocks_reads and any(
_group_included(context_groups, group)
_group_included(effective_groups, group)
for group in (CONTEXT_GROUP_MEMORY, CONTEXT_GROUP_LESSONS)
):
if private:
Expand All @@ -3912,7 +3971,7 @@ def _mark(label: str) -> None:
)
else:
memory = self.get_memory_for(workspace, memory_store)
if not blocks_reads and _group_included(context_groups, CONTEXT_GROUP_MEMORY):
if not blocks_reads and _group_included(effective_groups, CONTEXT_GROUP_MEMORY):
if private:
append_required(
"[Memory tools]\n"
Expand Down Expand Up @@ -4026,7 +4085,7 @@ def _mark(label: str) -> None:
lessons_renderer: Callable[[int], str] | None = None
lessons_part_index: int | None = None
if (memory is not None or member_vectors is not None) and _group_included(
context_groups, CONTEXT_GROUP_LESSONS
effective_groups, CONTEXT_GROUP_LESSONS
):
# V1 only: the JSONL store answers when the vector store is absent OR not yet
# populated, and stays silent once it holds lessons.
Expand Down Expand Up @@ -4128,7 +4187,7 @@ def _render_default_jsonl_lessons(hard_cap: int) -> str:
session_key
and self.conversation_log
and not blocks_reads
and _group_included(context_groups, CONTEXT_GROUP_MEMORY)
and _group_included(effective_groups, CONTEXT_GROUP_MEMORY)
):
provenance = self.conversation_log.recent_with_provenance(
session_key, exclude_last_n=exclude_last_n
Expand Down Expand Up @@ -4634,7 +4693,13 @@ def build_message(
# mapping excludes and an unmapped custom agent cannot receive a block
# its session-start context never contained.
if not is_new_session and needs_reinjection:
if not blocks_reads and _group_included(context_groups, CONTEXT_GROUP_MEMORY):
# The stored-memory half routes through the same config intersection
# as the session-start build: this path restores a block that build
# withheld, so reading the caller scope alone would hand back the
# activity index the operator's inject_memory setting excluded.
if not blocks_reads and _group_included(
_config_scoped_groups(context_groups), CONTEXT_GROUP_MEMORY
):
memory = self.get_memory_for(workspace, memory_store)
parts.append(_neutralize_structural_markers(memory.activity_index()))
parts.append(
Expand Down
24 changes: 24 additions & 0 deletions src/kiro_crew/dashboard/handlers/cron.py
Original file line number Diff line number Diff line change
Expand Up @@ -2507,6 +2507,30 @@ async def api_lessons_create(request: web.Request) -> web.Response:
{"error": "Memory writes are not allowed in this session mode."},
status=403,
)
# Global persistence switch (memory.persistence_enabled).
# Enforced on the route rather than in the learn_add MCP handler so every
# transport that posts here (MCP tool, dashboard, direct HTTP) is covered
# by the one check. Reads and deletions stay available — the right to
# forget survives the switch.
if not KiroCrewConfig.load().memory.persistence_enabled:
_sel().log_api_access(
caller=sk,
operation="learn_add",
outcome="denied",
source="dashboard",
resources="persistence_disabled",
error="Persistent memory is disabled (memory.persistence_enabled).",
)
return web.json_response(
{
"error": "Lesson was NOT saved: persistent memory is disabled "
"(memory.persistence_enabled is false). Re-enable it with "
"`kirocrew config set memory.persistence_enabled true` to save "
"lessons again.",
"code": "persistence_disabled",
},
status=403,
)
# Validate body fields against the SAME schema the learn_add MCP tool uses
# (LEARN_ADD_SCHEMA), so REST and tool paths share one source of truth:
# rule must be a string (bounded to MAX_SHORT_STRING), category/scope are
Expand Down
23 changes: 23 additions & 0 deletions src/kiro_crew/dashboard/handlers/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -2110,6 +2110,29 @@ async def api_memory_consolidate(request: web.Request) -> web.Response:
return gate
if not state.consolidator:
return web.json_response({"error": "consolidator not available"}, status=503)
# Global persistence switch (memory.persistence_enabled). The
# inner _consolidate gate would refuse anyway; refusing here tells the
# dashboard caller WHY instead of returning a generic refusal, and spends
# no transcript read on a request that cannot proceed. The denial is
# SEL-recorded: the request passed identity and the write gate, so the
# refusal is a config-state decision an audit trail has to show rather than
# an unauthenticated caller being turned away upstream.
if not KiroCrewConfig.load().memory.persistence_enabled:
_sel().log_api_access(
caller=request.headers.get("X-Session-Key", ""),
operation="memory.consolidate",
outcome="denied",
source="dashboard",
resources="persistence_disabled",
)
return web.json_response(
{
"error": "Consolidation is paused: persistent memory is disabled "
"(memory.persistence_enabled is false).",
"code": "persistence_disabled",
},
status=403,
)
body, body_err = await read_bounded_json(request, max_bytes=None)
if body_err is not None:
return body_err
Expand Down
Loading
Loading