Commit Graph
1439 Commits
Author SHA1 Message Date
Martin Vogel 9da4d66df2 Merge pull request #2115 from DeusData/fix/activation-guard-home-scope
fix(cli): scope the activation guard to the install-target HOME so a sandbox install can't drain the host daemon
2026-09-12 19:20:41 +02:00
Martin Vogel 734906379f fix(cli): name the check that refused, and a remedy that can remove it
A reporter brought a full ProcMon trace to #1856 and still could not say which
check refused their install. That is not their failing: the binary discards the
answer before printing it.

cli_activation_production_context_init() validates the cache, rendezvous and
log directories -- it is the emitter MOST likely to hold a useful detail -- and
it printed CLI_ACTIVATION_REFUSED_MESSAGE bare, through the raw sink rather
than cli_activation_diagnostic(). So the reader got "Check the errors above"
with nothing above. That is the exact dead end #1416 and #1537 already fixed;
the property was repaired on the paths that had tests and left broken on this
sibling, which had none. Route it through the attributing helper: the refusal
now names the transaction refusal note or cbm_daemon_ipc_validation_detail().

The remedy was also wrong for the reported shape. `icacls <dir> /remove:g <sid>`
cannot remove an INHERITED ACE, and the stock C:\ grant for Authenticated Users
reaches every new child directory exactly that way -- so a reporter following
our advice watches the command succeed and the refusal persist. The refusal now
says whether the ACE was inherited, and the advice names
`icacls <dir> /inheritance:r /grant:r "%USERNAME%":(OI)(CI)F` for that case.

No safety check is relaxed. An install directory writable by other accounts is
still refused; it is now refused in terms the reader can act on.

The new contract test guards the CLASS rather than this one call site: any
emitter of a refusal constant that bypasses the attributing helper fails it,
which is what would have caught this. It fails on the previous tree naming
src/cli/cli.c:750, plus the missing inherited-ACE report and the missing
/inheritance:r remedy.

Local: cli 314 passed; activation_transaction daemon_ipc daemon_bootstrap
daemon_version 110 passed, 1 skipped (user namespaces are Linux-only, runs on
the Linux leg); make -f Makefile.cbm lint-ci clean.

Reported by zaferavci1.

Refs #1856
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-12 16:50:42 +02:00
Martin Vogel 9a460b389c fix(sha256): keep the message schedule out of the transform's frame
sha256_transform held its 64-word message schedule as a 256-byte local.
That is large enough for ASan's use-after-return fake stack, so an
instrumented build heap-allocated it through __asan_stack_malloc on every
64-byte block -- millions of allocations to hash one large file. Under the
sanitized CI settings (detect_stack_use_after_return=1) fingerprinting a
freshly installed binary therefore took minutes, and the cli suite blew its
900s wall-clock budget and was killed as hung on the Linux arm64 leg. The
suite passes on macOS, where the fake stack is not engaged the same way,
which is why this only ever surfaced on one leg.

Move the schedule into cbm_sha256_ctx so it is allocated once per hash
instead of once per block. The computed values and the resulting digest are
identical; no sanitizer option is relaxed and use-after-return detection
stays enabled everywhere.

