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
15 changes: 15 additions & 0 deletions docs/APP_PERFORMANCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -446,3 +446,18 @@ writes for the current machine-draft and saved-source repair phases. Values are
cumulative worker seconds, may overlap, and may exceed wall time with parallel work.
Only numeric totals are retained; a new run resets them, Stop retains them, and
refresh/reopening reads them from server state or the saved last-run summary.

### Hourly follow-up: full-brief and helper startup regressions

A full function brief also serves base `Network` callers (for example room/library
clients), which do not run the GUI engine constructor. Function-specific knowledge
now obtains the same lazy, project-scoped service used by progress saves; concurrent
first use creates one service. It preserves historical attribution and leaves source,
claims and match status unchanged. Synthetic tests cover both legacy and migrated
project databases; this corrects a reproduced crash, not a measured latency gain.

Saved Cursor helpers with the earlier `cursor` ID resolve to `cursor-cli`. Family
selection separates the longest registered ID or alias from a helper name, so
`cursor-cli-claude-…` is attributed to the model family rather than `cli`. CLI messages
that explicitly require authentication or say `use /login` enter the existing
signed-out handling before the fatal-error/reconnection fallback.
10 changes: 10 additions & 0 deletions src/decompnet/agents/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,3 +386,13 @@ def get(kind: str) -> Agent:
raise ValueError(f"decompdecomp has no agent called {kind!r}: start one of "
f"{', '.join(a.name for a in AGENTS)}")
return found


def helper_parts(name: str) -> tuple[str, str]:
"""Separate a recorded helper kind from its model, including multiword IDs."""
name = name.lower()
for kind in sorted((*_BY_ID, *_OLD_IDS), key=len, reverse=True):
if name.startswith(kind + '-'):
return kind, name[len(kind) + 1:]
kind, _, rest = name.partition('-')
return kind, rest
1 change: 1 addition & 0 deletions src/decompnet/agents/cursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ def config_home() -> Path:

class Cursor(Agent):
id = 'cursor-cli'
aliases = ('cursor',) # Stored by earlier app versions; keep saved agents usable.
name = 'Cursor Agent'

@property
Expand Down
4 changes: 2 additions & 2 deletions src/decompnet/app/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,8 @@ def resumable(s):


# what an agent CLI says when nobody signed in to it (Claude Code: "Not logged in · Please run /login")
_SIGNED_OUT = re.compile(r"not logged in|run /login|invalid api key|not authenticated|please (?:log|sign) ?in|"
r"auth(?:entication)? method", re.I)
_SIGNED_OUT = re.compile(r"not logged in|(?:run|use) /login|invalid api key|not authenticated|please (?:log|sign) ?in|"
r"auth(?:entication)? (?:method|required)", re.I)
# and when its sign-in stopped working (Claude Code, exit code 1 at once, nothing done: "Failed to authenticate: OAuth
# session expired and could not be refreshed", its message marked "error": "authentication_failed"). Read as a plain
# failure, it went by unnoticed in a long session: two helpers retried after 10, 19, 39 and 76 s with no state saying
Expand Down
16 changes: 16 additions & 0 deletions src/decompnet/app/knowledge.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,22 @@ def _words(text: str) -> list[str]:
return re.findall(r"[a-z0-9_]+", text.lower())


def service(net):
"""Base Network callers need the same scoped knowledge as the GUI engine.

Initialize once on demand, including when two first briefs arrive together.
Never substitute the catalog for a function's operational project store.
"""
existing = getattr(net, 'knowledge', None)
if existing is not None:
return existing
with net.store.lock:
existing = getattr(net, 'knowledge', None)
if existing is None:
existing = net.knowledge = Knowledge(net)
return existing


