Skip to content
Merged

V2 #12

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
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,8 @@ demo/*.gif
# that ARE tracked - see docs/trust/INSTALL_PROOF_WINDOWS.md)
*.log.tmp
*.runtime.log

# bundled engine sidecar — built by pyinstaller, never committed
apps/launcher/src-tauri/binaries/
dist/
build/
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,7 @@ verification is performed — see
│ │ ├── events.py EventLogger + EventStore (JSONL)
│ │ ├── episodic.py Keyword + recency + kind-hint scorer
│ │ ├── sessions.py Session reconstructor
│ │ ├── workblocks.py Behavioural work-blocks (dwell-aware, C5)
│ │ ├── microcontexts.py Micro-context reconstructor
│ │ ├── resurfacing.py Idle-launcher continuity surface
│ │ ├── threads.py Persistent topic identity
Expand Down
15 changes: 14 additions & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,17 @@ telemetry. See the capture audit for the full diagnosis.
opted in via `ALLOWED_KINDS` + payload allowlist + smoke §34, with the
kind **deliberately absent from `RETRIEVABLE_KINDS`** — it is a
grouping signal for behavioural work-blocks, never a search result.
*The consumer (sessions grouping on dwell/blocks) is the follow-on.*
- [x] **Capture C5 — Behavioural sessions (use the signal).**
[`app/core/workblocks.py`](app/core/workblocks.py) — a pure,
deterministic derivation that regroups a session's events into
*work-blocks* of continuous attention. The 30-min clock over-merges
two scattered bursts into one session and can't tell focus from a
tab left open; work-blocks read the `dwell_ms`/`block` signal back
and **split** what the clock lumped (10-min behavioural idle) while
**bridging** gaps a dwell span or shared `wb-` id proves were
continuous. Additive — the `session_id` spine is untouched; `Session`
gains derived `work_blocks` + `behavioural_label` ("one 47-minute
focus block" / "3 attention blocks"), surfaced through `SessionOut`
and the launcher caption. 9 pure unit checks
([`_test_workblocks.py`](_test_workblocks.py)) + smoke §38; ~1 µs per
derivation, safe on the search hot path.
52 changes: 52 additions & 0 deletions _smoke_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1723,6 +1723,58 @@ def search(self, query, top_k=8):
print("[OK] /v1/loop/bump feeds the same ledger the console reads")


# ----------------------------------------------------------------------
section("38. Behavioural work-blocks reach the session wire (Capture C5)")
# ----------------------------------------------------------------------
# The 30-minute clock lumps two scattered bursts into one session; the
# dwell/work-block signal splits them. This verifies the derivation is
# wired all the way to SessionOut — the field the launcher and console
# describe attention with.
from app.core.events import Event as _Ev # noqa: E402
from app.core.sessions import Session as _Session # noqa: E402
from api.main import _session_to_out as _sess_out # noqa: E402

_wb_base = datetime(2026, 7, 20, 9, 0, 0, tzinfo=timezone.utc)


def _wb_ev(offset_s, kind="browser_visit", **payload):
ts = (_wb_base + timedelta(seconds=offset_s)).strftime("%Y-%m-%dT%H:%M:%SZ")
return _Ev(ts=ts, session_id="s_wb", kind=kind, payload=payload)


# one clock session, two attention islands 15 minutes apart
_scattered = _Session(
session_id="s_wb",
events=[
_wb_ev(0, kind="browser_focus", dwell_ms=20 * 60 * 1000, block="wb-a"),
_wb_ev(120),
_wb_ev(240 + 15 * 60, kind="browser_focus", dwell_ms=12 * 60 * 1000, block="wb-b"),
_wb_ev(240 + 15 * 60 + 120),
],
topic="websocket",
label="Working on websocket",
time_label="today",
score=1.0,
)
assert _scattered.work_blocks == 2, _scattered.work_blocks
assert "attention blocks" in _scattered.behavioural_label, _scattered.behavioural_label
_out = _sess_out(_scattered)
assert _out.work_blocks == 2
assert _out.behavioural_label == _scattered.behavioural_label
# a tight single burst stays one block and adds no clause
_tight = _Session(session_id="s2", events=[_wb_ev(0), _wb_ev(30), _wb_ev(90)])
assert _tight.work_blocks == 1 and _sess_out(_tight).behavioural_label == ""
# derivation is cheap — it runs on the search hot path
t0 = time.perf_counter()
for _ in range(200):
_ = _scattered.work_blocks
wb_us = (time.perf_counter() - t0) / 200 * 1e6
assert wb_us < 500, f"work-block derivation {wb_us:.0f}us, budget 500us"
print(f" scattered → {_out.work_blocks} blocks · \"{_out.behavioural_label}\"; "
f"{wb_us:.0f}us/derivation")
print("[OK] work-blocks flow to SessionOut, cheap enough for the hot path")


# Cleanup
shutil.rmtree(TMP, ignore_errors=True)

Expand Down
112 changes: 112 additions & 0 deletions _test_workblocks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
"""Deterministic tests for the pure work-blocks derivation (Capture C5).

Run: python _test_workblocks.py

No daemon, no disk, no clock — `workblocks` is a pure function of the
event timestamps and captured dwell spans, which is exactly why the
riskiest continuity logic is verifiable in isolation.
"""

from __future__ import annotations

from datetime import datetime, timedelta, timezone

from app.core.events import Event
from app.core.workblocks import (
BEHAVIOURAL_IDLE_SECONDS,
describe_blocks,
group_work_blocks,
)

_BASE = datetime(2026, 7, 20, 9, 0, 0, tzinfo=timezone.utc)

n = 0


def ok(msg: str) -> None:
global n
n += 1
print(f" [ok] {msg}")


def ev(offset_s: float, kind: str = "browser_visit", **payload) -> Event:
"""An event `offset_s` seconds after the base moment."""
ts = (_BASE + timedelta(seconds=offset_s)).strftime("%Y-%m-%dT%H:%M:%SZ")
return Event(ts=ts, session_id="s_test", kind=kind, payload=payload)


# --- empty + trivial ---------------------------------------------------
assert group_work_blocks([]) == []
assert describe_blocks([]) == ""
ok("empty stream → no blocks, no description")

single = [ev(0), ev(60), ev(120)]
blocks = group_work_blocks(single)
assert len(blocks) == 1, blocks
# a single block with no dwell signal stays quiet — the clock label covers it
assert describe_blocks(blocks) == ""
ok("tight clicks with no dwell → one block, no clause")

# --- the split the clock can't see -------------------------------------
# Two five-minute bursts 15 minutes apart. The 30-minute clock lumps
# them into ONE session; behaviourally they're two attention islands.
scattered = [
ev(0), ev(120), ev(240), # burst 1 (0–4 min)
ev(240 + 15 * 60), ev(240 + 15 * 60 + 120), # burst 2, 15-min gap
]
blocks = group_work_blocks(scattered)
assert len(blocks) == 2, f"expected 2 blocks, got {len(blocks)}"
assert len(blocks[0]) == 3 and len(blocks[1]) == 2
ok("15-min silence inside one clock session → two work-blocks")

# --- dwell bridges a gap the idle rule would split ---------------------
# A gap longer than the idle threshold, but a dwell event whose span
# reaches back across it — the user was present the whole time.
gap = BEHAVIOURAL_IDLE_SECONDS + 120 # over the idle threshold
bridged = [
ev(0),
ev(gap, kind="browser_focus", dwell_ms=(gap + 30) * 1000, block="wb-1"),
]
blocks = group_work_blocks(bridged)
assert len(blocks) == 1, f"dwell should bridge the gap, got {len(blocks)}"
ok("long gap covered by a dwell span → stays one block")

# a dwell too short to bridge does NOT rescue the gap
not_bridged = [
ev(0),
ev(gap, kind="browser_focus", dwell_ms=9000, block="wb-1"),
]
assert len(group_work_blocks(not_bridged)) == 2
ok("sub-threshold dwell across a long gap → two blocks")

# --- shared extension block id bridges ---------------------------------
same_block = [
ev(0, kind="browser_focus", dwell_ms=30000, block="wb-9"),
ev(gap, kind="browser_focus", dwell_ms=9000, block="wb-9"),
]
assert len(group_work_blocks(same_block)) == 1
ok("same extension work-block id bridges a long gap")

# --- order independence ------------------------------------------------
shuffled = [scattered[3], scattered[0], scattered[4], scattered[2], scattered[1]]
assert len(group_work_blocks(shuffled)) == 2
ok("result is independent of input order (stable sort)")

# --- descriptions ------------------------------------------------------
focus_hour = [
ev(0, kind="browser_focus", dwell_ms=47 * 60 * 1000, block="wb-1"),
]
assert describe_blocks(group_work_blocks(focus_hour)) == "one 47-minute focus block"
ok("single long dwell → 'one 47-minute focus block'")

multi = group_work_blocks([
ev(0, kind="browser_focus", dwell_ms=20 * 60 * 1000, block="wb-1"),
ev(240 + 15 * 60, kind="browser_focus", dwell_ms=15 * 60 * 1000, block="wb-2"),
ev(240 + 40 * 60, kind="browser_focus", dwell_ms=10 * 60 * 1000, block="wb-3"),
])
desc = describe_blocks(multi)
assert desc.startswith("3 attention blocks"), desc
assert "focused" in desc
ok(f"three blocks with dwell → '{desc}'")

print(f"\n{n} work-block checks passed")
2 changes: 2 additions & 0 deletions api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,8 @@ def _session_to_out(s: Session) -> SessionOut:
time_label=s.time_label,
score=s.score,
event_count=s.event_count,
work_blocks=s.work_blocks,
behavioural_label=s.behavioural_label,
kinds=s.kinds,
preview_events=[_event_to_out(ev) for ev in s.preview_events()],
openable_targets=[
Expand Down
6 changes: 6 additions & 0 deletions api/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,12 @@ class SessionOut(BaseModel):
time_label: str
score: float
event_count: int
# Capture C5 — behavioural attention shape, derived from the
# dwell/work-block signal. `work_blocks` counts continuous runs of
# attention inside the clock session; `behavioural_label` is the
# one-clause description ("" when there's no signal to add).
work_blocks: int = 1
behavioural_label: str = ""
kinds: List[str]
preview_events: List[EventOut]
openable_targets: List[OpenableTarget]
Expand Down
19 changes: 19 additions & 0 deletions app/core/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,25 @@ class Session:
def event_count(self) -> int:
return len(self.events)

@property
def work_blocks(self) -> int:
"""How many behavioural work-blocks this clock session actually
contains (Capture C5). 1 means one continuous run of attention;
more means the 30-minute window lumped together separate
bursts. Derived, never stored — see `workblocks.py`."""
from .workblocks import group_work_blocks

return len(group_work_blocks(self.events))

@property
def behavioural_label(self) -> str:
"""One quiet clause naming the session's attention shape, e.g.
"one 47-minute focus block" or "3 attention blocks". Empty when
there's no signal worth adding to the clock label."""
from .workblocks import describe_blocks, group_work_blocks

return describe_blocks(group_work_blocks(self.events))

@property
def kinds(self) -> List[str]:
seen: set[str] = set()
Expand Down
Loading
Loading