Verified in the Linux arm64 sanitized container under the exact CI
ASAN_OPTIONS (detect_stack_use_after_return=1:strict_string_checks=1:
detect_stack_use_after_scope=1): cli 316 passed in 356s, previously killed
at the 900s budget; daemon_version 10 passed, covering the build-fingerprint
digests that would break first on a wrong hash.

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-12 15:38:20 +02:00
Martin Vogel dd454b2346 Merge pull request #2111 from DeusData/fix/1839-1864-stage-orphans
fix(pipeline): sweep orphaned/nested .db.stage files and stop the false invalid_existing_db route (#1839, #1864)
2026-09-12 12:45:14 +02:00
Martin Vogel b790be3d15 Merge pull request #2110 from DeusData/fix/1954-uninstall-symlinked-config
fix(cli): don't let an agent-config failure abort uninstall; follow user-owned symlinked configs (#1954)
2026-09-12 04:19:56 +02:00
Martin Vogel 91bee4fb28 Merge pull request #2113 from DeusData/fix/1828-enospc-daemon-start-diagnostics
fix(daemon): name errno/path on listen failure and fail the client fast instead of a 30s timeout (#1828)
2026-09-12 03:59:26 +02:00
Martin Vogel 1b067e3b04 Merge pull request #2139 from DeusData/fix/decision-b-win-sid-trust
fix(install): trust the local machine's built-in Administrator; name untrusted owners (#1705, #2023, #1686)
2026-09-12 03:46:21 +02:00
Martin Vogel 951b9ab022 Merge branch 'main' into fix/1839-1864-stage-orphans 2026-09-11 23:26:38 +02:00
Martin Vogel 78a6d19f1e Merge branch 'main' into fix/activation-guard-home-scope 2026-09-11 23:26:36 +02:00
Martin Vogel 33534653f1 Merge branch 'main' into fix/1954-uninstall-symlinked-config 2026-09-11 23:26:33 +02:00
Martin Vogel ca86fdb057 Merge branch 'main' into fix/1828-enospc-daemon-start-diagnostics 2026-09-11 23:26:30 +02:00
Martin Vogel ca36316c6b Merge branch 'main' into fix/2054-orphan-sidecars 2026-09-11 23:26:28 +02:00
Martin Vogel 53700ee1c7 Merge branch 'main' into fix/decision-b-win-sid-trust 2026-09-11 23:26:01 +02:00
Martin Vogel 9b85dd3eaf Merge pull request #2180 from DeusData/fix/extract-cpu-time-budget
fix(extract): budget tree-sitter parses by thread CPU time, not wall clock
2026-09-11 23:24:17 +02:00
Martin Vogel 713764bd0b Merge pull request #2116 from DeusData/fix/713-1826-nongit-guard-openhands
fix: bound non-git auto_index (#713) + complete OpenHands settings/profile registration (#1826)
2026-09-11 22:44:19 +02:00
Martin Vogel 527016258e fix(extract): budget tree-sitter parses by thread CPU time, not wall clock
The per-file tree-sitter parse was bounded by a 5s WALL-CLOCK budget. Under CI
contention a worker thread can be descheduled long enough for 5s of wall time
to elapse against near-zero CPU, so a small, perfectly parseable file was
abandoned with a false "parse timeout" and yielded ZERO defs. When that file
defined a symbol other files resolve against (e.g. celery.app.Celery.send_task
backing an ASYNC_CALLS edge, or a userpb gRPC client backing GRPC_CALLS), the
cross-file service edge then failed to classify -- surfacing as the flaky
convergence_probe / edge_types_probe service-edge assertions (count 0), a
verdict decided by wall-clock scheduling rather than the input (violates O9,
"no timeout decides a test").

Gate the parse on per-thread CPU time instead, with a generous wall ceiling as
a backstop:
- New portable helper cbm_thread_cpu_time_ns() (compat.c/.h): POSIX/macOS
  clock_gettime(CLOCK_THREAD_CPUTIME_ID), Windows GetThreadTimes (kernel+user);
  returns 0 on clock failure, degrading safely to the wall ceiling. It is NOT
  cbm_clock_gettime, which is wall on every platform (QueryPerformanceCounter
  on Windows).
- The progress callback's payload becomes {cpu_deadline_ns, wall_ceiling_ns};
  it trips when this thread's CPU time passes the budget OR wall time passes
  t0 + budget * 12 (~60s for the 5s budget). Descheduling burns wall, not CPU,
  so a starved-but-parseable file survives; a CPU-spinning parse still trips
  the CPU deadline; a genuinely stuck parse still trips the wall ceiling
  (bounded, no hang).

RED-repro (deterministic, CBM_ENABLE_TEST_SEAMS only): a thread-local wall-clock
offset armed by CBM_TEST_WALL_STALL_ON emulates a descheduled worker (wall
reads budget + 1s ahead while CPU is untouched -- above the old 1x wall budget,
below the ceiling). async_calls_celery_wall_stall_seam arms it for the Celery
DEFINITION file and asserts ASYNC_CALLS >= 1. With the fix the parse completes
and the edge resolves; with the budget reverted to wall-only + a 1x ceiling the
def file is dropped and the edge count is 0.

Verified (macOS, sanitized): edge_types_probe + convergence_probe 107 passed /
0 failed with the fix; 58 passed / 1 failed on revert (only the seam test, at
the ASYNC_CALLS assertion); 107 restored. Regression smoke (extraction
parse_coverage pipeline lang_contract grammar_regression) 698 passed / 0
failed. lint-ci clean (cppcheck + clang-format Homebrew LLVM + NOLINT); the
Windows GetThreadTimes path is compile-checked by CI (not runnable on macOS).

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-11 21:40:54 +02:00
Martin Vogel f6a29270b7 fix(mcp): normalize the autoindex.skip root path in diagnostics (#713)
The autoindex over-limit skip warning logged `root=` with the raw
srv->session_root, which on Windows carries backslashes. The #713 guard test
autoindex_limit_guards_non_git_root_issue713 asserts the warning names the
skipped root via strstr(root, "/repo"), so it failed on the Windows CLANG64
(x86_64) leg where the path is `...\repo`. Normalize the logged root to
forward slashes with cbm_normalize_path_sep() (a no-op on POSIX), matching
cbm's forward-slash path convention used everywhere else in the graph and MCP
output; the diagnostic is now identical across platforms. Production-side fix,
not a test relaxation.

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-11 21:01:17 +02:00
Martin Vogel 6091db7104 fix(daemon): keep an ephemeral generation for a mid-HELLO cold-storm racer
A burst of one-shot clients (e.g. six parallel `cli list_projects`) shares one
ephemeral daemon generation and races to connect. The generation retired the
instant its last committed client disconnected, even when another one-shot's
connection was already accepted and still mid-HELLO -- stranding that racer on
a STOPPING daemon and forcing a full cold respawn (up to the 12s daemon-claim
handoff each). Under load the retire/respawn churn could exhaust a client's
30s bootstrap budget, surfacing as the Windows guard's "cold-storm client
failed (racing daemon spawn)" regression and, on POSIX, a startup that never
reached "serving".

When the last committed client of an ephemeral, non-permanent generation
disconnects, linger a bounded window if a peer connection is already accepted
but has not yet passed HELLO admission (in_use, connected, not admitted, not
disconnecting -- runtime_has_pending_hello_peer_locked). The accept loop's
reconcile retires the generation once that racer drains without committing or
the bounded window (RUNTIME_EPHEMERAL_LINGER_MS, seam-overridable) elapses; a
racer that does commit clears the linger. With no such racer -- the common
single-client case -- the generation retires immediately, unchanged.

The linger deliberately covers ONLY a pre-HELLO racer, never an already-
admitted provisional session (HELLO done, application session opening): the
contract that a provisional coordinator client cannot keep a retiring
generation alive is preserved (daemon_runtime_final_disconnect_rejects_blocked_
provisional_session). The daemon cannot count cross-process cohort peers
(advisory locks expose presence, not a holder count, and Windows LockFileEx has
no non-owning probe), so this uses the one peer signal it has locally: accepted
connections not yet admitted. The window is bounded, so a racer that never
commits cannot wedge the generation (rules out the unbounded idle hang).

Coordinator gains a transient `linger` hold (distinct from `permanent`) so its
own last-client self-transition to STOPPING is suppressed while the racer is
outstanding; clearing it while idle retires the coordinator at once.

Verified (macOS, sanitized build): daemon suites 224 passed / 0 failed / 1
skipped (the skip is the pre-existing Linux-only userns case). New tests pin
both directions -- daemon_runtime_ephemeral_lingers_while_peer_mid_hello
(a raw accepted-but-unHELLO'd peer keeps the generation RUNNING after the
committed client leaves) and daemon_runtime_ephemeral_linger_retires_within_bound
(the bounded backstop retires even while the peer is still accepted). RED on
revert: neutering the gate flips ASSERT(lingered) at test_daemon_runtime.c and
nothing else. clang-format (Homebrew LLVM) + cppcheck + NOLINT clean.

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-11 20:56:43 +02:00
Martin Vogel 62bafb76b3 Merge remote-tracking branch 'origin/main' into fix/decision-b-win-sid-trust
# Conflicts:
#	src/daemon/ipc.h
2026-09-10 01:11:18 +02:00
Martin Vogel 055fbb7d82 Merge pull request #2138 from DeusData/fix/decision-bd
fix(daemon): accept single-uid userns overflow-owned ancestors (#1830)
2026-09-10 01:06:58 +02:00
Martin VogelandClaude Fable 5.1 618849512d style(install): clang-format-20 the LSA helper declarations (#1705)
The LSA typedefs and GetProcAddress casts in the #1705 local-Administrator
resolver were formatted with a different clang-format; CI clang-format-20
(the lint leg) flagged the line-wrapping. Reformatted only those lines with
the CI binary; no logic change.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-10 00:57:54 +02:00
Martin VogelandClaude Fable 5.1 df579830f3 fix(install): trust the local machine's built-in Administrator; name untrusted owners (#1705, #2023, #1686)
Windows install/daemon runtime directories created by an elevated process are
owned by the built-in Administrator ACCOUNT (RID 500 under the local machine
account-domain SID), even when that account is renamed or disabled. cbm's
directory-owner/ACL trust refused it, breaking install/activation on such
machines.

#1705: resolve THIS machine's built-in Administrator SID via LSA
(LsaOpenPolicy(POLICY_VIEW_LOCAL_INFORMATION) +
LsaQueryInformationPolicy(PolicyAccountDomainInformation) ->
CreateWellKnownSid(WinAccountAdministratorSid, accountDomainSid)), cached once
per process, and accept it as a trusted owner/grantee in the daemon
(win_sid_trusted) and the CLI activation transaction. Resolution is
deliberately NOT IsWellKnownSid(WinAccountAdministratorSid) and NOT a
trailing-RID-500 match: both accept a FOREIGN S-1-5-21-*-500 (a domain
administrator, or another machine's built-in Administrator), which would be a
cross-machine trust escalation. Any LSA or synthesis failure caches "none" and
grants no tolerance (fail closed). owner-not-current-user (the exact-owner
target rule) is unchanged.

#2023/#1686: an owner-trust refusal now names the offending owner SID (the path
was already carried), so a terse "status -3, os 0" becomes actionable.

Scope notes: on a domain controller -- which has no separate local SAM, so its
account domain IS the AD domain -- this trusts the domain Administrator, by
design (on a DC that account is the machine-equivalent top admin). An
un-sysprepped cloned Windows image shares the machine account-domain SID, so a
sibling clone's built-in Administrator would be non-foreign; this is inherent
to machine-SID identity.

Verified on a native Windows (arm64) VM: compiles under the sanitized build;
the daemon_ipc SID-trust test passes (local RID-500 trusted, a fabricated
foreign S-1-5-21-*-500 rejected, BUILTIN\Administrators trusted) at 35 passed /
0 failed with the fix, and 34 passed / 1 failed (ASSERT(local_ok)) with the
trust clause reverted -- the test binds precisely to the fix. #1856 (stock
ancestor ACEs): the Windows ancestor-ACL guards already pass; no defect
reproduced, no code change.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-10 00:40:49 +02:00
Martin VogelandClaude Fable 5.1 8116672a7e fix(daemon): accept single-uid userns overflow-owned ancestors (#1830)
Inside a 1:1 user namespace (podman --userns=keep-id, unshare -U
--map-current-user), the root-owned ancestors /, /tmp appear owned by the
kernel overflow uid; the daemon's ancestor-ownership walk refused every
overflow-owned ancestor, making the daemon unusable in that legitimate setup.

Tolerate an overflow-owned ancestor ONLY when /proc/self/uid_map is a
single-uid map whose sole inside id is our euid AND /proc/sys/kernel/overflowuid
is readable (never hardcoded; unreadable => no tolerance). No environment
escape hatch. Group-writable overflow ancestor refused (host group unknown);
world-writable overflow tolerated only with the sticky bit (the /tmp shape).
The created/final/snapshot gates stay strict == geteuid(), so a host-squatted
overflow-owned private directory is still refused; the tolerance only widens
which ancestors the walk traverses. macOS byte-identical (overflow=-1).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-09 23:45:38 +02:00
Martin Vogel 5b6a30dee6 Merge pull request #1933 from Chewji9875/fix/opencode-hook-args-and-subagent-permissions
fix(opencode): pass input args to augment hook and allow tool search in subagents
2026-09-09 23:37:57 +02:00
Martin Vogel cc6743e9f3 Merge pull request #2060 from TheStranjer/fix/follow-own-symlinked-agent-roots
fix(cli): follow agent-root symlinks owned by the invoking user
2026-09-09 23:37:45 +02:00
Martin VogelandClaude Fable 5.1 4fa11d1ab0 fix(cli): remove orphan SQLite sidecars on index deletion (#2054)
cbm_remove_indexes unlinked each *.db and *.db.tmp but never the SQLite
sidecars (<db>-wal/-shm/-journal), so `cbm update`, `cbm uninstall`, and
`install --reset-indexes` (the four callers of the single deletion
chokepoint) left orphan -wal/-shm files behind. Call the existing
wide-path-safe cbm_remove_db_sidecars() helper on both the live and staged
db paths after the .db unlink; it is idempotent and ENOENT-tolerant, so an
orphan -wal that outlived its .db is still cleaned. Sidecars are not
indexes, so the removed-count is unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-09 21:06:27 +02:00
Martin VogelandClaude Fable 5.1 91c63be5d4 fix(cli): keep config follow-roots off the static TLS block (#2110)
#1954's config-symlink follow support stored its opted-in roots in a
_Thread_local char[4][4096] -- 16 KiB in the binary's static TLS block.
On glibc/x86-64 that block is carved out of every thread's stack, including
the parent-death watchdog thread, created with a deliberately tiny 64 KiB
stack (PARENT_WATCHDOG_STACK_SIZE, main.c). The extra 16 KiB pushed that
thread's pthread_create past the static-TLS + TCB + guard budget, so it
failed with EINVAL: client_start_parent_watchdog() returned false and the
stdio server exited before answering initialize. The parent-death watchdog
regression test (#406/#407, scripts/test.sh Step 5) went red on every Linux
x86-64 leg while macOS/arm64 stayed green -- its TLS is not stack-carved.

Move the buffer off the static TLS block: keep a _Thread_local POINTER
(8 bytes) and calloc the 16 KiB lazily on first add, freeing it in
follow_clear(). Per-thread isolation and the exact API/semantics are
unchanged; the watchdog thread's static-TLS budget is restored. main.c and
the watchdog path are untouched.

Evidence (local, Linux x86-64 gcc under QEMU + Linux arm64):
- PT_TLS MemSiz 59,889 B -> 43,505 B (-16,384 B, exactly the array).
- parent-watchdog test 10/10 red -> 10/10 green; red again on revert.
- origin/main 10/10 green on the same env (regression is PR-specific).
- config editor + cli suites: 522/522 ASan/UBSan (macOS),
  523/523 ASan/LeakSanitizer (Linux arm64), no leak.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-09 21:03:01 +02:00
Martin VogelandClaude Fable 5.1 9ef7da8cbf style(mcp): clang-format the auto-index boundary lines (#2116)
The earlier leak-fix commit was formatted with Homebrew clang-format v22, which spaces the trailing comment on cbm_mem_collect() differently than CI's clang-format-20 (AlignTrailingComments). CI's lint / lint leg failed on the resulting drift. Reformat only that line with the exact CI binary.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-09 21:01:40 +02:00
Martin VogelandClaude Fable 5.1 e45d705105 fix(mcp): free the extraction bitset cache on the in-process auto-index thread (LSan)
cbm_kind_in_set lazily builds a THREAD-LOCAL node-type bitset cache during
extraction. That cache must be freed before a worker thread exits, or the
calloc'd bitsets are orphaned when the thread's TLS is torn down and
LeakSanitizer reports them at process exit. Parallel workers already free it
(pass_parallel.c:993) and the main thread frees it at process teardown; the
IN-PROCESS sequential auto-index runs extraction on autoindex_thread — a
short-lived pthread joined by cbm_mcp_server_free — and was the one gap: it
built the cache but never freed it (360 bytes in 9 allocations leaked, all from
ks_build).

This is a PRE-EXISTING latent leak: the extraction path and autoindex_thread are
byte-identical to main. It is newly EXPOSED by #713's new
autoindex_limit_admits_non_git_root_under_limit test, the first LSan-observed
path that runs an in-process auto-index and joins the worker thread in-process —
so the fix ships with the test that exposes it.

Free the calling thread's bitset cache after cbm_pipeline_free(p), mirroring the
established per-worker-thread teardown. Zero behavior change to the CLI/main
path. macOS LSan lane, mcp suite: 360 B / 9 allocations -> 0.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-09 07:33:51 +02:00
Martin Vogel 1db8bace03 Merge pull request #2119 from DeusData/fix/2117-windows-user-path-uninstall
fix(cli): remove the install dir from the Windows user PATH on uninstall (#2117)
2026-09-09 06:49:07 +02:00
Martin Vogel 1d66538474 Merge pull request #2112 from DeusData/fix/decision-a-memory-budget-fail-whole
fix(pipeline,mcp,daemon): fail an over-budget index attempt whole with a named reason (#1997, #832)
2026-09-09 06:48:43 +02:00
Martin VogelandClaude Fable 5.1 91e31211df fix(pipeline): take the stage lock before the stage file is visible (close #2111 create→register race)
create_staging_path() minted the stage's main file with mkstemp and only then
took its sidecar .lock via stage_owner_register(). A second, concurrent
cbm_pipeline_run() against the same final_path (auto_index, or the
stale-rendezvous-recovery retry path) could land its sweep_orphan_stages() in
that window: the main file was visible but not yet locked, so the sweep treated
it like a genuinely orphaned stage and deleted it out from under the live writer
(POSIX), or collided on the not-yet-created sidecar and surfaced EACCES/errno=13
(Windows). That is the #2111 red on test-windows-guards and both test-windows
CLANG64 x86_64 shards (index_format / simhash / index_resilience, with
pipeline.stage action=lock_failed errno=13).

Fix: mint the six-char alphanumeric suffix in create_staging_path() itself,
create and hold the sidecar lock FIRST, then create the main file with O_EXCL.
The stage's main file is therefore never present on disk without its lock
already held, so a racing sweep can only ever find the stage lock-held: it
reaches the stage through the .lock entry too (stage_entry_stage_length()
matches it), probes the lock, sees a live holder, and keeps it. The
create->register TOCTOU is closed by construction.

#1839 is preserved: sweep_one_stage() still removes a stage whose sidecar is
absent (ENOENT). With live stages now always carrying their sidecar, ENOENT is
only ever a genuine pre-lock-era orphan minted by an older binary, which #1839
requires be swept.

stage_owner_register() becomes stage_owner_adopt(), recording the already-held
descriptor; re-taking the lock would self-conflict, since flock() and Windows
_SH_DENYRW deny a second acquire of the same sidecar even from this process.
A new after_stage_created test seam and pipeline_concurrent_sweep_must_not_-
remove_inflight_stage drive a real concurrent sweep in that window; the test is
RED without the lock-first ordering.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-08 22:30:34 +02:00
Martin VogelandClaude Fable 5.1 7e73b48ef1 style(cli): clang-format the OpenHands install helpers (#2116)
CI's clang-format-20 flagged continuation-line alignment in the new
OpenHands MCP install/uninstall helpers (cbm_build_openhands_mcp_entry,
cbm_upsert_openhands_settings_mcp, cbm_remove_openhands_settings_mcp,
openhands_update_profile_refs). Reformat only those regions with
clang-format-20 to satisfy the lint gate; whitespace-only, no behaviour
change.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-08 22:27:41 +02:00
Martin VogelandClaude Fable 5.1 8135be28a7 fix(cli): remove the install dir from the Windows user PATH on uninstall (#2117)
On Windows, install registers the install directory in the persistent
HKCU\Environment\Path, but uninstall never removed it — so every
install/uninstall cycle left its entry behind and the user PATH grew
without bound (a real test host reached ~8000 chars, emptying the
effective PATH and breaking tooling).

The reported non-ASCII "mojibake" is historical, not a current-code bug.
Both install paths already write the value through the UTF-16 registry
API: install.ps1 (shipped in each release archive) runs `cbm install`,
which calls RegSetValueExW(L"Path", ...) — git history shows no ANSI
(RegSetValueExA / SetEnvironmentVariableA) predecessor — and
setup-windows.ps1 writes via .NET [Environment]::SetEnvironmentVariable
(Unicode) with an ASCII-only install dir. The only path that handles a
non-ASCII directory is the wide-correct C path, so current code cannot
produce a garbled entry; the garbage the reporter saw was left by an
older binary. No code change is needed for the encoding itself.

The real defect is the missing uninstall-side removal. This adds
cli_remove_windows_user_path(), the counterpart to
cli_ensure_windows_user_path(): it opens the same key, walks the
';'-separated segments, and drops exactly the ones equal to the install
dir using the same case- and trailing-separator-insensitive comparison
the install `present` scan uses, so it removes precisely what install
would have de-duplicated. Every other segment is preserved
byte-for-byte, the value kind (REG_SZ / REG_EXPAND_SZ) is preserved, and
a registry error is a warning rather than a hard failure so a user is
never blocked from finishing an uninstall over a cosmetic PATH edit.
Removing the entry on uninstall also stops accumulation on reinstall: a
garbled historical entry defeats the install de-dup and gets re-added,
so taking our own entry back out keeps the value bounded.

Testing:
- tests/test_cli.c: a hermetic Windows unit test drives the append and
  remove logic against a GUID-scoped scratch key via the existing
  CBM_TEST_WINDOWS_USER_PATH_RUN_ID seam, never the developer's live
  HKCU\Environment\Path. A non-ASCII install dir doubles as a mojibake
  guard (a broken UTF-8->UTF-16 round-trip would fail the match and leak
  a duplicate). It asserts append, idempotent reinstall, exact removal
  from the tail and the middle, idempotent removal, and byte-for-byte
  survival of unrelated entries.
- tests/test_smoke_fixture_contract.sh: a macOS-runnable source contract
  that fails when the removal is absent and passes with it, proving the
  wiring binds (verified RED-on-revert).

The Windows-only registry code is #ifdef _WIN32; its compile and the
behavioral unit test are verified by CI's Windows leg (the local Windows
VM is down). Pre-existing mojibaked entries from old binaries are a
separate one-time cleanup, out of scope here, and setup-windows.ps1's
own lack of an uninstall mode is noted as a possible follow-up.

Fixes #2117

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-08 22:08:39 +02:00
Martin VogelandClaude Fable 5.1 3a4160b461 fix(cli): complete the OpenHands integration (settings.json mcp_config + agent-profile refs) (#1826)
install wrote only part of the OpenHands config. Register the server globally
under ~/.openhands/settings.json -> mcp_config {transport:stdio, command, enabled}
(owned-entry, unrelated content preserved), and add "codebase-memory-mcp" to
each ~/.openhands/agent-profiles/<p>.json mcp_server_refs array (null -> [it],
existing -> appended once). uninstall removes exactly what it added.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-08 20:38:22 +02:00
Martin VogelandClaude Fable 5.1 208ee99c86 fix(mcp): bound the non-git auto_index guard by discovery count, not git ls-files (#713)
auto_index_limit was bypassed for a non-git root because the admission guard
counted `git ls-files`, which is 0 outside a repo, so the whole tree was
walked into tens of GB of RAM. Bound the check by the discovery layer's
bounded count with the limit as the ceiling; a non-git root over the limit is
refused with the limit named, and git roots are unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-08 20:38:22 +02:00
Martin VogelandClaude Fable 5.1 7bf366f63b fix(cli): guard the POSIX-only edit-path note recorder from the Windows build
config_edit_path.c's edit_path_note is defined before the '#ifndef _WIN32'
follow-resolver block but only called inside it, so the Windows build compiled
it dead and failed under -Werror,-Wunused-function (pr-smoke windows-latest).
Windows never follows a symlinked config, so guard the recorder with the same
condition as its callers.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-08 20:30:17 +02:00
Martin VogelandClaude Fable 5.1 013e1f7ec7 fix(cli): scope the activation guard to the install-target HOME (amendment)
The rendezvous directory the CLI's activation guard talks to is per OS
account (service.h), not per HOME/CBM_CACHE_DIR: every daemon owned by
one user meets at the same endpoint, and only the cache fingerprint
carried in the cohort identity separates one HOME/CBM_CACHE_DIR
namespace from another. `cli_activation_production_reserve` used
`cbm_version_cohort_reserve_for_mutation`, which treats any lifetime-
lock holder at that shared endpoint as the daemon this activation must
drain, with no cache-fingerprint awareness at all. An `install` run
against a second HOME (a sandbox, a second profile, `--skip-binary`
into an alternate CBM_CACHE_DIR) therefore reached the LIVE host
daemon at the shared endpoint and drained it — disconnecting every one
of the host's real MCP clients — even though nothing the sandboxed
install touched belonged to the host's cache namespace.

The fix adds `cli_activation_resolve_scope`, a non-blocking probe via
the already cache-fingerprint-aware `cbm_version_cohort_acquire`, run
before the blind drain path. It distinguishes three cases from the
resolved target of THIS activation:
  - nothing to quiesce at all: a `--skip-binary` install that also
    resets no index publishes nothing, so no session anywhere needs to
    stop (`quiesce_required` on `cli_activation_guard_scoped`, plumbed
    from `cbm_cmd_install`'s own binary/index-reset decision);
  - the active cohort's cache fingerprint doesn't match this
    activation's target cache: a foreign namespace, left untouched;
  - same cache fingerprint (or no active cohort): this activation
    really does replace that daemon, so the existing drain/quiesce
    path runs unchanged, including the barrier wait when another
    activation already holds maintenance.

Verified against a real forked daemon (a live runtime service with one
committed client) standing in for the host: an install into a foreign
HOME/CBM_CACHE_DIR (`--skip-binary` and a full binary install) leaves
that daemon serving with its client still attached, while an install
that targets the host's own namespace still drains it and the
activation audit still names the client it disconnected.

New/updated tests in tests/test_cli.c (cli suite):
- cli_install_skip_binary_into_foreign_home_never_drains_host_cohort
- cli_install_binary_into_foreign_home_never_drains_host_cohort
- cli_install_into_host_namespace_still_drains_host_cohort (regression)
- cli_install_skip_binary_unchanged_in_host_namespace_quiesces_nothing
- cli_activation_quiesce_does_not_wait_on_bootstrap_startup updated to
  carry a real cache fingerprint for its participant, now that scope
  is fingerprint-gated

src/mcp/index_supervisor.{c,h}: CBM_CLI_ENABLE_TEST_API-gated setter
so the fixture's forked daemon can carry the same build fingerprint
the guard captures from the supervisor.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-08 20:28:58 +02:00
Martin VogelandClaude Fable 5.1 0567dc70a0 fix(daemon): guard the POSIX listen-failure recorder so Windows does not see it unused
The rich errno+path recorder ipc_listen_failed (and ipc_listen_failure_reset)
are defined before the POSIX '#ifndef _WIN32' listener block but only called
inside it, so the Windows build compiled them dead and failed under
-Werror,-Wunused-function (pr-smoke windows-latest). Wrap both in the same
'#ifndef _WIN32'; the failure struct and its cross-platform accessor
cbm_daemon_ipc_listen_failure_detail stay compiled on every platform.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-08 20:13:17 +02:00
Martin Vogel b5185d10c4 Merge pull request #2095 from DeusData/fix/1973-nested-gitignore-depth
fix(discover): stack every nested .gitignore on a path, not just the shallowest (#1973)
2026-09-08 20:03:13 +02:00
Martin Vogel 6741c29fc2 Merge pull request #2096 from DeusData/fix/1953-watcher-git-self-trigger
fix(watcher): exclude the indexer's own artifact dir from the git dirty signature (#1953)
2026-09-08 20:02:45 +02:00
Martin Vogel d40ed1a6bb Merge remote-tracking branch 'origin/main' into fix/1954-uninstall-symlinked-config
# Conflicts:
#	tests/test_cli.c
2026-09-08 19:55:13 +02:00
Martin Vogel 161df2bdb1 Merge pull request #2094 from DeusData/fix/1924-yaml-plain-scalar-indicators
fix(yaml): scope > | [ ] indicators to the value start so Hermes configs install (#1924)
2026-09-08 09:35:01 +02:00
TheStranjer 3c854ae217 fix(cli): bind a symlink's ownership judgement to the inode that is followed
Review of the previous head reproduced a check-then-use window in the
parent-chain walk: the link was judged by name (fstatat) and then opened
by name (openat), with nothing tying the two to the same entry. An
LD_PRELOAD shim that swaps the link for one pointing elsewhere the moment
the judgement returns made both earlier heads follow the swapped link,
including one owned by a foreign uid under root; the post-follow target
check only bounds where such a swap can land.

The link is now never opened by name after it has been judged. On Linux
an O_PATH|O_NOFOLLOW descriptor pins the inode, fstat on that descriptor
makes the ownership decision and readlinkat(fd, "") reads the target text
from the same inode; on other systems the link is stat'ed by name before
and after the readlinkat and both must be the same inode with the same
owner. The walk then opens the text from the parent directory, so a
relative text resolves against the link's own directory exactly as the
kernel resolves it, and the target check runs on what that opens. The
readlinkat form is used rather than /proc/self/fd so the walk does not
depend on /proc being mounted. What is still done by path is resolving
the text itself, which the target check bounds; the comment says so.

Test: relative, ../, absolute and chained link texts resolve from the
link's directory with the process CWD moved elsewhere. The race itself
is exercised out of tree with the harness from the review thread.

Refs #1722

Signed-off-by: TheStranjer <791672+TheStranjer@users.noreply.github.com>
2026-09-08 00:33:36 -06:00
TheStranjer 8622d6a0ed fix(cli): make following user-owned symlinks an opt-in per call site
Review of the previous head found the global rule unsound for one caller:
cbm_mkdir_p also creates <repo_path>/.codebase-memory inside the checkout
being indexed, and git creates symlinks owned by whoever cloned, so a
repository shipping `.codebase-memory -> ~/.ssh` would have been followed
by the artifact writer. "User-owned" says nothing about "user-intended"
once the path root is a checkout.

cbm_mkdir_p keeps the strict walk (root-owned links only). The new
cbm_mkdir_p_ex(path, mode, policy) with CBM_MKDIR_FOLLOW_OWNED also
follows a symlink owned by the invoking user, and only callers whose
paths are rooted in the user's own configuration opt in: the installer's
agent roots, skills, instruction files and hook directories, the
JSON-like config editor's parent creation, the cache root, <cache>/logs,
the UI config directory and the DB parent. The artifact directory inside
the checkout and the ~/.local/bin creations stay strict; the activation
transaction re-walks the latter with its own no-follow policy anyway.

What a follow lands on is now checked too: the opened target must be a
directory owned by root or the invoking user and not world-writable
unless sticky, so a link swapped between the fstatat and the openat
cannot steer the walk into a directory an attacker controls or one where
anyone can pre-plant entries. This applies to root-owned links as well;
macOS /private/tmp is root-owned and sticky and still passes. Refusal
restores the first openat's errno.

Tests: the plain walk refuses an own link that the opted-in walk
follows; targets that are world-writable without the sticky bit are
refused; as root, a foreign-owned target and a user-owned link are both
refused, each followed by restoring ownership and walking again; the
identical `.codebase-memory -> <user-owned dir>` link is refused by the
plain walk and followed once opted in; cbm_artifact_export refuses a
checked-in artifact-dir link and leaves its target empty; the installer
test gains the euid-0 leg with home, link and target owned by a non-root
uid. Under euid 0 the tests demote their links to a non-root owner, since
root-owned links are trusted by both walks.

Refs #1722

Signed-off-by: TheStranjer <791672+TheStranjer@users.noreply.github.com>
2026-09-07 23:17:50 -06:00
Martin VogelandClaude Fable 5.1 e5aabdf86e fix(cli): follow user-owned symlinked config files in the editors
Every config editor (JSON-like, TOML, YAML, text) opens with O_NOFOLLOW
and refuses symlinks, so a link planted at ~/.cursor/mcp.json cannot
point a privileged writer at another file. Users keep exactly those
files as symlinks into a dotfiles checkout; the blanket refusal made
install and uninstall fail on them and, before the previous commit,
turned uninstall into data loss (#1954).

Decision C: a symlink the INVOKING user owns, resolving to a regular
file the same user owns, is followed — as an explicit opt-in of the
agent-configuration writers only. cbm_install_agent_configs and the
uninstall activation register the user's configuration roots (HOME,
XDG_CONFIG_HOME) for the duration of their work; a link whose own
directory is outside every registered root, or any link seen by another
editor caller, stays refused, so repository paths never follow.

One shared helper (src/cli/config_edit_path.c) runs the race-safe
sequence: lstat(link) → owner == invoking uid (a root process follows
root-owned links only) → realpath → the target's parent directory
opened as a dirfd (O_DIRECTORY|O_NOFOLLOW; owned by the invoking user
or root, not writable by others unless sticky) → openat(dirfd, base,
O_NOFOLLOW) → fstat: regular file, same owner, link count 1, and the
same (dev, ino) as stat(realpath). Each editor reads through that
validated descriptor, stages its temp file with openat(dirfd, …,
O_CREAT|O_EXCL|O_NOFOLLOW), runs its pre-publish snapshot comparison
against the resolved path, and commits with renameat on the pinned
dirfd, so the link itself is never replaced. Every other link is refused
with an observable reason (surfaced in the uninstall diagnostics):
another owner, root over a non-root link, dangling, a directory or
special target, a hard-linked or swapped target, a foreign or
world-writable parent. Whether the target must also stay under a root
is a pending user decision behind CBM_CONFIG_EDIT_TARGET_UNDER_ROOT
(default: anywhere the user owns). Windows never follows reparse points.

Tests: each editor suite gains a same-owner link edited in place under
the opt-in (link preserved and still pointing at the same target, temp
file staged beside the target, bytes identical to the same edit on a
plain file, no stray temp files) and keeps its refusal cases; the
JSON-like suite adds no-opt-in, outside-root, dangling, directory,
identity-skew and world-writable-parent refusals. The foreign-owner and
root-run refusals move the observer through a test seam (a test cannot
create a foreign-owned link without root; a real root run demotes the
link first). test_cli.c drives `uninstall -y` end to end through a
symlinked ~/.cursor/mcp.json.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-08 02:04:51 +02:00
Martin VogelandClaude Fable 5.1 7b4eb4a00a fix(pipeline): route a first index as no_existing_db, not invalid_existing_db
The route probe opened whatever resolve_db_path returned, which inside
the staged run is the run's own stage. On a first index nothing was
copied into it, so the probe opened a 0-byte mkstemp placeholder, failed
its integrity check, and warned "pipeline.route path=full
reason=invalid_existing_db" -- on every first index of every project.
Read back after an OOM kill it looked like a corrupted database and a
daily "corrupt -> full rebuild -> OOM" loop (#1864); the loop is "no
database -> full -> OOM", and the stale 0-byte stage never influenced
the next run at all (each run mints a fresh name).

cbm_pipeline_run now records whether the destination existed and was
copied into the stage, and the route decision returns full early with
reason=no_existing_db (or existing_db_backup_failed, after the
backup_failed_full_rebuild warning) without probing a placeholder.
"invalid_existing_db" stays reserved for a real copy that fails its
integrity check.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-08 02:02:08 +02:00
Martin VogelandClaude Fable 5.1 00060cec85 fix(daemon): fail the client fast when the daemon cannot start
A daemon that died at listener publication (a full /tmp) took the
lifetime reservation, failed, and released it; the waiting client saw the
generation vanish, respawned it, and repeated that for its whole 30 s
deadline before reporting "CBM daemon is active or starting but could not
accept this client" -- the opposite of what happened, with no cause and
no path. MCP hosts then dropped the server silently (#1828).

A detached daemon has no stderr and no channel back to its launcher, so
the host now appends one start-failure record per failed start to
<cache>/logs/cbm-daemon.start-failures.log -- next to cbm-daemon.log,
through the same owner-only private-log open. Deliberately NOT the
runtime directory: that is exactly what a full /tmp cannot write, and a
new artifact there would entangle the stale-generation cleanup that
#1894 just hardened. The record carries the listener detail from the
previous commit (component, stage, errno, path) plus the runtime
directory and a wall-clock stamp, and is written while the lifetime
reservation is still held, so a client that watches the generation
vanish already finds the cause.

The client bootstrap loop reads that record (every 50 ms after its own
spawn, and unconditionally before any relaunch), accepts only records for
its endpoint not older than its spawn instant (2 s skew), and stops at
once:

    error: CBM daemon failed to start: pending_publication failed with
    ENOSPC (No space left on device) at /tmp/cbm-daemon-1000/cbm-<key>.sock.pending.tmp;
    see ~/.cache/codebase-memory-mcp/logs/cbm-daemon.log

The read is an optional bootstrap op (unit contracts with fake ops are
untouched); the production op resolves the cache log directory. Every
other wait state -- a live or stopping generation, a mute holder, a
concurrent starter -- keeps its existing semantics and diagnostics.

Tests (daemon_bootstrap):
- daemon_bootstrap_fails_fast_when_daemon_dies_at_publication: the
  production bootstrap (real cohort, probe, startup lock, handoff) with a
  seam-only spawn override that forks a REAL daemon host whose record
  writes fail with ENOSPC. RED before: 34.7 s and "active or starting";
  GREEN after: FAILED in well under 5 s naming ENOSPC and the temp path,
  one child spawned, daemon log carries errno=ENOSPC path=... .
- daemon_bootstrap_start_failure_record_round_trip: record/read/format
  contract, a stale record and another endpoint's record are ignored.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-08 02:01:33 +02:00
Martin VogelandClaude Fable 5.1 21591d5116 fix(daemon): slice the worker memory budget by active jobs, not by the job limit
The daemon handed every index worker aggregate/physical_job_limit (a
fixed quarter by default) regardless of how many jobs were running, so a
lone worker on a host like #1864 was capped at a quarter of the memory
the daemon itself was allowed — and with the budget now failing whole
(decision A) that fixed slice would have turned an idle host into a
guaranteed over_memory_budget. Decision 2 (#1997, #832): the slice is
decided at spawn time as aggregate / jobs active right then (the job
being spawned included), so a lone worker may use the whole aggregate
and concurrent jobs split it. The explicit CBM_MEM_BUDGET_MB override
keeps its precedence inside the worker (bf46b91f); the sub-byte-per-slot
guard is unchanged. The spawn line logs project, active_jobs,
aggregate_mb and slice_mb so a fail-whole verdict can be read against
the budget the worker really had.

Tests: sequenced admission proves first=aggregate, second=aggregate/2;
the racing 4-way admission test accepts any aggregate/1..4 slice (the
divisor is scheduling-dependent there); a scripted CLEAN worker
returning the over_memory_budget error response is passed through
verbatim on the first attempt — no recovery loop, no quarantine.

Refs #1997 #832 #1864

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-08 01:55:01 +02:00
Martin VogelandClaude Fable 5.1 b6458f924d fix(pipeline): sweep the orphaned stages of a dead writer before each run
Nothing on the worker-death path ever cleaned a stage up: the supervisor
reaps only an exit status, and a cancel is SIGTERM then SIGKILL after one
second, which a gigabyte backup or clone never finishes inside. Every
daemon-side cancel or OOM kill therefore left a full-size <db>.stage.X
(plus -wal/-shm) behind for good, and with auto_index a large project
filled the disk with copies of itself (#1839).

Each run now sweeps before minting its own stage. Only names of the exact
minted shape for THIS database are considered -- "<basename>.stage.<6
alphanumerics>" and that stage's -wal/-shm/-journal/.lock sidecars --
never the live database, a quarantined .corrupt, or another project's
files. Liveness is the ownership lock and nothing else: a stage whose
sidecar lock can be taken has no writer and is removed (logged as
pipeline.stage action=orphan_removed bytes=N); one whose lock a live
writer holds is kept (orphan_kept reason=live_writer). No pid, no mtime,
no grace period, so the sweep is deterministic and never races a writer.

A stage minted by an older binary carries no lock and is swept too; that
writer's final rename then fails and it discards its stage. The live
database is never named on either path.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-09-08 01:50:32 +02:00