class Knowledge:
def __init__(self, net):
self.net = net
Expand Down
7 changes: 2 additions & 5 deletions src/decompnet/app/saves.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,11 +363,8 @@ def _function_rows(net, project_id: int, *, sources: bool, names: list[str] | No
def _knowledge_store(net, project):
# Base Network users (including room recovery) do not own the GUI engine's
# Knowledge service, but portable progress still needs its project schema.
service = getattr(net, 'knowledge', None)
if service is None:
from .knowledge import Knowledge
service = net.knowledge = Knowledge(net)
return service._store(project)
from .knowledge import service
return service(net)._store(project)


def _manifest_from_rows(net, proj, cfg: dict, rows, folder: Path) -> tuple[dict, dict, set[str]]:
Expand Down
3 changes: 2 additions & 1 deletion src/decompnet/candidate_quality.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ def brief(net,fn):
source = fn['best_source'] or fn['seed'] or ''
abi = aggregate_hints(source, fn['name'], source)
prefix = ['### Aggregate ABI checks (advisory)', *abi] if abi else []
prefix += net.knowledge.for_function(fn)
from .app.knowledge import service
prefix += service(net).for_function(fn)
from .app.matched_context import brief as matched_context
prefix += matched_context(net, fn, source)
corrected = corrected_alternative(net, fn)
Expand Down
2 changes: 1 addition & 1 deletion src/decompnet/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ def hash_token(token: str) -> str:
def model_family(agent_name: str) -> str:
"""Who made an agent's model ("claude-opus-1": claude, "opencode-deepseek-v4.1-flash-2": deepseek); an agent
whose name says no model is a family of its own."""
kind, _, rest = agent_name.lower().partition("-")
kind, rest = agents.helper_parts(agent_name)
if kind in agents.FAMILIES:
return agents.FAMILIES[kind]
word = re.match(r"[a-z]+\d*", rest)
Expand Down
14 changes: 9 additions & 5 deletions tests/test_agent_kinds.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,18 +141,22 @@ def test_an_agent_that_runs_one_makers_models_names_their_family():
assert network.model_family("gemini-2") == network.model_family("antigravity-1") == "gemini"
assert network.model_family("opencode-deepseek-v4.1-flash-1") == "deepseek" # the model in its name says
assert network.model_family("zcode-glm-5.3-1") == "glm"
assert agents.get('cursor').id == 'cursor'
assert not agents.get('kimi').family
assert agents.get('cursor') is agents.get('cursor-cli')
assert agents.kind_id('cursor') == 'cursor-cli'
assert agents.get('kimi').family == 'kimi'
assert network.model_family(helpers.helper_name(agents.get('cursor').id, 'claude-sonnet-5', set())) == "claude"
assert network.model_family("cursor-gpt-5-1") == "gpt"
assert network.model_family("kimi-claude-sonnet-5-1") == "claude"
assert network.model_family("kimi-gemini-3-1") == "gemini"
assert network.model_family("cursor-cli-gpt-5-1") == "gpt"
assert network.model_family("cursor-cli-1") == "cursor-cli"
assert network.model_family("kimi-claude-sonnet-5-1") == "kimi"
assert network.model_family("kimi-gemini-3-1") == "kimi"


def test_real_cli_signin_errors_are_recognized_from_stderr():
assert helpers._SIGNED_OUT.search("Error: Authentication required. Please run 'agent login' first")
assert helpers._SIGNED_OUT.search("No model configured. Run kimi and use /login to sign in")
assert not agents.get('cursor').fatal("Error: Authentication required. Please run 'agent login' first")
# The shared manager recognizes sign-in before applying the CLI fatal fallback.
assert agents.get('cursor').fatal("Error: Authentication required. Please run 'agent login' first")
assert not agents.get('kimi').fatal("No model configured. Run kimi and use /login to sign in")


Expand Down
46 changes: 46 additions & 0 deletions tests/test_base_network_knowledge.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"""Full briefs also serve library/room callers without the GUI engine."""
import json
from concurrent.futures import ThreadPoolExecutor

import pytest

from decompnet import candidate_quality
from decompnet.app.knowledge import service
from decompnet.network import Network


@pytest.mark.parametrize('split', [False, True])
def test_base_network_brief_keeps_scoped_knowledge_and_reuses_service(tmp_path, split):
net = Network(tmp_path / 'app.db')
with net.store.tx() as db:
for pid in (1, 2):
db.execute('INSERT INTO projects(id,slug,name,root,config) VALUES(?,?,?,?,?)',
(pid, f'game{pid}', 'Synthetic', str(tmp_path), json.dumps({'kind': 'rom'})))
if split:
net.store.conn.close()
net = Network(tmp_path / 'app.db', project_databases=True)
store = net.project_store(1)
with store.tx() as db:
db.execute("INSERT INTO functions(id,project_id,name,status) VALUES(1,1,'target','open')")
assert not hasattr(net, 'knowledge')
fn = store.one('SELECT * FROM functions WHERE id=1')
# Previously raised AttributeError before reaching the actual claim's brief.
assert candidate_quality.brief(net, fn) == []
knowledge = net.knowledge
with knowledge._store(1).tx() as db:
db.execute("INSERT INTO knowledge(project_id,text,status,created_at) VALUES(1,'target uses a counter','accepted',0)")
with knowledge._store(2).tx() as db:
db.execute("INSERT INTO knowledge(project_id,text,status,created_at) VALUES(2,'target private to other project','accepted',0)")
text = '\n'.join(candidate_quality.brief(net, fn))
assert 'target uses a counter' in text
assert 'private to other project' not in text
assert net.knowledge is knowledge
assert store.one('SELECT status FROM functions WHERE id=1')[0] == 'open'
assert store.one('SELECT COUNT(*) FROM attempts')[0] == 0


def test_concurrent_first_use_creates_one_knowledge_service(tmp_path):
net = Network(tmp_path / 'app.db')
with ThreadPoolExecutor(max_workers=4) as pool:
services = list(pool.map(lambda _: service(net), range(12)))
assert all(item is services[0] for item in services)